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

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

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

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

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

No files matched your search

+1 -1
View File
@@ -2,4 +2,4 @@
'aicodeman': patch '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.
+1 -1
View File
@@ -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 ### 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 `<prefix> 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 <table>` 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-<letter> 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-<digit>`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-<digit>`, which writes Esc and the digit into that client's own pane, so a vim `<Esc>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 keysLine truncated **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 `<prefix> 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 <table>` 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-<letter> 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-<digit>`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-<digit>`, which writes Esc and the digit into that client's own pane, so a vim `<Esc>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) leaLine truncated
### Reverse-proxy base path ### Reverse-proxy base path
+9 -8
View File
@@ -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. in a pane that already fills your terminal.
The window follows whoever used it last, as plain tmux does. If a browser tab (a 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 phone, say) opens or resizes the session while you are attached, the window takes
window to that tab, and your terminal shows a smaller pane. Type, paste or resize that tab's size, and your terminal shows a smaller pane. Type, paste or resize your
your terminal and the window fills it again. The TUI does this with a terminal and the window fills it again; type in the tab and the tab gets it back.
`client-active[91]` hook on each session it dressed, which only acts for this The TUI does this with two hooks on each session it dressed (`client-active[91]`
terminal's tmux client, and it removes the hooks on detach. Typing in the browser and `after-resize-window[91]`) and a session option naming your terminal
tab is left to Codeman's own sizing rules. tmux older than 3.3 has no (`@codeman-tui-follow`), and removes all three on detach. A TUI that was killed
`client-active` hook, so there the pane stays at the browser's size until you while attached (a closed window, a dropped SSH) leaves them behind, and the next
detach and attach again. `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, 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 which is the difference the bar exists to make obvious. If an agent does exit, its
+8 -6
View File
@@ -664,10 +664,11 @@ export async function beginAttachHandoff(
// resizes this session mid-attach goes through Codeman's `resize-window`, // 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 // 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 // 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 // pasting here changed nothing until a detach and a fresh attach. The
// puts `latest` back when THIS terminal is used again, the way plain tmux // follow hooks (TUI_FOLLOW_HOOKS) keep the window on `latest`, so it
// follows whoever typed last. Needs the tty for its guard, like the switch // follows whichever client was used last, this terminal included. They
// keys, so without one the attach keeps the old behaviour. // 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); 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 // ⚠️ 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 (tty && isTuiClientTty(tty)) await client.disarmTuiSwitchGuard(tty);
if (oneKey) await client.unbindDetachKey(ONE_KEY_DETACH, 'root'); if (oneKey) await client.unbindDetachKey(ONE_KEY_DETACH, 'root');
if (claimed && alias) await client.unbindDetachKey(alias); if (claimed && alias) await client.unbindDetachKey(alias);
// The hooks before the size: a hook left armed would put `latest` back // The follow hooks before the size: the restore below is a
// the next time anything fired it, after the browser re-pinned the window. // `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); for (const target of followTyping) await client.disarmFollowTyping(target, tty as string);
// Options first, then the size: dropping the status bar gives its row // 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 // back to the pane, and the resize is what re-pins the browser's
+132 -113
View File
@@ -508,51 +508,61 @@ export function tuiSwitchAttachHook(tty: string): string {
} }
/** /**
* Session hook that gives the window back to the TUI's terminal when you type * Session option naming the tty of the `codeman tui` attach that owns the
* there. Indexed so it does not replace a user's own `client-active` hook, and * window size of this session. The follow hooks below read it, so a hook whose
* next to the switch guard's `[90]`. * 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 * Why they are needed: the attach sets `window-size latest`, but Codeman's web
* resize (`resizeWindow()` in tmux-manager.ts) runs `resize-window`, which * resize (`resizeWindow()` in tmux-manager.ts) runs `resize-window`, and
* puts the window back on `manual` at the browser's size. A phone opening the * 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 * session mid-attach therefore pinned the window to the phone, and typing or
* pasting in the terminal changed nothing until the user detached and * pasting in the terminal changed nothing until a detach and a fresh attach.
* attached again.
* *
* Set per session (`set-hook -t`), never globally: it lives and dies with the * - `after-resize-window[91]` puts `latest` back right after Codeman's
* attach's sessions and never reaches a session the TUI did not dress. * resize, so tmux keeps deciding: the browser's client is the latest one
* when Codeman resized its pty, and the terminal stays in front when the
* resize did not change that pty (a forced resize at the same size, which
* a browser sends when it opens a session).
* - `client-active[91]` puts `latest` back when the TUI's own client becomes
* the latest one again, which typing, pasting or resizing the terminal does
* after another client was used (measured on tmux 3.8). That covers
* `setManualWindowSize()`, which sets `manual` without a resize.
*
* Indexed so they do not replace a user's own hooks, next to the switch
* guard's `[90]`, and set per session (`set-hook -t`), never globally.
*
* ⚠️ Constant strings: the tty is read from `TUI_FOLLOW_OWNER` when a hook
* runs, never interpolated. And no `-t` on `set-window-option`: tmux parses a
* hook's command when the hook is set, and an unquoted `#{session_name}`
* there starts a comment (measured: "-t expects an argument"). Without `-t`
* the command targets the window the hook fired for.
*/ */
export const TUI_FOLLOW_TYPING_HOOK = 'client-active[91]'; export const TUI_FOLLOW_HOOKS: Readonly<Record<string, string>> = {
'client-active[91]': `if-shell -F "#{==:#{client_tty},#{${TUI_FOLLOW_OWNER}}}" "set-window-option window-size latest"`,
'after-resize-window[91]': `if-shell -F "#{!=:#{${TUI_FOLLOW_OWNER}},}" "set-window-option window-size latest"`,
};
/** /**
* `set-hook` command for `TUI_FOLLOW_TYPING_HOOK`. tmux runs `client-active` * For each follow hook name, what `show-hooks -t` lists at that index: `ours`,
* when a client becomes the latest one on its session, which includes typing * `theirs` (a hook of the user's), or absent when nothing is set there.
* 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 { export function parseFollowHooks(stdout: string): Record<string, 'ours' | 'theirs'> {
return `if-shell -F "#{==:#{client_tty},${tty}}" "set-window-option window-size latest"`; const found: Record<string, 'ours' | 'theirs'> = {};
} for (const line of stdout.split('\n')) {
const text = line.trim();
/** for (const name of Object.keys(TUI_FOLLOW_HOOKS)) {
* The tty a `client-active[91]` hook line from `show-hooks -t` was set for, if (!text.startsWith(`${name} `)) continue;
* or null when the line is not one of ours. The closed form `,<tty>}` is found[name] = text.includes(`#{${TUI_FOLLOW_OWNER}}`) ? 'ours' : 'theirs';
* matched, so `/dev/pts/4` is not read out of a hook for `/dev/pts/41`. }
*/ }
export function tuiFollowTypingHookTty(line: string): string | null { return found;
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)?$/; 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 * Make one session's window follow this terminal for the attach: record the
* effort, like the rest of the attach dressing: false leaves the attach as it * tty as the owner, then install `TUI_FOLLOW_HOOKS`. Best effort, like the
* was before the hook existed (the window follows the terminal until the web * rest of the attach dressing: false leaves the attach as it was before the
* UI resizes it). * 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 * A hook at either index that is not ours is the user's, and then nothing is
* of ours for another tty is replaced: it belongs to a TUI that was killed * installed. An owner already recorded is replaced: it is a TUI killed before
* before its restore (a stale tty), or to a second TUI on the same session, * its restore, or a second TUI on the same session, and the newest attach is
* and the newest attach is the one in front of the user. * the one in front of the user.
*/ */
async armFollowTyping(muxName: string, clientTty: string): Promise<boolean> { async armFollowTyping(muxName: string, clientTty: string): Promise<boolean> {
if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return false; if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return false;
try { try {
const current = await this.readFollowTypingHook(muxName); const hooks = await this.readFollowHooks(muxName);
if (current !== null && tuiFollowTypingHookTty(current) === null) return false; if (Object.values(hooks).includes('theirs')) return false;
await this.exec('tmux', [ await this.exec('tmux', ['-L', this.socket, 'set-option', '-t', muxName, TUI_FOLLOW_OWNER, clientTty]);
'-L', for (const [name, command] of Object.entries(TUI_FOLLOW_HOOKS)) {
this.socket, await this.exec('tmux', ['-L', this.socket, 'set-hook', '-t', muxName, name, command]);
'set-hook', }
'-t',
muxName,
TUI_FOLLOW_TYPING_HOOK,
tuiFollowTypingHook(clientTty),
]);
return true; return true;
} catch { } catch {
return false; return false;
@@ -1252,25 +1257,86 @@ export class TuiClient {
} }
/** /**
* Undo `armFollowTyping`, but only while the hook still names this tty: a * Undo `armFollowTyping`, but only while this tty is still the owner: a
* second TUI that attached later owns it now. * second TUI that attached later owns the session now. The owner goes first,
* so the hooks are inert from that moment even if removing them fails.
*/ */
async disarmFollowTyping(muxName: string, clientTty: string): Promise<void> { async disarmFollowTyping(muxName: string, clientTty: string): Promise<void> {
if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return; if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return;
try { try {
const current = await this.readFollowTypingHook(muxName); if ((await this.readFollowOwner(muxName)) !== clientTty) return;
if (current === null || tuiFollowTypingHookTty(current) !== clientTty) return; await this.dropFollowTyping(muxName);
await this.exec('tmux', ['-L', this.socket, 'set-hook', '-u', '-t', muxName, TUI_FOLLOW_TYPING_HOOK]);
} catch { } catch {
/* the session may be gone (the user exited the agent from inside the attach) */ /* the session may be gone (the user exited the agent from inside the attach) */
} }
} }
/** The session's own `client-active[91]` line, or null when nothing is set there. */ /**
private async readFollowTypingHook(muxName: string): Promise<string | null> { * Remove follow hooks a previous TUI never got to take down.
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; * Same leak as the banners: a terminal that dies while attached (a closed
* window, a dropped SSH) never reaches `restore()`, and its owner stays
* recorded, so the window kept following whatever client a pty reusing that
* number belonged to. This removes the owner and our hooks where the owner
* has no live tmux client.
*
* ⚠️ `ownTty` is never swept. The sweep runs fire-and-forget at startup, and
* an Enter pressed before it finishes arms this terminal before it is a tmux
* client, so the client listing cannot vouch for it yet. A second TUI
* mid-attach is a live client and is left alone the same way.
*/
async clearLeakedFollowTyping(ownTty: string | null = readControllingTty()): Promise<number> {
let names: string[];
let live: Set<string>;
try {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-sessions', '-F', '#{session_name}']);
names = stdout
.split('\n')
.map((line) => line.trim())
.filter((line) => MUX_NAME_PATTERN.test(line));
const clients = await this.exec('tmux', ['-L', this.socket, 'list-clients', '-F', '#{client_tty}']);
live = new Set(clients.stdout.split('\n').map((line) => line.trim()));
} catch {
return 0;
}
let cleared = 0;
for (const name of names) {
try {
const owner = await this.readFollowOwner(name);
if (owner === null || owner === ownTty || live.has(owner)) continue;
await this.dropFollowTyping(name);
cleared += 1;
} catch {
/* the session went away mid-sweep */
}
}
return cleared;
} }
/** The tty recorded as `TUI_FOLLOW_OWNER` on a session, or null when none is. */
private async readFollowOwner(muxName: string): Promise<string | null> {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'show-options', '-t', muxName]);
// The listing, not `show-options -v`: an unset user option is an error on
// tmux 3.5 but empty output and exit 0 on 3.2a.
const owner = parseSessionOptions(stdout, [TUI_FOLLOW_OWNER])[TUI_FOLLOW_OWNER];
return owner ? owner : null;
}
private async readFollowHooks(muxName: string): Promise<Record<string, 'ours' | 'theirs'>> {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'show-hooks', '-t', muxName]);
return parseFollowHooks(stdout);
}
/** Owner first (the hooks are inert from then on), then whichever hooks are ours. */
private async dropFollowTyping(muxName: string): Promise<void> {
await this.exec('tmux', ['-L', this.socket, 'set-option', '-u', '-t', muxName, TUI_FOLLOW_OWNER]);
const hooks = await this.readFollowHooks(muxName);
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) {
if (hooks[name] !== 'ours') continue;
await this.exec('tmux', ['-L', this.socket, 'set-hook', '-u', '-t', muxName, name]);
}
}
/** /**
* Give back a switch key, but only while it is still one of ours. * Give back a switch key, but only while it is still one of ours.
* *
@@ -1457,53 +1523,6 @@ export class TuiClient {
return cleared; return cleared;
} }
/**
* Drop `client-active[91]` hooks a previous TUI never got to remove.
*
* Same leak as the banners above: a terminal that dies while attached never
* reaches `restore()`. A leaked hook acts only for its tty, so it is harmless
* until a pty reuses that number, and then it hands a window to whatever
* client got it. This sweep removes ours whose tty has no live tmux client.
*
* ⚠️ `ownTty` is never swept. The sweep runs fire-and-forget at startup, and
* an Enter pressed before it finishes arms this terminal's hook before this
* terminal is a tmux client, so the client listing cannot vouch for it yet.
* A second TUI mid-attach is a live client and is left alone the same way.
*/
async clearLeakedFollowTyping(ownTty: string | null = readControllingTty()): Promise<number> {
let names: string[];
let live: Set<string>;
try {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-sessions', '-F', '#{session_name}']);
names = stdout
.split('\n')
.map((line) => line.trim())
.filter((line) => MUX_NAME_PATTERN.test(line));
const clients = await this.exec('tmux', ['-L', this.socket, 'list-clients', '-F', '#{client_tty}']);
live = new Set(clients.stdout.split('\n').map((line) => line.trim()));
} catch {
return 0;
}
let cleared = 0;
for (const name of names) {
let tty: string | null;
try {
const current = await this.readFollowTypingHook(name);
tty = current === null ? null : tuiFollowTypingHookTty(current);
} catch {
continue;
}
if (tty === null || tty === ownTty || live.has(tty)) continue;
try {
await this.exec('tmux', ['-L', this.socket, 'set-hook', '-u', '-t', name, TUI_FOLLOW_TYPING_HOOK]);
cleared += 1;
} catch {
/* the session went away mid-sweep */
}
}
return cleared;
}
private async setOption(args: readonly string[]): Promise<void> { private async setOption(args: readonly string[]): Promise<void> {
try { try {
await this.exec('tmux', ['-L', this.socket, 'set-option', ...args]); await this.exec('tmux', ['-L', this.socket, 'set-option', ...args]);
+126 -126
View File
@@ -29,9 +29,9 @@ import {
tuiSwitchBindingTty, tuiSwitchBindingTty,
tuiSwitchAttachHook, tuiSwitchAttachHook,
tuiSwitchGuard, tuiSwitchGuard,
tuiFollowTypingHook, parseFollowHooks,
tuiFollowTypingHookTty, TUI_FOLLOW_HOOKS,
TUI_FOLLOW_TYPING_HOOK, TUI_FOLLOW_OWNER,
isTuiClientTty, isTuiClientTty,
ATTACH_BANNER_MARKER, ATTACH_BANNER_MARKER,
parseTmuxSessionList, parseTmuxSessionList,
@@ -522,87 +522,134 @@ describe('degraded-mode tmux enumeration', () => {
}); });
}); });
describe('the follow-typing hook', () => { describe('the follow hooks', () => {
function hookClient(exec: TuiExecFile): TuiClient { /**
return new TuiClient({ baseUrl, socket: 'codeman-beta', exec }); * 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.
const line = (tty: string): string => `${TUI_FOLLOW_TYPING_HOOK} ${tuiFollowTypingHook(tty)}`; */
function fakeTmux(initial: { owner?: string; hooks?: Record<string, string>; clients?: string[] } = {}) {
it('reads its own tty back out of the closed form, and nothing else', () => { const state = { owner: initial.owner ?? null, hooks: { ...(initial.hooks ?? {}) } as Record<string, string> };
expect(tuiFollowTypingHookTty(line('/dev/pts/4'))).toBe('/dev/pts/4'); const writes: string[] = [];
expect(tuiFollowTypingHookTty(line('/dev/ttys033'))).toBe('/dev/ttys033'); const exec: TuiExecFile = async (_file, args) => {
expect(tuiFollowTypingHookTty(line('/dev/pts/41'))).toBe('/dev/pts/41'); const verb = args[2];
// The user's own hook at the same index, or at another one, is not ours. if (verb === 'list-sessions') return { stdout: 'codeman-1a2b3c4d\n', stderr: '' };
expect(tuiFollowTypingHookTty(`${TUI_FOLLOW_TYPING_HOOK} display-message mine`)).toBeNull(); if (verb === 'list-clients') return { stdout: (initial.clients ?? []).join('\n'), stderr: '' };
expect(tuiFollowTypingHookTty(`client-active[0] ${tuiFollowTypingHook('/dev/pts/4')}`)).toBeNull(); if (verb === 'show-options') {
expect(tuiFollowTypingHookTty('')).toBeNull(); return {
}); stdout: state.owner ? `${TUI_FOLLOW_OWNER} ${state.owner}\nstatus off\n` : 'status off\n',
stderr: '',
it('arms with an argv array on the session, after checking the slot is free', async () => { };
const calls: Array<readonly string[]> = []; }
const client = hookClient(async (_file, args) => { if (verb === 'show-hooks') {
calls.push(args); const lines = Object.entries(state.hooks).map(([name, command]) => `${name} ${command}`);
return { stdout: 'client-attached[90] something else\n', stderr: '' }; return { stdout: lines.join('\n'), stderr: '' };
}); }
await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(true); writes.push(args.slice(2).join(' '));
expect(calls).toEqual([ if (verb === 'set-option' && args.includes('-u')) state.owner = null;
['-L', 'codeman-beta', 'show-hooks', '-t', 'codeman-1a2b3c4d'], 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] ?? ''];
'-L', else if (verb === 'set-hook') state.hooks[args[args.length - 2] ?? ''] = args[args.length - 1] ?? '';
'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<readonly string[]> = [];
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<readonly string[]> = [];
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<readonly string[]> = [];
const client = hookClient(async (_file, args) => {
calls.push(args);
return { stdout: '', stderr: '' }; return { stdout: '', stderr: '' };
}); };
await expect(client.armFollowTyping('other-session', '/dev/pts/4')).resolves.toBe(false); return { client: new TuiClient({ baseUrl, socket: 'codeman-beta', exec }), state, writes };
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 () => { it('builds constant commands that read the owner option, with no -t and no tty in them', () => {
throw new Error('no server running on /tmp/tmux-1000/codeman-beta'); 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.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false);
await expect(dead.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBeUndefined(); 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<string, string>, 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', () => { describe('parseDetachKey', () => {
// Verbatim from `tmux -L codeman list-keys -T prefix` on tmux 3.4, trimmed to // 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 // the two lines that matter. They differ only by case, which is the whole
+67 -46
View File
@@ -5,8 +5,9 @@
* Against a real tmux on a private socket (never Codeman's). Two attach clients * 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 * 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 * `tmux attach-session` per session, sized by Codeman). The browser's resize is
* what `TmuxManager.resizeWindow()` runs: `resize-window -x -y`, which puts the * what `Session.resize()` does: resize its client's pty, then
* window on `manual`. * `TmuxManager.resizeWindow()`'s `resize-window -x -y`, which puts the window
* on `manual`.
* *
* Port: N/A (no server) * Port: N/A (no server)
*/ */
@@ -14,7 +15,7 @@ import { afterAll, describe, expect, it } from 'vitest';
import { execFileSync, execSync } from 'node:child_process'; import { execFileSync, execSync } from 'node:child_process';
import { rmSync } from 'node:fs'; import { rmSync } from 'node:fs';
import * as pty from 'node-pty'; 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 = (() => { const hasTmux = (() => {
try { try {
@@ -106,7 +107,7 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => {
if (socketPath.endsWith(`/${socket}`)) rmSync(socketPath, { force: true }); 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(['new-session', '-d', '-s', alpha, '-x', '120', '-y', '40', 'cat']);
run(['set-option', '-g', 'status', 'off']); run(['set-option', '-g', 'status', 'off']);
run(['set-window-option', '-t', alpha, 'window-size', 'manual']); 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 waitFor(() => (tuiTty = ttyOf(tui)) !== '')).toBe(true);
expect(await client.followAttachingClient(alpha)).toBe(true); expect(await client.followAttachingClient(alpha)).toBe(true);
expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true); expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true);
expect(hooks()).toContain(TUI_FOLLOW_TYPING_HOOK); for (const name of Object.keys(TUI_FOLLOW_HOOKS)) expect(hooks()).toContain(name);
// The closed form, which disarm and re-arm match on. expect(run(['show-options', '-t', alpha])).toContain(`${TUI_FOLLOW_OWNER} ${tuiTty}`);
expect(hooks()).toContain(`#{client_tty},${tuiTty}}`); // Set on the session, not the server: no other session gets them.
// Set on the session, not the server: no other session gets it. expect(run(['show-hooks', '-g'])).not.toContain('[91]');
expect(run(['show-hooks', '-g'])).not.toContain(TUI_FOLLOW_TYPING_HOOK);
expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true); 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); const browser = attach(60, 30);
expect(await waitFor(() => ttyOf(browser) !== '')).toBe(true); expect(await waitFor(() => ttyOf(browser) !== '')).toBe(true);
run(['resize-window', '-t', alpha, '-x', '60', '-y', '30']); await browserResize(browser, 61, 30);
expect(windowSize()).toBe('60x30 manual'); expect(windowSize()).toBe('61x30 latest');
// Typing in the browser tab is Codeman's business, not the hook's. // The bug: without the hooks the window stayed 61x30 manual here, and
browser.write('b'); // typing in the terminal changed nothing for the rest of the attach.
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'); tui.write('a');
expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true); expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true);
// Resizing the TUI terminal is using it too: tmux makes the resized client // A browser opening a session sends a FORCED resize at its current size.
// the latest one, so the hook fires without a keystroke (measured on 3.8). // Its pty does not change, so tmux keeps the terminal as the latest client
await browserResize(browser, 62, 30); // and the window stays where the user is typing.
expect(windowSize()).toBe('62x30 manual'); await browserResize(browser, 61, 30);
tui.resize(150, 45); expect(windowSize()).toBe('200x50 latest');
expect(await waitFor(() => windowSize() === '150x45 latest')).toBe(true);
// The browser resizing its client makes THAT client the latest one, so // Typing in the browser tab gives the window to the tab...
// the TUI's next keystroke is a change of client and fires the hook again. browser.write('b');
await browserResize(browser, 62, 31); expect(await waitFor(() => windowSize() === '61x30 latest')).toBe(true);
expect(windowSize()).toBe('62x31 manual'); // ...and typing in the terminal takes it back.
tui.write('a'); 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); expect(await waitFor(() => windowSize() === '150x45 latest')).toBe(true);
}); });
it('disarms only its own hook, and never replaces one of the user', async () => { it('stops when disarmed, leaves a second TUI and the user alone', async () => {
const tuiTty = ttyOf(clients[0]); const [tui, browser] = clients;
const tuiTty = ttyOf(tui);
expect(tuiTty).not.toBe(''); 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`); 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); await client.disarmFollowTyping(alpha, tuiTty);
expect(hooks()).not.toContain(TUI_FOLLOW_TYPING_HOOK); expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER);
// Disarmed means the next keystroke changes nothing. expect(hooks()).not.toContain('[91]');
await browserResize(clients[1], 64, 30); // Disarmed: Codeman's resize pins the window again, and typing changes nothing.
clients[0].write('a'); await browserResize(browser, 64, 30);
expect(windowSize()).toBe('64x30 manual');
tui.write('a');
await new Promise((resolve) => setTimeout(resolve, 300)); await new Promise((resolve) => setTimeout(resolve, 300));
expect(windowSize()).toBe('64x30 manual'); expect(windowSize()).toBe('64x30 manual');
// A hook of the user's own at that index is never overwritten. // Hooks left without an owner (a removal that failed) do nothing.
run(['set-hook', '-t', alpha, TUI_FOLLOW_TYPING_HOOK, 'display-message mine']); 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(await client.armFollowTyping(alpha, tuiTty)).toBe(false);
expect(hooks()).toContain('display-message mine'); expect(hooks()).toContain('display-message mine');
await client.disarmFollowTyping(alpha, tuiTty); expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER);
expect(hooks()).toContain('display-message mine'); run(['set-hook', '-u', '-t', alpha, 'after-resize-window[91]']);
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. // A leaked owner (a TUI killed mid-attach) is swept once its client is gone.
expect(await client.armFollowTyping(alpha, `${tuiTty}1`)).toBe(true); 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(await client.armFollowTyping(alpha, tuiTty)).toBe(true);
expect(hooks()).toContain(`#{client_tty},${tuiTty}}`); expect(await client.clearLeakedFollowTyping(null)).toBe(0);
expect(hooks()).not.toContain(`#{client_tty},${tuiTty}1}`); expect(run(['show-options', '-t', alpha])).toContain(`${TUI_FOLLOW_OWNER} ${tuiTty}`);
}); });
}); });