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(workspace): stop SSH projects resetting .nodeterm/project.json

enes1a989effe1b4
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index c3e2020f1..5942f45dd 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -387,7 +387,8 @@ describe('refreshSshProject', () => {
it('remote rev > cache rev → adopts remote and reports it', async () => {
const remote: Record<string, string> = {}
const io = {
- read: async (id: string) => remote[id] ?? null,
+ read: async (id: string) =>
+ remote[id] != null ? { status: 'ok' as const, content: remote[id] } : { status: 'absent' as const },
write: async (id: string, _s: any, c: string) => ((remote[id] = c), true)
}
const store = new WorkspaceStore(io)
@@ -404,7 +405,8 @@ describe('refreshSshProject', () => {
const remote: Record<string, string> = {}
const writes: string[] = []
const io = {
- read: async (id: string) => remote[id] ?? null,
+ read: async (id: string) =>
+ remote[id] != null ? { status: 'ok' as const, content: remote[id] } : { status: 'absent' as const },
write: async (id: string, _s: any, c: string) => (writes.push(id), (remote[id] = c), true)
}
const store = new WorkspaceStore(io)
@@ -418,7 +420,10 @@ describe('refreshSshProject', () => {
it('no remote file yet → pushes the cache up (first machine wins)', async () => {
const remote: Record<string, string> = {}
- const io = { read: async () => null, write: async (id: string, _s: any, c: string) => ((remote[id] = c), true) }
+ const io = {
+ read: async () => ({ status: 'absent' as const }),
+ write: async (id: string, _s: any, c: string) => ((remote[id] = c), true)
+ }
const store = new WorkspaceStore(io)
await remoteFileOf(store, project({ id: 'ps', ssh: sshConn, cwd: undefined }))
expect(await store.refreshSshProject('ps')).toBeNull()
@@ -429,12 +434,17 @@ describe('refreshSshProject', () => {
describe('ssh mirror guarantee (unmirrored retry)', () => {
const sshConn = { server: { host: 'h', user: 'u' } as any, remoteCwd: '~/app' }
- /** Fake IO whose write succeeds only while `up` is true (simulates the
- * ControlMaster still connecting during the first save). */
+ /** Fake IO simulating a ControlMaster that is down until `up` flips: reads ERROR while down
+ * (a dead connection is not "no file"), writes fail while down. */
const flakyIO = () => {
const state = { up: false, writes: 0, remote: {} as Record<string, string> }
const io = {
- read: async (id: string) => state.remote[id] ?? null,
+ read: async (id: string) => {
+ if (!state.up) return { status: 'error' as const }
+ return state.remote[id] != null
+ ? { status: 'ok' as const, content: state.remote[id] }
+ : { status: 'absent' as const }
+ },
write: async (id: string, _s: any, c: string) => {
state.writes++
if (!state.up) return false
@@ -445,23 +455,35 @@ describe('ssh mirror guarantee (unmirrored retry)', () => {
return { state, io }
}
- it('retries a dropped mirror write on the next save even with unchanged content', async () => {
+ it('lands the mirror on a later save even when the first save ran disconnected', async () => {
const { state, io } = flakyIO()
const store = new WorkspaceStore(io)
const w = ws([project({ id: 'ps', ssh: sshConn, cwd: undefined })])
- await store.save(w) // connection not up yet → write dropped
- expect(state.writes).toBe(1)
+ await store.save(w) // connection not up yet → read errors, nothing written, mirror owed
expect(state.remote['ps']).toBeUndefined()
state.up = true
await store.save(w) // content unchanged, but the mirror is still owed
- expect(state.writes).toBe(2)
expect(state.remote['ps']).toContain('"id": "ps"')
expect(JSON.parse(state.remote['ps']).rev).toBe(1) // retry does not bump rev
+ const writesSoFar = state.writes
await store.save(w) // confirmed → unchanged saves stop writing
- expect(state.writes).toBe(2)
+ expect(state.writes).toBe(writesSoFar)
+ })
+
+ it('markUnmirrored re-owes the mirror (a dropped trailing throttle write reports back)', async () => {
+ const { state, io } = flakyIO()
+ state.up = true
+ const store = new WorkspaceStore(io)
+ const w = ws([project({ id: 'ps', ssh: sshConn, cwd: undefined })])
+ await store.save(w) // reconciles (absent) + pushes
+ expect(state.remote['ps']).toContain('"id": "ps"')
+ delete state.remote['ps'] // the acked-but-dropped trailing write: server never got it
+ store.markUnmirrored('ps')
+ await store.save(w) // unchanged content, but the debt is back
+ expect(state.remote['ps']).toContain('"id": "ps"')
})
it('refreshSshProject records a failed push-up so the next save retries', async () => {
@@ -489,3 +511,109 @@ describe('ssh mirror guarantee (unmirrored retry)', () => {
expect(state.writes).toBe(writesAfterRefresh)
})
})
+
+// THE reset bug (field report: 12 fresh project ids for one server folder in two weeks, 45 orphaned
+// tmux sessions). Re-adding a folder via the SSH dialog minted a fresh project id with an empty
+// canvas; its first mirror write clobbered the server's populated .nodeterm/project.json, and rev
+// inflation (refresh seeded our counter from the remote lineage) made the empty canvas win every
+// later reconcile. These tests pin the lineage rules that prevent it.
+describe('ssh lineage safety', () => {
+ const sshConn = { server: { host: 'h', user: 'u' } as any, remoteCwd: '~/app' }
+
+ /** A populated remote project file from ANOTHER lineage (different project id). */
+ const foreignRemote = (rev: number, nodes = 1) =>
+ JSON.stringify({
+ version: 1, rev, savedAt: 'then', id: 'old1', name: 'original', color: '#ffd60a',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: Array.from({ length: nodes }, (_, i) => ({
+ id: `term-old-${i + 1}`, kind: 'terminal', position: { x: 0, y: 0 },
+ size: { width: 1, height: 1 }, title: 'survivor', color: '#fff', group: null
+ }))
+ })
+
+ /** Fake IO keyed by remoteCwd — the server file is the same file no matter which local
+ * project id points at it (that is what makes re-adding dangerous). */
+ const cwdIO = () => {
+ const files: Record<string, string> = {}
+ 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) => ((files[ssh.remoteCwd] = c), true)
+ }
+ return { files, io }
+ }
+
+ it('a fresh empty project on a populated remote ADOPTS the remote (re-keyed to our id) instead of clobbering it', async () => {
+ const { files, io } = cwdIO()
+ files['~/app'] = foreignRemote(900)
+ const store = new WorkspaceStore(io)
+ // The dialog's re-add: fresh id, empty canvas.
+ await store.save(ws([project({ id: 'fresh1', ssh: sshConn, cwd: undefined, nodes: [] })]))
+
+ // The server file survived (never overwritten with the empty canvas).
+ expect(JSON.parse(files['~/app']).nodes).toHaveLength(1)
+ // The adoption is broadcast to the renderer under OUR project id (the renderer knows no 'old1').
+ const msg = fake.sent.find((m) => m.channel === 'workspace:external-change')
+ expect(msg).toBeTruthy()
+ expect(msg!.args[0]).toMatchObject({ id: 'fresh1', name: 'original' })
+ expect((msg!.args[0] as Project).nodes[0].id).toBe('term-old-1')
+
+ // Rev continues the surviving lineage: the next real edit mirrors as rev 901, not rev 2.
+ const adopted = msg!.args[0] as Project
+ await store.save(ws([{ ...adopted, name: 'renamed' }]))
+ expect(JSON.parse(files['~/app'])).toMatchObject({ rev: 901, id: 'fresh1', name: 'renamed' })
+ })
+
+ it('an EMPTY foreign remote never beats a populated cache, even with a higher rev — and the push outbids it', async () => {
+ const { files, io } = cwdIO()
+ files['~/app'] = foreignRemote(900, 0) // the clobbered file a buggy client left behind
+ const store = new WorkspaceStore(io)
+ await store.save(ws([project({ id: 'fresh1', ssh: sshConn, cwd: undefined })])) // 1 real node
+
+ const after = JSON.parse(files['~/app'])
+ expect(after.id).toBe('fresh1')
+ expect(after.nodes).toHaveLength(1) // our populated canvas pushed up
+ expect(after.rev).toBeGreaterThan(900) // and it WINS future rev reconciles
+ expect(fake.sent.find((m) => m.channel === 'workspace:external-change')).toBeUndefined()
+ })
+
+ it('a read ERROR blocks the first mirror write entirely (no clobber on a flaky connect), then heals', async () => {
+ const files: Record<string, string> = {}
+ let up = false
+ const io = {
+ read: async (_id: string, ssh: any) => {
+ if (!up) return { status: 'error' as const }
+ return 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 (!up) return false
+ files[ssh.remoteCwd] = c
+ return true
+ }
+ }
+ const store = new WorkspaceStore(io)
+ const w = ws([project({ id: 'fresh1', ssh: sshConn, cwd: undefined })])
+ await store.save(w)
+ expect(files['~/app']).toBeUndefined() // error ≠ absent: nothing pushed blind
+ up = true
+ await store.save(w) // unchanged content — but the reconcile is still owed
+ expect(files['~/app']).toContain('"id": "fresh1"')
+ })
+
+ it('same-lineage reconcile is untouched: an emptier remote with a higher rev still wins (user cleared their canvas)', async () => {
+ const { files, io } = cwdIO()
+ const store = new WorkspaceStore(io)
+ await store.save(ws([project({ id: 'ps', ssh: sshConn, cwd: undefined })])) // rev 1, mirrored
+ const cleared = JSON.parse(files['~/app'])
+ cleared.rev = 7
+ cleared.nodes = [] // the same project id, deliberately emptied on another machine
+ files['~/app'] = JSON.stringify(cleared)
+ const adopted = await store.refreshSshProject('ps')
+ expect(adopted).toMatchObject({ id: 'ps' })
+ expect(adopted!.nodes).toHaveLength(0)
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 7b66b22fa..9ac27b65d 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -13,9 +13,13 @@ import {
} from './workspace-files'
import { hoistLegacyNodeExec, type LocalNodeExecMap } from '../shared/node-exec'
+/** Checked remote read: `absent` (no file — safe to push our cache) is NOT `error` (connection
+ * down / ssh failure — a failed read is never evidence of absence, so nothing may be pushed). */
+export type RemoteReadResult = { status: 'ok'; content: string } | { status: 'absent' } | { status: 'error' }
+
/** Remote file access for SSH projects (implemented in src/main over SshFs — src/core stays electron-free). */
export interface RemoteWorkspaceIO {
- read(projectId: string, ssh: NonNullable<Project['ssh']>): Promise<string | null>
+ read(projectId: string, ssh: NonNullable<Project['ssh']>): Promise<RemoteReadResult>
write(projectId: string, ssh: NonNullable<Project['ssh']>, content: string): Promise<boolean>
}
@@ -50,6 +54,10 @@ export class WorkspaceStore {
* save/connect until a write confirms — guarantees the server file lands regardless of node
* type or creation timing. Runtime-only, never persisted. */
private unmirrored = new Set<string>()
+ /** ssh project ids whose remote file has been read-compared at least once this run. Until then a
+ * save may NOT blind-write the mirror: a fresh/re-added project would clobber a populated
+ * server file it has never looked at (the ".nodeterm reset itself" bug). Runtime-only. */
+ private reconciled = new Set<string>()
/** Last index written/loaded — lets readLocalRef/refresh resolve entries without a full load. */
private index: WorkspaceIndexV3 | null = null
/** Optional hook fired after every load()/save() — the watcher re-syncs its watch set (Task 5). */
@@ -251,10 +259,19 @@ export class WorkspaceStore {
)
e.cache.rev = changedSinceLoad ? prevRev + 1 : prevRev
this.revs.set(e.id, e.cache.rev)
+ if (!this.remoteIO) continue
+ if (!this.reconciled.has(e.id)) {
+ // Never blind-write a remote file we have not read yet: the first mirror of a fresh or
+ // re-added project must LOOK first — an existing lineage on the server may win (adopted,
+ // broadcast to the renderer) instead of being clobbered by an empty newborn canvas.
+ const adopted = await this.reconcileSsh(e)
+ if (adopted) platform().broadcast(IPC.workspaceExternalChange, adopted)
+ continue
+ }
// Mirror on change, and re-mirror while a previous write is still owed (the first save
// often races the ControlMaster coming up — its write is dropped fail-open, and without
// the retry nothing rewrites until the next real content change).
- if (this.remoteIO && (changedSinceLoad || this.unmirrored.has(e.id))) {
+ if (changedSinceLoad || this.unmirrored.has(e.id)) {
const ok = await this.remoteIO.write(e.id, e.ssh, serializeProjectFile(e.cache))
if (ok) this.unmirrored.delete(e.id)
else this.unmirrored.add(e.id)
@@ -318,34 +335,83 @@ export class WorkspaceStore {
/**
* Called when an SSH project's connection comes up. Reconciles the server's
- * .nodeterm/project.json with our cached copy by rev: higher remote rev → adopt
- * remote (returned; caller broadcasts it); otherwise → push our cache up.
+ * .nodeterm/project.json with our cached copy (see reconcileSsh): remote won →
+ * adopt (returned; caller broadcasts it); otherwise our cache pushed up.
*/
async refreshSshProject(projectId: string): Promise<Project | null> {
const e = this.index?.entries.find((x) => x.id === projectId && x.ssh)
if (!e?.ssh || !this.remoteIO) return null
- const raw = await this.remoteIO.read(projectId, e.ssh)
+ const adopted = await this.reconcileSsh(e)
+ // The reconcile may have moved cache/rev/name — persist the index either way (cheap, atomic).
+ await writeAtomic(this.indexPath, JSON.stringify(this.index))
+ return adopted
+ }
+
+ /** A throttled trailing mirror write was acked but later dropped (connection died inside the
+ * throttle window): re-owe it so the next save retries. Wired from makeRemoteWorkspaceIO. */
+ markUnmirrored(projectId: string): void {
+ this.unmirrored.add(projectId)
+ }
+
+ /**
+ * The ONE place that decides who wins between an ssh entry's cache and the server's
+ * .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.
+ * - 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).
+ * - DIFFERENT lineage (the server file belongs to another project id — a re-added folder, a
+ * second machine, a git checkout): an empty side never beats a populated one, regardless of
+ * rev. Adoption re-keys the file to OUR entry id (node ids — tmux session names — are kept,
+ * so the terminals reattach); a push outbids the losing lineage's rev so it stays beaten.
+ * Returns the adopted project (for the caller to surface) or null when our cache stood/pushed.
+ */
+ private async reconcileSsh(e: IndexEntryV3): Promise<Project | null> {
+ if (!e.ssh || !this.remoteIO) return null
+ const res = await this.remoteIO.read(e.id, e.ssh)
+ if (res.status === 'error') {
+ this.unmirrored.add(e.id)
+ return null
+ }
let remote: ProjectFileV1 | null = null
- if (raw) {
+ if (res.status === 'ok') {
try {
- const parsed = JSON.parse(raw) as ProjectFileV1
+ 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 */ }
}
+ this.reconciled.add(e.id)
const cacheRev = e.cache?.rev ?? 0
- if (remote && remote.rev > cacheRev) {
- e.cache = remote
- this.revs.set(projectId, remote.rev)
- this.unmirrored.delete(projectId) // the server copy IS the truth now — nothing owed
- await writeAtomic(this.indexPath, JSON.stringify(this.index))
- return fileToProject(remote, { ssh: e.ssh, closed: e.closed, localExec: e.localExec })
+ const cacheNodes = e.cache?.nodes.length ?? 0
+ const sameLineage = !e.cache || !remote || remote.id === e.cache.id
+ const remoteWins =
+ remote !== null &&
+ (sameLineage
+ ? remote.rev > cacheRev
+ : (cacheNodes === 0 && remote.nodes.length > 0) ||
+ (remote.nodes.length > 0 && remote.rev > cacheRev))
+ if (remote && remoteWins) {
+ const adopted = remote.id === e.id ? remote : { ...remote, id: e.id }
+ e.cache = adopted
+ e.name = adopted.name
+ e.color = adopted.color
+ this.revs.set(e.id, adopted.rev)
+ this.unmirrored.delete(e.id) // the server copy IS the truth now — nothing owed
+ return fileToProject(adopted, { ssh: e.ssh, closed: e.closed, localExec: e.localExec })
}
if (e.cache) {
+ // Our cache stood. If it just beat a FOREIGN lineage on the merits (not on rev), outbid that
+ // lineage's rev so a later rev-only reconcile can't resurrect the losing side.
+ if (remote && !sameLineage && remote.rev >= e.cache.rev) {
+ e.cache.rev = remote.rev + 1
+ this.revs.set(e.id, e.cache.rev)
+ }
// 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(projectId, e.ssh, serializeProjectFile(e.cache))
- if (ok) this.unmirrored.delete(projectId)
- else this.unmirrored.add(projectId)
+ const ok = await this.remoteIO.write(e.id, e.ssh, serializeProjectFile(e.cache))
+ if (ok) this.unmirrored.delete(e.id)
+ else this.unmirrored.add(e.id)
}
return null
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 11dca74e9..9fc464186 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -138,9 +138,14 @@ let sshProjectManager: ReturnType<typeof initSshProject> | undefined
const workspaceSshFs = new SshFs((args, stdin) =>
sshProjectManager ? sshProjectManager.sshRun(args, stdin) : Promise.resolve({ code: 1, stdout: '' })
)
-const workspaceStore = new WorkspaceStore(
- makeRemoteWorkspaceIO((projectId) => sshProjectManager?.refForProject(projectId) ?? null, workspaceSshFs)
+const remoteWorkspaceIO = makeRemoteWorkspaceIO(
+ (projectId) => sshProjectManager?.refForProject(projectId) ?? null,
+ workspaceSshFs,
+ // A throttled trailing write that fails after its optimistic ack re-owes the mirror, so the
+ // next save retries instead of believing the server file landed.
+ (projectId) => workspaceStore.markUnmirrored(projectId)
)
+const workspaceStore = new WorkspaceStore(remoteWorkspaceIO)
// Watch each local ref's project.json for outside edits (git pull, a teammate's commit).
// Self-writes match the store's last-written cache and are ignored. Re-synced after every
// store load/save via onPersist; disposed on quit next to ptyManager.killAll().
@@ -1140,7 +1145,9 @@ app.on('window-all-closed', () => {
app.quit()
} else {
void ptyManager.killAll()
- sshProjectManager?.disconnectAll()
+ // Land any pending throttled .nodeterm mirror write BEFORE the masters die — killing a
+ // master mid-write used to leave a truncated project.json on the server.
+ void remoteWorkspaceIO.flush().finally(() => sshProjectManager?.disconnectAll())
}
})
@@ -1150,11 +1157,17 @@ let quitFlushed = false
app.on('before-quit', (e) => {
quitting = true // from here on, window close-events must NOT be turned into hide
workspaceWatcher.dispose()
- sshProjectManager?.disconnectAll()
chatDriver.disposeAll() // tear down every chat node's SDK query (resume-based, so this is safe)
- if (quitFlushed) return
+ if (quitFlushed) {
+ // Second pass (the deferred app.quit() below): the flush had its chance — drop the masters.
+ sshProjectManager?.disconnectAll()
+ return
+ }
quitFlushed = true
e.preventDefault()
- const flush = ptyManager.killAll()
+ // Pending throttled .nodeterm mirror writes must land BEFORE the ControlMasters die — killing
+ // a master mid-write used to leave a truncated project.json on the server. The masters are
+ // therefore kept up through the raced flush and dropped on the second before-quit pass.
+ const flush = Promise.allSettled([remoteWorkspaceIO.flush(), ptyManager.killAll()])
void Promise.race([flush, new Promise((r) => setTimeout(r, 1500))]).finally(() => app.quit())
})
diff --git a/src/main/remote-workspace-io.test.ts b/src/main/remote-workspace-io.test.ts
new file mode 100644
index 000000000..fb7d9a87a
--- /dev/null
+++ b/src/main/remote-workspace-io.test.ts
@@ -0,0 +1,101 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { makeRemoteWorkspaceIO } from './remote-workspace-io'
+import type { SshFs, SshFsRef } from './ssh-fs'
+import type { Project } from '../shared/types'
+
+const ssh = { server: { host: 'h', user: 'u' }, remoteCwd: '~/app' } as NonNullable<Project['ssh']>
+const ref: SshFsRef = { conn: { host: 'h', user: 'u' }, controlPath: '/s.sock' }
+
+/** Minimal fake of the two SshFs members the workspace IO uses. */
+const fakeFs = () => {
+ const fs = {
+ readTextChecked: vi.fn(async () => ({ status: 'ok' as const, content: 'body' })),
+ writeText: vi.fn(async (_ref: SshFsRef, _path: string, _content: string) => true)
+ }
+ return { fs, sshFs: fs as unknown as SshFs }
+}
+
+beforeEach(() => vi.useFakeTimers())
+afterEach(() => vi.useRealTimers())
+
+describe('read', () => {
+ it('disconnected (no ref) → error, never absent: a down connection must not read as "no file"', async () => {
+ const { sshFs } = fakeFs()
+ const io = makeRemoteWorkspaceIO(() => null, sshFs)
+ expect(await io.read('p1', ssh)).toEqual({ status: 'error' })
+ })
+
+ it('passes the checked read result through (ok / absent / error)', async () => {
+ const { fs, sshFs } = fakeFs()
+ const io = makeRemoteWorkspaceIO(() => ref, sshFs)
+ expect(await io.read('p1', ssh)).toEqual({ status: 'ok', content: 'body' })
+ fs.readTextChecked.mockResolvedValueOnce({ status: 'absent' } as never)
+ expect(await io.read('p1', ssh)).toEqual({ status: 'absent' })
+ fs.readTextChecked.mockResolvedValueOnce({ status: 'error' } as never)
+ expect(await io.read('p1', ssh)).toEqual({ status: 'error' })
+ })
+})
+
+describe('write', () => {
+ it('an immediate write reports the REAL outcome (false when the remote write fails)', async () => {
+ const { fs, sshFs } = fakeFs()
+ const io = makeRemoteWorkspaceIO(() => ref, sshFs)
+ fs.writeText.mockResolvedValueOnce(false as never)
+ expect(await io.write('p1', ssh, 'c1')).toBe(false)
+ expect(await io.write('p1', ssh, 'c2')).toBe(true)
+ })
+
+ it('a throttled trailing write that fails reports the drop via onDropped (so the store re-owes it)', async () => {
+ const { fs, sshFs } = fakeFs()
+ const dropped: string[] = []
+ const io = makeRemoteWorkspaceIO(() => ref, sshFs, (id) => dropped.push(id))
+ expect(await io.write('p1', ssh, 'c1')).toBe(true) // immediate
+ fs.writeText.mockResolvedValue(false as never) // connection flaps inside the throttle window
+ expect(await io.write('p1', ssh, 'c2')).toBe(true) // scheduled (optimistic ack)
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(dropped).toEqual(['p1'])
+ })
+
+ it('a trailing write that THROWS also reports the drop (never an unhandled rejection)', async () => {
+ const { fs, sshFs } = fakeFs()
+ const dropped: string[] = []
+ const io = makeRemoteWorkspaceIO(() => ref, sshFs, (id) => dropped.push(id))
+ await io.write('p1', ssh, 'c1')
+ fs.writeText.mockRejectedValue(new Error('conn reset'))
+ await io.write('p1', ssh, 'c2')
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(dropped).toEqual(['p1'])
+ })
+
+ it('newer content still replaces a pending trailing write (final-state-wins)', async () => {
+ const { fs, sshFs } = fakeFs()
+ const io = makeRemoteWorkspaceIO(() => ref, sshFs)
+ await io.write('p1', ssh, 'c1') // immediate
+ await io.write('p1', ssh, 'c2') // scheduled
+ await io.write('p1', ssh, 'c3') // reschedules, replacing c2
+ await vi.advanceTimersByTimeAsync(5000)
+ const bodies = fs.writeText.mock.calls.map((c) => c[2])
+ expect(bodies).toEqual(['c1', 'c3'])
+ })
+})
+
+describe('flush', () => {
+ it('fires every pending trailing write immediately (quit path: masters die right after)', async () => {
+ const { fs, sshFs } = fakeFs()
+ const io = makeRemoteWorkspaceIO(() => ref, sshFs)
+ await io.write('p1', ssh, 'c1') // immediate
+ await io.write('p1', ssh, 'c2') // pending trailing
+ await io.flush()
+ const bodies = fs.writeText.mock.calls.map((c) => c[2])
+ expect(bodies).toEqual(['c1', 'c2']) // no 5s wait
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(fs.writeText).toHaveBeenCalledTimes(2) // and the timer did not double-fire
+ })
+
+ it('flush with nothing pending resolves without writing', async () => {
+ const { fs, sshFs } = fakeFs()
+ const io = makeRemoteWorkspaceIO(() => ref, sshFs)
+ await io.flush()
+ expect(fs.writeText).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/remote-workspace-io.ts b/src/main/remote-workspace-io.ts
index bfc2437e9..c2a7a26e2 100644
--- a/src/main/remote-workspace-io.ts
+++ b/src/main/remote-workspace-io.ts
@@ -1,53 +1,84 @@
import path from 'path'
import type { Project } from '../shared/types'
-import type { RemoteWorkspaceIO } from '../core/workspace-store'
+import type { RemoteReadResult, RemoteWorkspaceIO } from '../core/workspace-store'
import { PROJECT_DIR, PROJECT_FILE } from '../core/workspace-files'
import type { SshFs, SshFsRef } from './ssh-fs'
/** Resolves an SSH project's live control master; null while disconnected. */
type RefResolver = (projectId: string) => SshFsRef | null
+export interface RemoteWorkspaceIOWithFlush extends RemoteWorkspaceIO {
+ /** Runs every pending throttled trailing write NOW. Call before the masters are killed at quit. */
+ flush(): Promise<void>
+}
+
/**
- * Remote .nodeterm IO over the project's existing ControlMaster. Fail-open: while the
- * project is disconnected every call is a quiet no-op (read null / write false) — the
- * cache in workspace.json keeps the project usable offline. Writes are throttled per
- * project (the renderer already debounces at 800 ms; a remote round-trip per keystroke
- * burst is still too chatty — spec says ~5 s).
+ * Remote .nodeterm IO over the project's existing ControlMaster. Fail-open on writes: while the
+ * project is disconnected a write is a quiet no-op (false) — the cache in workspace.json keeps
+ * the project usable offline. Reads are CHECKED: a down connection or ssh failure reports
+ * `error`, never `absent` — the reconciler treats only a real "no such file" as absence.
+ * Writes are throttled per project (the renderer already debounces at 800 ms; a remote
+ * round-trip per keystroke burst is still too chatty — spec says ~5 s). A throttled write is
+ * acked optimistically; if the trailing run later fails, `onDropped` reports it back so the
+ * store re-owes the mirror instead of believing it landed.
*/
-export function makeRemoteWorkspaceIO(resolveRef: RefResolver, sshFs: SshFs): RemoteWorkspaceIO {
+export function makeRemoteWorkspaceIO(
+ resolveRef: RefResolver,
+ sshFs: SshFs,
+ onDropped?: (projectId: string) => void
+): RemoteWorkspaceIOWithFlush {
const lastWrite = new Map<string, number>()
- const pending = new Map<string, ReturnType<typeof setTimeout>>()
+ const pending = new Map<string, { timer: ReturnType<typeof setTimeout>; run: () => Promise<void> }>()
const WRITE_THROTTLE_MS = 5000
const remotePath = (ssh: NonNullable<Project['ssh']>): string =>
path.posix.join(ssh.remoteCwd, PROJECT_DIR, PROJECT_FILE)
return {
- async read(projectId, ssh) {
+ async read(projectId, ssh): Promise<RemoteReadResult> {
const ref = resolveRef(projectId)
- if (!ref) return null
- const text = await sshFs.readText(ref, remotePath(ssh))
- return text || null
+ if (!ref) return { status: 'error' }
+ return sshFs.readTextChecked(ref, remotePath(ssh))
},
async write(projectId, ssh, content) {
- const ref = resolveRef(projectId)
- if (!ref) return false
- const run = async () => {
+ const run = async (): Promise<boolean> => {
lastWrite.set(projectId, Date.now())
- await sshFs.writeText(ref, remotePath(ssh), content)
+ // Re-resolve at fire time: a trailing write scheduled before a reconnect must use the
+ // live master, and a dead one must report the drop instead of throwing.
+ const ref = resolveRef(projectId)
+ if (!ref) return false
+ try {
+ return await sshFs.writeText(ref, remotePath(ssh), content)
+ } catch {
+ return false
+ }
}
+ if (!resolveRef(projectId)) return false
const since = Date.now() - (lastWrite.get(projectId) ?? 0)
if (since >= WRITE_THROTTLE_MS) {
// Cancel any pending trailing write so a stale older payload can't fire AFTER this newer
// one and clobber the final state (final-state-wins).
- clearTimeout(pending.get(projectId))
+ const prev = pending.get(projectId)
+ if (prev) clearTimeout(prev.timer)
pending.delete(projectId)
- await run()
- } else {
- clearTimeout(pending.get(projectId))
- pending.set(projectId, setTimeout(() => void run(), WRITE_THROTTLE_MS - since))
+ return run()
}
+ // Trailing write: acked optimistically; a later failure is reported via onDropped so the
+ // store re-owes the mirror (the old fire-and-forget silently lost the payload).
+ const fire = async (): Promise<void> => {
+ pending.delete(projectId)
+ if (!(await run())) onDropped?.(projectId)
+ }
+ const prev = pending.get(projectId)
+ if (prev) clearTimeout(prev.timer)
+ pending.set(projectId, { timer: setTimeout(() => void fire(), WRITE_THROTTLE_MS - since), run: fire })
return true
+ },
+ async flush() {
+ const flushed = [...pending.values()]
+ for (const p of flushed) clearTimeout(p.timer)
+ pending.clear()
+ await Promise.all(flushed.map((p) => p.run()))
}
}
}
diff --git a/src/main/ssh-fs.test.ts b/src/main/ssh-fs.test.ts
index 301ecea12..956ebcb34 100644
--- a/src/main/ssh-fs.test.ts
+++ b/src/main/ssh-fs.test.ts
@@ -14,20 +14,25 @@ describe('ssh-fs arg builders', () => {
it('readBinary base64s the quoted path', () => {
expect(sshReadBinaryArgs(conn, '/s.sock', '/i.png').join(' ')).toContain(`base64 '/i.png'`)
})
- it('write mkdir -p the dirname then cat > the quoted path (content via stdin, not interpolated)', () => {
+ // ATOMIC: `cat > file` truncates the target the moment it opens, so a connection dropped (or the
+ // ControlMaster killed at quit) mid-write left a HALF/EMPTY file behind — for .nodeterm/project.json
+ // that read as "my project reset itself". Write a sibling .tmp, then mv into place.
+ it('write mkdir -p the dirname, cat > a sibling .tmp, then mv into place (content via stdin)', () => {
const j = sshWriteArgs(conn, '/s.sock', '/d/e/f.txt').join(' ')
expect(j).toContain(`mkdir -p '/d/e'`)
- expect(j).toContain(`cat > '/d/e/f.txt'`)
+ expect(j).toContain(`cat > '/d/e/f.txt.tmp'`)
+ expect(j).toContain(`mv -f '/d/e/f.txt.tmp' '/d/e/f.txt'`)
})
// CRITICAL: SSH projects default to a home-relative remoteCwd (`~`). quoteRemotePath must leave a
// leading `~/` UNQUOTED so the remote shell tilde-expands it; the remainder stays single-quoted.
it('list leaves a leading ~/ unquoted so the remote shell tilde-expands the path', () => {
expect(sshListArgs(conn, '/s', '~/projects').join(' ')).toContain(`ls -Ap1 ~/'projects'`)
})
- it('write keeps ~/ unquoted for BOTH the mkdir dirname and the cat target', () => {
+ it('write keeps ~/ unquoted for the mkdir dirname, the .tmp target and the mv', () => {
const j = sshWriteArgs(conn, '/s', '~/projects/file.txt').join(' ')
expect(j).toContain(`mkdir -p ~/'projects'`)
- expect(j).toContain(`cat > ~/'projects/file.txt'`)
+ expect(j).toContain(`cat > ~/'projects/file.txt.tmp'`)
+ expect(j).toContain(`mv -f ~/'projects/file.txt.tmp' ~/'projects/file.txt'`)
})
it('mkdir runs mkdir -p on the quoted path', () => {
expect(sshMkdirArgs(conn, '/s.sock', '/a b/c').join(' ')).toContain(`mkdir -p '/a b/c'`)
@@ -90,4 +95,15 @@ describe('SshFs (injected runner)', () => {
expect(await new SshFs(async () => ({ code: 0, stdout: '' })).exists(ref, '/d')).toBe(true)
expect(await new SshFs(async () => ({ code: 1, stdout: '' })).exists(ref, '/d')).toBe(false)
})
+
+ // readText can't tell "the file is not there" from "the connection is down" — both come back ''.
+ // For workspace reconciliation that difference is load-bearing: absent → push our cache up,
+ // error → do NOTHING (a failed read is never evidence of absence). ssh itself exits 255 on any
+ // connection/auth failure; a remote `cat` on a missing file exits 1.
+ it('readTextChecked: exit 0 → ok+content, remote non-zero → absent, ssh 255/throw → error', async () => {
+ expect(await new SshFs(async () => ({ code: 0, stdout: 'hi' })).readTextChecked(ref, '/x')).toEqual({ status: 'ok', content: 'hi' })
+ expect(await new SshFs(async () => ({ code: 1, stdout: '' })).readTextChecked(ref, '/x')).toEqual({ status: 'absent' })
+ expect(await new SshFs(async () => ({ code: 255, stdout: '' })).readTextChecked(ref, '/x')).toEqual({ status: 'error' })
+ expect(await new SshFs(async () => { throw new Error('spawn') }).readTextChecked(ref, '/x')).toEqual({ status: 'error' })
+ })
})
diff --git a/src/main/ssh-fs.ts b/src/main/ssh-fs.ts
index 46548e82a..3a6535284 100644
--- a/src/main/ssh-fs.ts
+++ b/src/main/ssh-fs.ts
@@ -28,7 +28,12 @@ export function sshReadBinaryArgs(conn: SshConnection, cp: string, path: string)
return childArgs(conn, cp, `base64 ${quoteRemotePath(path)}`)
}
export function sshWriteArgs(conn: SshConnection, cp: string, path: string): string[] {
- return childArgs(conn, cp, `mkdir -p ${quoteRemotePath(dirname(path))} && cat > ${quoteRemotePath(path)}`)
+ // Atomic: `cat > file` truncates on open, so a connection dropped (or the ControlMaster killed
+ // at app quit) mid-write leaves a half/empty file — fatal for .nodeterm/project.json. Stream to
+ // a sibling .tmp and mv into place; a write that dies leaves the target untouched.
+ const target = quoteRemotePath(path)
+ const tmp = quoteRemotePath(`${path}.tmp`)
+ return childArgs(conn, cp, `mkdir -p ${quoteRemotePath(dirname(path))} && cat > ${tmp} && mv -f ${tmp} ${target}`)
}
export function sshMkdirArgs(conn: SshConnection, cp: string, path: string): string[] {
return childArgs(conn, cp, `mkdir -p ${quoteRemotePath(path)}`)
@@ -86,6 +91,25 @@ export class SshFs {
}
}
+ /**
+ * Like readText, but keeps "the file is not there" distinguishable from "the read failed".
+ * ssh exits 255 on any connection/auth failure; a remote command's own non-zero status (cat on
+ * a missing/unreadable file) passes through as-is. Workspace reconciliation depends on this:
+ * absent → push our cache up, error → do nothing (a failed read is never evidence of absence).
+ */
+ async readTextChecked(
+ ref: SshFsRef,
+ path: string
+ ): Promise<{ status: 'ok'; content: string } | { status: 'absent' } | { status: 'error' }> {
+ try {
+ const { code, stdout } = await this.run(sshReadArgs(ref.conn, ref.controlPath, path))
+ if (code === 0) return { status: 'ok', content: stdout }
+ return code === 255 ? { status: 'error' } : { status: 'absent' }
+ } catch {
+ return { status: 'error' }
+ }
+ }
+
async readBinary(ref: SshFsRef, path: string): Promise<string> {
try {
const { code, stdout } = await this.run(sshReadBinaryArgs(ref.conn, ref.controlPath, path))
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 83be6cdf2..c710bf062 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -4868,15 +4868,16 @@ export function Canvas() {
})
}, [])
- // Create an SSH project from the dialog: commit the current canvas, add + switch to the new
- // project (its master is opened by the active-project effect on switch), persist.
+ // Create an SSH project from the dialog: commit the current canvas, then open-or-reuse the
+ // project for that server folder (its master is opened by the active-project effect on switch),
+ // persist. openSshProject dedupes by endpoint+remoteCwd — re-adding a folder must reuse its
+ // existing project, never mint a fresh empty one that would clobber the server's project.json.
const createSshProject = useCallback(
(input: { server: SshServer; remoteCwd: string; label: string }) => {
commitActiveToStore()
- const project = useProjects
+ useProjects
.getState()
- .addProject(input.label, undefined, { server: input.server, remoteCwd: input.remoteCwd })
- useProjects.getState().setActive(project.id)
+ .openSshProject(input.label, { server: input.server, remoteCwd: input.remoteCwd })
// Same contract as onRepoCloned: the welcome screen waits behind the SSH dialog and
// dismisses only once the project is created (cancel returns to the welcome screen).
setWelcomeOpen(false)
diff --git a/src/renderer/state/projects.test.ts b/src/renderer/state/projects.test.ts
index 9b80c1075..4fe22d2a4 100644
--- a/src/renderer/state/projects.test.ts
+++ b/src/renderer/state/projects.test.ts
@@ -75,3 +75,55 @@ describe('setDinoHighScore', () => {
expect(useProjects.getState().projects).toHaveLength(0)
})
})
+
+// Regression: "Connect over SSH…" used to create a brand-new project (fresh id, empty canvas)
+// every time, even when a project for the same server+folder already existed — the empty canvas
+// then mirrored over the server's .nodeterm/project.json and wiped it. Same contract as
+// openFolderProject: reuse, reopen, never duplicate.
+describe('openSshProject', () => {
+ const server = { id: 's1', label: 'niova', host: 'h', user: 'root' } as never
+ const ssh = { server, remoteCwd: '~/app' }
+
+ it('creates a new ssh project and activates it when none matches', () => {
+ const p = useProjects.getState().openSshProject('app · niova', ssh)
+ expect(p.ssh).toEqual(ssh)
+ expect(p.name).toBe('app · niova')
+ const s = useProjects.getState()
+ expect(s.activeProjectId).toBe(p.id)
+ expect(s.projects).toHaveLength(1)
+ })
+
+ it('reuses the existing project for the same server+remoteCwd instead of duplicating', () => {
+ const first = useProjects.getState().openSshProject('app · niova', ssh)
+ // Re-added server entry: different SshServer id/label, same endpoint.
+ const readded = { id: 's2', label: 'renamed', host: 'h', user: 'root' } as never
+ const again = useProjects.getState().openSshProject('app · renamed', { server: readded, remoteCwd: '~/app' })
+ expect(again.id).toBe(first.id)
+ expect(useProjects.getState().projects).toHaveLength(1)
+ expect(useProjects.getState().activeProjectId).toBe(first.id)
+ })
+
+ it('reopens a closed matching project so it is visible again', () => {
+ const first = useProjects.getState().openSshProject('app · niova', ssh)
+ useProjects.getState().closeProject(first.id)
+ const p = useProjects.getState().openSshProject('app · niova', ssh)
+ expect(p.id).toBe(first.id)
+ const s = useProjects.getState()
+ expect(s.activeProjectId).toBe(first.id)
+ expect(s.projects.filter((q) => !q.closed).map((q) => q.id)).toEqual([first.id])
+ })
+
+ it('a different remoteCwd on the same server is a separate project', () => {
+ const first = useProjects.getState().openSshProject('app · niova', ssh)
+ const other = useProjects.getState().openSshProject('web · niova', { server, remoteCwd: '~/web' })
+ expect(other.id).not.toBe(first.id)
+ expect(useProjects.getState().projects).toHaveLength(2)
+ })
+
+ it('a different port on the same host is a separate project', () => {
+ const first = useProjects.getState().openSshProject('app · niova', ssh)
+ const alt = { id: 's3', label: 'alt', host: 'h', user: 'root', port: 2222 } as never
+ const other = useProjects.getState().openSshProject('app · alt', { server: alt, remoteCwd: '~/app' })
+ expect(other.id).not.toBe(first.id)
+ })
+})
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 8faa533b5..968cb66e3 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -25,6 +25,12 @@ interface ProjectsState {
* new one named after the folder. Activates and returns it (caller commits the current
* canvas first). */
openFolderProject(folder: string): Project
+ /** "Connect over SSH…": a server folder maps to one project, same contract as
+ * openFolderProject. Reuses the existing project with the same endpoint (host/user/port) and
+ * remoteCwd — reopening it if it was closed — or creates a new one. Re-adding must NEVER mint
+ * a fresh empty project for a folder that already has one: its first mirror write used to
+ * clobber the server's .nodeterm/project.json. Activates and returns it. */
+ openSshProject(label: string, ssh: NonNullable<Project['ssh']>): Project
/** Registers a probed project (from a folder's .nodeterm file). If the id collides with an
* existing project, derives a fresh project id (node ids untouched). Activates it. */
adoptProject(project: Project): Project
@@ -154,6 +160,24 @@ export const useProjects = create<ProjectsState>((set, get) => ({
return project
},
+ openSshProject(label, ssh) {
+ const existing = get().projects.find(
+ (p) =>
+ p.ssh &&
+ p.ssh.remoteCwd === ssh.remoteCwd &&
+ p.ssh.server.host === ssh.server.host &&
+ p.ssh.server.user === ssh.server.user &&
+ (p.ssh.server.port ?? 22) === (ssh.server.port ?? 22)
+ )
+ if (existing) {
+ get().reopenProject(existing.id)
+ return existing
+ }
+ const project = get().addProject(label, undefined, ssh)
+ set({ activeProjectId: project.id })
+ return project
+ },
+
adoptProject(project) {
const taken = get().projects.some((p) => p.id === project.id)
// A copied folder carries the original's project id; derive a fresh one. Node ids are