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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(server): a canvas-control verb never writes back the copy it loaded before a launch
review673ab0fa618c
diff --git a/src/core/canvas-sync.convergence.test.ts b/src/core/canvas-sync.convergence.test.tsindex 0588cd1c6..51fa862a3 100644--- a/src/core/canvas-sync.convergence.test.ts+++ b/src/core/canvas-sync.convergence.test.ts@@ -1188,7 +1188,7 @@ describe('a solo client on a governed project (the canvas authority)', () => {}it('with the project governed, the solo edit reaches the authority and is written', async () => {- const { solo, writes, authority } = soloWithAuthority(() => shouldPublishCanvas({ hasPeers: false, governed: true }))+ const { solo, writes, authority } = soloWithAuthority(() => shouldPublishCanvas(false, new Set([PROJECT]), PROJECT))solo.edit([node('n1', 42)])solo.editEdges({ bridges: [{ id: 'e1', source: 'n1', target: 'n1' }] })bus.settle()@@ -1200,7 +1200,7 @@ describe('a solo client on a governed project (the canvas authority)', () => {})it('with the pre-authority gate (a peer only), nothing is cast and nothing is written', async () => {- const { solo, writes, authority } = soloWithAuthority(() => shouldPublishCanvas({ hasPeers: false, governed: false }))+ const { solo, writes, authority } = soloWithAuthority(() => shouldPublishCanvas(false, new Set<string>(), PROJECT))solo.edit([node('n1', 42)])bus.settle()await authority.flushAll()diff --git a/src/preload/index.test.ts b/src/preload/index.test.tsindex cc7dfbc46..795da90ac 100644--- a/src/preload/index.test.ts+++ b/src/preload/index.test.ts@@ -136,3 +136,16 @@ describe('preload sshProject passphrase wiring', () => {expect(h.removeListener).toHaveBeenCalledWith(IPC.sshPassphraseDismiss, handler)})})++describe('preload canvasAuthority (the desktop governs nothing)', () => {+ it('answers no project, never assumes any, and never asks main', async () => {+ h.invoke.mockClear()+ h.on.mockClear()+ expect(api.canvasAuthority.assumeAllUntilAnswered).toBe(false)+ expect(await api.canvasAuthority.governed()).toEqual([])+ const off = api.canvasAuthority.onChanged(() => {})+ expect(() => off()).not.toThrow()+ expect(h.invoke).not.toHaveBeenCalled()+ expect(h.on).not.toHaveBeenCalled()+ })+})diff --git a/src/preload/index.ts b/src/preload/index.tsindex 67bb7b9ef..827300856 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -541,6 +541,7 @@ const api: NodeTerminalApi = {// (docs/hosted-team-relay.md), and main registers no `canvas:authority` handler. A relay tab onto// such a host answers for itself (renderer/bridge/relay-api.ts).canvasAuthority: {+ assumeAllUntilAnswered: false,governed: async () => [],onChanged: () => () => {}},diff --git a/src/renderer/bridge/relay-api.test.ts b/src/renderer/bridge/relay-api.test.tsindex 16a2b26f5..d9f5901f5 100644--- a/src/renderer/bridge/relay-api.test.ts+++ b/src/renderer/bridge/relay-api.test.ts@@ -329,17 +329,20 @@ describe('buildRelayApi — canvasAuthority (which projects publish even when al// Its host governs everything it shares, and a hosted tab holds only shared projects.expect(await api.canvasAuthority.governed()).toEqual(['p-team'])expect(typeof api.canvasAuthority.onChanged(() => {})).toBe('function')+ // Answered from its own bindings, at once: nothing is assumed governed before that.+ expect(api.canvasAuthority.assumeAllUntilAnswered).toBe(false)expect(t.sent).toEqual([])})it('a Team Access tab governs nothing: its host (a desktop) runs no authority', async () => {const local = fakeLocalApi().local as unknown as Record<string, unknown>- local.canvasAuthority = { governed: async () => [], onChanged: () => () => {} }+ local.canvasAuthority = { assumeAllUntilAnswered: false, governed: async () => [], onChanged: () => () => {} };(globalThis as Record<string, unknown>).window = { nodeTerminal: local }const t = new FakeTransport()const { api } = buildRelayApi('conn-1', t)bindProjectToSession('p-peer', createSession('relay', api, 'Peer').id)expect(await api.canvasAuthority.governed()).toEqual([])+ expect(api.canvasAuthority.assumeAllUntilAnswered).toBe(false)expect(t.sent).toEqual([])})})diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.tsindex 5f96ddcee..45dd360b0 100644--- a/src/renderer/bridge/relay-api.ts+++ b/src/renderer/bridge/relay-api.ts@@ -204,6 +204,8 @@ export function buildRelayApi(// binding already holds). A Team Access tab's host is a desktop, which governs nothing: `local`.canvasAuthority: hosted? {+ // Answered at once from the bindings, so nothing needs to be assumed before it.+ assumeAllUntilAnswered: false,governed: async () => projectIdsBoundToApi(api),// The set changes only when a tab binds or unbinds, and Canvas re-reads it on every bind.onChanged: () => () => {}diff --git a/src/renderer/bridge/stubs.test.ts b/src/renderer/bridge/stubs.test.tsindex b8451dec4..6ea78d9c3 100644--- a/src/renderer/bridge/stubs.test.ts+++ b/src/renderer/bridge/stubs.test.ts@@ -224,3 +224,12 @@ describe('bridge clipboard', () => {expect(ev.detail.message).toMatch(/copy/i)})})++describe('bridge stubs: canvasAuthority', () => {+ it('governs nothing and assumes nothing by default (only the Server Edition bridge overrides it)', async () => {+ const s = buildStubApi()+ expect(s.canvasAuthority.assumeAllUntilAnswered).toBe(false)+ expect(await s.canvasAuthority.governed()).toEqual([])+ expect(typeof s.canvasAuthority.onChanged(() => {})).toBe('function')+ })+})diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 953869fb5..4e4b8e16d 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -593,6 +593,7 @@ export function buildStubApi(): Omit<// Governs nothing by default. The Server Edition overrides it with the real bridge// (`buildCanvasAuthorityApi`); a relay tab answers from its own connection (relay-api.ts).canvasAuthority: {+ assumeAllUntilAnswered: false,governed: async () => [],onChanged: noopUnsub}diff --git a/src/renderer/bridge/ws-bridge.canvas.test.ts b/src/renderer/bridge/ws-bridge.canvas.test.tsindex fb3a32079..e71e31248 100644--- a/src/renderer/bridge/ws-bridge.canvas.test.ts+++ b/src/renderer/bridge/ws-bridge.canvas.test.ts@@ -58,6 +58,8 @@ describe('buildCanvasAuthorityApi (Server Edition: the core answers which projec}}const { canvasAuthority } = buildCanvasAuthorityApi(client as never)+ // Which projects are governed is known only once the core answers: until then, all of them.+ expect(canvasAuthority.assumeAllUntilAnswered).toBe(true)// A malformed entry is dropped: only project ids gate a publish.expect(await canvasAuthority.governed()).toEqual(['p1', 'p2'])expect(reqs).toEqual([{ method: IPC.canvasAuthority, args: [] }])diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 34e6601c8..054c63a68 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -783,6 +783,9 @@ export function buildCanvasAuthorityApi(client: RpcClient): Pick<NodeTerminalApiArray.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []return {canvasAuthority: {+ // A Server Edition core governs the projects its hosted team shares, and says which only when+ // asked: until it answers, a client publishes for every project (collab-sync `followGoverned`).+ assumeAllUntilAnswered: true,governed: () => client.request(IPC.canvasAuthority).then(ids, () => []),onChanged: (listener) => client.subscribe(IPC.canvasAuthorityChanged, ((v: unknown) => listener(ids(v))) as Listener)}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex a1c941d78..fb3880048 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -687,7 +687,14 @@ import {parseCloseTargets,CLOSE_BULK_MAX} from '../lib/closeTargets'-import { canvasSyncTarget, followGoverned } from './collab-sync'+import {+ canvasSyncTarget,+ followGoverned,+ NO_PROJECTS,+ provesPeer,+ shouldPublish,+ type GovernedProjects+} from './collab-sync'import {applyCanvasMutation,applyMutationToFlow,@@ -1747,8 +1754,15 @@ export function Canvas() {* content is written only from the ops the authority hears, so the gate publishes for them even* when nobody else is attached. Per core, like `hasPeersRef`, and a ref for the same reason (the* gate is asked at ~20 Hz while a node is dragged). Empty on the desktop, which governs nothing.+ *+ * The MOUNT window: before a core first answers, a Server Edition core counts every project as+ * governed (`assumeAllUntilAnswered`), so no edit made in that round trip goes unpublished; a+ * desktop or Team Access core governs nothing, and a hosted relay tab answers from its bindings at+ * once. What remains is the SHARE-TIME window, described at `onSharedChange` in src/server/index.ts.*/- const governedRef = useRef<ReadonlySet<string>>(new Set())+ const governedRef = useRef<GovernedProjects>(NO_PROJECTS)+ /** This Canvas's publisher tag (the `src` it stamps): what `provesPeer` tells our own echo by. */+ const canvasSrcRef = useRef<string | null>(null)const [, bumpHist] = useState(0)// Same trick as bumpHist, for the breadcrumb cursor: the Dock's back/forward buttons read// navRef during render, and a ref mutation is invisible to React — so every write to@@ -3723,6 +3737,7 @@ export function Canvas() {// the reflector's order, so it wins on every other client too).useEffect(() => {const src = `cv-${Math.random().toString(36).slice(2, 10)}`+ canvasSrcRef.current = srcconst order = createCanvasOrder(src)orderRef.current = order// Solo gate: publish only once someone else is attached. The presence hub's peer table includes@@ -3753,21 +3768,26 @@ export function Canvas() {// below re-derives it immediately from THIS session's presence. (No-op on a local→local switch:// the api is unchanged, so the effect does not re-run and the gate — like `order` — survives.)hasPeersRef.current = false+ // The governed set, per core like the peer gate: start clean on every (re-)bind, ask this core,+ // then follow its changes (collab-sync `followGoverned`, which also says what is assumed before+ // the first answer). Created before the first presence read, which may ask it to refresh.+ governedRef.current = NO_PROJECTS+ const governed = followGoverned(activeSession.api, (projects) => {+ governedRef.current = projects+ })const reconnected = createReconnectWatch(activePresence.store.getState().myId)const readPresence = (): void => {hasPeersRef.current =hasPeersRef.current || canvasSyncTarget(activeSession, activePresence.store.getState()).hasPeers- if (reconnected(activePresence.store.getState().myId)) order.reset()+ // A reconnect: forget the stale order, and ask again which projects are governed — a change+ // announced while we were away never reached us.+ if (reconnected(activePresence.store.getState().myId)) {+ order.reset()+ governed.refresh()+ }}readPresence()const unsub = activePresence.store.subscribe(readPresence)- // The governed set, per core like the peer gate: start clean on every (re-)bind, ask this core,- // then follow its changes (collab-sync `followGoverned`). Until the first answer the set is- // empty, so an edit made in that one round trip is not cast.- governedRef.current = new Set()- const offGoverned = followGoverned(activeSession.api, (ids) => {- governedRef.current = ids- })// `isCanvasMutation`, with a refusal remembered per node: a refused node is re-emitted on every// publish (that is what makes it sync the moment the sticky is trimmed) and a drag publishes at// ~20 Hz, so the size check re-serialized the one oversized node 20×/s, at a cost proportional to@@ -3852,7 +3872,7 @@ export function Canvas() {// The peer check FIRST: the node publisher asks this at ~20 Hz while a node is dragged, and a// solo canvas must pay for nothing more than it did before the board shared this gate (one// Set lookup when it is alone; the desktop's governed set is always empty).- (hasPeersRef.current || governedRef.current.has(projectId)) &&+ shouldPublish(hasPeersRef.current, governedRef.current, projectId) &&sessionForProject(projectId).api === activeSession.api &&!isHostedReadOnly(activeSession.id)const pub = createCanvasPublisher(@@ -3879,7 +3899,7 @@ export function Canvas() {return () => {setKanbanPublishHook(null)unsub()- offGoverned()+ governed.release()pub.dispose()publisherRef.current = nullorderRef.current = null@@ -3952,7 +3972,10 @@ export function Canvas() {pub.publish(publishableLater(nodesRef.current))}return activeSession.api.canvas.onMutation((projectId, mutation) => {- hasPeersRef.current = true // proof of a peer, whatever the presence table says+ // Proof of a peer, whatever the presence table says — but only a cast from ANOTHER client+ // (`provesPeer`): our own echo is our ack, and a lone client that casts on a governed project+ // must not start publishing every project on this core.+ if (provesPeer(mutation, canvasSrcRef.current)) hasPeersRef.current = trueconst order = orderRef.currentif (!order) returnconst key = mutationKey(mutation, projectId)diff --git a/src/renderer/canvas/authority-gate-wiring.test.ts b/src/renderer/canvas/authority-gate-wiring.test.tsindex 9caf69438..1acd7605b 100644--- a/src/renderer/canvas/authority-gate-wiring.test.ts+++ b/src/renderer/canvas/authority-gate-wiring.test.ts@@ -16,8 +16,8 @@ function between(src: string, start: string, end: string): string {describe('the publish gate hears the canvas authority', () => {it('the ONE gate opens for a peer OR a governed project, the peer check still first', () => {const gate = between(canvas, 'const shouldPublishFor = (projectId: string): boolean =>', 'const pub = createCanvasPublisher(')- expect(gate).toContain('(hasPeersRef.current || governedRef.current.has(projectId))')- expect(gate.indexOf('hasPeersRef.current')).toBeLessThan(gate.indexOf('governedRef.current'))+ // Through the pure rule (collab-sync `shouldPublish`), the peer check first.+ expect(gate).toContain('shouldPublish(hasPeersRef.current, governedRef.current, projectId) &&')// The two other halves are unchanged: the same core, and never a hosted viewer/commenter.expect(gate).toContain('sessionForProject(projectId).api === activeSession.api')expect(gate).toContain('!isHostedReadOnly(activeSession.id)')@@ -26,11 +26,23 @@ describe('the publish gate hears the canvas authority', () => {it('the governed set is read from the ACTIVE core, reset on every re-bind, and kept current', () => {const effect = between(canvas, 'const order = createCanvasOrder(src)', 'orderRef.current = null')// Per core, like `hasPeersRef`: a relay tab's governed projects must not leak onto a local tab.- expect(effect).toContain('governedRef.current = new Set()')+ expect(effect).toContain('governedRef.current = NO_PROJECTS')// `followGoverned` (collab-sync.test.ts) asks the core and follows its changes.- expect(effect).toContain('const offGoverned = followGoverned(activeSession.api, (ids) => {')- expect(effect).toContain('governedRef.current = ids')- // The subscription is released with the effect.- expect(effect).toMatch(/offGoverned\(\)/)+ expect(effect).toContain('const governed = followGoverned(activeSession.api, (projects) => {')+ expect(effect).toContain('governedRef.current = projects')+ // Asked again on a reconnect, beside the order reset: a change may have been missed meanwhile.+ expect(effect).toMatch(/if \(reconnected\(activePresence\.store\.getState\(\)\.myId\)\) \{\s*order\.reset\(\)\s*governed\.refresh\(\)/)+ // The follower exists before the first presence read can ask it to refresh.+ expect(effect.indexOf('const governed = followGoverned(')).toBeLessThan(effect.indexOf('readPresence()'))+ // Released with the effect.+ expect(effect).toMatch(/governed\.release\(\)/)+ })++ it('only ANOTHER client\'s mutation proves a peer (never our own echo)', () => {+ const handler = between(canvas, 'return activeSession.api.canvas.onMutation((projectId, mutation) => {', 'const order = orderRef.current')+ expect(handler).toContain('if (provesPeer(mutation, canvasSrcRef.current)) hasPeersRef.current = true')+ expect(handler).not.toMatch(/^\s*hasPeersRef\.current = true/m)+ const tag = between(canvas, 'const src = `cv-${Math.random().toString(36).slice(2, 10)}`', 'const order = createCanvasOrder(src)')+ expect(tag).toContain('canvasSrcRef.current = src')})})diff --git a/src/renderer/canvas/collab-sync.test.ts b/src/renderer/canvas/collab-sync.test.tsindex 39a1f487b..e5dfe7688 100644--- a/src/renderer/canvas/collab-sync.test.ts+++ b/src/renderer/canvas/collab-sync.test.ts@@ -7,7 +7,7 @@ import {sessionForProject,resetSessionsForTest,} from '../session/session'-import { canvasSyncTarget, followGoverned, shouldPublish } from './collab-sync'+import { canvasSyncTarget, EVERY_PROJECT, followGoverned, NO_PROJECTS, provesPeer, shouldPublish } from './collab-sync'const localApi = { marker: 'local' } as unknown as NodeTerminalApiconst relayApi = { marker: 'relay' } as unknown as NodeTerminalApi@@ -55,81 +55,147 @@ describe('canvasSyncTarget (Task 4 — publisher/onMutation follow the ACTIVE sedescribe('shouldPublish (the solo gate, and the canvas authority that overrides it)', () => {it('a governed project publishes even when nobody else is attached; neither = nothing is cast', () => {- expect(shouldPublish({ hasPeers: false, governed: true })).toBe(true)- expect(shouldPublish({ hasPeers: true, governed: false })).toBe(true)- expect(shouldPublish({ hasPeers: true, governed: true })).toBe(true)- expect(shouldPublish({ hasPeers: false, governed: false })).toBe(false)+ const governed = new Set(['p1'])+ expect(shouldPublish(false, governed, 'p1')).toBe(true)+ expect(shouldPublish(true, NO_PROJECTS, 'p1')).toBe(true)+ expect(shouldPublish(true, governed, 'p1')).toBe(true)+ expect(shouldPublish(false, governed, 'p2')).toBe(false)+ expect(shouldPublish(false, NO_PROJECTS, 'p1')).toBe(false)+ // While a core has not answered yet, every project on it counts as governed.+ expect(shouldPublish(false, EVERY_PROJECT, 'anything')).toBe(true)})- it('canvasSyncTarget carries the governed input into its verdict', () => {- const local = createSession('local', localApi, 'This Mac')- setActiveSession(local.id)- expect(canvasSyncTarget(local, { peers: { me: {} } }, true).shouldPublish).toBe(true)- expect(canvasSyncTarget(local, { peers: { me: {} } }, false).shouldPublish).toBe(false)- expect(canvasSyncTarget(local, { peers: { me: {} } }).shouldPublish).toBe(false)- expect(canvasSyncTarget(local, { peers: { me: {}, other: {} } }).shouldPublish).toBe(true)+ it('asks for a peer first: the governed set is not consulted when a peer is attached', () => {+ let asked = 0+ const counting = { has: () => (asked++, false) }+ expect(shouldPublish(true, counting, 'p1')).toBe(true)+ expect(asked).toBe(0)+ })+})++describe('provesPeer (the sticky proof that someone else is attached)', () => {+ it('a mutation cast by ANOTHER client proves a peer; our own echo and a core-originated op do not', () => {+ expect(provesPeer({ src: 'cv-other' }, 'cv-me')).toBe(true)+ // Our own echo is our ack: a lone client that casts must not start publishing everything.+ expect(provesPeer({ src: 'cv-me' }, 'cv-me')).toBe(false)+ // No `src`: the core itself (the canvas authority's diff, server canvas control) — no client.+ expect(provesPeer({}, 'cv-me')).toBe(false)+ // Before this Canvas has a tag, any tagged op is someone else's.+ expect(provesPeer({ src: 'cv-other' }, null)).toBe(true)})})describe('followGoverned (the governed set Canvas gates on, per core)', () => {- const authority = () => {- let answer!: (ids: string[]) => void+ const authority = (assumeAllUntilAnswered = false, fail = false) => {+ const answers: Array<{ resolve: (ids: string[]) => void; reject: (e: Error) => void }> = []let listener: ((ids: string[]) => void) | null = nullreturn {api: {canvasAuthority: {- governed: () => new Promise<string[]>((r) => (answer = r)),+ assumeAllUntilAnswered,+ governed: () =>+ new Promise<string[]>((resolve, reject) => {+ answers.push({ resolve, reject })+ if (fail) reject(new Error('E_NO_HANDLER'))+ }),onChanged: (l: (ids: string[]) => void) => {listener = lreturn () => (listener = null)}}} as unknown as Pick<NodeTerminalApi, 'canvasAuthority'>,- answer: (ids: string[]) => answer(ids),+ answer: (i: number, ids: string[]) => answers[i].resolve(ids),+ asks: () => answers.length,change: (ids: string[]) => listener?.(ids),subscribed: () => listener !== null}}const flush = (): Promise<void> => new Promise((r) => setTimeout(r, 0))+ const as = (g: { has(id: string): boolean }): string =>+ g === EVERY_PROJECT ? '*' : [...(g as ReadonlySet<string>)].join(',')it('takes the core\'s answer, then every change', async () => {const a = authority()- const seen: string[][] = []- followGoverned(a.api, (ids) => seen.push([...ids]))- a.answer(['p1'])+ const seen: string[] = []+ followGoverned(a.api, (g) => seen.push(as(g)))+ a.answer(0, ['p1'])await flush()a.change(['p1', 'p2'])- expect(seen).toEqual([['p1'], ['p1', 'p2']])+ expect(seen).toEqual(['p1', 'p1,p2'])+ })++ it('a core that governs nothing in advance (desktop, Team Access) is NEVER treated as governing', async () => {+ const a = authority(false)+ const seen: string[] = []+ followGoverned(a.api, (g) => seen.push(as(g)))+ expect(seen).toEqual([])+ a.answer(0, [])+ await flush()+ expect(seen).toEqual([''])+ })++ it('a Server Edition core counts EVERY project as governed until it answers', async () => {+ const a = authority(true)+ const seen: string[] = []+ followGoverned(a.api, (g) => seen.push(as(g)))+ expect(seen).toEqual(['*'])+ a.answer(0, ['p1'])+ await flush()+ expect(seen).toEqual(['*', 'p1'])})- it('a change that lands before the first answer wins over that (older) answer', async () => {+ it('a failed answer falls back to nothing governed', async () => {+ const a = authority(true, true)+ const seen: string[] = []+ followGoverned(a.api, (g) => seen.push(as(g)))+ await flush()+ expect(seen).toEqual(['*', ''])+ })++ it('a change that lands before an answer wins over that (older) answer', async () => {const a = authority()- const seen: string[][] = []- followGoverned(a.api, (ids) => seen.push([...ids]))+ const seen: string[] = []+ followGoverned(a.api, (g) => seen.push(as(g)))a.change(['p2'])- a.answer(['p1'])+ a.answer(0, ['p1'])await flush()- expect(seen).toEqual([['p2']])+ expect(seen).toEqual(['p2'])})- it('after release nothing more is applied, and the subscription is gone', async () => {+ it('refresh (a reconnect) asks again, recovering a change missed while disconnected', async () => {const a = authority()- const seen: string[][] = []- const off = followGoverned(a.api, (ids) => seen.push([...ids]))- off()- a.answer(['p1'])+ const seen: string[] = []+ const f = followGoverned(a.api, (g) => seen.push(as(g)))+ a.answer(0, ['p1'])await flush()- expect(seen).toEqual([])- expect(a.subscribed()).toBe(false)+ f.refresh()+ expect(a.asks()).toBe(2)+ a.answer(1, ['p1', 'p3'])+ await flush()+ expect(seen).toEqual(['p1', 'p1,p3'])})- it('a failed answer changes nothing (the solo gate stays as it was)', async () => {- const seen: string[][] = []- followGoverned(- { canvasAuthority: { governed: () => Promise.reject(new Error('x')), onChanged: () => () => {} } } as unknown as Pick<NodeTerminalApi, 'canvasAuthority'>,- (ids) => seen.push([...ids])- )+ it('only the newest ask counts: an older answer arriving late is dropped', async () => {+ const a = authority()+ const seen: string[] = []+ const f = followGoverned(a.api, (g) => seen.push(as(g)))+ f.refresh()+ a.answer(1, ['new'])+ a.answer(0, ['old'])+ await flush()+ expect(seen).toEqual(['new'])+ })++ it('after release nothing more is applied, no ask is made, and the subscription is gone', async () => {+ const a = authority()+ const seen: string[] = []+ const f = followGoverned(a.api, (g) => seen.push(as(g)))+ f.release()+ f.refresh()+ expect(a.asks()).toBe(1)+ a.answer(0, ['p1'])await flush()expect(seen).toEqual([])+ expect(a.subscribed()).toBe(false)})})diff --git a/src/renderer/canvas/collab-sync.ts b/src/renderer/canvas/collab-sync.tsindex c3d4795ed..b9abfca9b 100644--- a/src/renderer/canvas/collab-sync.ts+++ b/src/renderer/canvas/collab-sync.ts@@ -16,46 +16,84 @@ import type { WorkspaceSession } from '../session/session'*/export function canvasSyncTarget(session: WorkspaceSession,- presenceState: { peers: Record<string, unknown> },- governed = false-): { api: NodeTerminalApi; hasPeers: boolean; shouldPublish: boolean } {- const hasPeers = Object.keys(presenceState.peers).length > 1- return { api: session.api, hasPeers, shouldPublish: shouldPublish({ hasPeers, governed }) }+ presenceState: { peers: Record<string, unknown> }+): { api: NodeTerminalApi; hasPeers: boolean } {+ return { api: session.api, hasPeers: Object.keys(presenceState.peers).length > 1 }}+/** Which projects a core's canvas authority governs, as the gate asks it: by id. */+export type GovernedProjects = { has(projectId: string): boolean }+/** Nothing governed: the desktop, a Team Access tab, a core that answered none. */+export const NO_PROJECTS: GovernedProjects = new Set<string>()+/** Every project, while a core that may govern some has not answered yet (`assumeAllUntilAnswered`). */+export const EVERY_PROJECT: GovernedProjects = { has: () => true }+/**- * The publish rule (Canvas's `shouldPublishFor` applies it inline, beside the same-core and role- * checks): publish when a teammate is attached, OR when the project is governed by a canvas- * authority. A governed project's content is written only from the ops the authority hears- * (docs/hosted-team-relay.md), so a solo edit that is not published is never saved. One definition,- * in shared, so the core's end-to-end test drives the same rule.+ * The publish rule (`shouldPublishCanvas`, one definition in shared so the core's end-to-end test+ * drives it too), called by Canvas's one gate `shouldPublishFor` beside the same-core and role+ * checks: publish when a teammate is attached, OR when the project is governed by a canvas authority+ * (docs/hosted-team-relay.md).*/export const shouldPublish = shouldPublishCanvas/**- * Follow which projects a core's canvas authority governs: ask once, then take every change.- * `apply` gets the new set each time. A change that lands before the first answer wins over that- * answer, which it may postdate; a failed answer changes nothing. Returns the release: after it,- * nothing more is applied and the change subscription is gone.+ * Does this inbound mutation prove that ANOTHER client is attached? Only a cast from another client+ * does: our own echo is our ack (a lone client that casts on a governed project must not start+ * publishing every project on the core), and a mutation without `src` comes from the core itself+ * (the canvas authority's diff of an outside edit, Server Edition canvas control) — no client at all.+ */+export function provesPeer(m: { src?: unknown }, ownSrc: string | null): boolean {+ return typeof m.src === 'string' && m.src !== ownSrc+}++/** The governed set a Canvas gates on, followed for one core. */+export interface GovernedFollower {+ /** Ask the core again (a reconnect: a change may have been announced while it was away). */+ refresh(): void+ /** Stop: nothing more is applied, no ask is made, and the change subscription is gone. */+ release(): void+}++/**+ * Follow which projects a core's canvas authority governs. `apply` gets the whole set each time.+ * A core that may govern projects without saying which (`assumeAllUntilAnswered`: the Server+ * Edition) counts EVERY project as governed until it answers, so an edit made in that first round+ * trip is still published; one core that turns out to govern nothing costs one needless echo, while+ * a governed edit that is not published is never saved. A core that governs nothing in advance (the+ * desktop, a Team Access tab) and a hosted relay tab (which answers from its own bindings) are never+ * assumed to govern anything. A failed answer means nothing governed. Only the newest question+ * counts: a change, or a later ask, supersedes an answer still in flight.*/export function followGoverned(api: Pick<NodeTerminalApi, 'canvasAuthority'>,- apply: (ids: ReadonlySet<string>) => void-): () => void {+ apply: (projects: GovernedProjects) => void+): GovernedFollower {let live = true- let changed = false- void api.canvasAuthority.governed().then(- (ids) => {- if (live && !changed) apply(new Set(ids))- },- () => {}- )+ let generation = 0+ const ask = (): void => {+ const mine = ++generation+ void api.canvasAuthority.governed().then(+ (ids) => {+ if (live && mine === generation) apply(new Set(ids))+ },+ () => {+ if (live && mine === generation) apply(NO_PROJECTS)+ }+ )+ }+ if (api.canvasAuthority.assumeAllUntilAnswered) apply(EVERY_PROJECT)+ ask()const off = api.canvasAuthority.onChanged((ids) => {- changed = true+ generation++if (live) apply(new Set(ids))})- return () => {- live = false- off()+ return {+ refresh: () => {+ if (live) ask()+ },+ release: () => {+ live = false+ off()+ }}}diff --git a/src/renderer/canvas/hosted-team.source.test.ts b/src/renderer/canvas/hosted-team.source.test.tsindex d8e077b4a..aaea5be76 100644--- a/src/renderer/canvas/hosted-team.source.test.ts+++ b/src/renderer/canvas/hosted-team.source.test.ts@@ -69,7 +69,7 @@ describe('hosted team glue in Canvas', () => {expect(start).toBeGreaterThan(-1)const gate = src.slice(start, src.indexOf('const pub = createCanvasPublisher(', start))// The peer check, OR a project the host's canvas authority governs (authority-gate-wiring.test.ts).- expect(gate).toContain('(hasPeersRef.current || governedRef.current.has(projectId)) &&')+ expect(gate).toContain('shouldPublish(hasPeersRef.current, governedRef.current, projectId) &&')expect(gate).toContain('!isHostedReadOnly(activeSession.id)')expect(src).toContain('shouldPublish: () => shouldPublishFor(useProjects.getState().activeProjectId)')expect(src).toContain('shouldPublish: (projectId) => shouldPublishFor(projectId)')diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.tsindex 6c8626ed7..9e8a4a6e8 100644--- a/src/server/headless-node-factory.test.ts+++ b/src/server/headless-node-factory.test.ts@@ -4,7 +4,8 @@ import path from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { fakePlatform } from '../core/platform-fake'+import { fakePlatform, type FakePlatform } from '../core/platform-fake'+import { IPC } from '../shared/ipc'import { initPlatform, resetPlatformForTests } from '../core/platform'import { WorkspaceStore } from '../core/workspace-store'import { createCanvasAuthority } from '../core/canvas-authority'@@ -16,6 +17,7 @@ import {DEFAULT_SETTINGS,type CanvasMutation,type CanvasNodeState,+ type Project,type PtyCreateOptions,type PtyCreateResult,type Settings,@@ -1824,5 +1826,298 @@ describe('HeadlessNodeFactory — one load and one save, both through the cast hconst helper = src.lastIndexOf('private async castAndSave(', saveAt)expect(helper).toBeGreaterThan(0)expect(src.slice(helper, saveAt)).toContain('diffContent(')+ // The one read is the read-only view; every edit copies it (loadForEdit).+ const readAt = src.indexOf('workspaceStore.load(')+ expect(src.lastIndexOf('private readWorkspace(', readAt)).toBeGreaterThan(0)+ })++ it('browsers are sent the PERSISTED project, re-read after the save, never a verb\'s copy', () => {+ const calls = [...src.matchAll(/this\.deps\.publishProject/g)].map((m) => m.index ?? -1)+ const helper = src.indexOf('private async publishPersisted(')+ const end = src.indexOf('\n }\n', helper)+ expect(helper).toBeGreaterThan(0)+ for (const at of calls) expect(at > helper && at < end, `publishProject outside publishPersisted at ${at}`).toBe(true)+ expect(src.slice(helper, end)).toContain('await this.readWorkspace()')+ })+})++// A launch can take seconds. A verb's SECOND save (after it) must never write back the copy it+// loaded before the launch: that copy predates whatever a teammate did meanwhile, and a whole-node+// upsert (or a whole-project broadcast) built from it would undo it. Each second phase re-reads, and+// re-applies only its own patch (the launch outcome).+describe('HeadlessNodeFactory — a second phase re-reads before it writes (fix round 1)', () => {+ let dataDir = ''+ let projectDir = ''+ let store: WorkspaceStore+ let pty: FakePty+ let ownership: HeadlessNodeOwnership+ let fake: FakePlatform+ let shared: Set<string>+ let states: Record<string, AgentState | undefined>+ let cast: CanvasMutation[]+ let broadcast: Project[]+ let authority: ReturnType<typeof createCanvasAuthority>++ const held = (command: string, after: string[] = []) => ({ after, command, executor: 'server' as const })+ const deps = (): HeadlessNodeFactoryDeps => ({+ workspaceStore: store,+ ptyManager: pty,+ settings: () => ({ ...DEFAULT_SETTINGS, claudePermissionMode: 'manual' }),+ cliCaps: async () => ({ version: null, autoPermissionMode: false, fullscreenTui: false, sessionIdFlag: false }),+ grokCaps: async () => ({ sessionIdFlag: false, models: [] }),+ codexCaps: async () => ({ approvalValues: ['on-request', 'never'] }),+ codexSharedIdentity: async () => false,+ ownership,+ stateOf: (id) => states[id],+ launchTiming: { quietMs: 0, capMs: 0 },+ publishMutation: (id, m) => {+ cast.push(m)+ publishCanvasMutation(id, m)+ },+ publishProject: (project) => broadcast.push(structuredClone(project))+ })++ beforeEach(async () => {+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-headless-phase-'))+ projectDir = path.join(dataDir, 'project')+ fs.mkdirSync(projectDir, { recursive: true })+ resetPlatformForTests()+ fake = fakePlatform({ userDataDir: dataDir })+ initPlatform(fake)+ initCanvasSync()+ store = new WorkspaceStore()+ pty = new FakePty()+ states = {}+ cast = []+ broadcast = []+ ownership = createHeadlessNodeOwnership()+ for (const id of ['term-held', 'term-armed']) ownership.record(id, { sourceNodeId: 'term-source', projectId: 'project-1' })+ await store.save({+ version: 2,+ activeProjectId: 'project-1',+ projects: [+ {+ id: 'project-1',+ name: 'Test',+ color: '#0a84ff',+ cwd: projectDir,+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [+ terminal('term-source', 'Director'),+ terminal('term-dep', 'Dependency', 'claude', 700),+ { ...terminal('term-held', 'Held', 'claude', 1400), pendingLaunch: held('printf held') },+ { ...terminal('term-armed', 'Armed', 'claude', 2100), pendingLaunch: held('printf armed', ['term-dep']) }+ ],+ bridges: [],+ ropes: []+ }+ ]+ })+ shared = new Set(['project-1'])+ authority = createCanvasAuthority({+ sharedProjectIds: () => shared,+ readContent: (id) => store.readProjectContent(id),+ writeContent: (id, c) => store.writeProjectContent(id, c),+ publish: (id, m) => {+ publishCanvasMutation(id, m)+ },+ // No flush timer ever fires: the disk holds exactly what the verb's own saves wrote.+ setTimer: () => null,+ clearTimer: () => {},+ log: () => {}+ })+ store.setContentAuthority(authority)+ setReflectedListener((id, m) => authority.onReflected(id, m))+ })++ afterEach(async () => {+ await authority.stop()+ store.setContentAuthority(null)+ setReflectedListener(null)+ resetPlatformForTests()+ fs.rmSync(dataDir, { recursive: true, force: true })+ })++ /** A browser's cast, through the real reflector (the authority hears it). */+ const clientCast = (m: CanvasMutation): void => {+ fake.senderListeners[IPC.canvasMut](42, 'project-1', { ...m, src: 'browser-42' })+ }+ const liveNode = async (id: string): Promise<CanvasNodeState> =>+ (await store.load({ sideline: false })).projects[0].nodes.find((n) => n.id === id)!+ const onDisk = (id: string): CanvasNodeState | undefined =>+ (JSON.parse(fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')) as { nodes: CanvasNodeState[] })+ .nodes.find((n) => n.id === id)+ const upsertsOf = (ms: CanvasMutation[], id: string): CanvasNodeState[] =>+ ms.flatMap((m) => (m.op === 'upsert' && m.node.id === id ? [m.node] : []))++ it('open: a move made while the launch runs survives on disk, in the cast and in the broadcast', async () => {+ const factory = new HeadlessNodeFactory(deps())+ let castAtMove = -1+ const create = pty.createHeadless.bind(pty)+ vi.spyOn(pty, 'createHeadless').mockImplementation(async (o) => {+ clientCast({ op: 'upsert', node: { ...(await liveNode(o.persistKey!)), position: { x: 999, y: 7 } } })+ castAtMove = cast.length+ return create(o)+ })+ const reply = await factory.openAgent('term-source', { agent: 'claude', prompt: 'hello' }, true)+ factory.stop()+ expect(reply).toMatchObject({ ok: true })+ const id = (reply.result as { id: string }).id+ expect(castAtMove).toBeGreaterThan(0)+ // The verb's own patch (the launch was delivered) landed; the teammate's move was kept.+ expect(onDisk(id)?.position).toEqual({ x: 999, y: 7 })+ expect(onDisk(id)?.pendingLaunch).toBeUndefined()+ const later = upsertsOf(cast.slice(castAtMove), id)+ expect(later.length).toBeGreaterThan(0)+ for (const n of later) expect(n.position).toEqual({ x: 999, y: 7 })+ expect(broadcast.at(-1)?.nodes.find((n) => n.id === id)?.position).toEqual({ x: 999, y: 7 })+ })++ it('open: a node deleted while the launch runs stays deleted, and nothing re-creates it', async () => {+ const factory = new HeadlessNodeFactory(deps())+ let castAtDelete = -1+ let deleted = ''+ const create = pty.createHeadless.bind(pty)+ vi.spyOn(pty, 'createHeadless').mockImplementation(async (o) => {+ deleted = o.persistKey!+ clientCast({ op: 'remove', id: deleted })+ castAtDelete = cast.length+ return create(o)+ })+ await factory.openAgent('term-source', { agent: 'claude', prompt: 'hello' }, true)+ factory.stop()+ expect(deleted).not.toBe('')+ // Nothing is left for the verb to write (its node is gone), so the deletion reaches disk with the+ // authority's own flush — and a stale upsert from the verb would have re-created it there.+ await authority.flushAll()+ expect(onDisk(deleted)).toBeUndefined()+ expect(upsertsOf(cast.slice(castAtDelete), deleted)).toEqual([])+ expect(broadcast.at(-1)?.nodes.some((n) => n.id === deleted)).toBe(false)+ })++ it('run: a move made while the launch runs survives; the claim is cleared on the moved node', async () => {+ const factory = new HeadlessNodeFactory(deps())+ let castAtMove = -1+ const create = pty.createHeadless.bind(pty)+ vi.spyOn(pty, 'createHeadless').mockImplementation(async (o) => {+ clientCast({ op: 'upsert', node: { ...(await liveNode('term-held')), position: { x: 999, y: 7 } } })+ castAtMove = cast.length+ return create(o)+ })+ expect(await factory.run('term-source', { node: 'term-held' }, true)).toMatchObject({ ok: true, result: { started: true } })+ factory.stop()+ expect(onDisk('term-held')?.position).toEqual({ x: 999, y: 7 })+ expect(onDisk('term-held')?.pendingLaunch).toBeUndefined()+ for (const n of upsertsOf(cast.slice(castAtMove), 'term-held')) expect(n.position).toEqual({ x: 999, y: 7 })+ expect(broadcast.at(-1)?.nodes.find((n) => n.id === 'term-held')?.position).toEqual({ x: 999, y: 7 })+ })++ it('refreshArmed: a move made while the held launch is typed survives; the arm is cleared on the moved node', async () => {+ const factory = new HeadlessNodeFactory(deps())+ pty.live.add('term-armed')+ let castAtMove = -1+ const send = pty.sendText.bind(pty)+ vi.spyOn(pty, 'sendText').mockImplementation(async (id, text) => {+ clientCast({ op: 'upsert', node: { ...(await liveNode('term-armed')), position: { x: 999, y: 7 } } })+ castAtMove = cast.length+ return send(id, text)+ })+ await factory.refreshArmed({ nodeId: 'term-dep', state: 'done' })+ factory.stop()+ expect(pty.sends).toEqual([{ nodeId: 'term-armed', text: 'printf armed' }])+ expect(onDisk('term-armed')?.position).toEqual({ x: 999, y: 7 })+ expect(onDisk('term-armed')?.pendingLaunch).toBeUndefined()+ for (const n of upsertsOf(cast.slice(castAtMove), 'term-armed')) expect(n.position).toEqual({ x: 999, y: 7 })+ expect(broadcast.at(-1)?.nodes.find((n) => n.id === 'term-armed')?.position).toEqual({ x: 999, y: 7 })+ })++ it('an UNGOVERNED project: a browser save made while the launch runs is not overwritten either', async () => {+ shared.clear()+ const factory = new HeadlessNodeFactory(deps())+ const create = pty.createHeadless.bind(pty)+ vi.spyOn(pty, 'createHeadless').mockImplementation(async (o) => {+ const ws = await store.load({ sideline: false })+ const n = ws.projects[0].nodes.find((x) => x.id === o.persistKey)!+ n.position = { x: 999, y: 7 }+ await store.save(ws)+ return create(o)+ })+ const reply = await factory.openAgent('term-source', { agent: 'claude', prompt: 'hello' }, true)+ factory.stop()+ const id = (reply.result as { id: string }).id+ expect(onDisk(id)?.position).toEqual({ x: 999, y: 7 })+ expect(onDisk(id)?.pendingLaunch).toBeUndefined()+ })++ it('close: a browser save made while the panes are killed is not overwritten by the close', async () => {+ shared.clear()+ const factory = new HeadlessNodeFactory(deps())+ const destroy = pty.destroySession.bind(pty)+ vi.spyOn(pty, 'destroySession').mockImplementation(async (c, id, o) => {+ const ws = await store.load({ sideline: false })+ ws.projects[0].nodes.find((x) => x.id === 'term-dep')!.position = { x: 999, y: 7 }+ await store.save(ws)+ return destroy(c, id, o)+ })+ expect(await factory.close('term-source', { node: 'term-held' }, true)).toMatchObject({ ok: true })+ factory.stop()+ expect(onDisk('term-held')).toBeUndefined()+ expect(onDisk('term-dep')?.position).toEqual({ x: 999, y: 7 })+ expect(broadcast.at(-1)?.nodes.find((n) => n.id === 'term-dep')?.position).toEqual({ x: 999, y: 7 })+ })++ it('once canvas control stopped, a verb still mid-launch neither casts nor saves (and says so)', async () => {+ const factory = new HeadlessNodeFactory(deps())+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const save = vi.spyOn(store, 'save')+ let castAtStop = -1+ let savesAtStop = -1+ const create = pty.createHeadless.bind(pty)+ vi.spyOn(pty, 'createHeadless').mockImplementation(async (o) => {+ factory.stop()+ castAtStop = cast.length+ savesAtStop = save.mock.calls.length+ return create(o)+ })+ await factory.openAgent('term-source', { agent: 'claude', prompt: 'hello' }, true)+ expect(castAtStop).toBeGreaterThan(0)+ expect(cast.length).toBe(castAtStop)+ expect(save.mock.calls.length).toBe(savesAtStop)+ expect(warn.mock.calls.some((c) => String(c[0]).includes('canvas control stopped'))).toBe(true)+ warn.mockRestore()+ })++ it('a verb that stops before its FIRST save writes nothing either', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const save = vi.spyOn(store, 'save')+ let factory: HeadlessNodeFactory | null = null+ factory = new HeadlessNodeFactory({+ ...deps(),+ cliCaps: async () => {+ factory!.stop()+ return { version: null, autoPermissionMode: false, fullscreenTui: false, sessionIdFlag: false }+ }+ })+ await factory.openAgent('term-source', { agent: 'claude', prompt: 'hello' }, true)+ expect(cast).toEqual([])+ expect(save).not.toHaveBeenCalled()+ expect(broadcast).toEqual([])+ expect(warn.mock.calls.some((c) => String(c[0]).includes('canvas control stopped'))).toBe(true)+ warn.mockRestore()+ })++ it('refreshArmed with nothing ready deep-copies nothing and saves nothing', async () => {+ const factory = new HeadlessNodeFactory(deps())+ const save = vi.spyOn(store, 'save')+ const clone = vi.spyOn(globalThis, 'structuredClone')+ // Armed, but its dependency is not done: nothing changes.+ await factory.refreshArmed({ nodeId: 'term-dep', state: 'working' })+ // A hook event from a node nobody waits on.+ await factory.refreshArmed({ nodeId: 'term-source', state: 'done' })+ factory.stop()+ expect(clone).not.toHaveBeenCalled()+ expect(save).not.toHaveBeenCalled()+ expect(cast).toEqual([])+ clone.mockRestore()})})diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.tsindex cb7bb19cb..20219741e 100644--- a/src/server/headless-node-factory.ts+++ b/src/server/headless-node-factory.ts@@ -345,6 +345,54 @@ function addEdge(list: BridgeLink[], source: string, target: string, prefix: strlist.push({ id: edgeId(prefix, source, target), source, target })}+/** One node edit a verb re-applies to a fresh read (`savePatches`). Idempotent. */+interface NodePatch {+ projectId: string+ nodeId: string+ apply(node: CanvasNodeState): void+}++/** The held launch this verb owns, by its command: a patch never touches a launch someone replaced. */+const ownLaunch = (node: CanvasNodeState, command: string): boolean => node.pendingLaunch?.command === command++/** The launch was delivered: the hold is gone. */+function clearLaunch(projectId: string, nodeId: string, command: string): NodePatch {+ return {+ projectId,+ nodeId,+ apply: (node) => {+ if (ownLaunch(node, command)) delete node.pendingLaunch+ }+ }+}++/** The launch is claimed (or failed): only an explicit Run now may deliver it now. */+function claimLaunch(projectId: string, nodeId: string, command: string, attempted: boolean): NodePatch {+ return {+ projectId,+ nodeId,+ apply: (node) => {+ if (ownLaunch(node, command))+ node.pendingLaunch = { ...node.pendingLaunch!, manualOnly: true, ...(attempted ? { attempted: true } : {}) }+ }+ }+}++/** A dependency this arm waited for has had its first real working turn. */+function dropAwaitWorking(projectId: string, nodeId: string, command: string, depId: string): NodePatch {+ return {+ projectId,+ nodeId,+ apply: (node) => {+ const held = node.pendingLaunch+ if (!held || !ownLaunch(node, command) || !held.awaitWorking?.includes(depId)) return+ const rest = held.awaitWorking.filter((id) => id !== depId)+ const { awaitWorking: _awaitWorking, ...kept } = held+ node.pendingLaunch = rest.length ? { ...kept, awaitWorking: rest } : kept+ }+ }+}+/** A project absent from a baseline: all of its content is new. */const EMPTY_CONTENT: CanvasContent = { nodes: [], bridges: [], ropes: [] }@@ -609,13 +657,18 @@ export class HeadlessNodeFactory {return run}+ /** THE ONE READ of the store. A read-only view: never edited, never saved. */+ private readWorkspace(): Promise<Workspace> {+ return this.deps.workspaceStore.load({ sideline: false })+ }+/**- * THE ONE LOAD. A private copy of the workspace, so no verb ever edits an object the store or the- * canvas authority still holds (a governed project's nodes come from the authority's own state),- * and the content of every project as loaded: `castAndSave` diffs against it.+ * The load a verb EDITS. A private copy of the workspace, so no verb ever edits an object the store+ * or the canvas authority still holds (a governed project's nodes come from the authority's own+ * state), and the content of every project as loaded: `castAndSave` diffs against it.*/private async loadForEdit(): Promise<Workspace> {- const workspace = structuredClone(await this.deps.workspaceStore.load({ sideline: false }))+ const workspace = structuredClone(await this.readWorkspace())this.baselines.set(workspace, snapshotContent(workspace))return workspace}@@ -628,28 +681,62 @@ export class HeadlessNodeFactory {* (docs/hosted-team-relay.md). The reflector hands each op to the authority synchronously, so* every one is in its state before the overlay reads it. The ops are cast from a copy, never from* the workspace a verb keeps editing, so nobody downstream holds an object that changes later.+ *+ * Refused once canvas control has stopped: the shell detaches the authority from the store right+ * after, and a verb still mid-launch would otherwise write its copy un-overlaid over the+ * authority's final flush. `onlyIfChanged` skips a save that would carry no op. Answers whether it+ * saved.*/- private async castAndSave(workspace: Workspace): Promise<void> {+ private async castAndSave(workspace: Workspace, opts: { onlyIfChanged?: boolean } = {}): Promise<boolean> {+ if (this.stopped) {+ console.warn('[headless-node-factory] canvas control stopped: a pending canvas write was skipped')+ return false+ }const before = this.baselines.get(workspace)const after = snapshotContent(workspace)const cast = this.deps.publishMutation ?? ((projectId: string, m: CanvasMutation) => {publishCanvasMutation(projectId, m)})+ const ops: Array<[string, CanvasMutation]> = []for (const project of workspace.projects) {const next = after.get(project.id)if (!next) continue- for (const m of diffContent(before?.get(project.id) ?? EMPTY_CONTENT, next, project.id)) {- cast(project.id, m)- }+ for (const m of diffContent(before?.get(project.id) ?? EMPTY_CONTENT, next, project.id)) ops.push([project.id, m])}+ if (opts.onlyIfChanged && !ops.length) return false+ for (const [projectId, m] of ops) cast(projectId, m)this.baselines.set(workspace, after)await this.deps.workspaceStore.save(workspace)+ return true}- /** The whole project to browsers (`workspace:server-change`), after its save. Its content already- * travelled as ops in `castAndSave`. */- private publish(project: Project): void {- this.deps.publishProject?.(project)+ /**+ * A SECOND phase's save: the launch between the two phases can take seconds, and the copy the+ * verb loaded before it predates whatever a teammate did meanwhile (a move, a rename, a deletion).+ * So re-read, re-apply ONLY this verb's own patches to the nodes that still exist (a node deleted+ * meanwhile stays deleted), and save only if that changed anything. The patches must be idempotent:+ * every call re-applies all of them, so a later save still carries an earlier one.+ */+ private async savePatches(patches: readonly NodePatch[]): Promise<boolean> {+ if (!patches.length) return false+ const workspace = await this.loadForEdit()+ for (const patch of patches) {+ const node = workspace.projects.find((p) => p.id === patch.projectId)?.nodes.find((n) => n.id === patch.nodeId)+ if (node) patch.apply(node)+ }+ return this.castAndSave(workspace, { onlyIfChanged: true })+ }++ /** The PERSISTED projects to browsers (`workspace:server-change`), re-read after the save — never+ * a verb's own copy, which can predate a teammate's edit and would undo it on every client that+ * merges it. Their content already travelled as ops in `castAndSave`. */+ private async publishPersisted(projectIds: Iterable<string>): Promise<void> {+ if (!this.deps.publishProject || this.stopped) return+ const wanted = new Set(projectIds)+ if (!wanted.size) return+ for (const project of (await this.readWorkspace()).projects) {+ if (wanted.has(project.id)) this.deps.publishProject(project)+ }}/** Who opened `nodeId` during THIS server run (and into which project), or undefined — the@@ -940,23 +1027,30 @@ export class HeadlessNodeFactory {.map((id) => this.deps.ptyManager.destroySession(null, id, { everySocket: true })))- // The projects this close touched. What changed in them (removals, promoted frame members,- // pruned edges) is cast by `castAndSave`, which diffs the whole content.- const touched = new Set<Project>()+ // Run history first (it awaits), from the read the checks above used.for (const id of ids) {const projectId = this.ownership.ownerOf(id)!.projectId- const project = workspace.projects.find((candidate) => candidate.id === projectId)+ const target = workspace.projects.find((p) => p.id === projectId)?.nodes.find((node) => node.id === id)+ if (!target?.issueRef) continue+ // A run ends when its node is CLOSED — never when a turn ends.+ await this.logRun(projectId, runEndedEvent(target.issueRef, {+ id: target.id,+ title: target.title,+ agentId: target.agentId,+ agentSessionId: target.agentSessionId+ }, { state: this.deps.stateOf(target.id) }))+ }++ // The kills and the history took time: the removals go onto a FRESH read, so an edit a+ // teammate made meanwhile is never written back from the copy loaded before them. What+ // changed (removals, promoted frame members, pruned edges) is cast by `castAndSave`.+ const current = await this.loadForEdit()+ const touched = new Set<string>()+ for (const id of ids) {+ const projectId = this.ownership.ownerOf(id)!.projectId+ const project = current.projects.find((candidate) => candidate.id === projectId)const target = project?.nodes.find((node) => node.id === id)if (!project || !target) continue- if (target.issueRef) {- // A run ends when its node is CLOSED — never when a turn ends.- await this.logRun(project.id, runEndedEvent(target.issueRef, {- id: target.id,- title: target.title,- agentId: target.agentId,- agentSessionId: target.agentSessionId- }, { state: this.deps.stateOf(target.id) }))- }if (target.kind === 'group') {project.nodes = ungroupPersistedNodes(project.nodes, id).nodes} else {@@ -968,12 +1062,12 @@ export class HeadlessNodeFactory {if (project.bridges) {project.bridges = project.bridges.filter((edge) => edge.source !== id && edge.target !== id)}- touched.add(project)+ touched.add(project.id)}if (touched.size) {- await this.castAndSave(workspace)- for (const project of touched) this.publish(project)+ await this.castAndSave(current)+ await this.publishPersisted(touched)}for (const id of ids) {@@ -1055,7 +1149,7 @@ export class HeadlessNodeFactory {source.project.bridges = [...existing, ...plan.edges]await this.castAndSave(workspace)- this.publish(source.project)+ await this.publishPersisted([source.project.id])const note = plan.skipped.length? ` (skipped ${plan.skipped.map((skipped) => `${skipped.id}: ${skipped.why}`).join('; ')})`: ''@@ -1113,7 +1207,7 @@ export class HeadlessNodeFactory {sourceNodeId,projectId: source.project.id})- this.publish(source.project)+ await this.publishPersisted([source.project.id])const skipped = ids.length - resolvable.lengthconst note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''return {@@ -1156,7 +1250,7 @@ export class HeadlessNodeFactory {)await this.castAndSave(workspace)// Metadata only. In particular, Server Edition never mirrors `/rename` into the pane.- this.publish(source.project)+ await this.publishPersisted([source.project.id])return { ok: true, message: `renamed ${id} to "${title}"` }})}@@ -1201,9 +1295,9 @@ export class HeadlessNodeFactory {// As open() does: an agent this spawned fresh has not had its first real turn yet, so a// later `--after` on it must not be released by the CLI's boot `done` blip.if (node.agentId && launched.fresh) this.awaitingFirstWorking.add(id)- if (launched.outcome === 'delivered') node.pendingLaunch = undefined- await this.castAndSave(workspace)- this.publish(project)+ // The launch took time: only its outcome is written, onto a fresh read (`savePatches`).+ await this.savePatches(launched.outcome === 'delivered' ? [clearLaunch(project.id, id, held.command)] : [])+ await this.publishPersisted([project.id])return launched.outcome === 'delivered'? {ok: true,@@ -1245,7 +1339,7 @@ export class HeadlessNodeFactory {const byId = new Map(changed.map((node) => [node.id, node]))source.project.nodes = source.project.nodes.map((node) => byId.get(node.id) ?? node)await this.castAndSave(workspace)- this.publish(source.project)+ await this.publishPersisted([source.project.id])const skipped = ids.length - changed.lengthconst note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''return {@@ -1451,7 +1545,7 @@ export class HeadlessNodeFactory {for (const node of created) {this.ownership.record(node.id, { sourceNodeId, projectId: target.id })}- this.publish(target)+ await this.publishPersisted([target.id])if (issueRef) {for (const node of created) {await this.logRun(target.id, runStartedEvent(issueRef, {@@ -1493,11 +1587,19 @@ export class HeadlessNodeFactory {// Creation and delivery are separate transactions. A refused/throwing send retains the// exact command for the user's Run now action; boot still cannot adopt persisted nodes.+ // The launches took time, so their outcomes are written onto a fresh read, never this copy.+ const outcomes: NodePatch[] = []for (const node of created) {- if (failed.includes(node.id) && node.pendingLaunch) node.pendingLaunch.manualOnly = true+ const command = commands.get(node.id)+ if (failed.includes(node.id) && node.pendingLaunch) {+ node.pendingLaunch.manualOnly = true+ outcomes.push(claimLaunch(target.id, node.id, node.pendingLaunch.command, false))+ } else if (command && !node.pendingLaunch) {+ outcomes.push(clearLaunch(target.id, node.id, command))+ }}- await this.castAndSave(workspace)- this.publish(target)+ await this.savePatches(outcomes)+ await this.publishPersisted([target.id])const ids = created.map((node) => node.id)const queuedIds = created.filter((node) => node.pendingLaunch && !failed.includes(node.id))@@ -1588,7 +1690,7 @@ export class HeadlessNodeFactory {if (created) {this.ownership.record(node.id, { sourceNodeId, projectId: source.project.id })}- this.publish(source.project)+ await this.publishPersisted([source.project.id])return {ok: true,message: `${created ? 'created' : 'updated'} sticky ${node.id} (${write.mode})`,@@ -1615,35 +1717,45 @@ export class HeadlessNodeFactory {refreshArmed(observed?: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>): Promise<void> {return this.runExclusive(async () => {if (this.stopped) return- const workspace = await this.loadForEdit()- // The projects whose arms moved. Their content is cast whole by `castAndSave`.- const changedProjects = new Set<Project>()+ // A READ-ONLY look: every working/done hook event lands here, and most find nothing armed or+ // nothing ready. Nothing is copied or saved until an arm actually moves; then each save goes+ // through `savePatches`, a fresh read with only this pass's own patches re-applied, because a+ // delivery below can take seconds and must never write back the view it started from.+ const view = await this.readWorkspace()+ const patches: NodePatch[] = []+ const changedProjects = new Set<string>()+ let unsaved = false+ const patch = (p: NodePatch): void => {+ patches.push(p)+ changedProjects.add(p.projectId)+ unsaved = true+ }- for (const project of workspace.projects) {+ for (const project of view.projects) {for (const node of project.nodes) {const pending = node.pendingLaunchif (!pending || pending.executor !== 'server' || !pending.command || pending.manualOnly) continue// A persisted arm surviving a restart is data, not creator proof. Only a node freshly// spawned for this caller during the current run may receive automatic input.if (!this.ownership.ownerOf(node.id)) continue- const markChanged = (): void => {- changedProjects.add(project)- }- if (observed?.state === 'working' && pending.awaitWorking?.includes(observed.nodeId)) {- const remaining = pending.awaitWorking.filter((depId) => depId !== observed.nodeId)- pending.awaitWorking = remaining.length ? remaining : undefined+ const command = pending.command+ let awaitWorking = pending.awaitWorking+ if (observed?.state === 'working' && awaitWorking?.includes(observed.nodeId)) {+ const depId = observed.nodeId+ const rest = awaitWorking.filter((id) => id !== depId)+ awaitWorking = rest.length ? rest : undefined// Persist the evidence even if the dependent PTY is temporarily unavailable. Losing// this mutation would strand the arm when the next event is the legitimate `done`.- markChanged()+ patch(dropAwaitWorking(project.id, node.id, command, depId))}- for (const depId of pending.awaitWorking ?? []) {+ for (const depId of awaitWorking ?? []) {if (!(observed?.state === 'working' && observed.nodeId === depId))this.awaitingFirstWorking.add(depId)}const ready = pending.after.every((depId) => {const stillExists = project.nodes.some((candidate) => candidate.id === depId)if (!stillExists) return true- if (pending.awaitWorking?.includes(depId)) return false+ if (awaitWorking?.includes(depId)) return falsereturn observed?.nodeId === depId? observed.state === 'done': this.deps.stateOf(depId) === 'done'@@ -1658,14 +1770,12 @@ export class HeadlessNodeFactory {if (!live) continue// Persist the attempt BEFORE input. A failed/uncertain send (or a crash before its// acknowledgement save) must never be replayed by an unrelated hook.- pending.manualOnly = true- pending.attempted = true- await this.castAndSave(workspace)- markChanged()+ patch(claimLaunch(project.id, node.id, command, true))+ await this.savePatches(patches)+ unsaved = falseif (!isLaunchShell(await this.deps.ptyManager.paneCommand(node.id).catch(() => null))) continue- if ((await this.deps.ptyManager.sendText(node.id, pending.command).catch(() => false)) !== true) continue- node.pendingLaunch = undefined- markChanged()+ if ((await this.deps.ptyManager.sendText(node.id, command).catch(() => false)) !== true) continue+ patch(clearLaunch(project.id, node.id, command))}}@@ -1673,10 +1783,8 @@ export class HeadlessNodeFactory {// process-local fresh-spawn index aligned even when several arms named the same dependency.if (observed?.state === 'working') this.awaitingFirstWorking.delete(observed.nodeId)- if (changedProjects.size) {- await this.castAndSave(workspace)- for (const project of changedProjects) this.publish(project)- }+ if (unsaved) await this.savePatches(patches)+ if (changedProjects.size) await this.publishPersisted(changedProjects)})}diff --git a/src/server/index.ts b/src/server/index.tsindex b959d9d50..e07b13222 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -912,6 +912,12 @@ export async function startServer(projectCwd: (projectId) => workspaceStore.localCwdForProject(projectId),// A share or unshare: the authority adopts what joined and writes + releases what left, then every// client hears the new governed set (a client alone on a newly shared canvas must start publishing).+ // RESIDUAL, the share-time window (docs/hosted-team-relay.md): an edit a client made just before+ // the share — not yet published (it was alone) or published but not yet saved — is not in what the+ // authority adopts from disk here, and that client's next save is overlaid with the authority's+ // content, so the edit can be lost from disk (it stays on that client's screen until a reload).+ // The save debounce is 800 ms and `team share` is an admin action; the client-side mount window+ // is closed separately (collab-sync `followGoverned`, Canvas.tsx `governedRef`).onSharedChange: () => {canvasAuthority?.sharedChanged()platform.broadcast(IPC.canvasAuthorityChanged, canvasAuthority?.governedIds() ?? [])diff --git a/src/shared/canvas-publish.ts b/src/shared/canvas-publish.tsindex 8ba2f292d..1f5c66c2a 100644--- a/src/shared/canvas-publish.ts+++ b/src/shared/canvas-publish.ts@@ -141,13 +141,18 @@ const EMPTY_SCENE: CanvasScene = { nodes: [], bridges: [], ropes: [] }* moment something reads it, which for a solo user is never.*//**- * THE publish rule, one definition (the renderer's gate applies it through collab-sync's- * `shouldPublish`): publish when a teammate is attached, OR when the project is governed by a canvas- * authority. A governed project's content is written only from the ops the authority hears+ * THE publish rule, one definition (Canvas's one gate calls it, as collab-sync's `shouldPublish`):+ * publish when a teammate is attached, OR when the project is governed by a canvas authority. A+ * governed project's content is written only from the ops the authority hears* (docs/hosted-team-relay.md), so a solo edit there that is not published is never saved.+ * Positional and allocation-free, the peer check first: the gate is asked at ~20 Hz during a drag.*/-export function shouldPublishCanvas(gate: { hasPeers: boolean; governed: boolean }): boolean {- return gate.hasPeers || gate.governed+export function shouldPublishCanvas(+ hasPeers: boolean,+ governed: { has(projectId: string): boolean },+ projectId: string+): boolean {+ return hasPeers || governed.has(projectId)}export function createCanvasPublisher(diff --git a/src/shared/types.ts b/src/shared/types.tsindex 442f94a6c..a34299267 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3007,6 +3007,11 @@ export interface CanvasApi {* attached — the solo gate is overridden for it. The desktop runs no authority and governs nothing.*/export interface CanvasAuthorityApi {+ /** true = this core may govern projects, and which ones is known only once `governed()` answers:+ * until then a client publishes for EVERY project on it (the Server Edition). false = known in+ * advance, so nothing is assumed (the desktop and a Team Access tab govern nothing; a hosted+ * relay tab answers from its own bindings). */+ readonly assumeAllUntilAnswered: boolean/** The governed project ids right now. Never rejects: "unknown" is the empty list. */governed(): Promise<string[]>/** Fires with the NEW governed set whenever it changes (a share or unshare). Returns unsubscribe. */