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): serialize saves, unique tmp files, and empty-write guards

enesb64ce6928305
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 547d45b75..d6889a6cc 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { promises as fs } from 'fs'
import os from 'os'
import path from 'path'
@@ -825,3 +825,106 @@ describe('ssh lineage safety', () => {
expect(adopted?.nodes.map((n) => n.id)).toContain('term-mobile-1')
})
})
+
+// 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
+// older save could land its stale index after a newer one. A corrupt index then silently became
+// EMPTY_WORKSPACE, which the renderer's unconditional boot save wrote back — zero entries, no backup.
+describe('save corruption hardening', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('overlapping saves land in call order — a slow earlier save cannot regress the index', async () => {
+ const store = new WorkspaceStore()
+ // Stall the FIRST project-file write so the first save is still in flight when the second lands.
+ let release!: () => void
+ const gate = new Promise<void>((r) => { release = r })
+ const realWrite = fs.writeFile.bind(fs)
+ let stalled = false
+ vi.spyOn(fs, 'writeFile').mockImplementation(async (p, data, enc) => {
+ if (!stalled && String(p).includes('project.json')) {
+ stalled = true
+ await gate
+ }
+ return realWrite(p as string, data as string, enc as BufferEncoding)
+ })
+ const first = store.save(ws([project({ cwd: projRoot })]))
+ const second = store.save(ws([project({ cwd: projRoot, name: 'renamed' })]))
+ await new Promise((r) => setTimeout(r, 100)) // unserialized, the second save finishes here
+ release()
+ await Promise.all([first, second])
+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(index.entries[0].name).toBe('renamed')
+ })
+
+ it('no two atomic writes ever share a tmp path (concurrent writers cannot splice)', async () => {
+ const tmpPaths: string[] = []
+ const realWrite = fs.writeFile.bind(fs)
+ vi.spyOn(fs, 'writeFile').mockImplementation(async (p, data, enc) => {
+ if (String(p).includes('.tmp')) tmpPaths.push(String(p))
+ return realWrite(p as string, data as string, enc as BufferEncoding)
+ })
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ await store.save(ws([project({ cwd: projRoot, name: 'renamed' })]))
+ expect(tmpPaths.length).toBeGreaterThanOrEqual(2) // both saves really wrote
+ expect(new Set(tmpPaths).size).toBe(tmpPaths.length)
+ })
+
+ it('an empty canvas never blind-overwrites a populated project.json it has not read', async () => {
+ await new WorkspaceStore().save(ws([project({ cwd: projRoot })])) // populated file on disk
+ // A different store (fresh boot, setProjectFolder, migration…) that never read that file:
+ const fresh = new WorkspaceStore()
+ await fresh.save(ws([project({ cwd: projRoot, nodes: [] })]))
+ const file = JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))
+ expect(file.nodes.map((n: any) => n.id)).toEqual(['term-1'])
+ // The rest of the save still happened — only the destructive file write was skipped.
+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(index.entries[0].cwd).toBe(projRoot)
+ })
+
+ it('a legitimately cleared canvas still persists for a store that has read the file', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ await store.save(ws([project({ cwd: projRoot, nodes: [] })])) // user deleted every node
+ const file = JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))
+ expect(file.nodes).toEqual([])
+ })
+
+ it('an unparsable workspace.json is sidelined to .corrupt-<ts> on load, not silently emptied', async () => {
+ await fs.writeFile(path.join(userData, 'workspace.json'), '{"version":3,"entries":[{"id"')
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects).toEqual([])
+ const names = await fs.readdir(userData)
+ const sidelined = names.find((n) => /^workspace\.json\.corrupt-\d+$/.test(n))
+ expect(sidelined).toBeDefined()
+ expect(await fs.readFile(path.join(userData, sidelined!), 'utf-8')).toBe('{"version":3,"entries":[{"id"')
+ expect(names).not.toContain('workspace.json')
+ })
+
+ it('a read-only load (sideline: false) leaves an unparsable workspace.json in place', async () => {
+ await fs.writeFile(path.join(userData, 'workspace.json'), 'not json')
+ await new WorkspaceStore().load({ sideline: false })
+ expect(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')).toBe('not json')
+ })
+
+ it('a fresh store may not replace a populated index with an empty workspace', async () => {
+ await new WorkspaceStore().save(ws([project({ cwd: projRoot })]))
+ const before = await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')
+ // Boot-order accident: save(empty) from a store that never managed to load the index
+ // (transient read failure, or a hydrate that raced the load).
+ await new WorkspaceStore().save(ws([]))
+ expect(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')).toBe(before)
+ })
+
+ it('closing every project after a successful load still persists the empty workspace', async () => {
+ await new WorkspaceStore().save(ws([project({ cwd: projRoot })]))
+ const store = new WorkspaceStore()
+ await store.load()
+ await store.save(ws([])) // the user really closed/deleted the last project
+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(index.entries).toEqual([])
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index a4df87a71..ad44b2b42 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -27,8 +27,12 @@ export interface RemoteWorkspaceIO {
const projectFilePath = (cwd: string): string => path.join(cwd, PROJECT_DIR, PROJECT_FILE)
+let tmpSeq = 0
async function writeAtomic(filePath: string, content: string): Promise<void> {
- const tmp = `${filePath}.tmp`
+ // Unique per write: writers that bypass each other's queue (a second app instance, the SSH
+ // poll's index write) must never share a tmp file — interleaved writes into one shared tmp
+ // published spliced JSON under the atomic rename.
+ const tmp = `${filePath}.${process.pid}.${++tmpSeq}.tmp`
await fs.writeFile(tmp, content, 'utf-8')
await fs.rename(tmp, filePath)
}
@@ -100,6 +104,14 @@ export class WorkspaceStore {
try {
parsed = JSON.parse(raw)
} catch {
+ // Same rule as a corrupt project.json: sideline the only copy so the boot flow's
+ // unconditional save cannot replace it with an empty index. Read-only callers must not
+ // mutate the disk (sideline: false).
+ if (sideline) {
+ try {
+ await fs.rename(this.indexPath, `${this.indexPath}.corrupt-${Date.now()}`)
+ } catch { /* best effort — never destroy data */ }
+ }
return EMPTY_WORKSPACE
}
const anyParsed = parsed as { version?: number }
@@ -213,7 +225,47 @@ export class WorkspaceStore {
return null
}
- async save(workspace: Workspace): Promise<void> {
+ /** True when writing an empty canvas to `file` destroys nothing: the file is absent (fresh
+ * folder) or already an empty-nodes project file. Populated AND unparsable both answer false —
+ * a corrupt file is left for readProjectFile's sideline instead of being overwritten. */
+ private async emptyOrAbsentOnDisk(file: string): Promise<boolean> {
+ let raw: string
+ try {
+ raw = await fs.readFile(file, 'utf-8')
+ } catch {
+ return true
+ }
+ try {
+ const parsed = JSON.parse(raw) as ProjectFileV1
+ return parsed?.version === 1 && Array.isArray(parsed.nodes) && parsed.nodes.length === 0
+ } catch {
+ return false
+ }
+ }
+
+ /** In-flight save chain: saves run FIFO (same idiom as SpeechService.queue). Overlapping saves
+ * used to interleave their file writes and land their indexes out of call order — the "both
+ * projects went blank after tab switching" wipe. */
+ private saveChain: Promise<unknown> = Promise.resolve()
+
+ save(workspace: Workspace): Promise<void> {
+ const run = this.saveChain.then(() => this.saveNow(workspace))
+ this.saveChain = run.catch(() => {})
+ return run
+ }
+
+ private async saveNow(workspace: Workspace): Promise<void> {
+ if (!workspace.projects.length && !this.index) {
+ // A store that never read the index may not replace a populated one with "no projects":
+ // that is the boot-save wipe — load() failed transiently, the renderer hydrated zero
+ // projects, and its unconditional boot save would atomically erase every ref. A fresh
+ // install has no readable index and falls through.
+ try {
+ const disk = JSON.parse(await fs.readFile(this.indexPath, 'utf-8')) as
+ { entries?: unknown[]; projects?: unknown[] }
+ if ((disk.entries?.length ?? 0) > 0 || (disk.projects?.length ?? 0) > 0) return
+ } catch { /* absent or unparsable (loadInner sidelines corruption) — an empty write is fresh */ }
+ }
const savedAt = new Date().toISOString()
const { index, files } = splitWorkspace(workspace, (id) => this.revs.get(id) ?? 0, savedAt)
@@ -251,6 +303,13 @@ export class WorkspaceStore {
const prev = this.lastWritten.get(file)
const prevParsed = prev ? (JSON.parse(prev) as ProjectFileV1) : null
if (prevParsed && sameProjectContent(prevParsed, candidate)) continue
+ if (!prevParsed && candidate.nodes.length === 0 && !(await this.emptyOrAbsentOnDisk(file))) {
+ // The local twin of the SSH "never blind-write a file we have not read" rule: an empty
+ // canvas from a store that never read this file (setProjectFolder, migration, a hydrate
+ // race) must not overwrite the populated — or corrupt-but-recoverable — only copy. The
+ // disk stays authoritative; the next load returns its truth.
+ continue
+ }
const next: ProjectFileV1 = { ...candidate, rev: (this.revs.get(candidate.id) ?? 0) + 1 }
const content = serializeProjectFile(next)
try {