mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
fix(tui): sweep follow-typing hooks a killed TUI left behind
A terminal that dies while attached (closed window, dropped SSH) never reaches restore(), so its client-active[91] hooks stayed on the sessions. TUI startup now removes ours whose tty has no live tmux client, next to the leaked-banner sweep. The TUI's own tty is never swept: the sweep is fire-and-forget, and an early Enter can arm that hook before the attach client exists. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ba61cfe4e6
commit
d387cf8cdb
4 files changed
+96
-1
No files matched your search
@@ -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 `<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 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
|
||||
|
||||
### Reverse-proxy base path
|
||||
|
||||
|
||||
@@ -1278,6 +1278,7 @@ class TuiApp {
|
||||
// Fire and forget: a bar stranded by a previous run is cosmetic, so it must
|
||||
// never delay the first frame or fail a start.
|
||||
void this.client.clearLeakedAttachBanners().catch(() => undefined);
|
||||
void this.client.clearLeakedFollowTyping().catch(() => undefined);
|
||||
|
||||
return new Promise<number>((resolve) => {
|
||||
this.resolveExit = resolve;
|
||||
|
||||
@@ -1457,6 +1457,53 @@ export class TuiClient {
|
||||
return cleared;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop `client-active[91]` hooks a previous TUI never got to remove.
|
||||
*
|
||||
* Same leak as the banners above: a terminal that dies while attached never
|
||||
* reaches `restore()`. A leaked hook acts only for its tty, so it is harmless
|
||||
* until a pty reuses that number, and then it hands a window to whatever
|
||||
* client got it. This sweep removes ours whose tty has no live tmux client.
|
||||
*
|
||||
* ⚠️ `ownTty` is never swept. The sweep runs fire-and-forget at startup, and
|
||||
* an Enter pressed before it finishes arms this terminal's hook before this
|
||||
* terminal is a tmux client, so the client listing cannot vouch for it yet.
|
||||
* A second TUI mid-attach is a live client and is left alone the same way.
|
||||
*/
|
||||
async clearLeakedFollowTyping(ownTty: string | null = readControllingTty()): Promise<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> {
|
||||
try {
|
||||
await this.exec('tmux', ['-L', this.socket, 'set-option', ...args]);
|
||||
|
||||
@@ -897,6 +897,53 @@ describe('TuiClient.clearLeakedAttachBanners', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TuiClient.clearLeakedFollowTyping', () => {
|
||||
const ours = (tty: string): string => `${TUI_FOLLOW_TYPING_HOOK} ${tuiFollowTypingHook(tty)}`;
|
||||
|
||||
function sweeper(hooks: Record<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', () => {
|
||||
// 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
|
||||
|
||||
Reference in new issue
Block a user