Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(tmux): opt-in lead-pane width for Claude Code agent teams (#119)
enes0ef10b636535
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 6e9190e78..2680cd9b5 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -102,6 +102,7 @@ import {modelGatewayEnv,tmuxUpdateEnvironmentLine} from '../shared/agents/model-gateway'+import { leadPaneHookLines } from '../shared/tmux-lead-pane'import {remoteSessionEnvAvailable,remoteSessionEnvPath,@@ -246,7 +247,10 @@ function runWithStdin(file: string, args: readonly string[], input: string): Pro// payload with `terminal-features`). The renderer's OSC 52 handler writes the system clipboard, so// this is the copy path on EVERY platform and over SSH — no `pbcopy` pipe (that was macOS-only,// and half of why copying was broken).-export function tmuxConf(scrollback: number): string {+// LEAD-PANE WIDTH (issue #119): `leadPaneWidth` (settings.tmuxLeadPaneWidth) is OPT-IN and 0 by+// default — `leadPaneHookLines` returns '' then, so the default conf is byte-identical to the+// pre-feature output (pinned in tmux-conf.test.ts). See shared/tmux-lead-pane.ts for the story.+export function tmuxConf(scrollback: number, leadPaneWidth: number = 0): string {return `# auto-generated by node-terminal — do not editset -g status offset -g mouse on@@ -285,7 +289,7 @@ bind -T copy-mode DoubleClick1Pane send-keys -X select-word \\; send-keys -Xbind -T copy-mode-vi DoubleClick1Pane send-keys -X select-word \\; send-keys -X copy-pipe-and-cancelbind -T copy-mode TripleClick1Pane send-keys -X select-line \\; send-keys -X copy-pipe-and-cancelbind -T copy-mode-vi TripleClick1Pane send-keys -X select-line \\; send-keys -X copy-pipe-and-cancel-`+${leadPaneHookLines(leadPaneWidth)}`}/**@@ -1516,7 +1520,8 @@ export class PtyManager {if (!found) returnthis.confPath = path.join(platform().userDataDir, 'tmux.conf')try {- fs.writeFileSync(this.confPath, tmuxConf(this.getSettings().tmuxScrollback))+ const s = this.getSettings()+ fs.writeFileSync(this.confPath, tmuxConf(s.tmuxScrollback, s.tmuxLeadPaneWidth))} catch {// If we can't write the config, stay on the plain-shell fallback.returndiff --git a/src/core/tmux-conf.test.ts b/src/core/tmux-conf.test.tsindex 23ccded89..fcf470781 100644--- a/src/core/tmux-conf.test.ts+++ b/src/core/tmux-conf.test.ts@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest'import { tmuxConf } from './pty-manager'+import { leadPaneHookLines } from '../shared/tmux-lead-pane'describe('tmuxConf', () => {const c = tmuxConf(50000)@@ -54,4 +55,22 @@ describe('tmuxConf', () => {expect(tmuxConf(10)).toContain('set -g history-limit 1000')expect(c).toContain('set -g history-limit 50000')})++ it('lead-pane width OFF (default/0/invalid) is byte-identical and carries no set-hook (issue #119)', () => {+ // The opt-in guarantee enes set for the feature: with the setting off, the generated conf is+ // bit-for-bit the pre-feature output — nodeterm ships no tmux hooks unless asked to.+ expect(tmuxConf(50000, 0)).toBe(c)+ expect(tmuxConf(50000, NaN)).toBe(c)+ expect(tmuxConf(50000, -3)).toBe(c)+ expect(c).not.toContain('set-hook')+ })++ it('lead-pane width ON only APPENDS the shared guarded hook pair — nothing above changes', () => {+ const on = tmuxConf(50000, 72)+ expect(on.startsWith(c)).toBe(true)+ expect(on).toContain(leadPaneHookLines(72))+ // Same builder as remoteTmuxConf, so the local and SSH sockets cannot drift.+ expect(on).toContain('set-hook -g after-resize-pane')+ expect(on).toContain('set-hook -g after-split-window')+ })})diff --git a/src/core/tmux-lead-pane.realtmux.test.ts b/src/core/tmux-lead-pane.realtmux.test.tsnew file mode 100644index 000000000..d5137d049--- /dev/null+++ b/src/core/tmux-lead-pane.realtmux.test.ts@@ -0,0 +1,150 @@+// LEAD-PANE WIDTH HOOKS (issue #119), PROVEN AGAINST A REAL TMUX.+//+// Unit tests pin what `tmuxConf`/`remoteTmuxConf` emit; whether tmux PARSES the hook lines and+// whether the guarded pair actually (a) restores a squeezed lead, (b) self-terminates, and+// (c) respects a manual width at/above the guard threshold is a property of tmux — so it is+// measured here, on this tmux, with the EXACT conf text `tmuxConf()` ships. This suite is what+// caught the string-compare trap: the issue reporter's original split hook used plain+// `#{<:pane_width,window_width}`, and on tmux 3.4 that is a STRING compare (#{<:59,200} = 0), so+// the hook silently never fired — the shipped conf uses the numeric `e|<` form instead.+//+// The Claude Code geometry being simulated is the one the reporter traced in the 2.1.227 binary:+// first teammate `split-window -h -l 70%`, later spawns `select-layout main-vertical` ++// `resize-pane -t <lead> -x 30%`.+//+// Each scenario runs on its OWN socket (`-f` is read only at server start, and a `new-session`+// racing a dying server's socket silently attaches WITHOUT the conf — measured: the hooks were+// absent and every assertion chased a phantom).+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import path from 'path'+import { tmuxConf } from './pty-manager'+import { makeTmuxTmpdir } from './tmux-test-socket'++const SOCKET_OFF = `nt-lead0-${process.pid}`+const SOCKET_ON = `nt-lead1-${process.pid}`+// Window geometry the assertions are computed against (set via new-session -x/-y).+const W = 200++let tmp: string+let tmuxOk = false++function tmux(socket: string, args: string[]): string {+ return execFileSync('tmux', ['-L', socket, ...args], {+ env: { ...process.env, TMUX_TMPDIR: tmp },+ stdio: ['ignore', 'pipe', 'pipe']+ }).toString()+}++/** Start a fresh server from `conf` (a `-f` file is read once, at server start). */+function startServer(socket: string, conf: string, session: string): void {+ const file = path.join(tmp, `${session}.conf`)+ fs.writeFileSync(file, conf)+ tmux(socket, [+ '-f', file, 'new-session', '-d', '-x', String(W), '-y', '50', '-s', session, 'sleep 120'+ ])+}++function killServer(socket: string): void {+ try {+ tmux(socket, ['kill-server'])+ } catch {+ /* no server */+ }+}++function leadWidth(socket: string, session: string): number {+ return parseInt(+ tmux(socket, ['display-message', '-p', '-t', `${session}:0.0`, '#{pane_width}']),+ 10+ )+}++/** Hooks run inside the server right after the triggering command; poll a beat for the settle. */+async function waitForWidth(+ socket: string,+ session: string,+ ok: (w: number) => boolean,+ ms = 3000+): Promise<number> {+ const t0 = Date.now()+ for (;;) {+ const w = leadWidth(socket, session)+ if (ok(w)) return w+ if (Date.now() - t0 > ms) return w+ await new Promise((r) => setTimeout(r, 50))+ }+}++beforeAll(() => {+ try {+ execFileSync('tmux', ['-V'], { stdio: 'ignore' })+ tmuxOk = true+ } catch {+ return // no tmux on this host — every test below self-skips+ }+ tmp = makeTmuxTmpdir('ntlead-', SOCKET_ON)+})++afterAll(() => {+ if (!tmuxOk) return+ killServer(SOCKET_OFF)+ killServer(SOCKET_ON)+ fs.rmSync(tmp, { recursive: true, force: true })+})++describe('setting OFF — the default conf really ships no hooks', () => {+ it('loads cleanly, configures zero hooks, and leaves the 70/30 squeeze alone (CC default behavior)', async () => {+ if (!tmuxOk) return+ startServer(SOCKET_OFF, tmuxConf(2000), 'off')+ // `show-hooks -g` prints every hook NAME even when unset — a configured entry is `name[0] …`.+ expect(tmux(SOCKET_OFF, ['show-hooks', '-g'])).not.toMatch(/\[\d+\]/)+ // CC's first-teammate split squeezes the lead to ~30% and NOTHING corrects it.+ tmux(SOCKET_OFF, ['split-window', '-h', '-l', '70%', '-t', 'off', 'sleep 120'])+ await new Promise((r) => setTimeout(r, 300))+ expect(leadWidth(SOCKET_OFF, 'off')).toBeLessThan(W / 2)+ killServer(SOCKET_OFF)+ })+})++describe('setting ON — the guarded hook pair, measured', () => {+ it('the generated conf parses and BOTH hooks are configured (new-session under -f)', () => {+ if (!tmuxOk) return+ startServer(SOCKET_ON, tmuxConf(2000, 72), 'on')+ const hooks = tmux(SOCKET_ON, ['show-hooks', '-g'])+ expect(hooks).toMatch(/after-resize-pane\[0\] if-shell/)+ expect(hooks).toMatch(/after-split-window\[0\] if-shell/)+ })++ it("CC's first teammate (split-window -h -l 70%) → the lead is nudged back to 72%", async () => {+ if (!tmuxOk) return+ tmux(SOCKET_ON, ['split-window', '-h', '-l', '70%', '-t', 'on', 'sleep 120'])+ // Without the hook the lead sits at ~59 of 200; the after-split-window hook restores 72%.+ const w = await waitForWidth(SOCKET_ON, 'on', (w) => w >= 0.7 * W)+ expect(w).toBeGreaterThanOrEqual(0.7 * W)+ expect(w).toBeLessThanOrEqual(0.74 * W)+ })++ it("CC's later rebalance (main-vertical + resize-pane -x 30%) → restored again; no resize loop", async () => {+ if (!tmuxOk) return+ tmux(SOCKET_ON, ['split-window', '-h', '-t', 'on', 'sleep 120']) // 3 panes: CC rebalances from here+ tmux(SOCKET_ON, ['select-layout', '-t', 'on', 'main-vertical'])+ tmux(SOCKET_ON, ['resize-pane', '-t', 'on:0.0', '-x', '30%']) // the clobber the issue is about+ const w = await waitForWidth(SOCKET_ON, 'on', (w) => w >= 0.7 * W)+ expect(w).toBeGreaterThanOrEqual(0.7 * W)+ // Self-termination: the hook's own resize fired the hook again and it no-opped (lead >= 60%).+ // A loop would keep the server busy re-resizing; a second stable read proves it settled.+ await new Promise((r) => setTimeout(r, 300))+ expect(leadWidth(SOCKET_ON, 'on')).toBe(w)+ })++ it('a manual width at/above the guard threshold is RESPECTED (the guard is a no-op, not a snap-back)', async () => {+ if (!tmuxOk) return+ // Guard for 72% is 60% (120 of 200). 130 >= 120, so the after-resize-pane hook must not touch it.+ tmux(SOCKET_ON, ['resize-pane', '-t', 'on:0.0', '-x', '130'])+ await new Promise((r) => setTimeout(r, 300))+ expect(leadWidth(SOCKET_ON, 'on')).toBe(130)+ killServer(SOCKET_ON)+ })+})diff --git a/src/main/index.ts b/src/main/index.tsindex 69cd84334..04b97c266 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -3464,7 +3464,10 @@ app.whenReady().then(async () => {// path, and the result is cached (the artifact never changes within an app run). A missing// artifact resolves to '' — `installRemoteCodexRuntime` treats an empty bundle as "no runtime"// and never fails a plain SSH connect over it.- loadCodexRelayBundle+ loadCodexRelayBundle,+ // Lead-pane width (issue #119) for the remote tmux conf, read at connect time so the host+ // carries the value the user last saved. 0 (the default) keeps the conf byte-identical.+ () => settingsStore.get().tmuxLeadPaneWidth)// Wake-from-sleep: re-validate every SSH master NOW instead of letting ServerAlive discover the// dead TCP ~60s later — until it does, every remote terminal looks alive and is dead (no echo,diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 866ea706a..7b2d6b250 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -85,6 +85,10 @@ interface Runners {* Codex runtime rather than a crash. Undefined keeps every non-Codex SSH path unchanged. */codexRelaySource?: () => Promise<string>onStatus: (e: SshProjectStatusEvent) => void+ /** Current `settings.tmuxLeadPaneWidth` (issue #119), read at connect time so the value the+ * remote conf carries is the one the user last saved. Optional: absent (tests, older callers)+ * ⇒ 0 ⇒ the pre-feature conf, byte-identical. Sanitized inside `leadPaneHookLines`. */+ leadPaneWidth?: () => number/** Delays between claude-probe retries after a FAILED attempt (claude not found). Injected so* tests don't wait on real backoff; production uses PROBE_RETRY_DELAYS_MS. */probeRetryDelaysMs?: number[]@@ -691,7 +695,9 @@ export class SshProjectManager {const confWrite = remoteAtomicWrite(confPath)const w = await this.r.run(childArgs(conn, controlPath, confWrite.command),- remoteTmuxConf(50000)+ // Lead-pane width applies on the host too: an agent team spawned in a remote+ // session squeezes the lead exactly like a local one. 0/absent ⇒ pre-feature conf.+ remoteTmuxConf(50000, this.r.leadPaneWidth?.() ?? 0))if (w.code === 0) {// source-file is best-effort (pushes options into a warm server); ignore its result.@@ -2196,7 +2202,10 @@ export function initSshProject(* Linux host. Injected by the caller (main/index.ts) so this module reads no build artifact* itself. Undefined ⇒ no managed Codex runtime is installed, and every non-Codex path is* unchanged (Server Edition passes nothing today — see the PR's I2 decision). */- codexRelaySource?: () => Promise<string>+ codexRelaySource?: () => Promise<string>,+ /** Current `settings.tmuxLeadPaneWidth` for the remote tmux conf (issue #119). Injected by+ * main/index.ts because the settings store lives there; absent ⇒ 0 ⇒ pre-feature conf. */+ leadPaneWidth?: () => number): SshProjectManager {const ssh = sshBin()const scp = scpBin()@@ -2294,6 +2303,7 @@ export function initSshProject(}),getHook: () => ({ port: hookServer.getPort(), token: hookServer.getToken(), version: hookServer.getVersion() }),codexRelaySource,+ leadPaneWidth,// Per-node identity for REMOTE nodes. Both come from the same module the local materialiser// uses, so one canvas cannot be judged by two different rules depending on where it runs.nodeIdsForProject: (projectId) => nodeIdsForCanvas(projectId),diff --git a/src/renderer/components/settings/sections/TmuxSection.tsx b/src/renderer/components/settings/sections/TmuxSection.tsxindex 1041d2c66..b14267917 100644--- a/src/renderer/components/settings/sections/TmuxSection.tsx+++ b/src/renderer/components/settings/sections/TmuxSection.tsx@@ -4,6 +4,11 @@ import { SearchableRow } from '../SearchableRow'import { FieldRow } from '../FieldRow'import { Switch } from '@renderer/ui/Switch'import { NumberField } from '@renderer/ui/NumberField'+import {+ LEAD_PANE_WIDTH_DEFAULT,+ LEAD_PANE_WIDTH_MAX,+ LEAD_PANE_WIDTH_MIN+} from '@shared/tmux-lead-pane'const ROWS = {enabled: {@@ -11,6 +16,10 @@ const ROWS = {keywords: ['tmux', 'persistent', 'session', 'continuity']},scrollback: { title: 'Scrollback lines', keywords: ['tmux', 'scrollback', 'history', 'lines'] },+ leadPane: {+ title: 'Keep lead pane wide (agent teams)',+ keywords: ['lead', 'pane', 'width', 'agent', 'team', 'teammates', 'split', 'claude', 'resize']+ },offscreen: {title: 'Release offscreen terminals',keywords: ['offscreen', 'memory', 'ram', 'release', 'reattach', 'idle', 'minutes']@@ -55,6 +64,39 @@ export function TmuxSection({ isActive }: { isActive: boolean }): React.JSX.Elem}/></SearchableRow>+ <SearchableRow {...ROWS.leadPane}>+ <FieldRow+ label="Keep lead pane wide (agent teams)"+ description={+ 'Claude Code agent teams re-apply a hardcoded 70/30 tmux split on every teammate spawn, squeezing the pane you type into. ' ++ 'When on, guarded tmux hooks keep the lead pane at the chosen % of the node width (40–90), locally and on SSH hosts (at next connect). ' ++ 'Side effect: a manual 50/50 split in a plain terminal is nudged to the same width. ' ++ 'Turning it off leaves a running tmux server’s hooks in place until that server exits (close all terminals, or tmux -L node-terminal kill-server).'+ }+ control={+ <div className="flex items-center gap-2">+ {settings.tmuxLeadPaneWidth > 0 ? (+ <NumberField+ value={settings.tmuxLeadPaneWidth}+ min={LEAD_PANE_WIDTH_MIN}+ max={LEAD_PANE_WIDTH_MAX}+ step={1}+ ariaLabel="Lead pane width (%)"+ // Raw value stored; out-of-range hand edits are re-validated where the conf is+ // generated (sanitizeLeadPaneWidth), so mid-typing values never snap under the+ // user's cursor.+ onChange={(v) => update({ tmuxLeadPaneWidth: Number.isFinite(v) ? v : 0 })}+ />+ ) : null}+ <Switch+ checked={settings.tmuxLeadPaneWidth > 0}+ onChange={(v) => update({ tmuxLeadPaneWidth: v ? LEAD_PANE_WIDTH_DEFAULT : 0 })}+ ariaLabel="Keep lead pane wide"+ />+ </div>+ }+ />+ </SearchableRow><SearchableRow {...ROWS.offscreen}><FieldRowlabel="Release offscreen terminals"diff --git a/src/shared/ssh.test.ts b/src/shared/ssh.test.tsindex b971798b0..b66a69d23 100644--- a/src/shared/ssh.test.ts+++ b/src/shared/ssh.test.ts@@ -13,6 +13,7 @@ import {sshConnectionIdForProject,sshHostKey} from './ssh'+import { leadPaneHookLines } from './tmux-lead-pane'describe('sshHostKey', () => {it('is user@host', () => {@@ -284,6 +285,18 @@ describe('remoteTmuxConf', () => {expect(remoteTmuxConf(10)).toContain('set -g history-limit 1000')expect(remoteTmuxConf(50000)).toContain('set -g history-limit 50000')})+ it('lead-pane width OFF (default/0/invalid) is byte-identical and carries no set-hook (issue #119)', () => {+ // The opt-in guarantee: nodeterm ships no tmux hooks unless the user turned the setting on,+ // and the off path must be bit-for-bit the pre-feature conf.+ expect(remoteTmuxConf(50000, 0)).toBe(c)+ expect(remoteTmuxConf(50000, NaN)).toBe(c)+ expect(c).not.toContain('set-hook')+ })+ it('lead-pane width ON only APPENDS the shared guarded hook pair', () => {+ const on = remoteTmuxConf(50000, 72)+ expect(on.startsWith(c)).toBe(true)+ expect(on).toContain(leadPaneHookLines(72))+ })})describe('remoteTmuxCommand confPath', () => {diff --git a/src/shared/ssh.ts b/src/shared/ssh.tsindex 291fa9834..4e936c48d 100644--- a/src/shared/ssh.ts+++ b/src/shared/ssh.ts@@ -1,4 +1,5 @@import { tmuxUpdateEnvironmentLine } from './agents/model-gateway'+import { leadPaneHookLines } from './tmux-lead-pane'/*** Pure helpers for launching the system `ssh` binary as a terminal session program.* No Electron, no node-pty — unit-testable in isolation.@@ -271,7 +272,10 @@ export function quoteRemotePath(p: string): string {* only thing that ever made copying work over SSH. It needs `terminal-features ",*:clipboard"`:* the `terminal-overrides ',xterm*:Ms=...'` entry this config used to carry emits NOTHING on* tmux 3.2+ (measured), so it is gone — do not add it back. */-export function remoteTmuxConf(scrollback: number): string {+// LEAD-PANE WIDTH (issue #119): same opt-in as the local conf — an agent team spawned on the SSH+// host squeezes the lead pane exactly like a local one, so the setting emits into both configs+// through the ONE shared builder (`leadPaneHookLines`). 0/omitted ⇒ '' ⇒ byte-identical output.+export function remoteTmuxConf(scrollback: number, leadPaneWidth: number = 0): string {return `# auto-generated by node-terminal (remote) — do not editset -g status offset -g mouse on@@ -315,7 +319,7 @@ bind -T copy-mode DoubleClick1Pane send-keys -X select-word \\; send-keys -Xbind -T copy-mode-vi DoubleClick1Pane send-keys -X select-word \\; send-keys -X copy-pipe-and-cancelbind -T copy-mode TripleClick1Pane send-keys -X select-line \\; send-keys -X copy-pipe-and-cancelbind -T copy-mode-vi TripleClick1Pane send-keys -X select-line \\; send-keys -X copy-pipe-and-cancel-`+${leadPaneHookLines(leadPaneWidth)}`}/** Build the remote shell command that attaches-or-creates this node's remote tmux session. */diff --git a/src/shared/tmux-lead-pane.test.ts b/src/shared/tmux-lead-pane.test.tsnew file mode 100644index 000000000..10566e009--- /dev/null+++ b/src/shared/tmux-lead-pane.test.ts@@ -0,0 +1,79 @@+import { describe, it, expect } from 'vitest'++import {+ LEAD_PANE_GUARD_GAP,+ LEAD_PANE_WIDTH_DEFAULT,+ LEAD_PANE_WIDTH_MAX,+ LEAD_PANE_WIDTH_MIN,+ leadPaneHookLines,+ sanitizeLeadPaneWidth+} from './tmux-lead-pane'++describe('sanitizeLeadPaneWidth', () => {+ it('off (0 / negative / non-number / non-finite) sanitizes to 0 — the pre-feature conf', () => {+ // settings.json is hand-editable JSON; anything that is not an unambiguous "on" must degrade+ // to the bare conf, never to a guessed width (same rule as permissionModeFlag).+ expect(sanitizeLeadPaneWidth(0)).toBe(0)+ expect(sanitizeLeadPaneWidth(-5)).toBe(0)+ expect(sanitizeLeadPaneWidth('72')).toBe(0)+ expect(sanitizeLeadPaneWidth(NaN)).toBe(0)+ expect(sanitizeLeadPaneWidth(Infinity)).toBe(0)+ expect(sanitizeLeadPaneWidth(undefined)).toBe(0)+ expect(sanitizeLeadPaneWidth(null)).toBe(0)+ // Forged-object values (the `constructor` class of attack) are not numbers → off.+ expect(sanitizeLeadPaneWidth({ valueOf: () => 72 })).toBe(0)+ })++ it('positive values clamp into [40, 90]; fractions round', () => {+ expect(sanitizeLeadPaneWidth(72)).toBe(72)+ expect(sanitizeLeadPaneWidth(10)).toBe(LEAD_PANE_WIDTH_MIN)+ expect(sanitizeLeadPaneWidth(99)).toBe(LEAD_PANE_WIDTH_MAX)+ expect(sanitizeLeadPaneWidth(72.4)).toBe(72)+ })++ it('the guard stays strictly below the target for every allowed width — the self-termination invariant', () => {+ // The after-resize-pane hook resizes the lead to the target, which fires the hook again; the+ // chain stops ONLY because the lead is then >= the guard threshold. guard >= target would loop.+ for (let w = LEAD_PANE_WIDTH_MIN; w <= LEAD_PANE_WIDTH_MAX; w++) {+ expect(w - LEAD_PANE_GUARD_GAP).toBeGreaterThan(0)+ expect(w - LEAD_PANE_GUARD_GAP).toBeLessThan(w)+ }+ })+})++describe('leadPaneHookLines', () => {+ it("off ⇒ '' exactly — the interpolation site adds nothing, so the conf stays byte-identical", () => {+ expect(leadPaneHookLines(0)).toBe('')+ expect(leadPaneHookLines(undefined)).toBe('')+ expect(leadPaneHookLines('junk')).toBe('')+ })++ it('emits the reporter-tested guarded hook pair with the width and derived guard interpolated', () => {+ const lines = leadPaneHookLines(LEAD_PANE_WIDTH_DEFAULT)+ // The default (72) must reproduce the issue-#119 recipe's numbers: target 72%, guard 60%+ // (the reporter wrote window_width*6/10; we emit the equivalent *60/100).+ expect(lines).toContain(+ `set-hook -g after-resize-pane "if-shell -F -t '{top-left}' '#{e|<:#{pane_width},#{e|/:#{e|*:#{window_width},60},100}}' { resize-pane -t '{top-left}' -x '72%' }"`+ )+ // NOT the reporter's literal `#{<:...}` here: on tmux 3.4 the plain comparison is a STRING+ // compare (#{<:59,200} = 0 — measured), so the split hook must use the numeric e| form.+ expect(lines).toContain(+ `set-hook -g after-split-window "if-shell -F -t '{top-left}' '#{&&:#{==:#{window_panes},2},#{e|<:#{pane_width},#{window_width}}}' { resize-pane -t '{top-left}' -x '72%' }"`+ )+ // Splices cleanly between conf lines.+ expect(lines.endsWith('\n')).toBe(true)+ expect(lines.startsWith('#')).toBe(true)+ })++ it('a non-default width lands in both the guard and the resize target', () => {+ const lines = leadPaneHookLines(80)+ expect(lines).toContain(`#{e|*:#{window_width},${80 - LEAD_PANE_GUARD_GAP}}`)+ expect(lines).toContain("-x '80%'")+ expect(lines).not.toContain("'72%'")+ })++ it('an out-of-range hand edit emits the clamped width, never the raw value', () => {+ expect(leadPaneHookLines(999)).toContain(`-x '${LEAD_PANE_WIDTH_MAX}%'`)+ expect(leadPaneHookLines(1)).toContain(`-x '${LEAD_PANE_WIDTH_MIN}%'`)+ })+})diff --git a/src/shared/tmux-lead-pane.ts b/src/shared/tmux-lead-pane.tsnew file mode 100644index 000000000..72ed27633--- /dev/null+++ b/src/shared/tmux-lead-pane.ts@@ -0,0 +1,78 @@+/**+ * Lead-pane width hooks (issue #119) — the ONE definition both generated tmux configs consume+ * (`tmuxConf` in core/pty-manager.ts and `remoteTmuxConf` in shared/ssh.ts), so the local socket+ * and an SSH host's socket can never drift apart.+ *+ * Why this exists: Claude Code's agent-team tmux backend (traced in the 2.1.227 binary by the+ * issue reporter) hardcodes its geometry — first teammate `split-window -h -l 70%`, every later+ * spawn `select-layout main-vertical` + `resize-pane -t <lead> -x 30%` — and re-applies it on+ * every teammate spawn, so the pane the user actually types into ends up a ~30% column and a+ * manual resize is clobbered seconds later. There is no CC setting for it, and nodeterm owns the+ * tmux server + generated conf, so this is the one place a user preference can live.+ *+ * The mechanism is the reporter's own tested pair of guarded hooks (tmux 3.6a, macOS; re-proven+ * against this repo's tmux in tmux-lead-pane.realtmux.test.ts):+ * - `after-resize-pane`: if the lead ({top-left}) has been squeezed below the guard threshold,+ * resize it back to the target width. SELF-TERMINATING by construction: the hook's own+ * resize-pane fires the same hook again, but by then the lead is at the target (>= guard), the+ * if-shell no-ops, and the chain stops — the guard threshold sitting BELOW the target is what+ * makes that true, so `LEAD_PANE_GUARD_GAP` must stay positive. Do not "simplify" the guard+ * away; it is the part that makes the whole thing safe (no resize loop).+ * - `after-split-window`: covers the single-teammate case (CC only rebalances at 3+ panes) — a+ * fresh side-by-side split that squeezed the lead is nudged to the target. Honest side effect,+ * stated in the Settings row: a manual 50/50 split in a plain terminal node is nudged too.+ *+ * Pane %ids never change across a resize, so CC's teammate tracking (kill/target by %id) is+ * unaffected; if a future CC version changes its layout commands the hooks simply stop firing.+ *+ * OPT-IN, default off: with the setting off both confs are byte-identical to their pre-feature+ * output (pinned in tmux-conf.test.ts / ssh.test.ts) — nodeterm ships no other `set-hook`, and+ * the no-hooks default must stay bit-for-bit unchanged.+ */++/** Bounds for the target width. Below 40% the lead is squeezed anyway (defeats the point) and the+ * derived guard would approach 0; above 90% teammates become unreadable slivers. */+export const LEAD_PANE_WIDTH_MIN = 40+export const LEAD_PANE_WIDTH_MAX = 90+/** Default target when the user just flips the switch — the reporter's field-tested 72%. */+export const LEAD_PANE_WIDTH_DEFAULT = 72+/** Guard threshold = target − gap. 12 reproduces the reporter's tested 60/72 pair and keeps the+ * guard strictly below the target for every allowed width (40 → 28), which is what terminates+ * the resize-hook chain (see the doc comment above). */+export const LEAD_PANE_GUARD_GAP = 12++/**+ * Re-validate the hand-editable setting at the interpolation site (settings.json is user-edited+ * JSON and this number lands inside generated tmux source — same rule as `permissionModeFlag`).+ * Not a number / non-finite / <= 0 ⇒ 0 = off, the bare pre-feature conf. Positive values clamp+ * into [40, 90]: the enable intent is unambiguous, and an out-of-range target would either defeat+ * the guard (too low) or starve the teammates (too high).+ */+export function sanitizeLeadPaneWidth(v: unknown): number {+ if (typeof v !== 'number' || !Number.isFinite(v)) return 0+ const n = Math.round(v)+ if (n <= 0) return 0+ return Math.min(LEAD_PANE_WIDTH_MAX, Math.max(LEAD_PANE_WIDTH_MIN, n))+}++/**+ * The conf lines both `tmuxConf` and `remoteTmuxConf` interpolate. `''` when the setting is off —+ * the interpolation site must add NOTHING of its own around it, so the off path stays+ * byte-identical to the pre-feature conf. When on, the block ends with `\n` so it splices between+ * existing lines cleanly.+ */+export function leadPaneHookLines(widthPct: unknown): string {+ const width = sanitizeLeadPaneWidth(widthPct)+ if (width === 0) return ''+ const guard = width - LEAD_PANE_GUARD_GAP+ return `# Lead-pane width (issue #119, opt-in — see shared/tmux-lead-pane.ts for the full story):+# Claude Code's agent-team backend hardcodes its geometry and re-applies it on every teammate+# spawn, squeezing the lead pane to ~30%. These guarded hooks re-assert the user's target after+# each layout pass. Self-terminating: lead already >= ${guard}% of the window -> no-op, so the+# hook's own resize-pane cannot loop. The guard is load-bearing — do not simplify it away.+# Every comparison is the NUMERIC e| form: measured on tmux 3.4, plain #{<:59,200} answers 0+# (STRING compare — "5" > "2"), which silently killed the reporter's original split hook there.+set-hook -g after-resize-pane "if-shell -F -t '{top-left}' '#{e|<:#{pane_width},#{e|/:#{e|*:#{window_width},${guard}},100}}' { resize-pane -t '{top-left}' -x '${width}%' }"+set-hook -g after-split-window "if-shell -F -t '{top-left}' '#{&&:#{==:#{window_panes},2},#{e|<:#{pane_width},#{window_width}}}' { resize-pane -t '{top-left}' -x '${width}%' }"+`+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex e843095aa..c74cfcf8d 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1260,6 +1260,14 @@ export interface Settings {* renderer. See `resolveTerminalRenderer` (shared/webgl.ts) for the full history. */terminalGpuRendering: 'auto' | 'on' | 'off' | 'shared'tmuxScrollback: number+ /** OPT-IN lead-pane width for Claude Code agent teams (issue #119). 0 = off (default): the+ * generated tmux confs stay byte-identical to their pre-feature output — no `set-hook` at all.+ * 40–90 = emit guarded after-resize-pane / after-split-window hooks (shared/tmux-lead-pane.ts)+ * that keep the lead pane at this % of the node width when CC's team backend re-applies its+ * hardcoded 70/30 split. Hand-editable; re-validated at the conf-generation site+ * (`sanitizeLeadPaneWidth`). Honest side effect while on: a manual 50/50 split in a plain+ * terminal node is nudged to the target too. */+ tmuxLeadPaneWidth: number/** Minutes a terminal may sit fully offscreen before its xterm+PTY client is torn down in* place (tmux keeps the session; re-approach reattaches and redraws). 0 = never. */offscreenTerminalMinutes: number@@ -1471,6 +1479,7 @@ export const DEFAULT_SETTINGS: Settings = {ptyShadowClients: true,terminalGpuRendering: 'auto',tmuxScrollback: 50000,+ tmuxLeadPaneWidth: 0,offscreenTerminalMinutes: 10,commitAgent: 'claude',commitAgentCommand: '',