From ba61cfe4e6f005d279cecf561e1d4736953bc5a2 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Tue, 24 Nov 2026 18:28:06 +0100 Subject: [PATCH] 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}`); + }); +});