diff --git a/.changeset/tmux-one-binding-list-keys.md b/.changeset/tmux-one-binding-list-keys.md new file mode 100644 index 00000000..10605ac6 --- /dev/null +++ b/.changeset/tmux-one-binding-list-keys.md @@ -0,0 +1,5 @@ +--- +'aicodeman': patch +--- + +A tmux built from master (`next-3.7`) prints nothing for `list-keys -T prefix` when the prefix table holds exactly one binding, which is the shape Codeman reduces it to. Codeman then reset the already reduced table on every session create, and `codeman tui` read a bound key as free, so it could claim a key the user relies on. Both now read a blank answer from the full `list-keys` listing. tmux 3.4 is unchanged. diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index e17a089b..7d8c5970 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. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. +**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): a tmux built from master (`next-3.7`) prints nothing for `list-keys -T ` when the table holds exactly one binding, which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. ### Reverse-proxy base path diff --git a/src/tmux-prefix-table.ts b/src/tmux-prefix-table.ts index 3af1d7da..3e452179 100644 --- a/src/tmux-prefix-table.ts +++ b/src/tmux-prefix-table.ts @@ -153,6 +153,16 @@ export function restrictTmuxPrefixTable(tmux: string, run: TmuxRunner = defaultR let listing: string | null; try { listing = run(`${tmux} list-keys -T prefix`); + // ⚠️ Some tmux builds (a `next-3.7` development build) print NOTHING for + // `list-keys -T prefix` when the table holds exactly one binding, which is the + // shape this function leaves behind: read blank as "ask the full listing" and keep + // only its prefix-table lines, or every call would reset an already-reduced table. + if (!listing.trim()) { + listing = run(`${tmux} list-keys`) + .split('\n') + .filter((line) => PREFIX_LINE.test(line.trim())) + .join('\n'); + } } catch { listing = null; // an empty table makes list-keys fail on some tmux builds } diff --git a/src/tui/tui-client.ts b/src/tui/tui-client.ts index dcfa0efc..7f72070a 100644 --- a/src/tui/tui-client.ts +++ b/src/tui/tui-client.ts @@ -991,6 +991,19 @@ export class TuiClient { return null; } + /** + * One key table as `list-keys` prints it. ⚠️ Some tmux builds (seen on a `next-3.7` + * development build) print NOTHING for `list-keys -T
` when the table holds + * exactly one binding, which is the shape Codeman reduces the prefix table to. So a + * blank answer is retried as the full listing: every line there names its table, + * and both parsers already filter on it. + */ + private async listKeyTable(table: TuiKeyTable): Promise { + const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]); + if (stdout.trim()) return stdout; + return (await this.exec('tmux', ['-L', this.socket, 'list-keys'])).stdout; + } + /** * The key that detaches, straight from tmux's own key table. Key tables are * server-global, so unlike the prefix this takes no session. A failure is @@ -998,8 +1011,7 @@ export class TuiClient { */ async readDetachKey(): Promise { try { - const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', 'prefix']); - return parseDetachKey(stdout); + return parseDetachKey(await this.listKeyTable('prefix')); } catch { return null; } @@ -1012,8 +1024,7 @@ export class TuiClient { */ async readPrefixBinding(key: string, table: TuiKeyTable = 'prefix'): Promise { try { - const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]); - return parsePrefixBinding(stdout, key, table); + return parsePrefixBinding(await this.listKeyTable(table), key, table); } catch { return null; } diff --git a/test/tmux-prefix-table.test.ts b/test/tmux-prefix-table.test.ts index 6d497f12..472a4e9b 100644 --- a/test/tmux-prefix-table.test.ts +++ b/test/tmux-prefix-table.test.ts @@ -115,6 +115,32 @@ describe('restrictTmuxPrefixTable (recorded commands)', () => { expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(false); expect(tmux.calls.filter((c) => c.includes('bind-key'))).toEqual([]); }); + + it('reads a one-binding table from the full listing when `list-keys -T prefix` prints nothing', () => { + // A tmux `next-3.7` build lists a table holding exactly one binding as nothing at + // all. The reduced table must still read as reduced, or every call resets it. + const tmux = fakeTmux({ + 'show-options -gv prefix': 'C-b\n', + 'list-keys -T prefix': '', + 'list-keys': + 'bind-key -T copy-mode C-a send-keys -X start-of-line\n' + + 'bind-key -T prefix C-b send-prefix\n' + + 'bind-key -T root F1 detach-client\n', + }); + expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(false); + expect(tmux.calls).toContain(`tmux -L 'codeman' list-keys`); + expect(tmux.calls.filter((c) => c.includes('bind-key') || c.includes('unbind-key'))).toEqual([]); + }); + + it('still resets when the full listing shows a stock prefix binding', () => { + const tmux = fakeTmux({ + 'show-options -gv prefix': 'C-b\n', + 'list-keys -T prefix': '', + 'list-keys': 'bind-key -T prefix ) switch-client -n\n', + }); + expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(true); + expect(tmux.calls).toContain(`tmux -L 'codeman' unbind-key -a -T prefix`); + }); }); const hasTmux = (() => { @@ -126,12 +152,29 @@ const hasTmux = (() => { } })(); +/** + * One key table as `list-keys -T
` prints it. Some tmux builds (a `next-3.7` + * development build) print NOTHING there when the table holds exactly one binding, + * which is the shape every reset in this file produces, so a blank answer is read from + * the full listing instead, its padding folded to the `-T
` form. + */ +function listKeyTable(base: string, table: string): string { + const run = (cmd: string): string => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); + const direct = run(`${base} list-keys -T ${table}`); + if (direct.trim()) return direct; + return run(`${base} list-keys`) + .split('\n') + .filter((line) => new RegExp(`^bind-key\\s+(?:-\\S+\\s+)*?-T\\s+${table}\\s`).test(line.trim())) + .map((line) => line.trim().replace(/-T\s+(\S+)\s+/, '-T $1 ')) + .join('\n'); +} + describe.skipIf(!hasTmux)('restrictTmuxPrefixTable against a real tmux (private socket)', () => { // Throwaway server, never Codeman's socket; -f /dev/null keeps the user's config out. const socket = `codeman-prefix-test-${process.pid}`; const tmux = `tmux -L ${socket} -f /dev/null`; const run = (cmd: string): string => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); - const keys = (table: string) => run(`${tmux} list-keys -T ${table}`); + const keys = (table: string) => listKeyTable(tmux, table); let client: pty.IPty | null = null; /** The session the attach client is looking at right now. */ @@ -275,7 +318,8 @@ describe.skipIf(!hasTmux)('restrictTmuxPrefixTable against a real tmux (private run(`${tmux} set-option -g prefix 'C-\\'`); try { expect(restrictTmuxPrefixTable(tmux, run)).toBe(true); - expect(keys('prefix')).toMatch(/-T prefix C-\\\\\s+send-prefix/); + // `list-keys -T` escapes the key (`C-\\`); the full listing some builds fall back to does not. + expect(keys('prefix')).toMatch(/-T prefix C-\\(?:\\)?\s+send-prefix/); expect(restrictTmuxPrefixTable(tmux, run)).toBe(false); } finally { run(`${tmux} set-option -g prefix C-b`); @@ -345,7 +389,7 @@ describe.skipIf(!hasTmux)('nested Docker/remote tmux prefix table (private socke it('after the nested reset, Ctrl+Q ), s and w leave the client, and Ctrl+Q Ctrl+Q reaches the pane', async () => { for (const command of nestedPrefixTableResetCommands()) run(`${tmux} ${command}`); - const prefix = run(`${tmux} list-keys -T prefix`) + const prefix = listKeyTable(tmux, 'prefix') .split('\n') .filter((line) => line.trim()); expect(prefix).toEqual([expect.stringMatching(/-T prefix C-q\s+send-prefix$/)]); @@ -381,7 +425,7 @@ describe.skipIf(!hasTmux)('nested Docker/remote tmux prefix table (private socke ].join(' \\; '); try { run(`${base} -f ${config} ${chain}`); - const prefix = run(`${base} list-keys -T prefix`) + const prefix = listKeyTable(base, 'prefix') .split('\n') .filter((line) => line.trim()); expect(prefix).toEqual([expect.stringMatching(/-T prefix C-q\s+send-prefix$/)]); diff --git a/test/tui/tui-client.test.ts b/test/tui/tui-client.test.ts index ce1c39d1..1239f937 100644 --- a/test/tui/tui-client.test.ts +++ b/test/tui/tui-client.test.ts @@ -1015,3 +1015,35 @@ describe('resumeSession', () => { expect(recorded).toHaveLength(1); }); }); + +describe('TuiClient key-table reads on a tmux that lists a one-binding table as nothing', () => { + // A tmux `next-3.7` build prints nothing for `list-keys -T prefix` when the table + // holds exactly one binding, which is how Codeman leaves it. Reading that as "free" + // would let the TUI claim a key the user has bound. + const fullListing = + 'bind-key -T copy-mode C-a send-keys -X start-of-line\n' + + 'bind-key -T prefix C-b send-prefix\n' + + 'bind-key -T root F1 detach-client\n'; + function client(direct: string) { + const calls: string[][] = []; + const exec = async (_file: string, args: readonly string[]) => { + calls.push([...args]); + return { stdout: args.includes('-T') ? direct : fullListing, stderr: '' }; + }; + return { tui: new TuiClient({ socket: 'cod563', exec }), calls }; + } + + it('falls back to the full listing when the table answer is blank', async () => { + const { tui, calls } = client(''); + expect(await tui.readPrefixBinding('C-b')).toBe('send-prefix'); + expect(await tui.readPrefixBinding('F1', 'root')).toBe('detach-client'); + expect(await tui.readPrefixBinding('x')).toBeNull(); + expect(calls.some((args) => args.length === 3 && args[2] === 'list-keys')).toBe(true); + }); + + it('keeps the table answer when there is one, with no second call', async () => { + const { tui, calls } = client('bind-key -T prefix d detach-client\n'); + expect(await tui.readDetachKey()).toBe('d'); + expect(calls).toEqual([['-L', 'cod563', 'list-keys', '-T', 'prefix']]); + }); +});