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