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-sync): cast every own store write into an off-screen governed project (N2, extended)
review32142b02ffae
diff --git a/CLAUDE.md b/CLAUDE.mdindex 9b6bd5898..a7a5af965 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -7386,10 +7386,13 @@ The invariants, each with its reason:own node writes into a background project are not received ops and take `applyOwnNodeMutation`(unstripped: the held launch is ours to set or clear — see the `pendingLaunch` paragraph). **Thenode publisher never casts them** (it diffs React Flow, and a load is ADOPTED as its baseline), so- that store path and `appendCanvasLinks` hand every write to `setStoredCanvasPublishHook`, which- Canvas casts only for a GOVERNED project that is not the one React Flow holds- (`canvas/stored-publish.ts`): without it a ⌘⇧T reopen or a cold open into an off-screen shared- project was dropped from disk by the next overlaid save. An ungoverned project casts nothing new.+ every own writer of the projects store (`applyOwnNodeMutation`, `appendCanvasLinks`, and the+ sessions sidebar's `renameNode` / `recolorNode` / `removeNode` / `moveNodeToGroup` / …) runs+ through `ownWrite`, which hands a lazy diff of the project's nodes and edges to+ `setStoredCanvasPublishHook`; Canvas casts it only for a GOVERNED project that is not the one React+ Flow holds (`canvas/stored-publish.ts`). Without it a ⌘⇧T reopen or a cold open into an off-screen+ shared project was dropped from disk by the next overlaid save, and a sidebar close killed the+ session while the overlay put the node back. An ungoverned project casts nothing new.- **The solo-gate trap.** The publisher casts nothing while no teammate is attached, and on a governedproject that loses every edit. The gate is `shouldPublishFor` = `(hasPeers || governed) && sameCore&& !readOnly`: a Server Edition tab publishes every project until its first `canvas:authority`diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 68ee214e4..5d5b9463a 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -497,9 +497,9 @@ anything else. Board-level fields survive every transform — `pullLinks` is oneEdition hosting a team, the canvas authority writes a shared project's nodes, edges and boardfrom the ops it hears, and overlays every save with that content, so a content change that reachesthe core only inside a save is dropped from disk. A renderer write into a project that is NOT on- screen goes through the projects store's `applyOwnNodeMutation` / `appendCanvasLinks`, whose- publish hook casts it (`canvas/stored-publish.ts`); a new store writer of that kind must call the- hook too. Deep version: CLAUDE.md § Hosted team relay.+ screen goes through the projects store, whose node and edge writers run inside `ownWrite` so the+ write is cast (`canvas/stored-publish.ts`); a new store writer of that kind must use `ownWrite`+ too. Deep version: CLAUDE.md § Hosted team relay.- **Normalize BOTH sides of a path comparison, through one function.** A marker normalized whereit is built and matched raw where it is used is a no-op on the machine you wrote it on and adiff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.mdindex b1d262c2f..8cfb4ee3b 100644--- a/docs/hosted-team-relay.md+++ b/docs/hosted-team-relay.md@@ -335,10 +335,11 @@ whole-workspace saves still write them.1. **Ops**: from Editors' hosted tabs, from the server's own browser tabs, and from server canvascontrol, which diffs everything a verb changed and casts each op before it saves (`castAndSave`,`src/server/headless-node-factory.ts`). A tab also casts what it writes into a governed project- it is not showing (a ⌘⇧T or "Recently closed" reopen, a cold open, an off-canvas node or link):- those writes go to its projects store, not its canvas, so the store hands each one to the publish- hook (`src/renderer/canvas/stored-publish.ts`). Without the cast the next overlaid save would- drop them.+ it is not showing (a ⌘⇧T or "Recently closed" reopen, a cold open, an off-canvas node or link, a+ rename, move, duplicate or close from the sessions sidebar): those writes go to its projects+ store, not its canvas, so the store hands each one to the publish hook+ (`src/renderer/canvas/stored-publish.ts`). Without the cast the next overlaid save would drop+ them, and a sidebar close would end the session while the node stayed on disk.2. **Saves.** Before a whole-workspace save is written, a governed project's content is replaced bythe authority's (`overlaySave`). The board is overlaid field by field: its items (columns, cards,metadata, labels, views) come from the authority, `github` and `pullLinks` from the save. This@@ -434,6 +435,9 @@ it is a new way to use it.- **Board edits reach only the active tab's core.** A client casts only to the core its active tabis on. An edit on the Omni board to a lane of a project on another core (a hosted lane while alocal tab is active, or the reverse) is not cast, so on a hosted core it is not written either.+- **Node order is not synced.** The sessions sidebar's order is the node list's order, and no op+ carries an order change, so on a governed project a reorder stays on the screen that made it: the+ file keeps the authority's order (the order it read, with nodes it hears about later appended).- **Load-time repairs are not cast.** What a client derives while it loads a project (a missing`--after` dependency rope it heals, a legacy node migrated to its current shape) becomes thatclient's baseline and is never cast, so on a governed project it never reaches disk: every loaddiff --git a/src/renderer/canvas/stored-publish.test.ts b/src/renderer/canvas/stored-publish.test.tsindex aee073665..1c3c25067 100644--- a/src/renderer/canvas/stored-publish.test.ts+++ b/src/renderer/canvas/stored-publish.test.ts@@ -114,6 +114,38 @@ describe('own writes into a stored project are cast (N2)', () => {expect(useProjects.getState().getProject('G')?.nodes.map((n) => n.id)).toEqual(['g1', 'g3'])})+ // The same hole, every other store writer: the sessions sidebar renames, recolours, moves,+ // duplicates and CLOSES nodes of a project that is not on screen through the store. On a governed+ // project a close killed the tmux session while the overlay put the node back on disk.+ it('every other own store writer is cast too: close, rename, recolour, move, duplicate, rebind', () => {+ const w = wire()+ const st = () => useProjects.getState()+ st().applyOwnNodeMutation('G', { op: 'upsert', node: node('frame', 0, { kind: 'group' } as never) })+ w.casts.length = 0+ st().renameNode('G', 'g1', 'Renamed')+ st().recolorNode('G', 'g1', '#123456')+ st().rebindNode('G', 'g1', { agentId: 'codex' as never })+ st().moveNodeToGroup('G', 'g1', 'frame')+ st().duplicateNode('G', 'g1')+ st().removeNode('G', 'g1')+ const ops = w.casts.map(([id, m]) => {+ expect(id).toBe('G')+ return m+ })+ const upserts = ops.filter((m): m is Extract<CanvasMutation, { op: 'upsert' }> => m.op === 'upsert')+ expect(upserts[0].node).toMatchObject({ id: 'g1', title: 'Renamed', titleAuto: false })+ expect(upserts[1].node).toMatchObject({ id: 'g1', color: '#123456' })+ expect(upserts[2].node).toMatchObject({ id: 'g1', agentId: 'codex' })+ expect(upserts[3].node).toMatchObject({ id: 'g1', parentId: 'frame' })+ expect(upserts[4].node.id).not.toBe('g1') // the duplicate+ expect(ops.at(-1)).toEqual({ op: 'remove', id: 'g1' })+ expect(ops).toHaveLength(6)+ // …and an ungoverned project still casts nothing from any of them.+ st().renameNode('U', 'u1', 'x')+ st().removeNode('U', 'u1')+ expect(w.casts).toHaveLength(6)+ })+it('with no hook registered (no Canvas bound), a store write casts nothing and still applies', () => {useProjects.getState().applyOwnNodeMutation('G', { op: 'upsert', node: node('g4') })expect(useProjects.getState().getProject('G')?.nodes.map((n) => n.id)).toEqual(['g1', 'g4'])diff --git a/src/renderer/canvas/stored-publish.ts b/src/renderer/canvas/stored-publish.tsindex 3a76d451b..dbd009e53 100644--- a/src/renderer/canvas/stored-publish.ts+++ b/src/renderer/canvas/stored-publish.ts@@ -1,10 +1,11 @@-// Casts the node and edge writes THIS renderer makes into a project's STORED copy — the projects-// store's `applyOwnNodeMutation` / `appendCanvasLinks`, which call the store's publish hook+// Casts the node and edge writes THIS renderer makes into a project's STORED copy — every own+// writer of the projects store (`applyOwnNodeMutation`, `appendCanvasLinks`, the sessions sidebar's+// rename / recolour / move / duplicate / close …), which call its publish hook// (`setStoredCanvasPublishHook`). The node publisher cannot: it diffs React Flow, and a stored// project's nodes enter React Flow only through a load, which it adopts as its baseline. So a ⌘⇧T-// reopen, a cold open, an off-canvas display node or a headless start's launch patch into a project-// that is not on screen was never cast, and on a project a Server Edition canvas authority governs-// the next save overlay dropped it from disk (docs/hosted-team-relay.md).+// reopen, a cold open, an off-canvas display node, a headless start's launch patch or a sidebar+// action on a project that is not on screen was never cast, and on a project a Server Edition+// canvas authority governs the next save overlay dropped it from disk (docs/hosted-team-relay.md).//// The rule lives here rather than in Canvas so it is tested without a canvas:// - ONLY A GOVERNED PROJECT. The authority is what drops an un-cast write; an ungoverned project's@@ -32,9 +33,10 @@ export interface StoredCanvasPublisherDeps {}export function createStoredCanvasPublisher(deps: StoredCanvasPublisherDeps): StoredCanvasPublishHook {- return (projectId, m) => {+ return (projectId, ops) => {if (deps.renderedProjectId() === projectId) returnif (!deps.isGoverned(projectId) || !deps.shouldPublish(projectId)) return- deps.send(projectId, m)+ // Only now is the write diffed: a project that casts nothing never pays for it.+ for (const m of ops()) deps.send(projectId, m)}}diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex 98a3c6684..7e6501b1a 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -8,6 +8,7 @@ import type {NavStop,Project,ProjectKanban,+ SceneMutation,Viewport,Workspace} from '@shared/types'@@ -23,6 +24,7 @@ import {type CanvasLayout} from '@shared/canvas-layout'import { applyCanvasOp as applyCanvasOpTo, contentOf } from '@shared/canvas-content'+import { diffToMutations, type CanvasScene } from '@shared/canvas-mutations'import { applyOwnCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'import { markWorkspaceDirty } from './workspaceDirty'import { folderName } from '../lib/projectOpen'@@ -423,23 +425,46 @@ export function setKanbanPublishHook(hook: KanbanPublishHook | null): void {}/**- * Publishes a node or edge write THIS renderer made into a project's STORED copy- * (`applyOwnNodeMutation`, `appendCanvasLinks`): a ⌘⇧T / "Recently closed" reopen into a project that- * is not on screen, a cold open, an off-canvas display node, a headless start's launch patch. The node+ * Publishes the node and edge writes THIS renderer makes into a project's STORED copy — every own+ * store writer: `applyOwnNodeMutation` and `appendCanvasLinks` (a ⌘⇧T / "Recently closed" reopen+ * into a project that is not on screen, a cold open, an off-canvas display node or link, a headless+ * start's launch patch) and the sessions sidebar's `renameNode` / `recolorNode` / `rebindNode` /+ * `removeNode` / `duplicateNode` / `moveNodeToGroup` / `reorderNode` / `reorderGroup`. The node* publisher never sees these writes: it diffs React Flow, and a stored project's nodes enter React* Flow only through a load, which it ADOPTS as its baseline rather than casting. On a project a* Server Edition canvas authority governs that was data loss, because the save overlay replaces the- * stored content with what the authority heard as ops (docs/hosted-team-relay.md). Called AFTER the- * store write, once per op actually written. Same one-owner rule as the board hook: a peer's op is- * applied with `applyCanvasOp`, which never calls it, so nothing received is published again.+ * stored content with what the authority heard as ops (docs/hosted-team-relay.md): a reopened node+ * vanished from disk, and a sidebar close killed the session while the node came back.+ *+ * Called AFTER the write with `ops`, which diffs the project's nodes and edges before and after it+ * (`diffToMutations`, the publisher's own diff, so no writer keeps a list of its own that drifts).+ * LAZY: a hook that casts nothing for this project never pays for the diff. Node order is not in+ * the op vocabulary, so a pure reorder yields no op. Same one-owner rule as the board hook: a peer's+ * op is applied with `applyCanvasOp`, which never calls it, so nothing received is published again.*/-export type StoredCanvasPublishHook = (projectId: string, m: CanvasMutation) => void+export type StoredCanvasPublishHook = (projectId: string, ops: () => readonly SceneMutation[]) => voidlet storedCanvasPublishHook: StoredCanvasPublishHook | null = null/** Canvas registers this once per core binding and clears it (`null`) on teardown. */export function setStoredCanvasPublishHook(hook: StoredCanvasPublishHook | null): void {storedCanvasPublishHook = hook}+const sceneOf = (p: Project): CanvasScene => ({+ nodes: Array.isArray(p.nodes) ? p.nodes : [],+ bridges: p.bridges ?? [],+ ropes: p.ropes ?? []+})++/** Run one own write into a stored project, then hand what it changed to the publish hook. */+function ownWrite(get: () => ProjectsState, projectId: string, write: () => void): void {+ const before = get().getProject(projectId)+ write()+ const hook = storedCanvasPublishHook+ const after = get().getProject(projectId)+ if (!hook || !before || !after || before === after) return+ hook(projectId, () => diffToMutations(sceneOf(before), sceneOf(after)))+}+export const useProjects = create<ProjectsState>((set, get) => ({projects: [],activeProjectId: '',@@ -648,13 +673,7 @@ export const useProjects = create<ProjectsState>((set, get) => ({},appendCanvasLinks(projectId, links) {- // The edges actually appended, per kind: what the publish hook casts (a re-link casts nothing).- const added: { bridge: BridgeLink[]; rope: BridgeLink[] } = { bridge: [], rope: [] }- const add = (- kind: 'bridge' | 'rope',- existing: BridgeLink[] | undefined,- incoming: BridgeLink[] | undefined- ) => {+ const add = (existing: BridgeLink[] | undefined, incoming: BridgeLink[] | undefined) => {if (!incoming?.length) return existingconst kept = existing ?? []const seenId = new Set(kept.map((e) => e.id))@@ -666,21 +685,17 @@ export const useProjects = create<ProjectsState>((set, get) => ({seenPair.add(pair)return true})- added[kind] = freshreturn fresh.length ? [...kept, ...fresh] : existing}- const p = get().projects.find((x) => x.id === projectId)- if (!p) return- const next = {- ...p,- bridges: add('bridge', p.bridges, links.bridges),- ropes: add('rope', p.ropes, links.ropes)- }- set((s) => ({- projects: s.projects.map((x) => (x.id === projectId ? next : x))- }))- for (const kind of ['bridge', 'rope'] as const)- for (const edge of added[kind]) storedCanvasPublishHook?.(projectId, { op: 'edge-upsert', kind, edge })+ ownWrite(get, projectId, () =>+ set((s) => ({+ projects: s.projects.map((p) =>+ p.id === projectId+ ? { ...p, bridges: add(p.bridges, links.bridges), ropes: add(p.ropes, links.ropes) }+ : p+ )+ }))+ )},applyCanvasOp(projectId, mutation) {@@ -713,112 +728,128 @@ export const useProjects = create<ProjectsState>((set, get) => ({applyOwnNodeMutation(projectId, mutation) {if (!get().projects.some((p) => p.id === projectId)) return false- set((s) => ({- projects: mapProjectNodes(s.projects, projectId, (nodes) =>- applyOwnCanvasMutation(nodes, mutation)- )- }))- // A node op only: `applyOwnCanvasMutation` writes nothing for any other family.- if (mutation.op === 'upsert' || mutation.op === 'remove') storedCanvasPublishHook?.(projectId, mutation)+ ownWrite(get, projectId, () =>+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) =>+ applyOwnCanvasMutation(nodes, mutation)+ )+ }))+ )return true},renameNode(projectId, nodeId, title) {- set((s) => ({- projects: mapProjectNodes(s.projects, projectId, (nodes) =>- // An explicit rename means the user owns the name now: stop auto-tracking the session.- nodes.map((n) => (n.id === nodeId ? { ...n, title, titleAuto: false } : n))- )- }))+ ownWrite(get, projectId, () =>+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) =>+ // An explicit rename means the user owns the name now: stop auto-tracking the session.+ nodes.map((n) => (n.id === nodeId ? { ...n, title, titleAuto: false } : n))+ )+ }))+ )},recolorNode(projectId, nodeId, color) {- set((s) => ({- projects: mapProjectNodes(s.projects, projectId, (nodes) =>- nodes.map((n) => (n.id === nodeId ? { ...n, color } : n))- )- }))+ ownWrite(get, projectId, () =>+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) =>+ nodes.map((n) => (n.id === nodeId ? { ...n, color } : n))+ )+ }))+ )},rebindNode(projectId, nodeId, patch) {- set((s) => ({- projects: mapProjectNodes(s.projects, projectId, (nodes) =>- nodes.map((n) => (n.id === nodeId ? { ...n, ...patch } : n))- )- }))+ ownWrite(get, projectId, () =>+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) =>+ nodes.map((n) => (n.id === nodeId ? { ...n, ...patch } : n))+ )+ }))+ )},removeNode(projectId, nodeId) {- set((s) => ({- projects: mapProjectNodes(s.projects, projectId, (nodes) =>- nodes.filter((n) => n.id !== nodeId)- )- }))+ ownWrite(get, projectId, () =>+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) =>+ nodes.filter((n) => n.id !== nodeId)+ )+ }))+ )},duplicateNode(projectId, nodeId) {- set((s) => ({- projects: mapProjectNodes(s.projects, projectId, (nodes) => {- const src = nodes.find((n) => n.id === nodeId)- if (!src) return nodes- const copy: CanvasNodeState = {- ...src,- id: `${src.kind}-${Math.random().toString(36).slice(2, 10)}`,- title: `${src.title} copy`,- position: { x: src.position.x + 24, y: src.position.y + 24 }- }- return [...nodes, copy]- })- }))+ ownWrite(get, projectId, () =>+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) => {+ const src = nodes.find((n) => n.id === nodeId)+ if (!src) return nodes+ const copy: CanvasNodeState = {+ ...src,+ id: `${src.kind}-${Math.random().toString(36).slice(2, 10)}`,+ title: `${src.title} copy`,+ position: { x: src.position.x + 24, y: src.position.y + 24 }+ }+ return [...nodes, copy]+ })+ }))+ )},moveNodeToGroup(projectId, nodeId, groupId) {- set((s) => ({- projects: mapProjectNodes(s.projects, projectId, (nodes) => {- const node = nodes.find((n) => n.id === nodeId)- if (!node) return nodes- if ((node.parentId ?? null) === groupId) return nodes- // A frame may be moved into another frame, but never into itself or its own subtree.- if (groupId === nodeId || (groupId && stateIsDescendant(nodes, groupId, nodeId))) {- return nodes- }- const next = repositionState(node, groupId, nodes)- if (next === node) return nodes // target group missing / not a group- return nodes.map((n) => (n.id === nodeId ? next : n))- })- }))+ ownWrite(get, projectId, () =>+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) => {+ const node = nodes.find((n) => n.id === nodeId)+ if (!node) return nodes+ if ((node.parentId ?? null) === groupId) return nodes+ // A frame may be moved into another frame, but never into itself or its own subtree.+ if (groupId === nodeId || (groupId && stateIsDescendant(nodes, groupId, nodeId))) {+ return nodes+ }+ const next = repositionState(node, groupId, nodes)+ if (next === node) return nodes // target group missing / not a group+ return nodes.map((n) => (n.id === nodeId ? next : n))+ })+ }))+ )},reorderNode(projectId, draggedId, beforeId) {- set((s) => ({- projects: mapProjectNodes(s.projects, projectId, (nodes) => {- if (draggedId === beforeId) return nodes- const dragged = nodes.find((n) => n.id === draggedId)- const before = nodes.find((n) => n.id === beforeId)- if (!dragged || !before || dragged.kind === 'group') return nodes- const targetParent = before.parentId ?? null- const moved =- (dragged.parentId ?? null) === targetParent- ? dragged- : repositionState(dragged, targetParent, nodes)- const without = nodes.filter((n) => n.id !== draggedId)- const idx = without.findIndex((n) => n.id === beforeId)- return [...without.slice(0, idx), moved, ...without.slice(idx)]- })- }))+ ownWrite(get, projectId, () =>+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) => {+ if (draggedId === beforeId) return nodes+ const dragged = nodes.find((n) => n.id === draggedId)+ const before = nodes.find((n) => n.id === beforeId)+ if (!dragged || !before || dragged.kind === 'group') return nodes+ const targetParent = before.parentId ?? null+ const moved =+ (dragged.parentId ?? null) === targetParent+ ? dragged+ : repositionState(dragged, targetParent, nodes)+ const without = nodes.filter((n) => n.id !== draggedId)+ const idx = without.findIndex((n) => n.id === beforeId)+ return [...without.slice(0, idx), moved, ...without.slice(idx)]+ })+ }))+ )},reorderGroup(projectId, draggedId, parentId, beforeId) {- set((s) => ({- projects: mapProjectNodes(s.projects, projectId, (nodes) => {- const dragged = nodes.find((node) => node.id === draggedId)- const before = beforeId ? nodes.find((node) => node.id === beforeId) : undefined- if (!dragged || dragged.kind !== 'group' || (beforeId && before?.kind !== 'group')) {- return nodes- }- return reorderGroupWithinParent(nodes, draggedId, parentId, beforeId)- })- }))+ ownWrite(get, projectId, () =>+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) => {+ const dragged = nodes.find((node) => node.id === draggedId)+ const before = beforeId ? nodes.find((node) => node.id === beforeId) : undefined+ if (!dragged || dragged.kind !== 'group' || (beforeId && before?.kind !== 'group')) {+ return nodes+ }+ return reorderGroupWithinParent(nodes, draggedId, parentId, beforeId)+ })+ }))+ )},reorderProject(draggedId, beforeId) {