fix(tui): keep the window following the client used last, forced resizes included

A browser that opens a session sends a forced resize at its current size.
Its pty does not change, so tmux keeps the TUI's client as the latest one
and `client-active` never fires again, while Codeman's `resize-window`
still pins the window to `manual` at the browser's size. Typing in the
terminal then did nothing, which is the bug this branch fixes.

An `after-resize-window[91]` hook now puts `latest` back after Codeman's
resize, so tmux keeps deciding by the client used last; `client-active[91]`
stays for Codeman's own attach (`setManualWindowSize()`), which sets
`manual` without a resize.

The owner's tty moves into the session option `@codeman-tui-follow`, and
both hook commands are constants that read it, so no tty is interpolated
into a hook and hooks whose owner is gone do nothing. restore() and the
startup sweep drop the owner first, then our hooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kamil KaliszandClaude Opus 5.5 committed 2026-11-24 18:39:54 +01:00
1 parent d387cf8cdb
commit dbf545ce8f
7 files changed
+344 -301

No files matched your search

+8 -6
View File
@@ -664,10 +664,11 @@ export async function beginAttachHandoff(
// resizes this session mid-attach goes through Codeman's `resize-window`,
// which puts the window back on `manual` at the BROWSER's size: a phone
// opening it left the terminal showing a phone-sized pane, and typing or
// pasting here changed nothing until a detach and a fresh attach. The hook
// puts `latest` back when THIS terminal is used again, the way plain tmux
// follows whoever typed last. Needs the tty for its guard, like the switch
// keys, so without one the attach keeps the old behaviour.
// pasting here changed nothing until a detach and a fresh attach. The
// follow hooks (TUI_FOLLOW_HOOKS) keep the window on `latest`, so it
// follows whichever client was used last, this terminal included. They
// need the tty to name their owner, like the switch keys, so without one
// the attach keeps the old behaviour.
if (guarded && (await client.armFollowTyping(target, tty as string))) followTyping.push(target);
}
// ⚠️ Armed LAST, as the final tmux call before the caller's `spawnSync`. The
@@ -686,8 +687,9 @@ export async function beginAttachHandoff(
if (tty && isTuiClientTty(tty)) await client.disarmTuiSwitchGuard(tty);
if (oneKey) await client.unbindDetachKey(ONE_KEY_DETACH, 'root');
if (claimed && alias) await client.unbindDetachKey(alias);
// The hooks before the size: a hook left armed would put `latest` back
// the next time anything fired it, after the browser re-pinned the window.
// The follow hooks before the size: the restore below is a
// `resize-window`, and an armed `after-resize-window` hook would put
// `latest` straight back over the browser's size.
for (const target of followTyping) await client.disarmFollowTyping(target, tty as string);
// Options first, then the size: dropping the status bar gives its row
// back to the pane, and the resize is what re-pins the browser's
+132 -113
View File
@@ -508,51 +508,61 @@ export function tuiSwitchAttachHook(tty: string): string {
}
/**
* Session hook that gives the window back to the TUI's terminal when you type
* there. Indexed so it does not replace a user's own `client-active` hook, and
* next to the switch guard's `[90]`.
* Session option naming the tty of the `codeman tui` attach that owns the
* window size of this session. The follow hooks below read it, so a hook whose
* owner is gone does nothing.
*/
export const TUI_FOLLOW_OWNER = '@codeman-tui-follow';
/**
* Session hooks that keep a window following the attach's terminal, the way
* plain tmux follows whichever client was used last.
*
* Why it is needed: the attach sets `window-size latest`, but Codeman's web
* resize (`resizeWindow()` in tmux-manager.ts) runs `resize-window`, which
* puts the window back on `manual` at the browser's size. A phone opening the
* Why they are needed: the attach sets `window-size latest`, but Codeman's web
* resize (`resizeWindow()` in tmux-manager.ts) runs `resize-window`, and
* Codeman's own attach (`setManualWindowSize()`) sets `manual`. Either puts
* the window back on `manual` at the browser's size. A phone opening the
* session mid-attach therefore pinned the window to the phone, and typing or
* pasting in the terminal changed nothing until the user detached and
* attached again.
* pasting in the terminal changed nothing until a detach and a fresh attach.
*
* Set per session (`set-hook -t`), never globally: it lives and dies with the
* attach's sessions and never reaches a session the TUI did not dress.
* - `after-resize-window[91]` puts `latest` back right after Codeman's
* resize, so tmux keeps deciding: the browser's client is the latest one
* when Codeman resized its pty, and the terminal stays in front when the
* resize did not change that pty (a forced resize at the same size, which
* a browser sends when it opens a session).
* - `client-active[91]` puts `latest` back when the TUI's own client becomes
* the latest one again, which typing, pasting or resizing the terminal does
* after another client was used (measured on tmux 3.8). That covers
* `setManualWindowSize()`, which sets `manual` without a resize.
*
* Indexed so they do not replace a user's own hooks, next to the switch
* guard's `[90]`, and set per session (`set-hook -t`), never globally.
*
* ⚠️ Constant strings: the tty is read from `TUI_FOLLOW_OWNER` when a hook
* runs, never interpolated. And no `-t` on `set-window-option`: tmux parses a
* hook's command when the hook is set, and an unquoted `#{session_name}`
* there starts a comment (measured: "-t expects an argument"). Without `-t`
* the command targets the window the hook fired for.
*/
export const TUI_FOLLOW_TYPING_HOOK = 'client-active[91]';
export const TUI_FOLLOW_HOOKS: Readonly<Record<string, string>> = {
'client-active[91]': `if-shell -F "#{==:#{client_tty},#{${TUI_FOLLOW_OWNER}}}" "set-window-option window-size latest"`,
'after-resize-window[91]': `if-shell -F "#{!=:#{${TUI_FOLLOW_OWNER}},}" "set-window-option window-size latest"`,
};
/**
* `set-hook` command for `TUI_FOLLOW_TYPING_HOOK`. tmux runs `client-active`
* when a client becomes the latest one on its session, which includes typing
* or pasting after another client did (measured on tmux 3.8). Only this TUI's
* client (`client_tty`) puts `latest` back; a browser tab's client is left to
* Codeman's own arbitration (`Session.resize()`).
*
* ⚠️ `set-window-option` takes no `-t` here on purpose. tmux parses a hook's
* command when the hook is set, and an unquoted `#{session_name}` there
* starts a comment (measured: "-t expects an argument"). Without `-t` the
* command targets the window of the client that fired the hook, which is the
* one it is meant for.
* For each follow hook name, what `show-hooks -t` lists at that index: `ours`,
* `theirs` (a hook of the user's), or absent when nothing is set there.
*/
export function tuiFollowTypingHook(tty: string): string {
return `if-shell -F "#{==:#{client_tty},${tty}}" "set-window-option window-size latest"`;
}
/**
* The tty a `client-active[91]` hook line from `show-hooks -t` was set for,
* or null when the line is not one of ours. The closed form `,<tty>}` is
* matched, so `/dev/pts/4` is not read out of a hook for `/dev/pts/41`.
*/
export function tuiFollowTypingHookTty(line: string): string | null {
const text = line.trim();
if (!text.startsWith(`${TUI_FOLLOW_TYPING_HOOK} `)) return null;
if (!text.includes('set-window-option window-size latest')) return null;
const match = /#\{==:#\{client_tty\},(\/dev\/[^}]+)\}/.exec(text);
const tty = match?.[1] ?? '';
return isTuiClientTty(tty) ? tty : null;
export function parseFollowHooks(stdout: string): Record<string, 'ours' | 'theirs'> {
const found: Record<string, 'ours' | 'theirs'> = {};
for (const line of stdout.split('\n')) {
const text = line.trim();
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) {
if (!text.startsWith(`${name} `)) continue;
found[name] = text.includes(`#{${TUI_FOLLOW_OWNER}}`) ? 'ours' : 'theirs';
}
}
return found;
}
const LEGACY_TUI_SWITCH = /^switch-client -t (\S+?)(?: \\; set-window-option -t \1 window-size latest)?$/;
@@ -1221,30 +1231,25 @@ export class TuiClient {
}
/**
* Install `TUI_FOLLOW_TYPING_HOOK` on one session for this terminal. Best
* effort, like the rest of the attach dressing: false leaves the attach as it
* was before the hook existed (the window follows the terminal until the web
* UI resizes it).
* Make one session's window follow this terminal for the attach: record the
* tty as the owner, then install `TUI_FOLLOW_HOOKS`. Best effort, like the
* rest of the attach dressing: false leaves the attach as it was before the
* hooks existed (the window follows the terminal until the web UI resizes it).
*
* A hook at that index that is not ours is the user's and is left alone. One
* of ours for another tty is replaced: it belongs to a TUI that was killed
* before its restore (a stale tty), or to a second TUI on the same session,
* and the newest attach is the one in front of the user.
* A hook at either index that is not ours is the user's, and then nothing is
* installed. An owner already recorded is replaced: it is a TUI killed before
* its restore, or a second TUI on the same session, and the newest attach is
* the one in front of the user.
*/
async armFollowTyping(muxName: string, clientTty: string): Promise<boolean> {
if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return false;
try {
const current = await this.readFollowTypingHook(muxName);
if (current !== null && tuiFollowTypingHookTty(current) === null) return false;
await this.exec('tmux', [
'-L',
this.socket,
'set-hook',
'-t',
muxName,
TUI_FOLLOW_TYPING_HOOK,
tuiFollowTypingHook(clientTty),
]);
const hooks = await this.readFollowHooks(muxName);
if (Object.values(hooks).includes('theirs')) return false;
await this.exec('tmux', ['-L', this.socket, 'set-option', '-t', muxName, TUI_FOLLOW_OWNER, clientTty]);
for (const [name, command] of Object.entries(TUI_FOLLOW_HOOKS)) {
await this.exec('tmux', ['-L', this.socket, 'set-hook', '-t', muxName, name, command]);
}
return true;
} catch {
return false;
@@ -1252,25 +1257,86 @@ export class TuiClient {
}
/**
* Undo `armFollowTyping`, but only while the hook still names this tty: a
* second TUI that attached later owns it now.
* Undo `armFollowTyping`, but only while this tty is still the owner: a
* second TUI that attached later owns the session now. The owner goes first,
* so the hooks are inert from that moment even if removing them fails.
*/
async disarmFollowTyping(muxName: string, clientTty: string): Promise<void> {
if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return;
try {
const current = await this.readFollowTypingHook(muxName);
if (current === null || tuiFollowTypingHookTty(current) !== clientTty) return;
await this.exec('tmux', ['-L', this.socket, 'set-hook', '-u', '-t', muxName, TUI_FOLLOW_TYPING_HOOK]);
if ((await this.readFollowOwner(muxName)) !== clientTty) return;
await this.dropFollowTyping(muxName);
} catch {
/* the session may be gone (the user exited the agent from inside the attach) */
}
}
/** The session's own `client-active[91]` line, or null when nothing is set there. */
private async readFollowTypingHook(muxName: string): Promise<string | null> {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'show-hooks', '-t', muxName]);
return stdout.split('\n').find((line) => line.startsWith(`${TUI_FOLLOW_TYPING_HOOK} `)) ?? null;
/**
* Remove follow hooks a previous TUI never got to take down.
*
* Same leak as the banners: a terminal that dies while attached (a closed
* window, a dropped SSH) never reaches `restore()`, and its owner stays
* recorded, so the window kept following whatever client a pty reusing that
* number belonged to. This removes the owner and our hooks where the owner
* has no live tmux client.
*
* ⚠️ `ownTty` is never swept. The sweep runs fire-and-forget at startup, and
* an Enter pressed before it finishes arms this terminal before it is a tmux
* client, so the client listing cannot vouch for it yet. A second TUI
* mid-attach is a live client and is left alone the same way.
*/
async clearLeakedFollowTyping(ownTty: string | null = readControllingTty()): Promise<number> {
let names: string[];
let live: Set<string>;
try {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-sessions', '-F', '#{session_name}']);
names = stdout
.split('\n')
.map((line) => line.trim())
.filter((line) => MUX_NAME_PATTERN.test(line));
const clients = await this.exec('tmux', ['-L', this.socket, 'list-clients', '-F', '#{client_tty}']);
live = new Set(clients.stdout.split('\n').map((line) => line.trim()));
} catch {
return 0;
}
let cleared = 0;
for (const name of names) {
try {
const owner = await this.readFollowOwner(name);
if (owner === null || owner === ownTty || live.has(owner)) continue;
await this.dropFollowTyping(name);
cleared += 1;
} catch {
/* the session went away mid-sweep */
}
}
return cleared;
}
/** The tty recorded as `TUI_FOLLOW_OWNER` on a session, or null when none is. */
private async readFollowOwner(muxName: string): Promise<string | null> {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'show-options', '-t', muxName]);
// The listing, not `show-options -v`: an unset user option is an error on
// tmux 3.5 but empty output and exit 0 on 3.2a.
const owner = parseSessionOptions(stdout, [TUI_FOLLOW_OWNER])[TUI_FOLLOW_OWNER];
return owner ? owner : null;
}
private async readFollowHooks(muxName: string): Promise<Record<string, 'ours' | 'theirs'>> {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'show-hooks', '-t', muxName]);
return parseFollowHooks(stdout);
}
/** Owner first (the hooks are inert from then on), then whichever hooks are ours. */
private async dropFollowTyping(muxName: string): Promise<void> {
await this.exec('tmux', ['-L', this.socket, 'set-option', '-u', '-t', muxName, TUI_FOLLOW_OWNER]);
const hooks = await this.readFollowHooks(muxName);
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) {
if (hooks[name] !== 'ours') continue;
await this.exec('tmux', ['-L', this.socket, 'set-hook', '-u', '-t', muxName, name]);
}
}
/**
* Give back a switch key, but only while it is still one of ours.
*
@@ -1457,53 +1523,6 @@ export class TuiClient {
return cleared;
}
/**
* Drop `client-active[91]` hooks a previous TUI never got to remove.
*
* Same leak as the banners above: a terminal that dies while attached never
* reaches `restore()`. A leaked hook acts only for its tty, so it is harmless
* until a pty reuses that number, and then it hands a window to whatever
* client got it. This sweep removes ours whose tty has no live tmux client.
*
* ⚠️ `ownTty` is never swept. The sweep runs fire-and-forget at startup, and
* an Enter pressed before it finishes arms this terminal's hook before this
* terminal is a tmux client, so the client listing cannot vouch for it yet.
* A second TUI mid-attach is a live client and is left alone the same way.
*/
async clearLeakedFollowTyping(ownTty: string | null = readControllingTty()): Promise<number> {
let names: string[];
let live: Set<string>;
try {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-sessions', '-F', '#{session_name}']);
names = stdout
.split('\n')
.map((line) => line.trim())
.filter((line) => MUX_NAME_PATTERN.test(line));
const clients = await this.exec('tmux', ['-L', this.socket, 'list-clients', '-F', '#{client_tty}']);
live = new Set(clients.stdout.split('\n').map((line) => line.trim()));
} catch {
return 0;
}
let cleared = 0;
for (const name of names) {
let tty: string | null;
try {
const current = await this.readFollowTypingHook(name);
tty = current === null ? null : tuiFollowTypingHookTty(current);
} catch {
continue;
}
if (tty === null || tty === ownTty || live.has(tty)) continue;
try {
await this.exec('tmux', ['-L', this.socket, 'set-hook', '-u', '-t', name, TUI_FOLLOW_TYPING_HOOK]);
cleared += 1;
} catch {
/* the session went away mid-sweep */
}
}
return cleared;
}
private async setOption(args: readonly string[]): Promise<void> {
try {
await this.exec('tmux', ['-L', this.socket, 'set-option', ...args]);