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): final-review findings — relay v2 blob, read-only probe, conflict-bar race, same-cwd clobber, unavailable switch guard

enes1ee9dac327a4
diff --git a/src/core/workspace-files.test.ts b/src/core/workspace-files.test.ts
index 34f8a25c2..b16219266 100644
--- a/src/core/workspace-files.test.ts
+++ b/src/core/workspace-files.test.ts
@@ -83,6 +83,25 @@ describe('splitWorkspace', () => {
expect(index.entries[2].cache!.id).toBe('p3')
expect(files.has('~/app')).toBe(false) // ssh files are not local writes
})
+ it('two projects on the same cwd → one file + one inline entry (no last-wins clobber)', () => {
+ const shared: Workspace = {
+ version: 2, activeProjectId: 'a',
+ projects: [
+ project({ id: 'a', name: 'first', cwd: '/a/foo' }),
+ project({ id: 'b', name: 'second', cwd: '/a/foo' })
+ ]
+ }
+ const { index, files } = splitWorkspace(shared, () => 1, '2026-07-11T00:00:00.000Z')
+ expect(files.size).toBe(1) // only the first claims the file
+ expect(files.get('/a/foo')!.id).toBe('a')
+ expect(index.entries[0]).toMatchObject({ id: 'a', cwd: '/a/foo' })
+ expect(index.entries[0].project).toBeUndefined()
+ // The second is kept verbatim inline — no file, nothing lost.
+ expect(index.entries[1].cwd).toBeUndefined()
+ expect(index.entries[1].project).toMatchObject({ id: 'b', name: 'second', cwd: '/a/foo' })
+ expect(index.entries[1].project!.unavailable).toBeUndefined()
+ })
+
it('never persists the runtime unavailable flag inline', () => {
const { index } = splitWorkspace(
{ version: 2, activeProjectId: 'x', projects: [project({ id: 'x', unavailable: true })] },
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index e0944b52d..a96c6db69 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -134,9 +134,16 @@ export function splitWorkspace(
}
if (p.ssh) {
entries.push({ ...header, ssh: p.ssh, cache: projectToFile(p, revOf(p.id), savedAt) })
- } else if (p.cwd) {
+ } else if (p.cwd && !files.has(p.cwd)) {
files.set(p.cwd, projectToFile(p, revOf(p.id), savedAt))
entries.push({ ...header, cwd: p.cwd })
+ } else if (p.cwd) {
+ // Another project already claimed this cwd (two tabs on one folder). Keying `files` by cwd
+ // would collapse them last-wins, and reload would resurrect BOTH entries from the one file
+ // (duplicate ids, first canvas lost). Emit this one INLINE instead — kept verbatim in the
+ // index, no file write — so both canvases survive a save→load round trip.
+ const { unavailable: _u, ...inline } = p
+ entries.push({ ...header, project: inline })
} else {
const { unavailable: _u, ...inline } = p
entries.push({ ...header, project: inline })
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index d4094398e..7cc68ebeb 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -170,6 +170,17 @@ describe('probeFolder', () => {
expect(probed).toMatchObject({ id: 'p1', cwd: projRoot })
expect(await store.probeFolder(path.join(projRoot, 'nope'))).toBeNull()
})
+
+ it('is read-only: a corrupt file returns null WITHOUT sidelining it (arbitrary-path RPC)', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ const p = path.join(projRoot, '.nodeterm/project.json')
+ await fs.writeFile(p, '{ not json')
+ expect(await store.probeFolder(projRoot)).toBeNull()
+ expect(await fs.readFile(p, 'utf-8')).toBe('{ not json') // untouched
+ const dir = await fs.readdir(path.join(projRoot, '.nodeterm'))
+ expect(dir.some((f) => f.startsWith('project.json.corrupt-'))).toBe(false) // no sideline
+ })
})
describe('readLocalRefByPath', () => {
@@ -181,6 +192,50 @@ describe('readLocalRefByPath', () => {
expect(p).toMatchObject({ id: 'p1', cwd: projRoot })
expect(await store.readLocalRefByPath(path.join(projRoot, 'nope/project.json'))).toBeNull()
})
+
+ it('leaves a git-conflict-marked file in place (mid-merge is hand-resolvable, never sidelined)', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ const filePath = path.join(projRoot, '.nodeterm/project.json')
+ const conflicted = '<<<<<<< HEAD\n{"version":1}\n=======\n{"version":1}\n>>>>>>> theirs\n'
+ await fs.writeFile(filePath, conflicted)
+ expect(await store.readLocalRefByPath(filePath)).toBeNull() // unparsable → no project
+ expect(await fs.readFile(filePath, 'utf-8')).toBe(conflicted) // but left in place
+ const dir = await fs.readdir(path.join(projRoot, '.nodeterm'))
+ expect(dir.some((f) => f.startsWith('project.json.corrupt-'))).toBe(false)
+ })
+})
+
+describe('same-cwd projects survive a save → load round trip', () => {
+ it('two tabs on one folder both come back (first file-backed, second inline)', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ id: 'a', name: 'first', cwd: projRoot }), project({ id: 'b', name: 'second', cwd: projRoot })]))
+ // Only one file exists on disk; the second is inline in the index.
+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(index.entries.filter((e: any) => e.cwd).length).toBe(1)
+ expect(index.entries.find((e: any) => e.project)?.project.id).toBe('b')
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects.map((p) => p.id).sort()).toEqual(['a', 'b'])
+ expect(loaded.projects.find((p) => p.id === 'a')).toMatchObject({ name: 'first', cwd: projRoot })
+ expect(loaded.projects.find((p) => p.id === 'b')).toMatchObject({ name: 'second' })
+ })
+})
+
+describe('projects.list relay blob (iOS wire contract)', () => {
+ it('the blob JSON.stringify(load()) parses as {version:2, projects:[…]} even when the file is v3', async () => {
+ // Seed a real v3 tree on disk (file-backed local ref), as listProjectsOutput sees it.
+ await new WorkspaceStore().save(ws([project({ cwd: projRoot })]))
+ const onDisk = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(onDisk.version).toBe(3) // the raw file the OLD blob shipped
+
+ // listProjectsOutput now serves JSON.stringify(await workspaceStore.load()).
+ const blob = JSON.stringify(await new WorkspaceStore().load())
+ const parsed = JSON.parse(blob)
+ expect(parsed.version).toBe(2)
+ expect(Array.isArray(parsed.projects)).toBe(true)
+ expect(parsed.projects[0]).toMatchObject({ id: 'p1', cwd: projRoot })
+ expect(parsed.projects[0].nodes[0].id).toBe('term-1') // node data present (not in the v3 file)
+ })
})
describe('refreshSshProject', () => {
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 9c7945131..a04671ed5 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -90,7 +90,7 @@ export class WorkspaceStore {
if (e.project) {
projects.push(e.project)
} else if (e.cwd) {
- const p = await this.readProjectFile(e.cwd)
+ const p = await this.readProjectFile(e.cwd, true)
if (p) {
this.revs.set(p.id, p.rev)
this.lastWritten.set(projectFilePath(e.cwd), serializeProjectFile(p))
@@ -113,8 +113,14 @@ export class WorkspaceStore {
return { version: 2, activeProjectId: active, projects }
}
- /** Reads + parses one project file; a corrupt file is set aside (never overwritten). */
- private async readProjectFile(cwd: string): Promise<ProjectFileV1 | null> {
+ /**
+ * Reads + parses one project file. Only the authoritative loadV3 path passes `sideline: true`,
+ * which renames an unparsable/wrong-shape file to `.corrupt-<ts>` so a later save can't overwrite
+ * the only copy. Read-only callers (probeFolder — an RPC reachable with arbitrary paths on Server
+ * Edition — and the watcher's readLocalRef*) pass false: a probe must never mutate the disk, and a
+ * git-conflict-marked project.json mid-merge must be left in place so the user can hand-resolve it.
+ */
+ private async readProjectFile(cwd: string, sideline: boolean): Promise<ProjectFileV1 | null> {
const file = projectFilePath(cwd)
let raw: string
try {
@@ -127,9 +133,11 @@ export class WorkspaceStore {
if (parsed?.version === 1 && typeof parsed.id === 'string' && Array.isArray(parsed.nodes)) return parsed
// parses but isn't a ProjectFileV1 — sideline it too, so a later save can't overwrite the only copy.
} catch { /* not JSON — sideline below */ }
- try {
- await fs.rename(file, `${file}.corrupt-${Date.now()}`)
- } catch { /* best effort — never destroy data */ }
+ if (sideline) {
+ try {
+ await fs.rename(file, `${file}.corrupt-${Date.now()}`)
+ } catch { /* best effort — never destroy data */ }
+ }
return null
}
@@ -178,24 +186,27 @@ export class WorkspaceStore {
}
}
+ // 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.
+ const migrating = this.pendingV2Backup !== null
+ if (migrating) {
+ try {
+ await writeAtomic(path.join(platform().userDataDir, 'workspace.v2.bak'), this.pendingV2Backup!)
+ } catch { /* backup is best-effort */ }
+ this.pendingV2Backup = null
+ }
+
// Compact index, atomic — same reasoning as the old single-file store.
await writeAtomic(this.indexPath, JSON.stringify(index))
this.index = index
- if (this.pendingV2Backup !== null) {
- const bak = this.pendingV2Backup
- this.pendingV2Backup = null
- try {
- await writeAtomic(path.join(platform().userDataDir, 'workspace.v2.bak'), bak)
- } catch { /* backup is best-effort */ }
- platform().broadcast(IPC.workspaceMigrated)
- }
+ if (migrating) platform().broadcast(IPC.workspaceMigrated)
this.onPersist?.()
}
async probeFolder(folder: string): Promise<Project | null> {
- const f = await this.readProjectFile(folder)
+ const f = await this.readProjectFile(folder, false)
return f ? fileToProject(f, { cwd: folder }) : null
}
@@ -210,7 +221,7 @@ export class WorkspaceStore {
async readLocalRef(projectId: string): Promise<Project | null> {
const e = this.index?.entries.find((x) => x.id === projectId && x.cwd)
if (!e?.cwd) return null
- const f = await this.readProjectFile(e.cwd)
+ const f = await this.readProjectFile(e.cwd, false)
if (!f) return null
this.revs.set(f.id, f.rev)
this.lastWritten.set(projectFilePath(e.cwd), serializeProjectFile(f))
diff --git a/src/main/index.ts b/src/main/index.ts
index 7389b864e..de73ba50f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -143,7 +143,15 @@ const NT_STATUS_MARK = '--NT-STATUS-SPLIT--'
*/
async function listProjectsOutput(): Promise<string> {
const dir = app.getPath('userData')
- const workspace = await readFile(join(dir, 'workspace.json'), 'utf8').catch(() => '')
+ // Serve the ASSEMBLED v2-shaped workspace, never the raw workspace.json. Post-migration the file
+ // is a v3 index ({version:3, entries:[…]}) whose local-ref entries hold no node data at all — the
+ // paired iOS client decodes `{ projects: [Project] }`, so a raw v3 file lists zero projects.
+ // load() re-reads each ref's .nodeterm/project.json and returns {version:2, projects:[…]}; it is
+ // idempotent (and re-syncs the watcher via onPersist), so calling it here is safe.
+ const workspace = await workspaceStore
+ .load()
+ .then((w) => JSON.stringify(w))
+ .catch(() => '')
const status = await readFile(join(dir, 'agent-status.json'), 'utf8').catch(() => '')
const sessions = (await ptyManager.listNodetermSessions().catch(() => [])).join('\n')
return `${workspace}\n${NT_PROJECTS_MARK}\n${sessions}\n${NT_STATUS_MARK}\n${status}`
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 4d10a53e4..ef5e78136 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -880,12 +880,15 @@ export function Canvas() {
setConflict(null)
}, [activeProjectId])
- // Debounced auto-save for canvas edits.
+ // Debounced auto-save for canvas edits. Suppressed while a conflict bar is up: the bar only ever
+ // appears WHILE dirty, so without this gate the 800ms timer would fire and silently "keep mine"
+ // (overwrite the external disk version) before the user can choose. `conflict` is a dep so
+ // resolving it (either button clears it) re-arms the save.
useEffect(() => {
- if (!dirty) return
+ if (!dirty || conflict) return
const t = setTimeout(() => void persist(), 800)
return () => clearTimeout(t)
- }, [dirty, persist])
+ }, [dirty, conflict, persist])
// ---- remote canvas mirror (host side) ----
// While hosting, push the serialized active-project canvas to main (debounced ~120ms) on every
@@ -3459,10 +3462,18 @@ export function Canvas() {
async (id: string) => {
const folder = await window.nodeTerminal.dialog.selectFolder()
if (!folder) return
+ // Folder ↔ project is deduped like "Open folder…": if another project already owns this cwd,
+ // don't point a second tab at it (two same-cwd tabs collapse to one file on save) — just
+ // switch to the existing one.
+ const existing = useProjects.getState().projects.find((p) => p.cwd === folder && p.id !== id)
+ if (existing) {
+ switchProject(existing.id)
+ return
+ }
useProjects.getState().setProjectCwd(id, folder)
void persist()
},
- [persist]
+ [persist, switchProject]
)
const setProjectDefaultAccount = useCallback(
@@ -3664,7 +3675,10 @@ export function Canvas() {
]
const store = useProjects.getState()
store.projects
- .filter((p) => p.id !== store.activeProjectId)
+ // Skip unavailable projects: activating one lets edits commit to the store but they're
+ // dropped on save (the ref emits header-only), so switching there silently loses work.
+ // The TabBar already guards its own click; this covers the palette (⌘K) path.
+ .filter((p) => p.id !== store.activeProjectId && !p.unavailable)
.forEach((p) =>
cmds.push({
id: `proj-${p.id}`,
@@ -3769,6 +3783,10 @@ export function Canvas() {
<ConflictBar
onReload={() => {
useProjects.getState().replaceProject(conflict)
+ // The canvas now matches disk exactly → no local unsaved edits. Clear dirty so the
+ // re-armed autosave (conflict just went null) can't turn around and overwrite the
+ // just-reloaded disk version.
+ setDirty(false)
setConflict(null)
reloadActiveProject()
}}