From ba61cfe4e6f005d279cecf561e1d4736953bc5a2 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Tue, 24 Nov 2026 18:28:06 +0100 Subject: [PATCH 1/5] fix(tui): take the window size back when the attached terminal is used `codeman tui` sets `window-size latest` for an attach, but a browser tab that opens or resizes the same session mid-attach makes Codeman run `resize-window`, which puts the window back on `manual` at the browser's size. The terminal then showed a phone-sized pane, and typing or pasting changed nothing until a detach and a fresh attach. The attach now sets a per-session `client-active[91]` hook on every session it dresses. It runs `set-window-option window-size latest` only for the TUI's own client (`#{client_tty}`), so typing, pasting or resizing the terminal hands the window back to it, the way plain tmux follows whoever used it last. `restore()` removes the hooks before the window sizes are put back, and only while they still name this tty. Co-Authored-By: Claude Opus 5.5 --- .changeset/tui-follow-typing-client.md | 5 + docs/architecture-invariants.md | 2 +- docs/tui.md | 10 ++ src/tui/tui-app.ts | 13 ++ src/tui/tui-client.ts | 99 +++++++++++++ test/tui/tui-app.test.ts | 78 +++++++++++ test/tui/tui-client.test.ts | 87 ++++++++++++ test/tui/tui-follow-typing.test.ts | 187 +++++++++++++++++++++++++ 8 files changed, 480 insertions(+), 1 deletion(-) create mode 100644 .changeset/tui-follow-typing-client.md create mode 100644 test/tui/tui-follow-typing.test.ts diff --git a/.changeset/tui-follow-typing-client.md b/.changeset/tui-follow-typing-client.md new file mode 100644 index 00000000..9874f42a --- /dev/null +++ b/.changeset/tui-follow-typing-client.md @@ -0,0 +1,5 @@ +--- +'aicodeman': patch +--- + +`codeman tui`: a terminal attached to a session takes the window size back when you type, paste or resize it, after a browser tab (a phone, for example) opened or resized the same session and Codeman sized the window to that tab. Until now the terminal kept showing a small pane until a detach and a fresh attach. The attach sets a `client-active` hook on the sessions it dressed that acts only for its own tmux client, and removes it on detach. Needs tmux 3.3 or newer. diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index a10b1f72..047c7373 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -18,7 +18,7 @@ Implementation detail extracted from `CLAUDE.md` so that file stays small enough ### The prefix table on Codeman's socket holds only send-prefix -**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T ` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. +**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T
` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). The attach also sets a per-session `client-active[91]` hook (`tuiFollowTypingHook` in `src/tui/tui-client.ts`, `set-hook -t` on each session it dresses, never `-g`) that runs `set-window-option window-size latest` only when `#{client_tty}` is the TUI's terminal: a browser opening the session mid-attach makes Codeman run `resize-window`, which puts the window back on `manual` at the browser's size, and without the hook typing in the terminal never took it back. tmux fires `client-active` when a different client becomes the latest on the session, and a client resize counts (measured on tmux 3.8), so Codeman's resize of its own attach client re-arms the next keystroke. ⚠️ The hook's command carries no `-t`: tmux parses it when the hook is set, and an unquoted `#{session_name}` there starts a comment. `restore()` removes it only while it names this tty; a hook for a dead tty (TUI killed before restore) is replaced by the next attach and, if a browser's client reuses that pty, only sets `latest` for a window that client already sizes. Tests: `test/tui/tui-follow-typing.test.ts` (real tmux, two pty clients). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. ### Reverse-proxy base path diff --git a/docs/tui.md b/docs/tui.md index 571e0f15..1ad5c041 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -216,6 +216,16 @@ exactly as it was on detach, along with each window's size. Every session the st can switch to is dressed and sized the same way, so switching is instant and lands in a pane that already fills your terminal. +The window follows whoever used it last, as plain tmux does. If a browser tab (a +phone, say) opens or resizes the session while you are attached, Codeman sizes the +window to that tab, and your terminal shows a smaller pane. Type, paste or resize +your terminal and the window fills it again. The TUI does this with a +`client-active[91]` hook on each session it dressed, which only acts for this +terminal's tmux client, and it removes the hooks on detach. Typing in the browser +tab is left to Codeman's own sizing rules. tmux older than 3.3 has no +`client-active` hook, so there the pane stays at the browser's size until you +detach and attach again. + Detaching leaves the agent running; typing `exit` or pressing `Ctrl+D` would end it, which is the difference the bar exists to make obvious. If an agent does exit, its pane stays as a corpse: the TUI refuses to attach to a dead pane and offers `r` to diff --git a/src/tui/tui-app.ts b/src/tui/tui-app.ts index bbe39a58..0d7641b9 100644 --- a/src/tui/tui-app.ts +++ b/src/tui/tui-app.ts @@ -638,6 +638,7 @@ export async function beginAttachHandoff( const banner = bannerFor(muxName, label); const dressed: Array<{ muxName: string; options: TuiSessionOptions }> = []; const resized: Array<{ muxName: string; sizing: TuiWindowSizing }> = []; + const followTyping: string[] = []; const targets = new Map([[muxName, label]]); for (const tab of tabs.slice(0, 9)) { if (tab.muxName && !targets.has(tab.muxName)) targets.set(tab.muxName, tab.label); @@ -659,6 +660,15 @@ export async function beginAttachHandoff( // let the session we are actually opening follow the terminal live. if (cols && rows && rows > 1) await client.presizeWindow(target, cols, rows - 1); if (target === muxName) await client.followAttachingClient(target); + // ⚠️ `latest` does not hold for the whole attach. A browser that opens or + // 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. + 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 // hook is one-shot for this tty, so a TUI killed between arming and attaching @@ -676,6 +686,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. + 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 // authority over the window. diff --git a/src/tui/tui-client.ts b/src/tui/tui-client.ts index 89462694..02d19f42 100644 --- a/src/tui/tui-client.ts +++ b/src/tui/tui-client.ts @@ -507,6 +507,54 @@ 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]`. + * + * 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 + * 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. + * + * 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. + */ +export const TUI_FOLLOW_TYPING_HOOK = 'client-active[91]'; + +/** + * `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. + */ +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 `,}` 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; +} + const LEGACY_TUI_SWITCH = /^switch-client -t (\S+?)(?: \\; set-window-option -t \1 window-size latest)?$/; /** @@ -1172,6 +1220,57 @@ 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). + * + * 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. + */ + async armFollowTyping(muxName: string, clientTty: string): Promise { + 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), + ]); + return true; + } catch { + return false; + } + } + + /** + * Undo `armFollowTyping`, but only while the hook still names this tty: a + * second TUI that attached later owns it now. + */ + async disarmFollowTyping(muxName: string, clientTty: string): Promise { + 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]); + } 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 { + 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; + } /** * Give back a switch key, but only while it is still one of ours. * diff --git a/test/tui/tui-app.test.ts b/test/tui/tui-app.test.ts index c3e0e03a..4e293249 100644 --- a/test/tui/tui-app.test.ts +++ b/test/tui/tui-app.test.ts @@ -676,6 +676,8 @@ describe('attach switch keys stay on the TUI client', () => { order.push('follow'); return true; }, + armFollowTyping: async () => true, + disarmFollowTyping: async () => undefined, restoreWindowSizing: async () => true, } as unknown as TuiClient; @@ -726,6 +728,82 @@ describe('attach switch keys stay on the TUI client', () => { }); }); +describe('attach takes the window back from a browser when the terminal is used', () => { + /** Records the sizing calls in order; everything else is a no-op. */ + function sizingFake(armResult = true) { + const calls: string[] = []; + const client = { + readPrefixKey: async () => 'C-b', + readDetachKey: async () => 'd', + readPrefixBinding: async () => null, + bindDetachKey: async () => true, + unbindDetachKey: async () => true, + armTuiSwitchGuard: async () => true, + disarmTuiSwitchGuard: async () => undefined, + bindSwitchKey: async () => true, + unbindSwitchKey: async () => undefined, + readSessionOptions: async () => null, + applySessionOptions: async () => true, + restoreSessionOptions: async () => undefined, + readWindowSizing: async () => ({ cols: 60, rows: 30, mode: 'manual' }), + presizeWindow: async () => true, + followAttachingClient: async (muxName: string) => { + calls.push(`follow ${muxName}`); + return true; + }, + armFollowTyping: async (muxName: string, tty: string) => { + calls.push(`arm ${muxName} ${tty}`); + return armResult; + }, + disarmFollowTyping: async (muxName: string, tty: string) => { + calls.push(`disarm ${muxName} ${tty}`); + }, + restoreWindowSizing: async (muxName: string) => { + calls.push(`size ${muxName}`); + }, + } as unknown as TuiClient; + return { client, calls }; + } + + const tabs = [ + { index: 1, label: 'w1', active: true, muxName: 'codeman-aaaa1111' }, + { index: 2, label: 'w2', active: false, muxName: 'codeman-bbbb2222' }, + ]; + + it('arms the hook on every session the strip can reach, and drops it before the size is put back', async () => { + const { client, calls } = sizingFake(); + const handoff = await beginAttachHandoff(client, 'codeman-aaaa1111', 'w1', tabs, 200, 50, '/dev/pts/4'); + // Alt+2 lands in the second session, and a phone can pin that one too. + expect(calls).toEqual([ + 'follow codeman-aaaa1111', + 'arm codeman-aaaa1111 /dev/pts/4', + 'arm codeman-bbbb2222 /dev/pts/4', + ]); + + calls.length = 0; + await handoff.restore(); + // Disarmed first: the size restore re-pins the browser's authority, and + // a hook still armed after it could hand the window back to a reused pty. + expect(calls).toEqual([ + 'disarm codeman-aaaa1111 /dev/pts/4', + 'disarm codeman-bbbb2222 /dev/pts/4', + 'size codeman-aaaa1111', + 'size codeman-bbbb2222', + ]); + }); + + it('arms nothing without a tty to guard on, and disarms only what it armed', async () => { + const bare = sizingFake(); + await (await beginAttachHandoff(bare.client, 'codeman-aaaa1111', 'w1', tabs, 200, 50, null)).restore(); + expect(bare.calls.filter((call) => call.startsWith('arm') || call.startsWith('disarm'))).toEqual([]); + + // A session whose hook slot is the user's (arm answered false) is not disarmed. + const refused = sizingFake(false); + await (await beginAttachHandoff(refused.client, 'codeman-aaaa1111', 'w1', tabs, 200, 50, '/dev/pts/4')).restore(); + expect(refused.calls.filter((call) => call.startsWith('disarm'))).toEqual([]); + }); +}); + describe('naming a session the TUI starts', () => { it("follows the web UI's w- convention", () => { expect(nextSessionName('mirofish', [])).toBe('w1-mirofish'); diff --git a/test/tui/tui-client.test.ts b/test/tui/tui-client.test.ts index 2c09e094..ec7f8634 100644 --- a/test/tui/tui-client.test.ts +++ b/test/tui/tui-client.test.ts @@ -29,6 +29,9 @@ import { tuiSwitchBindingTty, tuiSwitchAttachHook, tuiSwitchGuard, + tuiFollowTypingHook, + tuiFollowTypingHookTty, + TUI_FOLLOW_TYPING_HOOK, isTuiClientTty, ATTACH_BANNER_MARKER, parseTmuxSessionList, @@ -519,6 +522,90 @@ describe('degraded-mode tmux enumeration', () => { }); }); +describe('the follow-typing hook', () => { + function hookClient(exec: TuiExecFile): TuiClient { + return new TuiClient({ baseUrl, socket: 'codeman-beta', exec }); + } + const line = (tty: string): string => `${TUI_FOLLOW_TYPING_HOOK} ${tuiFollowTypingHook(tty)}`; + + it('reads its own tty back out of the closed form, and nothing else', () => { + expect(tuiFollowTypingHookTty(line('/dev/pts/4'))).toBe('/dev/pts/4'); + expect(tuiFollowTypingHookTty(line('/dev/ttys033'))).toBe('/dev/ttys033'); + expect(tuiFollowTypingHookTty(line('/dev/pts/41'))).toBe('/dev/pts/41'); + // The user's own hook at the same index, or at another one, is not ours. + expect(tuiFollowTypingHookTty(`${TUI_FOLLOW_TYPING_HOOK} display-message mine`)).toBeNull(); + expect(tuiFollowTypingHookTty(`client-active[0] ${tuiFollowTypingHook('/dev/pts/4')}`)).toBeNull(); + expect(tuiFollowTypingHookTty('')).toBeNull(); + }); + + it('arms with an argv array on the session, after checking the slot is free', async () => { + const calls: Array = []; + const client = hookClient(async (_file, args) => { + calls.push(args); + return { stdout: 'client-attached[90] something else\n', stderr: '' }; + }); + await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(true); + expect(calls).toEqual([ + ['-L', 'codeman-beta', 'show-hooks', '-t', 'codeman-1a2b3c4d'], + [ + '-L', + 'codeman-beta', + 'set-hook', + '-t', + 'codeman-1a2b3c4d', + 'client-active[91]', + 'if-shell -F "#{==:#{client_tty},/dev/pts/4}" "set-window-option window-size latest"', + ], + ]); + }); + + it('leaves a hook of the user at its index alone', async () => { + const calls: Array = []; + const client = hookClient(async (_file, args) => { + calls.push(args); + return { stdout: `${TUI_FOLLOW_TYPING_HOOK} display-message mine\n`, stderr: '' }; + }); + await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); + await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); + expect(calls.every((args) => args[2] === 'show-hooks')).toBe(true); + }); + + it('disarms only while the hook still names this tty', async () => { + let stored = line('/dev/pts/41'); + const calls: Array = []; + const client = hookClient(async (_file, args) => { + calls.push(args); + return { stdout: `${stored}\n`, stderr: '' }; + }); + // pts/4 is a prefix of pts/41: that hook is another TUI's. + await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); + expect(calls.map((args) => args[2])).toEqual(['show-hooks']); + + stored = line('/dev/pts/4'); + calls.length = 0; + await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); + expect(calls[1]).toEqual(['-L', 'codeman-beta', 'set-hook', '-u', '-t', 'codeman-1a2b3c4d', 'client-active[91]']); + }); + + it('refuses names and ttys it must not interpolate, and swallows a dead tmux', async () => { + const calls: Array = []; + const client = hookClient(async (_file, args) => { + calls.push(args); + return { stdout: '', stderr: '' }; + }); + await expect(client.armFollowTyping('other-session', '/dev/pts/4')).resolves.toBe(false); + await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4"; kill-server; "')).resolves.toBe(false); + await client.disarmFollowTyping('codeman-ssh-prod', '/dev/pts/4'); + expect(calls).toEqual([]); + + const dead = hookClient(async () => { + throw new Error('no server running on /tmp/tmux-1000/codeman-beta'); + }); + await expect(dead.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); + await expect(dead.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBeUndefined(); + }); +}); + describe('attach window sizing', () => { /** A client that only ever needs its injected exec: none of this talks to a server. */ function sizingClient(exec: TuiExecFile): TuiClient { diff --git a/test/tui/tui-follow-typing.test.ts b/test/tui/tui-follow-typing.test.ts new file mode 100644 index 00000000..45655eee --- /dev/null +++ b/test/tui/tui-follow-typing.test.ts @@ -0,0 +1,187 @@ +/** + * @fileoverview A `codeman tui` attach takes the window size back when you type + * in it, after a browser tab re-pinned the window to its own size. + * + * Against a real tmux on a private socket (never Codeman's). Two attach clients + * on ptys: one is the TUI's terminal, the other is what a browser tab is (one + * `tmux attach-session` per session, sized by Codeman). The browser's resize is + * what `TmuxManager.resizeWindow()` runs: `resize-window -x -y`, which puts the + * window on `manual`. + * + * Port: N/A (no server) + */ +import { afterAll, describe, expect, it } from 'vitest'; +import { execFileSync, execSync } from 'node:child_process'; +import { rmSync } from 'node:fs'; +import * as pty from 'node-pty'; +import { TUI_FOLLOW_TYPING_HOOK, TuiClient } from '../../src/tui/tui-client.js'; + +const hasTmux = (() => { + try { + execSync('tmux -V', { stdio: 'ignore' }); + } catch { + return false; + } + // `client-active` exists from tmux 3.3. An older tmux refuses the hook, and + // armFollowTyping() answers false there, which the unit tests cover. + const version = /tmux (?:next-)?([0-9]+)\.([0-9]+)/.exec(execSync('tmux -V', { encoding: 'utf8' })); + if (!version) return false; + const major = Number(version[1]); + const minor = Number(version[2]); + return major > 3 || (major === 3 && minor >= 3); +})(); + +describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => { + const socket = `codeman-tui-follow-${process.pid}`; + const alpha = 'codeman-aaaa3333'; + const run = (args: readonly string[]): string => + execFileSync('tmux', ['-L', socket, '-f', '/dev/null', ...args], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + const client = new TuiClient({ socket }); + const clients: pty.IPty[] = []; + + function attach(cols: number, rows: number): pty.IPty { + const env = { ...process.env } as Record; + delete env.TMUX; + const term = pty.spawn('tmux', ['-L', socket, '-f', '/dev/null', 'attach-session', '-t', alpha], { + name: 'xterm-256color', + cols, + rows, + env, + }); + term.onData(() => { + /* drain, so tmux never blocks on a full pty */ + }); + clients.push(term); + return term; + } + + /** The tty tmux reports for a client, found by its pid (portable: macOS has no /proc). */ + function ttyOf(term: pty.IPty): string { + for (const line of run(['list-clients', '-F', '#{client_pid}\t#{client_tty}']).split('\n')) { + const [pid, tty] = line.trim().split('\t'); + if (pid === String(term.pid) && tty) return tty; + } + return ''; + } + + function windowSize(): string { + return run(['display-message', '-p', '-t', alpha, '#{window_width}x#{window_height} #{window-size}']).trim(); + } + + function hooks(): string { + return run(['show-hooks', '-t', alpha]); + } + + async function waitFor(check: () => boolean, ms = 4000): Promise { + const deadline = Date.now() + ms; + while (Date.now() < deadline) { + if (check()) return true; + await new Promise((resolve) => setTimeout(resolve, 40)); + } + return check(); + } + + /** + * Codeman's web resize, as `Session.resize()` does it: the tab's attach + * client's pty, then `TmuxManager.resizeWindow()`'s `resize-window`. + */ + async function browserResize(term: pty.IPty, cols: number, rows: number): Promise { + term.resize(cols, rows); + await new Promise((resolve) => setTimeout(resolve, 150)); + run(['resize-window', '-t', alpha, '-x', String(cols), '-y', String(rows)]); + } + + afterAll(() => { + for (const term of clients) term.kill(); + let socketPath = ''; + try { + socketPath = run(['display-message', '-p', '#{socket_path}']).trim(); + run(['kill-server']); + } catch { + /* already gone */ + } + if (socketPath.endsWith(`/${socket}`)) rmSync(socketPath, { force: true }); + }); + + it('gives the window back to the TUI terminal on its next keystroke, and only to that terminal', async () => { + run(['new-session', '-d', '-s', alpha, '-x', '120', '-y', '40', 'cat']); + run(['set-option', '-g', 'status', 'off']); + run(['set-window-option', '-t', alpha, 'window-size', 'manual']); + + const tui = attach(200, 50); + let tuiTty = ''; + expect(await waitFor(() => (tuiTty = ttyOf(tui)) !== '')).toBe(true); + expect(await client.followAttachingClient(alpha)).toBe(true); + expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true); + expect(hooks()).toContain(TUI_FOLLOW_TYPING_HOOK); + // The closed form, which disarm and re-arm match on. + expect(hooks()).toContain(`#{client_tty},${tuiTty}}`); + // Set on the session, not the server: no other session gets it. + expect(run(['show-hooks', '-g'])).not.toContain(TUI_FOLLOW_TYPING_HOOK); + expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true); + + // A phone opens the session: its client attaches and Codeman pins the window. + const browser = attach(60, 30); + expect(await waitFor(() => ttyOf(browser) !== '')).toBe(true); + run(['resize-window', '-t', alpha, '-x', '60', '-y', '30']); + expect(windowSize()).toBe('60x30 manual'); + + // Typing in the browser tab is Codeman's business, not the hook's. + browser.write('b'); + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(windowSize()).toBe('60x30 manual'); + + // Typing in the TUI terminal takes it back. This is the bug: without the + // hook the window stayed 60x30 manual here for the rest of the attach. + tui.write('a'); + expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true); + + // Resizing the TUI terminal is using it too: tmux makes the resized client + // the latest one, so the hook fires without a keystroke (measured on 3.8). + await browserResize(browser, 62, 30); + expect(windowSize()).toBe('62x30 manual'); + tui.resize(150, 45); + expect(await waitFor(() => windowSize() === '150x45 latest')).toBe(true); + + // The browser resizing its client makes THAT client the latest one, so + // the TUI's next keystroke is a change of client and fires the hook again. + await browserResize(browser, 62, 31); + expect(windowSize()).toBe('62x31 manual'); + tui.write('a'); + expect(await waitFor(() => windowSize() === '150x45 latest')).toBe(true); + }); + + it('disarms only its own hook, and never replaces one of the user', async () => { + const tuiTty = ttyOf(clients[0]); + expect(tuiTty).not.toBe(''); + + // Another tty's restore leaves this attach's hook alone (pts/4 vs pts/41 included). + await client.disarmFollowTyping(alpha, `${tuiTty}1`); + expect(hooks()).toContain(TUI_FOLLOW_TYPING_HOOK); + + await client.disarmFollowTyping(alpha, tuiTty); + expect(hooks()).not.toContain(TUI_FOLLOW_TYPING_HOOK); + // Disarmed means the next keystroke changes nothing. + await browserResize(clients[1], 64, 30); + clients[0].write('a'); + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(windowSize()).toBe('64x30 manual'); + + // A hook of the user's own at that index is never overwritten. + run(['set-hook', '-t', alpha, TUI_FOLLOW_TYPING_HOOK, 'display-message mine']); + expect(await client.armFollowTyping(alpha, tuiTty)).toBe(false); + expect(hooks()).toContain('display-message mine'); + await client.disarmFollowTyping(alpha, tuiTty); + expect(hooks()).toContain('display-message mine'); + run(['set-hook', '-u', '-t', alpha, TUI_FOLLOW_TYPING_HOOK]); + + // One of ours for a stale tty (a TUI killed before its restore) is taken over. + expect(await client.armFollowTyping(alpha, `${tuiTty}1`)).toBe(true); + expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true); + expect(hooks()).toContain(`#{client_tty},${tuiTty}}`); + expect(hooks()).not.toContain(`#{client_tty},${tuiTty}1}`); + }); +}); From d387cf8cdbfacb23b0323353ae5648bfe6d65eab Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Tue, 24 Nov 2026 18:30:27 +0100 Subject: [PATCH 2/5] fix(tui): sweep follow-typing hooks a killed TUI left behind A terminal that dies while attached (closed window, dropped SSH) never reaches restore(), so its client-active[91] hooks stayed on the sessions. TUI startup now removes ours whose tty has no live tmux client, next to the leaked-banner sweep. The TUI's own tty is never swept: the sweep is fire-and-forget, and an early Enter can arm that hook before the attach client exists. Co-Authored-By: Claude Opus 5.5 --- docs/architecture-invariants.md | 2 +- src/tui/tui-app.ts | 1 + src/tui/tui-client.ts | 47 +++++++++++++++++++++++++++++++++ test/tui/tui-client.test.ts | 47 +++++++++++++++++++++++++++++++++ 4 files changed, 96 insertions(+), 1 deletion(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 047c7373..dcab0877 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -18,7 +18,7 @@ Implementation detail extracted from `CLAUDE.md` so that file stays small enough ### The prefix table on Codeman's socket holds only send-prefix -**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T
` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). The attach also sets a per-session `client-active[91]` hook (`tuiFollowTypingHook` in `src/tui/tui-client.ts`, `set-hook -t` on each session it dresses, never `-g`) that runs `set-window-option window-size latest` only when `#{client_tty}` is the TUI's terminal: a browser opening the session mid-attach makes Codeman run `resize-window`, which puts the window back on `manual` at the browser's size, and without the hook typing in the terminal never took it back. tmux fires `client-active` when a different client becomes the latest on the session, and a client resize counts (measured on tmux 3.8), so Codeman's resize of its own attach client re-arms the next keystroke. ⚠️ The hook's command carries no `-t`: tmux parses it when the hook is set, and an unquoted `#{session_name}` there starts a comment. `restore()` removes it only while it names this tty; a hook for a dead tty (TUI killed before restore) is replaced by the next attach and, if a browser's client reuses that pty, only sets `latest` for a window that client already sizes. Tests: `test/tui/tui-follow-typing.test.ts` (real tmux, two pty clients). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. +**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T
` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). The attach also sets a per-session `client-active[91]` hook (`tuiFollowTypingHook` in `src/tui/tui-client.ts`, `set-hook -t` on each session it dresses, never `-g`) that runs `set-window-option window-size latest` only when `#{client_tty}` is the TUI's terminal: a browser opening the session mid-attach makes Codeman run `resize-window`, which puts the window back on `manual` at the browser's size, and without the hook typing in the terminal never took it back. tmux fires `client-active` when a different client becomes the latest on the session, and a client resize counts (measured on tmux 3.8), so Codeman's resize of its own attach client re-arms the next keystroke. ⚠️ The hook's command carries no `-t`: tmux parses it when the hook is set, and an unquoted `#{session_name}` there starts a comment. `restore()` removes it only while it names this tty. A TUI killed mid-attach leaks it, so TUI startup runs `clearLeakedFollowTyping()` beside the banner sweep: it removes ours whose tty has no live tmux client, and never the TUI's own tty (the sweep is fire-and-forget, so an early Enter can arm that one before its client exists). Tests: `test/tui/tui-follow-typing.test.ts` (real tmux, two pty clients). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. ### Reverse-proxy base path diff --git a/src/tui/tui-app.ts b/src/tui/tui-app.ts index 0d7641b9..72943281 100644 --- a/src/tui/tui-app.ts +++ b/src/tui/tui-app.ts @@ -1278,6 +1278,7 @@ class TuiApp { // Fire and forget: a bar stranded by a previous run is cosmetic, so it must // never delay the first frame or fail a start. void this.client.clearLeakedAttachBanners().catch(() => undefined); + void this.client.clearLeakedFollowTyping().catch(() => undefined); return new Promise((resolve) => { this.resolveExit = resolve; diff --git a/src/tui/tui-client.ts b/src/tui/tui-client.ts index 02d19f42..bc1aa14c 100644 --- a/src/tui/tui-client.ts +++ b/src/tui/tui-client.ts @@ -1457,6 +1457,53 @@ 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 { + let names: string[]; + let live: Set; + 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 { try { await this.exec('tmux', ['-L', this.socket, 'set-option', ...args]); diff --git a/test/tui/tui-client.test.ts b/test/tui/tui-client.test.ts index ec7f8634..7ebb385e 100644 --- a/test/tui/tui-client.test.ts +++ b/test/tui/tui-client.test.ts @@ -897,6 +897,53 @@ describe('TuiClient.clearLeakedAttachBanners', () => { }); }); +describe('TuiClient.clearLeakedFollowTyping', () => { + const ours = (tty: string): string => `${TUI_FOLLOW_TYPING_HOOK} ${tuiFollowTypingHook(tty)}`; + + function sweeper(hooks: Record, clients: string[]): { client: TuiClient; unset: string[] } { + const unset: string[] = []; + const exec: TuiExecFile = async (_file, args) => { + if (args.includes('list-sessions')) return { stdout: Object.keys(hooks).join('\n'), stderr: '' }; + if (args.includes('list-clients')) return { stdout: clients.join('\n'), stderr: '' }; + if (args.includes('show-hooks')) return { stdout: hooks[args[args.indexOf('-t') + 1] ?? ''] ?? '', stderr: '' }; + if (args.includes('set-hook')) unset.push(args[args.indexOf('-t') + 1] ?? ''); + return { stdout: '', stderr: '' }; + }; + return { client: new TuiClient({ baseUrl, socket: 'codeman-beta', exec }), unset }; + } + + it('removes ours for a tty with no live client, and nothing else', async () => { + const { client, unset } = sweeper( + { + // A TUI killed mid-attach (window closed, SSH dropped). + 'codeman-aaaa1111': ours('/dev/pts/7'), + // A second TUI attached right now. + 'codeman-bbbb2222': ours('/dev/pts/8'), + // The user's own hook at that index. + 'codeman-cccc3333': `${TUI_FOLLOW_TYPING_HOOK} display-message mine`, + 'codeman-dddd4444': '', + }, + ['/dev/pts/8', '/dev/pts/2'] + ); + expect(await client.clearLeakedFollowTyping(null)).toBe(1); + expect(unset).toEqual(['codeman-aaaa1111']); + }); + + it("never sweeps this terminal's own hook, which an early Enter may have armed already", async () => { + const { client, unset } = sweeper({ 'codeman-aaaa1111': ours('/dev/pts/7') }, []); + expect(await client.clearLeakedFollowTyping('/dev/pts/7')).toBe(0); + expect(unset).toEqual([]); + }); + + it('reports nothing rather than throwing when there is no tmux server', async () => { + const exec: TuiExecFile = async () => { + throw new Error('no server running on /tmp/tmux-1000/codeman-beta'); + }; + const client = new TuiClient({ baseUrl, socket: 'codeman-beta', exec }); + await expect(client.clearLeakedFollowTyping(null)).resolves.toBe(0); + }); +}); + describe('parseDetachKey', () => { // Verbatim from `tmux -L codeman list-keys -T prefix` on tmux 3.4, trimmed to // the two lines that matter. They differ only by case, which is the whole From dbf545ce8ff3ed8b12e7a9d4b269dcc28522f19f Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Tue, 24 Nov 2026 18:39:54 +0100 Subject: [PATCH 3/5] 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 --- .changeset/tui-follow-typing-client.md | 2 +- docs/architecture-invariants.md | 2 +- docs/tui.md | 17 +- src/tui/tui-app.ts | 14 +- src/tui/tui-client.ts | 245 +++++++++++++----------- test/tui/tui-client.test.ts | 252 ++++++++++++------------- test/tui/tui-follow-typing.test.ts | 113 ++++++----- 7 files changed, 344 insertions(+), 301 deletions(-) diff --git a/.changeset/tui-follow-typing-client.md b/.changeset/tui-follow-typing-client.md index 9874f42a..64e94dd4 100644 --- a/.changeset/tui-follow-typing-client.md +++ b/.changeset/tui-follow-typing-client.md @@ -2,4 +2,4 @@ 'aicodeman': patch --- -`codeman tui`: a terminal attached to a session takes the window size back when you type, paste or resize it, after a browser tab (a phone, for example) opened or resized the same session and Codeman sized the window to that tab. Until now the terminal kept showing a small pane until a detach and a fresh attach. The attach sets a `client-active` hook on the sessions it dressed that acts only for its own tmux client, and removes it on detach. Needs tmux 3.3 or newer. +`codeman tui`: while a terminal is attached, the window follows whichever client was used last, as plain tmux does. Before, a browser tab (a phone, for example) that opened or resized the same session pinned the window to the tab's size, and typing or pasting in the terminal did not take it back until a detach and a fresh attach. Now typing, pasting or resizing the terminal fills it again, and typing in the tab gives the tab the size. The attach sets two hooks and an owner option on the sessions it dressed and removes them on detach; a TUI killed mid-attach has its leftovers removed by the next `codeman tui`. Needs tmux 3.3 or newer. diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index dcab0877..3837e4f9 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -18,7 +18,7 @@ Implementation detail extracted from `CLAUDE.md` so that file stays small enough ### The prefix table on Codeman's socket holds only send-prefix -**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T
` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). The attach also sets a per-session `client-active[91]` hook (`tuiFollowTypingHook` in `src/tui/tui-client.ts`, `set-hook -t` on each session it dresses, never `-g`) that runs `set-window-option window-size latest` only when `#{client_tty}` is the TUI's terminal: a browser opening the session mid-attach makes Codeman run `resize-window`, which puts the window back on `manual` at the browser's size, and without the hook typing in the terminal never took it back. tmux fires `client-active` when a different client becomes the latest on the session, and a client resize counts (measured on tmux 3.8), so Codeman's resize of its own attach client re-arms the next keystroke. ⚠️ The hook's command carries no `-t`: tmux parses it when the hook is set, and an unquoted `#{session_name}` there starts a comment. `restore()` removes it only while it names this tty. A TUI killed mid-attach leaks it, so TUI startup runs `clearLeakedFollowTyping()` beside the banner sweep: it removes ours whose tty has no live tmux client, and never the TUI's own tty (the sweep is fire-and-forget, so an early Enter can arm that one before its client exists). Tests: `test/tui/tui-follow-typing.test.ts` (real tmux, two pty clients). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. +**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T
` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). **The attach keeps each window it dressed following the client used last** (`TUI_FOLLOW_HOOKS` in `src/tui/tui-client.ts`, `set-hook -t` per session, never `-g`). Codeman's web resize runs `resize-window` and its own attach runs `setManualWindowSize()`, and either puts the window on `manual` at the browser's size, so before this a phone opening the session mid-attach pinned the terminal to a phone-sized pane until a detach. `after-resize-window[91]` puts `latest` back after Codeman's resize: Codeman resizes its client's pty first, which makes that client the latest one, and a forced resize at an unchanged size (what a browser sends when it opens a session) leaves the terminal in front. `client-active[91]` puts `latest` back when the TUI's client becomes the latest one again (typing, pasting or resizing the terminal after another client was used, measured on tmux 3.8), which covers `setManualWindowSize()`. Both are constant commands that read the session option `@codeman-tui-follow` (the owner's tty), so hooks whose owner is gone do nothing; `restore()` and the startup sweep `clearLeakedFollowTyping()` drop the owner first, then our hooks, and only for an owner that is this tty (restore) or has no live tmux client and is not this terminal (sweep, which is fire-and-forget, so an early Enter can arm this terminal before its client exists). The size restore on detach is a `resize-window`, so the hooks go before it. ⚠️ The commands carry no `-t`: tmux parses a hook command when it is set, and an unquoted `#{session_name}` there starts a comment. Tests: `test/tui/tui-follow-typing.test.ts` (real tmux, two pty clients). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. ### Reverse-proxy base path diff --git a/docs/tui.md b/docs/tui.md index 1ad5c041..8dbb422f 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -217,14 +217,15 @@ can switch to is dressed and sized the same way, so switching is instant and lan in a pane that already fills your terminal. The window follows whoever used it last, as plain tmux does. If a browser tab (a -phone, say) opens or resizes the session while you are attached, Codeman sizes the -window to that tab, and your terminal shows a smaller pane. Type, paste or resize -your terminal and the window fills it again. The TUI does this with a -`client-active[91]` hook on each session it dressed, which only acts for this -terminal's tmux client, and it removes the hooks on detach. Typing in the browser -tab is left to Codeman's own sizing rules. tmux older than 3.3 has no -`client-active` hook, so there the pane stays at the browser's size until you -detach and attach again. +phone, say) opens or resizes the session while you are attached, the window takes +that tab's size, and your terminal shows a smaller pane. Type, paste or resize your +terminal and the window fills it again; type in the tab and the tab gets it back. +The TUI does this with two hooks on each session it dressed (`client-active[91]` +and `after-resize-window[91]`) and a session option naming your terminal +(`@codeman-tui-follow`), and removes all three on detach. A TUI that was killed +while attached (a closed window, a dropped SSH) leaves them behind, and the next +`codeman tui` removes them. tmux older than 3.3 has no `client-active` hook, so +there the pane stays at the browser's size until you detach and attach again. Detaching leaves the agent running; typing `exit` or pressing `Ctrl+D` would end it, which is the difference the bar exists to make obvious. If an agent does exit, its diff --git a/src/tui/tui-app.ts b/src/tui/tui-app.ts index 72943281..b2b5fd84 100644 --- a/src/tui/tui-app.ts +++ b/src/tui/tui-app.ts @@ -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 diff --git a/src/tui/tui-client.ts b/src/tui/tui-client.ts index bc1aa14c..7684a35b 100644 --- a/src/tui/tui-client.ts +++ b/src/tui/tui-client.ts @@ -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> = { + '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 `,}` 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 { + const found: Record = {}; + 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 { 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 { 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 { - 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 { + let names: string[]; + let live: Set; + 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 { + 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> { + 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 { + 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 { - let names: string[]; - let live: Set; - 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 { try { await this.exec('tmux', ['-L', this.socket, 'set-option', ...args]); diff --git a/test/tui/tui-client.test.ts b/test/tui/tui-client.test.ts index 7ebb385e..34ad095e 100644 --- a/test/tui/tui-client.test.ts +++ b/test/tui/tui-client.test.ts @@ -29,9 +29,9 @@ import { tuiSwitchBindingTty, tuiSwitchAttachHook, tuiSwitchGuard, - tuiFollowTypingHook, - tuiFollowTypingHookTty, - TUI_FOLLOW_TYPING_HOOK, + parseFollowHooks, + TUI_FOLLOW_HOOKS, + TUI_FOLLOW_OWNER, isTuiClientTty, ATTACH_BANNER_MARKER, parseTmuxSessionList, @@ -522,87 +522,134 @@ describe('degraded-mode tmux enumeration', () => { }); }); -describe('the follow-typing hook', () => { - function hookClient(exec: TuiExecFile): TuiClient { - return new TuiClient({ baseUrl, socket: 'codeman-beta', exec }); - } - const line = (tty: string): string => `${TUI_FOLLOW_TYPING_HOOK} ${tuiFollowTypingHook(tty)}`; - - it('reads its own tty back out of the closed form, and nothing else', () => { - expect(tuiFollowTypingHookTty(line('/dev/pts/4'))).toBe('/dev/pts/4'); - expect(tuiFollowTypingHookTty(line('/dev/ttys033'))).toBe('/dev/ttys033'); - expect(tuiFollowTypingHookTty(line('/dev/pts/41'))).toBe('/dev/pts/41'); - // The user's own hook at the same index, or at another one, is not ours. - expect(tuiFollowTypingHookTty(`${TUI_FOLLOW_TYPING_HOOK} display-message mine`)).toBeNull(); - expect(tuiFollowTypingHookTty(`client-active[0] ${tuiFollowTypingHook('/dev/pts/4')}`)).toBeNull(); - expect(tuiFollowTypingHookTty('')).toBeNull(); - }); - - it('arms with an argv array on the session, after checking the slot is free', async () => { - const calls: Array = []; - const client = hookClient(async (_file, args) => { - calls.push(args); - return { stdout: 'client-attached[90] something else\n', stderr: '' }; - }); - await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(true); - expect(calls).toEqual([ - ['-L', 'codeman-beta', 'show-hooks', '-t', 'codeman-1a2b3c4d'], - [ - '-L', - 'codeman-beta', - 'set-hook', - '-t', - 'codeman-1a2b3c4d', - 'client-active[91]', - 'if-shell -F "#{==:#{client_tty},/dev/pts/4}" "set-window-option window-size latest"', - ], - ]); - }); - - it('leaves a hook of the user at its index alone', async () => { - const calls: Array = []; - const client = hookClient(async (_file, args) => { - calls.push(args); - return { stdout: `${TUI_FOLLOW_TYPING_HOOK} display-message mine\n`, stderr: '' }; - }); - await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); - await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); - expect(calls.every((args) => args[2] === 'show-hooks')).toBe(true); - }); - - it('disarms only while the hook still names this tty', async () => { - let stored = line('/dev/pts/41'); - const calls: Array = []; - const client = hookClient(async (_file, args) => { - calls.push(args); - return { stdout: `${stored}\n`, stderr: '' }; - }); - // pts/4 is a prefix of pts/41: that hook is another TUI's. - await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); - expect(calls.map((args) => args[2])).toEqual(['show-hooks']); - - stored = line('/dev/pts/4'); - calls.length = 0; - await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); - expect(calls[1]).toEqual(['-L', 'codeman-beta', 'set-hook', '-u', '-t', 'codeman-1a2b3c4d', 'client-active[91]']); - }); - - it('refuses names and ttys it must not interpolate, and swallows a dead tmux', async () => { - const calls: Array = []; - const client = hookClient(async (_file, args) => { - calls.push(args); +describe('the follow hooks', () => { + /** + * A fake tmux holding one session's options and hooks, so arm, disarm and + * the sweep run against state rather than a script of canned answers. + */ + function fakeTmux(initial: { owner?: string; hooks?: Record; clients?: string[] } = {}) { + const state = { owner: initial.owner ?? null, hooks: { ...(initial.hooks ?? {}) } as Record }; + const writes: string[] = []; + const exec: TuiExecFile = async (_file, args) => { + const verb = args[2]; + if (verb === 'list-sessions') return { stdout: 'codeman-1a2b3c4d\n', stderr: '' }; + if (verb === 'list-clients') return { stdout: (initial.clients ?? []).join('\n'), stderr: '' }; + if (verb === 'show-options') { + return { + stdout: state.owner ? `${TUI_FOLLOW_OWNER} ${state.owner}\nstatus off\n` : 'status off\n', + stderr: '', + }; + } + if (verb === 'show-hooks') { + const lines = Object.entries(state.hooks).map(([name, command]) => `${name} ${command}`); + return { stdout: lines.join('\n'), stderr: '' }; + } + writes.push(args.slice(2).join(' ')); + if (verb === 'set-option' && args.includes('-u')) state.owner = null; + else if (verb === 'set-option') state.owner = args[args.length - 1] ?? null; + else if (verb === 'set-hook' && args.includes('-u')) delete state.hooks[args[args.length - 1] ?? '']; + else if (verb === 'set-hook') state.hooks[args[args.length - 2] ?? ''] = args[args.length - 1] ?? ''; return { stdout: '', stderr: '' }; - }); - await expect(client.armFollowTyping('other-session', '/dev/pts/4')).resolves.toBe(false); - await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4"; kill-server; "')).resolves.toBe(false); - await client.disarmFollowTyping('codeman-ssh-prod', '/dev/pts/4'); - expect(calls).toEqual([]); + }; + return { client: new TuiClient({ baseUrl, socket: 'codeman-beta', exec }), state, writes }; + } - const dead = hookClient(async () => { - throw new Error('no server running on /tmp/tmux-1000/codeman-beta'); + it('builds constant commands that read the owner option, with no -t and no tty in them', () => { + expect(Object.keys(TUI_FOLLOW_HOOKS)).toEqual(['client-active[91]', 'after-resize-window[91]']); + for (const command of Object.values(TUI_FOLLOW_HOOKS)) { + expect(command).toContain(`#{${TUI_FOLLOW_OWNER}}`); + expect(command).toContain('"set-window-option window-size latest"'); + // tmux parses a hook command when it is set: an unquoted #{...} after -t is a comment. + expect(command).not.toContain('-t '); + expect(command).not.toContain('/dev/'); + } + // client-active acts only for the owner's client. + expect(TUI_FOLLOW_HOOKS['client-active[91]']).toContain(`#{==:#{client_tty},#{${TUI_FOLLOW_OWNER}}}`); + }); + + it('tells our hooks from the user ones at the same index', () => { + const ours = Object.entries(TUI_FOLLOW_HOOKS).map(([name, command]) => `${name} ${command}`); + expect(parseFollowHooks(ours.join('\n'))).toEqual({ + 'client-active[91]': 'ours', + 'after-resize-window[91]': 'ours', + }); + expect(parseFollowHooks('client-active[91] display-message mine\nclient-active[0] x')).toEqual({ + 'client-active[91]': 'theirs', + }); + expect(parseFollowHooks('client-active\nafter-resize-window\n')).toEqual({}); + }); + + it('arms the owner before the hooks, and disarms the owner first', async () => { + const { client, state, writes } = fakeTmux(); + await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(true); + expect(writes).toEqual([ + `set-option -t codeman-1a2b3c4d ${TUI_FOLLOW_OWNER} /dev/pts/4`, + `set-hook -t codeman-1a2b3c4d client-active[91] ${TUI_FOLLOW_HOOKS['client-active[91]']}`, + `set-hook -t codeman-1a2b3c4d after-resize-window[91] ${TUI_FOLLOW_HOOKS['after-resize-window[91]']}`, + ]); + writes.length = 0; + await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); + // Owner first: from that moment both hooks are inert, even if a removal fails. + expect(writes).toEqual([ + `set-option -u -t codeman-1a2b3c4d ${TUI_FOLLOW_OWNER}`, + 'set-hook -u -t codeman-1a2b3c4d client-active[91]', + 'set-hook -u -t codeman-1a2b3c4d after-resize-window[91]', + ]); + expect(state).toEqual({ owner: null, hooks: {} }); + }); + + it('installs nothing over a hook of the user, and never removes one', async () => { + const { client, state, writes } = fakeTmux({ hooks: { 'after-resize-window[91]': 'display-message mine' } }); + await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); + expect(writes).toEqual([]); + // Even with an owner recorded (a TUI killed before restore), the user's hook stays. + state.owner = '/dev/pts/4'; + await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); + expect(state.hooks).toEqual({ 'after-resize-window[91]': 'display-message mine' }); + }); + + it('leaves the session to a second TUI that took it over', async () => { + const { client, state } = fakeTmux(); + await client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); + await client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/41'); + // pts/4 is a prefix of pts/41, and its restore must not take pts/41's hooks. + await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); + expect(state.owner).toBe('/dev/pts/41'); + expect(Object.keys(state.hooks)).toHaveLength(2); + }); + + it('sweeps an owner with no live client, and never a live one or its own', async () => { + const dead = fakeTmux({ owner: '/dev/pts/7', hooks: { ...TUI_FOLLOW_HOOKS }, clients: ['/dev/pts/2'] }); + await expect(dead.client.clearLeakedFollowTyping(null)).resolves.toBe(1); + expect(dead.state).toEqual({ owner: null, hooks: {} }); + + const live = fakeTmux({ owner: '/dev/pts/8', hooks: { ...TUI_FOLLOW_HOOKS }, clients: ['/dev/pts/8'] }); + await expect(live.client.clearLeakedFollowTyping(null)).resolves.toBe(0); + expect(live.state.owner).toBe('/dev/pts/8'); + + // An Enter pressed before the sweep finished: armed, not yet a client. + const own = fakeTmux({ owner: '/dev/pts/7', hooks: { ...TUI_FOLLOW_HOOKS } }); + await expect(own.client.clearLeakedFollowTyping('/dev/pts/7')).resolves.toBe(0); + expect(own.state.owner).toBe('/dev/pts/7'); + }); + + it('refuses names and ttys it must not pass on, and swallows a dead tmux', async () => { + const { client, writes } = fakeTmux(); + await expect(client.armFollowTyping('other-session', '/dev/pts/4')).resolves.toBe(false); + await expect(client.armFollowTyping('codeman-1a2b3c4d', '/tmp/not-a-tty')).resolves.toBe(false); + await client.disarmFollowTyping('codeman-ssh-prod', '/dev/pts/4'); + expect(writes).toEqual([]); + + const dead = new TuiClient({ + baseUrl, + socket: 'codeman-beta', + exec: async () => { + throw new Error('no server running on /tmp/tmux-1000/codeman-beta'); + }, }); await expect(dead.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); await expect(dead.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBeUndefined(); + await expect(dead.clearLeakedFollowTyping(null)).resolves.toBe(0); }); }); @@ -897,53 +944,6 @@ describe('TuiClient.clearLeakedAttachBanners', () => { }); }); -describe('TuiClient.clearLeakedFollowTyping', () => { - const ours = (tty: string): string => `${TUI_FOLLOW_TYPING_HOOK} ${tuiFollowTypingHook(tty)}`; - - function sweeper(hooks: Record, clients: string[]): { client: TuiClient; unset: string[] } { - const unset: string[] = []; - const exec: TuiExecFile = async (_file, args) => { - if (args.includes('list-sessions')) return { stdout: Object.keys(hooks).join('\n'), stderr: '' }; - if (args.includes('list-clients')) return { stdout: clients.join('\n'), stderr: '' }; - if (args.includes('show-hooks')) return { stdout: hooks[args[args.indexOf('-t') + 1] ?? ''] ?? '', stderr: '' }; - if (args.includes('set-hook')) unset.push(args[args.indexOf('-t') + 1] ?? ''); - return { stdout: '', stderr: '' }; - }; - return { client: new TuiClient({ baseUrl, socket: 'codeman-beta', exec }), unset }; - } - - it('removes ours for a tty with no live client, and nothing else', async () => { - const { client, unset } = sweeper( - { - // A TUI killed mid-attach (window closed, SSH dropped). - 'codeman-aaaa1111': ours('/dev/pts/7'), - // A second TUI attached right now. - 'codeman-bbbb2222': ours('/dev/pts/8'), - // The user's own hook at that index. - 'codeman-cccc3333': `${TUI_FOLLOW_TYPING_HOOK} display-message mine`, - 'codeman-dddd4444': '', - }, - ['/dev/pts/8', '/dev/pts/2'] - ); - expect(await client.clearLeakedFollowTyping(null)).toBe(1); - expect(unset).toEqual(['codeman-aaaa1111']); - }); - - it("never sweeps this terminal's own hook, which an early Enter may have armed already", async () => { - const { client, unset } = sweeper({ 'codeman-aaaa1111': ours('/dev/pts/7') }, []); - expect(await client.clearLeakedFollowTyping('/dev/pts/7')).toBe(0); - expect(unset).toEqual([]); - }); - - it('reports nothing rather than throwing when there is no tmux server', async () => { - const exec: TuiExecFile = async () => { - throw new Error('no server running on /tmp/tmux-1000/codeman-beta'); - }; - const client = new TuiClient({ baseUrl, socket: 'codeman-beta', exec }); - await expect(client.clearLeakedFollowTyping(null)).resolves.toBe(0); - }); -}); - describe('parseDetachKey', () => { // Verbatim from `tmux -L codeman list-keys -T prefix` on tmux 3.4, trimmed to // the two lines that matter. They differ only by case, which is the whole diff --git a/test/tui/tui-follow-typing.test.ts b/test/tui/tui-follow-typing.test.ts index 45655eee..eaa04bde 100644 --- a/test/tui/tui-follow-typing.test.ts +++ b/test/tui/tui-follow-typing.test.ts @@ -5,8 +5,9 @@ * Against a real tmux on a private socket (never Codeman's). Two attach clients * on ptys: one is the TUI's terminal, the other is what a browser tab is (one * `tmux attach-session` per session, sized by Codeman). The browser's resize is - * what `TmuxManager.resizeWindow()` runs: `resize-window -x -y`, which puts the - * window on `manual`. + * what `Session.resize()` does: resize its client's pty, then + * `TmuxManager.resizeWindow()`'s `resize-window -x -y`, which puts the window + * on `manual`. * * Port: N/A (no server) */ @@ -14,7 +15,7 @@ import { afterAll, describe, expect, it } from 'vitest'; import { execFileSync, execSync } from 'node:child_process'; import { rmSync } from 'node:fs'; import * as pty from 'node-pty'; -import { TUI_FOLLOW_TYPING_HOOK, TuiClient } from '../../src/tui/tui-client.js'; +import { TUI_FOLLOW_HOOKS, TUI_FOLLOW_OWNER, TuiClient } from '../../src/tui/tui-client.js'; const hasTmux = (() => { try { @@ -106,7 +107,7 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => { if (socketPath.endsWith(`/${socket}`)) rmSync(socketPath, { force: true }); }); - it('gives the window back to the TUI terminal on its next keystroke, and only to that terminal', async () => { + it('follows whichever client was used last, the TUI terminal included', async () => { run(['new-session', '-d', '-s', alpha, '-x', '120', '-y', '40', 'cat']); run(['set-option', '-g', 'status', 'off']); run(['set-window-option', '-t', alpha, 'window-size', 'manual']); @@ -116,72 +117,92 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => { expect(await waitFor(() => (tuiTty = ttyOf(tui)) !== '')).toBe(true); expect(await client.followAttachingClient(alpha)).toBe(true); expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true); - expect(hooks()).toContain(TUI_FOLLOW_TYPING_HOOK); - // The closed form, which disarm and re-arm match on. - expect(hooks()).toContain(`#{client_tty},${tuiTty}}`); - // Set on the session, not the server: no other session gets it. - expect(run(['show-hooks', '-g'])).not.toContain(TUI_FOLLOW_TYPING_HOOK); + for (const name of Object.keys(TUI_FOLLOW_HOOKS)) expect(hooks()).toContain(name); + expect(run(['show-options', '-t', alpha])).toContain(`${TUI_FOLLOW_OWNER} ${tuiTty}`); + // Set on the session, not the server: no other session gets them. + expect(run(['show-hooks', '-g'])).not.toContain('[91]'); expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true); - // A phone opens the session: its client attaches and Codeman pins the window. + // A phone opens the session: Codeman's client attaches and is resized to it. const browser = attach(60, 30); expect(await waitFor(() => ttyOf(browser) !== '')).toBe(true); - run(['resize-window', '-t', alpha, '-x', '60', '-y', '30']); - expect(windowSize()).toBe('60x30 manual'); + await browserResize(browser, 61, 30); + expect(windowSize()).toBe('61x30 latest'); - // Typing in the browser tab is Codeman's business, not the hook's. - browser.write('b'); - await new Promise((resolve) => setTimeout(resolve, 300)); - expect(windowSize()).toBe('60x30 manual'); - - // Typing in the TUI terminal takes it back. This is the bug: without the - // hook the window stayed 60x30 manual here for the rest of the attach. + // The bug: without the hooks the window stayed 61x30 manual here, and + // typing in the terminal changed nothing for the rest of the attach. tui.write('a'); expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true); - // Resizing the TUI terminal is using it too: tmux makes the resized client - // the latest one, so the hook fires without a keystroke (measured on 3.8). - await browserResize(browser, 62, 30); - expect(windowSize()).toBe('62x30 manual'); - tui.resize(150, 45); - expect(await waitFor(() => windowSize() === '150x45 latest')).toBe(true); + // A browser opening a session sends a FORCED resize at its current size. + // Its pty does not change, so tmux keeps the terminal as the latest client + // and the window stays where the user is typing. + await browserResize(browser, 61, 30); + expect(windowSize()).toBe('200x50 latest'); - // The browser resizing its client makes THAT client the latest one, so - // the TUI's next keystroke is a change of client and fires the hook again. - await browserResize(browser, 62, 31); - expect(windowSize()).toBe('62x31 manual'); + // Typing in the browser tab gives the window to the tab... + browser.write('b'); + expect(await waitFor(() => windowSize() === '61x30 latest')).toBe(true); + // ...and typing in the terminal takes it back. tui.write('a'); + expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true); + + // Codeman's own attach (`setManualWindowSize()`) sets manual with no resize. + browser.write('b'); + expect(await waitFor(() => windowSize() === '61x30 latest')).toBe(true); + run(['set-window-option', '-t', alpha, 'window-size', 'manual']); + tui.write('a'); + expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true); + + // Resizing the terminal is using it too. + browser.write('b'); + expect(await waitFor(() => windowSize() === '61x30 latest')).toBe(true); + tui.resize(150, 45); expect(await waitFor(() => windowSize() === '150x45 latest')).toBe(true); }); - it('disarms only its own hook, and never replaces one of the user', async () => { - const tuiTty = ttyOf(clients[0]); + it('stops when disarmed, leaves a second TUI and the user alone', async () => { + const [tui, browser] = clients; + const tuiTty = ttyOf(tui); expect(tuiTty).not.toBe(''); - // Another tty's restore leaves this attach's hook alone (pts/4 vs pts/41 included). + // Another tty's restore leaves this attach armed (pts/4 vs pts/41 included). await client.disarmFollowTyping(alpha, `${tuiTty}1`); - expect(hooks()).toContain(TUI_FOLLOW_TYPING_HOOK); + expect(run(['show-options', '-t', alpha])).toContain(TUI_FOLLOW_OWNER); await client.disarmFollowTyping(alpha, tuiTty); - expect(hooks()).not.toContain(TUI_FOLLOW_TYPING_HOOK); - // Disarmed means the next keystroke changes nothing. - await browserResize(clients[1], 64, 30); - clients[0].write('a'); + expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER); + expect(hooks()).not.toContain('[91]'); + // Disarmed: Codeman's resize pins the window again, and typing changes nothing. + await browserResize(browser, 64, 30); + expect(windowSize()).toBe('64x30 manual'); + tui.write('a'); await new Promise((resolve) => setTimeout(resolve, 300)); expect(windowSize()).toBe('64x30 manual'); - // A hook of the user's own at that index is never overwritten. - run(['set-hook', '-t', alpha, TUI_FOLLOW_TYPING_HOOK, 'display-message mine']); + // Hooks left without an owner (a removal that failed) do nothing. + for (const [name, command] of Object.entries(TUI_FOLLOW_HOOKS)) run(['set-hook', '-t', alpha, name, command]); + await browserResize(browser, 65, 30); + tui.write('a'); + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(windowSize()).toBe('65x30 manual'); + for (const name of Object.keys(TUI_FOLLOW_HOOKS)) run(['set-hook', '-u', '-t', alpha, name]); + + // A hook of the user's own at either index is never overwritten. + run(['set-hook', '-t', alpha, 'after-resize-window[91]', 'display-message mine']); expect(await client.armFollowTyping(alpha, tuiTty)).toBe(false); expect(hooks()).toContain('display-message mine'); - await client.disarmFollowTyping(alpha, tuiTty); - expect(hooks()).toContain('display-message mine'); - run(['set-hook', '-u', '-t', alpha, TUI_FOLLOW_TYPING_HOOK]); + expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER); + run(['set-hook', '-u', '-t', alpha, 'after-resize-window[91]']); - // One of ours for a stale tty (a TUI killed before its restore) is taken over. - expect(await client.armFollowTyping(alpha, `${tuiTty}1`)).toBe(true); + // A leaked owner (a TUI killed mid-attach) is swept once its client is gone. + expect(await client.armFollowTyping(alpha, '/dev/ttys999')).toBe(true); + expect(await client.clearLeakedFollowTyping(null)).toBe(1); + expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER); + expect(hooks()).not.toContain('[91]'); + // A live one is not. expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true); - expect(hooks()).toContain(`#{client_tty},${tuiTty}}`); - expect(hooks()).not.toContain(`#{client_tty},${tuiTty}1}`); + expect(await client.clearLeakedFollowTyping(null)).toBe(0); + expect(run(['show-options', '-t', alpha])).toContain(`${TUI_FOLLOW_OWNER} ${tuiTty}`); }); }); From 9753ca9d703bc2a95ce2a25cc0b416b6ebb484fe Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Tue, 24 Nov 2026 18:42:21 +0100 Subject: [PATCH 4/5] fix(tui): undo a half-done follow arm armFollowTyping() set the owner option, then a hook. On tmux before 3.3 there is no client-active hook, so the first set-hook failed and the arm answered false with the owner still set; restore() disarms only what armed, so it stayed on the session. A failed arm now drops the owner and any of our hooks it already set. Co-Authored-By: Claude Opus 5.5 --- src/tui/tui-client.ts | 14 ++++++++++++++ test/tui/tui-client.test.ts | 14 +++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/tui/tui-client.ts b/src/tui/tui-client.ts index 7684a35b..defbabd9 100644 --- a/src/tui/tui-client.ts +++ b/src/tui/tui-client.ts @@ -1240,18 +1240,32 @@ export class TuiClient { * 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. + * + * ⚠️ A half-done arm is undone before answering false, because `restore()` + * only disarms what armed. tmux before 3.3 has no `client-active` hook, so + * there the owner is set and the first hook is refused; left alone, the + * owner would stay on the session for good. */ async armFollowTyping(muxName: string, clientTty: string): Promise { if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return false; try { const hooks = await this.readFollowHooks(muxName); if (Object.values(hooks).includes('theirs')) return false; + } catch { + return false; + } + try { 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 { + try { + await this.dropFollowTyping(muxName); + } catch { + /* the session is gone, or tmux is: nothing is left to undo then */ + } return false; } } diff --git a/test/tui/tui-client.test.ts b/test/tui/tui-client.test.ts index 34ad095e..5e891106 100644 --- a/test/tui/tui-client.test.ts +++ b/test/tui/tui-client.test.ts @@ -527,7 +527,9 @@ describe('the follow hooks', () => { * A fake tmux holding one session's options and hooks, so arm, disarm and * the sweep run against state rather than a script of canned answers. */ - function fakeTmux(initial: { owner?: string; hooks?: Record; clients?: string[] } = {}) { + function fakeTmux( + initial: { owner?: string; hooks?: Record; clients?: string[]; refuseHook?: string } = {} + ) { const state = { owner: initial.owner ?? null, hooks: { ...(initial.hooks ?? {}) } as Record }; const writes: string[] = []; const exec: TuiExecFile = async (_file, args) => { @@ -544,6 +546,9 @@ describe('the follow hooks', () => { const lines = Object.entries(state.hooks).map(([name, command]) => `${name} ${command}`); return { stdout: lines.join('\n'), stderr: '' }; } + if (verb === 'set-hook' && !args.includes('-u') && args.includes(initial.refuseHook ?? '\0')) { + throw new Error(`invalid option: ${initial.refuseHook}`); + } writes.push(args.slice(2).join(' ')); if (verb === 'set-option' && args.includes('-u')) state.owner = null; else if (verb === 'set-option') state.owner = args[args.length - 1] ?? null; @@ -598,6 +603,13 @@ describe('the follow hooks', () => { expect(state).toEqual({ owner: null, hooks: {} }); }); + it('undoes a half-done arm, as on a tmux without client-active (before 3.3)', async () => { + const { client, state } = fakeTmux({ refuseHook: 'client-active[91]' }); + await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); + // restore() disarms only what armed, so nothing may be left behind here. + expect(state).toEqual({ owner: null, hooks: {} }); + }); + it('installs nothing over a hook of the user, and never removes one', async () => { const { client, state, writes } = fakeTmux({ hooks: { 'after-resize-window[91]': 'display-message mine' } }); await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); From 70ee1312d414f436a0c10946b684595a35e6e80d Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Thu, 26 Nov 2026 10:46:57 +0100 Subject: [PATCH 5/5] fix(tui): Redraw wins, leaks are told by process, detach unsets the whole hook array Review follow-up on the follow-typing attach. - Redraw (and every forced resize at an unchanged size) handed the window back to the terminal: an unchanged pty sends tmux no SIGWINCH, so the terminal stayed the latest client and the after-resize-window hook undid the resize-window. Session.resize() now nudges the pty one row first (FORCED_RESIZE_NUDGE_MS), then applies the size, so tmux counts the tab as the client used last; the second move bumps the guarded geometry revision too. Under manual with no attach the agent sees no change. - With the nudge, client-active[91] alone covers every case, so the after-resize-window hook is gone. It kept latest through every browser resize and cost the agent three height changes per resize; now the first resize after the terminal was used costs two and later ones one. The cost is stated next to the hook. - The leak sweep matched owners by tty, and Linux hands the next terminal the pty that just closed, so the common leak was never swept. The arm now records the TUI's pid (@codeman-tui-follow-pid), and the sweep keeps only sessions this process armed (a Set filled before the first write) or whose pid is another live process. One list-sessions call reads every owner. It also runs before each attach dresses its sessions, so `codeman tui ` gets it and a leaked hook cannot undo presizeWindow(). - `set-hook -u` on our index left an empty session-level array, which hides the user's global hook on that event. Disarm unsets the whole event when ours is its only entry, and arm refuses while the user has a global client-active hook. - Arm and disarm are one tmux call to read and one to write (`;` lists). - Docs: the "forced resize when a browser opens a session" wording was wrong (selectSession sends no force; only Redraw, a closing pop-out and the split pane do), fixed in tui-client.ts, docs/tui.md and the invariants, whose paragraph now stands on its own. Co-Authored-By: Claude Opus 5.5 --- .changeset/tui-follow-typing-client.md | 2 +- docs/architecture-invariants.md | 4 +- docs/tui.md | 86 +++---- src/session.ts | 39 +++- src/tui/tui-app.ts | 15 +- src/tui/tui-client.ts | 285 +++++++++++++++++------- test/session-resize-arbitration.test.ts | 51 ++++- test/tui/tui-app.test.ts | 8 + test/tui/tui-client.test.ts | 225 ++++++++++++------- test/tui/tui-follow-typing.test.ts | 79 +++++-- 10 files changed, 569 insertions(+), 225 deletions(-) diff --git a/.changeset/tui-follow-typing-client.md b/.changeset/tui-follow-typing-client.md index 64e94dd4..9b1c7a11 100644 --- a/.changeset/tui-follow-typing-client.md +++ b/.changeset/tui-follow-typing-client.md @@ -2,4 +2,4 @@ 'aicodeman': patch --- -`codeman tui`: while a terminal is attached, the window follows whichever client was used last, as plain tmux does. Before, a browser tab (a phone, for example) that opened or resized the same session pinned the window to the tab's size, and typing or pasting in the terminal did not take it back until a detach and a fresh attach. Now typing, pasting or resizing the terminal fills it again, and typing in the tab gives the tab the size. The attach sets two hooks and an owner option on the sessions it dressed and removes them on detach; a TUI killed mid-attach has its leftovers removed by the next `codeman tui`. Needs tmux 3.3 or newer. +`codeman tui`: while a terminal is attached, the window follows whichever client was used last, as plain tmux does. Before, a browser tab (a phone, for example) that opened or resized the same session pinned the window to the tab's size, and typing or pasting in the terminal did not take it back until a detach and a fresh attach. Now typing, pasting or resizing the terminal fills it again, and typing in the tab, or its Redraw, gives the tab the size. The attach sets one hook and two owner options on the sessions it dressed and removes them on detach; a TUI killed mid-attach has its leftovers removed by the next `codeman tui`. A forced resize at an unchanged size (Redraw) now nudges the attach client's pty by one row first, so tmux counts that tab as the client used last. Needs tmux 3.3 or newer. diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 3837e4f9..1f59d872 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -18,7 +18,9 @@ Implementation detail extracted from `CLAUDE.md` so that file stays small enough ### The prefix table on Codeman's socket holds only send-prefix -**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T
` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). **The attach keeps each window it dressed following the client used last** (`TUI_FOLLOW_HOOKS` in `src/tui/tui-client.ts`, `set-hook -t` per session, never `-g`). Codeman's web resize runs `resize-window` and its own attach runs `setManualWindowSize()`, and either puts the window on `manual` at the browser's size, so before this a phone opening the session mid-attach pinned the terminal to a phone-sized pane until a detach. `after-resize-window[91]` puts `latest` back after Codeman's resize: Codeman resizes its client's pty first, which makes that client the latest one, and a forced resize at an unchanged size (what a browser sends when it opens a session) leaves the terminal in front. `client-active[91]` puts `latest` back when the TUI's client becomes the latest one again (typing, pasting or resizing the terminal after another client was used, measured on tmux 3.8), which covers `setManualWindowSize()`. Both are constant commands that read the session option `@codeman-tui-follow` (the owner's tty), so hooks whose owner is gone do nothing; `restore()` and the startup sweep `clearLeakedFollowTyping()` drop the owner first, then our hooks, and only for an owner that is this tty (restore) or has no live tmux client and is not this terminal (sweep, which is fire-and-forget, so an early Enter can arm this terminal before its client exists). The size restore on detach is a `resize-window`, so the hooks go before it. ⚠️ The commands carry no `-t`: tmux parses a hook command when it is set, and an unquoted `#{session_name}` there starts a comment. Tests: `test/tui/tui-follow-typing.test.ts` (real tmux, two pty clients). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. +**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T
` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. + +**The attach keeps each window it dressed following the client used last** (`TUI_FOLLOW_HOOKS` in `src/tui/tui-client.ts`, `set-hook -t` per session, never `-g`). Codeman's web resize runs `resize-window` and its own attach runs `setManualWindowSize()`, and either puts the window on `manual` at the browser's size, so before this a phone opening the session mid-attach pinned the terminal to a phone-sized pane until a detach. One hook, `client-active[91]`, puts `latest` back when the TUI's client becomes the latest one again (typing, pasting or resizing the terminal after another client was used, measured on tmux 3.8). A browser resize makes the tab's client the latest one, because `Session.resize()` resizes that client's pty before tmux sees the `resize-window`. ⚠️ A forced resize at an unchanged size (Redraw, a closing pop-out window, the split pane; a browser opening a session sends none, since `selectSession` resizes without `force` and the server drops an unchanged size) would not change the pty, so tmux would keep the terminal as the latest client and its next key would undo the user's Redraw. `Session.resize()` nudges the pty one row first (`FORCED_RESIZE_NUDGE_MS`), then applies the real size: under `manual` with no attach the window ignores the client's pty, so the agent sees no change. Cost: the first browser resize after the terminal was used changes the agent's height twice (the window is on `latest`, so the tab's pty moves it, then `resize-window` does), where master changes it once; later resizes from the same tab cost one. Height changes cost Claude's inline renderer transcript lines (#672), which is why there is no second hook on `after-resize-window`: keeping `latest` through every browser resize cost three. The hook is a constant command that reads the session option `@codeman-tui-follow` (the owner's tty), so a hook whose owner is gone does nothing. `@codeman-tui-follow-pid` records the TUI process, because a tty proves nothing: Linux hands the next terminal the pty that just closed, and a browser tab's attach client can land on it. `restore()` drops the owner first, then the hook, only while the owner is this tty, and before the window sizes are put back. `clearLeakedFollowTyping()` drops every owner this process did not arm whose recorded pid is not another live process; it runs at TUI startup and again before each attach dresses its sessions, since a leaked hook undoes `presizeWindow()` and `codeman tui ` has no dashboard. ⚠️ When ours is the only entry of the event, the whole session array is unset: `set-hook -u` on one index leaves an empty session-level array, which keeps hiding a global hook on that event (the same trap as `status-format[0]`). For the same reason nothing is armed while the user has a global `client-active` hook. ⚠️ The command carries no `-t`: tmux parses a hook command when it is set, and an unquoted `#{session_name}` there starts a comment. Tests: `test/tui/tui-follow-typing.test.ts` (real tmux, two pty clients), `test/session-resize-arbitration.test.ts` (the nudge). ### Reverse-proxy base path diff --git a/docs/tui.md b/docs/tui.md index 8dbb422f..8eea3ed4 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -7,7 +7,7 @@ tmux pane with one keystroke. It is **additional, not a replacement**: the web UI stays the primary surface and gets every feature first. The TUI exists for the terminal workflow (SSH, Termius, -a tmux window you keep open all day), and it is a *client* of the running server, +a tmux window you keep open all day), and it is a _client_ of the running server, so the two surfaces can never disagree about what a session is doing. It is also not a multiplexer: tmux still owns every pane, and attaching hands the terminal to tmux rather than proxying bytes. @@ -27,11 +27,11 @@ Neither sets up a screen, so both are as quick as the one API call they make, an What it needs: -| Needs | What you get | -| --- | --- | +| Needs | What you get | +| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Full features** | A running Codeman server (states, approvals, preview, prompts, search, digest). The TUI finds it the way `codeman attach` does: `CODEMAN_API_URL`, else loopback on `CODEMAN_PORT` for this `CODEMAN_INSTANCE`. The self-signed certificate an `--https` install generates is accepted, as it is everywhere else in the CLI. | -| **Server down** | It still starts, in **degraded mode**: sessions are enumerated straight from `tmux -L codeman` plus a read-only peek at `state.json`, and attach is the only verb. See [Troubleshooting](#troubleshooting). | -| **A terminal** | `codeman tui` refuses to run when stdin/stdout are not a TTY, and says to use `--list` instead. A cron job or a pipe therefore fails loudly rather than emitting escape codes into a log. | +| **Server down** | It still starts, in **degraded mode**: sessions are enumerated straight from `tmux -L codeman` plus a read-only peek at `state.json`, and attach is the only verb. See [Troubleshooting](#troubleshooting). | +| **A terminal** | `codeman tui` refuses to run when stdin/stdout are not a TTY, and says to use `--list` instead. A cron job or a pipe therefore fails loudly rather than emitting escape codes into a log. | ## What it looks like @@ -98,13 +98,13 @@ before the terminal check, so a script can tell them apart without a TTY. Groups are always in this order, and a session is in exactly one of them: -| Group | Glyph | Means | Comes from | -| --- | --- | --- | --- | -| **NEEDS YOU** | `⚠` | A permission or question dialog is blocking the agent | The approvals inbox (`permission_prompt` hooks, with the on-screen options parsed; for Codex, a dialog read off its screen) | -| | `✋` | Waiting for your next instruction, or errored | `idle_prompt`, or an errored session (equally something only a human clears) | -| **WORKING** | `✻` animating | A turn is running | The same working classification the web dashboard uses | -| **IDLE** | `○` | Live, but sitting there | | -| **RECENT** | `✔` | A past session from the unified list | History rows, no live pane | +| Group | Glyph | Means | Comes from | +| ------------- | ------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| **NEEDS YOU** | `⚠` | A permission or question dialog is blocking the agent | The approvals inbox (`permission_prompt` hooks, with the on-screen options parsed; for Codex, a dialog read off its screen) | +| | `✋` | Waiting for your next instruction, or errored | `idle_prompt`, or an errored session (equally something only a human clears) | +| **WORKING** | `✻` animating | A turn is running | The same working classification the web dashboard uses | +| **IDLE** | `○` | Live, but sitting there | | +| **RECENT** | `✔` | A past session from the unified list | History rows, no live pane | Ordering inside a group is "the one that has waited longest, first": blocked sessions sort by how long the dialog has been up, working sessions by when their @@ -121,20 +121,20 @@ same item announced twice does not ring twice. ## Keymap -| Key | Does | -| --- | --- | -| `↑` `↓` or `j` `k` | Move the cursor. PageUp/PageDown jump five rows. | -| `Enter` | Attach to the selected session (see [Attaching](#attaching)) | -| `1`-`9` | Jump to that row and attach. When a dialog is on screen, a digit answers it instead (see below). | -| `y` | Approve the selected session's dialog | -| `n` | Deny it, or **start a new session** when there is no dialog | -| `p` | Send one line to the selected session without attaching | -| `x` | Kill the selected session; `y` confirms, any other key cancels | -| `/` | Search sessions, events and files | -| `g` | Away digest: what happened while you were gone | -| `?` | Help overlay | -| `Esc` | Close whatever overlay is open | -| `q` or `Ctrl+C` | Quit, restoring the screen you started with | +| Key | Does | +| ------------------ | ------------------------------------------------------------------------------------------------ | +| `↑` `↓` or `j` `k` | Move the cursor. PageUp/PageDown jump five rows. | +| `Enter` | Attach to the selected session (see [Attaching](#attaching)) | +| `1`-`9` | Jump to that row and attach. When a dialog is on screen, a digit answers it instead (see below). | +| `y` | Approve the selected session's dialog | +| `n` | Deny it, or **start a new session** when there is no dialog | +| `p` | Send one line to the selected session without attaching | +| `x` | Kill the selected session; `y` confirms, any other key cancels | +| `/` | Search sessions, events and files | +| `g` | Away digest: what happened while you were gone | +| `?` | Help overlay | +| `Esc` | Close whatever overlay is open | +| `q` or `Ctrl+C` | Quit, restoring the screen you started with | Inside the `p` composer and the `/` query: `←` `→` `Home` `End` `Delete` `Backspace` plus `Ctrl+A` / `Ctrl+E` / `Ctrl+U` / `Ctrl+W`, `Enter` to send or open, @@ -217,15 +217,19 @@ can switch to is dressed and sized the same way, so switching is instant and lan in a pane that already fills your terminal. The window follows whoever used it last, as plain tmux does. If a browser tab (a -phone, say) opens or resizes the session while you are attached, the window takes -that tab's size, and your terminal shows a smaller pane. Type, paste or resize your -terminal and the window fills it again; type in the tab and the tab gets it back. -The TUI does this with two hooks on each session it dressed (`client-active[91]` -and `after-resize-window[91]`) and a session option naming your terminal -(`@codeman-tui-follow`), and removes all three on detach. A TUI that was killed -while attached (a closed window, a dropped SSH) leaves them behind, and the next -`codeman tui` removes them. tmux older than 3.3 has no `client-active` hook, so -there the pane stays at the browser's size until you detach and attach again. +phone, say) resizes the session while you are attached, the window takes that tab's +size, and your terminal shows a smaller pane. Type, paste or resize your terminal and +the window fills it again; type in the tab, or press its Redraw, and the tab gets it +back. A tab that only opens the session at the size it already had changes nothing. +The TUI does this with one hook on each session it dressed (`client-active[91]`) and +two session options naming your terminal and the TUI process (`@codeman-tui-follow`, +`@codeman-tui-follow-pid`), and removes all three on detach. It sets nothing on a +session where you have a hook of your own at that index, or anywhere while you have +a global `client-active` hook, which a session hook would hide. A TUI that was killed +while attached (a closed window, a dropped SSH) leaves them behind; the next +`codeman tui`, including `codeman tui `, removes them before it attaches. tmux +older than 3.3 has no `client-active` hook, so there the pane stays at the browser's +size until you detach and attach again. Detaching leaves the agent running; typing `exit` or pressing `Ctrl+D` would end it, which is the difference the bar exists to make obvious. If an agent does exit, its @@ -234,11 +238,11 @@ resume the conversation in a fresh one instead. Three cases: -| Where you are | What happens | -| --- | --- | -| Not in tmux | `tmux -L codeman attach-session` | -| Already in tmux on Codeman's socket | `switch-client`, so you do not nest | -| In tmux on a **different** socket | Refused, with an explanation: detach from that tmux first, then run `codeman tui` again | +| Where you are | What happens | +| ----------------------------------- | --------------------------------------------------------------------------------------- | +| Not in tmux | `tmux -L codeman attach-session` | +| Already in tmux on Codeman's socket | `switch-client`, so you do not nest | +| In tmux on a **different** socket | Refused, with an explanation: detach from that tmux first, then run `codeman tui` again | A direct-PTY session has no pane to attach to, and says so. @@ -278,7 +282,7 @@ server. Start the server (`codeman web -d`, or `systemctl --user start codeman-w and the banner clears on its own: the TUI keeps re-probing. **It found the wrong server, or none.** Discovery is instance-scoped. A beta -instance (`CODEMAN_INSTANCE=beta`) has its own data dir *and* its own tmux socket, +instance (`CODEMAN_INSTANCE=beta`) has its own data dir _and_ its own tmux socket, so its TUI sees only its own sessions. Set `CODEMAN_PORT` or `CODEMAN_API_URL` explicitly when you run more than one. diff --git a/src/session.ts b/src/session.ts index 27e9f9f2..ae3dab75 100644 --- a/src/session.ts +++ b/src/session.ts @@ -5696,13 +5696,46 @@ export class Session extends EventEmitter { this._guardedGeometryRevision++; this._ptyCols = cols; this._ptyRows = rows; - if (!IS_TEST_MODE && this._mux && this._muxSession) { - this._mux.resizeWindow?.(this._muxSession.muxName, cols, rows); + // ⚠️ A forced resize at an unchanged size is a device asking for the pane + // back (the Redraw button, a closing pop-out window, the split pane). An + // unchanged pty sends tmux no SIGWINCH, so tmux never counts this client + // as the one used last, and while a `codeman tui` attach keeps the window + // on `latest`, its follow hook (TUI_FOLLOW_HOOKS) hands the window back + // to that terminal at its next key. A one-row nudge first makes this + // client the latest one, as a real resize does. Under `manual` with no + // attach the window ignores the client's pty, so the agent sees nothing. + if (!dimsChanged && rows > 1) { + this.nudgeThenResize(cols, rows); + return; } - this.ptyProcess.resize(cols, rows); + this.applyResize(cols, rows); } } + /** How long tmux gets to read the nudged size before the real one. */ + static readonly FORCED_RESIZE_NUDGE_MS = 60; + + private applyResize(cols: number, rows: number): void { + if (!IS_TEST_MODE && this._mux && this._muxSession) { + this._mux.resizeWindow?.(this._muxSession.muxName, cols, rows); + } + this.ptyProcess?.resize(cols, rows); + } + + private nudgeThenResize(cols: number, rows: number): void { + const revision = this._guardedGeometryRevision; + this.ptyProcess?.resize(cols, rows - 1); + const timer = setTimeout(() => { + // A newer resize won: it set its own size, so this one has nothing left to do. + if (revision !== this._guardedGeometryRevision || !this.ptyProcess) return; + // The pane moves a second time, so guarded input read between the two + // must see a new revision too. + this._guardedGeometryRevision++; + this.applyResize(cols, rows); + }, Session.FORCED_RESIZE_NUDGE_MS); + timer.unref?.(); + } + // Legacy method for compatibility with session-manager async start(): Promise { this._status = 'idle'; diff --git a/src/tui/tui-app.ts b/src/tui/tui-app.ts index b2b5fd84..90735c34 100644 --- a/src/tui/tui-app.ts +++ b/src/tui/tui-app.ts @@ -643,6 +643,10 @@ export async function beginAttachHandoff( for (const tab of tabs.slice(0, 9)) { if (tab.muxName && !targets.has(tab.muxName)) targets.set(tab.muxName, tab.label); } + // A follow hook a killed TUI left behind would undo the presize below, so + // leaks go first. The dashboard also sweeps at startup; this covers + // `codeman tui `, which has no dashboard. + await client.clearLeakedFollowTyping().catch(() => 0); for (const [target, targetLabel] of targets) { const snapshot = await client.readSessionOptions(target, Object.keys(banner)); if (snapshot) dressed.push({ muxName: target, options: snapshot }); @@ -665,9 +669,9 @@ export async function beginAttachHandoff( // 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 - // 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 + // follow hook (TUI_FOLLOW_HOOKS) puts `latest` back when this terminal is + // used again, so the window follows whichever client was used last. It + // needs the tty to name its 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); } @@ -687,9 +691,8 @@ 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 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. + // The follow hook before the size, so nothing of this attach acts on + // the window once the restore below has re-pinned 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 diff --git a/src/tui/tui-client.ts b/src/tui/tui-client.ts index defbabd9..cc07ec56 100644 --- a/src/tui/tui-client.ts +++ b/src/tui/tui-client.ts @@ -509,62 +509,111 @@ export function tuiSwitchAttachHook(tty: string): string { /** * 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 + * window size of this session. The follow hook below reads 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. + * Session option holding the pid of the `codeman tui` process that set + * `TUI_FOLLOW_OWNER`. The startup sweep reads it to tell a leak from a live + * attach. A tty cannot do that: Linux hands out the lowest free pty, so a new + * terminal (or a browser tab's attach client) usually gets the number of the + * one that just closed. + */ +export const TUI_FOLLOW_PID = '@codeman-tui-follow-pid'; + +/** The event `TUI_FOLLOW_HOOKS` hooks, without its index. */ +const FOLLOW_HOOK_EVENT = 'client-active'; + +/** + * The session hook that keeps a window following the attach's terminal, the + * way plain tmux follows whichever client was used last. * - * Why they are needed: the attach sets `window-size latest`, but Codeman's web + * Why it is 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 a detach and a fresh attach. * - * - `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. + * `client-active[91]` puts `latest` back when the TUI's own client becomes the + * latest one again: typing, pasting or resizing the terminal after another + * client was used (measured on tmux 3.8). A browser resize makes the tab's + * client the latest one, because Codeman resizes that client's pty first. A + * forced resize at an unchanged size (the browser's Redraw, a closing pop-out + * window, the split pane) would not, so `Session.resize()` nudges the pty + * there; see its comment. The window then stays on `manual` at the browser's + * size until the terminal is used again. * - * Indexed so they do not replace a user's own hooks, next to the switch + * Cost: the first browser resize after the terminal was used changes the + * agent's height twice where master changes it once. The window is on + * `latest` then, so the tab's pty resize moves it (one row short, for the + * attach's status bar), and `resize-window` moves it again. Later resizes + * from the same tab find the window on `manual` and cost one change, as + * without an attach. Height changes cost Claude's inline renderer transcript + * lines (#672). A second hook on `after-resize-window` used to keep the + * window on `latest` through every browser resize, which cost three. + * + * Indexed so it does not replace a user's own hook, 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 + * ⚠️ Constant string: the tty is read from `TUI_FOLLOW_OWNER` when the 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_HOOKS: Readonly> = { - '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"`, + [`${FOLLOW_HOOK_EVENT}[91]`]: `if-shell -F "#{==:#{client_tty},#{${TUI_FOLLOW_OWNER}}}" "set-window-option window-size latest"`, }; +/** What `show-hooks` lists for one follow hook. */ +export interface FollowHookState { + /** Our index: `ours`, `theirs` (a hook of the user's), or absent. */ + slot?: 'ours' | 'theirs'; + /** Entries at any other index of the same event. */ + others: number; +} + /** - * 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. + * For each follow hook name, what a `show-hooks` listing holds for its event: + * our index and how many other entries there are. */ -export function parseFollowHooks(stdout: string): Record { - const found: Record = {}; +export function parseFollowHooks(stdout: string): Record { + const found: Record = {}; + for (const name of Object.keys(TUI_FOLLOW_HOOKS)) found[name] = { others: 0 }; 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'; + const event = name.slice(0, name.indexOf('[')); + if (text.startsWith(`${name} `)) { + found[name].slot = text.includes(`#{${TUI_FOLLOW_OWNER}}`) ? 'ours' : 'theirs'; + } else if (text.startsWith(`${event}[`)) { + found[name].others += 1; + } } } return found; } +/** Between the global and the session listing in one `show-hooks` read. */ +const FOLLOW_READ_SPLIT = '@@codeman-follow-split@@'; + +/** Sessions this process armed, by socket: the sweep never takes them for a leak. */ +const armedHere = new Set(); + +/** True when `pid` is a process of this user other than this one. */ +function isOtherLiveProcess(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid) return false; + try { + process.kill(pid, 0); + return true; + } catch (err) { + return (err as NodeJS.ErrnoException).code === 'EPERM'; + } +} + const LEGACY_TUI_SWITCH = /^switch-client -t (\S+?)(?: \\; set-window-option -t \1 window-size latest)?$/; /** @@ -1232,35 +1281,60 @@ export class TuiClient { /** * 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). + * tty and this process 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 hook existed (the window follows the terminal until the web + * UI resizes it). * - * 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 + * Nothing is installed when the user has a hook of their own at our index, + * or a GLOBAL hook on the same event: a session-level array hides the global + * one for that session (measured: a global hook stopped firing during the + * attach). 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. * + * One tmux call reads, one writes, so nine tabs stay quick to attach. + * * ⚠️ A half-done arm is undone before answering false, because `restore()` * only disarms what armed. tmux before 3.3 has no `client-active` hook, so - * there the owner is set and the first hook is refused; left alone, the - * owner would stay on the session for good. + * there the owner is set and the hook is refused; left alone, the owner + * would stay on the session for good. */ async armFollowTyping(muxName: string, clientTty: string): Promise { if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return false; try { - const hooks = await this.readFollowHooks(muxName); - if (Object.values(hooks).includes('theirs')) return false; + const { global, session } = await this.readFollowHooks(muxName); + for (const name of Object.keys(TUI_FOLLOW_HOOKS)) { + if (session[name].slot === 'theirs') return false; + if (global[name].slot !== undefined || global[name].others > 0) return false; + } } catch { return false; } + // Recorded before the first write, so a sweep running concurrently (it is + // fire-and-forget at startup) never takes this arm for a leak. + armedHere.add(this.armedKey(muxName)); + const args = [ + 'set-option', + '-t', + muxName, + TUI_FOLLOW_OWNER, + clientTty, + ';', + 'set-option', + '-t', + muxName, + TUI_FOLLOW_PID, + String(process.pid), + ]; + for (const [name, command] of Object.entries(TUI_FOLLOW_HOOKS)) { + args.push(';', 'set-hook', '-t', muxName, name, command); + } try { - 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]); - } + await this.exec('tmux', ['-L', this.socket, ...args]); return true; } catch { + armedHere.delete(this.armedKey(muxName)); try { await this.dropFollowTyping(muxName); } catch { @@ -1272,16 +1346,29 @@ export class TuiClient { /** * 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. + * second TUI that attached later owns the session now. */ async disarmFollowTyping(muxName: string, clientTty: string): Promise { if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return; try { - if ((await this.readFollowOwner(muxName)) !== clientTty) return; - await this.dropFollowTyping(muxName); + const { stdout } = await this.exec('tmux', [ + '-L', + this.socket, + 'show-options', + '-t', + muxName, + ';', + 'show-hooks', + '-t', + muxName, + ]); + // Hook lines never start with `@`, so the option parse ignores them. + if (parseSessionOptions(stdout, [TUI_FOLLOW_OWNER])[TUI_FOLLOW_OWNER] !== clientTty) return; + await this.dropFollowTyping(muxName, parseFollowHooks(stdout)); } catch { /* the session may be gone (the user exited the agent from inside the attach) */ + } finally { + armedHere.delete(this.armedKey(muxName)); } } @@ -1290,34 +1377,39 @@ export class TuiClient { * * 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. + * recorded, so the window followed whatever client a pty reusing that + * number belonged to. Left alone the hook also undoes `presizeWindow()` on + * the next attach. * - * ⚠️ `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. + * A session is left alone when this process armed it, or when the pid + * recorded with the owner is another live process (a second TUI mid-attach). + * Everything else with an owner is a leak, whatever its tty: Linux reuses + * pty numbers, so a tty proves nothing. + * + * Runs at TUI startup and again before each attach dresses its sessions, so + * `codeman tui ` gets it too. One tmux call lists every owner. */ - async clearLeakedFollowTyping(ownTty: string | null = readControllingTty()): Promise { - let names: string[]; - let live: Set; + async clearLeakedFollowTyping(): Promise { + let rows: 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())); + const { stdout } = await this.exec('tmux', [ + '-L', + this.socket, + 'list-sessions', + '-F', + `#{session_name}\t#{${TUI_FOLLOW_OWNER}}\t#{${TUI_FOLLOW_PID}}`, + ]); + rows = stdout.split('\n'); } catch { return 0; } let cleared = 0; - for (const name of names) { + for (const row of rows) { + const [name = '', owner = '', pid = ''] = row.trim().split('\t'); + if (!MUX_NAME_PATTERN.test(name) || !owner) continue; + if (armedHere.has(this.armedKey(name))) continue; + if (isOtherLiveProcess(Number(pid))) continue; try { - const owner = await this.readFollowOwner(name); - if (owner === null || owner === ownTty || live.has(owner)) continue; await this.dropFollowTyping(name); cleared += 1; } catch { @@ -1327,28 +1419,69 @@ export class TuiClient { return cleared; } - /** The tty recorded as `TUI_FOLLOW_OWNER` on a session, or null when none is. */ - private async readFollowOwner(muxName: string): Promise { - 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 armedKey(muxName: string): string { + return `${this.socket}\0${muxName}`; } - private async readFollowHooks(muxName: string): Promise> { - const { stdout } = await this.exec('tmux', ['-L', this.socket, 'show-hooks', '-t', muxName]); - return parseFollowHooks(stdout); + /** The global and the session hook listings, in one tmux call. */ + private async readFollowHooks( + muxName: string + ): Promise<{ global: Record; session: Record }> { + const { stdout } = await this.exec('tmux', [ + '-L', + this.socket, + 'show-hooks', + '-g', + ';', + 'display-message', + '-p', + '-t', + muxName, + FOLLOW_READ_SPLIT, + ';', + 'show-hooks', + '-t', + muxName, + ]); + const split = stdout.indexOf(FOLLOW_READ_SPLIT); + if (split === -1) throw new Error('unexpected show-hooks output'); + return { + global: parseFollowHooks(stdout.slice(0, split)), + session: parseFollowHooks(stdout.slice(split + FOLLOW_READ_SPLIT.length)), + }; } - /** Owner first (the hooks are inert from then on), then whichever hooks are ours. */ - private async dropFollowTyping(muxName: string): Promise { - await this.exec('tmux', ['-L', this.socket, 'set-option', '-u', '-t', muxName, TUI_FOLLOW_OWNER]); - const hooks = await this.readFollowHooks(muxName); + /** + * Owner first (the hook is inert from then on), then our hook, in one call. + * + * ⚠️ When ours is the only entry of the event, the whole session array is + * unset, not just our index: `set-hook -u` on one index leaves an empty + * session-level array, which keeps hiding the user's global hook for that + * event (measured on tmux 3.8). `restoreSessionOptions()` documents the + * same trap for `status-format[0]`. + */ + private async dropFollowTyping(muxName: string, known?: Record): Promise { + const hooks = known ?? (await this.readFollowHooks(muxName)).session; + const args = [ + 'set-option', + '-u', + '-t', + muxName, + TUI_FOLLOW_OWNER, + ';', + 'set-option', + '-u', + '-t', + muxName, + TUI_FOLLOW_PID, + ]; 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]); + const state = hooks[name]; + if (state.slot !== 'ours') continue; + const event = name.slice(0, name.indexOf('[')); + args.push(';', 'set-hook', '-u', '-t', muxName, state.others === 0 ? event : name); } + await this.exec('tmux', ['-L', this.socket, ...args]); } /** diff --git a/test/session-resize-arbitration.test.ts b/test/session-resize-arbitration.test.ts index 568acb8e..e89df4c5 100644 --- a/test/session-resize-arbitration.test.ts +++ b/test/session-resize-arbitration.test.ts @@ -144,13 +144,56 @@ describe('Session resize arbitration', () => { expect(resize).toHaveBeenCalledWith(100, 30); }); - it('applies forced resizes even when the dimensions did not change', () => { + // A forced resize at an unchanged size is a device asking for the pane back + // (Redraw). An unchanged pty gives tmux no SIGWINCH, so a `codeman tui` + // attach would keep the window; a one-row nudge first makes this client + // the one tmux counts as used last. + it('applies forced resizes even when the dimensions did not change, through a one-row nudge', () => { + vi.useFakeTimers(); + try { + const session = new Session({ workingDir: '/tmp', mode: 'shell' }); + const resize = attachFakePty(session, 120, 40); + + session.resize(120, 40, { force: true }); + expect(resize.mock.calls).toEqual([[120, 39]]); + const between = session.guardedInputGeneration; + vi.advanceTimersByTime(Session.FORCED_RESIZE_NUDGE_MS); + // The second move invalidates guarded input read between the two. + expect(session.guardedInputGeneration).not.toBe(between); + expect(resize.mock.calls).toEqual([ + [120, 39], + [120, 40], + ]); + expect(session.ptyGeometry).toEqual({ cols: 120, rows: 40 }); + } finally { + vi.useRealTimers(); + } + }); + + it('drops the end of a nudge that a newer resize overtook', () => { + vi.useFakeTimers(); + try { + const session = new Session({ workingDir: '/tmp', mode: 'shell' }); + const resize = attachFakePty(session, 120, 40); + + session.resize(120, 40, { force: true }); + session.resize(100, 30); + vi.advanceTimersByTime(Session.FORCED_RESIZE_NUDGE_MS); + expect(resize.mock.calls).toEqual([ + [120, 39], + [100, 30], + ]); + } finally { + vi.useRealTimers(); + } + }); + + it('does not nudge a forced resize that changes the size', () => { const session = new Session({ workingDir: '/tmp', mode: 'shell' }); const resize = attachFakePty(session, 120, 40); - session.resize(120, 40, { force: true }); - - expect(resize).toHaveBeenCalledWith(120, 40); + session.resize(100, 30, { force: true }); + expect(resize.mock.calls).toEqual([[100, 30]]); }); describe('idle-desktop override (whoever is active wins)', () => { diff --git a/test/tui/tui-app.test.ts b/test/tui/tui-app.test.ts index 4e293249..e85373b7 100644 --- a/test/tui/tui-app.test.ts +++ b/test/tui/tui-app.test.ts @@ -624,6 +624,7 @@ describe('the way out when F1 is taken, on a socket with no detach key', () => { restoreSessionOptions: async () => true, readWindowSizing: async () => null, presizeWindow: async () => true, + clearLeakedFollowTyping: async () => 0, followAttachingClient: async () => true, restoreWindowSizing: async () => true, } as unknown as TuiClient; @@ -672,6 +673,7 @@ describe('attach switch keys stay on the TUI client', () => { restoreSessionOptions: async () => true, readWindowSizing: async () => null, presizeWindow: async () => true, + clearLeakedFollowTyping: async () => 0, followAttachingClient: async () => { order.push('follow'); return true; @@ -747,6 +749,10 @@ describe('attach takes the window back from a browser when the terminal is used' restoreSessionOptions: async () => undefined, readWindowSizing: async () => ({ cols: 60, rows: 30, mode: 'manual' }), presizeWindow: async () => true, + clearLeakedFollowTyping: async () => { + calls.push('sweep'); + return 0; + }, followAttachingClient: async (muxName: string) => { calls.push(`follow ${muxName}`); return true; @@ -773,8 +779,10 @@ describe('attach takes the window back from a browser when the terminal is used' it('arms the hook on every session the strip can reach, and drops it before the size is put back', async () => { const { client, calls } = sizingFake(); const handoff = await beginAttachHandoff(client, 'codeman-aaaa1111', 'w1', tabs, 200, 50, '/dev/pts/4'); + // Leaks first, so a killed TUI's hook cannot undo the presize. Then // Alt+2 lands in the second session, and a phone can pin that one too. expect(calls).toEqual([ + 'sweep', 'follow codeman-aaaa1111', 'arm codeman-aaaa1111 /dev/pts/4', 'arm codeman-bbbb2222 /dev/pts/4', diff --git a/test/tui/tui-client.test.ts b/test/tui/tui-client.test.ts index 5e891106..e6a5b671 100644 --- a/test/tui/tui-client.test.ts +++ b/test/tui/tui-client.test.ts @@ -32,6 +32,7 @@ import { parseFollowHooks, TUI_FOLLOW_HOOKS, TUI_FOLLOW_OWNER, + TUI_FOLLOW_PID, isTuiClientTty, ATTACH_BANNER_MARKER, parseTmuxSessionList, @@ -523,126 +524,200 @@ describe('degraded-mode tmux enumeration', () => { }); describe('the follow hooks', () => { + const HOOK = 'client-active[91]'; + let sockets = 0; + /** - * A fake tmux holding one session's options and hooks, so arm, disarm and - * the sweep run against state rather than a script of canned answers. + * A fake tmux holding one session's options and hooks plus the global hooks, + * so arm, disarm and the sweep run against state rather than canned answers. + * It splits each call at `;` like tmux does. Every fake gets its own socket, + * because the "armed by this process" record is keyed by socket. */ function fakeTmux( - initial: { owner?: string; hooks?: Record; clients?: string[]; refuseHook?: string } = {} + initial: { + owner?: string; + pid?: string; + hooks?: Record; + global?: Record; + refuseHook?: string; + } = {} ) { - const state = { owner: initial.owner ?? null, hooks: { ...(initial.hooks ?? {}) } as Record }; - const writes: string[] = []; - const exec: TuiExecFile = async (_file, args) => { - const verb = args[2]; - if (verb === 'list-sessions') return { stdout: 'codeman-1a2b3c4d\n', stderr: '' }; - if (verb === 'list-clients') return { stdout: (initial.clients ?? []).join('\n'), stderr: '' }; - if (verb === 'show-options') { - return { - stdout: state.owner ? `${TUI_FOLLOW_OWNER} ${state.owner}\nstatus off\n` : 'status off\n', - stderr: '', - }; - } - if (verb === 'show-hooks') { - const lines = Object.entries(state.hooks).map(([name, command]) => `${name} ${command}`); - return { stdout: lines.join('\n'), stderr: '' }; - } - if (verb === 'set-hook' && !args.includes('-u') && args.includes(initial.refuseHook ?? '\0')) { - throw new Error(`invalid option: ${initial.refuseHook}`); - } - writes.push(args.slice(2).join(' ')); - if (verb === 'set-option' && args.includes('-u')) state.owner = null; - else if (verb === 'set-option') state.owner = args[args.length - 1] ?? null; - else if (verb === 'set-hook' && args.includes('-u')) delete state.hooks[args[args.length - 1] ?? '']; - else if (verb === 'set-hook') state.hooks[args[args.length - 2] ?? ''] = args[args.length - 1] ?? ''; - return { stdout: '', stderr: '' }; + const state = { + owner: initial.owner ?? null, + pid: initial.pid ?? null, + hooks: { ...(initial.hooks ?? {}) } as Record, + /** Events left with an empty session array (what `set-hook -u name[i]` leaves). */ + empty: [] as string[], }; - return { client: new TuiClient({ baseUrl, socket: 'codeman-beta', exec }), state, writes }; + const calls: string[][] = []; + const writes: string[] = []; + const session = 'codeman-1a2b3c4d'; + const listHooks = (hooks: Record, empty: string[]) => + [...Object.entries(hooks).map(([name, command]) => `${name} ${command}`), ...empty].join('\n') + '\n'; + const run = (cmd: string[]): string => { + const [verb] = cmd; + if (verb === 'list-sessions') return `${session}\t${state.owner ?? ''}\t${state.pid ?? ''}\n`; + if (verb === 'display-message') return `${cmd[cmd.length - 1]}\n`; + if (verb === 'show-hooks' && cmd.includes('-g')) return listHooks(initial.global ?? {}, []); + if (verb === 'show-hooks') return listHooks(state.hooks, state.empty); + if (verb === 'show-options') { + const lines = ['status off']; + if (state.owner) lines.unshift(`${TUI_FOLLOW_OWNER} ${state.owner}`); + if (state.pid) lines.unshift(`${TUI_FOLLOW_PID} ${state.pid}`); + return lines.join('\n') + '\n'; + } + const unset = cmd.includes('-u'); + const key = unset ? cmd[cmd.length - 1] : cmd[cmd.length - 2]; + if (verb === 'set-option' && key === TUI_FOLLOW_OWNER) state.owner = unset ? null : cmd[cmd.length - 1]; + else if (verb === 'set-option' && key === TUI_FOLLOW_PID) state.pid = unset ? null : cmd[cmd.length - 1]; + else if (verb === 'set-hook' && !unset) { + if (key === initial.refuseHook) throw new Error(`invalid option: ${key}`); + state.hooks[key] = cmd[cmd.length - 1]; + state.empty = state.empty.filter((event) => !key.startsWith(`${event}[`)); + } else if (verb === 'set-hook' && key.includes('[')) { + delete state.hooks[key]; + const event = key.slice(0, key.indexOf('[')); + if (!Object.keys(state.hooks).some((name) => name.startsWith(`${event}[`)) && !state.empty.includes(event)) { + state.empty.push(event); + } + } else if (verb === 'set-hook') { + for (const name of Object.keys(state.hooks)) if (name.startsWith(`${key}[`)) delete state.hooks[name]; + state.empty = state.empty.filter((event) => event !== key); + } + return ''; + }; + const exec: TuiExecFile = async (_file, args) => { + calls.push([...args]); + const commands: string[][] = [[]]; + for (const arg of args.slice(2)) { + if (arg === ';') commands.push([]); + else commands[commands.length - 1].push(arg); + } + if (commands.some((cmd) => cmd[0]?.startsWith('set-'))) writes.push(args.slice(2).join(' ')); + let stdout = ''; + for (const cmd of commands) stdout += run(cmd); + return { stdout, stderr: '' }; + }; + sockets += 1; + return { client: new TuiClient({ baseUrl, socket: `codeman-follow-${sockets}`, exec }), state, calls, writes }; } - it('builds constant commands that read the owner option, with no -t and no tty in them', () => { - expect(Object.keys(TUI_FOLLOW_HOOKS)).toEqual(['client-active[91]', 'after-resize-window[91]']); - for (const command of Object.values(TUI_FOLLOW_HOOKS)) { - expect(command).toContain(`#{${TUI_FOLLOW_OWNER}}`); - expect(command).toContain('"set-window-option window-size latest"'); - // tmux parses a hook command when it is set: an unquoted #{...} after -t is a comment. - expect(command).not.toContain('-t '); - expect(command).not.toContain('/dev/'); - } - // client-active acts only for the owner's client. - expect(TUI_FOLLOW_HOOKS['client-active[91]']).toContain(`#{==:#{client_tty},#{${TUI_FOLLOW_OWNER}}}`); + it('builds a constant command that reads the owner option, with no -t and no tty in it', () => { + expect(Object.keys(TUI_FOLLOW_HOOKS)).toEqual([HOOK]); + const command = TUI_FOLLOW_HOOKS[HOOK]; + // Acts only for the owner's client. + expect(command).toContain(`#{==:#{client_tty},#{${TUI_FOLLOW_OWNER}}}`); + expect(command).toContain('"set-window-option window-size latest"'); + // tmux parses a hook command when it is set: an unquoted #{...} after -t is a comment. + expect(command).not.toContain('-t '); + expect(command).not.toContain('/dev/'); }); - it('tells our hooks from the user ones at the same index', () => { - const ours = Object.entries(TUI_FOLLOW_HOOKS).map(([name, command]) => `${name} ${command}`); - expect(parseFollowHooks(ours.join('\n'))).toEqual({ - 'client-active[91]': 'ours', - 'after-resize-window[91]': 'ours', + it('tells our hook from the user ones, and counts the other entries of the event', () => { + expect(parseFollowHooks(`${HOOK} ${TUI_FOLLOW_HOOKS[HOOK]}\n`)).toEqual({ [HOOK]: { slot: 'ours', others: 0 } }); + expect(parseFollowHooks('client-active[91] display-message mine\nclient-active[0] x\n')).toEqual({ + [HOOK]: { slot: 'theirs', others: 1 }, }); - expect(parseFollowHooks('client-active[91] display-message mine\nclient-active[0] x')).toEqual({ - 'client-active[91]': 'theirs', - }); - expect(parseFollowHooks('client-active\nafter-resize-window\n')).toEqual({}); + // An empty session array (what `set-hook -u name[i]` leaves) is no entry. + expect(parseFollowHooks('client-active\nafter-resize-window[2] y\n')).toEqual({ [HOOK]: { others: 0 } }); }); - it('arms the owner before the hooks, and disarms the owner first', async () => { + it('arms in one write, owner and pid first, and disarms in one, owner first', async () => { const { client, state, writes } = fakeTmux(); await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(true); expect(writes).toEqual([ - `set-option -t codeman-1a2b3c4d ${TUI_FOLLOW_OWNER} /dev/pts/4`, - `set-hook -t codeman-1a2b3c4d client-active[91] ${TUI_FOLLOW_HOOKS['client-active[91]']}`, - `set-hook -t codeman-1a2b3c4d after-resize-window[91] ${TUI_FOLLOW_HOOKS['after-resize-window[91]']}`, + `set-option -t codeman-1a2b3c4d ${TUI_FOLLOW_OWNER} /dev/pts/4 ; ` + + `set-option -t codeman-1a2b3c4d ${TUI_FOLLOW_PID} ${process.pid} ; ` + + `set-hook -t codeman-1a2b3c4d ${HOOK} ${TUI_FOLLOW_HOOKS[HOOK]}`, ]); writes.length = 0; await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); - // Owner first: from that moment both hooks are inert, even if a removal fails. + // The whole array goes when ours was its only entry: an empty one would keep + // hiding a global hook on the event. expect(writes).toEqual([ - `set-option -u -t codeman-1a2b3c4d ${TUI_FOLLOW_OWNER}`, - 'set-hook -u -t codeman-1a2b3c4d client-active[91]', - 'set-hook -u -t codeman-1a2b3c4d after-resize-window[91]', + `set-option -u -t codeman-1a2b3c4d ${TUI_FOLLOW_OWNER} ; ` + + `set-option -u -t codeman-1a2b3c4d ${TUI_FOLLOW_PID} ; ` + + 'set-hook -u -t codeman-1a2b3c4d client-active', ]); - expect(state).toEqual({ owner: null, hooks: {} }); + expect(state).toEqual({ owner: null, pid: null, hooks: {}, empty: [] }); + }); + + it('takes one tmux call to read and one to write, per arm and per disarm', async () => { + const { client, calls } = fakeTmux(); + await client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); + expect(calls).toHaveLength(2); + calls.length = 0; + await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); + expect(calls).toHaveLength(2); + }); + + it('removes only our index when the user has another entry on the event', async () => { + const { client, state } = fakeTmux({ hooks: { 'client-active[3]': 'display-message mine' } }); + await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(true); + await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); + expect(state.hooks).toEqual({ 'client-active[3]': 'display-message mine' }); }); it('undoes a half-done arm, as on a tmux without client-active (before 3.3)', async () => { - const { client, state } = fakeTmux({ refuseHook: 'client-active[91]' }); + const { client, state } = fakeTmux({ refuseHook: HOOK }); await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); // restore() disarms only what armed, so nothing may be left behind here. - expect(state).toEqual({ owner: null, hooks: {} }); + expect(state).toEqual({ owner: null, pid: null, hooks: {}, empty: [] }); }); it('installs nothing over a hook of the user, and never removes one', async () => { - const { client, state, writes } = fakeTmux({ hooks: { 'after-resize-window[91]': 'display-message mine' } }); + const { client, state, writes } = fakeTmux({ hooks: { [HOOK]: 'display-message mine' } }); await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); expect(writes).toEqual([]); // Even with an owner recorded (a TUI killed before restore), the user's hook stays. state.owner = '/dev/pts/4'; await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); - expect(state.hooks).toEqual({ 'after-resize-window[91]': 'display-message mine' }); + expect(state.hooks).toEqual({ [HOOK]: 'display-message mine' }); + }); + + it('installs nothing while the user has a global hook on the event, which a session array would hide', async () => { + for (const global of [{ 'client-active[0]': 'display-message g' }, { [HOOK]: 'display-message g' }]) { + const { client, writes } = fakeTmux({ global }); + await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); + expect(writes).toEqual([]); + } }); it('leaves the session to a second TUI that took it over', async () => { const { client, state } = fakeTmux(); await client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); - await client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/41'); - // pts/4 is a prefix of pts/41, and its restore must not take pts/41's hooks. + state.owner = '/dev/pts/41'; + // pts/4 is a prefix of pts/41, and its restore must not take pts/41's hook. await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4'); expect(state.owner).toBe('/dev/pts/41'); - expect(Object.keys(state.hooks)).toHaveLength(2); + expect(Object.keys(state.hooks)).toEqual([HOOK]); }); - it('sweeps an owner with no live client, and never a live one or its own', async () => { - const dead = fakeTmux({ owner: '/dev/pts/7', hooks: { ...TUI_FOLLOW_HOOKS }, clients: ['/dev/pts/2'] }); - await expect(dead.client.clearLeakedFollowTyping(null)).resolves.toBe(1); - expect(dead.state).toEqual({ owner: null, hooks: {} }); + it('sweeps by process, never by tty: a dead pid goes, a live one and this process stay', async () => { + const hooks = { ...TUI_FOLLOW_HOOKS }; + // The pty number came back to a live terminal; the pid says it is a leak. + const dead = fakeTmux({ owner: '/dev/pts/7', pid: String(2 ** 22 + 1), hooks }); + await expect(dead.client.clearLeakedFollowTyping()).resolves.toBe(1); + expect(dead.state).toEqual({ owner: null, pid: null, hooks: {}, empty: [] }); - const live = fakeTmux({ owner: '/dev/pts/8', hooks: { ...TUI_FOLLOW_HOOKS }, clients: ['/dev/pts/8'] }); - await expect(live.client.clearLeakedFollowTyping(null)).resolves.toBe(0); + // An owner with no pid at all is a leak too (nothing can vouch for it). + const nopid = fakeTmux({ owner: '/dev/pts/7', hooks }); + await expect(nopid.client.clearLeakedFollowTyping()).resolves.toBe(1); + + // A second TUI mid-attach: another live process. + const live = fakeTmux({ owner: '/dev/pts/8', pid: String(process.ppid), hooks }); + await expect(live.client.clearLeakedFollowTyping()).resolves.toBe(0); expect(live.state.owner).toBe('/dev/pts/8'); - // An Enter pressed before the sweep finished: armed, not yet a client. - const own = fakeTmux({ owner: '/dev/pts/7', hooks: { ...TUI_FOLLOW_HOOKS } }); - await expect(own.client.clearLeakedFollowTyping('/dev/pts/7')).resolves.toBe(0); + // This process's own arm (an Enter pressed before the startup sweep ended). + const own = fakeTmux(); + await own.client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/7'); + await expect(own.client.clearLeakedFollowTyping()).resolves.toBe(0); expect(own.state.owner).toBe('/dev/pts/7'); + // Once disarmed it is no longer ours, so a copy left behind would be swept. + await own.client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/7'); + Object.assign(own.state, { owner: '/dev/pts/7', pid: String(process.pid), hooks: { ...hooks } }); + await expect(own.client.clearLeakedFollowTyping()).resolves.toBe(1); }); it('refuses names and ttys it must not pass on, and swallows a dead tmux', async () => { @@ -661,7 +736,7 @@ describe('the follow hooks', () => { }); await expect(dead.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false); await expect(dead.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBeUndefined(); - await expect(dead.clearLeakedFollowTyping(null)).resolves.toBe(0); + await expect(dead.clearLeakedFollowTyping()).resolves.toBe(0); }); }); diff --git a/test/tui/tui-follow-typing.test.ts b/test/tui/tui-follow-typing.test.ts index eaa04bde..2a1ee367 100644 --- a/test/tui/tui-follow-typing.test.ts +++ b/test/tui/tui-follow-typing.test.ts @@ -15,7 +15,8 @@ import { afterAll, describe, expect, it } from 'vitest'; import { execFileSync, execSync } from 'node:child_process'; import { rmSync } from 'node:fs'; import * as pty from 'node-pty'; -import { TUI_FOLLOW_HOOKS, TUI_FOLLOW_OWNER, TuiClient } from '../../src/tui/tui-client.js'; +import { TUI_FOLLOW_HOOKS, TUI_FOLLOW_OWNER, TUI_FOLLOW_PID, TuiClient } from '../../src/tui/tui-client.js'; +import { Session } from '../../src/session.js'; const hasTmux = (() => { try { @@ -95,6 +96,17 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => { run(['resize-window', '-t', alpha, '-x', String(cols), '-y', String(rows)]); } + /** + * A forced resize at the tab's current size (Redraw), as `Session.resize()` + * does it: a one-row nudge of the tab's pty, then the real size and the + * `resize-window`. + */ + async function browserRedraw(term: pty.IPty, cols: number, rows: number): Promise { + term.resize(cols, rows - 1); + await new Promise((resolve) => setTimeout(resolve, Session.FORCED_RESIZE_NUDGE_MS)); + await browserResize(term, cols, rows); + } + afterAll(() => { for (const term of clients) term.kill(); let socketPath = ''; @@ -127,18 +139,19 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => { const browser = attach(60, 30); expect(await waitFor(() => ttyOf(browser) !== '')).toBe(true); await browserResize(browser, 61, 30); - expect(windowSize()).toBe('61x30 latest'); + expect(windowSize()).toBe('61x30 manual'); - // The bug: without the hooks the window stayed 61x30 manual here, and - // typing in the terminal changed nothing for the rest of the attach. + // The bug: without the hook the window stayed 61x30 manual from here on, + // and typing in the terminal changed nothing for the rest of the attach. tui.write('a'); expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true); - // A browser opening a session sends a FORCED resize at its current size. - // Its pty does not change, so tmux keeps the terminal as the latest client - // and the window stays where the user is typing. - await browserResize(browser, 61, 30); - expect(windowSize()).toBe('200x50 latest'); + // The browser's Redraw is a FORCED resize at its current size: the user + // asking for the pane back. It wins, and the terminal's next key takes it back. + await browserRedraw(browser, 61, 30); + expect(windowSize()).toBe('61x30 manual'); + tui.write('a'); + expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true); // Typing in the browser tab gives the window to the tab... browser.write('b'); @@ -188,21 +201,51 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => { expect(windowSize()).toBe('65x30 manual'); for (const name of Object.keys(TUI_FOLLOW_HOOKS)) run(['set-hook', '-u', '-t', alpha, name]); - // A hook of the user's own at either index is never overwritten. - run(['set-hook', '-t', alpha, 'after-resize-window[91]', 'display-message mine']); + // A hook of the user's own at our index is never overwritten. + run(['set-hook', '-t', alpha, 'client-active[91]', 'display-message mine']); expect(await client.armFollowTyping(alpha, tuiTty)).toBe(false); expect(hooks()).toContain('display-message mine'); expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER); - run(['set-hook', '-u', '-t', alpha, 'after-resize-window[91]']); + run(['set-hook', '-u', '-t', alpha, 'client-active']); - // A leaked owner (a TUI killed mid-attach) is swept once its client is gone. - expect(await client.armFollowTyping(alpha, '/dev/ttys999')).toBe(true); - expect(await client.clearLeakedFollowTyping(null)).toBe(1); + // Nor is a global one hidden: a session-level array would stop it firing here. + run(['set-hook', '-g', 'client-active', 'display-message global']); + expect(await client.armFollowTyping(alpha, tuiTty)).toBe(false); expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER); - expect(hooks()).not.toContain('[91]'); - // A live one is not. + run(['set-hook', '-gu', 'client-active']); + + // Disarm removes the whole session array when ours was its only entry: an + // empty array left behind would keep hiding a global hook on the event. expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true); - expect(await client.clearLeakedFollowTyping(null)).toBe(0); + await client.disarmFollowTyping(alpha, tuiTty); + expect(hooks()).not.toMatch(/^client-active/m); + // A user's own entry on the same event stays, and so does its array. + run(['set-hook', '-t', alpha, 'client-active[3]', 'display-message mine']); + expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true); + await client.disarmFollowTyping(alpha, tuiTty); + expect(hooks()).toContain('client-active[3] display-message mine'); + expect(hooks()).not.toContain('[91]'); + run(['set-hook', '-u', '-t', alpha, 'client-active']); + + // A leak is told by its process, never its tty: Linux hands the next + // terminal the pty that just closed, so here the leaked owner's tty is the + // live TUI's own, and the dead pid still marks it as a leak. + const leak = (tty: string, pid: number) => { + run(['set-option', '-t', alpha, TUI_FOLLOW_OWNER, tty]); + run(['set-option', '-t', alpha, TUI_FOLLOW_PID, String(pid)]); + for (const [name, command] of Object.entries(TUI_FOLLOW_HOOKS)) run(['set-hook', '-t', alpha, name, command]); + }; + leak(tuiTty, 2 ** 22 + 1); + expect(await client.clearLeakedFollowTyping()).toBe(1); + expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER); + expect(hooks()).not.toMatch(/^client-active/m); + // Another live process (a second TUI mid-attach) keeps its arm. + leak('/dev/ttys998', tui.pid); + expect(await client.clearLeakedFollowTyping()).toBe(0); + expect(run(['show-options', '-t', alpha])).toContain(`${TUI_FOLLOW_OWNER} /dev/ttys998`); + // So does this process's own arm, whatever its tty. + expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true); + expect(await client.clearLeakedFollowTyping()).toBe(0); expect(run(['show-options', '-t', alpha])).toContain(`${TUI_FOLLOW_OWNER} ${tuiTty}`); }); });