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(ssh): a dropped trailing mirror write must not resurrect deleted nodes
enese2895efd7632
diff --git a/CLAUDE.md b/CLAUDE.mdindex 420fcd56d..e6307a036 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -322,6 +322,30 @@ Persistence has two layers:`refreshSshProject` runs ON `saveChain`: off the chain a poll snapshotting the pre-save entrycould complete its slow ssh read after the save's mirror landed and "adopt" the store's ownwrite on rev alone.+ **A write ACK is not evidence about the server's CONTENT — only a read is** (2026-09-06 field+ report: 16 terminals deleted on an SSH project came straight back, announced as sessions+ registered from a phone the reporter does not own). `clearedNodes` is the tombstone set that+ tells the mirror's re-read "we deleted this, do not rescue it back", and it used to be dropped+ the moment `remoteIO.write` returned true. That ack is **optimistic for the 5 s throttle's+ trailing write** (`makeRemoteWorkspaceIO` returns true and schedules the run) — so when the+ connection died inside the window, `markUnmirrored` re-owed the mirror (`unmirrored.add`) while+ the tombstones were already gone, and the retry's re-read found every just-deleted node still on+ the server with nothing left to filter with: `rescueRemoteNodes` merged all 16 back into the+ cache, bumped the rev and broadcast them as an external change. The asymmetry was in one place —+ `unmirrored` was restored, `clearedNodes` was not. A tombstone is now retired ONLY by+ `confirmClearedDeletions`: a read that no longer lists the id (taken from reads the store already+ makes — the mirror's own re-read and `reconcileSsh` — so it costs no round-trip), or an adopt,+ which overrules our deletions outright. **Both** read sites must call it; wiring one leaves the+ other's tombstones alive for the whole run. The cost is that GC lags a landed write by one read,+ which only prolongs the suppression of a rescue we do not want; the benefit is that the rule no+ longer depends on a dropped write being REPORTED. Symmetrically restoring the set inside+ `markUnmirrored` was the smaller diff and was rejected: it needs the same shadow state anyway,+ and it only closes the one failure path that happens to report back. The set is runtime-only,+ bounded by the ids deleted this run, and pruned for projects that leave the index.+ **Neither surface may name a device for an adopted node** (`adoptedClause`,+ `renderer/lib/externalChange.ts`): nothing at that layer knows the source — a stale own mirror+ and a phone append are indistinguishable there — so the copy names the project FILE and offers+ the possibilities without asserting one.- **Live terminal sessions** (tmux): terminals continue where they left off across noderemounts *and* full app restarts, including running processes. See below.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 0323b48ae..3c4b0bf84 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -125,6 +125,18 @@ lane unaffected.see. Keep a remote temp's own leaf bounded: extending an already-valid maximum-length target leafwith a UUID suffix turns an atomic write into a guaranteed `ENAMETOOLONG` failure.+- **A write ack is a claim about a WRITE, never about what the remote now holds.** Do not retire+ state that records "the server still needs to be told X" just because the write returned true.+ The SSH mirror's writer acks the 5 s throttle's trailing write **optimistically** — it returns+ true and schedules the run — so a connection that dies inside that window leaves an ack behind+ with nothing on the wire. Deleting the deletion tombstones on that ack is how 16 terminals+ deleted on a slow link came back, announced as sessions from a phone the reporter does not own+ (`clearedNodes` / `confirmClearedDeletions`, `src/core/workspace-store.ts`). Retire such state on+ a READ that shows the remote no longer has it — which is the same rule this codebase already+ applies in the other direction, "a failed read is never evidence of absence". And when you cannot+ observe where incoming data came from, **do not name a source in the UI copy**: a wrong+ attribution sends the reader hunting for a device instead of at the file.+- **Never write to a child's stdin without an `'error'` listener on that stream.** A pipe write'sfailure is not a throw at the call site: when the child exits before draining stdin (a CLI handeda flag it doesn't know, an unreachable ssh host), Node re-emits the EPIPE as an async `'error'`diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.tsindex fad8d3bcd..cddb9d9bc 100644--- a/src/core/workspace-store.test.ts+++ b/src/core/workspace-store.test.ts@@ -1954,3 +1954,129 @@ describe('projectMetaFor (issue #338 PR 1) — target exists / is SSH, from theexpect(store.projectMetaFor('p-b')).toBeUndefined()})})++// Field bug (enes, 2026-09-06, SSH project on a SLOW link): 16 terminals deleted, and all 16 came+// straight back with "16 new sessions registered from another device (your phone, or another+// machine)". No phone and no second machine were involved — the only other writer was OUR OWN+// stale server file.+//+// The chain: a save records the nodes it dropped in `clearedNodes`, which is the ONLY thing that+// tells the mirror's re-read "we deleted this, do not rescue it". `mirrorSshCache` used to drop+// that record the moment the write was ACKED — but the real remote IO acks the 5 s throttle's+// TRAILING write optimistically, before it is on the wire. When that trailing write is later+// dropped, `markUnmirrored` re-owes the mirror but could not restore the tombstones, so the next+// mirror write re-read a server file that still listed all 16 nodes, had nothing left to filter+// with, and "rescued" every one of them back onto the canvas.+describe('ssh mirror: an optimistically-acked write that never lands must not resurrect deletions', () => {+ const sshConn = { server: { host: 'h', user: 'u' } as any, remoteCwd: '~/app' }+ const node = (id: string, title: string) => ({+ id, kind: 'terminal' as const, position: { x: 0, y: 0 }, size: { width: 1, height: 1 },+ title, color: '#fff', group: null+ })++ /** The real remote IO's throttle, modelled exactly: while `hold` is on the write returns TRUE+ * (the optimistic ack for a trailing run) but the server content does not change. */+ const throttleIO = () => {+ const files: Record<string, string> = {}+ const state = { hold: false }+ const io = {+ read: async (_id: string, ssh: any) =>+ files[ssh.remoteCwd] != null+ ? { status: 'ok' as const, content: files[ssh.remoteCwd] }+ : { status: 'absent' as const },+ write: async (_id: string, ssh: any, c: string) => {+ if (!state.hold) files[ssh.remoteCwd] = c+ return true // acked either way — "the trailing write will land"+ }+ }+ return { files, state, io }+ }++ const idsOn = (files: Record<string, string>): string[] =>+ JSON.parse(files['~/app']).nodes.map((n: any) => n.id)++ it('keeps deletions dead across a dropped trailing write — while a genuine phone append is still rescued', async () => {+ const { files, state, io } = throttleIO()+ const store = new WorkspaceStore(io)+ const p = (nodes: ReturnType<typeof node>[]) =>+ ws([project({ id: 'ps', ssh: sshConn, cwd: undefined, nodes })])++ const keep = node('term-keep', 'kept')+ const a = node('term-a', 'closed by the user')+ const b = node('term-b', 'closed by the user')+ await store.save(p([keep, a, b])) // rev 1, mirrored: the server holds all three+ expect(idsOn(files).sort()).toEqual(['term-a', 'term-b', 'term-keep'])++ // The phone appends a session it just started, straight into the server file (its own SSH path).+ const phone = node('term-phone-1', 'Mobile')+ const f = JSON.parse(files['~/app'])+ files['~/app'] = JSON.stringify({ ...f, rev: f.rev + 1, nodes: [...f.nodes, phone] })++ // The user closes term-a and term-b. The mirror write is ACKED (throttle) but never lands.+ state.hold = true+ fake.sent.length = 0+ await store.save(p([keep]))+ // The phone's node IS foreign — it must be rescued and announced, fix or no fix.+ const rescueMsg = fake.sent.find((m) => m.channel === 'workspace:external-change')+ expect((rescueMsg!.args[0] as Project).nodes.map((n) => n.id)).toContain('term-phone-1')+ expect((rescueMsg!.args[0] as Project).nodes.map((n) => n.id)).not.toContain('term-a')++ // …and the connection dies inside the throttle window, so the trailing write is dropped.+ store.markUnmirrored('ps')++ // The next save retries the owed mirror. Its re-read still sees term-a/term-b on the server.+ state.hold = false+ fake.sent.length = 0+ await store.save(p([keep, phone])) // the renderer adopted the phone node above++ expect(idsOn(files).sort()).toEqual(['term-keep', 'term-phone-1']) // the deletions travelled+ const resurrected = fake.sent+ .filter((m) => m.channel === 'workspace:external-change')+ .flatMap((m) => (m.args[0] as Project).nodes.map((n) => n.id))+ expect(resurrected).not.toContain('term-a')+ expect(resurrected).not.toContain('term-b')+ })++ // When the tombstones are GARBAGE-COLLECTED: on the first READ that shows the server no longer+ // lists the id — positive confirmation, taken from a read the store already makes (the mirror's+ // re-read, the 15 s poll, the connect-time refresh), so it costs no extra round-trip. It+ // therefore lags the landed write by one read, which is the price of not trusting the ack: a+ // tombstone that outlives its usefulness by a few seconds only suppresses a rescue of a node we+ // deliberately deleted. After the confirmation the id is an ordinary unknown one again — if it+ // comes back on the server it is a genuine foreign addition (another machine restored it, a git+ // checkout) and is rescued like any other.+ // BOTH reading sites confirm, and each is covered: the mirror write's own re-read (which runs on+ // every changed save, so it is the usual one) and `reconcileSsh` (the 15 s poll / connect-time+ // refresh). Wiring only one of them leaves the other's tombstones alive for the whole run.+ const confirmingReads: [string, (store: WorkspaceStore, save: () => Promise<unknown>) => Promise<unknown>][] = [+ ["the mirror write's own re-read", (_store, save) => save()],+ ['the 15 s poll', (store) => store.refreshSshProject('ps', { pushIfStanding: false })]+ ]+ for (const [label, confirm] of confirmingReads) {+ it(`drops a tombstone once ${label} shows the deletion travelled, so a later re-appearance is rescued again`, async () => {+ const { files, io } = throttleIO()+ const store = new WorkspaceStore(io)+ const p = (nodes: ReturnType<typeof node>[]) =>+ ws([project({ id: 'ps', ssh: sshConn, cwd: undefined, nodes })])+ const keep = node('term-keep', 'kept')+ const a = node('term-a', 'closed by the user')++ await store.save(p([keep, a]))+ await store.save(p([keep])) // the deletion lands: the server no longer lists term-a+ expect(idsOn(files)).toEqual(['term-keep'])++ // …and something reads the server back, seeing term-a gone: our deletion HAS travelled.+ await confirm(store, () => store.save(p([keep, node('term-confirm', 'an ordinary edit')])))++ // Only NOW does another machine put a node with that id back into the server file.+ const f = JSON.parse(files['~/app'])+ files['~/app'] = JSON.stringify({ ...f, rev: f.rev + 1, nodes: [...f.nodes, node('term-a', 'restored')] })+ fake.sent.length = 0+ await store.save(p([keep, node('term-2', 'new here')])) // an ordinary local edit mirrors++ expect(idsOn(files)).toContain('term-a') // rescued: the tombstone was already retired+ const msg = fake.sent.find((m) => m.channel === 'workspace:external-change')+ expect((msg!.args[0] as Project).nodes.map((n) => n.id)).toContain('term-a')+ })+ }+})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex f58962593..dd881aee2 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -147,8 +147,10 @@ export class WorkspaceStore {* told about yet. The one discriminator between the two ways our cache can lack a node the server* has: "the user deleted it here" (the deletion must travel — never rescue it back) and "we simply* never had it" (the phone appended it while we were looking away — never delete it). Both rescue- * sites consult it; a confirmed write / an adopt drops the entry, because the server then already- * reflects our side. Runtime-only: after a restart an UNMIRRORED clear is indistinguishable from a+ * sites consult it. An id is retired ONLY by a READ that no longer lists it (`confirmClearedDeletions`)+ * or by an adopt that overrules our deletions — never by a write ack, which is optimistic for the+ * throttle's trailing write and cost the 2026-09-06 resurrection bug.+ * Runtime-only: after a restart an UNMIRRORED clear is indistinguishable from a* node we never had, and the tie is broken toward rescuing (a resurrected node is visible and* deletable again; a deleted session node is gone with no trace of where it went). */private clearedNodes = new Map<string, Set<string>>()@@ -1057,6 +1059,12 @@ export class WorkspaceStore {// extra round-trip per CHANGED save (an unchanged, already-mirrored save still reads nothing).if (changedSinceLoad || this.unmirrored.has(e.id)) await this.mirrorSshCache(e)}+ // Tombstones are retired by a server read (`confirmClearedDeletions`), so a project that left+ // the index would keep its set for the rest of the run with nothing left to read it. Bound it.+ if (this.clearedNodes.size) {+ const liveIds = new Set(index.entries.map((e) => e.id))+ for (const id of this.clearedNodes.keys()) if (!liveIds.has(id)) this.clearedNodes.delete(id)+ }// Back up the raw v2 file BEFORE the v3 index flip: a crash between the two must never leave a// migrated tree (project files already written above) without its pre-migration backup.@@ -1667,8 +1675,8 @@ export class WorkspaceStore {if (ok) {this.recordMirrored(e.id, content)this.unmirrored.delete(e.id)- // The server now holds exactly our cache, deletions included — nothing left to remember.- this.clearedNodes.delete(e.id)+ // The tombstones deliberately SURVIVE this ack — see `confirmClearedDeletions`. An ack is not+ // evidence that the server holds our deletions; only a read that no longer lists them is.} else {this.unmirrored.add(e.id)}@@ -1695,6 +1703,7 @@ export class WorkspaceStore {if (parsed?.version === 1 && Array.isArray(parsed.nodes)) remote = parsed} catch { /* corrupt server file — our cache is the only readable copy; it is written as-is */ }if (!remote || remote.id !== e.cache.id) return null+ this.confirmClearedDeletions(e.id, remote.nodes)const rescued = this.rescuableNodes(e.id, e.cache.nodes, remote.nodes)if (!rescued.length) return null// The merged set must outrank both sides, or the next reconcile could rev-decide it away.@@ -1724,6 +1733,33 @@ export class WorkspaceStore {return cleared ? missing.filter((n) => !cleared.has(n.id)) : missing}+ /**+ * Retire the tombstones the SERVER has confirmed: ids `clearedNodes` holds that the file we just+ * read no longer lists. Our deletion has travelled, so the record has done its job — and the id+ * becomes an ordinary unknown one again, so a later re-appearance (another machine restored the+ * node, a git checkout) is rescued like any other foreign addition.+ *+ * This — plus an adopt, which overrules our deletions outright — is the ONLY thing that retires a+ * tombstone. It used to be the mirror write's ACK, and that was the 2026-09-06 field bug: the real+ * remote IO acks the 5 s throttle's TRAILING write optimistically, before it is on the wire (see+ * `recordMirrored`). When the connection died inside that window the write was dropped,+ * `markUnmirrored` re-owed the mirror but had nothing with which to restore the tombstones, and the+ * retry's re-read found all 16 just-deleted nodes still on the server with no filter left — so it+ * "rescued" every one of them back onto the canvas and announced them as sessions from another+ * device. An ack is a claim about a write; a tombstone is a claim about the server's CONTENT, and+ * only a read can settle that. Same rule the reconciler already lives by ("a failed read is never+ * evidence of absence") applied to the other direction.+ *+ * It costs no extra round-trip: both call sites are reads the store already makes.+ */+ private confirmClearedDeletions(projectId: string, remoteNodes: CanvasNodeState[]): void {+ const cleared = this.clearedNodes.get(projectId)+ if (!cleared) return+ const onServer = new Set(remoteNodes.map((n) => n.id))+ for (const id of cleared) if (!onServer.has(id)) cleared.delete(id)+ if (!cleared.size) this.clearedNodes.delete(projectId)+ }+/** Record the nodes a save removed from an ssh cache (see `clearedNodes`). */private recordLocalDeletions(projectId: string,@@ -1769,6 +1805,9 @@ export class WorkspaceStore {const parsed = JSON.parse(res.content) as ProjectFileV1if (parsed?.version === 1 && Array.isArray(parsed.nodes)) remote = parsed} catch { /* corrupt remote file → treat as absent, our cache pushes up */ }+ // Before the self-write nulling below: an id absent from the file ON THE SERVER is confirmed+ // gone whoever wrote those bytes, and an older own write that still lists it confirms nothing.+ if (remote && e.cache && remote.id === e.cache.id) this.confirmClearedDeletions(e.id, remote.nodes)// Self-write echo: the server holds bytes this store itself mirrored (a poll reading right// behind a save's write, or an OLDER own write the 5 s throttle has not yet replaced).// Nothing foreign is there to adopt, merge or announce — decide exactly as if the remote@@ -1860,7 +1899,8 @@ export class WorkspaceStore {if (ok) {this.recordMirrored(e.id, content)this.unmirrored.delete(e.id)- this.clearedNodes.delete(e.id) // the server holds our deletions now+ // Tombstones survive the ack here too (see `confirmClearedDeletions`): this write is the+ // same optimistically-acked throttled write the mirror path makes.} else this.unmirrored.add(e.id)}// Surface a rescued merge to the renderer even on a read-only poll (pushIfStanding:false) — thediff --git a/src/renderer/lib/externalChange.test.ts b/src/renderer/lib/externalChange.test.tsindex 1cf500d33..cb410fef0 100644--- a/src/renderer/lib/externalChange.test.ts+++ b/src/renderer/lib/externalChange.test.ts@@ -197,14 +197,33 @@ describe('conflict copy', () => {})it('names what arrived, and says it is already on the canvas', () => {const msg = conflictBarMessage(1)- expect(msg).toContain('1 new session')- expect(msg).toContain('added to this canvas')+ expect(msg).toContain('1 session')+ expect(msg).toContain('not on this canvas')+ expect(msg).toContain('added')})it('pluralizes', () => {- expect(conflictBarMessage(2)).toContain('2 new sessions')- expect(conflictBarMessage(2)).toContain('were added to this canvas')- expect(adoptedNodesNotice(1)).toContain('1 new session')- expect(adoptedNodesNotice(3)).toContain('3 new sessions')- expect(adoptedNodesNotice(3)).toContain('were added to this canvas')+ expect(conflictBarMessage(2)).toContain('2 sessions')+ expect(conflictBarMessage(2)).toContain('were not on this canvas')+ expect(adoptedNodesNotice(1)).toContain('1 session')+ expect(adoptedNodesNotice(1)).toContain('was not on this canvas')+ expect(adoptedNodesNotice(3)).toContain('3 sessions')+ expect(adoptedNodesNotice(3)).toContain('were not on this canvas')+ })+ // 2026-09-06 field report: 16 terminals deleted on a slow SSH link came back announced as+ // sessions "registered from another device (your phone, or another machine)" — the reporter owns+ // no phone and runs no second machine. The source was our own stale server file (a mirror write+ // acked by the 5 s throttle and then dropped). Nothing at this layer knows where an adopted node+ // came from, so neither surface may name a device: it names the FILE, which is what was observed,+ // and offers the possibilities without asserting one.+ it('never attributes the sessions to a device it cannot have observed', () => {+ for (const msg of [conflictBarMessage(16), adoptedNodesNotice(16)]) {+ expect(msg).not.toMatch(/phone/i)+ expect(msg).not.toMatch(/registered from/i)+ expect(msg).toContain('project file')+ expect(msg).toContain('or from an older copy of the file')+ }+ })+ it('says the same thing on both surfaces — one clause, no drift', () => {+ expect(conflictBarMessage(4).startsWith(adoptedNodesNotice(4))).toBe(true)})})diff --git a/src/renderer/lib/externalChange.ts b/src/renderer/lib/externalChange.tsindex abcfb1060..7347de24d 100644--- a/src/renderer/lib/externalChange.ts+++ b/src/renderer/lib/externalChange.ts@@ -103,6 +103,27 @@ export function mergeIncomingNodes<T extends { id: string }>(current: T[], incomreturn fresh.length ? [...current, ...fresh] : current}+/**+ * The one clause both surfaces use to describe adopted sessions, so they cannot drift.+ *+ * It deliberately does NOT say "from another device (your phone, or another machine)". Nothing that+ * reaches this point knows the source: the adopting side is a diff against the project file, and+ * that file can hold a session this canvas never had for reasons that have no device behind them —+ * an SSH mirror write that was acked and then dropped, a git pull, a stale server copy. The 2026-09-06+ * field report was exactly that: 16 terminals deleted on a slow SSH link came straight back claiming+ * a phone had registered them, and the user owns no phone. A wrong attribution is worse than none —+ * it sends the reader looking for a device instead of at the file — so this names the FILE, which is+ * the only thing actually observed, and offers the possibilities without asserting one.+ */+function adoptedClause(addedCount: number): string {+ const s = addedCount === 1 ? '' : 's'+ const verb = addedCount === 1 ? 'was' : 'were'+ return (+ `${addedCount} session${s} in the project file ${verb} not on this canvas and ${verb} added ` ++ `(from another device, or from an older copy of the file).`+ )+}+/** The conflict strip's sentence. Derived from what actually arrived so the bar cannot claim* something vague while a real session sits on the canvas behind it. */export function conflictBarMessage(addedCount: number): string {@@ -114,11 +135,8 @@ export function conflictBarMessage(addedCount: number): string {const paused = ' Your canvas is not being saved until you choose.'if (addedCount <= 0)return 'Project file changed on disk (git pull or another machine).' + paused- const s = addedCount === 1 ? '' : 's'- const verb = addedCount === 1 ? 'was' : 'were'return (- `${addedCount} new session${s} registered from another device (your phone, or another machine) ` +- `${verb} added to this canvas. Other parts of the project file also changed on disk — ` ++ `${adoptedClause(addedCount)} Other parts of the project file also changed on disk — ` +`choose which version of those to keep.` +paused)@@ -126,7 +144,5 @@ export function conflictBarMessage(addedCount: number): string {/** The one-off note shown when an incoming session was adopted with no bar at all. */export function adoptedNodesNotice(addedCount: number): string {- const s = addedCount === 1 ? '' : 's'- const verb = addedCount === 1 ? 'was' : 'were'- return `${addedCount} new session${s} registered from another device (your phone, or another machine) ${verb} added to this canvas.`+ return adoptedClause(addedCount)}