Skip to content

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.

fix(terminal): co-attach review fixes (park-safe fit, no lost worktree move, respawn tombstone)

enes6a32a3351fd2
diff --git a/docs/team-presence.md b/docs/team-presence.md
index 5de3176b1..6489ac971 100644
--- a/docs/team-presence.md
+++ b/docs/team-presence.md
@@ -208,14 +208,40 @@ Killing a node's tmux session is used for two opposite intents, and PtyManager k
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,
+ canvas and keeps working. Co-viewers get `pty:recycled:<sid> { ready }`: 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.
+The recycled notice is **withheld until the replacement session is registered** (`ready:true`). 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.
+
+A recycler can die between the `kill-session` and its own `create()` (app quit / crash), so a 10 s
+timeout releases the co-viewers anyway — with **`ready:false`**, which means *do not respawn*. This
+is the one case where restarting is worse than not: a co-viewer's create options still carry the
+node's **old cwd** (a cwd change is not broadcast on this branch), so its spawn would put
+`nt-<nodeId>` back in the stale folder — and when the mover's app returns, its own `new-session -A`
+**reattaches** that session (the cwd option is ignored on attach), so *everyone's* node would claim
+the worktree path while the shell sits in the old directory. Silent, and exactly what the withheld
+notice exists to prevent. So the terminal shows **"session ended — reopen to restart"** instead: the
+move can be lost only by an explicit user click, never by a timeout.
+
+### The respawn guard — and the tombstone that backs it
+
+`pty:closed` only reaches a session's **subscribers**. A co-viewer whose project is *inactive or
+closed* has no mounted terminal, so it is not one — yet the node is still on its canvas. Its next
+`create` for that node (opening the project later) would find no session, fail `tmux has-session`,
+and spawn a brand-new one: the deleted terminal, resurrected as a fresh shell.
+
+`PtyManager.tombstones` closes that: a destroyed `persistKey` is remembered, and a later `create`
+for it by **another** client is refused (`PtyCreateResult.closed = { by }`) instead of spawning —
+the renderer lands in the same "closed by <name>" state. The destroying client is **exempt**, so its
+own ⌘Z (undo of a delete) still restores the node, and the single-user path is untouched. A
+`recycle` clears the tombstone (nothing was deleted).
+
+Its limits are real (see Known risks): the tombstone is in-memory, so it lives exactly as long as
+the core process. The complete fix is Stage 3's canvas-delete **mutation**, which removes the node
+from every canvas so no client is left holding one to re-create.
## Canvas sync
@@ -363,3 +389,11 @@ same identity. Call them **A** and **B**; log both in with the shared password.
- **Concurrent typing garbles input** — accepted; the badge is the warning.
- **Cross-user undo** — last-write-wins, no CRDT.
- **Cursor traffic** is 20 Hz × peers: comfortable for a 5–10 person team, not for a public room.
+- **A deleted node can still be resurrected across a core restart.** The respawn guard is two
+ layers: the `pty:closed` event (subscribers only) and the in-memory `tombstones` map (everyone
+ else, for as long as the core process lives). Restart the core — the Server Edition process, the
+ desktop app hosting the relay — and the tombstones are gone: a client whose canvas still carries
+ the deleted node will spawn a fresh `nt-<id>` for it the next time it opens that project. The
+ tombstone is deliberately not persisted, because persistence is not the missing piece: the node
+ should not be on that canvas at all. Stage 3's canvas-delete mutation removes it from every
+ client, which is the actual fix; until then this is a bounded, honestly-named gap, not a promise.
diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.ts
index bb36c90d9..0de9bc762 100644
--- a/src/core/pty-coattach.test.ts
+++ b/src/core/pty-coattach.test.ts
@@ -76,6 +76,7 @@ describe('terminal co-attach: one PTY, N subscribers', () => {
fake.handlers[IPC.ptyCreate](clientId, { cols, rows, persistKey }) as Promise<{
sessionId: string
fresh: boolean
+ closed?: { by: number | null }
}>
// pty:kill is sender-aware (it unsubscribes ONE client), so it lands in senderListeners.
const kill = (clientId: number, sessionId: string) =>
@@ -166,14 +167,15 @@ describe('terminal co-attach: one PTY, N subscribers', () => {
expect(spawned[0].writes).toEqual(['a', 'b'])
})
- it('a destroyed node is never co-attached to (the × path un-indexes it)', async () => {
+ it('a destroyed node is never co-attached to, and never respawned (the × path un-indexes + tombstones it)', async () => {
const m = await manager()
- const first = await create(ALICE)
+ await create(ALICE)
await m.destroySession(ALICE, 'node-1') // user clicked ×: the tmux session is gone for good
const second = await create(BOB)
- expect(second.sessionId).not.toBe(first.sessionId)
- expect(spawned).toHaveLength(2)
+ expect(second.sessionId).toBe('') // neither the dead session…
+ expect(second.closed).toEqual({ by: ALICE }) // …nor a fresh one: the node is gone
+ expect(spawned).toHaveLength(1)
})
it('a relay-served (detached) pty is NOT indexed: it keeps its own session', async () => {
@@ -559,6 +561,7 @@ describe('node destroyed while co-viewed', () => {
fake.handlers[IPC.ptyCreate](clientId, { cols: 80, rows: 24, persistKey }) as Promise<{
sessionId: string
fresh: boolean
+ closed?: { by: number | null }
}>
// pty:destroy is sender-aware: the closed event has to name WHO pressed ×.
const destroy = (clientId: number, persistKey = 'node-1') =>
@@ -582,16 +585,58 @@ describe('node destroyed while co-viewed', () => {
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 () => {
+ // The `pty:closed` event only reaches SUBSCRIBERS. A co-viewer whose project is inactive/closed
+ // has no mounted terminal, is not subscribed, and hears nothing — its canvas still has the node,
+ // so opening that project later would `create` it and RESURRECT a terminal its owner deliberately
+ // deleted, in a fresh shell. The tombstone is what makes that create refuse instead of spawn.
+ it('a create by ANOTHER client after the destroy is refused — it never resurrects the node', async () => {
await manager()
- const { sessionId } = await create(ALICE)
+ 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(again.closed).toEqual({ by: ALICE }) // "closed by Alice", not a brand-new shell
+ expect(again.sessionId).toBe('')
+ expect(spawned).toHaveLength(1) // …and nothing was spawned
+ })
+
+ it('a create by a client that never saw the destroy is refused too (unsubscribed co-viewer)', async () => {
+ await manager()
+ await create(ALICE)
+ await destroy(ALICE) // Carol was not watching — she got no pty:closed
+
+ const carol = await create(CAROL)
+ expect(carol.closed).toEqual({ by: ALICE })
+ expect(spawned).toHaveLength(1)
+ })
+
+ it('the client that DELETED the node may still respawn it (undo) — and that clears the tombstone', async () => {
+ await manager()
+ await create(ALICE)
+ await destroy(ALICE)
+
+ // ⌘Z restores the node on Alice's canvas: her own re-create must spawn, exactly as it always
+ // did (the single-user delete→undo path is untouched by the tombstone).
+ const undone = await create(ALICE)
+ expect(undone.closed).toBeUndefined()
+ expect(undone.fresh).toBe(true)
+ expect(spawned).toHaveLength(2)
+ // The node is alive again, so a co-viewer must be able to join it rather than stay tombstoned.
+ const bob = await create(BOB)
+ expect(bob.sessionId).toBe(undone.sessionId)
+ })
+
+ it('a RECYCLE (worktree move) leaves no tombstone — the node is not deleted', async () => {
+ await manager()
+ await create(ALICE)
+ await create(BOB)
+ await (fake.senderListeners[IPC.ptyRecycle](ALICE, 'node-1') as unknown as Promise<void>)
+
+ const again = await create(ALICE) // the mover respawns in the new cwd
+ expect(again.closed).toBeUndefined()
+ const bob = await create(BOB) // and the co-viewer joins it
+ expect(bob.sessionId).toBe(again.sessionId)
expect(spawned).toHaveLength(2)
})
@@ -702,6 +747,8 @@ describe('node recycled (worktree move) while co-viewed', () => {
expect(spawned).toHaveLength(2)
expect(fresh.sessionId).not.toBe(sessionId)
expect(recycled(sessionId).map((s) => s.to)).toEqual([BOB]) // only now is Bob told
+ // `ready` is what makes Bob's restart safe: there IS a session to co-attach to.
+ expect(recycled(sessionId)[0].args[0]).toEqual({ ready: true })
const bob = await create(BOB) // Bob's terminal restarts…
expect(bob.sessionId).toBe(fresh.sessionId) // …onto the LIVE new session
@@ -730,6 +777,11 @@ describe('node recycled (worktree move) while co-viewed', () => {
// 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])
+ // …but it says there is NOTHING to restart onto. Bob must not spawn `nt-node-1` himself: his
+ // options still carry the node's OLD cwd, so his session would silently undo the move (and
+ // Alice's app, on its return, would `new-session -A` straight back into that stale-cwd
+ // session). He shows "session ended — reopen to restart" instead.
+ expect(recycled(sessionId)[0].args[0]).toEqual({ ready: false })
})
it('a recycle with no other subscriber notifies nobody (the solo path is untouched)', async () => {
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 8a2b32af9..db22da7b5 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -379,6 +379,28 @@ export class PtyManager {
string,
{ sessionId: string; clients: Set<ClientId>; timer: ReturnType<typeof setTimeout> }
>()
+ /**
+ * persistKey (node id) → the client that DELETED it. The respawn guard for clients the
+ * `pty:closed` event cannot reach.
+ *
+ * `pty:closed` fans out to the dying session's SUBSCRIBERS. A co-viewer whose project is
+ * inactive or closed has no mounted terminal, is not a subscriber, and is told nothing — yet the
+ * node is still on its canvas. When it opens that project, its `create` finds no session, `tmux
+ * has-session` fails, and it would SPAWN A BRAND-NEW `nt-<id>`: a terminal its owner deliberately
+ * deleted, resurrected as a fresh shell, plus a stray tmux session nobody asked for. The
+ * tombstone makes that create refuse (`PtyCreateResult.closed`) instead.
+ *
+ * Deliberate limits, because this is the smallest honest fix and not the real one:
+ * - it is IN-MEMORY, so it dies with the core process. Co-attach means one core with N clients
+ * (Server Edition / relay), so it covers every co-viewer for as long as that core lives — but
+ * after a server restart the resurrection is back.
+ * - it is keyed by the DESTROYER, who is exempt: their own ⌘Z (undo of a delete) must still
+ * restore the node, and a solo user is always the destroyer, so their path is untouched.
+ * - a `recycle` (worktree move) explicitly CLEARS it: nothing was deleted there.
+ * The real fix is Stage 3's canvas-delete mutation, which removes the node from every canvas so
+ * no client is left holding one to re-create. See docs/team-presence.md (Known risks).
+ */
+ private tombstones = new Map<string, { by: ClientId | null }>()
private counter = 0
private tmuxPath: string | null = null
private confPath = ''
@@ -526,6 +548,11 @@ export class PtyManager {
// on a *new* in-flight entry is exactly the same wait as the one we just did.
if (this.inflight.get(key)) return this.create(clientId, options)
}
+ // Another client DELETED this node (and there is no live session for it — `join` above already
+ // covers a resurrection by its owner). Refuse rather than spawn: see `tombstones`. Checked
+ // AFTER the in-flight barrier so a create racing the owner's own respawn joins it instead.
+ const tomb = this.tombstones.get(key)
+ if (tomb && tomb.by !== clientId) return { sessionId: '', fresh: false, closed: { by: tomb.by } }
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
@@ -967,11 +994,16 @@ 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)
+ // This node has a live session again, so it is no longer deleted: drop any tombstone. Only the
+ // destroyer can even reach a spawn for a tombstoned node (create() refuses everyone else), so
+ // this is exactly "the owner brought the node back" (⌘Z) — and its co-viewers must be able to
+ // join the new session rather than stay refused.
+ if (session.indexKey) this.tombstones.delete(session.indexKey)
// 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)
+ this.fireRecycled(session.indexKey, true)
proc.onData((data) => this.queueData(sessionId, session, data))
@@ -997,21 +1029,34 @@ export class PtyManager {
this.pendingRecycle.set(persistKey, {
sessionId,
clients: new Set(clients),
- timer: setTimeout(() => this.fireRecycled(persistKey), RECYCLE_NOTIFY_TIMEOUT_MS)
+ timer: setTimeout(() => this.fireRecycled(persistKey, false), 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 {
+ /**
+ * Release a recycled node's co-viewers from the dead session. The event is keyed by the OLD
+ * session id — that is the one their listeners are subscribed to — and carries the ONE thing they
+ * cannot know and must not guess: whether there is a replacement session to restart onto.
+ *
+ * `ready` (fired the moment the replacement is registered) → restart: their create() joins it and
+ * they follow the node into its new cwd.
+ *
+ * `!ready` (the escape-hatch timeout: the recycler's app died between the kill and its create) →
+ * the terminal ENDS and offers a manual reopen. It must NOT auto-respawn: a co-viewer's create
+ * options still carry the node's OLD cwd (a cwd change is not broadcast to other clients on this
+ * branch), so it would spawn `nt-<id>` in the stale directory — and when the mover's app comes
+ * back, its own `new-session -A` REATTACHES that stale-cwd session (the cwd option is ignored on
+ * attach). Everyone's node would then claim the worktree path while the shell sits in the old
+ * folder: exactly the silent failure the withheld notice exists to prevent, just 10 s later. An
+ * ended terminal is honest, recoverable, and cannot lose the move.
+ */
+ private fireRecycled(persistKey: string, ready: boolean): 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)
+ for (const client of entry.clients) this.send(client, channel, { ready })
}
/** Drop a dead/released session from both indexes. Keyed off `indexKey` (not `persistKey`,
@@ -1423,7 +1468,9 @@ 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.
+ * state, plus a stray tmux session nobody asked for. It only reaches SUBSCRIBERS, though, so the
+ * destroy also leaves a `tombstone`: a client that was never subscribed (its project is closed /
+ * inactive, so it has no mounted terminal) is refused at `create` time instead.
*
* `clientId` is null when nothing/no-one attributable did it (an internal caller).
*/
@@ -1479,6 +1526,12 @@ export class PtyManager {
// 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 ending.
this.inflight.delete(persistKey)
+ // A DELETE is remembered (the respawn guard for clients `pty:closed` cannot reach — see
+ // `tombstones`); a RECYCLE explicitly forgets, because the node is not going anywhere and its
+ // replacement session must be spawnable. Recorded even when no live session exists in this
+ // process: the node may be deleted from a canvas whose terminal was never opened here.
+ if (intent === 'delete') this.tombstones.set(persistKey, { by: clientId })
+ else this.tombstones.delete(persistKey)
if (dyingId && dying) {
this.byPersistKey.delete(persistKey)
dying.indexKey = undefined
diff --git a/src/preload/index.ts b/src/preload/index.ts
index ee078ed18..8b35a7b92 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -6,6 +6,7 @@ import type {
NodeTerminalApi,
Project,
PtyCreateOptions,
+ RecycledInfo,
UpdateInfo,
UpdateProgress,
Workspace
@@ -84,7 +85,7 @@ const api: NodeTerminalApi = {
},
onRecycled: (sessionId, listener) => {
const channel = IPC.ptyRecycled(sessionId)
- const handler = (): void => listener()
+ const handler = (_e: unknown, info: RecycledInfo): void => listener(info)
ipcRenderer.on(channel, handler)
return () => ipcRenderer.removeListener(channel, handler)
},
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 0a619faa6..9af615ab3 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -29,11 +29,15 @@ import { useSettings } from '../state/settings'
import { useAgentStatus, inferInterruptAfterSettle } from '../state/agentStatus'
import {
closedByLabel,
- isLetterboxed,
+ forgetNodeTermState,
+ letterboxFor,
+ markRecycled,
+ recycleAction,
reportedSize,
+ setFittedSize,
shouldApplyResync,
- toXtermText,
- type TermSize
+ takeRecycled,
+ toXtermText
} from '../terminal/terminal-config'
import { reportFocus, releaseFocus, usePresence } from '../state/presence'
import type { ClientId } from '@shared/presence'
@@ -163,7 +167,27 @@ export function disposeTerminalOnUnmount(id: string): void {
noParkIds.add(id)
disposeParkedTerminal(id)
coStates.delete(id)
- recycledIds.delete(id)
+ forgetNodeTermState(id)
+}
+
+/**
+ * Resize the emulator the way `FitAddon.fit()` does — clearing the render service FIRST.
+ *
+ * We drive `term.resize()` ourselves (the pty, not the fit, is the authority on the grid under
+ * co-attach), and the `clear()` is not decoration: it forces a full repaint, without which
+ * shrinking a terminal can leave stale glyph rows behind in the area that was cut. That is a
+ * regression EVERY user would hit on a plain drag-resize, solo included — so we keep the addon's
+ * behavior byte for byte. Private API (`_core._renderService`), exactly as addon-fit uses it, so it
+ * is fail-soft: if xterm ever renames it, we still resize.
+ */
+function resizeTerm(term: Terminal, cols: number, rows: number): void {
+ if (term.cols === cols && term.rows === rows) return
+ try {
+ ;(term as unknown as { _core: { _renderService: { clear(): void } } })._core._renderService.clear()
+ } catch {
+ // private API moved — the resize below still happens (worst case: a stale row until the next paint)
+ }
+ term.resize(cols, rows)
}
/**
@@ -185,8 +209,20 @@ interface CoState {
letterbox: boolean
/** Set once the session was destroyed by someone else. `by` is null for an unattributed destroy. */
closed: { by: ClientId | null } | null
+ /**
+ * The session ENDED under us and there is nothing to re-attach to, but the node is NOT deleted:
+ * the client that recycled it (moved it into a worktree) never registered a replacement session
+ * — its app quit or crashed mid-move — so core released us on the escape-hatch timeout.
+ *
+ * We must not respawn: our create options still carry the node's OLD cwd (the mover's cwd change
+ * is not broadcast to us), so we would spawn `nt-<id>` in the stale folder and the mover's own
+ * `new-session -A` would then reattach it — everyone's node claiming the worktree path with a
+ * shell sitting somewhere else. So the terminal ends and the user reopens it deliberately, which
+ * is recoverable and, unlike a silent stale-cwd respawn, honest. Cleared by that reopen.
+ */
+ ended: boolean
}
-const NO_CO: CoState = { letterbox: false, closed: null }
+const NO_CO: CoState = { letterbox: false, closed: null, ended: false }
const coStates = new Map<string, CoState>()
const coSubs = new Map<string, (s: CoState) => void>()
@@ -205,10 +241,6 @@ const coSubs = new Map<string, (s: CoState) => void>()
* 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
@@ -219,7 +251,8 @@ function setCo(id: string, patch: Partial<CoState>): void {
const next = { ...prev, ...patch }
// A no-op write must stay a no-op: applyFit clears the letterbox on every fit, and handing the
// node a fresh object each time would re-render it for nothing (and, solo, on every resize tick).
- if (next.letterbox === prev.letterbox && next.closed === prev.closed) return
+ if (next.letterbox === prev.letterbox && next.closed === prev.closed && next.ended === prev.ended)
+ return
coStates.set(id, next)
coSubs.get(id)?.(next)
}
@@ -353,6 +386,15 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// overlay is terminal state anyway, so resolving the name when `co.closed` appears is enough.
const closedName = co.closed ? closedByLabel(co.closed.by, usePresence.getState().peers) : ''
+ // "Session ended" (a recycle whose replacement never came — see CoState.ended): the user asks for
+ // a shell explicitly. Only now do we spawn, in THIS client's cwd — no silent stale-cwd respawn.
+ const reopenEnded = (): void => {
+ setCo(id, { ended: false })
+ updateNodeData(id, (n) => ({
+ respawnNonce: ((n.data.respawnNonce as number | undefined) ?? 0) + 1
+ }))
+ }
+
// Stable fallback reader: serialize the live xterm buffer when tmux capture is unavailable.
const readBuffer = useCallback(() => {
const t = termRef.current
@@ -466,8 +508,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// the other viewer's (larger) grid. Zeroed here, so an adopting client always re-reports.
let sentCols = 0
let sentRows = 0
- /** What we last reported — the reference the letterbox is measured against. */
- let fitted: TermSize | null = null
+ // What we last REPORTED — the reference the letterbox is measured against — is published to a
+ // module-level registry (`setFittedSize`), NOT held here: the `onSize` listener that reads it is
+ // wired once and SURVIVES a park, so a closure variable would leave it comparing the pty's size
+ // against a previous mount's grid (see terminal-config's fittedByNode).
/**
* Co-attach sizing: we REPORT what we could render (`proposeDimensions`) and the pty tells us
@@ -487,10 +531,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
const size = reportedSize(fit.proposeDimensions())
if (!size) return
if (size.cols === sentCols && size.rows === sentRows) return
- fitted = size
+ setFittedSize(id, size)
sentCols = size.cols
sentRows = size.rows
- if (term.cols !== size.cols || term.rows !== size.rows) term.resize(size.cols, size.rows)
+ resizeTerm(term, size.cols, size.rows)
setCo(id, { letterbox: false })
// Before the session exists we are the only voice: the size rides the initial `create()`.
if (sessionId) transport.resize(sessionId, size.cols, size.rows)
@@ -579,16 +623,23 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// Prefetch the persisted scrollback in parallel with the spawn so it's ready to replay the
// instant the session resolves (a cold restart after a reboot recreates the tmux session
// empty — see the `fresh` handling below). Cheap no-op ('') when there's no snapshot.
+ const noSpawn = !!getCo(id).closed || getCo(id).ended
const scrollbackPromise =
- parked || getCo(id).closed
+ parked || noSpawn
? Promise.resolve('')
: window.nodeTerminal.pty.readScrollback(id).catch(() => '')
+ // Consume the recycle-restart flag HERE, at the start of the spawn it belongs to — not in the
+ // create() continuation, which returns early when the node unmounted mid-spawn and would leave
+ // the flag set for some unrelated mount hours later ("session restarted by another user" out of
+ // nowhere). The banner is printed below once the session resolves.
+ const wasRecycled = takeRecycled(id)
void (async () => {
if (parked) return // adopted a live session — nothing to spawn or replay
- // Another client DESTROYED this node's session (tmux kill-session — for everyone). Never
- // spawn: `create(persistKey)` would happily start a brand-new tmux session and resurrect a
- // terminal its owner deliberately killed. The overlay explains the state instead.
- if (getCo(id).closed) return
+ // Another client DESTROYED this node's session (tmux kill-session — for everyone), or it was
+ // recycled with no replacement to re-attach to. Never spawn: `create(persistKey)` would
+ // happily start a brand-new tmux session — resurrecting a terminal its owner deliberately
+ // killed, or reviving this node in our STALE cwd. The overlay explains the state instead.
+ if (noSpawn) return
// SSH-project terminal: the project's live ControlMaster controlPath is established by
// Canvas's active-project effect. On a cold app load child effects run before that parent
// connect, so wait for it (briefly) before spawning. In Phase 1 a node only exists in the
@@ -613,7 +664,15 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
accountId: data.accountId,
sshRemote
})
- .then(async ({ sessionId: sid, fresh, accountFallback: fellBack }) => {
+ .then(async ({ sessionId: sid, fresh, accountFallback: fellBack, closed }) => {
+ // REFUSED: core's tombstone says another client deleted this node while we weren't
+ // subscribed (our project was closed/inactive, so no `pty:closed` could reach us). Nothing
+ // was spawned — land in the same "closed by <name>" state a subscribed co-viewer gets.
+ if (closed) {
+ setCo(id, { closed })
+ if (!disposed) term.write('\r\n\x1b[90m[session closed by another user]\x1b[0m\r\n')
+ return
+ }
if (disposed) {
transport.kill(sid)
return
@@ -629,9 +688,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
if (transport.onSize) {
cleanups.push(
transport.onSize(sid, (size) => {
- if (term.cols !== size.cols || term.rows !== size.rows)
- term.resize(size.cols, size.rows)
- setCo(id, { letterbox: isLetterboxed(size, fitted) })
+ resizeTerm(term, size.cols, size.rows)
+ // Measured against the CURRENT mount's fit (the registry, not a closure): this
+ // listener outlives the mount that wired it — see terminal-config's fittedByNode.
+ setCo(id, { letterbox: letterboxFor(id, size) })
})
)
}
@@ -645,19 +705,28 @@ 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.
+ // Someone else RECYCLED this node (moved it into a worktree): our session id is dead. If a
+ // replacement is already live under the same node id (`ready`), 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 NO replacement ever
+ // came (the mover's app died mid-move), we must NOT respawn: our options still carry the
+ // node's stale cwd, and spawning it would silently undo the worktree move for everyone —
+ // the terminal ends instead, with a reopen (see CoState.ended / recycleAction).
if (transport.onRecycled) {
cleanups.push(
- transport.onRecycled(sid, () => {
+ transport.onRecycled(sid, (info) => {
+ if (recycleAction(info) === 'ended') {
+ disposeParkedTerminal(id) // the park holds a dead pty either way
+ setCo(id, { ended: true })
+ term.write('\r\n\x1b[90m[session ended — reopen to restart]\x1b[0m\r\n')
+ return
+ }
const restart = restartSubs.get(id)
if (!restart) {
disposeParkedTerminal(id) // unmounted: drop the park, the next mount creates fresh
return
}
- recycledIds.add(id)
+ markRecycled(id)
restart()
})
)
@@ -665,7 +734,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// 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))
+ if (wasRecycled)
term.write(
'\r\n\x1b[90m── session restarted by another user (moved to a new folder) ──\x1b[0m\r\n'
)
@@ -793,9 +862,11 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// A respawn (worktree move: the ref was bumped before this cleanup ran) needs a FRESH
// session in the new cwd — never park it. A plain unmount with a live session parks:
// the xterm (element detached) and its PTY stay alive so a remount re-adopts them. A session
- // another client destroyed is gone — nothing to park (and nothing left to keep alive).
+ // another client destroyed — or ended under us with no replacement — is gone: nothing to park
+ // (and nothing left to keep alive).
const isRespawn = respawnNonceRef.current !== myNonce
- if (sessionId && !isRespawn && !getCo(id).closed && !noParkIds.delete(id)) {
+ const co = getCo(id)
+ if (sessionId && !isRespawn && !co.closed && !co.ended && !noParkIds.delete(id)) {
// Park = "subscribed, but not viewing": report no size at all, so this window's (possibly
// small) grid stops clamping every other subscriber's terminal for the next five minutes.
// The subscription itself stays — output keeps streaming into the parked xterm — and the
@@ -1332,6 +1403,14 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
Closed by {closedName} — this session was ended.
</div>
)}
+ {!co.closed && co.ended && (
+ <div className="term-node__closed nodrag">
+ <span>Session ended — the node was moved and never came back.</span>
+ <button className="term-node__reopen" onClick={reopenEnded}>
+ Reopen
+ </button>
+ </div>
+ )}
{armed && !mdMode && (
<div
className="term-hover-guard"
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 629417ab7..f6c4f3750 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -1063,6 +1063,24 @@ body,
font-size: 12px;
color: var(--muted);
background: rgba(30, 30, 30, 0.88);
+ flex-direction: column;
+ gap: 10px;
+}
+
+/* "Session ended — reopen to restart": the ONLY way a terminal whose session was recycled without
+ a replacement gets a shell back. Deliberately a manual action — an automatic respawn would use
+ this client's stale cwd and silently undo the worktree move (see CoState.ended). */
+.term-node__reopen {
+ padding: 4px 12px;
+ border: 1px solid var(--separator);
+ border-radius: 6px;
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--text);
+ font-size: 12px;
+ cursor: pointer;
+}
+.term-node__reopen:hover {
+ background: rgba(255, 255, 255, 0.12);
}
/* Markdown view overlay (Cmd/Ctrl+M) */
diff --git a/src/renderer/terminal/local-transport.ts b/src/renderer/terminal/local-transport.ts
index 26ff7b7aa..b2e448fe2 100644
--- a/src/renderer/terminal/local-transport.ts
+++ b/src/renderer/terminal/local-transport.ts
@@ -1,4 +1,4 @@
-import type { PtyCreateOptions, PtyCreateResult } from '@shared/types'
+import type { PtyCreateOptions, PtyCreateResult, RecycledInfo } from '@shared/types'
import type { ClientId } from '@shared/presence'
import type { TerminalTransport } from './transport'
@@ -56,7 +56,7 @@ export class LocalTransport implements TerminalTransport {
return this.pty.onClosed(sessionId, listener)
}
- onRecycled(sessionId: string, listener: () => void): () => void {
+ onRecycled(sessionId: string, listener: (info: RecycledInfo) => void): () => void {
return this.pty.onRecycled(sessionId, listener)
}
diff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.ts
index d24fd7398..0a7fd2fc7 100644
--- a/src/renderer/terminal/terminal-config.test.ts
+++ b/src/renderer/terminal/terminal-config.test.ts
@@ -1,9 +1,15 @@
-import { describe, it, expect } from 'vitest'
+import { describe, it, expect, beforeEach } from 'vitest'
import {
closedByLabel,
+ forgetNodeTermState,
isLetterboxed,
+ letterboxFor,
+ markRecycled,
+ recycleAction,
reportedSize,
+ setFittedSize,
shouldApplyResync,
+ takeRecycled,
toXtermText
} from './terminal-config'
import type { ClientId } from '@shared/presence'
@@ -69,3 +75,76 @@ describe('closedByLabel', () => {
expect(closedByLabel(99 as ClientId, peers)).toBe('another user')
})
})
+
+// The fitted size is read by the pty:size listener, which is wired ONCE and SURVIVES a park
+// (the terminal is adopted by a later mount with its listeners intact). It therefore may not
+// live in the mounting effect's closure: after a park/adopt, the listener would keep measuring
+// the letterbox against the PRE-PARK grid — so a co-viewer who parks, changes the font size and
+// comes back gets a letterbox he shouldn't have (or loses one he should).
+describe('fitted-size registry (survives a park, like the listeners that read it)', () => {
+ beforeEach(() => forgetNodeTermState('n1'))
+
+ it('measures the letterbox against the fit of the CURRENTLY mounted terminal', () => {
+ // Mount A fits 120×40 and wires the pty:size listener.
+ setFittedSize('n1', { cols: 120, rows: 40 })
+ const onSize = (size: { cols: number; rows: number }): boolean => letterboxFor('n1', size)
+ expect(onSize({ cols: 80, rows: 24 })).toBe(true) // a smaller co-viewer clamps us → letterbox
+
+ // Park + adopt: the SAME listener lives on, but the user bumped the font size, so mount B
+ // fits a smaller grid — which is now exactly the pty's size. No letterbox.
+ setFittedSize('n1', { cols: 80, rows: 24 })
+ expect(onSize({ cols: 80, rows: 24 })).toBe(false)
+ })
+
+ it('reports no letterbox for a node that has never reported a fit', () => {
+ expect(letterboxFor('never-fitted', { cols: 80, rows: 24 })).toBe(false)
+ })
+
+ it('forgets a node on permanent deletion (a recycled node id must not inherit a stale fit)', () => {
+ setFittedSize('n1', { cols: 200, rows: 60 })
+ forgetNodeTermState('n1')
+ expect(letterboxFor('n1', { cols: 80, rows: 24 })).toBe(false)
+ })
+})
+
+// The "session restarted by another user" banner is armed when the recycle notice lands and must
+// be CONSUMED by the spawn it belongs to — even when that spawn is abandoned (the node unmounted
+// while create() was in flight). A flag left behind would print the banner on some unrelated
+// mount hours later.
+describe('recycle banner flag', () => {
+ beforeEach(() => forgetNodeTermState('n1'))
+
+ it('is consumed exactly once', () => {
+ markRecycled('n1')
+ expect(takeRecycled('n1')).toBe(true)
+ expect(takeRecycled('n1')).toBe(false)
+ })
+
+ it('is false for a node that was never recycled', () => {
+ expect(takeRecycled('n1')).toBe(false)
+ })
+
+ it('is dropped with the node (no stale banner on a much later mount)', () => {
+ markRecycled('n1')
+ forgetNodeTermState('n1')
+ expect(takeRecycled('n1')).toBe(false)
+ })
+})
+
+// The recycle notice carries whether a REPLACEMENT session is already live. Without one (the
+// recycler crashed between the kill and the create), restarting would spawn `nt-<id>` from this
+// client's own — stale — cwd, silently undoing the worktree move for everybody. So: only restart
+// when there is something to restart onto.
+describe('recycleAction', () => {
+ it('restarts onto the replacement session when it is live', () => {
+ expect(recycleAction({ ready: true })).toBe('restart')
+ })
+
+ it('ends the terminal (reopen to restart) when no replacement was ever registered', () => {
+ expect(recycleAction({ ready: false })).toBe('ended')
+ })
+
+ it('treats a payload-less/legacy notice as "no replacement" (never spawn in a stale cwd)', () => {
+ expect(recycleAction(undefined)).toBe('ended')
+ })
+})
diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.ts
index f072aabae..fb6d528b6 100644
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@ -40,6 +40,76 @@ export function isLetterboxed(effective: TermSize, fitted: TermSize | null): boo
return effective.cols < fitted.cols || effective.rows < fitted.rows
}
+/**
+ * Per-node terminal state that must OUTLIVE a mount — because the transport listeners that read it
+ * do. `TerminalNode` wires `onSize` / `onClosed` / `onRecycled` ONCE, in the spawn continuation,
+ * and an adopted (parked) terminal carries those listeners into the next mount without
+ * re-subscribing. Anything they read therefore cannot live in the mounting effect's closure: the
+ * live listener would keep reading MOUNT A's variables while mount B updates its own.
+ *
+ * `fitted` is exactly that: the last size THIS client reported, and the reference the letterbox is
+ * measured against (`letterboxFor`). Park, change the font size, come back — mount B fits a
+ * different grid, and a closure-captured `fitted` would leave the surviving `onSize` listener
+ * comparing the pty's size against the pre-park one, permanently letterboxing a terminal that
+ * should fill its node (or un-letterboxing one that shouldn't).
+ */
+const fittedByNode = new Map<string, TermSize>()
+
+/** Record what this client last REPORTED it can render (called from every applyFit). */
+export function setFittedSize(nodeId: string, size: TermSize): void {
+ fittedByNode.set(nodeId, size)
+}
+
+/** `isLetterboxed` against the CURRENT mount's fit — see `fittedByNode`. */
+export function letterboxFor(nodeId: string, effective: TermSize): boolean {
+ return isLetterboxed(effective, fittedByNode.get(nodeId) ?? null)
+}
+
+/**
+ * Node ids whose next spawn is a recycle RESTART: the co-viewer's session was replaced under it
+ * (someone moved the node into a worktree), and the new xterm prints a one-line reason — the
+ * replacement is a fresh shell in a different folder, so the screen legitimately changes and a
+ * silent reset would just look like a glitch.
+ *
+ * `takeRecycled` consumes the flag, and the spawn path consumes it BEFORE `create()` resolves: a
+ * node that unmounts while its create is in flight abandons that spawn, and a flag left behind
+ * would print "session restarted by another user" on some unrelated mount hours later.
+ */
+const recycledIds = new Set<string>()
+
+export function markRecycled(nodeId: string): void {
+ recycledIds.add(nodeId)
+}
+
+/** Consume the recycle flag: true exactly once per `markRecycled`. */
+export function takeRecycled(nodeId: string): boolean {
+ return recycledIds.delete(nodeId)
+}
+
+/** Drop every cross-mount trace of a node — called when it is permanently deleted. */
+export function forgetNodeTermState(nodeId: string): void {
+ fittedByNode.delete(nodeId)
+ recycledIds.delete(nodeId)
+}
+
+/**
+ * What a `pty:recycled` notice means for this terminal.
+ *
+ * `ready` says a REPLACEMENT session is already registered for the node, so restarting is safe:
+ * our re-create co-attaches to it and we follow the node into its new cwd.
+ *
+ * Without one — the recycler's app died between the `tmux kill-session` and its own `create()`, so
+ * the notice fired on the escape-hatch timeout — a restart would be actively harmful: our create
+ * options still carry the node's OLD cwd (a cwd change is not broadcast to other clients), so we
+ * would spawn `nt-<id>` in the stale directory, and the mover's app, on its return, would
+ * `new-session -A` straight into it. Everyone's node would then claim the worktree path while the
+ * shell sits in the old folder — the exact silent failure the withheld notice exists to prevent.
+ * So we DON'T spawn: the terminal ends, and the user reopens it deliberately if they want a shell.
+ */
+export function recycleAction(info: { ready: boolean } | undefined): 'restart' | 'ended' {
+ return info?.ready ? 'restart' : 'ended'
+}
+
/**
* Should a `pty:resync` payload be painted? The server promises never to send an empty capture,
* but the renderer guards anyway: a resync RESETS the emulator, and a screen reset on an empty
diff --git a/src/renderer/terminal/transport.ts b/src/renderer/terminal/transport.ts
index 7c32a5cfc..e110a7c12 100644
--- a/src/renderer/terminal/transport.ts
+++ b/src/renderer/terminal/transport.ts
@@ -1,4 +1,4 @@
-import type { PtyCreateOptions, PtyCreateResult } from '@shared/types'
+import type { PtyCreateOptions, PtyCreateResult, RecycledInfo } from '@shared/types'
import type { ClientId } from '@shared/presence'
/**
@@ -57,13 +57,16 @@ export interface TerminalTransport {
*/
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.
+ * Another client RECYCLED this node (moved it into a worktree): this session id is dead. With
+ * `ready:true` 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.
+ * With `ready:false` NO replacement ever came (the recycler's app died mid-move): do not
+ * respawn — a restart would spawn the node in this client's own, stale cwd and silently undo the
+ * move. The terminal ends and offers a manual reopen.
* OPTIONAL for the same reason as onSize. Returns an unsubscribe function.
*/
- onRecycled?(sessionId: string, listener: () => void): () => void
+ onRecycled?(sessionId: string, listener: (info: RecycledInfo) => 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 CURRENT
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 67da50710..765b7a74c 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -91,7 +91,11 @@ export const IPC = {
* 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. */
+ * stale cwd.
+ * Payload: `{ ready: boolean }`. `ready:true` = the replacement session is registered, restart
+ * onto it. `ready:false` = the escape-hatch timeout fired and NO replacement ever came (the
+ * recycler's app died mid-move): the terminal must NOT respawn — it would spawn `nt-<id>` in
+ * its own stale cwd and silently undo the move — it ends and offers a manual reopen. */
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
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 98bfb974c..1012d8927 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -44,6 +44,24 @@ export interface PtyCreateResult {
/** Set when the node's `accountId` had no config dir at spawn, so the session fell back to the
* system account. The renderer flags the account chip (folder-missing warning) when true. */
accountFallback?: boolean
+ /**
+ * REFUSED: this node's session was permanently destroyed by ANOTHER client, so nothing was
+ * spawned (`sessionId` is empty) — the terminal shows the "closed by <name>" state instead.
+ *
+ * This is the tombstone (PtyManager): `pty:closed` only reaches a session's SUBSCRIBERS, and a
+ * co-viewer whose project is inactive or closed is not one. Without this, the create it issues
+ * when it later opens that project would happily spawn a brand-new `nt-<id>` and resurrect a
+ * terminal its owner deliberately deleted. The client that DID the destroy is exempt (its ⌘Z
+ * must still restore the node), so the single-user delete→undo path is unchanged.
+ */
+ closed?: { by: number | null }
+}
+
+/** Payload of `pty:recycled` — see IPC.ptyRecycled and `recycleAction` in the renderer. */
+export interface RecycledInfo {
+ /** A replacement session is registered for the node: restart onto it. False = the escape-hatch
+ * timeout fired with no replacement (the recycler died mid-move) → do NOT respawn. */
+ ready: boolean
}
// 'subagent' and 'loop' are render-only (ephemeral hook-driven viz) and never persisted.
@@ -247,11 +265,12 @@ 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
+ /** Another client RECYCLED this node (moved it into a worktree): this session id is dead. With
+ * `ready:true` 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. With
+ * `ready:false` no replacement ever came (the recycler died mid-move): do NOT respawn — the
+ * terminal ends and offers a manual reopen. Returns an unsubscribe. */
+ onRecycled(sessionId: string, listener: (info: RecycledInfo) => 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