Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(whiteboard): refuse a save made over a newer board (compare-and-set)

review29daee037c5c
diff --git a/CLAUDE.md b/CLAUDE.md
index 045240566..3ccd8c73d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2168,9 +2168,18 @@ number: change the table in that one module, never in one emulator.
(project, node id) — `core/whiteboards.ts` — and NEVER by a path from node data (project.json is
git-shared, hostile input); node data holds only `whiteboardSource` (a copy's original, by id)
and `boardRev` (once per session); (3) the overlay is `data-nt-keyboard-owner`, which every
- typing-aware key site honours via `isKeyboardOwnerTarget`; (4) every save path compares versions
- against disk, and the unmount flush writes a snapshot kept from `onChange` — Excalidraw's api is
- empty by cleanup time, and reading it there once erased a board. Excalidraw loads lazily; fonts
+ typing-aware key site honours via `isKeyboardOwnerTarget`; (4) every save is a COMPARE-AND-SET:
+ it sends the revision its editor last read or wrote (`rev`, `dev:ino:size:mtimeNs` of the scene
+ file — writers publish by rename, so it changes on every write; `null` = no board of its own yet)
+ and the core refuses it when the file on disk has moved on, so a board open in two places (two
+ tabs, a desktop and a browser on one folder, two hosted-team Editors, a `git pull`) is never
+ silently replaced by the later writer — the editor says "Changed elsewhere" instead. Saves of one
+ board are serialized within a core; two CORES on one folder can still interleave between the
+ check and the rename. The editor's own "has anything changed" test compares with what IT last
+ saved, not with disk. The unmount flush writes a snapshot kept from `onChange` — Excalidraw's api
+ is empty by cleanup time, and reading it there once erased a board; (5) the project folder is
+ bound by its REAL path — a `.nodeterm` or `.nodeterm/whiteboards` symlink leading out of the
+ project is not followed (the board falls back to the app folder). Excalidraw loads lazily; fonts
come from `scripts/excalidraw-assets-plugin.ts`; mermaid is aliased to a stub.
- **Run node** (a `terminal` node carrying `data.runConfig`, NOT a new NodeKind;
`@shared/run-config`, `core/run-service.ts`, `nodes/RunBar.tsx`) — VS Code's "Run Without
diff --git a/docs/whiteboard-node.md b/docs/whiteboard-node.md
index ac91216a1..251cae128 100644
--- a/docs/whiteboard-node.md
+++ b/docs/whiteboard-node.md
@@ -68,10 +68,31 @@ could aim a read or an overwrite anywhere. A node id must be a `string` passing
stroke), so strokes never reach the workspace save, canvas undo or team sync.
Saves happen 1.5 s after the last change, when editing ends (with the picture), and on unmount
-(project switch, node closed, quit). Each compares the current version with what is on disk rather
-than trusting an `onChange` flag; the unmount flush writes a snapshot kept from `onChange`, because
-by cleanup time Excalidraw's api answers an empty scene. A board whose file does not parse is shown
-as unreadable and never opened, so an autosave cannot overwrite it.
+(project switch, node closed). Whether there is anything to save is decided by comparing the
+scene's version with the one this editor last saved, not by an `onChange` flag; the unmount flush
+writes a snapshot kept from `onChange`, because by cleanup time Excalidraw's api answers an empty
+scene. A board whose file does not parse is shown as unreadable and never opened, so an autosave
+cannot overwrite it.
+
+**Every save is a compare-and-set against the file on disk.** A board can be open in two places:
+two Server Edition tabs, the desktop and a browser on one folder, two Editors of a hosted team, or
+a `git pull` that rewrites the file while it is open. Each read returns the scene file's revision
+(`rev`: `dev:ino:size:mtimeNs` of the descriptor read — every writer publishes by rename, so it
+changes on every write, also on a coarse-mtime filesystem), the editor sends the revision it last
+read or wrote with every save (`null` when the node has no board of its own yet — a new board, or a
+copy still showing its source), and the core refuses a save whose revision is not the one on disk.
+Nothing is written then, and the header says **Changed elsewhere**: the other version was kept.
+Saves of one board are serialized inside one core, so two saves racing there cannot both pass the
+check; two cores writing one folder (a desktop and a Server Edition) can still interleave in the
+moment between the check and the rename. A core on an older build ignores the revision and answers
+the bare path, and the save is then unchecked, as before.
+
+**The project folder is bound by its real path.** `.nodeterm/` is git-shared, so a repository can
+commit `.nodeterm` or `.nodeterm/whiteboards` as a symlink to any directory on this machine. Each
+existing component is resolved before anything is created through it and must stay inside the
+project's real root; a link that leads out (or dangles) means the project folder is not used — a
+save lands in the app folder, a read does not look there. A link that stays inside the project is
+followed.
The two channels (`files.saveWhiteboard`, `files.readWhiteboard`) are registered in core for both
shells and classified in both relay policies exactly like a canvas image (save: editors only;
diff --git a/src/core/fs-handlers.ts b/src/core/fs-handlers.ts
index 075ce72e3..04c324ff3 100644
--- a/src/core/fs-handlers.ts
+++ b/src/core/fs-handlers.ts
@@ -83,14 +83,16 @@ export function registerFsHandlers(
// A whiteboard's scene + picture: beside project.json when the project has a local cwd, else in
// this core's data dir. Addressed by node id only — see core/whiteboards.ts for why a path is
// never accepted.
+ // `expectedRev` is the compare-and-set revision (see `saveWhiteboard`): a stale one is refused.
platform.handle(
IPC.filesSaveWhiteboard,
- (projectId: string, nodeId: string, scene: string, thumbnailBase64?: string) =>
+ (projectId: string, nodeId: string, scene: string, thumbnailBase64?: string, expectedRev?: string | null) =>
saveWhiteboard(
{ projectCwd: deps.localProjectCwd?.(projectId), userDataDir: platform.userDataDir },
nodeId,
scene,
- thumbnailBase64
+ thumbnailBase64,
+ expectedRev
)
)
platform.handle(
diff --git a/src/core/read-regular-file.ts b/src/core/read-regular-file.ts
index f3eb8a153..c90ab8a59 100644
--- a/src/core/read-regular-file.ts
+++ b/src/core/read-regular-file.ts
@@ -51,14 +51,19 @@ export async function readRegularFileNoFollow(
* `readRegularFileNoFollow`'s rules for binary or large files: the same single-descriptor open →
* fstat → lstat-identity check, but the buffer is sized from the fstat (not `maxBytes`, which for a
* whiteboard scene is 64 MB), the bytes come back raw, and `read: false` answers only the file's
- * mtime — so a caller can learn a file's revision without reading it. Resolves `null` for anything
- * that is not a readable regular file within `maxBytes`. Never throws.
+ * mtime and stamp — so a caller can learn a file's revision without reading it. Resolves `null` for
+ * anything that is not a readable regular file within `maxBytes`. Never throws.
+ *
+ * `stamp` is `dev:ino:size:mtimeNs` of the descriptor actually read: it changes whenever the file is
+ * rewritten — and on a coarse-mtime filesystem too, as long as writers publish by rename (a new
+ * inode each time), which is how every writer of ours publishes (the rule `WorkspaceStore.save`
+ * relies on for workspace.json).
*/
export async function readRegularFileBytesNoFollow(
file: string,
maxBytes: number,
opts: { read?: boolean } = {}
-): Promise<{ bytes?: Buffer; mtimeMs: number } | null> {
+): Promise<{ bytes?: Buffer; mtimeMs: number; stamp: string } | null> {
let fh: fs.FileHandle | undefined
try {
fh = await fs.open(file, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0))
@@ -67,7 +72,8 @@ export async function readRegularFileBytesNoFollow(
const named = await fs.lstat(file, { bigint: true })
if (!named.isFile() || (st.ino !== 0n && (named.dev !== st.dev || named.ino !== st.ino))) return null
const mtimeMs = Number(st.mtimeMs)
- if (opts.read === false) return { mtimeMs }
+ const stamp = `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}`
+ if (opts.read === false) return { mtimeMs, stamp }
// One byte past what fstat reported, from the SAME handle: a file that grew since is refused.
const want = Number(st.size) + 1
const buf = Buffer.alloc(want)
@@ -78,7 +84,7 @@ export async function readRegularFileBytesNoFollow(
total += bytesRead
}
if (total > Number(st.size) || total > maxBytes) return null
- return { bytes: buf.subarray(0, total), mtimeMs }
+ return { bytes: buf.subarray(0, total), mtimeMs, stamp }
} catch {
return null
} finally {
diff --git a/src/core/whiteboards.test.ts b/src/core/whiteboards.test.ts
index c34e8abf3..3aee50601 100644
--- a/src/core/whiteboards.test.ts
+++ b/src/core/whiteboards.test.ts
@@ -16,6 +16,10 @@ const scene = JSON.stringify({ type: 'excalidraw', elements: [{ id: 'a' }] })
const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff, 0xfe, 0x80])
const png = pngBytes.toString('base64')
+/** The written path of a successful save (the tests above the compare-and-set block do not care
+ * about revisions). */
+const pathOf = (r: Awaited<ReturnType<typeof saveWhiteboard>>): string | null => (r && r.ok ? r.path : null)
+
let root: string
let userDataDir: string
let projectCwd: string
@@ -31,7 +35,7 @@ afterEach(() => rm(root, { recursive: true, force: true }))
describe('saveWhiteboard / readWhiteboard', () => {
it('writes beside project.json and reads the scene and picture back, picture byte-exact', async () => {
const path = await saveWhiteboard({ projectCwd, userDataDir }, 'whiteboard-1', scene, png)
- expect(path).toBe(join(projectWhiteboardsDir(projectCwd), 'whiteboard-1.excalidraw'))
+ expect(pathOf(path)).toBe(join(projectWhiteboardsDir(projectCwd), 'whiteboard-1.excalidraw'))
const read = await readWhiteboard({ projectCwd, userDataDir }, 'whiteboard-1')
expect(read).toMatchObject({ scene, fromSource: false })
expect(Buffer.from(read!.thumbnailBase64!, 'base64').equals(pngBytes)).toBe(true)
@@ -40,21 +44,21 @@ describe('saveWhiteboard / readWhiteboard', () => {
it('uses the app folder for a project with no local cwd (cwd-less canvas, SSH project)', async () => {
const path = await saveWhiteboard({ userDataDir }, 'whiteboard-1', scene)
- expect(path).toBe(join(appWhiteboardsDir(userDataDir), 'whiteboard-1.excalidraw'))
+ expect(pathOf(path)).toBe(join(appWhiteboardsDir(userDataDir), 'whiteboard-1.excalidraw'))
expect((await readWhiteboard({ userDataDir }, 'whiteboard-1'))?.scene).toBe(scene)
})
it('never resurrects a deleted project folder; the board lands in the app folder instead', async () => {
await rm(projectCwd, { recursive: true, force: true })
const path = await saveWhiteboard({ projectCwd, userDataDir }, 'whiteboard-1', scene)
- expect(path).toBe(join(appWhiteboardsDir(userDataDir), 'whiteboard-1.excalidraw'))
+ expect(pathOf(path)).toBe(join(appWhiteboardsDir(userDataDir), 'whiteboard-1.excalidraw'))
await expect(fs.stat(projectCwd)).rejects.toThrow()
})
it('falls back to the app folder when the project folder will not take the file', async () => {
await fs.writeFile(join(projectCwd, '.nodeterm'), 'not a directory')
const path = await saveWhiteboard({ projectCwd, userDataDir }, 'whiteboard-1', scene)
- expect(path).toBe(join(appWhiteboardsDir(userDataDir), 'whiteboard-1.excalidraw'))
+ expect(pathOf(path)).toBe(join(appWhiteboardsDir(userDataDir), 'whiteboard-1.excalidraw'))
// ...and a read finds it there, since the project folder has no board.
expect((await readWhiteboard({ projectCwd, userDataDir }, 'whiteboard-1'))?.scene).toBe(scene)
})
@@ -137,14 +141,14 @@ describe.skipIf(process.platform === 'win32')('the project folder is bound by it
await fs.mkdir(join(projectCwd, '.nodeterm'))
await fs.symlink(outside, projectWhiteboardsDir(projectCwd))
const path = await saveWhiteboard({ projectCwd, userDataDir }, 'whiteboard-1', scene, png)
- expect(path).toBe(join(appWhiteboardsDir(userDataDir), 'whiteboard-1.excalidraw'))
+ expect(pathOf(path)).toBe(join(appWhiteboardsDir(userDataDir), 'whiteboard-1.excalidraw'))
expect(await fs.readdir(outside)).toEqual([])
})
it('a .nodeterm symlink out of the project: no folder is created on the other side', async () => {
await fs.symlink(outside, join(projectCwd, '.nodeterm'))
const path = await saveWhiteboard({ projectCwd, userDataDir }, 'whiteboard-1', scene, png)
- expect(path).toBe(join(appWhiteboardsDir(userDataDir), 'whiteboard-1.excalidraw'))
+ expect(pathOf(path)).toBe(join(appWhiteboardsDir(userDataDir), 'whiteboard-1.excalidraw'))
expect(await fs.readdir(outside)).toEqual([])
})
@@ -175,3 +179,76 @@ describe.skipIf(process.platform === 'win32')('the project folder is bound by it
expect(await fs.readdir(join(root, 'userData')).catch(() => [])).toEqual([])
})
})
+
+// A board can be open in two places at once: two Server Edition tabs, the desktop and a browser on
+// one folder, two Editors of a hosted team. Each save names the revision its editor last read or
+// wrote, and the core refuses a save whose revision is no longer the one on disk — instead of the
+// later writer silently replacing the earlier writer's whole board.
+describe('compare-and-set: a save made against a stale revision is refused', () => {
+ const sceneOf = (tag: string) => JSON.stringify({ type: 'excalidraw', elements: [{ id: tag }] })
+ const onDisk = () => fs.readFile(join(projectWhiteboardsDir(projectCwd), 'whiteboard-1.excalidraw'), 'utf8')
+
+ it('the second of two editors that opened the same board cannot overwrite the first', async () => {
+ const loc = { projectCwd, userDataDir }
+ await saveWhiteboard(loc, 'whiteboard-1', sceneOf('start'))
+ const a = await readWhiteboard(loc, 'whiteboard-1')
+ const b = await readWhiteboard(loc, 'whiteboard-1')
+ expect(a?.rev).toBeTruthy()
+ expect(a?.rev).toBe(b?.rev)
+
+ const savedB = await saveWhiteboard(loc, 'whiteboard-1', sceneOf('b'), undefined, b!.rev)
+ expect(savedB).toMatchObject({ ok: true })
+ const savedA = await saveWhiteboard(loc, 'whiteboard-1', sceneOf('a'), undefined, a!.rev)
+ expect(savedA).toMatchObject({ ok: false, conflict: true, currentRev: (savedB as { rev: string }).rev })
+ expect(await onDisk()).toBe(sceneOf('b'))
+ })
+
+ it('a save returns the new revision, and saving again against it succeeds', async () => {
+ const loc = { projectCwd, userDataDir }
+ const first = await saveWhiteboard(loc, 'whiteboard-1', sceneOf('1'), undefined, null)
+ expect(first).toMatchObject({ ok: true })
+ const rev = (first as { rev: string }).rev
+ expect((await readWhiteboard(loc, 'whiteboard-1'))?.rev).toBe(rev)
+ expect(await saveWhiteboard(loc, 'whiteboard-1', sceneOf('2'), undefined, rev)).toMatchObject({ ok: true })
+ expect(await onDisk()).toBe(sceneOf('2'))
+ })
+
+ it('a null revision means "I have no board of my own": one that appeared meanwhile is kept', async () => {
+ const loc = { projectCwd, userDataDir }
+ await saveWhiteboard(loc, 'whiteboard-1', sceneOf('theirs'))
+ expect(await saveWhiteboard(loc, 'whiteboard-1', sceneOf('mine'), undefined, null)).toMatchObject({
+ ok: false,
+ conflict: true
+ })
+ expect(await onDisk()).toBe(sceneOf('theirs'))
+ })
+
+ it('the revision changes on every write, even a same-size rewrite in the same millisecond', async () => {
+ const loc = { projectCwd, userDataDir }
+ const revs = new Set<string>()
+ for (const tag of ['aa', 'bb', 'cc']) {
+ const saved = await saveWhiteboard(loc, 'whiteboard-1', sceneOf(tag))
+ revs.add((saved as { rev: string }).rev)
+ }
+ expect(revs.size).toBe(3)
+ })
+
+ it('two saves racing in one core are serialized: exactly one of them wins', async () => {
+ const loc = { projectCwd, userDataDir }
+ const start = await saveWhiteboard(loc, 'whiteboard-1', sceneOf('start'))
+ const rev = (start as { rev: string }).rev
+ const results = await Promise.all([
+ saveWhiteboard(loc, 'whiteboard-1', sceneOf('x'), undefined, rev),
+ saveWhiteboard(loc, 'whiteboard-1', sceneOf('y'), undefined, rev)
+ ])
+ expect(results.filter((r) => r && 'ok' in r && r.ok)).toHaveLength(1)
+ expect(results.filter((r) => r && 'conflict' in r)).toHaveLength(1)
+ })
+
+ it('no revision at all (an older caller) keeps the unconditional write', async () => {
+ const loc = { projectCwd, userDataDir }
+ await saveWhiteboard(loc, 'whiteboard-1', sceneOf('one'))
+ expect(await saveWhiteboard(loc, 'whiteboard-1', sceneOf('two'))).toMatchObject({ ok: true })
+ expect(await onDisk()).toBe(sceneOf('two'))
+ })
+})
diff --git a/src/core/whiteboards.ts b/src/core/whiteboards.ts
index 083fd6d02..cfef00823 100644
--- a/src/core/whiteboards.ts
+++ b/src/core/whiteboards.ts
@@ -30,12 +30,12 @@ import { isAbsolute, join, relative, sep } from 'path'
import { renameAtomic, tempNameFor, writeFileAtomic } from './fs-atomic'
import { readRegularFileBytesNoFollow } from './read-regular-file'
import { isSafeNodeId } from '../shared/safe-id'
-import type { WhiteboardFile } from '../shared/whiteboard'
+import type { WhiteboardFile, WhiteboardSaveResult } from '../shared/whiteboard'
/** `isSafeNodeId` alone would pass a NUMBER (its regex coerces it); these arrive over IPC. */
const safeId = (id: unknown): id is string => typeof id === 'string' && isSafeNodeId(id)
-export type { WhiteboardFile }
+export type { WhiteboardFile, WhiteboardSaveResult }
export const projectWhiteboardsDir = (projectCwd: string): string =>
join(projectCwd, '.nodeterm', 'whiteboards')
@@ -120,21 +120,59 @@ async function candidateDirs(loc: WhiteboardLocation, write: boolean): Promise<s
return dirs
}
+/** The revision of this node's OWN board — the file `readWhiteboard` would answer for it — or null
+ * when it has none. Stat only: the scene is not read. */
+async function ownRev(dirs: string[], nodeId: string): Promise<string | null> {
+ for (const dir of dirs) {
+ const st = await readRegularFileBytesNoFollow(join(dir, `${nodeId}.excalidraw`), WHITEBOARD_SCENE_MAX_BYTES, {
+ read: false
+ })
+ if (st) return st.stamp
+ }
+ return null
+}
+
+/**
+ * One save at a time per board in this process, so a compare-and-set can never interleave with
+ * another save of the same board in the same core. Two CORES writing one folder (a desktop and a
+ * Server Edition on the same project) can still interleave between the check and the rename; that
+ * window is a stat and a rename long.
+ */
+const savesInFlight = new Map<string, Promise<unknown>>()
+function oneSaveAtATime<T>(key: string, run: () => Promise<T>): Promise<T> {
+ const next = (savesInFlight.get(key) ?? Promise.resolve()).then(run, run)
+ const tail = next.catch(() => undefined)
+ savesInFlight.set(key, tail)
+ void tail.then(() => {
+ if (savesInFlight.get(key) === tail) savesInFlight.delete(key)
+ })
+ return next
+}
+
/**
- * Write a board's scene (and optionally its picture). Resolves the scene's absolute path, or null
- * when the input is refused (bad id, over the cap) or no folder would take it. Never throws: the
- * caller keeps the board open and says the save failed — a drawing that silently was not saved is
- * the failure this must not have. The project folder is tried first; a read-only checkout or a
- * `.nodeterm` that is a file falls back to the app folder, like a canvas image.
+ * Write a board's scene (and optionally its picture). Resolves `{ok: true, path, rev}`, a conflict
+ * (below), or null when the input is refused (bad id, over the cap) or no folder would take it.
+ * Never throws: the caller keeps the board open and says the save failed — a drawing that silently
+ * was not saved is the failure this must not have. The project folder is tried first; a read-only
+ * checkout or a `.nodeterm` that is a file falls back to the app folder, like a canvas image.
+ *
+ * **Compare-and-set.** `expectedRev` is the revision the editor last read or wrote (`null`: it has
+ * no board of its own yet — a new board, or a copy still showing its source). When the board on
+ * disk is not that revision, nothing is written and the answer is `{conflict: true, currentRev}`:
+ * someone else saved it meanwhile, and replacing their whole board with ours is exactly the loss
+ * this exists to prevent. `undefined` (a caller that sends no revision — a renderer on an older
+ * build reaching this core over a relay) keeps the unconditional write.
*/
export async function saveWhiteboard(
loc: WhiteboardLocation,
nodeId: string,
scene: string,
- thumbnailBase64?: string
-): Promise<string | null> {
+ thumbnailBase64?: string,
+ expectedRev?: string | null
+): Promise<WhiteboardSaveResult | null> {
if (!safeId(nodeId)) return null
if (typeof scene !== 'string' || Buffer.byteLength(scene) > WHITEBOARD_SCENE_MAX_BYTES) return null
+ if (expectedRev !== undefined && expectedRev !== null && typeof expectedRev !== 'string') return null
let thumb: Buffer | undefined
if (typeof thumbnailBase64 === 'string' && thumbnailBase64.length) {
// Measure the ENCODED length first: decoding a hostile 2 GB string is the allocation the cap
@@ -143,22 +181,29 @@ export async function saveWhiteboard(
thumb = Buffer.from(thumbnailBase64, 'base64')
if (thumb.length > WHITEBOARD_THUMB_MAX_BYTES) return null
}
- for (const dir of await candidateDirs(loc, true)) {
- try {
- await fs.mkdir(dir, { recursive: true })
- const scenePath = join(dir, `${nodeId}.excalidraw`)
- await writeFileAtomic(scenePath, scene)
- // The picture is best-effort: a board whose scene saved but whose picture did not is still
- // a saved board (the node re-renders the picture the next time it is opened).
- if (thumb) await writeBytesAtomic(join(dir, `${nodeId}.png`), thumb).catch(() => undefined)
- // An empty string means the board is empty now: drop the old picture instead of showing it.
- else if (thumbnailBase64 === '') await fs.rm(join(dir, `${nodeId}.png`), { force: true }).catch(() => undefined)
- return scenePath
- } catch {
- // try the next folder
+ return oneSaveAtATime(JSON.stringify([loc.userDataDir, loc.projectCwd ?? '', nodeId]), async () => {
+ if (expectedRev !== undefined) {
+ const currentRev = await ownRev(await candidateDirs(loc, false), nodeId)
+ if (currentRev !== expectedRev) return { ok: false as const, conflict: true as const, currentRev }
}
- }
- return null
+ for (const dir of await candidateDirs(loc, true)) {
+ try {
+ await fs.mkdir(dir, { recursive: true })
+ const scenePath = join(dir, `${nodeId}.excalidraw`)
+ await writeFileAtomic(scenePath, scene)
+ // The picture is best-effort: a board whose scene saved but whose picture did not is still
+ // a saved board (the node re-renders the picture the next time it is opened).
+ if (thumb) await writeBytesAtomic(join(dir, `${nodeId}.png`), thumb).catch(() => undefined)
+ // An empty string means the board is empty now: drop the old picture instead of showing it.
+ else if (thumbnailBase64 === '') await fs.rm(join(dir, `${nodeId}.png`), { force: true }).catch(() => undefined)
+ const written = await readRegularFileBytesNoFollow(scenePath, WHITEBOARD_SCENE_MAX_BYTES, { read: false })
+ return { ok: true as const, path: scenePath, rev: written?.stamp ?? '' }
+ } catch {
+ // try the next folder
+ }
+ }
+ return null
+ })
}
/**
@@ -180,7 +225,8 @@ async function readIn(
return {
scene: scene.bytes?.toString('utf8'),
thumbnailBase64: png?.bytes?.toString('base64'),
- updatedAt: scene.mtimeMs
+ updatedAt: scene.mtimeMs,
+ rev: scene.stamp
}
}
return null
diff --git a/src/preload/index.ts b/src/preload/index.ts
index fee8a4fcb..3bd42eadb 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -482,8 +482,8 @@ const api: NodeTerminalApi = {
ipcRenderer.invoke(IPC.filesSaveUpload, name, dataBase64),
saveCanvasImage: (projectId: string, name: string, dataBase64: string) =>
ipcRenderer.invoke(IPC.filesSaveCanvasImage, projectId, name, dataBase64),
- saveWhiteboard: (projectId: string, nodeId: string, scene: string, thumbnailBase64?: string) =>
- ipcRenderer.invoke(IPC.filesSaveWhiteboard, projectId, nodeId, scene, thumbnailBase64),
+ saveWhiteboard: (projectId: string, nodeId: string, scene: string, thumbnailBase64?: string, expectedRev?: string | null) =>
+ ipcRenderer.invoke(IPC.filesSaveWhiteboard, projectId, nodeId, scene, thumbnailBase64, expectedRev),
readWhiteboard: (projectId: string, nodeId: string, sourceId?: string, withScene?: boolean) =>
ipcRenderer.invoke(IPC.filesReadWhiteboard, projectId, nodeId, sourceId, withScene),
saveAlertSound: (kind: AlertSoundKind, name: string, dataBase64: string) =>
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 06b4ac90f..6f6c50898 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -85,7 +85,7 @@ import {
import type { PeerIdentity } from '../../shared/presence'
import type { PaneOwner } from '../../shared/agents/pane-owner-predicate'
import type { LaunchIntentExecutionResult } from '../../shared/types'
-import type { WhiteboardFile } from '../../shared/whiteboard'
+import type { WhiteboardFile, WhiteboardSaveResult } from '../../shared/whiteboard'
import { fitsOneWsFrame } from '../../shared/ws-frame'
import { buildStubApi, unsupported } from './stubs'
import { sanitizeStationNotices } from '@shared/station-notice'
@@ -693,10 +693,10 @@ export function buildFilesApi(
// The server closes the WHOLE socket (code 1009) on a client frame over WS_MAX_PAYLOAD, so a
// board too big for one frame is refused here, before sending — the node shows "Not saved"
// instead of the browser tab losing its connection to every terminal.
- saveWhiteboard: (projectId, nodeId, scene, thumbnailBase64) =>
- fitsOneWsFrame([projectId, nodeId, scene, thumbnailBase64])
- ? (client.request(IPC.filesSaveWhiteboard, projectId, nodeId, scene, thumbnailBase64) as Promise<
- string | null
+ saveWhiteboard: (projectId, nodeId, scene, thumbnailBase64, expectedRev) =>
+ fitsOneWsFrame([projectId, nodeId, scene, thumbnailBase64, expectedRev])
+ ? (client.request(IPC.filesSaveWhiteboard, projectId, nodeId, scene, thumbnailBase64, expectedRev) as Promise<
+ WhiteboardSaveResult | string | null
>)
: Promise.resolve(null),
readWhiteboard: (projectId, nodeId, sourceId, withScene) =>
diff --git a/src/renderer/nodes/WhiteboardNode.test.tsx b/src/renderer/nodes/WhiteboardNode.test.tsx
new file mode 100644
index 000000000..ee4164355
--- /dev/null
+++ b/src/renderer/nodes/WhiteboardNode.test.tsx
@@ -0,0 +1,157 @@
+// @vitest-environment jsdom
+//
+// The whiteboard node's own decisions, with the real component: what it sends when it saves, what
+// it shows when a save fails or is refused. The live editor (Excalidraw) is replaced by a stub that
+// records the props the node hands it — the node is what decides those, and the editor's own logic
+// has its own test (whiteboard/WhiteboardEditor.test.tsx).
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ReactFlowProvider, type NodeProps } from '@xyflow/react'
+import type { CanvasNode } from '../state/workspace'
+import type { WhiteboardFile } from '@shared/whiteboard'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+// jsdom has none; the node only uses it to follow its own box while editing.
+;(globalThis as { ResizeObserver?: unknown }).ResizeObserver ??= class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+interface EditorProps {
+ initialScene: string | undefined
+ readOnly?: boolean
+ onSave: (scene: string, thumbnailBase64?: string) => Promise<boolean>
+ onExit: (changed: boolean) => void
+}
+const editor: { props: EditorProps | null } = { props: null }
+vi.mock('../whiteboard/WhiteboardEditor', () => ({
+ default: (props: EditorProps) => {
+ editor.props = props
+ return <div data-testid="editor" />
+ }
+}))
+
+const files = {
+ readWhiteboard: vi.fn<(...a: unknown[]) => Promise<WhiteboardFile | null>>(),
+ saveWhiteboard: vi.fn<(...a: unknown[]) => Promise<unknown>>()
+}
+vi.mock('../session/session', () => ({
+ useSession: () => ({ id: 'local', source: 'local', api: { files } })
+}))
+
+import { WhiteboardNode } from './WhiteboardNode'
+import { useProjects } from '../state/projects'
+
+const SCENE = JSON.stringify({ type: 'excalidraw', elements: [] })
+
+let host: HTMLDivElement
+let root: Root
+
+function mount(data: Partial<CanvasNode['data']> = {}) {
+ host = document.createElement('div')
+ // The overlay is portaled into `.canvas-root` and clipped to `.flow-wrap`; the node finds both
+ // by ancestry before it mounts an editor.
+ host.className = 'canvas-root'
+ const wrap = document.createElement('div')
+ wrap.className = 'flow-wrap'
+ host.append(wrap)
+ document.body.append(host)
+ root = createRoot(wrap)
+ const props = {
+ id: 'whiteboard-1',
+ data: { title: 'Whiteboard', color: '#64d2ff', group: null, ...data },
+ selected: false,
+ positionAbsoluteX: 0,
+ positionAbsoluteY: 0,
+ width: 900,
+ height: 600
+ } as unknown as NodeProps<CanvasNode>
+ act(() =>
+ root.render(
+ <ReactFlowProvider>
+ <WhiteboardNode {...props} />
+ </ReactFlowProvider>
+ )
+ )
+}
+
+/** Let the picture read, the scene read and the lazy editor chunk all settle. */
+const settle = () => act(async () => {
+ for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0))
+})
+
+async function openEditor(): Promise<EditorProps> {
+ await settle()
+ const body = host.querySelector('.whiteboard-node__body')!
+ act(() => {
+ body.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }))
+ })
+ await settle()
+ expect(editor.props).not.toBeNull()
+ return editor.props!
+}
+
+beforeEach(() => {
+ editor.props = null
+ files.readWhiteboard.mockReset()
+ files.saveWhiteboard.mockReset()
+ useProjects.setState({ activeProjectId: 'p1' })
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+})
+
+describe('saving sends the revision the editor started from', () => {
+ it('sends the loaded revision, then the one each save returns', async () => {
+ files.readWhiteboard.mockResolvedValue({ scene: SCENE, updatedAt: 1, rev: 'r1', fromSource: false })
+ files.saveWhiteboard
+ .mockResolvedValueOnce({ ok: true, path: '/p/whiteboard-1.excalidraw', rev: 'r2' })
+ .mockResolvedValueOnce({ ok: true, path: '/p/whiteboard-1.excalidraw', rev: 'r3' })
+ mount()
+ const props = await openEditor()
+ await act(async () => void (await props.onSave(SCENE)))
+ expect(files.saveWhiteboard.mock.calls[0]?.[4]).toBe('r1')
+ await act(async () => void (await props.onSave(SCENE)))
+ expect(files.saveWhiteboard.mock.calls[1]?.[4]).toBe('r2')
+ })
+
+ it('a copy still showing its source saves as "no board of my own yet" (null)', async () => {
+ files.readWhiteboard.mockResolvedValue({ scene: SCENE, updatedAt: 1, rev: 'src-rev', fromSource: true })
+ files.saveWhiteboard.mockResolvedValue({ ok: true, path: '/p/whiteboard-1.excalidraw', rev: 'r1' })
+ mount({ whiteboardSource: 'whiteboard-0' })
+ const props = await openEditor()
+ await act(async () => void (await props.onSave(SCENE)))
+ expect(files.saveWhiteboard.mock.calls[0]?.[4]).toBeNull()
+ })
+
+ it('a refused save (someone else saved meanwhile) is a failure the header names', async () => {
+ files.readWhiteboard.mockResolvedValue({ scene: SCENE, updatedAt: 1, rev: 'r1', fromSource: false })
+ files.saveWhiteboard.mockResolvedValue({ ok: false, conflict: true, currentRev: 'r9' })
+ mount()
+ const props = await openEditor()
+ let saved: boolean | undefined
+ await act(async () => {
+ saved = await props.onSave(SCENE)
+ })
+ expect(saved).toBe(false)
+ expect(host.querySelector('.whiteboard-node__save-failed')?.textContent).toMatch(/changed elsewhere/i)
+ })
+
+ it('a core on an older build (bare path answer, no revision) still counts as saved', async () => {
+ files.readWhiteboard.mockResolvedValue({ scene: SCENE, updatedAt: 1, fromSource: false })
+ files.saveWhiteboard.mockResolvedValue('/p/whiteboard-1.excalidraw')
+ mount()
+ const props = await openEditor()
+ let saved: boolean | undefined
+ await act(async () => {
+ saved = await props.onSave(SCENE)
+ })
+ expect(saved).toBe(true)
+ expect(files.saveWhiteboard.mock.calls[0]?.[4]).toBeUndefined()
+ expect(host.querySelector('.whiteboard-node__save-failed')).toBeNull()
+ })
+})
diff --git a/src/renderer/nodes/WhiteboardNode.tsx b/src/renderer/nodes/WhiteboardNode.tsx
index 8cc5772aa..f012c78c9 100644
--- a/src/renderer/nodes/WhiteboardNode.tsx
+++ b/src/renderer/nodes/WhiteboardNode.tsx
@@ -77,8 +77,15 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
const [geom, setGeom] = useState<Geometry | null>(null)
const [thumb, setThumb] = useState<string>()
const sceneRef = useRef<string | undefined>(undefined)
+ // The revision of the board file this editing session started from, then of each save it made —
+ // what every save sends, so the core can refuse one made over somebody else's newer board
+ // (core/whiteboards.ts, compare-and-set). `null`: this node has no board of its own yet (a new
+ // board, or a copy still showing its source). `undefined`: unknown (a core on an older build
+ // reports none), and the save is then not checked.
+ const revRef = useRef<string | null | undefined>(undefined)
const [loadState, setLoadState] = useState<'loading' | 'ready' | 'unreadable'>('loading')
- const [saveFailed, setSaveFailed] = useState(false)
+ // `conflict`: the core refused the last save because someone else saved this board meanwhile.
+ const [saveState, setSaveState] = useState<'saved' | 'failed' | 'conflict'>('saved')
const [copied, setCopied] = useState(false)
const maximizedByPresentRef = useRef(false)
const viewKey = useStore(transformKey)
@@ -139,14 +146,20 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
const save = useCallback(
async (scene: string, thumbnailBase64?: string): Promise<boolean> => {
- const path = await Promise.resolve()
- .then(() => api.files.saveWhiteboard(projectIdRef.current, id, scene, thumbnailBase64))
+ const res = await Promise.resolve()
+ .then(() => api.files.saveWhiteboard(projectIdRef.current, id, scene, thumbnailBase64, revRef.current))
.catch(() => null)
- if (!path) {
- setSaveFailed(true)
+ if (!res) {
+ setSaveState('failed')
return false
}
- setSaveFailed(false)
+ if (typeof res === 'object' && !res.ok) {
+ setSaveState('conflict')
+ return false
+ }
+ // A core on an older build answers the bare path and no revision: the next save goes unchecked.
+ revRef.current = typeof res === 'string' ? undefined : res.rev
+ setSaveState('saved')
sceneRef.current = scene
if (thumbnailBase64 !== undefined) setThumb(thumbnailBase64 ? pngDataUrl(thumbnailBase64) : undefined)
// A copy has its own file now; it stops reading the original's.
@@ -179,6 +192,8 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
}
}
sceneRef.current = file?.scene
+ revRef.current = !file || file.fromSource ? null : file.rev
+ setSaveState('saved')
if (next === 'present' && !dataRef.current.premaxRect) {
setMaximized(false)
maximizedByPresentRef.current = true
@@ -243,13 +258,17 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
spellCheck={false}
onChange={(e) => updateNodeData(id, { title: e.target.value })}
/>
- {saveFailed && (
+ {saveState !== 'saved' && (
<span
className="whiteboard-node__save-failed"
role="status"
- title="The last change could not be written. The board stays open; it retries on the next change."
+ title={
+ saveState === 'conflict'
+ ? 'Someone else saved this board while it was open here (another tab, another computer on this folder, or a teammate). Their version was kept; your changes are not saved.'
+ : 'The last change could not be written. The board stays open; it retries on the next change.'
+ }
>
- Not saved
+ {saveState === 'conflict' ? 'Changed elsewhere' : 'Not saved'}
</span>
)}
<span className="term-node__spacer" />
diff --git a/src/shared/types.ts b/src/shared/types.ts
index e8c82f8aa..fc2e2edd2 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,7 +1,7 @@
import type { ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from './text-delivery'
import type { PushWebhookMinted, PushWebhookResult, PushWebhookTokenInfo } from './push-webhook'
import type { IdentitySeedEntry } from './agent-identity-seed'
-import type { WhiteboardFile } from './whiteboard'
+import type { WhiteboardFile, WhiteboardSaveResult } from './whiteboard'
import type { PrWaitHold } from './pr-wait'
import type { SessionBackend } from './session-backend'
import type { AgentIntegrationsSettings } from './agent-integrations'
@@ -1676,10 +1676,18 @@ export interface FilesApi {
saveCanvasImage(projectId: string, name: string, dataBase64: string): Promise<string | null>
/**
* Save a whiteboard node's scene (Excalidraw JSON) and the picture it shows at rest. The core
- * derives the file from (projectId, nodeId) — beside project.json, or its own data dir — and
- * resolves its absolute path, or null when it could not be written. See core/whiteboards.ts.
+ * derives the file from (projectId, nodeId) — beside project.json, or its own data dir. Resolves
+ * `{ok: true, path, rev}`, a conflict when the board on disk is no longer `expectedRev` (nothing
+ * written), or null when it could not be written. A core on an older build answers the bare path
+ * string and ignores `expectedRev`. See core/whiteboards.ts.
*/
- saveWhiteboard(projectId: string, nodeId: string, scene: string, thumbnailBase64?: string): Promise<string | null>
+ saveWhiteboard(
+ projectId: string,
+ nodeId: string,
+ scene: string,
+ thumbnailBase64?: string,
+ expectedRev?: string | null
+ ): Promise<WhiteboardSaveResult | string | null>
/** Read a whiteboard back; `sourceId` is the board a copied node falls back to until it saves.
* `withScene: false` reads only the picture and revision (a board at rest). */
readWhiteboard(projectId: string, nodeId: string, sourceId?: string, withScene?: boolean): Promise<WhiteboardFile | null>
diff --git a/src/shared/whiteboard.ts b/src/shared/whiteboard.ts
index d59646b30..4efea211e 100644
--- a/src/shared/whiteboard.ts
+++ b/src/shared/whiteboard.ts
@@ -4,8 +4,25 @@ export interface WhiteboardFile {
scene?: string
/** The PNG the node shows at rest, base64; absent when none was saved. */
thumbnailBase64?: string
- /** Epoch ms of the scene's last write — the board's revision as far as readers care. */
+ /** Epoch ms of the scene's last write. Display only: two writes can share one. */
updatedAt: number
+ /**
+ * The scene file's revision (an opaque token that changes on every write). A save names the
+ * revision its editor last read or wrote, and is refused when the file has moved on since. Absent
+ * from a host on an older build — a save then carries none and is not checked.
+ */
+ rev?: string
/** True when this came from the source board because the node has none of its own yet. */
fromSource: boolean
}
+
+/**
+ * What a save answered. `null` (outside this type) still means "refused or could not be written".
+ * A conflict means the board on disk is not the revision this editor started from: another editor
+ * (a second tab, another machine on the same folder, a teammate, a `git pull`) wrote it meanwhile,
+ * and nothing was written. `currentRev` is the revision now on disk (null: there is no board of
+ * this node's own any more), so the editor can choose to overwrite it knowingly.
+ */
+export type WhiteboardSaveResult =
+ | { ok: true; path: string; rev: string }
+ | { ok: false; conflict: true; currentRev: string | null }