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.

feat(workspace): tell the user when a corrupt index was backed up

enesc634f0186228
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index d6889a6cc..d6448b3ca 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -910,6 +910,47 @@ describe('save corruption hardening', () => {
expect(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')).toBe('not json')
})
+ // Sidelining alone left the user in an empty workspace with no explanation ("my projects are
+ // gone") even though every .nodeterm/project.json is intact. The load path says so, once.
+ it('a sidelined index broadcasts the recovery note once, with the backup filename', async () => {
+ await fs.writeFile(path.join(userData, 'workspace.json'), 'not json')
+ const store = new WorkspaceStore()
+ await store.load()
+ const notes = fake.sent.filter((m) => m.channel === 'workspace:corrupt-recovered')
+ expect(notes).toHaveLength(1)
+ expect(notes[0].args[0]).toMatch(/^workspace\.json\.corrupt-\d+$/)
+ expect(await fs.readdir(userData)).toContain(notes[0].args[0])
+ // Second load of the same run (the sidelined copy is still there, index gone) stays quiet.
+ await store.load()
+ expect(fake.sent.filter((m) => m.channel === 'workspace:corrupt-recovered')).toHaveLength(1)
+ })
+
+ it('a read-only load (sideline: false) never broadcasts the recovery note', async () => {
+ await fs.writeFile(path.join(userData, 'workspace.json'), 'not json')
+ await new WorkspaceStore().load({ sideline: false })
+ expect(fake.sent.some((m) => m.channel === 'workspace:corrupt-recovered')).toBe(false)
+ })
+
+ // Crash between the sideline rename and the next index write: workspace.json is simply MISSING
+ // next to the backup, which is indistinguishable from a first run unless we look.
+ it('a missing index next to an existing .corrupt- backup still broadcasts (newest backup)', async () => {
+ await fs.writeFile(path.join(userData, 'workspace.json.corrupt-100'), 'old')
+ await fs.writeFile(path.join(userData, 'workspace.json.corrupt-900'), 'newer')
+ await new WorkspaceStore().load()
+ const notes = fake.sent.filter((m) => m.channel === 'workspace:corrupt-recovered')
+ expect(notes).toHaveLength(1)
+ expect(notes[0].args[0]).toBe('workspace.json.corrupt-900')
+ })
+
+ it('a normal load (and a first run) broadcasts nothing', async () => {
+ await new WorkspaceStore().save(ws([project({ cwd: projRoot })]))
+ await new WorkspaceStore().load() // healthy index
+ expect(fake.sent.some((m) => m.channel === 'workspace:corrupt-recovered')).toBe(false)
+ await fs.rm(path.join(userData, 'workspace.json'))
+ await new WorkspaceStore().load() // first run: nothing on disk at all
+ expect(fake.sent.some((m) => m.channel === 'workspace:corrupt-recovered')).toBe(false)
+ })
+
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')
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index ad44b2b42..3bf1c0003 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -56,6 +56,9 @@ export class WorkspaceStore {
private pendingExecNote = false
/** Raw v2 file content, kept until the first save backs it up (migration). */
private pendingV2Backup: string | null = null
+ /** The corrupt-index recovery note is a one-time-per-run banner: every later load in the same run
+ * sees the same missing index next to the same backup and must stay quiet. */
+ private corruptNoteSent = false
/** ssh project ids whose last mirror write was dropped (connection down). Retried on every
* save/connect until a write confirms — guarantees the server file lands regardless of node
* type or creation timing. Runtime-only, never persisted. */
@@ -98,6 +101,10 @@ export class WorkspaceStore {
try {
raw = await fs.readFile(this.indexPath, 'utf-8')
} catch {
+ // No index. Usually a first run — but it is also what a crash BETWEEN the sideline rename
+ // below and the next index write leaves behind, and that case owes the user the note. Only
+ // this branch pays for the readdir, and only for a load that may touch disk anyway.
+ if (sideline) this.noteCorruptIndex(await this.newestSidelined())
return EMPTY_WORKSPACE
}
let parsed: unknown
@@ -108,8 +115,11 @@ export class WorkspaceStore {
// unconditional save cannot replace it with an empty index. Read-only callers must not
// mutate the disk (sideline: false).
if (sideline) {
+ const backup = `${path.basename(this.indexPath)}.corrupt-${Date.now()}`
try {
- await fs.rename(this.indexPath, `${this.indexPath}.corrupt-${Date.now()}`)
+ await fs.rename(this.indexPath, path.join(platform().userDataDir, backup))
+ // Only AFTER the rename succeeded: the note promises a backup exists.
+ this.noteCorruptIndex(backup)
} catch { /* best effort — never destroy data */ }
}
return EMPTY_WORKSPACE
@@ -122,6 +132,28 @@ export class WorkspaceStore {
return legacy
}
+ /** Newest `workspace.json.corrupt-<ts>` sitting in userData, or null. */
+ private async newestSidelined(): Promise<string | null> {
+ const prefix = `${path.basename(this.indexPath)}.corrupt-`
+ let newest: { name: string; ts: number } | null = null
+ try {
+ for (const name of await fs.readdir(platform().userDataDir)) {
+ if (!name.startsWith(prefix)) continue
+ const ts = Number(name.slice(prefix.length))
+ if (!Number.isFinite(ts)) continue
+ if (!newest || ts > newest.ts) newest = { name, ts }
+ }
+ } catch { /* userData unreadable — nothing to report */ }
+ return newest?.name ?? null
+ }
+
+ /** One-time note: the index was lost but backed up, and no project data went with it. */
+ private noteCorruptIndex(backup: string | null): void {
+ if (!backup || this.corruptNoteSent) return
+ this.corruptNoteSent = true
+ platform().broadcast(IPC.workspaceCorruptRecovered, backup)
+ }
+
private async loadV3(index: WorkspaceIndexV3, sideline: boolean): Promise<Workspace> {
for (const entry of index.entries) entry.localApprovalId ||= randomUUID()
this.index = index
diff --git a/src/preload/index.ts b/src/preload/index.ts
index df0756473..b4db052c6 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -120,6 +120,11 @@ const api: NodeTerminalApi = {
ipcRenderer.on(IPC.workspaceMigrated, h)
return () => ipcRenderer.removeListener(IPC.workspaceMigrated, h)
},
+ onCorruptRecovered: (cb: (backupFile: string) => void) => {
+ const h = (_e: unknown, backupFile: string) => cb(backupFile)
+ ipcRenderer.on(IPC.workspaceCorruptRecovered, h)
+ return () => ipcRenderer.removeListener(IPC.workspaceCorruptRecovered, h)
+ },
onExternalChange: (cb: (project: Project) => void) => {
const h = (_e: unknown, p: Project) => cb(p)
ipcRenderer.on(IPC.workspaceExternalChange, h)
diff --git a/src/renderer/bridge/ws-bridge.namespaces.test.ts b/src/renderer/bridge/ws-bridge.namespaces.test.ts
index f79955f29..2a566793e 100644
--- a/src/renderer/bridge/ws-bridge.namespaces.test.ts
+++ b/src/renderer/bridge/ws-bridge.namespaces.test.ts
@@ -68,4 +68,12 @@ describe('buildRealApi: workspace', () => {
expect(c.calls[0]).toEqual({ kind: 'subscribe', method: IPC.workspaceMigrated, args: [] })
expect(typeof un).toBe('function')
})
+
+ it('onCorruptRecovered subscribes to the channel core actually broadcasts', () => {
+ const c = fakeClient()
+ const api = buildRealApi(c as never)
+ const un = api.workspace.onCorruptRecovered(() => {})
+ expect(c.calls[0]).toEqual({ kind: 'subscribe', method: IPC.workspaceCorruptRecovered, args: [] })
+ expect(typeof un).toBe('function')
+ })
})
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 3658e91b5..835fcbc2f 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -264,6 +264,8 @@ export function buildRealApi(
client.request(IPC.workspaceProbeFolder, folder) as ReturnType<WorkspaceApi['probeFolder']>,
// REAL: core broadcasts IPC.workspaceMigrated after a v2→v3 migration (workspace-store.ts).
onMigrated: (cb) => client.subscribe(IPC.workspaceMigrated, cb as Listener),
+ // REAL: core broadcasts IPC.workspaceCorruptRecovered from the load path (workspace-store.ts).
+ onCorruptRecovered: (cb) => client.subscribe(IPC.workspaceCorruptRecovered, cb as Listener),
// Deliberate degrade: the external-change WATCHER (core/workspace-watcher.ts) is only started
// by the desktop shell (src/main/index.ts), so the server never broadcasts
// IPC.workspaceExternalChange and there is nothing to subscribe to. Effect in the browser:
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 9f881d0c0..9b4327e9b 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -1819,6 +1819,16 @@ export function Canvas() {
})
}, [])
+ // Same strip, same one-shot rule: the workspace list came up empty because the index file was
+ // unreadable. Nothing was lost — say where the backup is and how to get the projects back.
+ useEffect(() => {
+ return api.workspace.onCorruptRecovered((backupFile) => {
+ setMigrationNote(
+ `The workspace index was corrupted and has been backed up as ${backupFile}. No project data was lost — each project's canvas is still in its own folder. Use “Open folder…” to add them back.`
+ )
+ })
+ }, [])
+
// A pending conflict is scoped to the project that was active when it fired. If the user
// switches projects first, drop it: commitActiveToStore already preserved the local edits in
// the store, so the next save keeps our version — resolving the stale bar against a different
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 2f0912fec..f1e83aaed 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -163,6 +163,8 @@ export const IPC = {
workspaceProbeFolder: 'workspace:probe-folder',
// main → renderer events
workspaceMigrated: 'workspace:migrated',
+ /** Payload: the `workspace.json.corrupt-<ts>` filename the unreadable index was preserved as. */
+ workspaceCorruptRecovered: 'workspace:corrupt-recovered',
workspaceExternalChange: 'workspace:external-change',
githubIssuesSubscribe: 'githubIssues:subscribe',
githubIssuesUnsubscribe: 'githubIssues:unsubscribe',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index ee0124e44..3330e5315 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -610,6 +610,10 @@ export interface WorkspaceApi {
* project folders; `exec` = the custom shell / advanced ssh args of already-open projects moved
* out of the shared project file into this machine's own workspace index (@shared/node-exec). */
onMigrated(cb: (kind: WorkspaceMigrationKind) => void): () => void
+ /** Fired once per run when a load found the workspace index unreadable and preserved it as
+ * `workspace.json.corrupt-<ts>` (the payload). The projects themselves are untouched — their
+ * canvases live in each <cwd>/.nodeterm/project.json — so the note tells the user to re-add them. */
+ onCorruptRecovered(cb: (backupFile: string) => void): () => void
/** Fired when a project file changed on disk outside the app (git pull, sync, teammate). */
onExternalChange(cb: (project: Project) => void): () => void
}