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