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
fix(pty): a co-attaching client can never inherit a paused pty, a dead one is dropped, and create() cannot double-spawn
enesf88376de6197
diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.tsindex 0a30646eb..5d65b01d6 100644--- a/src/core/pty-coattach.test.ts+++ b/src/core/pty-coattach.test.ts@@ -13,9 +13,15 @@ interface FakePty {killed: boolean}const spawned: FakePty[] = []+/** When set, the NEXT pty.spawn throws (simulates posix_spawn failing). */+let failNextSpawn = falsevi.mock('node-pty', () => ({spawn: (_file: string, _args: string[], _opts: unknown) => {+ if (failNextSpawn) {+ failNextSpawn = false+ throw new Error('posix_spawnp failed.')+ }const p: FakePty = { writes: [], resizes: [], paused: false, killed: false }spawned.push(p)return {@@ -49,6 +55,7 @@ describe('terminal co-attach: one PTY, N subscribers', () => {beforeEach(() => {spawned.length = 0+ failNextSpawn = falsefake = fakePlatform()initPlatform(fake)vi.useFakeTimers()@@ -184,6 +191,110 @@ describe('terminal co-attach: one PTY, N subscribers', () => {m.kill(null, id)expect(spawned[0].killed).toBe(true)})++ // ── Finding 1: a joiner must never inherit a PAUSED pty ────────────────────────────────+ // Flow control is per-client in the renderer (xterm backlog > 1 MB → setFlow(false)) and its+ // `paused` flag only clears when more data arrives. So a pty left paused by a client that+ // vanished can never be resumed by a new one: it would show a blank, frozen terminal forever.+ it('a client joining a PAUSED session resumes the pty (an empty backlog cannot resume it)', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ fake.listeners[IPC.ptyFlow](sessionId, false) // Alice's xterm backlog crossed the high water mark+ expect(spawned[0].paused).toBe(true)++ // Alice's browser tab is gone (or reloaded): a new client co-attaches to the same node.+ const bob = await create(BOB)+ expect(bob.sessionId).toBe(sessionId)+ expect(spawned[0].paused).toBe(false) // a joiner has an empty backlog by definition+ })++ it('a departing client cannot leave the pty paused for the subscribers that stay', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)+ fake.listeners[IPC.ptyFlow](sessionId, false)+ expect(spawned[0].paused).toBe(true)++ kill(ALICE, sessionId) // the client that paused it leaves+ expect(spawned[0].paused).toBe(false) // Bob's terminal keeps streaming+ })++ // ── Finding 2: a client that vanishes (WS close / destroyed webContents) is dropped ──────+ it('dropClient unsubscribes the client from EVERY session and releases the empty ones', async () => {+ const m = await manager()+ const shared = await create(ALICE, 80, 24, 'node-1')+ await create(BOB, 80, 24, 'node-1')+ const solo = await create(ALICE, 80, 24, 'node-2')++ m.dropClient(ALICE) // Alice's browser tab closed — no pty:kill ever arrives++ // node-1 still has Bob: the pty survives and keeps fanning out to him only.+ fake.sent.length = 0+ spawned[0].onDataCb?.('still here')+ vi.advanceTimersByTime(20)+ const data = fake.sent.filter((s) => s.channel === IPC.ptyData(shared.sessionId))+ expect(data.map((s) => s.to)).toEqual([BOB])+ expect(spawned[0].killed).toBe(false)++ // node-2 fell to zero subscribers: the pty client is released (the tmux session survives).+ expect(spawned[1].killed).toBe(true)+ const again = await create(BOB, 80, 24, 'node-2')+ expect(again.sessionId).not.toBe(solo.sessionId)+ expect(spawned).toHaveLength(3)+ })++ it('dropClient resumes a session the vanished client had paused', async () => {+ const m = await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)+ fake.listeners[IPC.ptyFlow](sessionId, false)++ m.dropClient(ALICE)+ expect(spawned[0].paused).toBe(false)+ expect(spawned[0].killed).toBe(false)+ })++ it('dropClient leaves a relay-served (detached) pty alone', async () => {+ const m = await manager()+ const id = m.attachDetached('node-1', { onData: () => {}, onExit: () => {} })+ m.dropClient(ALICE)+ expect(spawned[0].killed).toBe(false)+ m.kill(null, id)+ expect(spawned[0].killed).toBe(true)+ })++ // ── Finding 3: the same-tick create race ────────────────────────────────────────────────+ // create() awaits a `tmux has-session` subprocess + the shell-PATH probe between the index+ // lookup and spawnSession's synchronous registration, so two clients opening the same node+ // in that window both used to spawn — and the second `tmux -A -D` kicked the first viewer off.+ it('two overlapping creates for the same node resolve to ONE spawn', async () => {+ await manager()+ const [a, b] = await Promise.all([create(ALICE), create(BOB)])++ expect(spawned).toHaveLength(1)+ expect(b.sessionId).toBe(a.sessionId)+ expect(a.fresh).toBe(true) // Alice's call did the spawn+ expect(b.fresh).toBe(false) // Bob joined it — no cold-restore replay+ })++ it('a failed spawn clears the in-flight entry, so the node stays openable', async () => {+ await manager()+ failNextSpawn = true+ await expect(create(ALICE)).rejects.toThrow(/Failed to spawn terminal/)++ const ok = await create(ALICE)+ expect(ok.sessionId).toBeTruthy()+ expect(spawned).toHaveLength(1)+ })++ it('a create racing a failed spawn still gets a live session', async () => {+ await manager()+ failNextSpawn = true+ const [a, b] = await Promise.allSettled([create(ALICE), create(BOB)])+ expect(a.status).toBe('rejected')+ expect(b.status).toBe('fulfilled')+ expect(spawned).toHaveLength(1) // Bob's create spawned after the failure cleared the entry+ })})describe('tmuxAttachFlags', () => {diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex f448cbfed..5bf12f78c 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -255,6 +255,12 @@ interface Session {sshRemote?: NonNullable<PtyCreateOptions['sshRemote']>/** Output arrived since the last scrollback snapshot — idle sessions skip the capture. */outputSinceSnapshot: boolean+ /** True while the pty is paused by flow control (`setFlow(id,false)`). Tracked because the+ * resume can otherwise be LOST: the renderer's flow control is per-client and only resumes+ * when more data arrives, so a pty paused by a client that then vanished (tab closed) would+ * stay paused forever — a co-attaching client would inherit a frozen, blank terminal it can+ * never unfreeze. Every subscriber change re-checks it (join / leave / dropClient). */+ paused: boolean/** True when this node had an `accountId` but its config dir was gone at spawn, so we fell back* to the system account. `create()` surfaces it to the renderer (warning chip). */accountFallback?: boolean@@ -301,6 +307,10 @@ export class PtyManager {/** persistKey (node id) → live sessionId. The index that makes `pty:create` idempotent:* a second client asking for the same node subscribes to the running session. */private byPersistKey = new Map<string, string>()+ /** persistKey (node id) → the create() currently spawning it. Makes `pty:create` idempotent+ * ACROSS the awaits inside a spawn (see create()), not just after them. Entries are removed+ * as soon as the spawn settles, success or failure. */+ private inflight = new Map<string, Promise<PtyCreateResult>>()private counter = 0private tmuxPath: string | null = nullprivate confPath = ''@@ -395,22 +405,75 @@ export class PtyManager {}private async create(clientId: ClientId, options: PtyCreateOptions): Promise<PtyCreateResult> {+ const key = options.persistKey+ if (!key) return this.spawnNew(clientId, options)// Co-attach: a live session for this node id already exists in THIS process (another client,// or this client's own second view). Subscribe to it instead of spawning a second tmux client- // — `-D` would otherwise kick the first viewer off. `fresh:false` tells the renderer it joined- // a live session: no cold-restore scrollback replay, no agent resume (tmux redraws instead).- if (options.persistKey) {- const existingId = this.byPersistKey.get(options.persistKey)- const existing = existingId ? this.sessions.get(existingId) : undefined- if (existingId && existing) {- existing.subscribers.add(clientId)- existing.sizes.set(clientId, { cols: options.cols, rows: options.rows })- this.applySize(existingId, existing)- return existing.accountFallback- ? { sessionId: existingId, fresh: false, accountFallback: true }- : { sessionId: existingId, fresh: false }- }+ // — `-D` would otherwise kick the first viewer off.+ const joined = this.join(clientId, options, key)+ if (joined) return joined+ // Same-tick race: spawnNew() awaits a `tmux has-session` SUBPROCESS (tens of ms, not a+ // microtask) before spawnSession registers the session in `byPersistKey`, so two clients+ // opening the same node in that window would BOTH miss the index and both spawn — and the+ // second `tmux -A -D` detaches the first client, killing that user's terminal. So the spawn+ // is published as an in-flight promise from the TOP of create(): a racing create awaits it+ // and then takes the subscribe branch. (No locking primitive: the promise IS the barrier —+ // the single-user path never sees an in-flight entry and behaves exactly as before.)+ const inflight = this.inflight.get(key)+ if (inflight) {+ await inflight.catch(() => undefined) // the other spawn failed → fall through and try ourselves+ const late = this.join(clientId, options, key)+ if (late) return late+ }+ const spawn = this.spawnNew(clientId, options)+ this.inflight.set(key, spawn)+ // Clear on settle — INCLUDING on failure, or a single failed spawn would leave a rejected+ // promise in the map and make the node permanently unopenable.+ const clear = (): void => {+ if (this.inflight.get(key) === spawn) this.inflight.delete(key)}+ spawn.then(clear, clear)+ return spawn+ }++ /**+ * Subscribe `clientId` to the live session for this node id, if there is one. Returns the+ * create() result (`fresh:false` — the renderer joined a live session: no cold-restore+ * scrollback replay, no agent resume; tmux redraws instead), or undefined if none exists.+ */+ private join(+ clientId: ClientId,+ options: PtyCreateOptions,+ persistKey: string+ ): PtyCreateResult | undefined {+ const existingId = this.byPersistKey.get(persistKey)+ const existing = existingId ? this.sessions.get(existingId) : undefined+ if (!existingId || !existing) return undefined+ existing.subscribers.add(clientId)+ existing.sizes.set(clientId, { cols: options.cols, rows: options.rows })+ this.applySize(existingId, existing)+ // A joiner's backlog is empty by definition, so it will never issue the resume that a+ // previous (now gone) client's flow control owed us — and no data would ever arrive to+ // trigger one either. Resume here, or the new client stares at a frozen terminal forever.+ // (Per-client backpressure is Task 5's job; this only guarantees a join never lands on a+ // paused pty.)+ this.resumeIfPaused(existing)+ // KNOWN GAP — plain-shell (tmux disabled / unavailable) co-attach: `fresh:false` makes the+ // renderer skip the cold-restore scrollback replay, and with no tmux there is no client to+ // redraw the screen either, so this joiner sees a blank-but-live terminal until the next+ // output arrives (typing Enter paints it). Not fixed here on purpose: the renderer only+ // subscribes to `pty:data:<id>` AFTER create() resolves, so a join-time repaint cannot be+ // pushed on the wire — it needs a new field on PtyCreateResult plus renderer replay, i.e. a+ // cross-surface contract change that belongs with the per-client backlog work (Task 5), not+ // in a bugfix. A plain-shell session has no cross-client continuity to inherit anyway (it is+ // exactly what "no tmux = no persistence" already means everywhere else in this file).+ return existing.accountFallback+ ? { sessionId: existingId, fresh: false, accountFallback: true }+ : { sessionId: existingId, fresh: false }+ }++ /** Spawn a brand-new session for this client (the non-co-attach path). */+ private async spawnNew(clientId: ClientId, options: PtyCreateOptions): Promise<PtyCreateResult> {// A tmux-backed session is "fresh" (cold start) when no live session exists to reattach to// — i.e. first open, or after a machine reboot killed the tmux server. Plain (non-tmux)// sessions are always fresh: they have no cross-restart continuity. The renderer uses this@@ -777,6 +840,7 @@ export class PtyManager {persistKey: persisted ? options.persistKey : undefined,sshRemote: remote,outputSinceSnapshot: true, // capture the initial screen on the first tick+ paused: false,accountFallback}if (persisted) this.ensureSnapshotTimer()@@ -846,6 +910,7 @@ export class PtyManager {setFlow(sessionId: string, resume: boolean): void {const session = this.sessions.get(sessionId)if (!session) return+ session.paused = !resumetry {if (resume) session.proc.resume()else session.proc.pause()@@ -854,6 +919,18 @@ export class PtyManager {}}+ /** Resume a pty that flow control left paused. Called on every subscriber change, because a+ * pause is owed a resume by the client that issued it — and that client may be gone. */+ private resumeIfPaused(session: Session): void {+ if (!session.paused) return+ session.paused = false+ try {+ session.proc.resume()+ } catch {+ // proc already exited; ignore.+ }+ }+write(sessionId: string, data: string): void {this.sessions.get(sessionId)?.proc.write(data)}@@ -887,6 +964,11 @@ export class PtyManager {if (session.subscribers.size > 0 || session.onData) {// Somebody is still watching: the departing client's size no longer constrains the pty.this.applySize(sessionId, session)+ // The departing client may have been the one that paused us (its xterm backlog was over+ // the watermark) — and it will never send the matching resume now. Leaving the pause in+ // place would freeze the terminal for everyone who stayed. Whoever is still behind will+ // re-pause on their next high-water send.+ this.resumeIfPaused(session)return}if (session.flushTimer) clearTimeout(session.flushTimer)@@ -901,6 +983,25 @@ export class PtyManager {this.forget(sessionId, session)}+ /**+ * A client VANISHED (browser tab closed — the normal way to leave the Server Edition — or a+ * destroyed/crashed renderer): unsubscribe it from every session it was watching, exactly as a+ * `pty:kill` per session would. Sessions that fall to zero subscribers are released (final+ * scrollback snapshot + pty client released). tmux sessions are NOT killed — releasing the pty+ * client is the whole point: the terminal keeps running and the next open reattaches.+ *+ * Without this, a vanished client stays in `subscribers` forever: the pty is never released,+ * its detach-time snapshot never taken, and — worse — a pty that client had PAUSED could never+ * be resumed (the leave path is what returns the owed resume).+ */+ dropClient(clientId: ClientId): void {+ // Snapshot the entries: kill() mutates `sessions` when a session falls to zero subscribers.+ for (const [sessionId, session] of [...this.sessions]) {+ if (!session.subscribers.has(clientId)) continue+ this.kill(clientId, sessionId)+ }+ }+/*** Capture a session's output. `full` grabs the entire scrollback (`-S -`, for the* markdown view); otherwise the recent ~200 lines (AI naming, palette search).@@ -1031,6 +1132,9 @@ export class PtyManager {// kill-session below — the worktree-move respawn does exactly that — must spawn a fresh// session instead of co-attaching to the one we are about to destroy. The Session object// itself is dropped by its own onExit / the client's kill().+ // Also drop any in-flight create for this node: a create racing the kill-session below must+ // spawn a fresh session, not await (and then join) the one we are destroying.+ this.inflight.delete(persistKey)const dyingId = this.byPersistKey.get(persistKey)if (dyingId) {this.byPersistKey.delete(persistKey)diff --git a/src/main/index.ts b/src/main/index.tsindex 6b26ff24f..553f88797 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -246,7 +246,19 @@ function createWindow(): BrowserWindow {// its webContents are destroyed by then.)const presenceId = win.webContents.idpresenceHub.join(presenceId, 'desktop')- win.on('closed', () => presenceHub.leave(presenceId))+ win.on('closed', () => {+ presenceHub.leave(presenceId)+ // This webContents is a pty SUBSCRIBER (co-attach: one pty, N subscribers, keyed by the+ // webContents id). A destroyed window sends no `pty:kill`, so without this it would stay+ // subscribed forever: the pty client is never released, the detach-time scrollback snapshot+ // is skipped, and a session it had paused via flow control could never be resumed — the next+ // client to co-attach to that node would inherit a frozen terminal. The tmux sessions+ // themselves keep running, exactly as they do on quit (killAll).+ ptyManager.dropClient(presenceId)+ })+ // A crashed/killed renderer is the same story, minus the window: drop its subscriptions so the+ // reloaded renderer reattaches to live sessions instead of inheriting the dead one's state.+ win.webContents.on('render-process-gone', () => ptyManager.dropClient(presenceId))win.on('ready-to-show', () => win.show())diff --git a/src/server/index.ts b/src/server/index.tsindex c58f6be8f..b473732f0 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -114,7 +114,9 @@ export async function startServer(await hookServer.start()const server = http.createServer(createHttpHandler({ auth, rendererDir: config.rendererDir }))- attachWsServer(server, { platform, auth })+ // A closed browser tab is the NORMAL way to leave the Server Edition and sends no `pty:kill`,+ // so the WS close hook is what unsubscribes that client from the sessions it was watching.+ attachWsServer(server, { platform, auth, onClientGone: (uiId) => ptyManager.dropClient(uiId) })await new Promise<void>((resolve, reject) => {server.once('error', reject)diff --git a/src/server/platform-server.ts b/src/server/platform-server.tsindex 1bb0d4b93..93c22eb0e 100644--- a/src/server/platform-server.ts+++ b/src/server/platform-server.ts@@ -37,8 +37,15 @@ export class ServerPlatform implements CorePlatform {private sinks = new Map<number, UiSink>()private nextUiId = 1- // WS backpressure: per-session paused flag + the controller that pauses/resumes the- // tmux client. Keyed by sessionId alone (a session's pty:data always routes to one ui).+ // WS backpressure: per-session paused flag + the controller that pauses/resumes the pty.+ //+ // Keyed by sessionId ALONE, which co-attach (one pty, N subscribers) has made too coarse: a+ // session's pty:data now fans out to every subscribed ui, so this flag cannot express "behind+ // for browser A, flowing for browser B", and `flowController` pauses the ONE pty behind the+ // session for EVERYONE. Net effect today: one slow/backed-up browser pauses the shared pty for+ // all viewers (bounded — the pause is re-asserted per high send and resumes below LOW_WATER,+ // and PtyManager resumes on any subscriber change so nobody can be left frozen). Task 5 rekeys+ // this to (uiId, sessionId) and decides the pty-side policy (pause when ANY viewer is behind).private paused = new Map<string, boolean>()private flowController?: (sessionId: string, resume: boolean) => voiddiff --git a/src/server/ws.test.ts b/src/server/ws.test.tsindex 63d2f7ba8..25fc26088 100644--- a/src/server/ws.test.ts+++ b/src/server/ws.test.ts@@ -15,6 +15,8 @@ import { IPC } from '../shared/ipc'let dir: string, server: http.Server, port: number, auth: Auth, platform: ServerPlatform, cookie: string/** Every socket this file opens, so afterEach can tear them all down (see below). */let sockets: WebSocket[] = []+/** uiIds reported gone by the WS close hook (wired to PtyManager.dropClient at boot). */+let gone: number[] = []/** Poll until `pred` holds (or throw after ~2s) — socket teardown is async. */async function until(pred: () => boolean, what: string): Promise<void> {@@ -33,7 +35,8 @@ beforeEach(async () => {// core platform singleton — so this unit test must install the platform, exactly as boot does.initPlatform(platform)server = http.createServer((_q, s) => { s.statusCode = 404; s.end() })- attachWsServer(server, { platform, auth })+ gone = []+ attachWsServer(server, { platform, auth, onClientGone: (uiId) => gone.push(uiId) })await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))port = (server.address() as { port: number }).portcookie = `${SESSION_COOKIE}=${auth.createSession()}`@@ -177,6 +180,17 @@ describe('ws endpoint', () => {expect(casts).toEqual([])})+ it('a closed connection is reported gone, so its pty subscriptions are dropped', async () => {+ // A closed tab (or a reload) is the NORMAL way to leave the Server Edition and sends no+ // `pty:kill`. Without this hook the client stays a subscriber of every session it was+ // watching: the pty is never released, its final scrollback snapshot is skipped, and a+ // session it had paused would freeze the next client that co-attaches to that node.+ const ws = await connect({ cookie })+ ws.close()+ await until(() => gone.length === 1, 'the close hook fires')+ expect(gone).toEqual([1]) // the uiId this socket attached as+ })+it('heartbeat: terminates a socket that never answers a ping, dropping its presence peer', async () => {// Its own listener, so the heartbeat can run at test speed (production: WS_HEARTBEAT_MS).const hbServer = http.createServer((_q, s) => { s.statusCode = 404; s.end() })diff --git a/src/server/ws.ts b/src/server/ws.tsindex ba6b8d940..825a593eb 100644--- a/src/server/ws.ts+++ b/src/server/ws.ts@@ -55,6 +55,14 @@ export const WS_MAX_PAYLOAD = 8 * 1024 * 1024export interface WsServerOpts {platform: ServerPlatformauth: Auth+ /**+ * A connection is GONE (tab closed — the normal way to leave the Server Edition — reload, or a+ * peer reaped by the heartbeat). Wired to `PtyManager.dropClient` at boot, so the sessions that+ * client was watching lose it as a subscriber and the ones nobody watches any more are released.+ * Passed in rather than imported, because `src/server` owns the wiring and `src/core` may not+ * know about `ws`.+ */+ onClientGone?: (uiId: number) => void/** TEST ONLY: shorten the heartbeat period. Production always uses WS_HEARTBEAT_MS. */heartbeatMs?: number}@@ -83,7 +91,7 @@ function upgradeAllowed(req: http.IncomingMessage, auth: Auth): boolean {}export function attachWsServer(server: http.Server, opts: WsServerOpts): void {- const { platform, auth, heartbeatMs = WS_HEARTBEAT_MS } = opts+ const { platform, auth, onClientGone, heartbeatMs = WS_HEARTBEAT_MS } = optsconst wss = new WebSocketServer({ noServer: true, maxPayload: WS_MAX_PAYLOAD })// Liveness heartbeat. Node enables no TCP keepalive on an upgraded socket, so a browser that@@ -174,6 +182,11 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): void {ws.on('close', () => {presenceHub.leave(uiId)+ // Before detaching the sink: this client is a pty subscriber, and nothing else would ever+ // tell PtyManager it is gone (a closed tab sends no `pty:kill`). Leaving it subscribed+ // leaks the pty client, skips the detach-time scrollback snapshot, and can strand a+ // session it had paused — a client joining that node later would inherit a frozen pty.+ onClientGone?.(uiId)platform.detach(uiId)})})