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(core): workspace store seams for a content authority

review2cc3f2ed7b6d
diff --git a/src/core/workspace-store.content-authority.test.ts b/src/core/workspace-store.content-authority.test.ts
new file mode 100644
index 000000000..fd5c47f62
--- /dev/null
+++ b/src/core/workspace-store.content-authority.test.ts
@@ -0,0 +1,481 @@
+// The store seams the Server Edition canvas authority governs shared projects through: an overlay on
+// every whole-workspace save and load, a content read that never queues on `saveChain` (the
+// authority calls it from INSIDE a save), and an atomic content write that does a save's
+// bookkeeping (self-write record, rev, the inline cache + index, onPersist) without broadcasting.
+//
+// The load-bearing claim of the write is pinned by comparison, not by listing steps: a file written
+// by `writeProjectContent` is byte-identical to the file `save()` writes for the same project,
+// apart from `rev` and `savedAt`.
+import { describe, it, expect, beforeEach, afterEach, vi } 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, type ContentAuthorityHooks, type RemoteWorkspaceIO } from './workspace-store'
+import { contentOf, type CanvasContent } from '../shared/canvas-content'
+import type { CanvasNodeState, Project, ProjectKanban, Workspace } from '../shared/types'
+
+let userData: string
+let projRoot: string
+let fake: ReturnType<typeof fakePlatform>
+
+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: 'P', name: 'foo', color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [node('a')], ...over
+})
+const ws = (projects: Project[]): Workspace =>
+ ({ version: 2, activeProjectId: projects[0]?.id ?? '', projects })
+const content = (nodes: CanvasNodeState[], over: Partial<CanvasContent> = {}): CanvasContent =>
+ ({ nodes, bridges: [], ropes: [], ...over })
+const ids = (nodes: Array<{ id: string }>): string[] => nodes.map((n) => n.id)
+
+const SSH = { server: { host: 'h', user: 'u' }, remoteCwd: '~/x' } as unknown as Project['ssh']
+const INLINE_ID = 'project-p1'
+
+const projectFile = (root = projRoot): string => path.join(root, '.nodeterm/project.json')
+const dataFile = (id = INLINE_ID): string => path.join(userData, 'inline-projects', `${id}.json`)
+const readJson = async (file: string): Promise<Record<string, any>> =>
+ JSON.parse(await fs.readFile(file, 'utf-8'))
+const readIndex = (): Promise<Record<string, any>> => readJson(path.join(userData, 'workspace.json'))
+const externalChanges = (): unknown[] =>
+ fake.sent.filter((s) => s.channel === 'workspace:external-change')
+/** The file minus the two fields a write is allowed to differ in, re-serialized in its own key
+ * order — so a comparison also catches a reordered key. */
+const withoutBookkeeping = (raw: string): string => {
+ const { rev: _r, savedAt: _s, ...rest } = JSON.parse(raw)
+ return JSON.stringify(rest, null, 2)
+}
+
+/** Rejects if `p` has not settled within `ms` — the observable shape of a deadlock. */
+async function settlesWithin<T>(p: Promise<T>, ms: number): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const timeout = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`did not settle within ${ms} ms (deadlock)`)), ms)
+ })
+ try {
+ return await Promise.race([p, timeout])
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+const passThrough: ContentAuthorityHooks = {
+ overlaySave: async (w) => w,
+ overlayLoad: async (w) => w
+}
+
+/** An ssh IO whose "server" is one in-memory string, so a mirror write is observable. */
+function fakeRemote(): RemoteWorkspaceIO & { content: string | null; writes: number } {
+ const io = {
+ content: null as string | null,
+ writes: 0,
+ async read() {
+ return io.content === null
+ ? ({ status: 'absent' } as const)
+ : ({ status: 'ok', content: io.content } as const)
+ },
+ async write(_id: string, _ssh: never, c: string) {
+ io.content = c
+ io.writes++
+ return true
+ }
+ }
+ return io as never
+}
+
+/** A folder project written by hand at rev 3, with every non-content field a save must keep. */
+async function seedFolderAtRev3(): Promise<WorkspaceStore> {
+ await fs.mkdir(path.dirname(projectFile()), { recursive: true })
+ await fs.writeFile(projectFile(), JSON.stringify({
+ version: 1,
+ rev: 3,
+ savedAt: '2026-09-29T00:00:00.000Z',
+ name: 'X',
+ color: '#abcdef',
+ viewport: { x: 5, y: 5, zoom: 3 },
+ nodes: [node('a', { cwd: './sub' })],
+ defaultPermissionMode: 'plan',
+ agentMessaging: true,
+ dinoHighScore: 42,
+ kanban: {
+ columns: [{ id: 'c1', title: 'To Do', color: '#888' }],
+ assignments: [{ nodeId: 'a', columnId: 'c1' }],
+ github: { repository: 'a/b', columnMappings: [{ columnId: 'c1', label: 'todo' }] },
+ pullLinks: { noAutoMove: ['a'] }
+ }
+ }, null, 2))
+ await fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify({
+ version: 3,
+ activeProjectId: 'P',
+ entries: [{ id: 'P', name: 'X', color: '#abcdef', cwd: projRoot, execMigrated: true }]
+ }))
+ const store = new WorkspaceStore()
+ await store.load()
+ return store
+}
+
+/** A project exercising every transform the save path applies to content on the way out. */
+const richProject = (cwd: string | undefined, id = 'P'): Project => project({
+ id,
+ cwd,
+ name: 'rich',
+ color: '#123456',
+ defaultPermissionMode: 'plan',
+ agentMessaging: true,
+ dinoHighScore: 7,
+ nodes: [
+ // under the root → a portable `./sub` cwd; `shell` is machine-local and must never be written
+ node('a', { cwd: cwd ? path.join(cwd, 'sub') : undefined, shell: '/bin/zsh', position: { x: 40, y: 90 } }),
+ // outside the root → the absolute path stays
+ node('b', { cwd: '/elsewhere/abs', position: { x: -40, y: 12 } }),
+ // a malformed trigger spec is dropped on the way out
+ node('t', { kind: 'trigger', trigger: { bogus: true } as never })
+ ],
+ bridges: [{ id: 'br1', source: 'a', target: 'b' }],
+ ropes: [{ id: 'ctrl-a-b', source: 'a', target: 'b' }],
+ kanban: {
+ columns: [{ id: 'c1', title: 'To Do', color: '#888' }, { id: 'c2', title: 'Done', color: '#8b8' }],
+ assignments: [{ nodeId: 'a', columnId: 'c2' }],
+ github: { repository: 'a/b', columnMappings: [{ columnId: 'c1', label: 'todo' }] },
+ pullLinks: { unlinked: [{ nodeId: 'a', pull: 12 }] }
+ } as ProjectKanban
+})
+
+beforeEach(async () => {
+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-ws-'))
+ projRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-proj-'))
+ fake = fakePlatform({ userDataDir: userData })
+ initPlatform(fake)
+})
+afterEach(async () => {
+ resetPlatformForTests()
+ await fs.rm(userData, { recursive: true, force: true })
+ await fs.rm(projRoot, { recursive: true, force: true })
+})
+
+describe('the save overlay', () => {
+ it('replaces a governed project’s content before it is written', async () => {
+ const store = new WorkspaceStore()
+ store.setContentAuthority({
+ overlaySave: async (w) => ({
+ ...w,
+ projects: w.projects.map((p) => (p.id === 'P' ? { ...p, nodes: [node('b')] } : p))
+ }),
+ overlayLoad: async (w) => w
+ })
+ await store.save(ws([project({ cwd: projRoot, nodes: [node('a')] })]))
+ expect(ids((await readJson(projectFile())).nodes)).toEqual(['b'])
+
+ // Detached, a save writes exactly what it was handed again.
+ store.setContentAuthority(null)
+ await store.save(ws([project({ cwd: projRoot, nodes: [node('a')] })]))
+ expect(ids((await readJson(projectFile())).nodes)).toEqual(['a'])
+ })
+})
+
+describe('the load overlay', () => {
+ it('rewrites the load result only; the file is untouched', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot, nodes: [node('a')] })]))
+ const before = await fs.readFile(projectFile(), 'utf-8')
+
+ store.setContentAuthority({
+ overlaySave: async (w) => w,
+ overlayLoad: async (w) => ({ ...w, projects: w.projects.map((p) => ({ ...p, nodes: [node('b')] })) })
+ })
+ const loaded = await store.load()
+ expect(ids(loaded.projects[0].nodes)).toEqual(['b'])
+ expect(await fs.readFile(projectFile(), 'utf-8')).toBe(before)
+ expect(ids((await new WorkspaceStore().load()).projects[0].nodes)).toEqual(['a'])
+ })
+
+ it('a failing overlay still answers the load (a thrown one leaves the index unguarded against the next save)', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot, nodes: [node('a')] })]))
+ store.setContentAuthority({
+ overlaySave: async (w) => w,
+ overlayLoad: async () => { throw new Error('authority unavailable') }
+ })
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const loaded = await store.load()
+ expect(loaded.projects.map((p) => p.id)).toEqual(['P'])
+ expect(ids(loaded.projects[0].nodes)).toEqual(['a'])
+ expect(warn).toHaveBeenCalledTimes(1)
+ warn.mockRestore()
+ })
+})
+
+describe('readProjectContent', () => {
+ it('does not deadlock inside a save (it never queues on saveChain)', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot, nodes: [node('a')] })]))
+ let seen: CanvasContent | null | undefined
+ store.setContentAuthority({
+ overlaySave: async (w) => {
+ seen = await store.readProjectContent('P')
+ return w
+ },
+ overlayLoad: async (w) => w
+ })
+ await expect(
+ settlesWithin(store.save(ws([project({ cwd: projRoot, nodes: [node('a'), node('c')] })])), 2000)
+ ).resolves.toBeUndefined()
+ // What the store knew when the save began: the file before this save.
+ expect(ids(seen!.nodes)).toEqual(['a'])
+ expect(ids((await readJson(projectFile())).nodes)).toEqual(['a', 'c'])
+ })
+
+ it('answers a folder project with resolved cwds and this machine’s exec values re-applied', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({
+ cwd: projRoot,
+ nodes: [node('a', { cwd: path.join(projRoot, 'sub'), shell: '/bin/zsh' })],
+ ropes: [{ id: 'r1', source: 'a', target: 'a' }]
+ })]))
+ expect((await readJson(projectFile())).nodes[0].shell).toBeUndefined()
+
+ const c = await store.readProjectContent('P')
+ expect(c?.nodes[0]).toMatchObject({ id: 'a', cwd: path.join(projRoot, 'sub'), shell: '/bin/zsh' })
+ expect(c?.bridges).toEqual([])
+ expect(c?.ropes).toEqual([{ id: 'r1', source: 'a', target: 'a' }])
+ expect(c?.kanban).toBeUndefined()
+ })
+
+ it('answers what the store last wrote, not an unprocessed outside edit', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot, nodes: [node('a')] })]))
+ const outside = { ...(await readJson(projectFile())), nodes: [node('zz')] }
+ await fs.writeFile(projectFile(), JSON.stringify(outside, null, 2))
+ expect(ids((await store.readProjectContent('P'))!.nodes)).toEqual(['a'])
+ })
+
+ it('answers a cwd-less canvas from its cache', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ id: INLINE_ID, nodes: [node('a'), node('b')] })]))
+ expect(ids((await store.readProjectContent(INLINE_ID))!.nodes)).toEqual(['a', 'b'])
+ })
+
+ it('answers null for an unknown id, an SSH project and an unreadable folder', async () => {
+ const store = new WorkspaceStore(fakeRemote())
+ await store.save(ws([project({ id: 's1', ssh: SSH, cwd: undefined })]))
+ expect(await store.readProjectContent('s1')).toBeNull()
+ expect(await store.readProjectContent('nope')).toBeNull()
+
+ // A folder whose project file could not be read at load (and was never written by us).
+ await fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify({
+ version: 3, activeProjectId: 'P',
+ entries: [{ id: 'P', name: 'gone', color: '#fff', cwd: path.join(projRoot, 'missing') }]
+ }))
+ const cold = new WorkspaceStore()
+ await cold.load()
+ expect(await cold.readProjectContent('P')).toBeNull()
+ })
+})
+
+describe('writeProjectContent — folder project', () => {
+ it('keeps non-content fields and kanban.github/pullLinks, bumps rev, is a self-write', async () => {
+ const store = await seedFolderAtRev3()
+ const ok = await store.writeProjectContent('P', content(
+ [node('b', { cwd: path.join(projRoot, 'sub') })],
+ // The content's own GitHub config is NOT what lands: those two fields are the file's.
+ { kanban: { columns: [], assignments: [], github: { repository: 'evil/x', columnMappings: [] } } as ProjectKanban }
+ ))
+ expect(ok).toBe(true)
+
+ const raw = await fs.readFile(projectFile(), 'utf-8')
+ const f = JSON.parse(raw)
+ expect(f).toMatchObject({
+ name: 'X', color: '#abcdef', defaultPermissionMode: 'plan', agentMessaging: true, dinoHighScore: 42
+ })
+ expect(f.rev).toBe(4)
+ expect(ids(f.nodes)).toEqual(['b'])
+ expect(f.nodes[0].cwd).toBe('./sub')
+ // The file's viewport is DERIVED from its nodes (`framingViewport`), so it moves with them.
+ expect(f.viewport).toEqual({ x: 80, y: 80, zoom: 1 })
+ expect(f.kanban.columns).toEqual([])
+ expect(f.kanban.assignments).toEqual([])
+ expect(f.kanban.github).toEqual({ repository: 'a/b', columnMappings: [{ columnId: 'c1', label: 'todo' }] })
+ expect(f.kanban.pullLinks).toEqual({ noAutoMove: ['a'] })
+ // An empty list never ADDS a key the file did not have (a no-op flush must not diff the repo).
+ expect('bridges' in f).toBe(false)
+ expect('ropes' in f).toBe(false)
+ expect(store.isSelfWrite(projectFile(), raw)).toBe(true)
+ // Every client already has the change from the reflector: nothing is broadcast.
+ expect(externalChanges()).toHaveLength(0)
+ // The store's own record moved with it.
+ expect(ids((await store.readProjectContent('P'))!.nodes)).toEqual(['b'])
+ })
+
+ it('is byte-identical to a normal save of the same content, apart from rev and savedAt', async () => {
+ const rich = richProject(projRoot)
+ const store = new WorkspaceStore()
+ await store.save(ws([rich]))
+ const viaSave = await fs.readFile(projectFile(), 'utf-8')
+
+ // Move the file off that content first, so the comparison is against a REAL write.
+ expect(await store.writeProjectContent('P', content([node('z')]))).toBe(true)
+ expect(ids((await readJson(projectFile())).nodes)).toEqual(['z'])
+ expect(await store.writeProjectContent('P', contentOf(rich))).toBe(true)
+ const viaWrite = await fs.readFile(projectFile(), 'utf-8')
+
+ expect(JSON.parse(viaWrite).rev).toBe(3)
+ expect(withoutBookkeeping(viaWrite)).toBe(withoutBookkeeping(viaSave))
+ })
+
+ it('stays byte-identical for a project with no edge lists and no board', async () => {
+ const plain = project({ cwd: projRoot, nodes: [node('a', { cwd: path.join(projRoot, 'w') })] })
+ const store = new WorkspaceStore()
+ await store.save(ws([plain]))
+ const viaSave = await fs.readFile(projectFile(), 'utf-8')
+ expect(await store.writeProjectContent('P', content([node('z')]))).toBe(true)
+ expect(await store.writeProjectContent('P', contentOf(plain))).toBe(true)
+ expect(withoutBookkeeping(await fs.readFile(projectFile(), 'utf-8'))).toBe(withoutBookkeeping(viaSave))
+ })
+
+ it('never writes a rev below the one on disk (an outside edit the store has not reloaded yet)', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot, nodes: [node('a')] })]))
+ const outside = { ...(await readJson(projectFile())), rev: 9 }
+ await fs.writeFile(projectFile(), JSON.stringify(outside, null, 2))
+ expect(await store.writeProjectContent('P', content([node('b')]))).toBe(true)
+ expect((await readJson(projectFile())).rev).toBe(10)
+ })
+
+ it('keeps the file’s board when the content has none', async () => {
+ const store = await seedFolderAtRev3()
+ expect(await store.writeProjectContent('P', content([node('a')]))).toBe(true)
+ const f = await readJson(projectFile())
+ expect(f.kanban.columns.map((c: { id: string }) => c.id)).toEqual(['c1'])
+ expect(f.kanban.github.repository).toBe('a/b')
+ })
+
+ it('does not rewrite a file that already holds this content', async () => {
+ const store = new WorkspaceStore()
+ const p = project({ cwd: projRoot, nodes: [node('a')] })
+ await store.save(ws([p]))
+ const before = await fs.readFile(projectFile(), 'utf-8')
+ expect(await store.writeProjectContent('P', contentOf(p))).toBe(true)
+ expect(await fs.readFile(projectFile(), 'utf-8')).toBe(before)
+ })
+
+ it('never writes an empty canvas over a populated file it has not read', async () => {
+ // The folder's file was missing at load, and has since appeared (a remount, a checkout).
+ await fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify({
+ version: 3, activeProjectId: 'P',
+ entries: [{ id: 'P', name: 'foo', color: '#fff', cwd: projRoot, execMigrated: true }]
+ }))
+ const store = new WorkspaceStore()
+ await store.load()
+ await fs.mkdir(path.dirname(projectFile()), { recursive: true })
+ const populated = JSON.stringify({ version: 1, rev: 5, savedAt: 'x', name: 'foo', color: '#fff', nodes: [node('keep')] }, null, 2)
+ await fs.writeFile(projectFile(), populated)
+
+ expect(await store.writeProjectContent('P', content([]))).toBe(false)
+ expect(await fs.readFile(projectFile(), 'utf-8')).toBe(populated)
+ })
+})
+
+describe('writeProjectContent — cwd-less canvas', () => {
+ it('writes its data file and the index cache', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({
+ id: INLINE_ID,
+ nodes: [node('a')],
+ kanban: {
+ columns: [{ id: 'c1', title: 'To Do', color: '#888' }],
+ assignments: [],
+ github: { repository: 'a/b', columnMappings: [] }
+ } as ProjectKanban
+ })]))
+
+ const ok = await store.writeProjectContent(INLINE_ID, content([node('b')], {
+ kanban: { columns: [{ id: 'c2', title: 'Doing', color: '#88f' }], assignments: [] }
+ }))
+ expect(ok).toBe(true)
+
+ const raw = await fs.readFile(dataFile(), 'utf-8')
+ const f = JSON.parse(raw)
+ expect(f.rev).toBe(2)
+ expect(ids(f.nodes)).toEqual(['b'])
+ expect(f.kanban.columns.map((c: { id: string }) => c.id)).toEqual(['c2'])
+ expect(f.kanban.github).toEqual({ repository: 'a/b', columnMappings: [] })
+ expect(store.isSelfWrite(dataFile(), raw)).toBe(true)
+
+ const entry = (await readIndex()).entries[0]
+ expect(entry.dataFile).toBe(true)
+ expect(ids(entry.project.nodes)).toEqual(['b'])
+ expect(entry.project.kanban.github).toEqual({ repository: 'a/b', columnMappings: [] })
+ expect(ids((await store.readProjectContent(INLINE_ID))!.nodes)).toEqual(['b'])
+ expect(ids((await new WorkspaceStore().load()).projects[0].nodes)).toEqual(['b'])
+ expect(externalChanges()).toHaveLength(0)
+ })
+
+ it('is byte-identical to a normal save of the same content, apart from rev and savedAt', async () => {
+ const rich = richProject(undefined, INLINE_ID)
+ const store = new WorkspaceStore()
+ await store.save(ws([rich]))
+ const viaSave = await fs.readFile(dataFile(), 'utf-8')
+ expect(await store.writeProjectContent(INLINE_ID, content([node('z')]))).toBe(true)
+ expect(await store.writeProjectContent(INLINE_ID, contentOf(rich))).toBe(true)
+ const viaWrite = await fs.readFile(dataFile(), 'utf-8')
+ expect(JSON.parse(viaWrite).rev).toBe(3)
+ expect(withoutBookkeeping(viaWrite)).toBe(withoutBookkeeping(viaSave))
+ })
+
+ it('refuses when the file on disk carries a rev ahead of ours (another instance wrote it)', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ id: INLINE_ID, nodes: [node('a')] })]))
+ const theirs = JSON.stringify({ version: 1, rev: 9, savedAt: 'x', name: 'other', color: '#000', nodes: [node('other')] }, null, 2)
+ await fs.writeFile(dataFile(), theirs)
+ store.onPersist = vi.fn()
+
+ expect(await store.writeProjectContent(INLINE_ID, content([node('b')]))).toBe(false)
+ expect(await fs.readFile(dataFile(), 'utf-8')).toBe(theirs)
+ expect(ids((await readIndex()).entries[0].project.nodes)).toEqual(['a'])
+ expect(ids((await store.readProjectContent(INLINE_ID))!.nodes)).toEqual(['a'])
+ expect(store.onPersist).not.toHaveBeenCalled()
+ })
+})
+
+describe('writeProjectContent — bookkeeping and refusals', () => {
+ it('calls onPersist once per landed write', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot }), project({ id: INLINE_ID })]))
+ store.onPersist = vi.fn()
+
+ expect(await store.writeProjectContent('P', content([node('b')]))).toBe(true)
+ expect(store.onPersist).toHaveBeenCalledTimes(1)
+ expect(await store.writeProjectContent(INLINE_ID, content([node('b')]))).toBe(true)
+ expect(store.onPersist).toHaveBeenCalledTimes(2)
+ })
+
+ it('refuses an SSH project and an unknown id, writing nothing', async () => {
+ const remote = fakeRemote()
+ const store = new WorkspaceStore(remote)
+ store.setContentAuthority(passThrough)
+ await store.save(ws([project({ id: 's1', ssh: SSH, cwd: undefined })]))
+ const writes = remote.writes
+ const index = await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')
+ store.onPersist = vi.fn()
+
+ expect(await store.writeProjectContent('s1', content([node('b')]))).toBe(false)
+ expect(await store.writeProjectContent('nope', content([node('b')]))).toBe(false)
+ expect(remote.writes).toBe(writes)
+ expect(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')).toBe(index)
+ expect(store.onPersist).not.toHaveBeenCalled()
+ })
+
+ it('is queued on saveChain: it lands after a save already in flight', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot, nodes: [node('a')] })]))
+ const save = store.save(ws([project({ cwd: projRoot, nodes: [node('s')] })]))
+ const write = store.writeProjectContent('P', content([node('w')]))
+ await Promise.all([save, write])
+ expect(ids((await readJson(projectFile())).nodes)).toEqual(['w'])
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 6171adae7..16281c3ba 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -6,9 +6,10 @@ import { IPC } from '../shared/ipc'
import { platform } from './platform'
import {
DEFAULT_PROJECT_ID, EMPTY_WORKSPACE,
- type BridgeLink, type CanvasNodeState, type KanbanColumn, type KanbanLabel, type Project, type Workspace, type WorkspaceSaveOptions,
- type WorkspaceV1
+ type BridgeLink, type CanvasNodeState, type KanbanColumn, type KanbanLabel, type Project, type ProjectKanban,
+ type Workspace, type WorkspaceSaveOptions, type WorkspaceV1
} from '../shared/types'
+import { contentOf, type CanvasContent } from '../shared/canvas-content'
import {
PROJECT_DIR, PROJECT_FILE, fileToProject, inlineProjectFileRelPath, isInlineProjectFileId,
projectToFile, resolveNodes, sameProjectContent,
@@ -37,6 +38,19 @@ import { appendProjectNode, removeProjectNode, type RemoteNodeInput } from './pr
import { editProjectCardLabels, ensureProjectBoard, setProjectCardColumn, type CardLabelEdit } from './project-kanban-write'
import { boardLabels, cardMeta } from '../shared/kanban-labels'
+/**
+ * The seam a content authority (the Server Edition's canvas authority, `core/canvas-authority.ts`)
+ * governs shared projects through. For every project it governs it is the one writer of the CONTENT
+ * fields (nodes, bridges, ropes, board items); the renderer's whole-workspace saves and this store's
+ * loads still carry everything else, so both are passed through it.
+ */
+export interface ContentAuthorityHooks {
+ /** Rewrite governed projects' content fields just before a save is split and written. */
+ overlaySave(ws: Workspace): Promise<Workspace>
+ /** Rewrite governed projects' content fields in a load result. */
+ overlayLoad(ws: Workspace): Promise<Workspace>
+}
+
/** Checked remote read: `absent` (no file — safe to push our cache) is NOT `error` (connection
* down / ssh failure — a failed read is never evidence of absence, so nothing may be pushed). */
export type RemoteReadResult = { status: 'ok'; content: string } | { status: 'absent' } | { status: 'error' }
@@ -84,6 +98,90 @@ const NO_PROJECTS: readonly string[] = Object.freeze([])
const contentHash = (content: string): string => createHash('sha256').update(content).digest('hex')
+/**
+ * This machine's exec values for one ref'd entry's file, exactly as the load computes them
+ * (`WorkspaceStore.execOverlay`) but without its bookkeeping, so a read-only caller can ask: a
+ * migrated entry answers with its own `localExec`; an entry still owed the one-time migration also
+ * hoists what its file carried from before the trust boundary (@shared/node-exec).
+ */
+function localExecOverlay(e: IndexEntryV3, f: ProjectFileV1): LocalNodeExecMap | undefined {
+ if (e.execMigrated) return e.localExec
+ const hoisted = hoistLegacyNodeExec(f.nodes)
+ return hoisted ? { ...hoisted, ...e.localExec } : e.localExec
+}
+
+/** A project file's `rev` as a number. The file is hand-editable input; a string there would turn
+ * `rev + 1` into string concatenation. */
+const fileRev = (f: ProjectFileV1): number =>
+ typeof f.rev === 'number' && Number.isFinite(f.rev) ? f.rev : 0
+
+/** The board keys that belong to the FILE, not to the content vocabulary: the GitHub sync config
+ * and the pull-request link overrides are coupled to columns but are never carried by a canvas
+ * mutation, so a content write must not be able to change them. */
+const BOARD_CONFIG_KEYS = ['github', 'pullLinks'] as const
+
+/**
+ * `board` (the content's) with the file's own `github` / `pullLinks`, field-level: every other key
+ * comes from `board`, those two from `file` — present when the file has them, absent when it does
+ * not, whatever `board` says. Key order follows `board`, so a board that came out of this file
+ * serializes in the file's own order. When the content has no board, the file's board is kept as it
+ * is: a content write never deletes a board.
+ */
+function boardWithFileConfig(
+ board: ProjectKanban | undefined,
+ file: ProjectKanban | undefined
+): ProjectKanban | undefined {
+ if (!board) return file
+ const own = (file ?? {}) as Record<string, unknown>
+ const isConfig = (k: string): boolean => (BOARD_CONFIG_KEYS as readonly string[]).includes(k)
+ const out: Record<string, unknown> = {}
+ for (const [k, v] of Object.entries(board)) {
+ if (!isConfig(k)) out[k] = v
+ else if (own[k] !== undefined) out[k] = own[k]
+ }
+ for (const k of BOARD_CONFIG_KEYS) if (!(k in out) && own[k] !== undefined) out[k] = own[k]
+ return out as unknown as ProjectKanban
+}
+
+/** An edge list to write: the content's, except that an EMPTY list does not add a key the base did
+ * not carry — "no list" and "an empty list" are the same content, and writing `"bridges": []` into
+ * a file nobody drew a link in is a diff in the user's repository nobody made. */
+const edgeList = (next: BridgeLink[], prev: BridgeLink[] | undefined): BridgeLink[] | undefined =>
+ next.length || prev !== undefined ? next : undefined
+
+/** `base` with its content fields replaced by `content`: nodes and edge lists whole, the board
+ * field-level (`boardWithFileConfig`). Everything else — name, colour, icon, capabilities, layouts,
+ * the machine-local half — is `base`'s. */
+function withContent(base: Project, content: CanvasContent): Project {
+ const out: Project = { ...base, nodes: content.nodes }
+ const bridges = edgeList(content.bridges, base.bridges)
+ const ropes = edgeList(content.ropes, base.ropes)
+ const kanban = boardWithFileConfig(content.kanban, base.kanban)
+ if (bridges) out.bridges = bridges
+ else delete out.bridges
+ if (ropes) out.ropes = ropes
+ else delete out.ropes
+ if (kanban) out.kanban = kanban
+ else delete out.kanban
+ return out
+}
+
+/** A cwd-less canvas's content out of its index cache, admitted with the sanitizers the inline load
+ * branch applies: workspace.json is hand-editable, and the entry's `project` can be the raw copy
+ * (the load sanitizes what it RETURNS, not the entry). Null for a cache with no node list. */
+function inlineContent(p: Project): CanvasContent | null {
+ if (!Array.isArray(p.nodes)) return null
+ return contentOf({
+ nodes: sanitizeNodeTriggers(p.nodes),
+ bridges: p.bridges ? sanitizeLinks(p.bridges) : undefined,
+ ropes: p.ropes ? sanitizeLinks(p.ropes) : undefined,
+ kanban: sanitizeKanban(p.kanban)
+ })
+}
+
+/** What `writeDataFile` did. The save path ignores it; `writeProjectContent` answers with it. */
+type DataFileWrite = 'written' | 'unchanged' | 'ahead' | 'refused' | 'failed' | 'skipped'
+
/** Alias of the shared `ProjectSettingsSnapshot` (moved to `shared/project-settings.ts` so the
* renderer's `ProjectSettingsApi` can name the shape without importing core) — the store's
* methods keep this name in their signatures. */
@@ -227,9 +325,17 @@ export class WorkspaceStore {
private index: WorkspaceIndexV3 | null = null
/** Optional hook fired after every load()/save() — the watcher re-syncs its watch set (Task 5). */
onPersist?: () => void
+ /** The content authority, when this process runs one (Server Edition hosting a team). */
+ private contentAuthority: ContentAuthorityHooks | null = null
constructor(private remoteIO?: RemoteWorkspaceIO) {}
+ /** Attach (or, with null, detach) the content authority whose overlays every later save and load
+ * pass through. Set once at boot, before the first load. */
+ setContentAuthority(hooks: ContentAuthorityHooks | null): void {
+ this.contentAuthority = hooks
+ }
+
private get indexPath(): string {
return path.join(platform().userDataDir, 'workspace.json')
}
@@ -257,7 +363,20 @@ export class WorkspaceStore {
* a phone can trigger mid git-merge) pass false so a conflict-marked file is left hand-resolvable.
*/
async load(opts?: { sideline?: boolean }): Promise<Workspace> {
- const result = await this.loadInner(opts?.sideline ?? true)
+ let result = await this.loadInner(opts?.sideline ?? true)
+ const authority = this.contentAuthority
+ if (authority) {
+ try {
+ result = await authority.overlayLoad(result)
+ } catch (err) {
+ // Answer the load WITHOUT the overlay rather than throw. `loadInner` has already set
+ // `this.index`, so the empty-save guard at the top of `saveNow` (`!this.index`) no longer
+ // protects it: a renderer left without the projects this load failed to hand over can still
+ // save (a new project, say), and that save rebuilds the index without them and sweeps their
+ // inline data files. A stale copy is the safe side — the next save is overlaid again.
+ console.warn(`[workspace] content overlay failed on load; serving the stored workspace: ${String(err)}`)
+ }
+ }
this.onPersist?.()
return result
}
@@ -538,11 +657,10 @@ export class WorkspaceStore {
// the entry stays unmarked forever and the hoist re-runs on every full load, which would also
// let a project.json swapped in AFTER the deferral get its exec fields hoisted as trusted.
this.execUnmigrated.delete(e.id)
- if (e.execMigrated) return e.localExec
- const hoisted = hoistLegacyNodeExec(f.nodes)
- if (!hoisted) return e.localExec
- this.pendingExecNote = true
- return { ...hoisted, ...e.localExec }
+ const overlay = localExecOverlay(e, f)
+ // A hoist happened exactly when the overlay is not the entry's own map (see `localExecOverlay`).
+ if (overlay !== e.localExec) this.pendingExecNote = true
+ return overlay
}
/** The file was unreadable, so the hoist could not run: leave the entry unmarked and retry it on
@@ -999,6 +1117,138 @@ export class WorkspaceStore {
return parsed
}
+ /**
+ * The current content of a project as this store knows it, WITHOUT queueing on `saveChain`: the
+ * content authority calls it from inside `saveNow` (its save overlay), and a queued read would
+ * wait on the very save that is waiting on it. null = unknown project, SSH project (its file is
+ * on another machine), or a file this store cannot read.
+ *
+ * A folder project answers from the store's own last write or read of its file (`lastWritten`),
+ * else from one read off disk, converted the way a load converts it: portable cwds resolved
+ * against the folder and this machine's exec values re-applied. The read is NOT recorded:
+ * recording it would make the watcher take an outside edit it has not processed yet for one of
+ * our own writes. A cwd-less canvas answers from its index cache, which every save and every
+ * `writeProjectContent` keeps in step with its data file.
+ */
+ async readProjectContent(projectId: string): Promise<CanvasContent | null> {
+ const e = this.index?.entries.find((x) => x.id === projectId)
+ if (!e || e.ssh) return null
+ if (e.cwd) {
+ const file = await this.knownProjectFile(e.cwd)
+ if (!file) return null
+ return contentOf(fileToProject(file, { id: e.id, cwd: e.cwd, localExec: localExecOverlay(e, file) }))
+ }
+ return e.project ? inlineContent(e.project) : null
+ }
+
+ /** A folder project's file as this store last wrote or read it, else as it is on disk now. */
+ private async knownProjectFile(cwd: string): Promise<ProjectFileV1 | null> {
+ try {
+ const known = this.parsedLastWritten(projectFilePath(cwd))
+ if (known && Array.isArray(known.nodes)) return known
+ } catch { /* our own record, but never trusted blindly — fall back to the disk */ }
+ return (await this.readProjectFile(cwd, false))?.file ?? null
+ }
+
+ /**
+ * Replace a project's content fields (nodes, bridges, ropes, the board's items) atomically — the
+ * content authority's flush. Queued on `saveChain` like every other read-modify-write of a
+ * project file, so it can never interleave with a save.
+ *
+ * The file it writes is byte-identical to the one `save()` writes for the same project, apart
+ * from `rev` and `savedAt`: it goes through the same `projectToFile` (portable node cwds, exec
+ * fields stripped, triggers / links / board sanitized, the derived `viewport` and legacy `id`),
+ * and the project it hands that function is the file's own, read the way a load reads it, with
+ * only its content fields replaced. So the file keeps everything else it carried — name, colour,
+ * icon, capabilities, layouts — and its board keeps its own `github` and `pullLinks`.
+ *
+ * It does what a save does to the store's bookkeeping — `lastWritten` (so the watcher reads it
+ * as a self-write, never an outside edit), `revs`, a cwd-less canvas's `e.project` cache and the
+ * index write that carries it, and `onPersist` — and deliberately broadcasts nothing: every
+ * client already has the change from the reflector.
+ *
+ * Resolves false when nothing could be written: an unknown or SSH project, an unreadable file
+ * (never written over — a file mid-merge is left for the user), an I/O error, a cwd-less file
+ * whose disk rev is ahead of ours (another instance wrote it), or an empty canvas over a
+ * populated file this store has never read. The last two are the save path's own rules.
+ */
+ writeProjectContent(projectId: string, content: CanvasContent): Promise<boolean> {
+ const run = this.saveChain.then(() => this.writeProjectContentNow(projectId, content))
+ this.saveChain = run.catch(() => {})
+ return run
+ }
+
+ private async writeProjectContentNow(projectId: string, content: CanvasContent): Promise<boolean> {
+ const e = this.index?.entries.find((x) => x.id === projectId)
+ if (!e || e.ssh) return false
+ const savedAt = new Date().toISOString()
+ if (e.cwd) return this.writeFolderContent(e, e.cwd, content, savedAt)
+ if (e.project) return this.writeInlineContent(e, e.project, content, savedAt)
+ return false
+ }
+
+ /** The folder leg: `<cwd>/.nodeterm/project.json`, under the save's folder-leg rules. */
+ private async writeFolderContent(
+ e: IndexEntryV3,
+ cwd: string,
+ content: CanvasContent,
+ savedAt: string
+ ): Promise<boolean> {
+ const file = projectFilePath(cwd)
+ const read = await this.readProjectFile(cwd, false)
+ if (!read) return false
+ const candidate = projectToFile(withContent(fileToProject(read.file, { id: e.id, cwd }), content), 0, savedAt)
+ // Unchanged: nothing to write, and no rev to burn.
+ if (sameProjectContent(read.file, candidate)) return true
+ let known: ProjectFileV1 | null = null
+ try {
+ known = this.parsedLastWritten(file)
+ } catch { /* treated as never read */ }
+ // The save's rule: an empty canvas never overwrites a populated file this store has not read.
+ if (!known && candidate.nodes.length === 0 && read.file.nodes.length > 0) return false
+ const rev = Math.max(this.revs.get(e.id) ?? 0, fileRev(read.file)) + 1
+ const out = serializeProjectFile({ ...candidate, rev })
+ try {
+ await writeAtomic(file, out)
+ } catch {
+ return false
+ }
+ this.lastWritten.set(file, out)
+ this.revs.set(e.id, rev)
+ this.onPersist?.()
+ return true
+ }
+
+ /** The cwd-less leg: the data file under `writeDataFile`'s rules, then the index cache. A pre-file
+ * canvas (no `dataFile`, or an id we will not turn into a path) is stored IN the index, so for
+ * it the index write is the write. */
+ private async writeInlineContent(
+ e: IndexEntryV3,
+ cached: Project,
+ content: CanvasContent,
+ savedAt: string
+ ): Promise<boolean> {
+ const updated = withContent(cached, content)
+ const viaFile = e.dataFile === true && isInlineProjectFileId(e.id)
+ if (viaFile) {
+ const landed = await this.writeDataFile(e.id, projectToFile(updated, 0, savedAt))
+ if (landed !== 'written' && landed !== 'unchanged') return false
+ }
+ e.project = updated
+ try {
+ await this.writeIndexNow()
+ } catch {
+ // A data-ref's file already holds the content and wins at load, so a stale cache costs
+ // nothing lasting; a pre-file canvas has nowhere else to be.
+ if (!viaFile) {
+ e.project = cached
+ return false
+ }
+ }
+ this.onPersist?.()
+ return true
+ }
+
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":
@@ -1011,6 +1261,11 @@ export class WorkspaceStore {
if ((disk.entries?.length ?? 0) > 0 || (disk.projects?.length ?? 0) > 0) return
} catch { /* absent or unparsable (loadInner sidelines corruption) — an empty write is fresh */ }
}
+ // A governed project's content comes from the content authority, never from this (possibly
+ // stale) copy of it. Applied BEFORE the split, so every leg below — the project file, the data
+ // file, the index cache — writes the overlaid content. The authority reads the current content
+ // through `readProjectContent`, which does not queue on `saveChain`: this code runs ON it.
+ if (this.contentAuthority) workspace = await this.contentAuthority.overlaySave(workspace)
const savedAt = new Date().toISOString()
const previousIndex = this.index
const { index, files, dataFiles } = splitWorkspace(workspace, (id) => this.revs.get(id) ?? 0, savedAt)
@@ -1226,8 +1481,8 @@ export class WorkspaceStore {
* 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
+ private async writeDataFile(projectId: string, candidate: ProjectFileV1): Promise<DataFileWrite> {
+ if (!isInlineProjectFileId(projectId)) return 'skipped'
const file = inlineFilePath(projectId)
const prev = this.lastWritten.get(file)
let prevParsed: ProjectFileV1 | null = null
@@ -1236,7 +1491,7 @@ export class WorkspaceStore {
prevParsed = JSON.parse(prev) as ProjectFileV1
} catch { /* our own cache, but never trusted blindly */ }
}
- if (prevParsed && sameProjectContent(prevParsed, candidate)) return
+ if (prevParsed && sameProjectContent(prevParsed, candidate)) return 'unchanged'
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)
@@ -1245,9 +1500,9 @@ export class WorkspaceStore {
// against reality instead of re-deciding this every time.
this.lastWritten.set(file, onDisk.raw)
this.revs.set(projectId, onDisk.file.rev)
- return
+ return 'ahead'
}
- if (!prevParsed && candidate.nodes.length === 0 && (onDisk?.file.nodes.length ?? 0) > 0) return
+ if (!prevParsed && candidate.nodes.length === 0 && (onDisk?.file.nodes.length ?? 0) > 0) return 'refused'
const next: ProjectFileV1 = { ...candidate, rev: ourRev + 1 }
const content = serializeProjectFile(next)
try {
@@ -1255,7 +1510,11 @@ export class WorkspaceStore {
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 */ }
+ return 'written'
+ } catch {
+ // the index's `project` copy still holds this canvas; the next save retries
+ return 'failed'
+ }
}
/**