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.

perf(workspace): skip re-parsing and unchanged index writes on autosave

enes080644641060
diff --git a/CLAUDE.md b/CLAUDE.md
index b8dd6a1d6..e47622937 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -419,6 +419,8 @@ Persistence has two layers:
- **Live terminal sessions** (tmux): terminals continue where they left off across node
remounts *and* full app restarts, including running processes. See below.
+**Autosave does no unchanged work** (`WorkspaceStore.save`): the parse of each `lastWritten` value is cached per raw string, and `workspace.json` is not rewritten when its bytes equal the store's last write AND the file still has the size+mtime that write left — so another instance's rewrite is still answered, a store's first save and a v2 migration always write, and every other index writer of ours clears the record.
+
`settings.json` is a separate store (`core/settings-store.ts`, `state/settings.ts`).
## Projects (tabs)
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 1134d4b2a..3f7dea3cc 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -1236,6 +1236,76 @@ describe('ssh reconcile self-write recognition (the spurious conflict bar)', ()
// 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.
+// Autosave runs 800 ms after every edit or camera move. It must not re-parse every folder project's
+// last-written bytes, nor rewrite an index whose bytes it already wrote — but a write another
+// writer made on disk since then must still be answered with ours.
+describe('autosave skips unchanged work', () => {
+ const indexPath = () => path.join(userData, 'workspace.json')
+ const readIndex = async () =>
+ JSON.parse((await fs.readFile(indexPath(), 'utf-8')).replace(/\r\n/g, '\n'))
+ const tick = () => new Promise((r) => setTimeout(r, 20))
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('a second identical save does not rewrite workspace.json', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ const first = (await fs.stat(indexPath())).mtimeMs
+ await tick()
+ await store.save(ws([project({ cwd: projRoot })]))
+ expect((await fs.stat(indexPath())).mtimeMs).toBe(first)
+ })
+
+ it('rewrites workspace.json when another writer changed it on disk, even if our index is unchanged', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ await fs.writeFile(indexPath(), '{"version":3,"entries":[]}') // another instance
+ await store.save(ws([project({ cwd: projRoot })]))
+ expect((await readIndex()).entries.length).toBeGreaterThan(0)
+ })
+
+ it('a changed index is still written', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ await store.save(ws([project({ cwd: projRoot, name: 'renamed' })]))
+ expect((await readIndex()).entries[0].name).toBe('renamed')
+ })
+
+ it('the first save of a store instance always writes, even when the bytes on disk already match', async () => {
+ await new WorkspaceStore().save(ws([project({ cwd: projRoot })]))
+ const again = new WorkspaceStore()
+ const loaded = await again.load()
+ const before = (await fs.stat(indexPath())).mtimeMs
+ await tick()
+ await again.save(loaded)
+ expect((await fs.stat(indexPath())).mtimeMs).not.toBe(before)
+ })
+
+ it('steady-state autosaves do not re-parse the project file last written', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ await store.save(ws([project({ cwd: projRoot })])) // parses the last write once
+ const raw = await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')
+ const parse = vi.spyOn(JSON, 'parse')
+ await store.save(ws([project({ cwd: projRoot })]))
+ expect(parse.mock.calls.some(([text]) => text === raw)).toBe(false)
+ })
+
+ it('compares against the NEWEST write: A → B → A writes the project file every time', async () => {
+ const store = new WorkspaceStore()
+ const file = path.join(projRoot, '.nodeterm/project.json')
+ await store.save(ws([project({ cwd: projRoot, name: 'a' })]))
+ await store.save(ws([project({ cwd: projRoot, name: 'b' })]))
+ expect(JSON.parse(await fs.readFile(file, 'utf-8')).name).toBe('b')
+ await store.save(ws([project({ cwd: projRoot, name: 'a' })]))
+ const back = JSON.parse(await fs.readFile(file, 'utf-8'))
+ expect(back.name).toBe('a')
+ expect(back.rev).toBe(3)
+ })
+})
+
describe('save corruption hardening', () => {
afterEach(() => {
vi.restoreAllMocks()
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 5b86ef471..0e3672884 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -130,6 +130,14 @@ export class WorkspaceStore {
* never match isSelfWrite, so every fs event on it read as an external change forever — endless
* spurious reloads and conflict bars (field bug 2026-08-10). */
private lastWritten = new Map<string, string>()
+ /** `lastWritten`'s bytes, parsed once. `save()` compares every folder project's candidate against
+ * its last write on EVERY autosave; re-parsing each file each time was pure waste. Keyed by the
+ * raw string, so any `lastWritten.set` elsewhere invalidates it by construction. */
+ private lastWrittenParsed = new Map<string, { raw: string; parsed: ProjectFileV1 }>()
+ /** The index bytes we last wrote and the file's size/mtime right after, so an unchanged index is
+ * not rewritten on every autosave — but one another writer changed on disk still is. Any other
+ * index write of ours clears it, so it only ever describes the last write `save()` made. */
+ private lastIndexWrite: { json: string; size: number; mtimeMs: number } | null = null
/** project id -> rev of the last written/loaded file. */
private revs = new Map<string, number>()
/** Entries whose one-time exec migration could NOT run (their project file was unreadable at load).
@@ -479,6 +487,7 @@ export class WorkspaceStore {
// next boot reads the old index and repairs again (harmlessly, but forever).
if (!repaired || !sideline) return
try {
+ this.lastIndexWrite = null
await writeAtomic(this.indexPath, JSON.stringify(this.index))
} catch { /* the next save writes it anyway */ }
}
@@ -815,6 +824,7 @@ export class WorkspaceStore {
const index = this.index
if (!index) return
this.applySettingsToIndex(index)
+ this.lastIndexWrite = null
await writeAtomic(this.indexPath, JSON.stringify(index))
}
@@ -949,6 +959,18 @@ export class WorkspaceStore {
return run
}
+ /** The parse of `lastWritten.get(file)`, cached per raw string (see `lastWrittenParsed`). Throws
+ * exactly where the inline `JSON.parse` it replaces did. */
+ private parsedLastWritten(file: string): ProjectFileV1 | null {
+ const raw = this.lastWritten.get(file)
+ if (!raw) return null
+ const hit = this.lastWrittenParsed.get(file)
+ if (hit && hit.raw === raw) return hit.parsed
+ const parsed = JSON.parse(raw) as ProjectFileV1
+ this.lastWrittenParsed.set(file, { raw, parsed })
+ return parsed
+ }
+
private async saveNow(workspace: Workspace, localOnly = false): Promise<void> {
if (!workspace.projects.length && !this.index) {
// A store that never read the index may not replace a populated one with "no projects":
@@ -1039,8 +1061,7 @@ export class WorkspaceStore {
for (const [cwd, candidate] of files) {
const projectId = projectIdForCwd.get(cwd) ?? cwd
const file = projectFilePath(cwd)
- const prev = this.lastWritten.get(file)
- const prevParsed = prev ? (JSON.parse(prev) as ProjectFileV1) : null
+ const prevParsed = this.parsedLastWritten(file)
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
@@ -1123,8 +1144,22 @@ export class WorkspaceStore {
this.pendingV2Backup = null
}
- // Compact index, atomic — same reasoning as the old single-file store.
- await writeAtomic(this.indexPath, JSON.stringify(index))
+ // Compact index, atomic — same reasoning as the old single-file store. Skipped when the bytes
+ // equal our last write AND the file still has the size/mtime that write left (another instance
+ // sharing this userData rewrote it otherwise). A migration always writes: the v3 flip is the
+ // point of that save.
+ const indexJson = JSON.stringify(index)
+ const onDisk = !migrating && this.lastIndexWrite?.json === indexJson
+ ? await fs.stat(this.indexPath).catch(() => null)
+ : null
+ const unchanged =
+ !!onDisk && onDisk.size === this.lastIndexWrite!.size && onDisk.mtimeMs === this.lastIndexWrite!.mtimeMs
+ if (!unchanged) {
+ this.lastIndexWrite = null
+ await writeAtomic(this.indexPath, indexJson)
+ const st = await fs.stat(this.indexPath).catch(() => null)
+ this.lastIndexWrite = st ? { json: indexJson, size: st.size, mtimeMs: st.mtimeMs } : null
+ }
await this.sweepRemovedDataFiles(previousIndex, index)
this.index = index
@@ -1206,6 +1241,7 @@ export class WorkspaceStore {
const file = inlineFilePath(e.id)
await fs.rm(file, { force: true }).catch(() => undefined)
this.lastWritten.delete(file)
+ this.lastWrittenParsed.delete(file)
this.revs.delete(e.id)
}
}
@@ -1315,6 +1351,7 @@ export class WorkspaceStore {
// Persist the index only when the reconcile moved something — a quiet poll must not churn
// workspace.json every tick.
if (adopted || e.cache?.rev !== revBefore) {
+ this.lastIndexWrite = null
await writeAtomic(this.indexPath, JSON.stringify(this.index))
}
return adopted