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): tell deletion and recycling apart (a worktree move no longer bricks co-viewers)
enes0b7a4a5ac4a4
diff --git a/docs/team-presence.md b/docs/team-presence.mdindex a698c9793..502b000ac 100644--- a/docs/team-presence.md+++ b/docs/team-presence.md@@ -199,6 +199,24 @@ v2.If a node is deleted while others are attached, `destroy(persistKey)` kills the tmux session andthe remaining subscribers enter a "closed by <name>" state rather than respawning it.+### Deletion vs recycling++Killing a node's tmux session is used for two opposite intents, and PtyManager keeps them apart:++- **Deletion** (× / delete node) → `destroy(persistKey)`. The node leaves the canvas. Co-viewers get+ `pty:closed:<sid> { by }` and must never respawn it — a respawn would resurrect a terminal its+ owner deliberately killed, in a fresh shell, and strand a tmux session.+- **Recycling** ("move into worktree") → `recycle(persistKey)`. Same `tmux kill-session` (otherwise+ `new-session -A` would just reattach the old working directory), but the node **stays** on every+ canvas and keeps working. Co-viewers get `pty:recycled:<sid>` (no payload): restart the terminal,+ the node moved. Their re-create **co-attaches** to the replacement session, so they follow the node+ into its new cwd and are never left holding the dead pty.++The recycled notice is **withheld until the replacement session is registered** (and, as an escape+hatch for a recycler that never respawns, after a 10 s timeout). Sent any earlier, a co-viewer's+restart could beat the mover's own `create()` and spawn `nt-<nodeId>` from *its* options — i.e. in+the node's stale cwd — silently undoing the move for everyone.+## Canvas syncNode edits broadcast as mutations so cursors don't hover over stale geometry.diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.tsindex b9c41ddac..bb36c90d9 100644--- a/src/core/pty-coattach.test.ts+++ b/src/core/pty-coattach.test.ts@@ -636,6 +636,114 @@ describe('node destroyed while co-viewed', () => {})})+// ── A node RECYCLED (moved into a worktree) while somebody else is watching it ────────────────+// "Move into worktree" ends the node's tmux session so the SAME node id respawns in the new cwd.+// The node never leaves anybody's canvas and it keeps working — so a co-viewer must NOT be told+// "closed by <name>" (which is permanent and un-respawnable). They are told the session RESTARTED,+// and only once the replacement session exists: notify them any earlier and their own re-create+// could win the race and spawn the tmux session in their STALE cwd, silently undoing the move.+describe('node recycled (worktree move) 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:recycle is sender-aware: the client that recycled drives its OWN respawn, so it must be+ // excluded from the restart notice (it would otherwise respawn twice).+ const recycle = (clientId: number, persistKey = 'node-1') =>+ fake.senderListeners[IPC.ptyRecycle](clientId, persistKey) as unknown as Promise<void>+ const closed = (sessionId: string) =>+ fake.sent.filter((s) => s.channel === IPC.ptyClosed(sessionId))+ const recycled = (sessionId: string) =>+ fake.sent.filter((s) => s.channel === IPC.ptyRecycled(sessionId))++ it('never tells a co-viewer the node was CLOSED — it is still on their canvas', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)++ fake.sent.length = 0+ await recycle(ALICE)+ expect(closed(sessionId)).toEqual([]) // the un-respawnable "closed by <name>" state must NOT fire+ expect(spawned[0].killed).toBe(true) // the old pty is still released with its session+ })++ it('holds the restart notice until the replacement session exists, then joins the co-viewer to it', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)++ fake.sent.length = 0+ await recycle(ALICE)+ // Nothing yet: notifying Bob here would let his re-create spawn `nt-node-1` in his stale cwd.+ expect(recycled(sessionId)).toEqual([])++ const fresh = await create(ALICE) // Alice respawns the node in the worktree cwd+ expect(spawned).toHaveLength(2)+ expect(fresh.sessionId).not.toBe(sessionId)+ expect(recycled(sessionId).map((s) => s.to)).toEqual([BOB]) // only now is Bob told++ const bob = await create(BOB) // Bob's terminal restarts…+ expect(bob.sessionId).toBe(fresh.sessionId) // …onto the LIVE new session+ expect(bob.fresh).toBe(false) // a co-attach, not a resurrection+ expect(spawned).toHaveLength(2) // and nothing extra was spawned+ })++ it('never sends the restart notice to the client that recycled', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)+ await recycle(ALICE)+ await create(ALICE)+ expect(recycled(sessionId).map((s) => s.to)).not.toContain(ALICE)+ })++ it('a co-viewer is never left on a dead pty: the notice fires even if nobody respawns', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)++ fake.sent.length = 0+ await recycle(ALICE)+ expect(recycled(sessionId)).toEqual([])+ // Alice's app quit / crashed mid-move: no replacement session is ever registered. Bob still+ // has to be released from the dead session, so the notice fires on a timeout.+ vi.advanceTimersByTime(15_000)+ expect(recycled(sessionId).map((s) => s.to)).toEqual([BOB])+ })++ it('a recycle with no other subscriber notifies nobody (the solo path is untouched)', async () => {+ await manager()+ await create(ALICE)+ fake.sent.length = 0+ await recycle(ALICE)+ await create(ALICE)+ vi.advanceTimersByTime(15_000)+ expect(fake.sent.filter((s) => s.channel.startsWith('pty:recycled:'))).toEqual([])+ expect(fake.sent.filter((s) => s.channel.startsWith('pty:closed:'))).toEqual([])+ })+})+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.ts b/src/core/pty-manager.tsindex f5658d4b6..8a2b32af9 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -335,6 +335,24 @@ export function tmuxAttachFlags(detached: boolean): string[] {const FLUSH_MS = 8const MAX_BUF_BYTES = 256 * 1024+/**+ * How long a recycled node's co-viewers wait for the replacement session before they are told the+ * session restarted anyway (see `recycleSession`). The notice normally fires the instant the new+ * session is registered — milliseconds later. This is only the escape hatch for a recycler that+ * never respawns (its app quit / crashed between the kill and the create): the co-viewers are+ * still holding a dead pty, and being released late beats being frozen forever.+ */+const RECYCLE_NOTIFY_TIMEOUT_MS = 10_000++/** Why a session is being ended — the ONE thing `destroySession` could not tell apart. Both kill+ * the tmux session; they differ entirely in what the OTHER viewers are told.+ * - `delete`: the × / node deletion. The node leaves the canvas: co-viewers get `pty:closed`+ * ("closed by <name>") and must never respawn it (that would resurrect a terminal its owner+ * deliberately killed, in a fresh shell, stranding a tmux session).+ * - `recycle`: "move into worktree". The node STAYS on the canvas under the same id and respawns+ * in the new cwd. Co-viewers get `pty:recycled` (restart + re-attach), never the closed state. */+type EndIntent = 'delete' | 'recycle'+/*** Manages all live PTY processes and bridges them to the renderer over IPC.*@@ -353,6 +371,14 @@ export class PtyManager {* 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>>()+ /** persistKey (node id) → the co-viewers of a session that was RECYCLED (moved into a worktree),+ * waiting to be told to restart onto the replacement session. Held — not sent — until that+ * session is registered (`spawnSession`), so a co-viewer's restart can never win the race and+ * spawn the node in its own stale cwd. See `recycleSession`. */+ private pendingRecycle = new Map<+ string,+ { sessionId: string; clients: Set<ClientId>; timer: ReturnType<typeof setTimeout> }+ >()private counter = 0private tmuxPath: string | null = nullprivate confPath = ''@@ -460,6 +486,11 @@ export class PtyManager {platform().onWithSender(IPC.ptyDestroy, (senderId: number, persistKey: string) =>this.destroySession(senderId, persistKey))+ // Sender-aware for the opposite reason: the client that RECYCLED the node drives its own+ // respawn, so it is the one client that must NOT be sent the restart notice.+ platform().onWithSender(IPC.ptyRecycle, (senderId: number, persistKey: string) =>+ this.recycleSession(senderId, persistKey)+ )platform().handle(IPC.ptyReadScrollback, (persistKey: string) =>readScrollback(persistKey))@@ -936,6 +967,11 @@ export class PtyManager {// (relay-served) ptys are deliberately NOT indexed — the relay path keeps its own session,// exactly as before, so this change cannot regress it.if (session.indexKey) this.byPersistKey.set(session.indexKey, sessionId)+ // The replacement session for a RECYCLED node (worktree move) is now live and indexed, so its+ // co-viewers can safely be told to restart: their create() will `join` THIS session instead of+ // spawning `nt-<nodeId>` from their own (stale) cwd. This is the whole reason the notice waits.+ if (session.indexKey && this.pendingRecycle.has(session.indexKey))+ this.fireRecycled(session.indexKey)proc.onData((data) => this.queueData(sessionId, session, data))@@ -949,6 +985,35 @@ export class PtyManager {return sessionId}+ /** Park a recycled session's co-viewers until the replacement session shows up (or the timeout+ * fires). One entry per node: a second recycle before the first resolved supersedes it — the+ * earlier waiters are folded in, since their session is just as dead. */+ private armRecycle(persistKey: string, sessionId: string, clients: ClientId[]): void {+ const prev = this.pendingRecycle.get(persistKey)+ if (prev) {+ clearTimeout(prev.timer)+ for (const c of prev.clients) clients.push(c)+ }+ this.pendingRecycle.set(persistKey, {+ sessionId,+ clients: new Set(clients),+ timer: setTimeout(() => this.fireRecycled(persistKey), RECYCLE_NOTIFY_TIMEOUT_MS)+ })+ }++ /** Tell a recycled node's co-viewers to restart their terminal. Fired the moment the replacement+ * session is registered — or, if none ever is, on the timeout, so nobody is left holding a dead+ * pty forever (their restart then spawns the node itself, which is the best available outcome).+ * The event is keyed by the OLD session id: that is the one their listeners are subscribed to. */+ private fireRecycled(persistKey: string): void {+ const entry = this.pendingRecycle.get(persistKey)+ if (!entry) return+ this.pendingRecycle.delete(persistKey)+ clearTimeout(entry.timer)+ const channel = IPC.ptyRecycled(entry.sessionId)+ for (const client of entry.clients) this.send(client, channel)+ }+/** Drop a dead/released session from both indexes. Keyed off `indexKey` (not `persistKey`,* which is only set for tmux-PERSISTED sessions) so a plain-shell node is un-indexed too. */private forget(sessionId: string, session: Session): void {@@ -1358,39 +1423,79 @@ export class PtyManager {** 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.+ * state, plus a stray tmux session nobody asked for.** `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. The index is the co-attach one (UI- // sessions); the scan is the fallback for a session that is live but not indexed.+ destroySession(clientId: ClientId | null, persistKey: string): Promise<void> {+ return this.endSession(clientId, persistKey, 'delete')+ }++ /**+ * End a node's persistent session so the SAME node id can immediately respawn in a NEW cwd —+ * "move into worktree". The tmux kill is identical to `destroySession` (without it, the respawn's+ * `tmux new-session -A` would just reattach the old session, keeping the old working directory);+ * the INTENT is the opposite: nothing was deleted. The node is still on every canvas and still+ * works, so a co-viewer must not be pushed into the permanent, un-respawnable "closed by <name>"+ * state — that used to strand them on a live node until they deleted and re-added it.+ *+ * What a co-viewer gets instead is `pty:recycled:<oldSessionId>`: restart your terminal, the node+ * moved. Their re-create then CO-ATTACHES to the replacement session (`join`), so they follow the+ * node into its new cwd and are never left holding the dead pty.+ *+ * The notice is deliberately WITHHELD until the replacement session is registered (see+ * `spawnSession`). Sent any earlier, a co-viewer's restart could beat the recycler's own create+ * and spawn `nt-<nodeId>` from ITS options — i.e. in the node's STALE cwd — silently undoing the+ * move for everyone. `RECYCLE_NOTIFY_TIMEOUT_MS` is the escape hatch when no respawn ever comes.+ *+ * `clientId` is the recycler: it drives its own respawn (`respawnNonce`), so it is excluded from+ * the notice. Solo user: there is no one else, so nothing is sent and nothing is armed — the path+ * is the old destroy, minus a fan-out to an empty set.+ */+ recycleSession(clientId: ClientId | null, persistKey: string): Promise<void> {+ return this.endSession(clientId, persistKey, 'recycle')+ }++ /**+ * The shared teardown behind `destroySession` / `recycleSession`: drop the session (and its+ * co-attach index entry, in-flight create, buffered output, flow-control ledger), drop the+ * cold-restore snapshot, and `tmux kill-session`. Everything the two intents disagree about is+ * the ONE branch below — what the other subscribers are told (see `EndIntent`).+ */+ private async endSession(+ clientId: ClientId | null,+ persistKey: string,+ intent: EndIntent+ ): Promise<void> {+ // Both callers run while the session is still live, so its sshRemote is 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) : undefinedconst 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.+ // Un-index NOW (synchronously): this session is finished either way, 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 end.// 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.+ // spawn a fresh session, not await (and then join) the one we are ending.this.inflight.delete(persistKey)if (dyingId && dying) {this.byPersistKey.delete(persistKey)dying.indexKey = undefined- const channel = IPC.ptyClosed(dyingId)- for (const sub of dying.subscribers) {- if (sub !== clientId) this.send(sub, channel, { by: clientId })+ const others = [...dying.subscribers].filter((sub) => sub !== clientId)+ if (intent === 'delete') {+ const channel = IPC.ptyClosed(dyingId)+ for (const sub of others) this.send(sub, channel, { by: clientId })+ } else if (others.length > 0) {+ this.armRecycle(persistKey, dyingId, others)}// 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.)+ // backpressure bookkeeping on the Server Edition shell is pruned by the `pty:closed:` /+ // `pty:recycled:` event itself — see ServerPlatform.forgetFlowState.)if (dying.flushTimer) clearTimeout(dying.flushTimer)dying.subscribers.clear()dying.sizes.clear()@@ -1402,7 +1507,10 @@ export class PtyManager {releasePty(dying.proc as ReleasablePty)this.forget(dyingId, dying)}- // The node is gone for good — drop its cold-restore snapshot too.+ // This session is gone for good — drop its cold-restore snapshot too. A recycle drops it as+ // well (and always did, when the worktree move went through `destroy`): the snapshot is of the+ // OLD cwd's session, and the respawn is a cold start (`fresh`), so replaying it would paint the+ // pre-move terminal into the new one.await deleteScrollback(persistKey)if (sshRemote) {// Remote (ssh-project) node: there is no local tmux session — end the REMOTE one.@@ -1446,6 +1554,10 @@ export class PtyManager {}this.sessions.clear()this.byPersistKey.clear()+ // Pending recycle notices die with the sessions they were waiting on (their timers would+ // otherwise fire into a manager that has released everything).+ for (const entry of this.pendingRecycle.values()) clearTimeout(entry.timer)+ this.pendingRecycle.clear()// Clear the in-flight index with the other two, or a create still spawning at quit would leave// a promise (and the session it resolves to) reachable from a manager that has released// everything else — a later create would then co-attach to a session we already let go.@@ -1453,7 +1565,9 @@ export class PtyManager {return Promise.all(finals).then(() => undefined)}- private send(clientId: ClientId, channel: string, payload: unknown): void {- platform().sendTo(clientId, channel, payload)+ /** Variadic so a payload-less event (`pty:recycled`) sends no argument at all, rather than an+ * explicit `undefined` the shells would have to serialize and the renderer ignore. */+ private send(clientId: ClientId, channel: string, ...args: unknown[]): void {+ platform().sendTo(clientId, channel, ...args)}}diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.tsindex e0e40bdfa..14411936b 100644--- a/src/core/pty-single-user.test.ts+++ b/src/core/pty-single-user.test.ts@@ -351,4 +351,27 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =expect(kills).toHaveLength(1)expect(kills[0].args[kills[0].args.indexOf('-t') + 1]).toBe(sessionName('solo-1'))})++ // ── recycle (move into worktree) = destroy, minus the "someone closed it" fan-out ─────────+ // The solo user's node keeps its id and respawns in the new cwd: the tmux session must die+ // exactly as the × kills it (otherwise `new-session -A` reattaches the OLD working directory),+ // and — with nobody else watching — not a single extra message may go out.+ it('recycle (move into worktree) kills the tmux session exactly like the × does', async () => {+ await tmuxManager()+ const { sessionId } = await create(80, 24)+ fake.sent.length = 0+ await (fake.senderListeners[IPC.ptyRecycle](SOLO, 'solo-1') as unknown as Promise<void>)++ const kills = tmuxCalls('kill-session')+ expect(kills).toHaveLength(1)+ expect(kills[0].args[kills[0].args.indexOf('-t') + 1]).toBe(sessionName('solo-1'))+ expect(spawned[0].killed).toBe(true) // the old pty client is released+ expect(fake.sent).toEqual([]) // solo: nobody to tell, so nothing is sent++ // …and the respawn under the same node id gets a BRAND-NEW session (it never joins the dead one).+ const again = await create(80, 24)+ expect(spawned).toHaveLength(2)+ expect(again.sessionId).not.toBe(sessionId)+ expect(again.fresh).toBe(true)+ })})diff --git a/src/main/index.ts b/src/main/index.tsindex 553f88797..1dc5b5030 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -847,10 +847,14 @@ app.whenReady().then(async () => {}})- // Releasing tails on node close: pty:destroy fires when the user clicks × (persistKey = node- // id). pty-manager already handles the same channel to kill the tmux session; this extra- // listener tears down the per-node file tailers so they stop polling a now-dead session.- ipcMain.on(IPC.ptyDestroy, (_e, nodeId: string) => {+ // Releasing tails when a node's session ENDS — whichever way it ends. pty-manager handles the+ // same two channels to kill the tmux session; this extra listener tears down the per-node file+ // tailers so they stop polling a now-dead session:+ // - pty:destroy — the user clicked × (the node is gone);+ // - pty:recycle — "move into worktree" (the node stays, but its session is replaced, so the+ // tails of the OLD session's transcript are just as dead; the respawned agent re-registers+ // them under its new session id via the hook events).+ const releaseNodeTails = (nodeId: string): void => {const sessionId = nodeContextSession.get(nodeId)if (sessionId) {// Untrack both tails — untracking a non-tracked session is a no-op, so this is safe@@ -871,7 +875,9 @@ app.whenReady().then(async () => {}nodeSubagents.delete(nodeId)}- })+ }+ ipcMain.on(IPC.ptyDestroy, (_e, nodeId: string) => releaseNodeTails(nodeId))+ ipcMain.on(IPC.ptyRecycle, (_e, nodeId: string) => releaseNodeTails(nodeId))// Agent canvas control: the spawned agent's `nodeterm` CLI POSTs a verb to the hook server,// which we forward to the renderer and await a reply. A pending-request map (keyed by a random// requestId) bridges the two async hops; both the reply and the 120s timeout clear the entry.diff --git a/src/preload/index.ts b/src/preload/index.tsindex 3066c25b1..ee078ed18 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -49,6 +49,7 @@ const api: NodeTerminalApi = {setFlow: (sessionId, resume) => ipcRenderer.send(IPC.ptyFlow, sessionId, resume),kill: (sessionId) => ipcRenderer.send(IPC.ptyKill, sessionId),destroy: (persistKey) => ipcRenderer.send(IPC.ptyDestroy, persistKey),+ recycle: (persistKey) => ipcRenderer.send(IPC.ptyRecycle, persistKey),generateName: (persistKey, cwd) => ipcRenderer.invoke(IPC.ptyGenerateName, persistKey, cwd),generateGroupName: (memberKeys, cwd) =>ipcRenderer.invoke(IPC.ptyGenerateGroupName, memberKeys, cwd),@@ -81,6 +82,12 @@ const api: NodeTerminalApi = {ipcRenderer.on(channel, handler)return () => ipcRenderer.removeListener(channel, handler)},+ onRecycled: (sessionId, listener) => {+ const channel = IPC.ptyRecycled(sessionId)+ const handler = (): void => listener()+ ipcRenderer.on(channel, handler)+ return () => ipcRenderer.removeListener(channel, handler)+ },onResync: (sessionId, listener) => {const channel = IPC.ptyResync(sessionId)const handler = (_e: unknown, screen: string) => listener(screen)diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex e367427ed..1175cfdd4 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -164,6 +164,7 @@ function buildRealApi(client: RpcClient): Pick<NodeTerminalApi, 'pty' | 'workspasetFlow: (sessionId, resume) => client.cast(IPC.ptyFlow, sessionId, resume),kill: (sessionId) => client.cast(IPC.ptyKill, sessionId),destroy: (persistKey) => client.cast(IPC.ptyDestroy, persistKey),+ recycle: (persistKey) => client.cast(IPC.ptyRecycle, persistKey),// No server handler — degrade gracefully (never reject the boot path).generateName: () => Promise.resolve(AI_NAMING_UNAVAILABLE),generateGroupName: () => Promise.resolve(AI_NAMING_UNAVAILABLE),@@ -184,6 +185,8 @@ function buildRealApi(client: RpcClient): Pick<NodeTerminalApi, 'pty' | 'workspaonSize: (sessionId, listener) => client.subscribe(IPC.ptySize(sessionId), listener as Listener),onClosed: (sessionId, listener) =>client.subscribe(IPC.ptyClosed(sessionId), listener as Listener),+ onRecycled: (sessionId, listener) =>+ client.subscribe(IPC.ptyRecycled(sessionId), listener as Listener),onResync: (sessionId, listener) =>client.subscribe(IPC.ptyResync(sessionId), listener as Listener)}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 9ec3dd814..16eb96132 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1967,10 +1967,16 @@ export function Canvas() {const parent = nodesRef.current.find((p) => p.id === node?.parentId)const wtPath = parent?.data.worktree?.path as string | undefinedif (!node || node.data.remote || !wtPath || node.data.cwd === wtPath) return- // Permanently end the old tmux session (destroy, not kill) so the respawned create() opens- // a fresh session in the new cwd instead of reattaching to the existing `nt-<id>` session- // (which would keep the old working directory). The node id / persistKey is unchanged.- transport.destroy(id)+ // End the old tmux session (recycle, not kill) so the respawned create() opens a fresh session+ // in the new cwd instead of reattaching to the existing `nt-<id>` session (which would keep the+ // old working directory). The node id / persistKey is unchanged.+ //+ // RECYCLE, not DESTROY: the tmux kill is the same, but this is not a deletion — the node stays+ // on the canvas (here and on every co-viewer's) and keeps working. `destroy` would tell every+ // co-viewer "closed by <name>", which is permanent and un-respawnable: their still-present node+ // would be bricked until they deleted and re-added it. `recycle` tells them to restart onto the+ // replacement session instead, so they follow the node into its new cwd.+ transport.recycle(id)setNodes((ns) =>ns.map((n) =>n.id === iddiff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex f23c3eb07..0a619faa6 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -163,6 +163,7 @@ export function disposeTerminalOnUnmount(id: string): void {noParkIds.add(id)disposeParkedTerminal(id)coStates.delete(id)+ recycledIds.delete(id)}/**@@ -189,6 +190,26 @@ const NO_CO: CoState = { letterbox: false, closed: null }const coStates = new Map<string, CoState>()const coSubs = new Map<string, (s: CoState) => void>()+/**+ * Restart hooks for a RECYCLED node — the other half of the destroy/recycle split.+ *+ * "Move into worktree" ends a node's tmux session so the same node id respawns in the new cwd. It+ * is NOT a deletion: the node stays on every canvas. A co-viewer therefore must not land in the+ * `closed` state above (permanent, un-respawnable) — it has to RESTART its terminal onto the+ * replacement session, which core has already spawned by the time it tells us (so our re-create+ * co-attaches to it rather than spawning the node in our own, stale cwd).+ *+ * The mounted instance publishes its respawn trigger here, for the same reason as `coSubs`: the+ * transport listener is wired once, survives a park, and cannot hold a `setState` of a component+ * that may since have unmounted. No entry = nobody is mounted, and the park (if any) is disposed+ * instead — a parked terminal is holding the dead pty, and the next mount creates fresh.+ */+const restartSubs = new Map<string, () => void>()+/** Node ids whose next spawn is a recycle restart — the new xterm prints a one-line reason (the+ * replacement session is a fresh shell in a different folder, so the screen legitimately changes+ * under the co-viewer and a silent reset would just look like a glitch). */+const recycledIds = new Set<string>()+function getCo(id: string): CoState {return coStates.get(id) ?? NO_CO}@@ -313,6 +334,19 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNif (coSubs.get(id) === setCo_) coSubs.delete(id)}}, [id])+ // Publish this instance's restart trigger for the (park-surviving) onRecycled listener — see+ // restartSubs. Bumping `respawnNonce` re-runs the lifecycle effect below, which is exactly what+ // the mover's own canvas does; the transient nonce is never persisted.+ useEffect(() => {+ const restart = (): void =>+ updateNodeData(id, (n) => ({+ respawnNonce: ((n.data.respawnNonce as number | undefined) ?? 0) + 1+ }))+ restartSubs.set(id, restart)+ return () => {+ if (restartSubs.get(id) === restart) restartSubs.delete(id)+ }+ }, [id, updateNodeData])// The name of the peer who closed this node. Read NON-reactively (getState, not a selector): the// presence store is written at cursor rate and its perf contract reserves subscriptions for the// presence components — a per-terminal subscriber would run on every one of those writes. The@@ -611,6 +645,30 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN}))}+ // Someone else RECYCLED this node (moved it into a worktree): our session id is dead, but a+ // replacement is already live under the same node id. Restart onto it — the node is still+ // on our canvas and still working, so the closed state above would be a lie, and parking+ // this now-dead pty would hand a corpse to the next mount.+ if (transport.onRecycled) {+ cleanups.push(+ transport.onRecycled(sid, () => {+ const restart = restartSubs.get(id)+ if (!restart) {+ disposeParkedTerminal(id) // unmounted: drop the park, the next mount creates fresh+ return+ }+ recycledIds.add(id)+ restart()+ })+ )+ }+ // A restart we did not ask for: say why once, before the new session's output lands. (We+ // JOIN the replacement session, so tmux — which already has a client — does not redraw for+ // us; the first thing on this screen is whatever the new shell prints next.)+ if (recycledIds.delete(id))+ term.write(+ '\r\n\x1b[90m── session restarted by another user (moved to a new folder) ──\x1b[0m\r\n'+ )// We fell so far behind that the server discarded our queued output and redrew us from// tmux. The capture IS the current screen, so reset the emulator and write it — writing it// on top of a stale buffer would splice two different points in time. An EMPTY payload isdiff --git a/src/renderer/terminal/local-transport.ts b/src/renderer/terminal/local-transport.tsindex cb0abe9c2..26ff7b7aa 100644--- a/src/renderer/terminal/local-transport.ts+++ b/src/renderer/terminal/local-transport.ts@@ -36,6 +36,10 @@ export class LocalTransport implements TerminalTransport {this.pty.destroy(persistKey)}+ recycle(persistKey: string): void {+ this.pty.recycle(persistKey)+ }+onData(sessionId: string, listener: (data: string) => void): () => void {return this.pty.onData(sessionId, listener)}@@ -52,6 +56,10 @@ export class LocalTransport implements TerminalTransport {return this.pty.onClosed(sessionId, listener)}+ onRecycled(sessionId: string, listener: () => void): () => void {+ return this.pty.onRecycled(sessionId, listener)+ }+onResync(sessionId: string, listener: (screen: string) => void): () => void {return this.pty.onResync(sessionId, listener)}diff --git a/src/renderer/terminal/remote-transport.ts b/src/renderer/terminal/remote-transport.tsindex 0eb8ec63a..b626bcf45 100644--- a/src/renderer/terminal/remote-transport.ts+++ b/src/renderer/terminal/remote-transport.ts@@ -13,12 +13,13 @@ import type { TerminalTransport } from './transport'* LocalTransport's kill/destroy split, but the client never owns the lifecycle of the host's* persistent session.*- * The co-attach members (`onSize` / `onClosed` / `onResync`) are deliberately NOT implemented:- * the relay frame protocol carries no size, closed or resync frame, and a relay client is a- * mirror of the host's own terminal rather than an equal subscriber of the pty. Omitting the- * optional members makes TerminalNode fall back to today's behavior for relay-backed nodes- * (local FitAddon sizing, no closed overlay, no server-driven repaint) instead of silently- * doing nothing behind an implemented-looking method. See CLAUDE.md, "Three surfaces".+ * The co-attach members (`onSize` / `onClosed` / `onRecycled` / `onResync`) are deliberately NOT+ * implemented: the relay frame protocol carries no size, closed, recycled or resync frame, and a+ * relay client is a mirror of the host's own terminal rather than an equal subscriber of the pty.+ * Omitting the optional members makes TerminalNode fall back to today's behavior for relay-backed+ * nodes (local FitAddon sizing, no closed overlay, no restart-on-recycle, no server-driven repaint)+ * instead of silently doing nothing behind an implemented-looking method. See CLAUDE.md, "Three+ * surfaces".*/export class RemoteTransport implements TerminalTransport {constructor(private readonly connectionId: string) {}@@ -58,6 +59,11 @@ export class RemoteTransport implements TerminalTransport {// No-op: the client doesn't own the host's persistent (tmux) session lifecycle.}+ recycle(_persistKey: string): void {+ // No-op, for the same reason as `destroy` — and unreachable anyway: "move into worktree" is+ // refused for a relay-backed node (Canvas.confirmMoveIntoWorktree), whose cwd lives on the host.+ }+onData(sessionId: string, listener: (data: string) => void): () => void {return this.client.onData(this.connectionId, sessionId, listener)}diff --git a/src/renderer/terminal/transport.ts b/src/renderer/terminal/transport.tsindex 1b235346a..7c32a5cfc 100644--- a/src/renderer/terminal/transport.ts+++ b/src/renderer/terminal/transport.ts@@ -22,8 +22,19 @@ export interface TerminalTransport {setFlow(sessionId: string, resume: boolean): void/** Detaches the client; with tmux the underlying session survives. */kill(sessionId: string): void- /** Permanently ends a node's persistent session. */+ /**+ * Permanently ends a node's persistent session because the node is being DELETED (× / delete).+ * Co-viewers are told "closed by <name>" and must never respawn it.+ */destroy(persistKey: string): void+ /**+ * Ends a node's persistent session so the SAME node id can respawn in a new cwd ("move into+ * worktree"). The tmux kill is identical to `destroy` — without it the respawn would just+ * reattach the old session, keeping the old working directory — but the INTENT is the opposite:+ * the node is not going anywhere. Co-viewers therefore get `onRecycled` (restart, re-attach to+ * the replacement session), never the permanent, un-respawnable closed state.+ */+ recycle(persistKey: string): void/** Listens for output; returns an unsubscribe function. */onData(sessionId: string, listener: (data: string) => void): () => void/** Fires when the session closes; returns an unsubscribe function. */@@ -45,6 +56,14 @@ export interface TerminalTransport {* OPTIONAL for the same reason as onSize. Returns an unsubscribe function.*/onClosed?(sessionId: string, listener: (info: { by: ClientId | null }) => void): () => void+ /**+ * Another client RECYCLED this node (moved it into a worktree): this session id is dead, but a+ * replacement is already live under the same node id — so restart the terminal (its re-create+ * co-attaches to the new session) rather than showing the closed state. Nothing was deleted; the+ * node is still on the canvas and still working.+ * OPTIONAL for the same reason as onSize. Returns an unsubscribe function.+ */+ onRecycled?(sessionId: string, listener: () => void): () => void/*** This client fell so far behind that the server discarded its queued output (WS_DROP_WATER)* and is redrawing it from tmux: clear the emulator and write this capture — it is the CURRENTdiff --git a/src/server/agent-status.ts b/src/server/agent-status.tsindex 26eb5f97b..4857ae2d3 100644--- a/src/server/agent-status.ts+++ b/src/server/agent-status.ts@@ -142,12 +142,15 @@ export function wireAgentStatus(platform: ServerPlatform, opts: WireAgentStatusO}})- // Node close → tear down its tails and clear the maps (server parity with desktop+ // Session end → tear down its tails and clear the maps (server parity with desktop// `src/main/index.ts`'s local `ipcMain.on(IPC.ptyDestroy, …)` branch; the remote/SSH lines are- // dropped — the server has no SSH-project manager). Coexists with PtyManager's own ptyDestroy- // listener via the multi-listener `on`: that one kills the tmux session, this untracks the- // tails. Untracking a non-tracked session/subagent is a no-op, so re-destroy is harmless.- platform.on(IPC.ptyDestroy, (nodeId: string) => {+ // dropped — the server has no SSH-project manager). Coexists with PtyManager's own listeners via+ // the multi-listener `on`: those kill the tmux session, these untrack the tails. Untracking a+ // non-tracked session/subagent is a no-op, so a repeat is harmless.+ // - pty:destroy — the node was deleted;+ // - pty:recycle — the node was moved into a worktree: it stays, but this session is replaced, so+ // the old session's tails are dead either way (the respawned agent re-registers its own).+ const releaseNodeTails = (nodeId: string): void => {const sessionId = nodeContextSession.get(nodeId)if (sessionId) {contextTail.untrack(sessionId)@@ -158,5 +161,7 @@ export function wireAgentStatus(platform: ServerPlatform, opts: WireAgentStatusOfor (const toolUseId of subs) subagentTail.finish(toolUseId)nodeSubagents.delete(nodeId)}- })+ }+ platform.on(IPC.ptyDestroy, (nodeId: string) => releaseNodeTails(nodeId))+ platform.on(IPC.ptyRecycle, (nodeId: string) => releaseNodeTails(nodeId))}diff --git a/src/server/platform-server.ts b/src/server/platform-server.tsindex ee7d22908..8e0495cac 100644--- a/src/server/platform-server.ts+++ b/src/server/platform-server.ts@@ -20,6 +20,9 @@ const PTY_DATA_PREFIX = 'pty:data:'/** Session-death channels — the point where a (client, session)'s backpressure state is pruned. */const PTY_EXIT_PREFIX = 'pty:exit:'const PTY_CLOSED_PREFIX = 'pty:closed:'+/** A recycled session id is dead too (the node respawns under a NEW session id), so its+ * backpressure bookkeeping must be pruned exactly like an exited/closed one. */+const PTY_RECYCLED_PREFIX = 'pty:recycled:'/** Watermarks match the renderer terminal's own flow control. */const WS_HIGH_WATER = 1_000_000const WS_LOW_WATER = 256_000@@ -185,7 +188,9 @@ export class ServerPlatform implements CorePlatform {// alive for a session that no longer exists. Both channels are per-subscriber, so this prunes// exactly the (this client, that session) entries. Costs the healthy path nothing — pty:data// never reaches this branch.- const deadPrefix = [PTY_EXIT_PREFIX, PTY_CLOSED_PREFIX].find((p) => channel.startsWith(p))+ const deadPrefix = [PTY_EXIT_PREFIX, PTY_CLOSED_PREFIX, PTY_RECYCLED_PREFIX].find((p) =>+ channel.startsWith(p)+ )if (deadPrefix) this.forgetFlowState(ServerPlatform.flowKey(uiId, channel.slice(deadPrefix.length)))sink.sendText(JSON.stringify({ t: 'ev', channel, args }))}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 891ebeae6..67da50710 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -7,6 +7,11 @@ export const IPC = {ptyFlow: 'pty:flow',ptyKill: 'pty:kill',ptyDestroy: 'pty:destroy',+ /** End a node's persistent session so the SAME node id can respawn in a new cwd ("move into+ * worktree"). Same tmux kill-session as `ptyDestroy`, but it is NOT a deletion: the node stays+ * on every canvas, so co-viewers get the restart notice (`ptyRecycled`) instead of the+ * permanent, un-respawnable `ptyClosed`. */+ ptyRecycle: 'pty:recycle',ptyGenerateName: 'pty:generate-name',ptyGenerateGroupName: 'pty:generate-group-name',ptyCapture: 'pty:capture',@@ -82,6 +87,12 @@ export const IPC = {/** The node was permanently destroyed by another client (payload: { by: ClientId }). The* remaining subscribers show a "closed by <name>" state instead of respawning the session. */ptyClosed: (sessionId: string) => `pty:closed:${sessionId}`,+ /** The node's session was RECYCLED by another client (moved into a worktree): this session id is+ * dead, but a replacement is already live under the same node id — restart the terminal so it+ * co-attaches to it. Deliberately emitted only AFTER the replacement session exists (see+ * PtyManager.recycleSession), so a co-viewer's restart can never spawn the node in its own,+ * stale cwd. No payload. */+ ptyRecycled: (sessionId: string) => `pty:recycled:${sessionId}`,/** Redraw for a client that fell too far behind: the session's CURRENT screen, captured from* tmux. Sent instead of the discarded backlog (payload: the capture text). The terminal clears* and repaints from it — see ServerPlatform's WS_DROP_WATER.diff --git a/src/shared/types.ts b/src/shared/types.tsindex 05bb99f54..98bfb974c 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -212,8 +212,13 @@ export interface PtyApi {setFlow(sessionId: string, resume: boolean): void/** Detaches/terminates the PTY client (the underlying tmux session survives). */kill(sessionId: string): void- /** Permanently ends the persistent session for a node (kills its tmux session). */+ /** Permanently ends the persistent session for a node (kills its tmux session) because the node+ * is being DELETED. Co-viewers get `onClosed` and must not respawn it. */destroy(persistKey: string): void+ /** Ends a node's persistent session so the SAME node id respawns in a new cwd ("move into+ * worktree"). Same tmux kill as `destroy`, opposite intent: the node stays on the canvas, so+ * co-viewers get `onRecycled` (restart + re-attach), never the permanent closed state. */+ recycle(persistKey: string): void/** Suggest a terminal title from its recent output via the configured AI agent. */generateName(persistKey: string, cwd: string): Promise<GitResult>/** Suggest a group title from its member terminals' recent output via the configured AI agent. */@@ -242,6 +247,11 @@ export interface PtyApi {* client's ClientId, or null when the destroy was not attributed to a client (a local desktop* destroy); resolve it to a name via the presence store. Returns an unsubscribe. */onClosed(sessionId: string, listener: (info: { by: ClientId | null }) => void): () => void+ /** Another client RECYCLED this node (moved it into a worktree): this session id is dead, but a+ * replacement is already live under the same node id. Restart the terminal — the re-create+ * co-attaches to it — instead of showing the closed state: nothing was deleted. No payload.+ * Returns an unsubscribe. */+ onRecycled(sessionId: string, listener: () => void): () => void/** We fell too far behind and the server dropped our queued output; this is the session's* CURRENT screen captured from tmux. Reset the emulator and repaint from it.* CONTRACT: the payload is guaranteed NON-EMPTY (a failed capture is retried, never sent). The