Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas-authority): send a governed outside edit's persisted project on workspace:server-change (D2, R15)
review2fa3579b239a
diff --git a/CLAUDE.md b/CLAUDE.mdindex f6d87203d..6e4c05c49 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -289,7 +289,9 @@ Persistence has two layers:ride `workspace:external-change`, and so do the phone's `appendRemoteNode` and the SSHreconcile, which really are "another device". The exception is a project a hosted Server Editionshares with its team: the canvas authority adopts that outside edit and publishes it as- `canvas:mut` ops, with no `workspace:external-change` (see **Hosted team relay**).+ `canvas:mut` ops, with no `workspace:external-change`, then sends the persisted project on+ `workspace:server-change` so its non-content fields (name, permission default, capability flags…)+ reach the tabs too (see **Hosted team relay**).**A write this core made ITSELF rides `workspace:server-change` instead** — today that is ServerEdition headless canvas control (`server/canvas-control.ts`) — and the renderer three-way mergesit against the store baseline (`renderer/lib/serverChange.ts`: incoming nodes adopted silently,@@ -7355,8 +7357,10 @@ The invariants, each with its reason:team). A client's whole-workspace save is a stale copy of every canvas it holds, so saves ANDloads pass through the authority's overlay (`WorkspaceStore.setContentAuthority`), and an outsideedit (a `git pull`) is adopted and published as ops instead of `workspace:external-change`, whose- conflict bar would offer "Keep mine" over it. It writes 1 s after the last op, at most 5 s after- the first. The consequence for code: **a content change that is not cast as an op is dropped by+ conflict bar would offer "Keep mine" over it; the persisted project follows on+ `workspace:server-change` (silent merge), or a stale tab's autosave would revert the pulled+ non-content fields, `defaultPermissionMode` and the capability flags included. It writes 1 s+ after the last op, at most 5 s after the first. The consequence for code: **a content change that is not cast as an op is dropped bythe next overlaid save.** That is why server canvas control casts a diff of the whole contentbefore every save (`castAndSave`, never a per-verb list, which drifts), and why a hosted relaypeer may not `workspace:save` at all (refused for every role). One exception: a node too large@@ -7388,9 +7392,9 @@ The invariants, each with its reason:**Known limitations** (full list in the doc): non-editors still receive cross-project presence and`context:update` metadata (deploy one core per team); a viewer's socket backlog over 1 MB still-pauses the shared pty through Stage 2 backpressure; the canvas authority's own limits (outside edits-of name/colour/icon/layouts, the share-time window, oversized nodes, board edits to another core,-the card modal's comments on a relay tab) are under "Known limits" in the doc.+pauses the shared pty through Stage 2 backpressure; the canvas authority's own limits (a project's+non-content fields stay last writer wins between tabs, the share-time window, oversized nodes, board+edits to another core, the card modal's comments on a relay tab) are under "Known limits" in the doc.**Surfaces:** Desktop is full (joiner, plus approval and invite code in an owner's hosted tab).Server Edition is the host (the `team` CLI; its browser clients cannot approve and are not hosteddiff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.mdindex 749086145..4e6f58421 100644--- a/docs/hosted-team-relay.md+++ b/docs/hosted-team-relay.md@@ -350,7 +350,12 @@ whole-workspace saves still write them.4. **Outside edits.** A `git pull` or hand edit of a governed `.nodeterm/project.json`, seen by theserver's file watcher, is adopted: the authority re-applies the ops it has not written yet on top,publishes the difference as `canvas:mut` ops, and broadcasts no `workspace:external-change`, so no- client gets the Reload / Keep mine bar (`src/server/workspace-external-watch.ts`).+ client gets the Reload / Keep mine bar (`src/server/workspace-external-watch.ts`). The edit's other+ fields (name, colour, icon, layouts, the permission default, the capability flags, the board's+ `github` and `pullLinks`) follow right after the ops, as the persisted project on+ `workspace:server-change`, the channel server canvas control uses. The browser merges it without+ a bar, so a tab that still held the old values saves the pulled ones instead of writing its own+ back.**Writing.** A governed project is written 1 s after its last op, and at most 5 s after the first opnot yet written, through the store's atomic content write (`WorkspaceStore.writeProjectContent`: it@@ -397,10 +402,11 @@ it is a new way to use it.### Known limits-- **An outside edit's other fields are not delivered live.** A pulled change to a governed project's- name, colour, icon or layouts reaches no client until that client loads again. A Server Edition- browser tab that saves before it reloads writes its own copies back over the pulled ones: those- fields are still whole-file, last writer wins.+- **A project's other fields are last writer wins.** Name, colour, icon, layouts, the permission+ default, the capability flags and the board's `github`/`pullLinks` are not ops. A pulled change to+ them reaches every browser tab (`workspace:server-change`), but two tabs editing one of them at the+ same time still overwrite each other on save, as before the authority. A desktop joined over the+ relay does not save the host's workspace at all.- **The share-time window.** An edit a client made just before `team share` (not yet cast because itwas alone, or cast but not yet saved) is not in what the authority reads from disk, and thatclient's next save is overlaid, so the edit can be lost from disk. It stays on that client's screendiff --git a/src/core/canvas-authority.test.ts b/src/core/canvas-authority.test.tsindex a1263550f..d5019ea2f 100644--- a/src/core/canvas-authority.test.ts+++ b/src/core/canvas-authority.test.ts@@ -407,6 +407,28 @@ describe('canvas authority — outside edits', () => {expect(h.writes[0].content.kanban?.assignments).toEqual([{ nodeId: 'a', columnId: 'kx' }])})+ it('11f. answers the project as a load now returns it: the edit\'s own fields, the authority\'s content (R15)', async () => {+ const h = harness({ disk: { P: content([node('a'), node('b')]) } })+ await h.authority.overlayLoad(ws(project({ nodes: [node('a'), node('b')] })))+ h.cast({ op: 'upsert', node: node('c') })+ await settle()+ const persisted = await h.authority.adoptOutsideEdit(+ project({+ name: 'Renamed',+ defaultPermissionMode: 'manual',+ nodes: [node('a', { shell: '/bin/zsh' }), node('d')]+ })+ )+ expect(persisted).not.toBeNull()+ // The non-content fields come from the edit: they are what a stale tab would otherwise revert.+ expect(persisted?.name).toBe('Renamed')+ expect(persisted?.defaultPermissionMode).toBe('manual')+ // The content is the authority's: the edit with the unflushed op re-applied on top.+ expect(ids(persisted?.nodes ?? [])).toEqual(['a', 'd', 'c'])+ // This machine's exec rides from the edit's own copy, exactly as on a load.+ expect(shellOf(byId(persisted?.nodes ?? [], 'a'))).toBe('/bin/zsh')+ })+it('11d. an unavailable or relay project is never adopted as an outside edit', async () => {const h = harness({ disk: { P: content([node('a'), node('b')]) } })await h.authority.overlayLoad(ws(project({ nodes: [node('a'), node('b')] })))diff --git a/src/core/canvas-authority.ts b/src/core/canvas-authority.tsindex 6e91b6ea8..89a65bed0 100644--- a/src/core/canvas-authority.ts+++ b/src/core/canvas-authority.ts@@ -81,8 +81,11 @@ export interface CanvasAuthority {overlaySave(ws: Workspace): Promise<Workspace>/** Governed projects' content fields replaced by the authority's (the store's load hook). */overlayLoad(ws: Workspace): Promise<Workspace>- /** A project re-read after an outside edit (a git pull, a hand edit). */- adoptOutsideEdit(project: Project): Promise<void>+ /** A project re-read after an outside edit (a git pull, a hand edit): its content is adopted and+ * the difference published as ops. Answers the project exactly as a load now returns it (the+ * edit's own non-content fields, overlaid with the authority's content), for the shell to send to+ * every client on `workspace:server-change`; null = nothing was adopted. */+ adoptOutsideEdit(project: Project): Promise<Project | null>/** The shared set changed: flush and release what left it, adopt what joined it. */sharedChanged(): void/** Write every dirty project now. */@@ -419,10 +422,10 @@ export function createCanvasAuthority(deps: CanvasAuthorityDeps): CanvasAuthoritreturn { ...ws, projects }},- async adoptOutsideEdit(project: Project): Promise<void> {- if (!overlayable(project) || !governs(project.id)) return+ async adoptOutsideEdit(project: Project): Promise<Project | null> {+ if (!overlayable(project) || !governs(project.id)) return nullconst g = await adopt(project.id)- if (!g || !governs(project.id) || governed.get(project.id) !== g) return+ if (!g || !governs(project.id) || governed.get(project.id) !== g) return nullconst before = g.content// ADOPT the edit, then re-apply what disk does not have yet on top of it (rule 3).let after = governedContent(project)@@ -433,6 +436,10 @@ export function createCanvasAuthority(deps: CanvasAuthorityDeps): CanvasAuthoritfor (const m of diffContent(before, after, project.id)) deps.publish(project.id, m)// Disk already has the edit. It is owed a write only if our unflushed ops must go over it.if (g.unflushed.length) markDirty(project.id, g)+ // The ops carry the content; the edit's OTHER fields (name, colour, icon, layouts, the+ // permission default, the capability flags, the board's github mapping) reach no client+ // through them. Answered as a load would answer it, so the shell can send it whole.+ return overlayProject(project, g, 'load')},sharedChanged(): void {diff --git a/src/server/index.ts b/src/server/index.tsindex 03576a4cb..1bcb8cd95 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -711,11 +711,13 @@ export async function startServer(installAgentIntegrations: config.installHooks !== false})// 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`.+ // as canvas ops and then the persisted project on `workspace:server-change` (its non-content+ // fields); every other project keeps the whole-project `workspace:external-change`.const workspaceWatcher = createServerWorkspaceWatcher(workspaceStore, {publish: outsideEditPublisher(() => canvasAuthority,- (project) => platform.broadcast(IPC.workspaceExternalChange, project)+ (project) => platform.broadcast(IPC.workspaceExternalChange, project),+ (project) => platform.broadcast(IPC.workspaceServerChange, project))})// Every load()/save() is a canvas change as far as links are concerned: a browser drawing adiff --git a/src/server/workspace-external-watch.test.ts b/src/server/workspace-external-watch.test.tsindex 3eccd0412..a126dd994 100644--- a/src/server/workspace-external-watch.test.ts+++ b/src/server/workspace-external-watch.test.ts@@ -159,7 +159,8 @@ describe('Server Edition external workspace watcher', () => {debounceMs: 20,publish: outsideEditPublisher(() => authority,- (p) => fake.broadcast(IPC.workspaceExternalChange, p)+ (p) => fake.broadcast(IPC.workspaceExternalChange, p),+ (p) => fake.broadcast(IPC.workspaceServerChange, p))})@@ -198,9 +199,99 @@ describe('Server Edition external workspace watcher', () => {}})+ it('a GOVERNED outside edit\'s other fields reach clients on workspace:server-change, and a stale tab\'s next save keeps them (R15)', async () => {+ const a = node('term-a', 0)+ const governedProject: Project = {+ id: 'project-g',+ name: 'Governed',+ color: '#0a84ff',+ cwd: projectDir,+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [a],+ defaultPermissionMode: 'bypassPermissions'+ }+ const store = new WorkspaceStore()+ await store.save({ version: 2, activeProjectId: governedProject.id, projects: [governedProject] })+ 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))+ try {+ authority.sharedChanged()+ await authority.flushAll()+ fake.sent.length = 0+ watcher = createServerWorkspaceWatcher(store, {+ debounceMs: 20,+ publish: outsideEditPublisher(+ () => authority,+ (p) => fake.broadcast(IPC.workspaceExternalChange, p),+ (p) => fake.broadcast(IPC.workspaceServerChange, p)+ )+ })++ // A git pull renames the project and TIGHTENS its permission default (and moves a node).+ const file = path.join(projectDir, '.nodeterm', 'project.json')+ const edited = JSON.parse(await fs.readFile(file, 'utf8')) as {+ rev: number+ updatedAt: string+ name: string+ defaultPermissionMode?: string+ nodes: CanvasNodeState[]+ }+ edited.rev += 1+ edited.updatedAt = new Date(Date.now() + 1_000).toISOString()+ edited.name = 'Renamed'+ edited.defaultPermissionMode = 'manual'+ edited.nodes = edited.nodes.map((n) => ({ ...n, position: { x: 500, y: 0 } }))+ await fs.writeFile(file, JSON.stringify(edited), 'utf8')++ await vi.waitFor(() => {+ expect(fake.sent.some((e) => e.channel === IPC.workspaceServerChange)).toBe(true)+ }, { timeout: 3_000, interval: 20 })+ const changes = fake.sent.filter((e) => e.channel === IPC.workspaceServerChange)+ expect(changes).toHaveLength(1)+ const incoming = changes[0].args[0] as Project+ expect(incoming.id).toBe(governedProject.id)+ expect(incoming.name).toBe('Renamed')+ expect(incoming.defaultPermissionMode).toBe('manual')+ expect(incoming.nodes.map((n) => n.position.x)).toEqual([500])+ // Still no conflict bar: the content travelled as ops, the rest merges silently.+ expect(fake.sent.filter((e) => e.channel === IPC.workspaceExternalChange)).toEqual([])+ // The ops went out BEFORE the project, so a client merging it already holds the content.+ const lastOp = fake.sent.map((e) => e.channel).lastIndexOf(IPC.canvasMut)+ expect(lastOp).toBeGreaterThanOrEqual(0)+ expect(lastOp).toBeLessThan(fake.sent.findIndex((e) => e.channel === IPC.workspaceServerChange))++ // A tab that still held the OLD copy adopts the incoming project (`replaceProject`, which is+ // what the renderer does with workspace:server-change) and saves: the pulled values stay.+ const tabCopy: Project = incoming+ await store.save({ version: 2, activeProjectId: tabCopy.id, projects: [tabCopy] })+ const onDisk = JSON.parse(await fs.readFile(file, 'utf8')) as { name: string; defaultPermissionMode?: string }+ expect(onDisk.name).toBe('Renamed')+ expect(onDisk.defaultPermissionMode).toBe('manual')+ await authority.stop()+ } finally {+ setReflectedListener(null)+ store.setContentAuthority(null)+ }+ })+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 route = outsideEditPublisher(() => null, (p) => sent.push(p), () => {+ throw new Error('an ungoverned edit is never a server change')+ })const p = { id: 'x', name: 'x', color: '#000', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [] } as Projectroute(p)expect(sent).toEqual([p])diff --git a/src/server/workspace-external-watch.ts b/src/server/workspace-external-watch.tsindex f5135273f..dbb16722e 100644--- a/src/server/workspace-external-watch.ts+++ b/src/server/workspace-external-watch.ts@@ -52,22 +52,34 @@ export function createServerWorkspaceWatcher(* (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+ * is read on every edit (it is created later in boot, and absent when another server owns this 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.+ * The ops carry only the content. The edit's other fields (name, colour, icon, layouts, the+ * permission default, the capability flags, the board's `github` mapping and `pullLinks`) follow as+ * the persisted project on `workspace:server-change` (`serverChange`), the channel and three-way+ * merge server canvas control already uses: the renderer adopts it without a conflict bar, so a tab+ * that still held the old copy saves the pulled values instead of writing its own back. Some of+ * those fields are security-relevant (a pull that drops a `bypassPermissions` default or turns a+ * capability off must not be undone by the next autosave). The ops go out first, so a client+ * merging the project already holds its content.*/export function outsideEditPublisher(authority: () => Pick<CanvasAuthority, 'governs' | 'adoptOutsideEdit'> | null,- broadcast: (project: Project) => void+ broadcast: (project: Project) => void,+ serverChange: (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)- })+ void a+ .adoptOutsideEdit(project)+ .then((persisted) => {+ if (persisted) serverChange(persisted)+ })+ .catch((error: unknown) => {+ console.warn('[nodeterm-server] the canvas authority could not adopt an outside edit', error)+ })return}broadcast(project)