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
feat(server): the canvas authority governs shared projects on a hosted core
review8969f15045e9
diff --git a/src/core/canvas-sync.convergence.test.ts b/src/core/canvas-sync.convergence.test.tsindex f84025b09..0588cd1c6 100644--- a/src/core/canvas-sync.convergence.test.ts+++ b/src/core/canvas-sync.convergence.test.ts@@ -19,7 +19,8 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest'import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'-import { initCanvasSync, MUTATION_MAX_BYTES } from './canvas-sync'+import { initCanvasSync, MUTATION_MAX_BYTES, setReflectedListener } from './canvas-sync'+import { createCanvasAuthority } from './canvas-authority'import {applyCanvasMutation,applyEdgeMutationToScene,@@ -33,7 +34,7 @@ import {mutationKey,PENDING_TTL_MS} from '../shared/canvas-order'-import { createCanvasPublisher, publishableScene } from '../shared/canvas-publish'+import { createCanvasPublisher, publishableScene, shouldPublishCanvas } from '../shared/canvas-publish'import { applyCanvasOp, type CanvasContent } from '../shared/canvas-content'import { defaultKanbanFor } from '../shared/kanban-default-board'import { applyKanbanOp, diffKanbanOps, isKanbanOp, sanitizeKanbanOp } from '../shared/kanban-ops'@@ -177,7 +178,9 @@ class Client {constructor(readonly id: number,- private readonly bus: Bus+ private readonly bus: Bus,+ /** Canvas's publish gate. Absent = always publish (every other test here has a peer attached). */+ gate?: () => boolean) {// Built here, not as field initializers: a field initializer runs BEFORE the parameter// properties are assigned, so `this.id` would still be undefined and both clients would stamp@@ -189,7 +192,7 @@ class Client {this.order = createCanvasOrder(src, { now: () => clock })// Mirrors Canvas: the node/edge publisher and the board publisher cast through ONE send// (`castFor`), so both families are stamped, gated and recorded by the same order.- this.pub = createCanvasPublisher((m) => this.send(m), { src })+ this.pub = createCanvasPublisher((m) => this.send(m), { src, ...(gate ? { shouldPublish: gate } : {}) })bus.deliver.set(id, (projectId, m) => {if (projectId !== PROJECT) return// Mirrors Canvas: our own remove coming back RELEASES a re-creation the gate held — cast it now,@@ -1153,3 +1156,56 @@ describe('boards converge like nodes (kanban ops)', () => {expect(a.cast.filter((m) => m.op === 'kb-label')).toHaveLength(1) // repaired locally, not re-cast})})++// A browser alone on a project the hosted team shares (docs/hosted-team-relay.md). The canvas+// authority is the one writer of that project's content and writes ONLY what it hears as ops, so a+// solo client that kept the old solo gate (publish only with a peer) would edit a canvas that is+// never saved: its whole-workspace save is overlaid with the authority's content.+describe('a solo client on a governed project (the canvas authority)', () => {+ afterEach(() => setReflectedListener(null))++ const soloWithAuthority = (gate: () => boolean) => {+ bus = new Bus()+ initPlatform(bus.platform)+ initCanvasSync()+ const solo = new Client(1, bus, gate)+ bus.clients = [1]+ const writes: CanvasContent[] = []+ const authority = createCanvasAuthority({+ sharedProjectIds: () => new Set([PROJECT]),+ readContent: async () => ({ nodes: [], bridges: [], ropes: [] }),+ writeContent: async (_id, c) => {+ writes.push(c)+ return true+ },+ publish: () => {},+ setTimer: () => null,+ clearTimer: () => {},+ log: () => {}+ })+ setReflectedListener((id, m) => authority.onReflected(id, m))+ return { solo, writes, 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 }))+ solo.edit([node('n1', 42)])+ solo.editEdges({ bridges: [{ id: 'e1', source: 'n1', target: 'n1' }] })+ bus.settle()+ await authority.flushAll()+ expect(writes).toHaveLength(1)+ expect(writes[0].nodes.map((n) => [n.id, n.position.x])).toEqual([['n1', 42]])+ expect(writes[0].bridges.map((e) => e.id)).toEqual(['e1'])+ await authority.stop()+ })++ 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 }))+ solo.edit([node('n1', 42)])+ bus.settle()+ await authority.flushAll()+ expect(bus.castCount).toBe(0)+ expect(writes).toEqual([])+ await authority.stop()+ })+})diff --git a/src/core/canvas-sync.test.ts b/src/core/canvas-sync.test.tsindex 63bb730a9..c7a099120 100644--- a/src/core/canvas-sync.test.ts+++ b/src/core/canvas-sync.test.ts@@ -8,6 +8,7 @@ import {initCanvasSync,publishCanvasMutation,reflectTargets,+ setReflectedListener,stampMutation,isCanvasMutation,MUTATION_MAX_BYTES@@ -70,6 +71,7 @@ beforeEach(() => {initCanvasSync()})afterEach(() => {+ setReflectedListener(null)resetPlatformForTests()// Every test mints a fresh mkdtemp dir above; nothing removed them, so each run leaked one per// test into the shared temp dir (see src/core/platform-fake-dirs.ts for what that did to /tmp).@@ -320,3 +322,78 @@ describe('initCanvasSync (reflector) — kanban ops', () => {expect(t.sent).toEqual([])})})++describe('setReflectedListener (the Server Edition canvas authority hears the total order)', () => {+ // The authority (core/canvas-authority.ts) applies ops in the reflector's order and must see each+ // one synchronously, right after its stamp: its own published diff echoes back through here while+ // it is still publishing, and a later op for the same key must never overtake an earlier one.+ it('sees every reflected op of BOTH ingest paths, in seq order, with its seq', () => {+ t.setClients([1])+ const heard: Array<[string, CanvasMutation]> = []+ setReflectedListener((projectId, m) => heard.push([projectId, m]))+ t.cast(1, 'p1', { op: 'upsert', node: node('a', 1), src: 'c1' })+ expect(publishCanvasMutation('p2', { op: 'remove', id: 'b' })).toBe(true)+ t.cast(1, 'p1', { op: 'edge-upsert', kind: 'bridge', edge: { id: 'e1', source: 'a', target: 'b' } })+ expect(heard.map(([p, m]) => [p, m.op, m.seq])).toEqual([+ ['p1', 'upsert', 1],+ ['p2', 'remove', 2],+ ['p1', 'edge-upsert', 3]+ ])+ // What it hears is exactly what the clients were sent.+ expect(heard.map(([, m]) => m)).toEqual(t.sent.map((s) => s.args[1]))+ })++ it('is called synchronously, before the ingest returns', () => {+ t.setClients([1])+ let heard = 0+ setReflectedListener(() => heard++)+ publishCanvasMutation('p1', { op: 'remove', id: 'a' })+ expect(heard).toBe(1)+ t.cast(1, 'p1', { op: 'remove', id: 'b' })+ expect(heard).toBe(2)+ })++ it('hears nothing for a refused op, on either path', () => {+ t.setClients([1])+ const heard: CanvasMutation[] = []+ setReflectedListener((_p, m) => heard.push(m))+ t.cast(1, 'p1', { op: 'upsert', node: { id: 'bad' } })+ t.cast(1, '', { op: 'remove', id: 'a' })+ expect(publishCanvasMutation('p1', { op: 'kb-card-remove', nodeId: '' } as CanvasMutation)).toBe(false)+ expect(publishCanvasMutation('', { op: 'remove', id: 'a' })).toBe(false)+ expect(heard).toEqual([])+ })++ it('hears ops even with no client attached (a headless core still persists them)', () => {+ const heard: CanvasMutation[] = []+ setReflectedListener((_p, m) => heard.push(m))+ expect(publishCanvasMutation('p1', { op: 'remove', id: 'a' })).toBe(true)+ expect(heard).toHaveLength(1)+ })++ it('a throwing listener never stops the fan-out', () => {+ t.setClients([1, 2])+ setReflectedListener(() => {+ throw new Error('boom')+ })+ t.cast(1, 'p1', { op: 'remove', id: 'a' })+ expect(t.sent.map((s) => s.to)).toEqual([1, 2])+ })++ it('null detaches it, and a re-init of the reflector does not', () => {+ t.setClients([1])+ const heard: CanvasMutation[] = []+ setReflectedListener((_p, m) => heard.push(m))+ resetPlatformForTests()+ const again = testPlatform()+ initPlatform(again.p)+ initCanvasSync()+ again.setClients([1])+ again.cast(1, 'p1', { op: 'remove', id: 'a' })+ expect(heard).toHaveLength(1)+ setReflectedListener(null)+ again.cast(1, 'p1', { op: 'remove', id: 'b' })+ expect(heard).toHaveLength(1)+ rmSync(again.p.userDataDir, { recursive: true, force: true })+ })+})diff --git a/src/core/canvas-sync.ts b/src/core/canvas-sync.tsindex bd5ca5057..8cc72ceee 100644--- a/src/core/canvas-sync.ts+++ b/src/core/canvas-sync.ts@@ -22,7 +22,9 @@//// Beyond `seq` it is a pipe, not a store: it holds NO canvas state, applies no policy, and persists// nothing. The canvas itself stays where it has always been — React Flow in each renderer — and the-// disk write stays with WorkspaceStore.+// disk write stays with WorkspaceStore. On a Server Edition hosting a team, the canvas authority+// hears every stamped op through `setReflectedListener` and writes shared projects' content from+// them (docs/hosted-team-relay.md); that is the authority's state, never this module's.//// NOT RATE-LIMITED, deliberately — unlike presence (see PRESENCE_RATE_BUDGETS). A presence cast is// a SAMPLED signal whose loss is self-correcting: the next cursor frame carries the current@@ -105,6 +107,35 @@ let registeredOn: CorePlatform | null = null*/let seq = 0+/**+ * The one in-process listener of the total order: the Server Edition canvas authority+ * (core/canvas-authority.ts, docs/hosted-team-relay.md), which writes shared projects' content from+ * the ops it hears here. Module-level, like `seq`, and deliberately NOT cleared by `initCanvasSync`:+ * the shell that sets it owns it, and clears it on close.+ */+let reflectedListener: ((projectId: string, m: CanvasMutation) => void) | null = null++/**+ * Set (or, with null, clear) the listener every reflected op reaches. It is called SYNCHRONOUSLY,+ * right after the stamp, in both ingest paths (a client cast and `publishCanvasMutation`), so call+ * order is seq order. The authority depends on that: its own published diff echoes back through+ * here while it is still publishing. A refused op never reaches it.+ */+export function setReflectedListener(fn: ((projectId: string, m: CanvasMutation) => void) | null): void {+ reflectedListener = fn+}++/** Hand one stamped op to the listener. A throw is logged, never let into the fan-out: every client+ * must still get the op, whatever the authority made of it. */+function tellListener(projectId: string, stamped: CanvasMutation): void {+ if (!reflectedListener) return+ try {+ reflectedListener(projectId, stamped)+ } catch (err) {+ console.warn('[canvas-sync] the reflected-op listener threw', err)+ }+}+/*** Publish a mutation originated by the core itself (for example a headless Server Edition* control request). It takes the same validation, execution-field sanitization and total-order@@ -117,6 +148,7 @@ export function publishCanvasMutation(projectId: string, mutation: CanvasMutatioif (!clean) return falseconst p = platform()const stamped = stampMutation(clean, ++seq)+ tellListener(projectId, stamped)for (const id of p.clientIds()) p.sendTo(id, IPC.canvasMut, projectId, stamped)return true}@@ -146,6 +178,7 @@ export function initCanvasSync(): void {const clean = sanitizeCanvasMutation(mutation)if (!clean) returnconst stamped = stampMutation(clean, ++seq)+ tellListener(projectId, stamped)for (const id of reflectTargets(p.clientIds(), senderId)) {p.sendTo(id, IPC.canvasMut, projectId, stamped)}diff --git a/src/core/relay/access-policy.guard.test.ts b/src/core/relay/access-policy.guard.test.tsindex 294db4dbe..411ab300c 100644--- a/src/core/relay/access-policy.guard.test.ts+++ b/src/core/relay/access-policy.guard.test.ts@@ -55,6 +55,14 @@ describe('access-policy guard', () => {expect([...HOSTED_VIEW_METHODS].sort()).toEqual(Object.keys(VIEW).sort())expect([...HOSTED_COMMENT_METHODS].sort()).toEqual(Object.keys(COMMENT).sort())})+ it('canvas:authority is left Editor-only by omission: a relay tab answers it locally, never over the wire', () => {+ // A hosted tab's governed set is every project bound to its own connection (relay-api.ts), so+ // no relay builder names the channel and the guard above never forces a decision. Recorded+ // here instead: a non-editor may neither ask it nor receive its change event.+ expect(Object.hasOwn(VIEW, IPC.canvasAuthority) || Object.hasOwn(COMMENT, IPC.canvasAuthority)).toBe(false)+ expect(Object.hasOwn(VIEW_EVENTS, IPC.canvasAuthorityChanged)).toBe(false)+ expect(read('src/renderer/bridge/relay-api.ts')).not.toMatch(/IPC\.canvasAuthority/)+ })it('the renderer\'s role names are the team store\'s', () => {const toShared = (r: TeamRole): HostedRole => rconst toCore = (r: HostedRole): TeamRole => rdiff --git a/src/core/relay/hosted-service.test.ts b/src/core/relay/hosted-service.test.tsindex f55e4753f..7fcdeb7ac 100644--- a/src/core/relay/hosted-service.test.ts+++ b/src/core/relay/hosted-service.test.ts@@ -58,7 +58,7 @@ afterEach(() => {}})-type WorldOpts = Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'projectsOfNode' | 'nodeOfSession' | 'killPeer'>> & {+type WorldOpts = Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'projectsOfNode' | 'nodeOfSession' | 'killPeer' | 'onSharedChange'>> & {recordTimers?: booleandataDir?: string}@@ -105,6 +105,7 @@ function world(opts: WorldOpts = {}) {...(opts.now ? { now: opts.now } : {}),...(opts.monotonicNow ? { monotonicNow: opts.monotonicNow } : {}),...(opts.killPeer ? { killPeer: opts.killPeer } : {}),+ ...(opts.onSharedChange ? { onSharedChange: opts.onSharedChange } : {}),...timerDeps})live.push({ svc, dataDir })@@ -964,3 +965,63 @@ describe('hosted service — lifecycle', () => {for (const ch of hosted) expect(ch).toMatch(/^relay:hosted:/)})})++describe('hosted service — the canvas authority seam (docs/hosted-team-relay.md)', () => {+ it('sharedProjectIds() follows share/unshare, and onSharedChange fires after each write', async () => {+ const seen: string[][] = []+ // The callback reads the accessor: it must already answer with the NEW set when it is told.+ let svc: HostedService | null = null+ const w = world({ onSharedChange: () => seen.push([...svc!.sharedProjectIds()].sort()) })+ svc = w.svc+ await w.svc.init()+ expect([...w.svc.sharedProjectIds()]).toEqual([])+ await w.svc.share('P', true)+ expect([...w.svc.sharedProjectIds()]).toEqual(['P'])+ await w.svc.share('Q', true)+ await w.svc.share('P', false)+ expect([...w.svc.sharedProjectIds()]).toEqual(['Q'])+ expect(seen).toEqual([['P'], ['P', 'Q'], ['Q']])+ })++ it('a share whose write failed tells nobody', async () => {+ let told = 0+ const w = world({ onSharedChange: () => told++ })+ await w.svc.init()+ disk.failTeamWrite = true+ await expect(w.svc.share('P', true)).rejects.toThrow('disk full')+ expect(told).toBe(0)+ expect([...w.svc.sharedProjectIds()]).toEqual([])+ })++ it('a relay workspace:save is refused for every role, with E_ROLE and the reason, and never reaches the store', async () => {+ const w = world()+ const owner = await ownerOnline(w)+ const editor = await approvedGuest(w, owner, 'editor', 5)+ const viewer = await approvedGuest(w, owner, 'viewer', 6)+ const ws = { version: 2, activeProjectId: 'P', projects: [{ id: 'P', nodes: [] }] }+ owner.req(21, IPC.workspaceSave, [ws])+ editor.req(22, IPC.workspaceSave, [ws])+ viewer.req(23, IPC.workspaceSave, [ws])+ owner.req(24, IPC.workspaceLoad) // positive control: the owner's other requests still dispatch+ await vi.waitFor(() => expect(owner.res(24)).toBeDefined())+ await vi.waitFor(() => expect(editor.res(22)).toBeDefined())+ await vi.waitFor(() => expect(viewer.res(23)).toBeDefined())+ const refusal = {+ ok: false,+ error: {+ code: 'E_ROLE',+ message: "A hosted team cannot save the host's workspace over the relay; edits travel as canvas operations"+ }+ }+ expect(owner.res(21)).toMatchObject(refusal)+ expect(editor.res(22)).toMatchObject(refusal)+ expect(viewer.res(23)).toMatchObject(refusal)+ expect(w.dispatched).not.toContain(IPC.workspaceSave)+ expect(w.dispatched).toContain(IPC.workspaceLoad)+ // A cast of it is dropped too.+ owner.cast(IPC.workspaceSave, [ws])+ owner.req(25, IPC.relayHostedSelf)+ await vi.waitFor(() => expect(owner.res(25)).toBeDefined())+ expect(w.casts).not.toContain(IPC.workspaceSave)+ })+})diff --git a/src/core/relay/hosted-service.ts b/src/core/relay/hosted-service.tsindex ae719e487..4fcbf267c 100644--- a/src/core/relay/hosted-service.ts+++ b/src/core/relay/hosted-service.ts@@ -22,6 +22,9 @@// that pin is still being written wins: the write is skipped, or taken back. A peer that merely// drops meanwhile keeps its pin — both humans did approve. A key that already has an entry when// the pin is written (a racing `team add-owner`) keeps it: the approval writes nothing.+// - A relay peer never saves the host's workspace (`workspace:save` is refused for every role): the+// host's canvas authority writes shared projects' content from canvas ops alone, and the share+// set it governs is read through `sharedProjectIds()` and announced by `onSharedChange`.// - The scheduler hears about EVERY session end. The core fires `onClose` only for ends the shell// did not ask for; every end this service causes (deny, expiry, removal, a listener the// scheduler closes) runs the same `ended` bookkeeping, at most once per session.@@ -58,6 +61,13 @@ const JOIN_LABEL_MAX = 60const NOT_A_MEMBER = 'You are not a member of this team.'+/** A relay peer never saves the host's workspace, whatever its role: a whole-workspace save is a+ * stale copy of every canvas it holds, and the host's canvas authority is the one writer of a+ * shared project's content, fed by ops (docs/hosted-team-relay.md). The desktop's own canvas saves+ * go to its LOCAL core, so no relay tab flow depends on this request. */+export const RELAY_WORKSPACE_SAVE_REFUSED =+ "A hosted team cannot save the host's workspace over the relay; edits travel as canvas operations"+/** A device waiting for an owner. The renderer's type IS this one (one definition, in shared). */export type HostedPending = SharedHostedPending/** Why a pending request stopped being pending, as told to owners on `relay:hosted:pending-closed`.@@ -96,6 +106,9 @@ export interface HostedServiceDeps {monotonicNow?: () => numbersetTimeout?(fn: () => void, ms: number): unknownclearTimeout?(handle: unknown): void+ /** Called after every successful `share` (on or off), once the team file holds the new set. The+ * Server Edition's canvas authority adopts and releases projects here. */+ onSharedChange?(): void}export interface HostedInfo { relayEndpoint: string; hostId: string; hostPublicKeyB64: string; hostDeviceId: string; label: string }@@ -118,6 +131,8 @@ export interface HostedService {addOwner(pubkeyB64: string, label: string): Promise<void>remove(pubkeyB64: string, force: boolean): Promise<'removed' | 'last-owner' | 'unknown'>share(projectId: string, on: boolean): Promise<void>+ /** The projects shared with the team right now, read from the team store on every call. */+ sharedProjectIds(): ReadonlySet<string>info(): HostedInfo | nulljoinCode(): string | nullstatus(): HostedStatus@@ -448,6 +463,8 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {if (typeof method === 'string' && method.startsWith(HOSTED_PREFIX)) {return { allow: false, message: 'That is answered by the hosted team service only.' }}+ // Before the role: an owner is refused too (E_ROLE, like every access refusal).+ if (method === IPC.workspaceSave) return { allow: false, message: RELAY_WORKSPACE_SAVE_REFUSED }const role = standing(c, s)if (role === null) return { allow: false, message: NOT_A_MEMBER }return decideAccess(kind, method, args, ctxWith(role))@@ -589,6 +606,15 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {},async share(projectId, on) {await team.update((d) => setShared(d, projectId, on))+ // The share landed; a failing listener must not report it as failed to the admin.+ try {+ deps.onSharedChange?.()+ } catch (err) {+ console.warn(`[hosted-team] the shared-projects listener failed: ${errorMessage(err)}`)+ }+ },+ sharedProjectIds() {+ return new Set(team.current().sharedProjects)},info() {if (!keys) return nulldiff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex 2de252730..3c9b0898e 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -331,7 +331,8 @@ export class WorkspaceStore {constructor(private remoteIO?: RemoteWorkspaceIO) {}/** Attach (or, with null, detach) the content authority whose overlays every later save and load- * pass through. Set once at boot, before the first load. */+ * pass through. Set once at boot; the Server Edition sets it after its first index load (the+ * authority adopts every shared project itself) and clears it on close. */setContentAuthority(hooks: ContentAuthorityHooks | null): void {this.contentAuthority = hooks}diff --git a/src/preload/index.ts b/src/preload/index.tsindex c7b373595..67bb7b9ef 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -537,6 +537,13 @@ const api: NodeTerminalApi = {return () => ipcRenderer.removeListener(IPC.canvasMut, handler)}},+ // The desktop never governs: a canvas authority runs only in a Server Edition hosting a team+ // (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: {+ governed: async () => [],+ onChanged: () => () => {}+ },codex: {identityCaps: () => ipcRenderer.invoke(IPC.codexIdentityCaps),cliCaps: () => ipcRenderer.invoke(IPC.codexCliCaps),diff --git a/src/renderer/bridge/relay-api.test.ts b/src/renderer/bridge/relay-api.test.tsindex 06ef50ecc..16a2b26f5 100644--- a/src/renderer/bridge/relay-api.test.ts+++ b/src/renderer/bridge/relay-api.test.ts@@ -3,6 +3,7 @@ import { IPC } from '../../shared/ipc'import type { NodeTerminalApi } from '../../shared/types'import type { FrameTransport } from './frame-transport'import { buildRelayApi } from './relay-api'+import { bindProjectToSession, createSession, resetSessionsForTest } from '../session/session'import { onLocalRelayClose } from './relay-local-close'/**@@ -305,3 +306,40 @@ describe('buildRelayApi — hosted team tabs', () => {expect(methods(t)).toEqual([IPC.presenceChat, IPC.ptyWrite, IPC.canvasMut])})})++describe('buildRelayApi — canvasAuthority (which projects publish even when alone)', () => {+ let saved: unknown+ beforeEach(() => {+ saved = (globalThis as Record<string, unknown>).window+ resetSessionsForTest()+ })+ afterEach(() => {+ ;(globalThis as Record<string, unknown>).window = saved+ resetSessionsForTest()+ })++ it('a HOSTED tab: every project bound to its own connection is governed, asked of nobody over the wire', async () => {+ ;(globalThis as Record<string, unknown>).window = { nodeTerminal: fakeLocalApi().local }+ const t = new FakeTransport()+ const { api } = buildRelayApi('conn-1', t, { hosted: true })+ const other = buildRelayApi('conn-2', new FakeTransport(), { hosted: true }).api+ expect(await api.canvasAuthority.governed()).toEqual([])+ bindProjectToSession('p-team', createSession('relay', api, 'Team').id)+ bindProjectToSession('p-elsewhere', createSession('relay', other, 'Other team').id)+ // 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')+ 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: () => () => {} }+ ;(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(t.sent).toEqual([])+ })+})diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.tsindex 0c0e169f9..5f96ddcee 100644--- a/src/renderer/bridge/relay-api.ts+++ b/src/renderer/bridge/relay-api.ts@@ -47,6 +47,7 @@ import {} from './ws-bridge'import { buildStubApi } from './stubs'import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'+import { projectIdsBoundToApi } from '../session/session'/** What Task 6 consumes: the bridged api for `createSession`, an approval gate to await, and a* teardown hook to run on disconnect/revoke. */@@ -195,6 +196,20 @@ export function buildRelayApi(// ids into this machine's mirror under the peer's node ids.seedAgentIdentity: () => undefined,+ // Which of this tab's projects publish their canvas ops even when nobody else is attached. A+ // HOSTED tab's host runs the canvas authority (docs/hosted-team-relay.md), which governs every+ // project it shares, and a hosted tab holds shared projects only: so every project bound to THIS+ // connection is governed. Answered here, from the session registry, never over the wire (a+ // viewer could not ask anyway, and the host's answer names the host's projects, which is what the+ // binding already holds). A Team Access tab's host is a desktop, which governs nothing: `local`.+ canvasAuthority: hosted+ ? {+ governed: async () => projectIdsBoundToApi(api),+ // The set changes only when a tab binds or unbinds, and Canvas re-reads it on every bind.+ onChanged: () => () => {}+ }+ : local.canvasAuthority,+// The hosted team verbs — ONLY on a tab joined by a hosted team's code. A Team Access relay// tab's host answers none of them, so there the key is absent altogether (never `undefined`),// and every `api.hosted` check in the renderer takes its old path.diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 99cf54b66..953869fb5 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -589,6 +589,12 @@ export function buildStubApi(): Omit<list: async () => [],onChanged: noopUnsub,reportDropped: noop+ },+ // 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: {+ governed: async () => [],+ onChanged: noopUnsub}} satisfies Omit<NodeTerminalApi,diff --git a/src/renderer/bridge/ws-bridge.canvas.test.ts b/src/renderer/bridge/ws-bridge.canvas.test.tsindex 71087142e..fb3a32079 100644--- a/src/renderer/bridge/ws-bridge.canvas.test.ts+++ b/src/renderer/bridge/ws-bridge.canvas.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { buildCanvasApi } from './ws-bridge'+import { buildCanvasApi, buildCanvasAuthorityApi } from './ws-bridge'import { IPC } from '../../shared/ipc'import type { CanvasMutation } from '../../shared/types'@@ -42,3 +42,36 @@ describe('buildCanvasApi', () => {expect(seen).toHaveLength(1)})})++describe('buildCanvasAuthorityApi (Server Edition: the core answers which projects it governs)', () => {+ it('governed() asks canvas:authority; onChanged subscribes canvas:authority-changed', async () => {+ const reqs: Array<{ method: string; args: unknown[] }> = []+ const subs = new Map<string, (...a: unknown[]) => void>()+ const client = {+ request: (method: string, ...args: unknown[]) => {+ reqs.push({ method, args })+ return Promise.resolve(['p1', 7, 'p2'])+ },+ subscribe: (channel: string, fn: (...a: unknown[]) => void) => {+ subs.set(channel, fn)+ return () => subs.delete(channel)+ }+ }+ const { canvasAuthority } = buildCanvasAuthorityApi(client as never)+ // 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: [] }])+ const seen: string[][] = []+ const off = canvasAuthority.onChanged((ids) => seen.push(ids))+ subs.get(IPC.canvasAuthorityChanged)?.(['p3', null])+ expect(seen).toEqual([['p3']])+ off()+ expect(subs.has(IPC.canvasAuthorityChanged)).toBe(false)+ })++ it('an older server with no handler (or any failure) governs nothing, never a rejection', async () => {+ const client = { request: () => Promise.reject(new Error('E_NO_HANDLER')), subscribe: () => () => {} }+ const { canvasAuthority } = buildCanvasAuthorityApi(client as never)+ expect(await canvasAuthority.governed()).toEqual([])+ })+})diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 67c103e7c..34e6601c8 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -771,6 +771,24 @@ export function buildCanvasApi(client: RpcClient): Pick<NodeTerminalApi, 'canvas}}+/**+ * Build the `canvasAuthority` namespace over an RpcClient: a REAL implementation for the Server+ * Edition browser, whose core may run the canvas authority (docs/hosted-team-relay.md). A server+ * that does not answer (an older one, a failure) governs nothing, so the tab keeps the solo gate+ * rather than rejecting. Deliberately NOT part of `buildCanvasApi`, which the relay tab shares: a+ * relay tab answers from its own connection (relay-api.ts) and never asks the host over the wire.+ */+export function buildCanvasAuthorityApi(client: RpcClient): Pick<NodeTerminalApi, 'canvasAuthority'> {+ const ids = (v: unknown): string[] =>+ Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []+ return {+ canvasAuthority: {+ governed: () => client.request(IPC.canvasAuthority).then(ids, () => []),+ onChanged: (listener) => client.subscribe(IPC.canvasAuthorityChanged, ((v: unknown) => listener(ids(v))) as Listener)+ }+ }+}+/*** Build the `presence` namespace over an RpcClient, mirroring the preload's invoke(→request) /* send(→cast) / on(→subscribe) split member-for-member: `hello` is the only request (its response@@ -1215,6 +1233,7 @@ export async function installWsBridge(): Promise<boolean> {...buildAgentApi(client),...buildStationNoticeApi(client),...buildCanvasApi(client),+ ...buildCanvasAuthorityApi(client),...buildPresenceApi(client),...buildSpeechApi(client),...buildUsageApi(client),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex b123ce5bd..a1c941d78 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -687,7 +687,7 @@ import {parseCloseTargets,CLOSE_BULK_MAX} from '../lib/closeTargets'-import { canvasSyncTarget } from './collab-sync'+import { canvasSyncTarget, followGoverned } from './collab-sync'import {applyCanvasMutation,applyMutationToFlow,@@ -1742,6 +1742,13 @@ export function Canvas() {* Sticky once a peer mutation actually arrives: proof of a peer that outranks any table.*/const hasPeersRef = useRef(false)+ /**+ * The projects the ACTIVE core's canvas authority governs (docs/hosted-team-relay.md): their+ * 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.+ */+ const governedRef = useRef<ReadonlySet<string>>(new Set())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@@ -3754,6 +3761,13 @@ export function Canvas() {}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@@ -3829,13 +3843,16 @@ export function Canvas() {/*** THE ONE PUBLISH GATE, asked by the node publisher (for the active project) and the kanban* publisher (for the project a board write touched). Someone else must be attached (the solo- * gate), the project must be on the core this effect casts to (see `castFor`), and a hosted+ * gate) OR the project must be governed by a canvas authority, which writes a shared project's+ * content only from the ops it hears (collab-sync `shouldPublish`, docs/hosted-team-relay.md);+ * the project must be on the core this effect casts to (see `castFor`); and a hosted* Viewer/Commenter publishes nothing: the host refuses canvas:mut for them (R5).*/const shouldPublishFor = (projectId: string): boolean =>// 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.- hasPeersRef.current &&+ // 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)) &&sessionForProject(projectId).api === activeSession.api &&!isHostedReadOnly(activeSession.id)const pub = createCanvasPublisher(@@ -3862,6 +3879,7 @@ export function Canvas() {return () => {setKanbanPublishHook(null)unsub()+ offGoverned()pub.dispose()publisherRef.current = nullorderRef.current = nulldiff --git a/src/renderer/canvas/authority-gate-wiring.test.ts b/src/renderer/canvas/authority-gate-wiring.test.tsnew file mode 100644index 000000000..9caf69438--- /dev/null+++ b/src/renderer/canvas/authority-gate-wiring.test.ts@@ -0,0 +1,36 @@+// Source pins for the canvas-authority half of the publish gate (docs/hosted-team-relay.md). Canvas.tsx+// cannot be rendered in the node test environment, so the load-bearing SHAPES are pinned here; the+// behaviour behind them is collab-sync.test.ts (the rule), the bridge tests (who answers `governed`)+// and canvas-sync.convergence.test.ts (a solo edit on a governed project reaches the authority).+import { readFileSync } from 'node:fs'+import { describe, it, expect } from 'vitest'+const canvas = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')++function between(src: string, start: string, end: string): string {+ const i = src.indexOf(start)+ expect(i, `missing: ${start}`).toBeGreaterThan(-1)+ const j = src.indexOf(end, i + start.length)+ return src.slice(i, j === -1 ? undefined : j)+}++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'))+ // 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)')+ })++ 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()')+ // `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\(\)/)+ })+})diff --git a/src/renderer/canvas/collab-sync.test.ts b/src/renderer/canvas/collab-sync.test.tsindex bc6be9c2e..39a1f487b 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 } from './collab-sync'+import { canvasSyncTarget, followGoverned, shouldPublish } from './collab-sync'const localApi = { marker: 'local' } as unknown as NodeTerminalApiconst relayApi = { marker: 'relay' } as unknown as NodeTerminalApi@@ -52,3 +52,84 @@ describe('canvasSyncTarget (Task 4 — publisher/onMutation follow the ACTIVE seexpect(canvasSyncTarget(local, { peers: {} }).hasPeers).toBe(false)})})++describe('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)+ })++ 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)+ })+})++describe('followGoverned (the governed set Canvas gates on, per core)', () => {+ const authority = () => {+ let answer!: (ids: string[]) => void+ let listener: ((ids: string[]) => void) | null = null+ return {+ api: {+ canvasAuthority: {+ governed: () => new Promise<string[]>((r) => (answer = r)),+ onChanged: (l: (ids: string[]) => void) => {+ listener = l+ return () => (listener = null)+ }+ }+ } as unknown as Pick<NodeTerminalApi, 'canvasAuthority'>,+ answer: (ids: string[]) => answer(ids),+ change: (ids: string[]) => listener?.(ids),+ subscribed: () => listener !== null+ }+ }+ const flush = (): Promise<void> => new Promise((r) => setTimeout(r, 0))++ 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'])+ await flush()+ a.change(['p1', 'p2'])+ expect(seen).toEqual([['p1'], ['p1', 'p2']])+ })++ it('a change that lands before the first answer wins over that (older) answer', async () => {+ const a = authority()+ const seen: string[][] = []+ followGoverned(a.api, (ids) => seen.push([...ids]))+ a.change(['p2'])+ a.answer(['p1'])+ await flush()+ expect(seen).toEqual([['p2']])+ })++ it('after release nothing more is applied, and the subscription is gone', async () => {+ const a = authority()+ const seen: string[][] = []+ const off = followGoverned(a.api, (ids) => seen.push([...ids]))+ off()+ a.answer(['p1'])+ await flush()+ expect(seen).toEqual([])+ expect(a.subscribed()).toBe(false)+ })++ 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])+ )+ await flush()+ expect(seen).toEqual([])+ })+})diff --git a/src/renderer/canvas/collab-sync.ts b/src/renderer/canvas/collab-sync.tsindex fff765002..c3d4795ed 100644--- a/src/renderer/canvas/collab-sync.ts+++ b/src/renderer/canvas/collab-sync.ts@@ -1,4 +1,5 @@import type { NodeTerminalApi } from '@shared/types'+import { shouldPublishCanvas } from '@shared/canvas-publish'import type { WorkspaceSession } from '../session/session'/**@@ -15,7 +16,46 @@ import type { WorkspaceSession } from '../session/session'*/export function canvasSyncTarget(session: WorkspaceSession,- presenceState: { peers: Record<string, unknown> }-): { api: NodeTerminalApi; hasPeers: boolean } {- return { api: session.api, hasPeers: Object.keys(presenceState.peers).length > 1 }+ 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 }) }+}++/**+ * 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.+ */+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.+ */+export function followGoverned(+ api: Pick<NodeTerminalApi, 'canvasAuthority'>,+ apply: (ids: ReadonlySet<string>) => void+): () => void {+ let live = true+ let changed = false+ void api.canvasAuthority.governed().then(+ (ids) => {+ if (live && !changed) apply(new Set(ids))+ },+ () => {}+ )+ const off = api.canvasAuthority.onChanged((ids) => {+ changed = true+ if (live) apply(new Set(ids))+ })+ return () => {+ live = false+ off()+ }}diff --git a/src/renderer/canvas/hosted-team.source.test.ts b/src/renderer/canvas/hosted-team.source.test.tsindex 2dbc0cef4..d8e077b4a 100644--- a/src/renderer/canvas/hosted-team.source.test.ts+++ b/src/renderer/canvas/hosted-team.source.test.ts@@ -68,7 +68,8 @@ describe('hosted team glue in Canvas', () => {const start = src.indexOf('const shouldPublishFor = (projectId: string): boolean =>')expect(start).toBeGreaterThan(-1)const gate = src.slice(start, src.indexOf('const pub = createCanvasPublisher(', start))- expect(gate).toContain('hasPeersRef.current &&')+ // 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('!isHostedReadOnly(activeSession.id)')expect(src).toContain('shouldPublish: () => shouldPublishFor(useProjects.getState().activeProjectId)')expect(src).toContain('shouldPublish: (projectId) => shouldPublishFor(projectId)')diff --git a/src/renderer/session/session.test.ts b/src/renderer/session/session.test.tsindex 260c3fefd..75bf54bfb 100644--- a/src/renderer/session/session.test.ts+++ b/src/renderer/session/session.test.ts@@ -16,6 +16,7 @@ import {takeSessionOffline,activeSessionPresence,presenceForProject,+ projectIdsBoundToApi,} from './session'import { defaultPresence } from '../state/presence'import type { NodeTerminalApi } from '@shared/types'@@ -325,3 +326,22 @@ describe('setMeAll (obligation 2 — a rename re-helloes EVERY live session)', (expect(getSessionStores(s2.id).presence.store.getState().me).toEqual(me)})})++describe('projectIdsBoundToApi (a relay connection -> the tabs it serves)', () => {+ it('names exactly the projects bound to a live session holding THIS api', () => {+ const local = createSession('local', fakeApi, 'This Mac')+ setActiveSession(local.id)+ const apiA = { marker: 'a' } as unknown as NodeTerminalApi+ const apiB = { marker: 'b' } as unknown as NodeTerminalApi+ const a = createSession('relay', apiA, 'A')+ const b = createSession('relay', apiB, 'B')+ bindProjectToSession('pa', a.id)+ bindProjectToSession('pb', b.id)+ expect(projectIdsBoundToApi(apiA)).toEqual(['pa'])+ expect(projectIdsBoundToApi(apiB)).toEqual(['pb'])+ // The local api binds nothing: an unbound project merely FALLS BACK to local.+ expect(projectIdsBoundToApi(fakeApi)).toEqual([])+ disposeSession(a.id)+ expect(projectIdsBoundToApi(apiA)).toEqual([])+ })+})diff --git a/src/renderer/session/session.ts b/src/renderer/session/session.tsindex 4b3757531..0bbf1f412 100644--- a/src/renderer/session/session.ts+++ b/src/renderer/session/session.ts@@ -193,6 +193,17 @@ export function sessionForProject(projectId: string): WorkspaceSession {return localOrActiveSession()}+/** The projects bound to a live session whose api IS `api`, i.e. the tabs one relay connection+ * serves. An unbound project merely falls back to the local session, so the local api binds none. */+export function projectIdsBoundToApi(api: NodeTerminalApi): string[] {+ const out: string[] = []+ for (const [projectId, sessionId] of PROJECT_BINDINGS) {+ const e = SESSIONS.get(sessionId)+ if (e && !e.disposed && e.session.api === api) out.push(projectId)+ }+ return out+}+/** Re-broadcast the local human's identity on EVERY live session (obligation 2). Renaming yourself* must re-hello every connected core, not just the one the rename UI happened to read — otherwise a* remote peer keeps drawing your old name until reload. `setMe` saves + says hello per session. */diff --git a/src/server/canvas-control.test.ts b/src/server/canvas-control.test.tsindex c3320bbb4..cb43b4b38 100644--- a/src/server/canvas-control.test.ts+++ b/src/server/canvas-control.test.ts@@ -142,7 +142,10 @@ describe('initServerCanvasControl', () => {}const store = {load: vi.fn(async () => workspace),- save: vi.fn(async () => undefined),+ // A store keeps what it is handed: the factory edits a private copy of what it loaded.+ save: vi.fn(async (next: Workspace) => {+ Object.assign(workspace, structuredClone(next))+ }),persistedCanvases: () => [{ id: 'p1', nodes: workspace.projects[0].nodes }],// No strict true flag and no machine-local `kept` ack: capability is off by default.capabilityProjectFor: () => ({})@@ -271,7 +274,10 @@ describe('initServerCanvasControl', () => {}const store = {load: vi.fn(async () => workspace),- save: vi.fn(async () => undefined),+ // A store keeps what it is handed: the factory edits a private copy of what it loaded.+ save: vi.fn(async (next: Workspace) => {+ Object.assign(workspace, structuredClone(next))+ }),persistedCanvases: () => [{ id: 'p1', nodes: workspace.projects[0].nodes }],capabilityProjectFor: () => ({agentMessaging: true,@@ -389,7 +395,10 @@ describe('initServerCanvasControl', () => {}const store = {load: vi.fn(async () => workspace),- save: vi.fn(async () => undefined),+ // A store keeps what it is handed: the factory edits a private copy of what it loaded.+ save: vi.fn(async (next: Workspace) => {+ Object.assign(workspace, structuredClone(next))+ }),persistedCanvases: () => [{ id: 'p1', nodes: workspace.projects[0].nodes }],capabilityProjectFor: () => ({ agentMessaging: false, capabilityAck: {} })} as unknown as WorkspaceStorediff --git a/src/server/canvas-control.ts b/src/server/canvas-control.tsindex 6055cd813..aeb1a5480 100644--- a/src/server/canvas-control.ts+++ b/src/server/canvas-control.ts@@ -198,6 +198,9 @@ export async function initServerCanvasControl(// up suspends autosave, so it latched on, and "Keep my version" then wrote the browser's edge// state over the ropes this factory had just persisted. These writes are OURS; the renderer// merges them (renderer/lib/serverChange.ts) and is never asked to choose.+ // The CONTENT of each write (nodes, edges) travels separately, as canvas ops the factory casts+ // through the reflector BEFORE every save (its `castAndSave`; no `publishMutation` here = the+ // reflector). On a project the canvas authority governs, only what it heard as ops is written.publishProject: (project: Project) => platform().broadcast(IPC.workspaceServerChange, project),issueRepository: deps.issueRepository,// An issue card's run history lives in the same board log the messaging trace writes to.diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.tsindex f9ca1aac8..6c8626ed7 100644--- a/src/server/headless-node-factory.test.ts+++ b/src/server/headless-node-factory.test.ts@@ -7,11 +7,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { fakePlatform } from '../core/platform-fake'import { initPlatform, resetPlatformForTests } from '../core/platform'import { WorkspaceStore } from '../core/workspace-store'+import { createCanvasAuthority } from '../core/canvas-authority'+import { initCanvasSync, publishCanvasMutation, setReflectedListener } from '../core/canvas-sync'import type { AgentState } from '../shared/agents/normalize'import { MAX_LAUNCH_LINE_BYTES } from '../shared/canonical-line'import { RUN_NOW_AFTER_REFUSAL } from '../shared/control-verbs'import {DEFAULT_SETTINGS,+ type CanvasMutation,type CanvasNodeState,type PtyCreateOptions,type PtyCreateResult,@@ -22,8 +25,10 @@ import {createHeadlessNodeOwnership,HeadlessNodeFactory,launchFailedError,+ type HeadlessNodeFactoryDeps,type HeadlessNodeOwnership,- type HeadlessPty+ type HeadlessPty,+ type HeadlessWorkspace} from './headless-node-factory'class FakePty implements HeadlessPty {@@ -236,8 +241,12 @@ describe('HeadlessNodeFactory', () => {ownership,stateOf: (id) => states[id],launchTiming: { quietMs: 0, capMs: 0 },- publishNode: (_projectId, node) => published.push(node),- publishRemoval: (_projectId, nodeId) => removed.push(nodeId),+ // Every content op the factory casts; `published` / `removed` keep the node halves these+ // tests assert on (edges and board ops are cast too — see the cast-before-save suite).+ publishMutation: (_projectId, m) => {+ if (m.op === 'upsert') published.push(m.node)+ else if (m.op === 'remove') removed.push(m.id)+ },publishProject: (project) => publishedProjects.push(structuredClone(project))})})@@ -791,11 +800,10 @@ describe('HeadlessNodeFactory', () => {for (const id of ['term-upstream', groupId, 'sticky-color']) {expect(project.nodes.find((node) => node.id === id)?.color, id).toBe('#32d74b')}- expect(published.map((node) => node.id)).toEqual([- 'term-upstream',- groupId,- 'sticky-color'- ])+ // Cast in the project's node order (frames first), one upsert each.+ expect(published.map((node) => node.id).sort()).toEqual(+ ['term-upstream', groupId, 'sticky-color'].sort()+ )expect(publishedProjects).toHaveLength(1)expect(pty.sends).toEqual([])expect(pty.destroys).toEqual([])@@ -1635,3 +1643,186 @@ describe('HeadlessNodeFactory', () => {expect(node?.pendingLaunch).toEqual(held)})})++// Every content change this factory makes is CAST before it is SAVED (docs/hosted-team-relay.md):+// on a project a canvas authority governs, the save is overlaid with the authority's content, which+// holds only what it heard as ops — so a change that is not cast first is dropped from disk.+describe('HeadlessNodeFactory — casts every content change before it saves', () => {+ let dataDir = ''+ let projectDir = ''+ let store: WorkspaceStore+ let pty: FakePty+ let ownership: HeadlessNodeOwnership++ const deps = (over: Partial<HeadlessNodeFactoryDeps>): 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: () => undefined,+ launchTiming: { quietMs: 0, capMs: 0 },+ ...over+ })++ beforeEach(async () => {+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-headless-cast-'))+ projectDir = path.join(dataDir, 'project')+ fs.mkdirSync(projectDir, { recursive: true })+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dataDir }))+ store = new WorkspaceStore()+ pty = new FakePty()+ ownership = createHeadlessNodeOwnership()+ ownership.record('term-owned', { 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-owned', 'Owned', 'gemini', 900)],+ bridges: [],+ ropes: []+ }+ ]+ })+ })++ afterEach(() => {+ setReflectedListener(null)+ resetPlatformForTests()+ fs.rmSync(dataDir, { recursive: true, force: true })+ })++ const label = (m: CanvasMutation): string =>+ m.op === 'upsert'+ ? `upsert ${m.node.id}`+ : m.op === 'remove'+ ? `remove ${m.id}`+ : m.op === 'edge-upsert'+ ? `edge-upsert ${m.kind} ${m.edge.source}->${m.edge.target}`+ : m.op === 'edge-remove'+ ? `edge-remove ${m.id}`+ : m.op++ it('an open-agent that draws a rope and a bridge casts the node and BOTH edges, all before the save', async () => {+ const log: string[] = []+ const recording: HeadlessWorkspace = {+ load: (o) => store.load(o),+ save: async (ws) => {+ log.push('save')+ return store.save(ws)+ }+ }+ const factory = new HeadlessNodeFactory(+ deps({ workspaceStore: recording, publishMutation: (_p, m) => log.push(label(m)) })+ )+ 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+ // The first save persists the node, its hold, the rope and the bridge: every one of them was+ // cast BEFORE it, node first (an edge naming a node a peer does not have yet would be dropped).+ const firstSave = log.indexOf('save')+ expect(log.slice(0, firstSave)).toEqual([+ `upsert ${id}`,+ `edge-upsert bridge term-source->${id}`,+ `edge-upsert rope term-source->${id}`+ ])+ // The delivery's own save (the hold cleared) is cast before it too.+ expect(log.slice(firstSave + 1)).toEqual([`upsert ${id}`, 'save'])+ })++ it('a close casts the node removal and the edges it takes with it, before the save', async () => {+ const workspace = await store.load({ sideline: false })+ workspace.projects[0].ropes = [{ id: 'rope-1', source: 'term-source', target: 'term-owned' }]+ workspace.projects[0].bridges = [{ id: 'bridge-1', source: 'term-source', target: 'term-owned' }]+ await store.save(workspace)+ const log: string[] = []+ const recording: HeadlessWorkspace = {+ load: (o) => store.load(o),+ save: async (ws) => {+ log.push('save')+ return store.save(ws)+ }+ }+ const factory = new HeadlessNodeFactory(+ deps({ workspaceStore: recording, publishMutation: (_p, m) => log.push(label(m)) })+ )+ expect(await factory.close('term-source', { node: 'term-owned' }, true)).toMatchObject({ ok: true })+ factory.stop()+ expect(log).toEqual(['edge-remove bridge-1', 'edge-remove rope-1', 'remove term-owned', 'save'])+ })++ it('a verb that changes nothing casts nothing', async () => {+ const cast: CanvasMutation[] = []+ const factory = new HeadlessNodeFactory(deps({ publishMutation: (_p, m) => cast.push(m) }))+ // A refusal (unowned target) saves nothing and casts nothing.+ expect(await factory.rename('term-source', { node: 'term-source', title: 'x' })).toMatchObject({ ok: false })+ factory.stop()+ expect(cast).toEqual([])+ })++ it('on a GOVERNED project the new node and its rope survive the overlaid save (a real authority)', async () => {+ initCanvasSync()+ // No flush timer ever fires: what is on disk after the verb is exactly what its own save wrote.+ const authority = createCanvasAuthority({+ sharedProjectIds: () => new Set(['project-1']),+ readContent: (id) => store.readProjectContent(id),+ writeContent: (id, c) => store.writeProjectContent(id, c),+ publish: (id, m) => {+ publishCanvasMutation(id, m)+ },+ setTimer: () => null,+ clearTimer: () => {},+ log: () => {}+ })+ store.setContentAuthority(authority)+ setReflectedListener((id, m) => authority.onReflected(id, m))+ // The production default: casts go through the real reflector.+ const factory = new HeadlessNodeFactory(deps({}))+ const reply = await factory.openTerminal('term-source', {}, true)+ expect(reply).toMatchObject({ ok: true })+ const id = (reply.result as { id: string }).id+ const file = JSON.parse(fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')) as {+ nodes: CanvasNodeState[]+ ropes?: Array<{ source: string; target: string }>+ }+ expect(file.nodes.map((n) => n.id)).toContain(id)+ expect(file.ropes).toEqual([expect.objectContaining({ source: 'term-source', target: id })])++ // A verb with ONE save (the open above saves twice, so its second save would carry what the+ // first one's cast delivered late): the rename is on disk the moment the verb returns.+ const renamed = await factory.rename('term-source', { node: 'term-owned', title: 'Renamed' })+ factory.stop()+ expect(renamed).toMatchObject({ ok: true })+ const after = JSON.parse(fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')) as {+ nodes: CanvasNodeState[]+ }+ expect(after.nodes.find((n) => n.id === 'term-owned')?.title).toBe('Renamed')+ await authority.stop()+ store.setContentAuthority(null)+ })+})++describe('HeadlessNodeFactory — one load and one save, both through the cast helper (source)', () => {+ const src = fs.readFileSync(path.join(__dirname, 'headless-node-factory.ts'), 'utf8').replace(/\r\n/g, '\n')+ it('every verb loads through loadForEdit and saves through castAndSave', () => {+ // A second `workspaceStore.save(` is a save site that casts nothing: on a governed project the+ // authority's overlay would drop whatever it changed.+ expect(src.match(/workspaceStore\.save\(/g)?.length).toBe(1)+ expect(src.match(/workspaceStore\.load\(/g)?.length).toBe(1)+ const saveAt = src.indexOf('workspaceStore.save(')+ const helper = src.lastIndexOf('private async castAndSave(', saveAt)+ expect(helper).toBeGreaterThan(0)+ expect(src.slice(helper, saveAt)).toContain('diffContent(')+ })+})diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.tsindex 56baa85b9..cb7bb19cb 100644--- a/src/server/headless-node-factory.ts+++ b/src/server/headless-node-factory.ts@@ -4,6 +4,7 @@ import { randomBytes, randomUUID } from 'node:crypto'import path from 'node:path'import { publishCanvasMutation } from '../core/canvas-sync'+import { contentOf, diffContent, type CanvasContent } from '../shared/canvas-content'import { launchHeadless } from '../core/headless-launch'import { gateProjectTarget, GRANT_CAP } from '../core/project-grants'import {@@ -44,6 +45,7 @@ import type { BoardLogEntry } from '../shared/types'import { UNKNOWN_CODEX_CLI_CAPS } from '../shared/types'import type {BridgeLink,+ CanvasMutation,CanvasNodeState,ClaudeCliCaps,CodexCliCaps,@@ -112,8 +114,14 @@ export interface HeadlessNodeFactoryDeps {agentIdOf?(nodeId: string): string | undefinedenv?: Record<string, string | undefined>now?: () => number- publishNode?: (projectId: string, node: CanvasNodeState) => void- publishRemoval?: (projectId: string, nodeId: string) => void+ /**+ * Cast one content op (node, edge or board) to every client. Default: the reflector+ * (`publishCanvasMutation`), whose listener is the canvas authority. Every op is cast BEFORE the+ * save that persists it (`castAndSave`): on a governed project the save is overlaid with the+ * authority's content, which holds only what it heard as ops.+ */+ publishMutation?: (projectId: string, m: CanvasMutation) => void+ /** The whole project, to browsers, on `workspace:server-change` (merged, never a conflict bar). */publishProject?: (project: Project) => void/** Injectable only so tests can seed creator facts; production uses a fresh process-local ledger. */ownership?: HeadlessNodeOwnership@@ -337,6 +345,15 @@ function addEdge(list: BridgeLink[], source: string, target: string, prefix: strlist.push({ id: edgeId(prefix, source, target), source, target })}+/** A project absent from a baseline: all of its content is new. */+const EMPTY_CONTENT: CanvasContent = { nodes: [], bridges: [], ropes: [] }++/** Every project's content, deep-copied: a verb edits its workspace in place (`node.pendingLaunch =+ * …`), so a baseline that shared those objects would diff as unchanged. */+function snapshotContent(workspace: Workspace): Map<string, CanvasContent> {+ return new Map(workspace.projects.map((p) => [p.id, structuredClone(contentOf(p))]))+}+function nodeProjects(workspace: Workspace, nodeId: string): Project[] {return workspace.projects.filter((project) => project.nodes.some((node) => node.id === nodeId))}@@ -576,6 +593,8 @@ export class HeadlessNodeFactory {*/private projectGrants = new Map<string, Set<string>>()private stopped = false+ /** Per loaded workspace copy: every project's content as last loaded or saved (`castAndSave`). */+ private baselines = new WeakMap<Workspace, Map<string, CanvasContent>>()constructor(private readonly deps: HeadlessNodeFactoryDeps) {this.ownership = deps.ownership ?? createHeadlessNodeOwnership()@@ -590,24 +609,47 @@ export class HeadlessNodeFactory {return run}- private publishChangeSet(- project: Project,- nodes: readonly CanvasNodeState[],- removedIds: readonly string[]- ): void {- this.deps.publishProject?.(project)- const publishNode = this.deps.publishNode ?? ((projectId: string, node: CanvasNodeState) => {- publishCanvasMutation(projectId, { op: 'upsert', node })- })- const publishRemoval = this.deps.publishRemoval ?? ((projectId: string, nodeId: string) => {- publishCanvasMutation(projectId, { op: 'remove', id: nodeId })+ /**+ * 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.+ */+ private async loadForEdit(): Promise<Workspace> {+ const workspace = structuredClone(await this.deps.workspaceStore.load({ sideline: false }))+ this.baselines.set(workspace, snapshotContent(workspace))+ return workspace+ }++ /**+ * THE ONE SAVE. Diff every project's whole content against what was last loaded or saved, cast+ * every op, THEN save. Nothing is hand-listed per verb, and that is the point: on a project the+ * canvas authority governs, the save is overlaid with the authority's content, which holds only+ * what it heard as ops, so any change a verb made that is not cast here is dropped from disk+ * (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.+ */+ private async castAndSave(workspace: Workspace): Promise<void> {+ const before = this.baselines.get(workspace)+ const after = snapshotContent(workspace)+ const cast = this.deps.publishMutation ?? ((projectId: string, m: CanvasMutation) => {+ publishCanvasMutation(projectId, m)})- for (const node of nodes) publishNode(project.id, node)- for (const nodeId of removedIds) publishRemoval(project.id, nodeId)+ 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)+ }+ }+ this.baselines.set(workspace, after)+ await this.deps.workspaceStore.save(workspace)}- private publish(project: Project, nodes: readonly CanvasNodeState[]): void {- this.publishChangeSet(project, nodes, [])+ /** 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)}/** Who opened `nodeId` during THIS server run (and into which project), or undefined — the@@ -763,7 +805,7 @@ export class HeadlessNodeFactory {}}- const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const workspace = await this.loadForEdit()const source = sourceProject(workspace, sourceNodeId)if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }if (!sourceCanControl(source.node, this.deps.agentIdOf)) {@@ -856,7 +898,7 @@ export class HeadlessNodeFactory {}}- const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const workspace = await this.loadForEdit()const source = sourceProject(workspace, sourceNodeId)if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }if (!sourceCanControl(source.node, this.deps.agentIdOf)) {@@ -898,8 +940,9 @@ export class HeadlessNodeFactory {.map((id) => this.deps.ptyManager.destroySession(null, id, { everySocket: true })))- const removedByProject = new Map<Project, string[]>()- const changedByProject = new Map<Project, Map<string, CanvasNodeState>>()+ // 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>()for (const id of ids) {const projectId = this.ownership.ownerOf(id)!.projectIdconst project = workspace.projects.find((candidate) => candidate.id === projectId)@@ -915,11 +958,7 @@ export class HeadlessNodeFactory {}, { state: this.deps.stateOf(target.id) }))}if (target.kind === 'group') {- const ungrouped = ungroupPersistedNodes(project.nodes, id)- project.nodes = ungrouped.nodes- const changed = changedByProject.get(project) ?? new Map<string, CanvasNodeState>()- for (const node of ungrouped.promoted) changed.set(node.id, node)- changedByProject.set(project, changed)+ project.nodes = ungroupPersistedNodes(project.nodes, id).nodes} else {project.nodes = project.nodes.filter((node) => node.id !== id)}@@ -929,20 +968,12 @@ export class HeadlessNodeFactory {if (project.bridges) {project.bridges = project.bridges.filter((edge) => edge.source !== id && edge.target !== id)}- const removed = removedByProject.get(project) ?? []- removed.push(id)- removedByProject.set(project, removed)+ touched.add(project)}- if (removedByProject.size) {- await this.deps.workspaceStore.save(workspace)- for (const [project, removed] of removedByProject) {- const surviving = project.nodes.map((node) => node.id)- const changed = [...(changedByProject.get(project)?.values() ?? [])].filter((node) =>- surviving.includes(node.id)- )- this.publishChangeSet(project, changed, removed)- }+ if (touched.size) {+ await this.castAndSave(workspace)+ for (const project of touched) this.publish(project)}for (const id of ids) {@@ -973,7 +1004,7 @@ export class HeadlessNodeFactory {}}- const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const workspace = await this.loadForEdit()const source = sourceProject(workspace, sourceNodeId)if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }if (!sourceCanControl(source.node, this.deps.agentIdOf)) {@@ -1023,9 +1054,8 @@ export class HeadlessNodeFactory {}source.project.bridges = [...existing, ...plan.edges]- await this.deps.workspaceStore.save(workspace)- // An edge-only change has no node mutation to publish; the full-project event is the fanout.- this.publish(source.project, [])+ await this.castAndSave(workspace)+ this.publish(source.project)const note = plan.skipped.length? ` (skipped ${plan.skipped.map((skipped) => `${skipped.id}: ${skipped.why}`).join('; ')})`: ''@@ -1048,7 +1078,7 @@ export class HeadlessNodeFactory {color = resolveNodeColor(args.color)if (color === undefined) return { ok: false, error: invalidNodeColorMessage() }}- const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const workspace = await this.loadForEdit()const source = sourceProject(workspace, sourceNodeId)if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }if (!sourceCanControl(source.node, this.deps.agentIdOf)) {@@ -1078,12 +1108,12 @@ export class HeadlessNodeFactory {}source.project.nodes = grouped.nodes- await this.deps.workspaceStore.save(workspace)+ await this.castAndSave(workspace)this.ownership.record(grouped.groupId, {sourceNodeId,projectId: source.project.id})- this.publish(source.project, grouped.changed)+ this.publish(source.project)const skipped = ids.length - resolvable.lengthconst note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''return {@@ -1098,7 +1128,7 @@ export class HeadlessNodeFactory {return this.runExclusive(async () => {const flagError = unsupportedFlags(args, new Set(['node', 'title']))if (flagError) return { ok: false, error: `rename: ${flagError}` }- const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const workspace = await this.loadForEdit()const source = sourceProject(workspace, sourceNodeId)if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }if (!sourceCanControl(source.node, this.deps.agentIdOf)) {@@ -1124,9 +1154,9 @@ export class HeadlessNodeFactory {source.project.nodes = source.project.nodes.map((node) =>node.id === id ? renamed : node)- await this.deps.workspaceStore.save(workspace)+ await this.castAndSave(workspace)// Metadata only. In particular, Server Edition never mirrors `/rename` into the pane.- this.publish(source.project, [renamed])+ this.publish(source.project)return { ok: true, message: `renamed ${id} to "${title}"` }})}@@ -1150,7 +1180,7 @@ export class HeadlessNodeFactory {const owner = this.ownership.ownerOf(id)!const noNode: ServerControlReply = { ok: false, error: `run: no node with id ${id}` }if (args.project !== undefined && args.project !== owner.projectId) return noNode- const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const workspace = await this.loadForEdit()const project = workspace.projects.find((p) => p.id === owner.projectId)const node = project?.nodes.find((n) => n.id === id)if (!project || !node) return noNode@@ -1166,14 +1196,14 @@ export class HeadlessNodeFactory {}// Write-ahead, exactly as open() does before its own delivery.node.pendingLaunch = { ...held, attempted: true, manualOnly: true }- await this.deps.workspaceStore.save(workspace)+ await this.castAndSave(workspace)const launched = await this.launch(project, node, held.command)// 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.deps.workspaceStore.save(workspace)- this.publish(project, [node])+ await this.castAndSave(workspace)+ this.publish(project)return launched.outcome === 'delivered'? {ok: true,@@ -1195,7 +1225,7 @@ export class HeadlessNodeFactory {const color = resolveNodeColor(args.color)if (color === undefined) return { ok: false, error: invalidNodeColorMessage() }- const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const workspace = await this.loadForEdit()const source = sourceProject(workspace, sourceNodeId)if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }if (!sourceCanControl(source.node, this.deps.agentIdOf)) {@@ -1214,8 +1244,8 @@ 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.deps.workspaceStore.save(workspace)- this.publish(source.project, changed)+ await this.castAndSave(workspace)+ this.publish(source.project)const skipped = ids.length - changed.lengthconst note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''return {@@ -1252,7 +1282,7 @@ export class HeadlessNodeFactory {}}- const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const workspace = await this.loadForEdit()const source = sourceProject(workspace, sourceNodeId)if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }if (!sourceCanControl(source.node, this.deps.agentIdOf)) {@@ -1417,11 +1447,11 @@ export class HeadlessNodeFactory {target.nodes.push(...created)target.ropes = ropestarget.bridges = bridges- await this.deps.workspaceStore.save(workspace)+ await this.castAndSave(workspace)for (const node of created) {this.ownership.record(node.id, { sourceNodeId, projectId: target.id })}- this.publish(target, created)+ this.publish(target)if (issueRef) {for (const node of created) {await this.logRun(target.id, runStartedEvent(issueRef, {@@ -1466,8 +1496,8 @@ export class HeadlessNodeFactory {for (const node of created) {if (failed.includes(node.id) && node.pendingLaunch) node.pendingLaunch.manualOnly = true}- await this.deps.workspaceStore.save(workspace)- this.publish(target, created)+ await this.castAndSave(workspace)+ this.publish(target)const ids = created.map((node) => node.id)const queuedIds = created.filter((node) => node.pendingLaunch && !failed.includes(node.id))@@ -1504,7 +1534,7 @@ export class HeadlessNodeFactory {return this.runExclusive(async () => {const parsed = parseStickyArgs(args)if ('error' in parsed) return { ok: false, error: `sticky: ${parsed.error}` }- const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const workspace = await this.loadForEdit()const source = sourceProject(workspace, sourceNodeId)if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }if (!sourceCanControl(source.node, this.deps.agentIdOf)) {@@ -1554,11 +1584,11 @@ export class HeadlessNodeFactory {node.text = write.textnode.textUpdatedAt = (this.deps.now ?? Date.now)()node.textUpdatedBy = source.node.title || source.node.id- await this.deps.workspaceStore.save(workspace)+ await this.castAndSave(workspace)if (created) {this.ownership.record(node.id, { sourceNodeId, projectId: source.project.id })}- this.publish(source.project, [node])+ this.publish(source.project)return {ok: true,message: `${created ? 'created' : 'updated'} sticky ${node.id} (${write.mode})`,@@ -1585,8 +1615,9 @@ export class HeadlessNodeFactory {refreshArmed(observed?: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>): Promise<void> {return this.runExclusive(async () => {if (this.stopped) return- const workspace = await this.deps.workspaceStore.load({ sideline: false })- const changedByProject = new Map<Project, CanvasNodeState[]>()+ const workspace = await this.loadForEdit()+ // The projects whose arms moved. Their content is cast whole by `castAndSave`.+ const changedProjects = new Set<Project>()for (const project of workspace.projects) {for (const node of project.nodes) {@@ -1596,9 +1627,7 @@ export class HeadlessNodeFactory {// spawned for this caller during the current run may receive automatic input.if (!this.ownership.ownerOf(node.id)) continueconst markChanged = (): void => {- const list = changedByProject.get(project) ?? []- if (!list.includes(node)) list.push(node)- changedByProject.set(project, list)+ changedProjects.add(project)}if (observed?.state === 'working' && pending.awaitWorking?.includes(observed.nodeId)) {const remaining = pending.awaitWorking.filter((depId) => depId !== observed.nodeId)@@ -1631,7 +1660,7 @@ export class HeadlessNodeFactory {// acknowledgement save) must never be replayed by an unrelated hook.pending.manualOnly = truepending.attempted = true- await this.deps.workspaceStore.save(workspace)+ await this.castAndSave(workspace)markChanged()if (!isLaunchShell(await this.deps.ptyManager.paneCommand(node.id).catch(() => null))) continueif ((await this.deps.ptyManager.sendText(node.id, pending.command).catch(() => false)) !== true) continue@@ -1644,9 +1673,9 @@ 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 (changedByProject.size) {- await this.deps.workspaceStore.save(workspace)- for (const [project, nodes] of changedByProject) this.publish(project, nodes)+ if (changedProjects.size) {+ await this.castAndSave(workspace)+ for (const project of changedProjects) this.publish(project)}})}diff --git a/src/server/hosted-boot.test.ts b/src/server/hosted-boot.test.tsindex 6f28816e2..81f9c33e9 100644--- a/src/server/hosted-boot.test.ts+++ b/src/server/hosted-boot.test.ts@@ -64,7 +64,51 @@ describe('hosted team boot wiring (source)', () => {expect(body).toContain('await teamAdmin.close()')// Admin first: once it is closing, an in-flight `team init` can no longer start hosting.expect(body.indexOf('await teamAdmin.close()')).toBeLessThan(body.indexOf('hosted.stop()'))+ // The canvas authority writes what it still owes BEFORE the pty layer goes, after hosting and+ // canvas control stopped feeding it; then it is detached from the reflector and the store.+ const stop = body.indexOf('await canvasAuthority?.stop()')+ expect(stop, 'await canvasAuthority?.stop()').toBeGreaterThan(body.indexOf('hosted.stop()'))+ expect(stop).toBeGreaterThan(body.indexOf('canvasControl?.stop()'))+ expect(body.indexOf('setReflectedListener(null)')).toBeGreaterThan(stop)+ expect(body.indexOf('workspaceStore.setContentAuthority(null)')).toBeGreaterThan(stop)}+ expect(src.match(/canvasAuthority\?\.stop\(\)/g)?.length).toBe(2)+ })++ it('the canvas authority exists only where this process owns the team, and adopts at boot (R12a)', () => {+ const create = src.indexOf('createCanvasAuthority(')+ expect(create).toBeGreaterThan(0)+ expect(src.match(/createCanvasAuthority\(/g)?.length).toBe(1)+ // Never on the path where another server holds this data dir: that server is the one writer.+ const busy = src.indexOf('if (otherServerHere) {')+ const elseAt = src.indexOf('} else {', busy)+ expect(busy).toBeGreaterThan(0)+ expect(create).toBeGreaterThan(elseAt)+ expect(create).toBeLessThan(headlessAt)+ // Late-bound to the team store, fed by the reflector, and overlaid on every save and load.+ const block = src.slice(create, src.indexOf('hosted.start()', create))+ expect(block).toContain('sharedProjectIds: () => hosted.sharedProjectIds()')+ expect(block).toContain('workspaceStore.setContentAuthority(')+ expect(block).toContain('setReflectedListener(')+ // Every shared project is adopted ONCE at boot, after the index load and after hosting started+ // (start() loads the team file), before any outside edit could be adopted lazily: a lazy adoption+ // after a git pull reads the pulled file as its baseline and publishes no diff at all.+ const adopt = src.indexOf('authority.sharedChanged()')+ expect(adopt).toBeGreaterThan(src.indexOf('hosted.start()', create))+ expect(adopt).toBeGreaterThan(src.indexOf('await workspaceStore.load('))+ expect(adopt).toBeLessThan(headlessAt)+ expect(src.match(/authority\.sharedChanged\(\)/g)?.length).toBe(1)+ })++ it('outside edits are routed through the authority, and a share change re-announces the governed set', () => {+ expect(src).toMatch(/createServerWorkspaceWatcher\(workspaceStore, \{\s*publish: outsideEditPublisher\(/)+ const at = src.indexOf('onSharedChange:')+ expect(at).toBeGreaterThan(0)+ const body = src.slice(at, src.indexOf('\n },', at))+ expect(body).toContain('canvasAuthority?.sharedChanged()')+ expect(body).toContain('IPC.canvasAuthorityChanged')+ expect(body.indexOf('canvasAuthority?.sharedChanged()')).toBeLessThan(body.indexOf('IPC.canvasAuthorityChanged'))+ expect(src).toMatch(/platform\.handle\(IPC\.canvasAuthority, \(\) => canvasAuthority\?\.governedIds\(\) \?\? \[\]\)/)})it('relay peers share one teardown, in the order ws.ts uses', () => {diff --git a/src/server/hosted-e2e.test.ts b/src/server/hosted-e2e.test.tsindex 724f5ad2f..acf00630a 100644--- a/src/server/hosted-e2e.test.ts+++ b/src/server/hosted-e2e.test.ts@@ -4,7 +4,8 @@// verbs drive the same service the relay listeners belong to, the access policy sees the node and// project ids the real workspace store answers, the relay peer's requests reach the real platform// handlers, and a viewer's terminal is the owner's live one. The flow:-// team init → add-owner → share → the owner joins (auto-approved) and opens a terminal → a guest+// (the canvas is seeded through a WorkspaceStore before boot: a relay peer cannot save the host's+// workspace) team init → add-owner → share → the owner joins (auto-approved) and opens a terminal → a guest// knocks and waits → the owner approves it as a viewer → the viewer joins the owner's live// session, cannot start one, cannot write a file, cannot read the enclosing repository through git// → `team status` lists it as a connected viewer → `team unshare` silences its terminal.@@ -32,6 +33,9 @@ import fs from 'node:fs'import os from 'node:os'import path from 'node:path'import { startServer } from './index'+import { initPlatform, resetPlatformForTests } from '../core/platform'+import { fakePlatform } from '../core/platform-fake'+import { WorkspaceStore } from '../core/workspace-store'import { callTeamAdmin, type AdminInitResult, type AdminReply, type AdminStatusResult } from '../core/relay/team-admin'import { transportPair } from '../core/relay/transport-pair'import { connectRelayClient, type RelayClientSession } from '../core/relay/relay-client'@@ -315,6 +319,16 @@ describe.skipIf(process.platform === 'win32')('hosted team relay, end to end onteardown.push(() => fs.rmSync(repoBase, { recursive: true, force: true }))const { shared: sharedCwd } = repoWithSecret(repoBase)+ // The canvas is on this core before it boots: written through a WorkspaceStore on the SAME data+ // dir (the index, and the shared project's own .nodeterm/project.json). A relay peer can no longer+ // put it there — a hosted team never saves the host's workspace (step 2 checks the refusal).+ initPlatform(fakePlatform({ userDataDir: dataDir }))+ try {+ await step('seed the workspace', new WorkspaceStore().save(workspaceWith(sharedCwd)))+ } finally {+ resetPlatformForTests()+ }+const booting = startServer({port: 0,host: '127.0.0.1',@@ -360,8 +374,13 @@ describe.skipIf(process.platform === 'win32')('hosted team relay, end to end onbody: { hostPublicKeyB64: code.hostPublicKeyB64, deviceId: code.hostDeviceId }})- // The owner puts the canvas on this core and opens one terminal: that session is now live.- expect(await owner.call(IPC.workspaceSave, [workspaceWith(sharedCwd)])).toMatchObject({ ok: true })+ // Even the owner cannot save the host's workspace over the relay: shared content travels as+ // canvas ops, which the host's canvas authority writes (docs/hosted-team-relay.md).+ expect(await owner.call(IPC.workspaceSave, [workspaceWith(sharedCwd)])).toMatchObject({+ ok: false,+ error: { code: 'E_ROLE', message: expect.stringMatching(/cannot save the host's workspace over the relay/) }+ })+ // The owner opens one terminal of the seeded canvas: that session is now live.const opened = await owner.call(IPC.ptyCreate, [{ cols: 120, rows: 40, persistKey: LIVE }])expect(opened).toMatchObject({ ok: true, result: { fresh: true } })const ownerSessionId = (opened.result as PtyCreateResult).sessionIddiff --git a/src/server/index.ts b/src/server/index.tsindex 33fb221fc..b959d9d50 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -97,10 +97,11 @@ import { codexCliCaps } from '../core/codex-cli'import type { CodexCliCaps } from '../shared/types'import { claudeConfigDirFor, registerClaudeAccountsSource } from '../core/claude-config-dir'import { presenceHub } from '../core/presence/hub'-import { initCanvasSync } from '../core/canvas-sync'+import { initCanvasSync, publishCanvasMutation, setReflectedListener } from '../core/canvas-sync'+import { createCanvasAuthority, type CanvasAuthority } from '../core/canvas-authority'import { wireAgentStatus } from './agent-status'import { initServerContextLink } from './context-link'-import { createServerWorkspaceWatcher } from './workspace-external-watch'+import { createServerWorkspaceWatcher, outsideEditPublisher } from './workspace-external-watch'import { registerTranscriptIpc } from '../core/transcript-ipc'import { registerContextEnsureIpc } from '../core/context-ensure'import { IPC } from '@shared/ipc'@@ -276,6 +277,13 @@ export async function startServer(// Canvas sync: reflect each browser tab's node mutations to the other attached tabs, so every// client converges on the same node set (and no tab writes back a node another tab deleted).initCanvasSync()+ // The canvas authority (docs/hosted-team-relay.md): the one writer of the content of every project+ // shared with a hosted team. Created further down, and only where this process owns the team (not+ // when another server holds this data dir); read late by everything below that needs it. Until+ // then — and forever on a server that does not own the team — nothing is governed.+ let canvasAuthority: CanvasAuthority | null = null+ // A client asks which projects are governed, to publish its ops for them even when it is alone.+ platform.handle(IPC.canvasAuthority, () => canvasAuthority?.governedIds() ?? [])// Team presence (hello / cursor / focus / chat). The hub itself is joined per WebSocket in// ws.ts; this only registers the RPC surface. Presence is transient — nothing is persisted.presenceHub.registerIpc()@@ -696,7 +704,14 @@ export async function startServer(canvases: () => workspaceStore.persistedCanvases(),installAgentIntegrations: config.installHooks !== false})- const workspaceWatcher = createServerWorkspaceWatcher(workspaceStore)+ // A governed project's outside edit goes to the canvas authority, which publishes the difference+ // as canvas ops; every other project keeps the whole-project `workspace:external-change`.+ const workspaceWatcher = createServerWorkspaceWatcher(workspaceStore, {+ publish: outsideEditPublisher(+ () => canvasAuthority,+ (project) => platform.broadcast(IPC.workspaceExternalChange, project)+ )+ })// Every load()/save() is a canvas change as far as links are concerned: a browser drawing a// bridge edge reaches us as the workspace save it triggers. It also refreshes the local-ref// watcher set, so projects added or removed while the server runs get the same hand-edit path.@@ -895,6 +910,12 @@ export async function startServer(// stop a stream the viewer already joined). One map lookup.nodeOfSession: (sessionId) => ptyManager.nodeOfSession(sessionId),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).+ onSharedChange: () => {+ canvasAuthority?.sharedChanged()+ platform.broadcast(IPC.canvasAuthorityChanged, canvasAuthority?.governedIds() ?? [])+ },// TEST ONLY seams (see ServerConfig): never set by resolveConfig, so production dials the relay// and mints against API_BASE with the global fetch....(config.relayTestTransport ? { transport: config.relayTestTransport } : {}),@@ -918,6 +939,23 @@ export async function startServer(`directory (${config.dataDir}). Stop it, or give this server its own --data-dir.`)} else {+ // This process owns the team, so it owns the shared projects' content. Wired BEFORE hosting+ // starts, so no relay peer's op can reach the reflector before the authority listens to it.+ // `sharedProjectIds` is read on every call (the team store is the one source).+ const authority = createCanvasAuthority({+ sharedProjectIds: () => hosted.sharedProjectIds(),+ readContent: (id) => workspaceStore.readProjectContent(id),+ writeContent: (id, content) => workspaceStore.writeProjectContent(id, content),+ publish: (id, m) => {+ publishCanvasMutation(id, m)+ },+ log: (message) => console.warn(`[canvas-authority] ${message}`)+ })+ canvasAuthority = authority+ workspaceStore.setContentAuthority(authority)+ // Synchronous and in seq order (canvas-sync.ts): the authority's own published diff echoes back+ // through here while it is still publishing.+ setReflectedListener((id, m) => authority.onReflected(id, m))const hostedStart = await hosted.start().catch((err: unknown) => {console.error('[hosted-team] start failed:', err)return null@@ -926,6 +964,11 @@ export async function startServer(else if (hostedStart === 'host-key-unreadable') {console.error('Hosted team relay: OFF — the host key could not be read (see above; `team status`).')}+ // Adopt every shared project NOW, once: `start()` has loaded the team file (the shared set is not+ // known before it), and the index load above has run. An outside edit adopted lazily would read+ // the edited file as its own baseline and publish no difference at all, so every shared project+ // needs its baseline before the watcher can hand one over.+ authority.sharedChanged()}// Headless notification host: every core service above (incl. the loopback hook server, which@@ -951,6 +994,10 @@ export async function startServer(canvasControl?.stop()workspaceWatcher.dispose()await contextLink.stop()+ // Write what the canvas authority still owes, then detach it from the reflector and the store.+ await canvasAuthority?.stop()+ setReflectedListener(null)+ workspaceStore.setContentAuthority(null)await ptyManager.killAll()// Same native hazard as the desktop app: a whisper transcribe still running when the// node env is torn down aborts the process. See SpeechService.shutdown.@@ -1009,6 +1056,10 @@ export async function startServer(canvasControl?.stop()workspaceWatcher.dispose()await contextLink.stop()+ // Write what the canvas authority still owes (see the headless close() above).+ await canvasAuthority?.stop()+ setReflectedListener(null)+ workspaceStore.setContentAuthority(null)await ptyManager.killAll()// Same native hazard as the desktop app: a whisper transcribe still running when the node// env is torn down aborts the process. See SpeechService.shutdown.diff --git a/src/server/workspace-external-watch.test.ts b/src/server/workspace-external-watch.test.tsindex 224312637..3eccd0412 100644--- a/src/server/workspace-external-watch.test.ts+++ b/src/server/workspace-external-watch.test.ts@@ -7,9 +7,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { fakePlatform, type FakePlatform } from '../core/platform-fake'import { initPlatform, resetPlatformForTests } from '../core/platform'import { WorkspaceStore } from '../core/workspace-store'+import { createCanvasAuthority } from '../core/canvas-authority'+import { initCanvasSync, publishCanvasMutation, setReflectedListener } from '../core/canvas-sync'import { IPC } from '../shared/ipc'-import type { CanvasNodeState, Project, Workspace } from '../shared/types'-import { createServerWorkspaceWatcher } from './workspace-external-watch'+import type { CanvasMutation, CanvasNodeState, Project, Workspace } from '../shared/types'+import { createServerWorkspaceWatcher, outsideEditPublisher } from './workspace-external-watch'const node = (id: string, x: number): CanvasNodeState => ({id,@@ -105,4 +107,102 @@ describe('Server Edition external workspace watcher', () => {// channel a later refactor might mistake it for (that one merges silently, no question asked).expect(fake.sent.filter((entry) => entry.channel === IPC.workspaceServerChange)).toEqual([])})++ it('routes a GOVERNED project\'s outside edit through the canvas authority: ops, never the conflict bar', async () => {+ const otherDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nodeterm-server-watch-other-'))+ try {+ const a = node('term-a', 0)+ const b = node('term-b', 720)+ const governedProject: Project = {+ id: 'project-g',+ name: 'Governed',+ color: '#0a84ff',+ cwd: projectDir,+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [a, b],+ bridges: [{ id: 'bridge-ab', source: a.id, target: b.id }],+ ropes: []+ }+ const plainProject: Project = {+ id: 'project-u',+ name: 'Ungoverned',+ color: '#0a84ff',+ cwd: otherDir,+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [node('term-u', 0)],+ bridges: [],+ ropes: []+ }+ const store = new WorkspaceStore()+ await store.save({ version: 2, activeProjectId: governedProject.id, projects: [governedProject, plainProject] })+ initCanvasSync()+ fake.clients.push(1)+ const authority = createCanvasAuthority({+ sharedProjectIds: () => new Set([governedProject.id]),+ readContent: (id) => store.readProjectContent(id),+ writeContent: (id, c) => store.writeProjectContent(id, c),+ publish: (id, m) => {+ publishCanvasMutation(id, m)+ },+ setTimer: () => null,+ clearTimer: () => {},+ log: () => {}+ })+ store.setContentAuthority(authority)+ setReflectedListener((id, m) => authority.onReflected(id, m))+ // Boot adopts every shared project eagerly, BEFORE any outside edit can arrive: a lazy adoption+ // after the edit would read the edited file as its baseline and publish no diff at all.+ authority.sharedChanged()+ await authority.flushAll()+ fake.sent.length = 0+ watcher = createServerWorkspaceWatcher(store, {+ debounceMs: 20,+ publish: outsideEditPublisher(+ () => authority,+ (p) => fake.broadcast(IPC.workspaceExternalChange, p)+ )+ })++ // A git pull removes the bridge from the governed project.+ const file = path.join(projectDir, '.nodeterm', 'project.json')+ const edited = JSON.parse(await fs.readFile(file, 'utf8')) as { rev: number; updatedAt: string; bridges: unknown[] }+ edited.rev += 1+ edited.updatedAt = new Date(Date.now() + 1_000).toISOString()+ edited.bridges = []+ await fs.writeFile(file, JSON.stringify(edited), 'utf8')+ const muts = (): CanvasMutation[] =>+ fake.sent.filter((e) => e.channel === IPC.canvasMut && e.args[0] === governedProject.id).map((e) => e.args[1] as CanvasMutation)+ await vi.waitFor(() => {+ expect(muts().map((m) => m.op)).toEqual(['edge-remove'])+ }, { timeout: 3_000, interval: 20 })+ expect(muts()[0]).toMatchObject({ op: 'edge-remove', id: 'bridge-ab', seq: expect.any(Number) })+ expect(fake.sent.filter((e) => e.channel === IPC.workspaceExternalChange)).toEqual([])++ // The ungoverned project keeps the whole-project broadcast.+ const otherFile = path.join(otherDir, '.nodeterm', 'project.json')+ const other = JSON.parse(await fs.readFile(otherFile, 'utf8')) as { rev: number; updatedAt: string; nodes: CanvasNodeState[] }+ other.rev += 1+ other.updatedAt = new Date(Date.now() + 2_000).toISOString()+ other.nodes = []+ await fs.writeFile(otherFile, JSON.stringify(other), 'utf8')+ await vi.waitFor(() => {+ expect(fake.sent.some((e) => e.channel === IPC.workspaceExternalChange)).toBe(true)+ }, { timeout: 3_000, interval: 20 })+ const broadcast = fake.sent.filter((e) => e.channel === IPC.workspaceExternalChange)+ expect(broadcast.map((e) => (e.args[0] as Project).id)).toEqual([plainProject.id])+ expect(fake.sent.filter((e) => e.channel === IPC.canvasMut && e.args[0] === plainProject.id)).toEqual([])+ await authority.stop()+ } finally {+ setReflectedListener(null)+ await fs.rm(otherDir, { recursive: true, force: true })+ }+ })++ it('with no authority (another server owns this data dir), every outside edit is broadcast', () => {+ const sent: Project[] = []+ const route = outsideEditPublisher(() => null, (p) => sent.push(p))+ const p = { id: 'x', name: 'x', color: '#000', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [] } as Project+ route(p)+ expect(sent).toEqual([p])+ })})diff --git a/src/server/workspace-external-watch.ts b/src/server/workspace-external-watch.tsindex b3b032b42..f5135273f 100644--- a/src/server/workspace-external-watch.ts+++ b/src/server/workspace-external-watch.ts@@ -1,4 +1,5 @@import { platform } from '../core/platform'+import type { CanvasAuthority } from '../core/canvas-authority'import type { WorkspaceStore } from '../core/workspace-store'import { WorkspaceWatcher } from '../core/workspace-watcher'import { IPC } from '../shared/ipc'@@ -44,3 +45,31 @@ export function createServerWorkspaceWatcher(watcher.sync()return watcher}++/**+ * Where a genuine outside edit (a git pull, a hand edit) goes. A project the canvas authority+ * governs is ADOPTED by it, and its content reaches every client as canvas ops+ * (docs/hosted-team-relay.md). It is NOT also broadcast as `workspace:external-change`: that event+ * raises the Reload/Keep-mine conflict bar on a dirty canvas, and "Keep mine" would write a stale+ * copy over the shared project. Every other project keeps the whole-project broadcast. `authority`+ * is read on every edit (it is created later in boot, and absent when another server owns the data+ * directory).+ *+ * Residual: a governed outside edit's NON-content fields (name, colour, icon, layouts) reach no+ * client live; clients see them on their next load.+ */+export function outsideEditPublisher(+ authority: () => Pick<CanvasAuthority, 'governs' | 'adoptOutsideEdit'> | null,+ broadcast: (project: Project) => void+): (project: Project) => void {+ return (project) => {+ const a = authority()+ if (a?.governs(project.id)) {+ void a.adoptOutsideEdit(project).catch((error: unknown) => {+ console.warn('[nodeterm-server] the canvas authority could not adopt an outside edit', error)+ })+ return+ }+ broadcast(project)+ }+}diff --git a/src/shared/canvas-publish.ts b/src/shared/canvas-publish.tsindex ff2b471f5..8ba2f292d 100644--- a/src/shared/canvas-publish.ts+++ b/src/shared/canvas-publish.ts@@ -140,6 +140,16 @@ const EMPTY_SCENE: CanvasScene = { nodes: [], bridges: [], ropes: [] }* resolves it to diff against. Same baseline, same mutations — the work is merely deferred to the* 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+ * (docs/hosted-team-relay.md), so a solo edit there that is not published is never saved.+ */+export function shouldPublishCanvas(gate: { hasPeers: boolean; governed: boolean }): boolean {+ return gate.hasPeers || gate.governed+}+export function createCanvasPublisher(send: (m: CanvasMutation) => void | boolean,opts: { intervalMs?: number; src?: string; shouldPublish?: () => boolean } = {}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex c550fb47d..86af4a444 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -248,6 +248,12 @@ export const IPC = {* SAME channel to EVERY attached client — the sender included, whose copy is its ack (see* src/shared/canvas-order.ts). Args (both directions): [projectId: string, CanvasMutation]. */canvasMut: 'canvas:mut',+ /** Which projects this core's canvas authority governs (request → `string[]`): a client publishes+ * its canvas ops for them even when nobody else is attached, because the authority writes only+ * what it hears as ops (docs/hosted-team-relay.md). Server Edition only; the desktop answers none. */+ canvasAuthority: 'canvas:authority',+ /** Event: the governed set changed (`string[]`, the new set). Server Edition only. */+ canvasAuthorityChanged: 'canvas:authority-changed',contextLinkSetLinks: 'context-link:set-links',contextLinkInfo: 'context-link:info',/** Board-log (`.nodeterm/board-log.jsonl`): request/response append + read, routed per projectdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 74bd5d923..442f94a6c 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3000,6 +3000,19 @@ export interface CanvasApi {onMutation(listener: (projectId: string, mutation: CanvasMutation) => void): () => void}+/**+ * Which of this core's projects a canvas authority governs (the Server Edition hosting a team,+ * docs/hosted-team-relay.md). The authority writes a governed project's content only from the ops it+ * hears, so a client must publish its canvas ops for such a project even when nobody else is+ * attached — the solo gate is overridden for it. The desktop runs no authority and governs nothing.+ */+export interface CanvasAuthorityApi {+ /** 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. */+ onChanged(listener: (ids: string[]) => void): () => void+}+/** One searchable line extracted from a Claude session transcript. */export interface TranscriptLine {role: 'user' | 'assistant' | 'tool'@@ -3966,6 +3979,8 @@ export interface NodeTerminalApi {triggers: TriggersApicontext: ContextApicanvas: CanvasApi+ /** Which projects publish their canvas ops even when alone (see CanvasAuthorityApi). */+ canvasAuthority: CanvasAuthorityApicodex: CodexApiclaude: ClaudeApigrok: GrokApi