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(pty): ptyShadowClients kill switch + swap logging
enesedc556325090
diff --git a/src/core/pty-background-write.test.ts b/src/core/pty-background-write.test.tsindex a781bfdc8..ac363dff2 100644--- a/src/core/pty-background-write.test.ts+++ b/src/core/pty-background-write.test.ts@@ -183,6 +183,14 @@ describe('background writes into released sessions', () => {m.registerIpc()return m}+ /** The same manager with one setting flipped — tmux is still installed and still enabled. */+ async function managerWith(patch: Partial<typeof DEFAULT_SETTINGS>) {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager({ controlSpawn: control })+ m.init(() => ({ ...DEFAULT_SETTINGS, ...patch }))+ m.registerIpc()+ return m+ }const create = (clientId: number, persistKey = 'node-1', cols = 80, rows = 24) =>fake.handlers[IPC.ptyCreate](clientId, { cols, rows, persistKey }) as Promise<{sessionId: string@@ -452,6 +460,77 @@ describe('background writes into released sessions', () => {expect(await m.backgroundWrite('node-1', 'ls\n')).toBe(false)expect(control.calls).toHaveLength(0)})++ it('refuses the control-client tiers with ptyShadowClients switched off', async () => {+ const m = await managerWith({ ptyShadowClients: false })+ const { sessionId } = await create(ALICE)+ kill(ALICE, sessionId)++ // The kill switch means what it says: with it off, this process never spawns a `tmux -C` child,+ // so a released node is simply unreachable again — the behavior of the release this mechanism+ // shipped in.+ expect(await m.backgroundWrite('node-1', 'ls\n')).toBe(false)+ expect(control.calls).toHaveLength(0)+ })++ it('still writes into the painter with ptyShadowClients switched off — tier 1 is not a shadow', async () => {+ const m = await managerWith({ ptyShadowClients: false })+ await create(ALICE, 'node-1')++ // Tier 1 is the session's own pty, which exists with or without this feature. Gating it would+ // turn the kill switch into "background writes stop working", which is a different setting.+ expect(await m.backgroundWrite('node-1', 'ls\n')).toBe(true)+ expect(spawned[0].writes).toEqual(['ls\n'])+ expect(control.calls).toHaveLength(0)+ })++ it('falls through to the shared client when the node’s shadow is dead but still indexed', async () => {+ const m = await tmuxManager()+ await release(ALICE, 'node-1')+ const shadow = await m.shadowAttach('node-1')+ // A holder retiring the client it was handed. `dispose()` is SILENT by design (it fires no+ // `onExit`), so nothing evicted the map entry — the shadow is dead and still indexed.+ shadow?.dispose()++ expect(await m.backgroundWrite('node-1', 'ls\n')).toBe(true)++ // Tier 2 asks whether the shadow is ALIVE, not whether an entry exists. And falling through is+ // safe for exactly the reason the never-retry rule needs: a client that is not running rejects+ // `command()` BEFORE writing a byte (tmux-control-client.ts), so no send-keys can have reached+ // tmux twice.+ expect(control.calls).toHaveLength(2)+ expect(control.children[1].writes).toContain(LS_KEYS('nt-node-1'))+ expect(control.children[0].writes).not.toContain(LS_KEYS('nt-node-1'))+ })++ it('clears the linger when the shared client dies mid-command', async () => {+ const m = await tmuxManager()+ await release(ALICE, 'node-1')+ const before = vi.getTimerCount()++ const writing = m.backgroundWrite('node-1', 'ls\n') // arms the linger+ control.only.exit(1) // …and the client dies under it: its own onExit clears `shared`++ expect(await writing).toBe(false)+ // With nothing attached, the linger is a timer armed for a client that no longer exists — and+ // the dispose it will run is aimed at whatever IS attached when it fires. It goes with the+ // client, whether or not there was still an entry to dispose.+ expect(vi.getTimerCount()).toBe(before)+ })++ it('destroying a node disposes the shared client attached to its session', async () => {+ const m = await tmuxManager()+ await release(ALICE, 'node-1')+ await m.backgroundWrite('node-1', 'ls\n')++ await m.destroySession(ALICE, 'node-1')++ // The tmux session is about to be killed: a client of ours attached to it would linger until+ // tmux dropped it, and would meanwhile be subtracted from the session budget for a name that no+ // longer exists.+ expect(control.only.killed).toBe(1)+ expect(m.shadowedTmuxSessions(TMUX_SOCKET)).toEqual([])+ })})describe('isSessionName', () => {diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 6c7d55f5a..1dd8787d6 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -730,6 +730,9 @@ export class PtyManager {* shadow it with:* - tmux is unavailable or switched off: there is no tmux session to attach to, and a non-tmux* session's work lives in the pty client that is already gone.+ * - `ptyShadowClients` is off: the kill switch (see the setting's doc). This is ONE of the two+ * places it is read — the other is `backgroundWrite` — because these are the only two entry+ * points that can start a control client of ours.* - a PAINTER pty client is still attached for this node. A session never has both: the painter* attaches with `-D` (it would kick the shadow off a moment later anyway), and two clients of* ours on one pane would hand tmux the size negotiation that pty-size.ts exists to keep.@@ -752,7 +755,12 @@ export class PtyManager {// whether sessions are spawned under it. With tmux switched OFF, `tmuxPath` is still set (the// binary is installed) but every session is a plain shell — so a shadow would attach to a name// nothing ever created and die on arrival, and its caller would read that as "reached it".- if (!this.tmuxPath || !this.getSettings().tmuxEnabled) return null+ const settings = this.getSettings()+ if (!this.tmuxPath || !settings.tmuxEnabled) return null+ // The kill switch, read here rather than at each of the three places a shadow is USED: a caller+ // that cannot get a client cannot use one, and a flag scattered over the tier guards would be a+ // flag with three chances to be forgotten.+ if (!settings.ptyShadowClients) return nullconst live = this.shadows.get(persistKey)if (live?.alive) return live// Died since it was attached (its `onExit` normally clears the entry; this covers a caller that@@ -799,6 +807,10 @@ export class PtyManager {this.shadows.delete(persistKey)return null}+ // One line per swap direction, in the field-report vocabulary of this feature ("shadow attach" /+ // "painter attach", see `spawnSession`). Only when a client is actually STARTED: a re-used+ // shadow swapped nothing, and a line per caller would say nothing about the session's state.+ console.log(`[pty] shadow attach ${sessionName(persistKey)}`)const size = this.released.get(persistKey)?.sizeif (size) {const line = `refresh-client -C ${size.cols}x${size.rows}`@@ -957,7 +969,13 @@ export class PtyManager {}return true}- if (!this.tmuxPath || !this.getSettings().tmuxEnabled) return false+ const settings = this.getSettings()+ if (!this.tmuxPath || !settings.tmuxEnabled) return false+ // The kill switch, and the reason it sits BELOW tier 1: the painter is the session's own pty,+ // which exists with or without this feature — gating it would turn "no control clients" into+ // "background writes stop working", which is a different setting. Below here, every tier needs+ // a `tmux -C` child, so this one check covers both of them (`shadowAttach` carries the other).+ if (!settings.ptyShadowClients) return falseconst known = this.released.get(persistKey)if (!known || known.remote) return falseconst target = sessionName(persistKey)@@ -967,7 +985,12 @@ export class PtyManager {if (!isSessionName(target)) return falseconst line = encodeSendKeysHex(target, data)const shadow = this.shadows.get(persistKey)- if (shadow) return (await this.shadowCommand(persistKey, line))?.ok ?? false+ // ALIVE, not merely present: `dispose()` is silent (it fires no `onExit`), so a shadow retired+ // by whoever was handed it leaves its entry behind, and a dead client can deliver nothing.+ // Falling through to tier 3 does not violate the never-retry rule either — a client that is not+ // running rejects `command()` BEFORE writing a byte (tmux-control-client.ts), so the keys it+ // refused cannot also have reached tmux.+ if (shadow?.alive) return (await this.shadowCommand(persistKey, line))?.ok ?? falseconst client = this.sharedClientFor(persistKey)if (!client) return falsereturn (await this.controlCommand(client, line, () => this.sharedDispose(client)))?.ok ?? false@@ -990,7 +1013,11 @@ export class PtyManager {* synchronously on EMFILE and friends — the machine a background feature reaches for a client on).*/private sharedClientFor(persistKey: string): ControlModeClient | null {- if (!this.tmuxPath) return null+ // BOTH halves of "is there a tmux session at all", as `shadowAttach` carries them: with tmux+ // switched off `tmuxPath` is still set (the binary is installed) but nothing ever created a+ // session, so this would attach to a name that does not exist. Its only caller checks the same+ // thing three lines earlier — this is here so a second caller cannot arrive without it.+ if (!this.tmuxPath || !this.getSettings().tmuxEnabled) return nullthis.armSharedLinger()const live = this.sharedif (live?.client.alive) return live.client@@ -1014,6 +1041,10 @@ export class PtyManager {this.shared = nullreturn null}+ // Same line as a per-session shadow, deliberately: from the outside these are the same event —+ // a control client of ours became this session's attached client — and a field report should+ // not have to know which of the two kinds it is looking at. The linger keeps it rare.+ console.log(`[pty] shadow attach ${sessionName(persistKey)}`)return client}@@ -1027,16 +1058,24 @@ export class PtyManager {this.sharedLinger.unref?.()}- /** Retire the shared client. Idempotent. `only` makes it a no-op unless that exact client is- * still the current one — a caller reacting to a failure must not take down its successor. */+ /** Retire the shared client AND its linger. Idempotent. `only` makes it a no-op while a DIFFERENT+ * client is the current one — a caller reacting to its own client's failure must take down+ * neither the successor nor the successor's timer. With nothing attached at all there is no+ * successor to protect, and the timer goes either way. */private sharedDispose(only?: ControlModeClient): void {const live = this.shared- if (!live || (only && live.client !== only)) return- this.shared = null+ // A SUCCESSOR is left entirely alone, linger included: `only` is passed by a caller reacting to+ // its own client's failure, and by then a later write may already have started a new one.+ if (only && live && live.client !== only) return+ // Cleared even when nothing is attached — `onExit` clears `shared` on its own (a client that+ // died under us), and the linger armed for it would otherwise stay pending, aimed at whatever+ // is attached when it fires.if (this.sharedLinger) {clearTimeout(this.sharedLinger)this.sharedLinger = null}+ if (!live) return+ this.shared = nulllive.client.dispose()}@@ -1596,6 +1635,13 @@ export class PtyManager {// The shared background-write client goes too, for the same reason, when it is this node's// session it happens to be attached to.if (options.persistKey) {+ // The other half of the swap log (see `shadowAttach`), and only when there is really+ // something to retire: a painter arriving at a session no control client held swapped+ // nothing, and a line per terminal anyone opens is noise in the report it exists for.+ const held =+ this.shadows.get(options.persistKey)?.alive ||+ (this.shared?.persistKey === options.persistKey && this.shared.client.alive)+ if (held) console.log(`[pty] painter attach ${sessionName(options.persistKey)}`)this.shadowDispose(options.persistKey)this.sharedDisposeOn(options.persistKey)}diff --git a/src/core/pty-shadow.test.ts b/src/core/pty-shadow.test.tsindex 4cf769192..e9808c8be 100644--- a/src/core/pty-shadow.test.ts+++ b/src/core/pty-shadow.test.ts@@ -516,6 +516,55 @@ describe('control-mode shadow clients for released sessions', () => {expect(control.calls).toHaveLength(0)})+ it('spawns nothing with ptyShadowClients switched off — the kill switch', async () => {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager({ controlSpawn: control })+ m.init(() => ({ ...DEFAULT_SETTINGS, ptyShadowClients: false }))+ m.registerIpc()+ const { sessionId } = await create(ALICE)+ kill(ALICE, sessionId)++ // Everything else about this session is exactly as it is with the flag on: tmux is there, the+ // session is released, the record is ours. The flag is the ONE reason nothing attaches, which+ // is what makes "switch it off" a truthful instruction in a field report.+ expect(await m.shadowAttach('node-1')).toBeNull()+ expect(control.calls).toHaveLength(0)+ })++ it('logs one greppable line per swap direction', async () => {+ const lines: string[] = []+ vi.spyOn(console, 'log').mockImplementation((...a: unknown[]) => void lines.push(a.join(' ')))+ const m = await tmuxManager()+ const { sessionId } = await create(ALICE)+ kill(ALICE, sessionId)++ await m.shadowAttach('node-1')+ await m.shadowAttach('node-1') // re-used, not re-attached — so no second line++ expect(lines.filter((l) => l === `[pty] shadow attach ${sessionName('node-1')}`)).toHaveLength(1)++ liveTmuxSessions.add(sessionName('node-1')) // tmux kept the session across the detach+ await create(ALICE)++ // The other direction. "My terminal came back blank" is answerable from these two lines alone:+ // they name the session, the direction, and (by their order) which client held it when.+ expect(lines.filter((l) => l === `[pty] painter attach ${sessionName('node-1')}`)).toHaveLength(+ 1+ )+ })++ it('says nothing when a painter spawns with no control client to retire', async () => {+ const lines: string[] = []+ vi.spyOn(console, 'log').mockImplementation((...a: unknown[]) => void lines.push(a.join(' ')))+ const m = await tmuxManager()++ await create(ALICE) // the ordinary case: opening a terminal retires nothing++ // One line per SWAP, not per terminal anyone ever opens: a log nobody can read is a log that+ // answers no field report.+ expect(lines.some((l) => l.startsWith('[pty] painter attach'))).toBe(false)+ })+it('does nothing without tmux — there is no tmux session to shadow', async () => {const m = await plainManager()const { sessionId } = await create(ALICE)diff --git a/src/core/settings-store.test.ts b/src/core/settings-store.test.tsindex e1df34703..f6316a27e 100644--- a/src/core/settings-store.test.ts+++ b/src/core/settings-store.test.ts@@ -38,6 +38,27 @@ describe('SettingsStore nested-default merge', () => {expect(s.fontSize).toBe(15)})+ it('turns pty shadow clients ON for an existing settings.json that predates the flag', () => {+ writeFileSync(path.join(dir, 'settings.json'), JSON.stringify({ tmuxEnabled: true }), 'utf-8')+ const store = new SettingsStore()+ store.init()+ // Every install that upgrades into this release has a settings.json without the key. If the+ // shallow merge did not carry the default through, the feature would be off for exactly the+ // population it needs its soak release from.+ expect(store.get().ptyShadowClients).toBe(true)+ })++ it('keeps an explicit ptyShadowClients:false — the kill switch survives a load', () => {+ writeFileSync(+ path.join(dir, 'settings.json'),+ JSON.stringify({ ptyShadowClients: false }),+ 'utf-8'+ )+ const store = new SettingsStore()+ store.init()+ expect(store.get().ptyShadowClients).toBe(false)+ })+it('leaves an already-modern speech object alone', () => {writeFileSync(path.join(dir, 'settings.json'),diff --git a/src/shared/default-settings.test.ts b/src/shared/default-settings.test.tsindex 323db8c16..2399b95a0 100644--- a/src/shared/default-settings.test.ts+++ b/src/shared/default-settings.test.ts@@ -6,6 +6,13 @@ describe('DEFAULT_SETTINGS', () => {expect(DEFAULT_SETTINGS.gitAutoFetch).toBe(true)})+ it('ships pty shadow clients ON, so the kill switch is a real one', () => {+ // Default OFF would mean the mechanism never runs in the field and the flag proves nothing;+ // default ON means a field report can be answered with "turn it off", and that instruction+ // reaches existing installs through the { ...DEFAULT_SETTINGS, ...saved } merge.+ expect(DEFAULT_SETTINGS.ptyShadowClients).toBe(true)+ })+it('defaults to auto permission mode for new and existing users', () => {// Deliberate behavior change: auto mode ensures Claude sessions start with// permission auto-grants enabled. This reaches existing users viadiff --git a/src/shared/types.ts b/src/shared/types.tsindex 6d516e00b..f7b70468a 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -834,6 +834,20 @@ export interface Settings {browserMemorySaver: booleanaccent: stringtmuxEnabled: boolean+ /**+ * Reach a released tmux session with a control-mode (`tmux -C`) client instead of respawning its+ * terminal — the shadow clients in pty-manager.ts (`shadowAttach`) and the shared background-write+ * client behind `backgroundWrite`. A control client holds ZERO pty devices, which is the whole+ * point: the machine-wide `kern.tty.ptmx_max` ceiling is what a canvas of idle terminals runs into+ * first (see pty-devices.ts).+ *+ * ON by default, and read at those two entry points only: switching it off means this process+ * spawns no `tmux -C` child at all, and a released session is simply unreachable again — exactly+ * the behavior of the release before it. It is a kill switch for one soak release, not a feature+ * toggle: nothing user-visible depends on it (the mechanism has no production caller yet), so it+ * has no settings row and is flipped in settings.json.+ */+ ptyShadowClients: boolean/** GPU (WebGL) terminal rendering. 'off' routes every terminal to xterm's DOM renderer.* 'auto' (default) = one WebGL context PER TERMINAL everywhere except macOS, where it is* 'shared'. Repeated macOS field reports (whole-window flicker; terminals compositing black@@ -989,6 +1003,7 @@ export const DEFAULT_SETTINGS: Settings = {browserMemorySaver: true,accent: '#0a84ff',tmuxEnabled: true,+ ptyShadowClients: true,terminalGpuRendering: 'auto',tmuxScrollback: 50000,offscreenTerminalMinutes: 10,