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(ssh): stop the reconciler mistaking its own mirror writes for external edits

enesa1949aea6a54
diff --git a/CLAUDE.md b/CLAUDE.md
index 5e62257c7..36178ff5b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -212,6 +212,16 @@ Persistence has two layers:
(`markUnmirrored`); pending mirrors are flushed before the ControlMasters die at quit; and the
SSH dialog **dedupes by endpoint+remoteCwd** (`openSshProject`, same contract as
`openFolderProject`) instead of minting a fresh empty project for a folder that already has one.
+ **The reconciler also recognizes its own writes** (the SSH twin of the watcher's `isSelfWrite`):
+ the 15 s poll and the connect-time refresh read the very file the mirror writes, so
+ `recentMirrorHashes` remembers the last few payloads handed to `remoteIO.write` and a read that
+ returns those exact bytes decides "nothing new" — never an adopt/broadcast (which raised the
+ Reload/Keep-mine conflict bar over the store's own autosave), and never a rescue of an OLDER own
+ write still sitting under the 5 s throttle (which resurrected just-deleted nodes). Exact bytes
+ only, so a phone append or another machine's save still reads as external. And
+ `refreshSshProject` runs ON `saveChain`: off the chain a poll snapshotting the pre-save entry
+ could complete its slow ssh read after the save's mirror landed and "adopt" the store's own
+ write on rev alone.
- **Live terminal sessions** (tmux): terminals continue where they left off across node
remounts *and* full app restarts, including running processes. See below.
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 58405a03a..607329996 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -1066,6 +1066,106 @@ describe('ssh lineage safety', () => {
})
})
+// Field bug (enes, 2026-09-01): on an SSH project with heavy canvas-control churn (rev 19468 on the
+// live file), the "Reload from disk / Keep mine" conflict bar kept appearing with nobody else
+// editing. The reconciler recognized its own mirror writes only by REV — it had no analogue of the
+// local watcher's `isSelfWrite` byte comparison — and `refreshSshProject` (the 15 s poll + the
+// connect-time refresh) ran OFF the save chain, so a poll holding a pre-save entry snapshot could
+// read the server file AFTER the save's mirror write landed: remote.rev > (stale) cacheRev, the
+// store's own bytes were "adopted" and broadcast as an external change, and a dirty canvas raised
+// the conflict bar over a file nobody else touched.
+describe('ssh reconcile self-write recognition (the spurious conflict bar)', () => {
+ 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
+ })
+
+ it('a poll interleaved with a save never adopts that save\'s own mirror write', async () => {
+ const remote: Record<string, string> = {}
+ const gate: { open: (() => void) | null } = { open: null }
+ let holdNextRead = false
+ const io = {
+ read: async (_id: string, ssh: any) => {
+ if (holdNextRead) {
+ // The poll's ssh `cat` in flight on a slow WAN link.
+ holdNextRead = false
+ await new Promise<void>((resolve) => { gate.open = resolve })
+ }
+ return remote[ssh.remoteCwd] != null
+ ? { status: 'ok' as const, content: remote[ssh.remoteCwd] }
+ : { status: 'absent' as const }
+ },
+ write: async (_id: string, ssh: any, c: string) => ((remote[ssh.remoteCwd] = c), true)
+ }
+ const store = new WorkspaceStore(io)
+ const p1 = project({ id: 'ps', ssh: sshConn, cwd: undefined, nodes: [node('term-1', 't')] })
+ await store.save(ws([p1])) // seed: cache rev 1, mirrored
+
+ // The 15 s poll fires; its read hangs mid-flight…
+ holdNextRead = true
+ const poll = store.refreshSshProject('ps', { pushIfStanding: false })
+ await vi.waitFor(() => { if (!gate.open && holdNextRead) throw new Error('poll read not reached') })
+ // …while an ordinary autosave (canvas-control created a node) lands and mirrors rev 2.
+ const p2 = { ...p1, nodes: [...p1.nodes, node('term-2', 'spawned')] }
+ const save2 = store.save(ws([p2]))
+ // Give an un-serialized save time to run to completion (under the fix it queues instead).
+ await new Promise((resolve) => setTimeout(resolve, 25))
+ gate.open?.()
+ await save2
+ // The poll saw either the pre-save file (rev 1 == its snapshot) or the save's own write —
+ // neither is an external change, so nothing may be adopted / broadcast toward the conflict bar.
+ await expect(poll).resolves.toBeNull()
+ expect(JSON.parse(remote['~/app']).rev).toBe(2) // the save's mirror still landed
+ })
+
+ it('an older own mirror write read back inside the throttle window does not resurrect a deleted node', async () => {
+ // Simulates the real remote IO's 5 s trailing throttle: the write is acked optimistically
+ // while the server still holds the PREVIOUS bytes.
+ const remote: Record<string, string> = {}
+ let throttleHold = false
+ const io = {
+ read: async (_id: string, ssh: any) =>
+ remote[ssh.remoteCwd] != null
+ ? { status: 'ok' as const, content: remote[ssh.remoteCwd] }
+ : { status: 'absent' as const },
+ write: async (_id: string, ssh: any, c: string) => {
+ if (!throttleHold) remote[ssh.remoteCwd] = c
+ return true // optimistic ack either way — the trailing write "will" land
+ }
+ }
+ const store = new WorkspaceStore(io)
+ const both = [node('term-1', 't'), node('term-x', 'closed later')]
+ await store.save(ws([project({ id: 'ps', ssh: sshConn, cwd: undefined, nodes: both })])) // rev 1 on the server
+ throttleHold = true // next mirror write is acked but not yet on the wire
+ await store.save(ws([project({ id: 'ps', ssh: sshConn, cwd: undefined, nodes: [node('term-1', 't')] })])) // user closed term-x
+ // The poll reads the server before the trailing write fires: it sees OUR OWN rev-1 bytes,
+ // which still contain term-x. That is a self-write echo, not a foreign append — rescuing
+ // term-x here would resurrect the node the user just deliberately closed.
+ await expect(store.refreshSshProject('ps', { pushIfStanding: false })).resolves.toBeNull()
+ })
+
+ it('a genuinely external edit is still adopted — self-write recognition matches exact bytes only', async () => {
+ const remote: Record<string, string> = {}
+ const io = {
+ read: async (_id: string, ssh: any) =>
+ remote[ssh.remoteCwd] != null
+ ? { status: 'ok' as const, content: remote[ssh.remoteCwd] }
+ : { status: 'absent' as const },
+ write: async (_id: string, ssh: any, c: string) => ((remote[ssh.remoteCwd] = c), true)
+ }
+ const store = new WorkspaceStore(io)
+ await store.save(ws([project({ id: 'ps', ssh: sshConn, cwd: undefined, nodes: [node('term-1', 't')] })]))
+ // Another machine edits the file we last mirrored: content derived from ours, but not ours.
+ const f = JSON.parse(remote['~/app'])
+ f.rev = 5
+ f.name = 'renamed-elsewhere'
+ remote['~/app'] = JSON.stringify(f)
+ const adopted = await store.refreshSshProject('ps', { pushIfStanding: false })
+ expect(adopted).toMatchObject({ id: 'ps', name: 'renamed-elsewhere' })
+ })
+})
+
// Field bug (2026-08-10): two projects + rapid tab switching → both canvases wiped. Every switch
// fires an un-awaited full save; save() was unserialized and writeAtomic used one fixed tmp path,
// so overlapping saves spliced each other's tmp bytes (corrupt JSON published by rename) and a slow
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index defa9ce9b..78a3d211d 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -1,5 +1,5 @@
import { promises as fs } from 'fs'
-import { randomUUID } from 'node:crypto'
+import { createHash, randomUUID } from 'node:crypto'
import path from 'path'
import { renameAtomic, writeFileAtomic } from './fs-atomic'
import { IPC } from '../shared/ipc'
@@ -43,6 +43,13 @@ export interface RemoteWorkspaceIO {
const projectFilePath = (cwd: string): string => path.join(cwd, PROJECT_DIR, PROJECT_FILE)
+/** How many recent mirror payloads a project remembers for self-write recognition (see
+ * `recentMirrorHashes`). Big enough to cover a burst of throttled writes inside one poll window;
+ * small enough that a server-side revert to genuinely old content still reads as external. */
+const RECENT_MIRROR_CAP = 8
+
+const contentHash = (content: string): string => createHash('sha256').update(content).digest('hex')
+
/** Alias of the shared `ProjectSettingsSnapshot` (moved to `shared/project-settings.ts` so the
* renderer's `ProjectSettingsApi` can name the shape without importing core) — the store's
* methods keep this name in their signatures. */
@@ -137,6 +144,18 @@ export class WorkspaceStore {
* 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>>()
+ /** ssh project id -> sha256 of the last few project.json payloads THIS store handed to
+ * `remoteIO.write`. The SSH twin of `lastWritten`'s watcher self-write suppression: the 15 s
+ * poll and the connect-time refresh read the very file the mirror writes, so a reconcile can
+ * read the store's OWN bytes back — either a write that just landed, or (because the real IO's
+ * 5 s throttle acks a trailing write optimistically) an OLDER own write the trailing one has
+ * not yet replaced. Recognized by exact bytes, they are never an external change: without this
+ * a rev-only decision "adopted" our own mirror and broadcast it, raising the Reload/Keep-mine
+ * conflict bar over a file nobody else touched — and the older-write echo could rescue back a
+ * node the user had just deleted. Several hashes (RECENT_MIRROR_CAP), not one, precisely for
+ * that throttle window. Runtime-only: after a restart the rev comparison is the arbiter, as
+ * before. */
+ private recentMirrorHashes = new Map<string, string[]>()
/** project id -> this machine's settings overlay, already sanitized. The map — not the index
* entry — is the live copy: `splitWorkspace` rebuilds entries from the renderer's Workspace,
* which has never carried machine-local state, so every save would otherwise drop the overlay
@@ -1010,8 +1029,21 @@ export class WorkspaceStore {
* companion appended to the server file reaches the live canvas). The poll passes
* `pushIfStanding: false`: when our cache simply stands, a poll must be read-only — only an
* OWED mirror (a previously dropped write) may still push.
+ *
+ * Runs ON `saveChain`, like every other read-modify-write of the same state: off the chain a
+ * poll could snapshot the pre-save index entry, then complete its slow ssh read AFTER the save's
+ * mirror write landed — remote.rev > (stale) cacheRev, and the store "adopted" and broadcast its
+ * OWN write as an external change (the spurious Reload/Keep-mine conflict bar). Queued, a
+ * reconcile always compares the server file against the same generation of cache/rev state, and
+ * its index write cannot interleave with a save's either.
*/
- async refreshSshProject(projectId: string, opts?: { pushIfStanding?: boolean }): Promise<Project | null> {
+ refreshSshProject(projectId: string, opts?: { pushIfStanding?: boolean }): Promise<Project | null> {
+ const run = this.saveChain.then(() => this.refreshSshProjectNow(projectId, opts))
+ this.saveChain = run.catch(() => {})
+ return run
+ }
+
+ private async refreshSshProjectNow(projectId: string, opts?: { pushIfStanding?: boolean }): Promise<Project | null> {
const e = this.index?.entries.find((x) => x.id === projectId && x.ssh)
if (!e?.ssh || !this.remoteIO) return null
const revBefore = e.cache?.rev
@@ -1255,6 +1287,24 @@ export class WorkspaceStore {
this.unmirrored.add(projectId)
}
+ /** Remembers a project.json payload handed to `remoteIO.write` (see `recentMirrorHashes`).
+ * Called only on an acked write: an ack may be optimistic (the throttle's trailing write), but
+ * a read can only ever return these bytes if they actually landed — so a dropped trailing
+ * write leaves a harmless unused hash, never a false echo. */
+ private recordMirrored(projectId: string, content: string): void {
+ const hashes = this.recentMirrorHashes.get(projectId) ?? []
+ hashes.push(contentHash(content))
+ while (hashes.length > RECENT_MIRROR_CAP) hashes.shift()
+ this.recentMirrorHashes.set(projectId, hashes)
+ }
+
+ /** True when `content` is byte-identical to a payload this store recently mirrored — a
+ * self-write echo, never an external change. Exact bytes only: any other writer's edit
+ * (a phone append, another machine's save with its own savedAt) hashes differently. */
+ private isOwnMirrorContent(projectId: string, content: string): boolean {
+ return this.recentMirrorHashes.get(projectId)?.includes(contentHash(content)) ?? false
+ }
+
/**
* Registers a PHONE-STARTED session as a node in a LOCAL ref project's file — the host side of
* the relay `projects.registerNode` verb. v1 scope: local-cwd projects only (an ssh ref's file
@@ -1388,8 +1438,10 @@ export class WorkspaceStore {
if (!e.ssh || !e.cache || !this.remoteIO) return
const rescued = await this.rescueRemoteNodes(e)
// AFTER the rescue: it replaces e.cache with the merged copy, which is what must land.
- const ok = await this.remoteIO.write(e.id, e.ssh, serializeProjectFile(e.cache))
+ const content = serializeProjectFile(e.cache)
+ const ok = await this.remoteIO.write(e.id, e.ssh, content)
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)
@@ -1467,6 +1519,9 @@ export class WorkspaceStore {
* .nodeterm/project.json. Rules, in order:
* - read ERROR → decide nothing (a failed read is never evidence of absence): stay
* un-reconciled, mirror stays owed, no write.
+ * - the server holds bytes THIS store recently mirrored (`recentMirrorHashes`) → a self-write
+ * echo, not an external change: the cache stands, nothing is adopted or merged, nothing is
+ * broadcast (no conflict bar); an owed mirror still pushes.
* - absent/corrupt remote → push our cache up.
* - same lineage (ids match): higher remote rev wins (rev is this file's save counter) —
* including an emptier remote (the user really cleared their canvas elsewhere).
@@ -1489,6 +1544,13 @@ export class WorkspaceStore {
const parsed = JSON.parse(res.content) as ProjectFileV1
if (parsed?.version === 1 && Array.isArray(parsed.nodes)) remote = parsed
} catch { /* corrupt remote file → treat as absent, our cache pushes up */ }
+ // 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
+ // said nothing new: the cache stands, and an owed mirror still pushes below. Matching by
+ // exact bytes keeps the genuine-external-edit path untouched (any other writer's file —
+ // a phone append, another machine's save — hashes differently).
+ if (remote && this.isOwnMirrorContent(e.id, res.content)) remote = null
}
this.reconciled.add(e.id)
const cacheRev = e.cache?.rev ?? 0
@@ -1566,8 +1628,10 @@ export class WorkspaceStore {
}
// Push-up runs with the master just up, but record the outcome anyway: a failed write
// (connection flapped) stays owed so the next save retries it.
- const ok = await this.remoteIO.write(e.id, e.ssh, serializeProjectFile(e.cache))
+ const content = serializeProjectFile(e.cache)
+ const ok = await this.remoteIO.write(e.id, e.ssh, content)
if (ok) {
+ this.recordMirrored(e.id, content)
this.unmirrored.delete(e.id)
this.clearedNodes.delete(e.id) // the server holds our deletions now
} else this.unmirrored.add(e.id)