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): destroying a co-viewed node closes it for the other viewers
enes19affb73cb6a
diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.tsindex e0ec9864c..b9c41ddac 100644--- a/src/core/pty-coattach.test.ts+++ b/src/core/pty-coattach.test.ts@@ -169,7 +169,7 @@ describe('terminal co-attach: one PTY, N subscribers', () => {it('a destroyed node is never co-attached to (the × path un-indexes it)', async () => {const m = await manager()const first = await create(ALICE)- await m.destroySession('node-1') // user clicked ×: the tmux session is gone for good+ await m.destroySession(ALICE, 'node-1') // user clicked ×: the tmux session is gone for goodconst second = await create(BOB)expect(second.sessionId).not.toBe(first.sessionId)@@ -528,6 +528,114 @@ describe('size negotiation: smallest subscriber wins', () => {})})+// ── A node DELETED while somebody else is watching it ─────────────────────────────────────────+// The × button means "this terminal is gone for good" (tmux kill-session). With co-attach the+// node may have other viewers, and the one thing they must NOT do is quietly reopen it: a respawn+// would resurrect a session its owner deliberately destroyed — in a fresh shell, with none of the+// state, and leaving a stray tmux session behind. They are told WHO closed it instead, and land in+// a closed state (the renderer paints "closed by <name>" from the presence table — Tasks 9-10).+describe('node destroyed while co-viewed', () => {+ let fake: FakePlatform++ beforeEach(() => {+ spawned.length = 0+ failNextSpawn = false+ fake = fakePlatform()+ initPlatform(fake)+ vi.useFakeTimers()+ })+ afterEach(() => {+ vi.useRealTimers()+ resetPlatformForTests()+ })++ async function manager() {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager()+ m.registerIpc()+ return m+ }+ const create = (clientId: number, persistKey = 'node-1') =>+ fake.handlers[IPC.ptyCreate](clientId, { cols: 80, rows: 24, persistKey }) as Promise<{+ sessionId: string+ fresh: boolean+ }>+ // pty:destroy is sender-aware: the closed event has to name WHO pressed ×.+ const destroy = (clientId: number, persistKey = 'node-1') =>+ fake.senderListeners[IPC.ptyDestroy](clientId, persistKey) as unknown as Promise<void>+ const flow = (clientId: number, sessionId: string, resume: boolean) =>+ fake.senderListeners[IPC.ptyFlow](clientId, sessionId, resume)+ const closed = (sessionId: string) =>+ fake.sent.filter((s) => s.channel === IPC.ptyClosed(sessionId))++ it('tells the OTHER subscribers who closed it, and does not respawn', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)++ fake.sent.length = 0+ await destroy(ALICE) // Alice hits the × on the node++ expect(closed(sessionId).map((s) => s.to)).toEqual([BOB]) // the closer does not need telling+ expect(closed(sessionId)[0].args[0]).toEqual({ by: ALICE })+ expect(spawned[0].killed).toBe(true) // the pty client is released with the session+ expect(spawned).toHaveLength(1) // …and nothing respawned it+ })++ it('a create AFTER the destroy spawns a fresh session — it never joins the doomed one', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)+ await destroy(ALICE)++ // Bob's renderer re-creating the node (a remount, a reconnect) must not resurrect the session.+ const again = await create(BOB)+ expect(again.sessionId).not.toBe(sessionId)+ expect(again.fresh).toBe(true) // a brand-new session, not a co-attach to the dead one+ expect(spawned).toHaveLength(2)+ })++ it('the destroyed session stops fanning out: no data, and no exit after the close', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)+ await destroy(ALICE)++ fake.sent.length = 0+ spawned[0].onDataCb?.('ghost output') // the pty client is being torn down+ vi.advanceTimersByTime(20)+ spawned[0].onExitCb?.({ exitCode: 1 }) // …and its exit lands after the close event+ expect(fake.sent.filter((s) => s.channel === IPC.ptyData(sessionId))).toEqual([])+ // "[process exited with code 1]" on top of "closed by Alice" would be noise at best: the+ // subscribers were told the truth already, and the session is off the books.+ expect(fake.sent.filter((s) => s.channel === IPC.ptyExit(sessionId))).toEqual([])+ })++ it('releases a session a subscriber had PAUSED (a dying pty must not keep its fd)', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)+ flow(BOB, sessionId, false) // Bob's xterm is drowning — the pty is paused for everyone+ expect(spawned[0].paused).toBe(true)++ await destroy(ALICE)+ // releasePty resumes before destroying: a paused pty never reads EOF, so it would otherwise+ // leak its master fd (see pty-release.ts). Bob owes a resume that will never come — the+ // session is gone, so the ledger goes with it.+ expect(spawned[0].paused).toBe(false)+ expect(spawned[0].killed).toBe(true)+ expect(closed(sessionId).map((s) => s.to)).toEqual([BOB])+ })++ it('a destroy with no live session still tells nobody and kills the tmux session', async () => {+ await manager()+ // Nothing was ever created for node-9 in this process (e.g. it is only running in tmux).+ await destroy(ALICE, 'node-9')+ expect(fake.sent).toEqual([])+ expect(spawned).toHaveLength(0)+ })+})+describe('tmuxAttachFlags', () => {it("keeps -D for the app's own client: exactly ONE tmux client per session", async () => {const { tmuxAttachFlags } = await import('./pty-manager')diff --git a/src/core/pty-manager-platform.test.ts b/src/core/pty-manager-platform.test.tsindex ae1b29d7c..c4f9eec2f 100644--- a/src/core/pty-manager-platform.test.ts+++ b/src/core/pty-manager-platform.test.ts@@ -46,7 +46,7 @@ describe('PtyManager platform registration', () => {it('registers the sender-aware pty channels EXACTLY ONCE (no composed plain listener)', async () => {const { PtyManager } = await import('./pty-manager')new PtyManager().registerIpc()- for (const ch of [IPC.ptyWrite, IPC.ptyResize, IPC.ptyFlow, IPC.ptyKill]) {+ for (const ch of [IPC.ptyWrite, IPC.ptyResize, IPC.ptyFlow, IPC.ptyKill, IPC.ptyDestroy]) {expect(fake.senderListeners[ch], ch).toBeDefined()expect(fake.listeners[ch], ch).toBeUndefined()}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex cc1966219..f5658d4b6 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -453,7 +453,13 @@ export class PtyManager {platform().onWithSender(IPC.ptyKill, (senderId: number, sessionId: string) =>this.kill(senderId, sessionId))- platform().on(IPC.ptyDestroy, (persistKey: string) => this.destroySession(persistKey))+ // Sender-aware: the × permanently ends a session OTHER people may be watching, so the close+ // event they get has to name WHO did it ("closed by <name>" — see `destroySession`).+ // Registered ONLY here: `on` and `onWithSender` compose on the same channel, so a leftover+ // plain listener would run the destroy — and its `tmux kill-session` — twice.+ platform().onWithSender(IPC.ptyDestroy, (senderId: number, persistKey: string) =>+ this.destroySession(senderId, persistKey)+ )platform().handle(IPC.ptyReadScrollback, (persistKey: string) =>readScrollback(persistKey))@@ -1339,23 +1345,62 @@ export class PtyManager {}}- /** Permanently end a node's persistent tmux session (called when the user closes it). */- async destroySession(persistKey: string): Promise<void> {+ /**+ * Permanently end a node's persistent session — the user clicked ×, and that means "this+ * terminal is gone, for everyone" (`tmux kill-session`), which is the whole meaning of the+ * button. With co-attach the node may have OTHER viewers, and they must be told: each one gets+ * `pty:closed:<sessionId>` carrying `{ by: <the ClientId that pressed ×> }`, so their terminal+ * lands in a "closed by <name>" state.+ *+ * The payload names the CLIENT, not the person: names are unverified presence data and live in+ * the renderer's presence table, so PtyManager needs no dependency on the peer table (and cannot+ * be made to lie about a name it never sees).+ *+ * The close event is what STOPS the other viewers from quietly reopening the node: a respawn+ * would resurrect a session its owner deliberately deleted — a fresh shell with none of the+ * state, plus a stray tmux session nobody asked for. Everything below therefore also makes a+ * respawn structurally impossible from THIS process: the co-attach index entry, the in-flight+ * create, and the Session itself all go away synchronously, before the kill-session lands.+ *+ * `clientId` is null when nothing/no-one attributable did it (an internal caller).+ */+ async destroySession(clientId: ClientId | null, persistKey: string): Promise<void> {// destroy() is called (close button) while the session is still live, so its sshRemote is- // known. Capture it synchronously before any await.- const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote+ // known. Capture it synchronously before any await. The index is the co-attach one (UI+ // sessions); the scan is the fallback for a session that is live but not indexed.+ const dyingId = this.byPersistKey.get(persistKey)+ const dying = dyingId ? this.sessions.get(dyingId) : undefined+ const sshRemote = dying?.sshRemote ?? this.sessionByPersistKey(persistKey)?.sshRemote// Un-index NOW (synchronously): the node is gone for good, so a create() that races the// 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().+ // session instead of co-attaching to the one we are about to destroy.// 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) {+ if (dyingId && dying) {this.byPersistKey.delete(persistKey)- const dying = this.sessions.get(dyingId)- if (dying) dying.indexKey = undefined+ dying.indexKey = undefined+ const channel = IPC.ptyClosed(dyingId)+ for (const sub of dying.subscribers) {+ if (sub !== clientId) this.send(sub, channel, { by: clientId })+ }+ // Tear the session down HERE rather than leaving it to the client's own `kill` / the pty's+ // onExit: with N subscribers there is no single kill to wait for, and every one of them may+ // be mid-anything — parked, paused (its owed resume will never come now), desynced past the+ // drop ceiling. The Session object holds all of that state, so dropping it drops the lot: no+ // leaked pause, no stray subscriber still in the fan-out, no timer. (The per-client+ // backpressure bookkeeping on the Server Edition shell is pruned by the `pty:closed:` event+ // itself — see ServerPlatform.forgetFlowState.)+ if (dying.flushTimer) clearTimeout(dying.flushTimer)+ dying.subscribers.clear()+ dying.sizes.clear()+ dying.shown.clear()+ dying.pausedBy.clear()+ // releasePty (not proc.kill()): a paused pty never reads EOF, so kill() alone would leak the+ // master fd — and a session destroyed while a drowning viewer had it paused is exactly that+ // case (see pty-release.ts). It resumes the pty first, so the fd actually closes.+ releasePty(dying.proc as ReleasablePty)+ this.forget(dyingId, dying)}// The node is gone for good — drop its cold-restore snapshot too.await deleteScrollback(persistKey)diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.tsindex 0e8cdb8ba..e0e40bdfa 100644--- a/src/core/pty-single-user.test.ts+++ b/src/core/pty-single-user.test.ts@@ -346,7 +346,7 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =it('destroy (the × button) DOES kill the tmux session', async () => {const m = await tmuxManager()await create(80, 24)- await m.destroySession('solo-1')+ await m.destroySession(SOLO, 'solo-1')const kills = tmuxCalls('kill-session')expect(kills).toHaveLength(1)expect(kills[0].args[kills[0].args.indexOf('-t') + 1]).toBe(sessionName('solo-1'))