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(canvas-sync): cast own writes into an off-screen governed project (N2)

reviewdb14edc21c45
diff --git a/CLAUDE.md b/CLAUDE.md
index 6e4c05c49..40e3f7307 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -7377,7 +7377,12 @@ The invariants, each with its reason:
(`applyMutationToFlow`), because a trip through the serializers would wipe the selection; live
edge ops go through the reducer's own edge applier, `applyEdgeMutationToScene`. THIS renderer's
own node writes into a background project are not received ops and take `applyOwnNodeMutation`
- (unstripped: the held launch is ours to set or clear — see the `pendingLaunch` paragraph).
+ (unstripped: the held launch is ours to set or clear — see the `pendingLaunch` paragraph). **The
+ node publisher never casts them** (it diffs React Flow, and a load is ADOPTED as its baseline), so
+ that store path and `appendCanvasLinks` hand every write to `setStoredCanvasPublishHook`, which
+ Canvas casts only for a GOVERNED project that is not the one React Flow holds
+ (`canvas/stored-publish.ts`): without it a ⌘⇧T reopen or a cold open into an off-screen shared
+ project was dropped from disk by the next overlaid save. An ungoverned project casts nothing new.
- **The solo-gate trap.** The publisher casts nothing while no teammate is attached, and on a governed
project that loses every edit. The gate is `shouldPublishFor` = `(hasPeers || governed) && sameCore
&& !readOnly`: a Server Edition tab publishes every project until its first `canvas:authority`
diff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.md
index 4e6f58421..5bb0cce37 100644
--- a/docs/hosted-team-relay.md
+++ b/docs/hosted-team-relay.md
@@ -334,7 +334,11 @@ whole-workspace saves still write them.
1. **Ops**: from Editors' hosted tabs, from the server's own browser tabs, and from server canvas
control, which diffs everything a verb changed and casts each op before it saves (`castAndSave`,
- `src/server/headless-node-factory.ts`).
+ `src/server/headless-node-factory.ts`). A tab also casts what it writes into a governed project
+ it is not showing (a ⌘⇧T or "Recently closed" reopen, a cold open, an off-canvas node or link):
+ those writes go to its projects store, not its canvas, so the store hands each one to the publish
+ hook (`src/renderer/canvas/stored-publish.ts`). Without the cast the next overlaid save would
+ drop them.
2. **Saves.** Before a whole-workspace save is written, a governed project's content is replaced by
the authority's (`overlaySave`). The board is overlaid field by field: its items (columns, cards,
metadata, labels, views) come from the authority, `github` and `pullLinks` from the save. This
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 989040db3..e4c285963 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -405,7 +405,7 @@ import {
shouldShowExplorerPinHint,
writeSeenExplorerPinHint
} from '../lib/explorerPinHint'
-import { setKanbanPublishHook, useProjects } from '../state/projects'
+import { setKanbanPublishHook, setStoredCanvasPublishHook, useProjects } from '../state/projects'
import { useAgentStatus, recordsTurnInterrupt } from '../state/agentStatus'
import { hostChatSend, hostChatSession, hostChatStatus } from '../lib/hostChatQuery'
import { chatPaneRefusal } from '../lib/chatPaneGate'
@@ -652,6 +652,7 @@ import { snapResizeChanges } from '../lib/resizeSnap'
import { canClearDirty, canCommitCanvas, canCreateOnCanvas, liveCanvasHolds } from '../state/persistGuards'
import { rebaseOnLatest, useNodesEpoch } from './nodesEpoch'
import { boardLiveNodeIds, createKanbanPublisher } from './kanban-sync'
+import { createStoredCanvasPublisher } from './stored-publish'
import { isHidden } from '../lib/ui-visibility'
import { boardLogEvents } from '../lib/boardLogDiff'
import { useBoardLog } from '../state/boardLog'
@@ -3973,8 +3974,21 @@ export function Canvas() {
applyLocal: (projectId, m) => applyToStored(projectId, m)
})
setKanbanPublishHook((id, prev, next) => kanbanPublisher.publish(id, prev, next))
+ // Own node/edge writes into a project that is NOT on screen (a ⌘⇧T reopen, a cold open, an
+ // off-canvas display node, a headless launch patch) reach the store only, never React Flow, so
+ // the node publisher above never casts them — and a governed project's save overlay would drop
+ // them from disk (canvas/stored-publish.ts). Same cast, same gate.
+ setStoredCanvasPublishHook(
+ createStoredCanvasPublisher({
+ renderedProjectId: () => nodesProjectIdRef.current,
+ isGoverned: (projectId) => governedRef.current.has(projectId),
+ shouldPublish: (projectId) => shouldPublishFor(projectId),
+ send: (projectId, m) => castFor(projectId, m)
+ })
+ )
return () => {
setKanbanPublishHook(null)
+ setStoredCanvasPublishHook(null)
unsub()
governed.release()
pub.dispose()
diff --git a/src/renderer/canvas/stored-publish.test.ts b/src/renderer/canvas/stored-publish.test.ts
new file mode 100644
index 000000000..aee073665
--- /dev/null
+++ b/src/renderer/canvas/stored-publish.test.ts
@@ -0,0 +1,133 @@
+// N2: a node or edge THIS renderer writes into a project that is not on screen (⌘⇧T / "Recently
+// closed" reopen, a cold open, an off-canvas display node, a headless start's launch patch) goes
+// through the projects store, never React Flow — so the node publisher never casts it, and on a
+// governed project the canvas authority's save overlay dropped it from disk. The store now hands
+// every such write to one hook, and Canvas casts it through the same gate as everything else.
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import { setStoredCanvasPublishHook, useProjects } from '../state/projects'
+import { createStoredCanvasPublisher } from './stored-publish'
+import { applyCanvasOp, contentOf } from '@shared/canvas-content'
+import { sanitizeInboundMutation } from '@shared/node-exec'
+import type { CanvasMutation, CanvasNodeState, Project } from '@shared/types'
+
+const node = (id: string, x = 0, over: Partial<CanvasNodeState> = {}): CanvasNodeState => ({
+ id,
+ kind: 'terminal',
+ position: { x, y: 0 },
+ size: { width: 480, height: 320 },
+ title: id,
+ color: '#fff',
+ group: '',
+ ...over
+})
+
+const project = (id: string, nodes: CanvasNodeState[]): Project => ({
+ id,
+ name: id,
+ color: '#0a84ff',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes
+})
+
+interface Wiring {
+ casts: Array<[string, CanvasMutation]>
+ rendered: string | null
+ governed: Set<string>
+ gateOpen: boolean
+}
+
+function wire(): Wiring {
+ const w: Wiring = { casts: [], rendered: 'A', governed: new Set(['G']), gateOpen: true }
+ setStoredCanvasPublishHook(
+ createStoredCanvasPublisher({
+ renderedProjectId: () => w.rendered,
+ isGoverned: (id) => w.governed.has(id),
+ shouldPublish: () => w.gateOpen,
+ send: (id, m) => {
+ w.casts.push([id, m])
+ return true
+ }
+ })
+ )
+ return w
+}
+
+beforeEach(() => {
+ useProjects.getState().hydrate({
+ version: 2,
+ activeProjectId: 'A',
+ projects: [project('A', [node('a1')]), project('G', [node('g1')]), project('U', [node('u1')])]
+ })
+})
+
+afterEach(() => {
+ setStoredCanvasPublishHook(null)
+})
+
+describe('own writes into a stored project are cast (N2)', () => {
+ it('a reopen into an off-screen GOVERNED project casts the upsert, and the authority holds it', () => {
+ const w = wire()
+ // What ⌘⇧T's `insertStored` does for a project that is not on screen.
+ const reopened = node('g2', 300, { pendingLaunch: { after: [], command: 'claude' } })
+ useProjects.getState().applyOwnNodeMutation('G', { op: 'upsert', node: reopened })
+ expect(w.casts).toEqual([['G', { op: 'upsert', node: reopened }]])
+
+ // The authority hears the cast (the reflector hands it on without the launch) and folds it into
+ // its content through the one reducer, so its save overlay now carries the node instead of
+ // dropping it (the core half is pinned in canvas-authority.test.ts).
+ let authority = contentOf(project('G', [node('g1')]))
+ for (const [id, m] of w.casts) authority = applyCanvasOp(authority, sanitizeInboundMutation(m), id)
+ expect(authority.nodes.map((n) => n.id)).toEqual(['g1', 'g2'])
+ expect(authority.nodes.find((n) => n.id === 'g2')?.pendingLaunch).toBeUndefined()
+ })
+
+ it('a link appended to an off-screen governed project casts each NEW edge once', () => {
+ const w = wire()
+ const rope = { id: 'ctrl-a1-g1', source: 'a1', target: 'g1' }
+ const bridge = { id: 'bridge-g1-a1', source: 'g1', target: 'a1' }
+ useProjects.getState().appendCanvasLinks('G', { ropes: [rope], bridges: [bridge] })
+ expect(w.casts).toEqual([
+ ['G', { op: 'edge-upsert', kind: 'bridge', edge: bridge }],
+ ['G', { op: 'edge-upsert', kind: 'rope', edge: rope }]
+ ])
+ // A re-link is a no-op in the store, and casts nothing.
+ useProjects.getState().appendCanvasLinks('G', { ropes: [rope], bridges: [{ ...bridge, id: 'other-id' }] })
+ expect(w.casts).toHaveLength(2)
+ })
+
+ it('casts nothing where the gate is off: an unshared project, the rendered one, a closed gate', () => {
+ const w = wire()
+ // Unshared, even with a teammate attached (the gate itself open): byte-identical to before.
+ useProjects.getState().applyOwnNodeMutation('U', { op: 'upsert', node: node('u2') })
+ useProjects.getState().appendCanvasLinks('U', { ropes: [{ id: 'r', source: 'u1', target: 'u2' }] })
+ // The project React Flow holds belongs to the node publisher.
+ w.governed.add('A')
+ useProjects.getState().applyOwnNodeMutation('A', { op: 'upsert', node: node('a2') })
+ // The publish gate closed (a viewer, another core, or nobody to publish to).
+ w.gateOpen = false
+ useProjects.getState().applyOwnNodeMutation('G', { op: 'upsert', node: node('g3') })
+ expect(w.casts).toEqual([])
+ // The store writes themselves are unchanged.
+ expect(useProjects.getState().getProject('U')?.nodes.map((n) => n.id)).toEqual(['u1', 'u2'])
+ expect(useProjects.getState().getProject('G')?.nodes.map((n) => n.id)).toEqual(['g1', 'g3'])
+ })
+
+ it('with no hook registered (no Canvas bound), a store write casts nothing and still applies', () => {
+ useProjects.getState().applyOwnNodeMutation('G', { op: 'upsert', node: node('g4') })
+ expect(useProjects.getState().getProject('G')?.nodes.map((n) => n.id)).toEqual(['g1', 'g4'])
+ })
+
+ it('Canvas registers the hook in the publisher effect, behind its gate, and clears it on teardown', () => {
+ const src = fs.readFileSync(path.join(__dirname, 'Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')
+ const wiring = src.indexOf('setStoredCanvasPublishHook(\n createStoredCanvasPublisher(')
+ expect(wiring).toBeGreaterThan(-1)
+ const body = src.slice(wiring, wiring + 900)
+ expect(body).toMatch(/send: \(projectId, m\) => castFor\(projectId, m\)/)
+ expect(body).toMatch(/shouldPublish: \(projectId\) => shouldPublishFor\(projectId\)/)
+ expect(body).toMatch(/isGoverned: \(projectId\) => governedRef\.current\.has\(projectId\)/)
+ expect(body).toMatch(/renderedProjectId: \(\) => nodesProjectIdRef\.current/)
+ expect(src).toContain('setStoredCanvasPublishHook(null)')
+ })
+})
diff --git a/src/renderer/canvas/stored-publish.ts b/src/renderer/canvas/stored-publish.ts
new file mode 100644
index 000000000..3a76d451b
--- /dev/null
+++ b/src/renderer/canvas/stored-publish.ts
@@ -0,0 +1,40 @@
+// Casts the node and edge writes THIS renderer makes into a project's STORED copy — the projects
+// store's `applyOwnNodeMutation` / `appendCanvasLinks`, which call the store's publish hook
+// (`setStoredCanvasPublishHook`). The node publisher cannot: it diffs React Flow, and a stored
+// project's nodes enter React Flow only through a load, which it adopts as its baseline. So a ⌘⇧T
+// reopen, a cold open, an off-canvas display node or a headless start's launch patch into a project
+// that is not on screen was never cast, and on a project a Server Edition canvas authority governs
+// the next save overlay dropped it from disk (docs/hosted-team-relay.md).
+//
+// The rule lives here rather than in Canvas so it is tested without a canvas:
+// - ONLY A GOVERNED PROJECT. The authority is what drops an un-cast write; an ungoverned project's
+// stored write keeps riding the whole-file save exactly as before, so the desktop and every
+// unshared project cast nothing new, even with a teammate attached.
+// - NEVER THE PROJECT REACT FLOW HOLDS. That canvas is the node publisher's; a store write there is
+// a stale copy the next commit overwrites, and casting it would put a value on the wire this canvas
+// does not show. A project mid-switch (active, not yet installed) is still the store's, and its
+// load adopts what was cast here, so nothing is cast twice.
+// - THE SAME GATE AND THE SAME CAST as every other family (`shouldPublishFor`, `castFor`): the same
+// core, a role that may publish, the order's pending entry and the size guard. A held launch rides
+// the owner leg as usual.
+import type { StoredCanvasPublishHook } from '../state/projects'
+import type { CanvasMutation } from '@shared/types'
+
+export interface StoredCanvasPublisherDeps {
+ /** The project React Flow holds right now (the epoch tag), or null. */
+ renderedProjectId(): string | null
+ /** Is `projectId` governed by a canvas authority (Canvas's followed governed set)? */
+ isGoverned(projectId: string): boolean
+ /** Canvas's one publish gate for `projectId`. */
+ shouldPublish(projectId: string): boolean
+ /** Canvas's one cast. `false` = not cast. */
+ send(projectId: string, m: CanvasMutation): boolean
+}
+
+export function createStoredCanvasPublisher(deps: StoredCanvasPublisherDeps): StoredCanvasPublishHook {
+ return (projectId, m) => {
+ if (deps.renderedProjectId() === projectId) return
+ if (!deps.isGoverned(projectId) || !deps.shouldPublish(projectId)) return
+ deps.send(projectId, m)
+ }
+}
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 62e21ec6c..98a3c6684 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -422,6 +422,24 @@ export function setKanbanPublishHook(hook: KanbanPublishHook | null): void {
kanbanPublishHook = hook
}
+/**
+ * Publishes a node or edge write THIS renderer made into a project's STORED copy
+ * (`applyOwnNodeMutation`, `appendCanvasLinks`): a ⌘⇧T / "Recently closed" reopen into a project that
+ * is not on screen, a cold open, an off-canvas display node, a headless start's launch patch. The node
+ * publisher never sees these writes: it diffs React Flow, and a stored project's nodes enter React
+ * Flow only through a load, which it ADOPTS as its baseline rather than casting. On a project a
+ * Server Edition canvas authority governs that was data loss, because the save overlay replaces the
+ * stored content with what the authority heard as ops (docs/hosted-team-relay.md). Called AFTER the
+ * store write, once per op actually written. Same one-owner rule as the board hook: a peer's op is
+ * applied with `applyCanvasOp`, which never calls it, so nothing received is published again.
+ */
+export type StoredCanvasPublishHook = (projectId: string, m: CanvasMutation) => void
+let storedCanvasPublishHook: StoredCanvasPublishHook | null = null
+/** Canvas registers this once per core binding and clears it (`null`) on teardown. */
+export function setStoredCanvasPublishHook(hook: StoredCanvasPublishHook | null): void {
+ storedCanvasPublishHook = hook
+}
+
export const useProjects = create<ProjectsState>((set, get) => ({
projects: [],
activeProjectId: '',
@@ -630,7 +648,13 @@ export const useProjects = create<ProjectsState>((set, get) => ({
},
appendCanvasLinks(projectId, links) {
- const add = (existing: BridgeLink[] | undefined, incoming: BridgeLink[] | undefined) => {
+ // The edges actually appended, per kind: what the publish hook casts (a re-link casts nothing).
+ const added: { bridge: BridgeLink[]; rope: BridgeLink[] } = { bridge: [], rope: [] }
+ const add = (
+ kind: 'bridge' | 'rope',
+ existing: BridgeLink[] | undefined,
+ incoming: BridgeLink[] | undefined
+ ) => {
if (!incoming?.length) return existing
const kept = existing ?? []
const seenId = new Set(kept.map((e) => e.id))
@@ -642,15 +666,21 @@ export const useProjects = create<ProjectsState>((set, get) => ({
seenPair.add(pair)
return true
})
+ added[kind] = fresh
return fresh.length ? [...kept, ...fresh] : existing
}
+ const p = get().projects.find((x) => x.id === projectId)
+ if (!p) return
+ const next = {
+ ...p,
+ bridges: add('bridge', p.bridges, links.bridges),
+ ropes: add('rope', p.ropes, links.ropes)
+ }
set((s) => ({
- projects: s.projects.map((p) =>
- p.id === projectId
- ? { ...p, bridges: add(p.bridges, links.bridges), ropes: add(p.ropes, links.ropes) }
- : p
- )
+ projects: s.projects.map((x) => (x.id === projectId ? next : x))
}))
+ for (const kind of ['bridge', 'rope'] as const)
+ for (const edge of added[kind]) storedCanvasPublishHook?.(projectId, { op: 'edge-upsert', kind, edge })
},
applyCanvasOp(projectId, mutation) {
@@ -688,6 +718,8 @@ export const useProjects = create<ProjectsState>((set, get) => ({
applyOwnCanvasMutation(nodes, mutation)
)
}))
+ // A node op only: `applyOwnCanvasMutation` writes nothing for any other family.
+ if (mutation.op === 'upsert' || mutation.op === 'remove') storedCanvasPublishHook?.(projectId, mutation)
return true
},