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): give every cwd-less project its own file

enes879739fa52a1
diff --git a/CLAUDE.md b/CLAUDE.md
index 455225a24..6d0143877 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -198,8 +198,19 @@ Persistence has two layers:
**index**: local folder projects are refs to `<cwd>/.nodeterm/project.json` (the source of
truth — git-shareable, machine-portable; pretty-printed, portable `./` node cwds, monotonic
`rev`), SSH projects are refs to the same file on the server (offline `cache` in the index,
- reconciled by rev on connect, mirrored via `SshFs` with a 5 s write throttle), cwd-less
- canvases stay inline. The renderer contract is untouched: `workspace.load()/save()` still
+ reconciled by rev on connect, mirrored via `SshFs` with a 5 s write throttle), and cwd-less
+ canvases are refs to `userData/inline-projects/<id>.json`. **Every entry is a ref — one shape,
+ three kinds:**
+
+ | kind | source of truth for the CONTENT | what the index entry carries |
+ |---|---|---|
+ | folder-ref | `<cwd>/.nodeterm/project.json` (git-shared) | `cwd` + header + machine-local half |
+ | ssh-ref | the same file on the host | `ssh` + header + `cache` (offline copy, rev-reconciled) |
+ | local-data-ref | `userData/inline-projects/<id>.json` | `dataFile` + header + `project` (cache) |
+
+ In all three the file carries CONTENT and the entry carries the machine-local half — project
+ `id`, `viewport`, `defaultAccountId`, `breadcrumbs`, `closedSessions`, `localApprovalId`,
+ `localExec`, `localSettings` (the #510 rule). The renderer contract is untouched: `workspace.load()/save()` still
speak an assembled v2-shaped `Workspace`; all fan-out lives in `core/workspace-store.ts` +
pure `core/workspace-files.ts`. v2 files migrate on first save (backup `workspace.v2.bak`,
one-time renderer note). Outside edits (git pull/sync) are detected by
@@ -209,17 +220,32 @@ Persistence has two layers:
`.nodeterm/project.json` — the probe MINTS the project id (node ids — tmux names — kept), and
re-opening the folder is answered by the cwd lookup, not a second adoption.
**A cwd-less canvas is a supported, first-class project, not a degraded one** — "New project" on
- the welcome screen creates exactly that, and the whole `Project` (nodes, viewport, kanban,
- closedSessions, per-node `shell`) rides `IndexEntryV3.project` verbatim, so it survives a restart
- intact. It is the correct fallback layer and `localStorage` is not: the index is in `userData`
- (backed up with the app's data, atomic-written, one store for all three shells), while
- localStorage is renderer-origin state that the Server Edition would shard per browser profile.
- What inline genuinely lacks is a SECOND copy: a folder project's canvas also lives in
- `<cwd>/.nodeterm/project.json`, so a corrupt index costs it nothing (`Open folder…` adopts it
- back), whereas an inline canvas exists ONLY inside the index — and therefore only inside the
- `workspace.json.corrupt-<ts>` sideline, with no UI path back. The corrupt-index note must say
- that plainly; it used to promise "No project data was lost — each project's canvas is still in
- its own folder", which is true for refs and false for exactly the projects that just vanished.
+ the welcome screen creates exactly that, and it survives a restart intact. It is the correct
+ fallback layer and `localStorage` is not: `userData` is backed up with the app's data,
+ atomic-written, and one store for all three shells, while localStorage is renderer-origin state
+ the Server Edition would shard per browser profile.
+ **What it used to lack was a SECOND copy, and that is what `local-data-ref` fixes.** A folder
+ project's canvas also lives in `<cwd>/.nodeterm/project.json`, so a corrupt or clobbered index
+ costs it nothing; an inline canvas existed ONLY inside the index — one file, last-writer-wins, so
+ a second instance sharing that `userData` erased canvases that existed nowhere else, and a corrupt
+ index left them only inside the `workspace.json.corrupt-<ts>` sideline with no UI path back.
+ Each now has its own atomically written file, and the entry's `project` field is kept beside it as
+ a **cache** — the dual-write that (a) lets a build older than this one still read the canvas out
+ of the index (the downgrade contract, ONE release; the iOS SSH-browse path cats `workspace.json`
+ directly and depends on it too) and (b) answers when the data file is missing or corrupt.
+ The file wins whenever it reads. Rules that make this safe, all in `WorkspaceStore.writeDataFile`:
+ an unchanged candidate is not written at all; **a lower `rev` may not overwrite a higher one** (a
+ second instance wrote it after we looked — its canvas stands, the next load here adopts it, and
+ there is deliberately NO merge: the guarantee is "two instances cannot erase each other", not
+ "two instances stay in sync"); an empty candidate never overwrites a populated file this store has
+ not read. A corrupt data file is set aside as `.corrupt-<ts>` like any other project file, and the
+ sweep that deletes a removed project's file only ever touches ids THIS store had loaded — a file
+ belonging to another instance is never deleted, at the price of some litter after a re-key.
+ `userData/inline-projects` is deliberately NOT watched (`workspace-watcher` covers folder refs
+ only): nothing external edits it — no git pull, no teammate — and the rev rule is the whole
+ concurrency story. The corrupt-index note still matters and must stay honest; it used to promise
+ "No project data was lost — each project's canvas is still in its own folder", which was true for
+ refs and false for exactly the projects that had just vanished.
**Binding a folder to an existing project is a WRITE, so probe before you bind.** "Set folder…"
(tab ⌄) promotes an inline canvas to a ref, and the next autosave writes that folder's
`project.json` — over whatever was already there. It used to bind unconditionally, so pointing a
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e70d794f3..7f7da4f1c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -235,9 +235,22 @@ no backup, nothing on screen. Both entrances now share the rule (`renderer/lib/s
an occupied *or unreadable* project file refuses the bind and says why. The store's "never
blind-write" guard will not save you — it only refuses an EMPTY canvas over a populated file.
+**Every workspace entry is a REF — content in a file, machine-local state on the entry.** There are
+three kinds and they now share one shape: a folder ref (`<cwd>/.nodeterm/project.json`, git-shared),
+an SSH ref (the same file on the host, with an offline `cache`), and a cwd-less canvas
+(`userData/inline-projects/<id>.json`, with the entry's `project` field kept as a cache for one
+release so an older build still reads it). Two habits follow. **Content goes in the file; anything
+this machine would legitimately disagree with another machine about — project id, viewport, default
+account, breadcrumbs, closed-session history, per-node `shell` — goes on the index entry**
+(`IndexEntryV3`), or a `git worktree add` / a second instance hands one machine's state to another.
+And **`workspace.json` is one file with last-writer-wins semantics, so it may not be the only home
+of any content**: that is precisely what let a second app instance erase a cwd-less canvas. Between
+two instances the arbiter is the file's `rev` — a lower rev never overwrites a higher one — and
+there is no merge; if you add a fourth kind, give it a file and say which rev wins.
+
**A project with no folder is a real project — degrade explicitly, never silently.** "New project"
-creates a cwd-less canvas that persists inline in `workspace.json`, so every folder-shaped feature
-meets one. Keep the affordance and disable it with its reason (`NEW_FILE_NO_CWD_HINT`,
+creates a cwd-less canvas, so every folder-shaped feature meets one. Keep the affordance and
+disable it with its reason (`NEW_FILE_NO_CWD_HINT`,
`WORKTREE_NO_CWD_HINT`, the Explorer/Source Control notes); a row that simply vanishes teaches
nothing, and a message that names the wrong cause ("not a git repository" for a project that has no
folder to be one) sends the user hunting a problem that does not exist.
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index d88d8cd8b..ef18f558e 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -57,6 +57,28 @@ export function sanitizeNodeTriggers(nodes: CanvasNodeState[]): CanvasNodeState[
export const PROJECT_DIR = '.nodeterm'
export const PROJECT_FILE = 'project.json'
+/** Where a cwd-less ("inline") project's content lives, under userData: the twin of a folder
+ * project's `<cwd>/.nodeterm/project.json`. One file per project, named by the project id. */
+export const INLINE_PROJECT_DIR = 'inline-projects'
+
+/**
+ * May this project id name a file in `userData/inline-projects/`?
+ *
+ * workspace.json is hand-editable (and on Server Edition it sits next to other users' reach), so an
+ * id read back out of it is INPUT, not something we wrote. Minted ids are `project-<base36>-<hex>`
+ * (`freshProjectId` / `derivedProjectId`), well inside this charset; anything else — a separator, a
+ * `..` segment, a leading dot, an empty or absurdly long string — is refused, and its entry simply
+ * keeps the pre-file inline shape (content in the index) instead of naming a path we did not mean.
+ */
+export function isInlineProjectFileId(id: string): boolean {
+ return /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(id) && !id.includes('..')
+}
+
+/** The data file for one inline project, relative to userData. */
+export function inlineProjectFileRelPath(id: string): string {
+ return path.join(INLINE_PROJECT_DIR, `${id}.json`)
+}
+
/**
* On-disk shape of <cwd>/.nodeterm/project.json — a GIT-SHARED document (users are asked to
* commit it so the canvas travels with the repo).
@@ -129,10 +151,28 @@ export interface ProjectFileV1 {
// `IndexEntryV3.closedSessions`. It is machine-local, like `viewport`/`breadcrumbs`.
}
-/** One workspace.json v3 entry. Exactly one of: `cwd` (local ref), `ssh` (remote ref),
- * `project` (inline, cwd-less canvas). name/color are a cached header so an
- * unavailable ref still renders a labeled grey tab. `cache` (ssh only) is the last
- * ProjectFileV1 seen/written — used while the server is unreachable. */
+/**
+ * One workspace.json v3 entry — a REF, in one of three kinds. name/color are a cached header so an
+ * unavailable ref still renders a labeled grey tab.
+ *
+ * kind | source of truth for the content | what the index entry carries
+ * ---------------|---------------------------------------|--------------------------------------
+ * folder-ref | `<cwd>/.nodeterm/project.json` (git) | `cwd` + header + machine-local half
+ * ssh-ref | the same file on the host | `ssh` + header + `cache` (offline)
+ * local-data-ref | `userData/inline-projects/<id>.json` | `dataFile` + header + `project` (cache)
+ *
+ * The third kind is the cwd-less canvas ("New project", no folder). It used to have no file at
+ * all — the whole `Project` rode `project` inside this index, which is ONE file with
+ * last-writer-wins semantics: a second instance sharing this userData could erase a canvas that
+ * existed nowhere else (measured in #621). It now has its own atomically written file like the
+ * other two, and `project` stays beside it as a cache, so a build older than this one still finds
+ * the canvas where it expects it.
+ *
+ * In all three kinds the file carries CONTENT and the entry carries the machine-local half
+ * (id, viewport, defaultAccountId, breadcrumbs, closedSessions, localApprovalId, localExec) — the
+ * #510 rule. That uniformity is the point: it is also what makes a future "Set folder…" a MOVE of
+ * the data file into `<cwd>/.nodeterm/project.json` rather than a reshaping of the project.
+ */
export interface IndexEntryV3 {
/**
* THE project id — this machine's, and the only authority for it. It is minted here (a new
@@ -175,6 +215,23 @@ export interface IndexEntryV3 {
cwd?: string
ssh?: Project['ssh']
cache?: ProjectFileV1
+ /**
+ * This entry is a LOCAL-DATA ref: its content lives in `userData/inline-projects/<id>.json` and
+ * THAT FILE is the source of truth. Absent = the pre-file shape, where `project` below IS the
+ * content. Never set together with `cwd`/`ssh`.
+ *
+ * A build that predates this field ignores it and reads `project`, which is why the two are
+ * written together for one release (the downgrade contract).
+ */
+ dataFile?: boolean
+ /**
+ * The cwd-less canvas.
+ *
+ * Before `dataFile` this WAS the storage. Beside a `dataFile` entry it is a CACHE — the local
+ * twin of the ssh `cache` above — doing two jobs: an older build still finds the canvas here,
+ * and a data file that is missing or corrupt right now falls back to it instead of opening an
+ * empty canvas. The file wins whenever it reads.
+ */
project?: Project
/** MACHINE-LOCAL per-node exec values (`shell`, `ssh.extraArgs`) for a ref'd project. They are
* stripped from the shared project file precisely so a cloned/hostile one cannot run code
@@ -491,14 +548,26 @@ export function sameProjectContent(a: ProjectFileV1, b: ProjectFileV1): boolean
return JSON.stringify(strip(a)) === JSON.stringify(strip(b))
}
-/** Splits an in-memory workspace into the v3 index + the local project files to write. */
+/**
+ * Splits an in-memory workspace into the v3 index + the project files to write.
+ *
+ * `files` is keyed by CWD (folder refs, written into the user's own repo); `dataFiles` is keyed by
+ * PROJECT ID (cwd-less canvases, written under `userData/inline-projects`). Both hold a
+ * `ProjectFileV1` — one shape, which is what lets a future "Set folder…" MOVE the second into the
+ * first instead of converting it.
+ */
export function splitWorkspace(
ws: Workspace,
revOf: (projectId: string) => number,
savedAt: string
-): { index: WorkspaceIndexV3; files: Map<string, ProjectFileV1> } {
+): {
+ index: WorkspaceIndexV3
+ files: Map<string, ProjectFileV1>
+ dataFiles: Map<string, ProjectFileV1>
+} {
const entries: IndexEntryV3[] = []
const files = new Map<string, ProjectFileV1>()
+ const dataFiles = new Map<string, ProjectFileV1>()
const seenIds = new Set<string>()
for (const incoming of ws.projects) {
// A relay tab is a LIVE connection to another machine's project, not a workspace on this
@@ -582,11 +651,28 @@ export function splitWorkspace(
const { unavailable: _u, ...inline } = p
entries.push({ ...header, project: inline })
} else {
+ // The cwd-less canvas: a LOCAL-DATA ref (see IndexEntryV3). The file is the source of truth
+ // and `project` rides along as the cache — the dual-write that lets an older build open this
+ // canvas, and that keeps a half-done migration (file written, index write lost, or the
+ // reverse) readable either way round.
+ //
+ // It is otherwise treated exactly like the other two refs: content in the file, the
+ // machine-local half on the entry (`localState`), exec-enabling node fields hoisted into
+ // `localExec` and STRIPPED from the file by `projectToFile`. That last part costs nothing
+ // today — the file sits in userData, as machine-local as the index it replaces — and it is
+ // what makes the file safe to move into a repo the day "Set folder…" moves it.
const { unavailable: _u, ...inline } = p
- entries.push({ ...header, project: inline })
+ if (!isInlineProjectFileId(p.id)) {
+ // A hand-edited id we will not turn into a path: keep the pre-file shape, where the index
+ // IS the storage for this one entry.
+ entries.push({ ...header, project: inline })
+ continue
+ }
+ dataFiles.set(p.id, projectToFile(p, revOf(p.id), savedAt))
+ entries.push({ ...header, ...localState, ...localRef, dataFile: true, project: inline })
}
}
- return { index: { version: 3, activeProjectId: ws.activeProjectId, entries }, files }
+ return { index: { version: 3, activeProjectId: ws.activeProjectId, entries }, files, dataFiles }
}
/** Pretty, stable-order JSON for the project file (git-diffable; the index stays compact). */
diff --git a/src/core/workspace-store.inline-file.test.ts b/src/core/workspace-store.inline-file.test.ts
new file mode 100644
index 000000000..c434af00b
--- /dev/null
+++ b/src/core/workspace-store.inline-file.test.ts
@@ -0,0 +1,320 @@
+// The cwd-less ("inline") canvas has its own file — `userData/inline-projects/<id>.json`, the twin
+// of a folder project's `<cwd>/.nodeterm/project.json`.
+//
+// It used to have none: the whole Project rode inside `workspace.json`, which is ONE file with
+// last-writer-wins semantics, so a second app instance sharing this userData could erase a canvas
+// that existed nowhere else (measured in #621, which deliberately left the shape alone). These
+// tests pin the file layer, the DOWNGRADE contract that keeps the same index readable by an older
+// build, and the one rule standing in for a merge between two instances: a lower rev may not
+// overwrite a higher one.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { promises as fs } from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { WorkspaceStore } from './workspace-store'
+import type { CanvasNodeState, Project, Workspace } from '../shared/types'
+
+let userData: string
+
+const node = (id: string, over: Partial<CanvasNodeState> = {}): CanvasNodeState => ({
+ id, kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 },
+ title: id, color: '#fff', group: null, ...over
+})
+const project = (over: Partial<Project> = {}): Project => ({
+ id: 'project-p1', name: 'scratch', color: '#7aa2f7', viewport: { x: 4, y: 5, zoom: 2 },
+ nodes: [node('term-1')], ...over
+})
+const ws = (projects: Project[], active = projects[0]?.id ?? ''): Workspace =>
+ ({ version: 2, activeProjectId: active, projects })
+
+const dataFile = (id: string) => path.join(userData, 'inline-projects', `${id}.json`)
+const readIndex = async () =>
+ JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+const readData = async (id: string) => JSON.parse(await fs.readFile(dataFile(id), 'utf-8'))
+const writeIndex = async (index: unknown) =>
+ fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify(index))
+const ids = (nodes: CanvasNodeState[]) => nodes.map((n) => n.id)
+
+beforeEach(async () => {
+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-inline-'))
+ initPlatform(fakePlatform({ userDataDir: userData }))
+})
+afterEach(async () => {
+ resetPlatformForTests()
+ await fs.rm(userData, { recursive: true, force: true })
+})
+
+describe('a cwd-less project gets its own file', () => {
+ it('writes userData/inline-projects/<id>.json and round-trips through a fresh store', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({
+ kanban: { columns: [{ id: 'c1', name: 'To Do' }], assignments: [] }
+ })]))
+
+ const file = await readData('project-p1')
+ expect(file).toMatchObject({ version: 1, rev: 1, name: 'scratch' })
+ expect(ids(file.nodes)).toEqual(['term-1'])
+ expect(file.kanban.columns[0].name).toBe('To Do')
+
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects).toHaveLength(1)
+ expect(loaded.projects[0]).toMatchObject({ id: 'project-p1', name: 'scratch' })
+ expect(ids(loaded.projects[0].nodes)).toEqual(['term-1'])
+ // The machine-local half moved to the entry (#510), but the project the renderer sees is the
+ // same object it always was.
+ expect(loaded.projects[0].viewport).toEqual({ x: 4, y: 5, zoom: 2 })
+ expect(loaded.projects[0].kanban?.columns[0].name).toBe('To Do')
+ })
+
+ it('keeps the machine-local half on the entry and the content in the file', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({
+ defaultAccountId: 'acct-9',
+ nodes: [node('term-1', { shell: '/bin/fish' })]
+ })]))
+
+ const entry = (await readIndex()).entries[0]
+ expect(entry).toMatchObject({
+ dataFile: true, viewport: { x: 4, y: 5, zoom: 2 }, defaultAccountId: 'acct-9'
+ })
+ expect(entry.localExec).toEqual({ 'term-1': { shell: '/bin/fish' } })
+
+ // The file is written exec-free, exactly like a git-shared project.json — which is what makes
+ // it movable into a repo the day "Set folder…" moves it.
+ const file = await readData('project-p1')
+ expect(file.nodes[0].shell).toBeUndefined()
+ expect(JSON.stringify(file)).not.toContain('acct-9')
+
+ // …and the user's own shell still comes back.
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].nodes[0].shell).toBe('/bin/fish')
+ expect(loaded.projects[0].defaultAccountId).toBe('acct-9')
+ })
+
+ it('does not churn the file when nothing changed, and bumps rev when it did', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project()]))
+ await store.save(ws([project()]))
+ expect((await readData('project-p1')).rev).toBe(1)
+
+ await store.save(ws([project({ nodes: [node('term-1'), node('term-2')] })]))
+ expect((await readData('project-p1')).rev).toBe(2)
+ })
+
+ it('deletes the data file of a project this store had and the user removed', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project(), project({ id: 'project-p2', name: 'other' })]))
+ await store.save(ws([project()]))
+ await expect(fs.access(dataFile('project-p2'))).rejects.toThrow()
+ await expect(fs.access(dataFile('project-p1'))).resolves.toBeUndefined()
+ })
+
+ it('refuses to name a file from a hand-edited id and keeps that entry in the pre-file shape', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ id: '../../evil' })]))
+ const entry = (await readIndex()).entries[0]
+ expect(entry.dataFile).toBeUndefined()
+ expect(entry.project.nodes).toHaveLength(1)
+ expect(await fs.readdir(userData)).not.toContain('evil.json')
+ const loaded = await new WorkspaceStore().load()
+ expect(ids(loaded.projects[0].nodes)).toEqual(['term-1'])
+ })
+
+ it('leaves a folder project and an ssh entry exactly as they were', async () => {
+ const cwd = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-folder-'))
+ try {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ id: 'project-folder', cwd })]))
+ const entry = (await readIndex()).entries[0]
+ expect(entry.cwd).toBe(cwd)
+ expect(entry.dataFile).toBeUndefined()
+ expect(entry.project).toBeUndefined()
+ await expect(fs.access(path.join(cwd, '.nodeterm', 'project.json'))).resolves.toBeUndefined()
+ await expect(fs.access(path.join(userData, 'inline-projects'))).rejects.toThrow()
+ } finally {
+ await fs.rm(cwd, { recursive: true, force: true })
+ }
+ })
+})
+
+describe('the downgrade contract (dual-write, one release)', () => {
+ it('keeps the whole canvas in the index entry, so a build that ignores `dataFile` still reads it', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ nodes: [node('term-1'), node('term-2')] })]))
+
+ // MEASURED: this is exactly what an older loadV3 sees — it knows only `project`.
+ const entry = (await readIndex()).entries[0]
+ expect(ids(entry.project.nodes)).toEqual(['term-1', 'term-2'])
+ expect(entry.project.viewport).toEqual({ x: 4, y: 5, zoom: 2 })
+
+ // And this build falls back to the same cache when the file is gone.
+ await fs.rm(dataFile('project-p1'))
+ const loaded = await new WorkspaceStore().load()
+ expect(ids(loaded.projects[0].nodes)).toEqual(['term-1', 'term-2'])
+ })
+
+ it('never drops an entry carrying fields this build does not know', async () => {
+ // The forward half of the same measurement: a NEWER build's entry read by this one. An entry
+ // with an unknown ref kind and no content this build recognises must still render — as the
+ // labeled grey placeholder every unreadable ref becomes — because the save that follows a
+ // silent drop would write it out of the index for good.
+ await writeIndex({
+ version: 3,
+ activeProjectId: 'project-p1',
+ entries: [
+ {
+ id: 'project-p1', name: 'known', color: '#fff',
+ dataFile: true, project: project(), futureThing: 7
+ },
+ { id: 'project-p2', name: 'from the future', color: '#0f0', blobRef: 'blobs/p2.json' }
+ ]
+ })
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects.map((p) => p.id)).toEqual(['project-p1', 'project-p2'])
+ expect(ids(loaded.projects[0].nodes)).toEqual(['term-1'])
+ expect(loaded.projects[1]).toMatchObject({ name: 'from the future', unavailable: true })
+ })
+
+ it('a placeholder save keeps the ref shape instead of storing the empty canvas', async () => {
+ // The data file was unreadable at load (a half-written disk, a permission problem): the entry
+ // loads as a placeholder, and the save that follows must not make `nodes: []` the stored truth.
+ await writeIndex({
+ version: 3,
+ activeProjectId: 'project-p1',
+ entries: [{ id: 'project-p1', name: 'scratch', color: '#fff', dataFile: true }]
+ })
+ const store = new WorkspaceStore()
+ const loaded = await store.load()
+ expect(loaded.projects[0]).toMatchObject({ unavailable: true })
+ await store.save(loaded)
+ const entry = (await readIndex()).entries[0]
+ expect(entry.dataFile).toBe(true)
+ expect(entry.project).toBeUndefined()
+ })
+})
+
+describe('migration from the pre-file shape', () => {
+ const legacyIndex = {
+ version: 3,
+ activeProjectId: 'project-p1',
+ entries: [{
+ id: 'project-p1', name: 'scratch', color: '#7aa2f7',
+ project: { ...project(), nodes: [node('term-1', { shell: '/bin/zsh' })] }
+ }]
+ }
+
+ it('migrates on the first save, loses nothing, and is idempotent', async () => {
+ await writeIndex(legacyIndex)
+ const store = new WorkspaceStore()
+ const loaded = await store.load()
+ expect(loaded.projects[0].nodes[0].shell).toBe('/bin/zsh')
+ await store.save(loaded)
+
+ expect((await readData('project-p1')).rev).toBe(1)
+ expect((await readIndex()).entries[0].dataFile).toBe(true)
+
+ const again = await new WorkspaceStore().load()
+ expect(again.projects[0]).toMatchObject({ name: 'scratch', viewport: { x: 4, y: 5, zoom: 2 } })
+ expect(again.projects[0].nodes[0].shell).toBe('/bin/zsh')
+
+ await new WorkspaceStore().save(again)
+ expect((await readData('project-p1')).rev).toBe(1) // unchanged content, no rewrite
+ })
+
+ it('stays consistent when only half of it landed (file written, index write lost)', async () => {
+ // The crash window. The index is the only thing that says which KIND an entry is, so a
+ // pre-file entry still reads its cache; nothing is corrupt, and the next save reconciles the
+ // two copies — both of which were ours.
+ await fs.mkdir(path.join(userData, 'inline-projects'), { recursive: true })
+ await fs.writeFile(dataFile('project-p1'), JSON.stringify({
+ version: 1, rev: 5, savedAt: 'x', name: 'scratch', color: '#7aa2f7',
+ viewport: { x: 0, y: 0, zoom: 1 }, nodes: [node('term-9')]
+ }))
+ await writeIndex(legacyIndex)
+
+ const store = new WorkspaceStore()
+ const first = await store.load()
+ expect(ids(first.projects[0].nodes)).toEqual(['term-1'])
+ await store.save(first)
+
+ // The file's rev is ahead of ours, so it is not overwritten and the next load adopts it.
+ const after = await new WorkspaceStore().load()
+ expect(ids(after.projects[0].nodes)).toEqual(['term-9'])
+ expect((await readData('project-p1')).rev).toBe(5)
+ })
+
+ it('sidelines a corrupt data file and answers from the index cache', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project()]))
+ await fs.writeFile(dataFile('project-p1'), '{ not json')
+
+ const loaded = await new WorkspaceStore().load()
+ expect(ids(loaded.projects[0].nodes)).toEqual(['term-1'])
+ const sidelined = (await fs.readdir(path.join(userData, 'inline-projects')))
+ .filter((f) => f.includes('.corrupt-'))
+ expect(sidelined).toHaveLength(1)
+ })
+})
+
+describe('two app instances sharing one userData', () => {
+ it('the file is the source of truth: a stale index cache never beats it', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project()]))
+ // The other instance advanced the file; our index copy is now stale.
+ const file = await readData('project-p1')
+ await fs.writeFile(dataFile('project-p1'),
+ JSON.stringify({ ...file, rev: 9, nodes: [node('term-other')] }))
+
+ const loaded = await new WorkspaceStore().load()
+ expect(ids(loaded.projects[0].nodes)).toEqual(['term-other'])
+ })
+
+ it('a lower rev may not overwrite a higher one', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project()]))
+ const file = await readData('project-p1')
+ await fs.writeFile(dataFile('project-p1'),
+ JSON.stringify({ ...file, rev: 9, nodes: [node('term-other')] }))
+
+ await store.save(ws([project({ nodes: [node('term-1'), node('term-2')] })]))
+ const after = await readData('project-p1')
+ expect(after.rev).toBe(9)
+ expect(ids(after.nodes)).toEqual(['term-other'])
+ })
+
+ it("an index write that forgets another instance's project no longer destroys its canvas", async () => {
+ // THE bug this layer exists for. B loaded an index that did not have A's project yet, so B's
+ // next index write drops A's entry (one shared index, last-writer-wins — unchanged). What
+ // changed is that A's canvas is still on disk, so it is recoverable rather than gone.
+ const b = new WorkspaceStore()
+ await b.load()
+ const a = new WorkspaceStore()
+ await a.load()
+ await a.save(ws([project({ id: 'project-a', name: 'A canvas' })]))
+
+ await b.save(ws([project({ id: 'project-b', name: 'B canvas' })]))
+ expect((await readIndex()).entries.map((e: { id: string }) => e.id)).toEqual(['project-b'])
+ expect((await readData('project-a')).nodes).toHaveLength(1)
+ })
+
+ it('an empty canvas never overwrites a populated file the store has not read', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project()]))
+
+ // A store that never loaded — the hydrate race / boot-save shape — saving zero nodes for a
+ // project whose file is populated. Its rev is 0, so the rev rule alone would let this through
+ // if the file's rev were 0 too; the emptiness rule is what refuses it.
+ const neverLoaded = new WorkspaceStore()
+ await neverLoaded.save(ws([project({ nodes: [] })], 'project-p1'))
+ expect((await readData('project-p1')).nodes).toHaveLength(1)
+
+ // A store that HAS read the file may of course empty the canvas — that is the user deleting
+ // their nodes, not a race.
+ const loaded = new WorkspaceStore()
+ await loaded.load()
+ await loaded.save(ws([project({ nodes: [] })], 'project-p1'))
+ expect((await readData('project-p1')).nodes).toHaveLength(0)
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 04c8d94e9..4cf3c2ad1 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -9,7 +9,8 @@ import {
type BridgeLink, type CanvasNodeState, type Project, type Workspace, type WorkspaceV1
} from '../shared/types'
import {
- PROJECT_DIR, PROJECT_FILE, fileToProject, projectToFile, resolveNodes, sameProjectContent,
+ PROJECT_DIR, PROJECT_FILE, fileToProject, inlineProjectFileRelPath, isInlineProjectFileId,
+ projectToFile, resolveNodes, sameProjectContent,
sanitizeLoadedClosedSessions, sanitizeNodeTriggers, serializeProjectFile, splitWorkspace,
validKanban,
type IndexEntryV3, type ProjectFileV1, type WorkspaceIndexV3
@@ -44,6 +45,12 @@ export interface RemoteWorkspaceIO {
const projectFilePath = (cwd: string): string => path.join(cwd, PROJECT_DIR, PROJECT_FILE)
+/** The data file of one cwd-less ("inline") project: `userData/inline-projects/<id>.json`. Only
+ * ever called with an id `isInlineProjectFileId` has already accepted — workspace.json is
+ * hand-editable, so an id read back out of it is input and may not reach a path unchecked. */
+const inlineFilePath = (projectId: string): string =>
+ path.join(platform().userDataDir, inlineProjectFileRelPath(projectId))
+
/** How many recent mirror payloads a project remembers for self-write recognition (see
* `recentMirrorHashes`). Big enough to cover a burst of throttled writes inside one poll window;
* small enough that a server-side revert to genuinely old content still reads as external. */
@@ -287,7 +294,14 @@ export class WorkspaceStore {
this.index = index
const built: LoadedEntry[] = []
for (const e of index.entries) {
- if (e.project) {
+ // A LOCAL-DATA ref reads its own file first; `e.project` below is its cache and answers only
+ // when the file is missing or unreadable (and for a pre-file entry, which has no file yet).
+ const fromDataFile = e.dataFile && !e.cwd && !e.ssh
+ ? await this.loadDataFileEntry(e, sideline)
+ : null
+ if (fromDataFile) {
+ built.push(fromDataFile)
+ } else if (e.project) {
// Inline projects are stored verbatim in the index (no fileToProject pass), so apply the
// same kanban shape guard here — a v1/hand-edited board would otherwise crash the render —
// and the same trigger shape rule (workspace.json is hand-editable input too).
@@ -359,6 +373,14 @@ export class WorkspaceStore {
this.deferExecMigration(e)
built.push({ entry: e, project: unavailableProject(e) })
}
+ } else {
+ // Nothing this build recognises as content: a data-ref whose file is gone AND whose cache
+ // has already been dropped, or an entry written by a NEWER build carrying a ref kind this
+ // one has never heard of. It becomes the same labeled grey placeholder an unreadable
+ // folder does, because the one thing an entry may never do is silently vanish — the save
+ // that follows a silent drop writes it out of the index, and whatever it named is then
+ // unreachable for good.
+ built.push({ entry: e, project: unavailableProject(e) })
}
}
await this.repairDuplicateIds(built, sideline)
@@ -799,6 +821,66 @@ export class WorkspaceStore {
return null
}
+ /**
+ * The LOCAL-DATA ref's load leg: read `userData/inline-projects/<id>.json` and build the project
+ * from it, or answer null so the caller falls back to the index's `project` cache.
+ *
+ * Identical in shape to the folder-ref leg above — the file carries content, the ENTRY carries
+ * this machine's camera / default account / breadcrumbs / trash can / consent / exec overlay —
+ * which is the whole point of giving the cwd-less canvas a file: one ref shape everywhere, and a
+ * file already in the form that "Set folder…" will move into `<cwd>/.nodeterm/project.json`.
+ *
+ * The in-memory entry's `project` cache is refreshed from what the file said, because a dozen
+ * sync readers (`getNode`, `persistedCanvases`, `capabilityProjectFor`, …) answer out of the
+ * loaded index and must not keep serving a copy the file has already superseded.
+ */
+ private async loadDataFileEntry(e: IndexEntryV3, sideline: boolean): Promise<LoadedEntry | null> {
+ if (!isInlineProjectFileId(e.id)) return null
+ const file = inlineFilePath(e.id)
+ if (sideline) await sweepStaleTmp(file)
+ const read = await this.readDataFile(e.id, sideline)
+ if (!read) return null
+ this.revs.set(e.id, read.file.rev)
+ this.lastWritten.set(file, read.raw)
+ const project = fileToProject(read.file, {
+ id: e.id,
+ closed: e.closed,
+ closedAt: e.closedAt,
+ viewport: e.viewport,
+ defaultAccountId: e.defaultAccountId,
+ breadcrumbs: e.breadcrumbs,
+ closedSessions: e.closedSessions,
+ capabilityAck: e.capabilityAck,
+ localExec: this.execOverlay(e, read.file)
+ })
+ e.project = project
+ return { entry: e, project, file: read.file }
+ }
+
+ /** Reads + parses one inline data file. Same rules as `readProjectFile`: a file that is not a
+ * ProjectFileV1 is sidelined to `.corrupt-<ts>` on the authoritative load path so a later save
+ * cannot overwrite the only copy — here the index's `project` cache is the other copy, which is
+ * what makes sidelining cost the user nothing. */
+ private async readDataFile(projectId: string, sideline: boolean): Promise<ProjectFileRead | null> {
+ const file = inlineFilePath(projectId)
+ let raw: string
+ try {
+ raw = await fs.readFile(file, 'utf-8')
+ } catch {
+ return null
+ }
+ try {
+ const parsed = JSON.parse(raw) as ProjectFileV1
+ if (parsed?.version === 1 && Array.isArray(parsed.nodes)) return { file: parsed, raw }
+ } catch { /* not JSON — sideline below */ }
+ if (sideline) {
+ try {
+ await renameAtomic(file, `${file}.corrupt-${Date.now()}`)
+ } catch { /* best effort — never destroy data */ }
+ }
+ return null
+ }
+
/** 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. */
@@ -841,7 +923,8 @@ export class WorkspaceStore {
} 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)
+ const previousIndex = this.index
+ const { index, files, dataFiles } = splitWorkspace(workspace, (id) => this.revs.get(id) ?? 0, savedAt)
for (const entry of index.entries) {
const previous = this.index?.entries.find((candidate) => candidate.id === entry.id)
@@ -860,7 +943,10 @@ export class WorkspaceStore {
// is what keeps a project.json cloned AFTER the upgrade (the hostile case) out of the hoist. An
// entry whose file we could not read at load stays unmarked, so it is retried.
for (const e of index.entries) {
- if (e.project) continue // inline canvases live in this machine-local file already
+ // A pre-file inline canvas keeps its exec values inside its own `project` copy, so it has no
+ // overlay to migrate. A LOCAL-DATA ref does: its file is written exec-free and the values
+ // ride `localExec`, exactly like a folder ref.
+ if (e.project && !e.dataFile) continue
if (!this.execUnmigrated.has(e.id)) e.execMigrated = true
}
@@ -887,6 +973,16 @@ export class WorkspaceStore {
// The clone-notice acknowledgment must also survive an unavailable window: forgetting it
// would re-raise a notice the user already answered the moment the folder remounts.
if (old?.capabilityAck) e.capabilityAck = old.capabilityAck
+ // A data-ref placeholder (its file was unreadable at load) must stay a data-ref. Without
+ // this the entry comes back as a PRE-FILE inline entry holding the placeholder's
+ // `nodes: []` — the empty canvas becomes the stored truth and the file it named is
+ // orphaned. Restore the previous cache, or drop the field entirely so the entry stays a
+ // pure ref and renders as the grey tab it is.
+ if (old?.dataFile) {
+ e.dataFile = true
+ if (old.project) e.project = old.project
+ else delete e.project
+ }
}
}
@@ -920,6 +1016,13 @@ export class WorkspaceStore {
} catch { /* folder gone (unmounted disk): the entry simply stays stale → unavailable next load */ }
}
+ // Inline (cwd-less) canvases: their own file under userData, written before the index and with
+ // the same rules the folder leg lives by — skip an unchanged candidate, never let an empty
+ // candidate overwrite a populated file this store has not read — plus the one rule only this
+ // leg needs (see `writeDataFile`): a second app instance shares this userData, so a file whose
+ // rev has moved ahead of ours belongs to that instance and is not overwritten.
+ for (const [projectId, candidate] of dataFiles) await this.writeDataFile(projectId, candidate)
+
// ssh caches: bump rev on change so a later remote write can win; mirror write in Task 8.
for (const e of index.entries) {
if (!e.ssh || !e.cache) continue
@@ -967,6 +1070,7 @@ export class WorkspaceStore {
// Compact index, atomic — same reasoning as the old single-file store.
await writeAtomic(this.indexPath, JSON.stringify(index))
+ await this.sweepRemovedDataFiles(previousIndex, index)
this.index = index
if (migrating) platform().broadcast(IPC.workspaceMigrated, 'v2')
@@ -978,6 +1082,79 @@ export class WorkspaceStore {
this.onPersist?.()
}
+ /**
+ * Writes one cwd-less canvas to `userData/inline-projects/<id>.json`.
+ *
+ * Three refusals, in order, and each one leaves the disk MORE authoritative than this store:
+ *
+ * 1. unchanged since we last wrote or read it → no write at all (the common save), so an idle
+ * canvas costs neither a read nor a write;
+ * 2. the file on disk carries a rev ABOVE ours → a second app instance sharing this userData
+ * wrote it after we last looked, and a lower rev may not overwrite a higher one. The two
+ * canvases are NOT merged (see the limits in CLAUDE.md): that instance's canvas stands and
+ * the next load here adopts it. What the rule buys is that two instances can no longer
+ * ERASE each other, which is exactly what the single shared index allowed;
+ * 3. an empty candidate over a populated file this store has never read → the local twin of the
+ * folder leg's rule, for a renderer that hydrated zero nodes for some transient reason.
+ *
+ * A failed write is not fatal and is deliberately not retried here: the index still carries this
+ * canvas in `project` (the dual-write), so the content is readable either way round — which is
+ * also what makes a half-done migration consistent in both directions.
+ */
+ private async writeDataFile(projectId: string, candidate: ProjectFileV1): Promise<void> {
+ if (!isInlineProjectFileId(projectId)) return
+ const file = inlineFilePath(projectId)
+ const prev = this.lastWritten.get(file)
+ let prevParsed: ProjectFileV1 | null = null
+ if (prev) {
+ try {
+ prevParsed = JSON.parse(prev) as ProjectFileV1
+ } catch { /* our own cache, but never trusted blindly */ }
+ }
+ if (prevParsed && sameProjectContent(prevParsed, candidate)) return
+ const ourRev = this.revs.get(projectId) ?? 0
+ // Read the file only when we are actually about to write it.
+ const onDisk = await this.readDataFile(projectId, false)
+ if (onDisk && onDisk.file.rev > ourRev) {
+ // Adopt the other writer's bytes as what we know is on disk, so the next save compares
+ // against reality instead of re-deciding this every time.
+ this.lastWritten.set(file, onDisk.raw)
+ this.revs.set(projectId, onDisk.file.rev)
+ return
+ }
+ if (!prevParsed && candidate.nodes.length === 0 && (onDisk?.file.nodes.length ?? 0) > 0) return
+ const next: ProjectFileV1 = { ...candidate, rev: ourRev + 1 }
+ const content = serializeProjectFile(next)
+ try {
+ await fs.mkdir(path.dirname(file), { recursive: true })
+ await writeAtomic(file, content)
+ this.lastWritten.set(file, content)
+ this.revs.set(projectId, next.rev)
+ } catch { /* the index's `project` copy still holds this canvas; the next save retries */ }
+ }
+
+ /**
+ * Deletes the data file of a project THIS store had and no longer has — i.e. one the user
+ * removed. Nothing else: a file whose id was never in our own loaded index is left alone,
+ * because that is precisely a second instance's project, and the whole point of this layer is
+ * that one instance's index write can no longer destroy another's canvas. The cost of the
+ * asymmetry is a few KB of litter after a re-key or a crash, which is the right side to err on.
+ */
+ private async sweepRemovedDataFiles(
+ previous: WorkspaceIndexV3 | null,
+ next: WorkspaceIndexV3
+ ): Promise<void> {
+ if (!previous) return
+ const live = new Set(next.entries.map((e) => e.id))
+ for (const e of previous.entries) {
+ if (!e.dataFile || live.has(e.id) || !isInlineProjectFileId(e.id)) continue
+ const file = inlineFilePath(e.id)
+ await fs.rm(file, { force: true }).catch(() => undefined)
+ this.lastWritten.delete(file)
+ this.revs.delete(e.id)
+ }
+ }
+
/**
* The ADOPTION path: a folder with no index entry (Open folder…, a fresh clone). It is the one
* place that must MINT an id — the file used to supply one, which is exactly how a worktree's
diff --git a/src/core/workspace-watcher.ts b/src/core/workspace-watcher.ts
index f70a08c68..62d9e401f 100644
--- a/src/core/workspace-watcher.ts
+++ b/src/core/workspace-watcher.ts
@@ -19,6 +19,11 @@ const REARM_MAX_TRIES = 25
* a teammate's commit). Self-writes are recognized by exact content match against
* the store's last-written cache and ignored. Events are debounced per file —
* editors and git often touch a file several times in quick succession.
+ *
+ * A cwd-less canvas's data file (`userData/inline-projects/<id>.json`) is deliberately NOT watched:
+ * nothing external edits it — no git pull, no teammate, no sync client aimed at userData — and the
+ * only other writer is a second app instance, which is settled by the rev rule in
+ * `WorkspaceStore.writeDataFile` rather than by a live reload. See the ref-kinds table in CLAUDE.md.
*/
export class WorkspaceWatcher {
private watchers = new Map<string, FSWatcher>()