Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas): canvas sync converges on a real (async) bus
enescd403e1736b1
diff --git a/docs/team-presence.md b/docs/team-presence.mdindex 36a6b4f9c..1d547170d 100644--- a/docs/team-presence.md+++ b/docs/team-presence.md@@ -9,9 +9,14 @@ browsers, the Electron window, cursorless relay phones), a real `window.nodeTerm**Stage 2** — terminal co-attach (the [Terminal co-attach](#terminal-co-attach) section): one pty,N subscribers; idempotent `pty:create`; smallest-subscriber-wins sizing; per-client backpressure withan 8 MB drop-and-redraw ceiling; typing attribution; and the delete/recycle split.-**Stage 3** — canvas mutation sync (the [Canvas sync](#canvas-sync) section): a stateless `canvas:mut`-reflector, a diff-based publisher with an `adopt()` loop guard, a real `window.nodeTerminal.canvas` on-both surfaces, and per-project apply (including into a loaded-but-inactive project's serialized nodes).+**Stage 3** — canvas mutation sync (the [Canvas sync](#canvas-sync) section): a `canvas:mut` reflector+that stamps one total order (`seq`) and fans each mutation to every client, a diff-based publisher+with an `adopt()` loop guard and a solo gate, per-node last-write-wins in that order+(`canvas-order.ts`) so concurrent edits **converge** instead of splitting the canvas in two, an+in-place apply into the live React Flow array, a real `window.nodeTerminal.canvas` on both surfaces,+and per-project apply (including into a loaded-but-inactive project's serialized nodes). What it+resolves and what it does not:+[Concurrent-edit resolution](#concurrent-edit-resolution-what-converges-and-what-does-not).Deltas between this document and what actually shipped are recorded in[What Stage 1 changed](#what-stage-1-changed-relative-to-this-spec),[What Stage 2 changed](#what-stage-2-changed-relative-to-this-spec) and@@ -323,14 +328,35 @@ independently on each client from the already-broadcast `agent:status` stream; aagainst the last one it published (`diffToMutations`), so edits that never pass through`onNodesChange` (a rename, a color pick, a collapse, a direct `setNodes`) sync too. Position framesare throttled to ~20 Hz while dragging and flushed on drag-stop; everything else is a full upsert.- Ephemeral subagent/loop cards are filtered out (`publishableStates`).-- **Reflector** (`src/core/canvas-sync.ts`) — stateless: it holds no canvas state, persists nothing,- and sends each mutation to every attached client except the sender (`CorePlatform.clientIds()` +- `onWithSender`). Echo suppression is by sender `ClientId`.+ Ephemeral subagent/loop cards are filtered out (`publishableStates`). Every mutation is stamped+ with `src`, this Canvas's publisher tag.+- **Solo gate** — `shouldPublish` (fed by the presence peer table, read through a ref so it can never+ re-render Canvas). With nobody else attached, `publish()` degrades to `adopt()`: it takes the+ snapshot as the baseline and does **no** diff, no `stableStringify` of every node, no IPC cast. A+ solo user pays nothing for team sync, and because the baseline still tracks the canvas, the first+ edit after a peer joins diffs correctly — no resync step, no missed mutation.+- **Reflector** (`src/core/canvas-sync.ts`) — holds no canvas state and persists nothing, but it is+ **not** stateless: it stamps every mutation with a monotone **`seq`** and sends it to **every**+ attached client, the sender included (`CorePlatform.clientIds()` + `onWithSender`). `seq` is+ server-authoritative (a client-supplied one is overwritten at ingest).+- **Ordering** (`src/shared/canvas-order.ts`) — the client half, and the reason concurrent edits+ converge instead of splitting the canvas in two. Per node, the highest `seq` wins. Two rules: (1)+ our own echo is an **ack**, not an edit — it carries the `seq` our mutation was given, and is never+ re-applied (re-applying it would rubber-band a node we are still dragging); (2) while one of our+ own mutations for a node is unacked, we ignore peers' mutations for that node — FIFO delivery means+ ours is necessarily *later* in the total order, so it will win on every other client too. A pending+ entry expires after `PENDING_TTL_MS` so a cast the reflector refused cannot deafen a node forever.- **Loop guard** — a mutation applied from a peer is `adopt()`ed into the publisher's baseline beforethe next diff runs, so it can never be re-published (no A→B→C→A ping-pong).- **Apply** — the vocabulary is single-sourced in `src/shared/canvas-mutations.ts` and used by both- ends. `window.nodeTerminal.canvas` is real on the preload **and** the ws-bridge.+ ends. In the renderer, an incoming mutation is patched into the **live React Flow array**+ (`applyMutationToFlow`, `src/renderer/state/workspace.ts`) — never round-tripped through the+ (lossy) serializers, which would wipe your selection, delete your relay-remote nodes and re-render+ every node component on every peer mutation. `window.nodeTerminal.canvas` is real on the preload+ **and** the ws-bridge.+- **Undo is rebased, not clobbered** — a peer's mutation is applied to the undo baseline+ (`committedRef`) rather than replacing it, so a local edit still inside the 300 ms undo debounce+ survives a peer's mutation landing on top of it.## UI@@ -510,20 +536,54 @@ here so the delta is legible.(`TOMBSTONE_MAX` / `TOMBSTONE_TTL_MS`), still exempting the destroyer so their own ⌘Z works.5. **What canvas sync does NOT cover** (all deliberate; none of it is fixed by this stage):- - **Edges are not in the mutation vocabulary** — only nodes are. A context-link edge or a- sticky→terminal note link drawn by one client does **not** appear on the other, and a peer's- node *delete* can leave a **dangling edge** on your canvas (an edge whose endpoint node is- gone). React Flow tolerates it and the next save/load drops it, but until then it renders.- - **A peer's node removal unmounts the node but PARKS the terminal** — it does not kill the tmux- session locally, and it does not run the local delete path's cleanup- (`disposeTerminalOnUnmount` / `useAgentStatus.remove`). The session itself is already dead (the- *deleting* client's `transport.destroy` killed it), so nothing leaks server-side; what remains- on the peer is a parked xterm holding a dead pty until the 5-minute park timer fires, plus a- stale `agentStatus` entry for a node id that no longer exists.+ - **Edges are NOT in the mutation vocabulary** — only nodes are, and edges (`edges`, `bridges`,+ `ropes`) ride the same whole-file `workspace.save`, which is last-write-wins. So this is worse+ than a cosmetic gap: an edge you draw does not appear on your peer's canvas, **and their next+ save — of a canvas that never had it — DELETES it**, because their file write is authoritative+ for the whole project. (Same in reverse: their edge dies on your save.) A peer's node delete+ also leaves a **dangling edge** on your canvas until the next save/load drops it. Edge sync is+ the obvious next slice of this stage; until then, draw links when you are alone on the canvas.+ - **A peer's node removal unmounts the node and disposes its terminal co-state**+ (`disposeTerminalOnUnmount` — the module-level xterm/park/co-attach state), but it does **not**+ run the rest of the local delete path (`useAgentStatus.remove`, chat-driver dispose). The+ session itself is already dead (the *deleting* client's `transport.destroy` killed it), so+ nothing leaks server-side; what remains on the peer is a stale `agentStatus` entry for a node id+ that no longer exists. Disposing the co-state matters because the delete is undoable: if the+ owner hits ⌘Z, the node comes back **alive**, and a peer that had kept the stale co-state would+ be looking at a node stuck in "closed by another user" whose only obvious cure (clicking `×`)+ would kill the owner's live session for real.- **Project lifecycle** (create / rename / close / delete / folder change) is **not** synced.- **Viewport, selection and undo** are not synced. Undo is local per user, by design.- - **No conflict resolution beyond node-level last-write-wins.** Two clients editing the same node- converge on whichever mutation landed last — never a merge, never a duplicate. No CRDT.+ - **No conflict resolution beyond per-node last-write-wins.** See+ [Concurrent-edit resolution](#concurrent-edit-resolution-what-converges-and-what-does-not).+ No CRDT.++## Concurrent-edit resolution: what converges, and what does not++**Converges — guaranteed, on any interleaving.** Every client ends with the same **node set** and+the same **value** for every node, because every mutation is ordered by the reflector's `seq` and the+highest `seq` per node wins everywhere (`src/shared/canvas-order.ts`). This is the property+persistence depends on: whichever client's whole-file `workspace.save` runs, it writes a canvas the+others agree with. Proven end-to-end against an **asynchronous** bus (queued casts + FIFO deliveries,+edits genuinely in flight) in `src/core/canvas-sync.convergence.test.ts`.++**Does NOT converge — named, not hidden:**++- **Array order after a resurrection.** If a delete *loses* the order race, the client that issued it+ removed the node and then re-appended it, so it can sit in a different **slot** in the array than+ on a client that never removed it. Node set, positions, sizes and data all agree; only the array+ order (which drives the sidebar listing) can differ, and the next load normalizes it.+- **Intent, on a contended node.** Two people dragging the same node fight: the node lands wherever+ the last-ordered frame put it. Two people typing a title get one title. That is last-write-wins,+ not a merge — by design (no CRDT).+- **A delete that loses to a concurrent edit.** If A deletes a node while B is mid-drag, and B's next+ frame is ordered after A's remove, the node **survives on both canvases** — the last write wins,+ and it happened to be an upsert. A's `transport.destroy` already killed the tmux session, so the+ surviving node is a shell: opening it starts a fresh session. The node is *consistent* everywhere+ (no split-brain save, which was the whole point), it is simply not the outcome A wanted. Deleting a+ node someone else is actively dragging is a race between two humans; nodeterm resolves it, it does+ not arbitrate it.+- **Anything outside the node vocabulary** — edges, project lifecycle (see item 5 above).## Non-goals (v1)@@ -554,19 +614,32 @@ read-only guests, per-user settings.it. → `src/core/pty-manager-platform.test.ts`- **Single-client regression** (delivered): min-size equals your own size and the spawn path isunchanged. → `src/core/pty-single-user.test.ts` (17 tests)-- **Canvas sync** (delivered): the reflector fans a mutation to every client but the sender, refuses a- malformed/oversized cast, and registers exactly once per platform; the publisher diffs snapshots,- throttles drag frames, flushes on settle, and `adopt()`s without emitting. →- `src/core/canvas-sync.test.ts`, `src/shared/canvas-publish.test.ts`,+- **Canvas sync** (delivered): the reflector stamps the total order (`seq`, monotone across senders+ and projects, never trusted from the client) and fans a mutation to every client *including* the+ sender, refuses a malformed/oversized cast, and registers exactly once per platform; the publisher+ diffs snapshots, stamps `src`, throttles drag frames, flushes on settle, `adopt()`s without+ emitting, and — while solo — emits and diffs **nothing** while still keeping its baseline current.+ → `src/core/canvas-sync.test.ts`, `src/shared/canvas-publish.test.ts`,`src/shared/canvas-mutations.test.ts`-- **Canvas convergence** (delivered): two clients running the **real** publisher against the **real**- reflector, with interleaved local edits, land on identical node sets — in every interleaving tried;- last-write-wins on the same node produces one value, not a merge or a duplicate; a peer's mutation- is applied exactly once and **re-published never** (the `adopt()` loop guard: one cast per local- edit, no counter-cast, even for a bulk delete across three clients); a client never receives its own- mutation back; ephemeral subagent/loop cards never go on the wire; a client that joins late- converges with the other two; and a peer's delete is not resurrected by the surviving client's next- save. → `src/core/canvas-sync.convergence.test.ts` (8 tests)+- **Ordering** (delivered): an own echo is an ack and is never re-applied; a peer's edit loses to an+ unacked local edit of the same node (per node, counted per in-flight frame); a superseded straggler+ is dropped; an ack that never comes expires. → `src/shared/canvas-order.test.ts` (11 tests)+- **Canvas convergence** (delivered): two clients running the **real** publisher and **real** ordering+ against the **real** reflector, over an **ASYNCHRONOUS** bus (casts and deliveries queued, FIFO per+ link — so several edits are genuinely in flight and the test chooses the interleaving). *The+ earlier synchronous bus could not express concurrency at all, and therefore "passed" a design that+ diverged permanently on the first concurrent drag.* Covered: a concurrent move of the same node+ converges on the ordered winner (both orderings); a concurrent delete-vs-drag converges (both ways+ round) — no split-brain save; 20 frames of two clients dragging one node converge; three clients+ editing one node converge; every interleaving × every settle point of a six-edit set converges; a+ peer's mutation is applied once and **re-published never** (one cast per local edit, no+ counter-cast, even for a bulk delete across three clients); ephemeral cards never go on the wire; a+ late joiner converges; and a peer's delete is not resurrected by the surviving client's next save.+ → `src/core/canvas-sync.convergence.test.ts` (14 tests)+- **Applying a peer's mutation** (delivered): patches the live React Flow array — keeps your+ selection, keeps relay-remote nodes, keeps local-only node data, keeps every untouched node's+ object identity, drops the stale `measured` size so a peer's resize is not fought back, and keeps+ group parents before their children. → `src/renderer/state/workspace.mutation.test.ts` (10 tests)### Manual smoke test (Stage 1)@@ -718,15 +791,43 @@ logged in, named, and on the **same project**.loop guard has regressed.8. **A SOLO user sees no change whatsoever.** The regression that matters most. In the desktop app(`npm run dev`), alone: add, drag, rename, recolor, group, delete nodes; undo/redo; switch projects- and back. With one client `clientIds()` has one entry and the reflector sends **nothing** — the- canvas must look and behave exactly as on `main`, with no extra dirty marks, no undo-stack entries- you did not create, and no node ever moving on its own.+ and back. With no peer attached the publisher does not even **diff** (the solo gate) — the canvas+ must look and behave exactly as on `main`, with no extra dirty marks, no undo-stack entries you did+ not create, and no node ever moving on its own.+9. **Both drag the same node.** A and B grab the **same** node and drag it in opposite directions for+ a few seconds, then both let go. It fights (expected — last write wins), but when the dust settles+ **both canvases show it in the same place**. Reload both: still the same place. (Before the+ ordering fix, A and B ended up holding the node at two different positions *permanently*, and+ whoever saved last silently moved it for the other.)+10. **Delete a node the other is dragging.** B drags a node; A deletes it mid-drag. Whatever happens+ (it survives on both, or it dies on both — the total order decides), **A and B agree**, and after+ a reload of both tabs the canvas is the same on each. What must never happen is one of them+ holding a node the other does not.+11. **Your selection survives a teammate's drag.** In B, box-select two nodes and hold the selection+ while A drags a *third* node around. B's selection must stay selected (before the in-place apply,+ each of A's ~20 Hz mutations wiped it). Likewise, B's relay-remote terminal nodes (if any) must+ not vanish while A edits.+12. **Your undo is not eaten.** In B, move a node, and within a moment have A move a *different* node+ (so a peer mutation lands during B's undo debounce). Now press ⌘Z in **B**: it must undo **B's**+ move — not skip past it to an older state (which would also revert A's edit).## Known risks- **Weak identity** — anyone can claim any name.- **Concurrent typing garbles input** — accepted; the badge is the warning.- **Cross-user undo** — last-write-wins, no CRDT.+- **Per-node last-write-wins is a resolution, not an arbitration.** Clients always converge, but a+ delete can lose to a concurrent drag frame (the node survives everywhere, with a dead session), and+ two people dragging one node fight over it. Named in full under+ [Concurrent-edit resolution](#concurrent-edit-resolution-what-converges-and-what-does-not).+- **A peer's edge (context link / note link) is deleted by your next save.** Edges are not synced but+ they *are* persisted, in the same whole-file write. See item 5 of+ [What Stage 3 changed](#what-stage-3-changed-relative-to-this-spec).+- **The publisher's solo gate reads the presence peer table.** If a client's presence handshake never+ completes, that client sees no peers and therefore publishes nothing (it still *applies* what it+ receives, and the first mutation from a peer flips the gate on for good). Presence and canvas sync+ ride the same transport, so a client that cannot say hello generally cannot cast either — but the+ coupling is real and is the price of a solo user paying zero.- **Cursor traffic** is 20 Hz × peers: comfortable for a 5–10 person team, not for a public room.- **Plain-shell (no tmux) co-attach shows a joiner a blank-but-live terminal** until the next outputarrives (pressing Enter paints it). A joiner gets `fresh:false`, so it skips the cold-restorediff --git a/src/core/canvas-sync.convergence.test.ts b/src/core/canvas-sync.convergence.test.tsindex b74fc98a5..5fd94db1d 100644--- a/src/core/canvas-sync.convergence.test.ts+++ b/src/core/canvas-sync.convergence.test.ts@@ -1,18 +1,27 @@-// Convergence: two clients, interleaved local edits, one stateless reflector → identical node sets.+// Convergence: two clients, interleaved local edits, one ordering reflector → identical node sets.//-// No CRDT: node-level last-write-wins is the whole contract. This is the property that makes-// persistence safe — whichever client calls workspace.save writes the same bytes, so a peer's-// delete can never be written back to disk by someone whose canvas still held the node.+// No CRDT: per-node last-write-wins IN THE REFLECTOR'S TOTAL ORDER is the whole contract. That+// property is what makes persistence safe — whichever client calls workspace.save writes the same+// bytes, so a peer's delete can never be written back to disk by someone whose canvas still held+// the node, and two people dragging one node cannot leave it at two different places forever.//-// Everything here runs against the REAL pieces: the real reflector (initCanvasSync), the real-// publisher (createCanvasPublisher, diff + adopt loop guard + ephemeral filter) and the real-// apply vocabulary (applyCanvasMutation). Only the transport is simulated — a Bus that routes-// `sendTo(id, …)` into the addressed client, exactly as CorePlatform does on both shells.+// THE BUS IS ASYNCHRONOUS, deliberately. The first version of this suite delivered each mutation+// into the peer inside the sender's own cast() call, so two edits could never be in flight at once+// — which is the ONLY condition under which last-write-wins can diverge. It therefore "passed" a+// design that diverged permanently on the very first concurrent drag. A synchronous bus cannot+// catch this class of bug. Here, casts and deliveries are QUEUED (FIFO per link, exactly as IPC and+// a WebSocket deliver), so a test can hold several edits in flight and choose the interleaving.+//+// Everything else runs against the REAL pieces: the real reflector (initCanvasSync — `seq` stamping+// + fan-out to every client, sender included), the real publisher (createCanvasPublisher: diff,+// `src` stamping, adopt loop guard, ephemeral filter), the real ordering state (createCanvasOrder)+// and the real apply vocabulary (applyCanvasMutation). Only the transport is simulated.import { describe, it, expect, beforeEach, afterEach } from 'vitest'import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'import { initCanvasSync } from './canvas-sync'import { applyCanvasMutation } from '../shared/canvas-mutations'+import { createCanvasOrder } from '../shared/canvas-order'import { createCanvasPublisher, publishableStates } from '../shared/canvas-publish'import { IPC } from '../shared/ipc'import type { CanvasMutation, CanvasNodeState } from '../shared/types'@@ -30,14 +39,21 @@ const node = (id: string, x: number, title = 't', color = '#fff'): CanvasNodeStaconst PROJECT = 'p1'-/** The transport: routes sendTo(id, …) into the addressed client's deliver hook, and counts every- * cast that reaches the reflector — the number that would grow without bound in an echo loop. */+/**+ * The transport, ASYNC. Two FIFO queues — the two orderings a real deployment guarantees:+ * - `casts`: client → reflector. The order the reflector pops them in IS the total order.+ * - `inbox[clientId]`: reflector → that client. Per-connection FIFO (IPC and WS both give this,+ * and canvas-order's rule 2 depends on it).+ * Nothing moves until the test says so, so several clients can hold edits in flight at once.+ */class Bus {- deliver = new Map<number, (projectId: string, m: CanvasMutation) => void>()- private senderListeners = new Map<string, (senderId: number, ...args: any[]) => void>()+ private readonly senderListeners = new Map<string, (senderId: number, ...args: any[]) => void>()+ private readonly casts: Array<{ sender: number; projectId: string; m: CanvasMutation }> = []+ private readonly inbox = new Map<number, Array<{ projectId: string; m: CanvasMutation }>>()+ readonly deliver = new Map<number, (projectId: string, m: CanvasMutation) => void>()clients: number[] = []/** Total casts made BY clients (publisher → reflector). One per real local edit; never more. */- casts = 0+ castCount = 0platform: CorePlatform = {userDataDir: '/tmp/nodeterm-convergence',@@ -50,38 +66,85 @@ class Bus {clientIds: () => this.clients,sendTo: (to, channel, ...args) => {if (channel !== IPC.canvasMut) return- this.deliver.get(to)?.(args[0] as string, args[1] as CanvasMutation)+ const q = this.inbox.get(to) ?? []+ q.push({ projectId: args[0] as string, m: args[1] as CanvasMutation })+ this.inbox.set(to, q)},broadcast: () => {},openExternal: async () => {}}+ /** A client casts: the mutation is QUEUED, not reflected. It reaches the reflector on settle(). */cast(senderId: number, projectId: string, m: CanvasMutation): void {- this.casts++- this.senderListeners.get(IPC.canvasMut)?.(senderId, projectId, m)+ this.castCount+++ this.casts.push({ sender: senderId, projectId, m })+ }++ /** Pop one cast into the reflector — this is where a mutation gets its place in the total order. */+ private stepCast(): boolean {+ const c = this.casts.shift()+ if (!c) return false+ this.senderListeners.get(IPC.canvasMut)?.(c.sender, c.projectId, c.m)+ return true+ }++ /** Pop one queued delivery into its addressed client (FIFO within that client's inbox). */+ private stepDelivery(): boolean {+ for (const id of this.clients) {+ const q = this.inbox.get(id)+ if (!q?.length) continue+ const d = q.shift() as { projectId: string; m: CanvasMutation }+ this.deliver.get(id)?.(d.projectId, d.m)+ return true+ }+ return false+ }++ /** Run the network to quiescence: every queued cast reflected, every delivery delivered. */+ settle(): void {+ for (let i = 0; i < 10_000; i++) {+ if (this.stepCast()) continue+ if (this.stepDelivery()) continue+ return+ }+ throw new Error('bus did not settle — mutation loop?')}}-/** A simulated client: its own node list, its own publisher, wired to the reflector by ClientId.- * Mirrors the two Canvas effects — publish the diff of the settled snapshot, and adopt (never- * re-publish) whatever arrives from a peer. */+/** A simulated client: its own node list, publisher and ordering state, wired by ClientId.+ * Mirrors the two Canvas effects — publish the diff of the settled snapshot; on an incoming+ * mutation ask the ordering state whether to apply it, then adopt (never re-publish) the result. */class Client {states: CanvasNodeState[] = []/** Ephemeral cards (subagent / loop) this client renders — derived locally, never published. */ephemeral = new Set<string>()- /** Mutations received FROM peers (echo suppression means: never one of our own). */- received = 0- private readonly pub = createCanvasPublisher((m) => this.bus.cast(this.id, PROJECT, m))+ /** Mutations APPLIED from the wire (an own echo, or one the order supersedes, is not applied). */+ applied = 0+ private readonly order: ReturnType<typeof createCanvasOrder>+ private readonly pub: ReturnType<typeof createCanvasPublisher>constructor(readonly id: number,private readonly bus: Bus) {+ // Built here, not as field initializers: a field initializer runs BEFORE the parameter+ // properties are assigned, so `this.id` would still be undefined and both clients would stamp+ // the same `src` — every peer mutation would then look like their own echo.+ const src = `src-${id}`+ this.order = createCanvasOrder(src)+ this.pub = createCanvasPublisher(+ (m) => {+ this.order.onLocal(m)+ bus.cast(id, PROJECT, m)+ },+ { src }+ )bus.deliver.set(id, (projectId, m) => {if (projectId !== PROJECT) return- this.received+++ if (!this.order.accept(m)) return+ this.applied++this.states = applyCanvasMutation(this.states, m)- this.pub.adopt(this.publishable()) // loop guard — never re-publish a peer's change+ this.pub.adopt(this.publishable()) // loop guard — never re-publish someone else's change})}@@ -110,42 +173,141 @@ class Client {ids(): string[] {return this.states.map((n) => n.id).sort()}++ x(id: string): number | undefined {+ return this.states.find((n) => n.id === id)?.position.x+ }}+/**+ * The convergence contract, canonically: the same NODE SET, and the same VALUE for every node.+ *+ * Array ORDER is deliberately NOT part of it. When a delete loses the order race, the client that+ * issued it removed the node and then re-appended it (applyCanvasMutation appends an upsert of an+ * absent node), so its array can end up carrying that node in a different SLOT than a client that+ * never removed it. Array order drives only the sidebar listing — positions, sizes, data and the+ * node set all agree, so either client's save writes a canvas the other agrees with. Documented as+ * such in docs/team-presence.md; use this helper wherever a resurrection can happen.+ */+const canon = (c: Client): CanvasNodeState[] =>+ [...c.persisted()].sort((x, y) => x.id.localeCompare(y.id))+let bus: Buslet a: Clientlet b: Client-beforeEach(() => {+function boot(): void {bus = new Bus()initPlatform(bus.platform)initCanvasSync()a = new Client(1, bus)b = new Client(2, bus)bus.clients = [1, 2]-})+}++beforeEach(boot)afterEach(() => resetPlatformForTests())-describe('canvas convergence', () => {+describe('canvas convergence (async bus)', () => {+ // THE case a synchronous bus cannot express: both clients edit the SAME node before either has+ // heard from the other. Two people dragging one node cross like this on every single frame.+ it('concurrent move of the same node converges (both land on the ordered winner)', () => {+ a.edit([node('n1', 0)])+ bus.settle()++ // In flight at the same time: A drags n1 to 200, B drags the same node to 100.+ a.edit([node('n1', 200)])+ b.edit([node('n1', 100)])+ bus.settle()++ expect(a.states).toEqual(b.states)+ expect(a.x('n1')).toBe(b.x('n1'))+ // The reflector popped A's cast first, so B's is the LATER write in the total order — B wins,+ // on both canvases. (Before the ordering fix: A showed 200 and B showed 100, forever.)+ expect(a.x('n1')).toBe(100)+ expect(a.persisted()).toEqual(b.persisted())+ })++ it('converges whichever way the reflector orders the two concurrent writes', () => {+ b.edit([node('n1', 100)]) // B's cast is queued first this time+ a.edit([node('n1', 200)])+ bus.settle()+ expect(a.states).toEqual(b.states)+ expect(a.x('n1')).toBe(200) // A's cast was popped last → A wins, on both+ })++ // The bug Stage 3 exists to kill, in its sharpest form: A deletes a node while B is dragging it.+ // Divergence here is not cosmetic — A's next whole-file workspace.save would write the node+ // straight back over B's canvas (or vice versa).+ it('concurrent delete vs move of the same node converges (no split-brain save)', () => {+ a.edit([node('n1', 0), node('n2', 0)])+ bus.settle()++ a.edit(a.states.filter((n) => n.id !== 'n1')) // A deletes n1…+ b.edit(b.states.map((n) => (n.id === 'n1' ? node('n1', 50) : n))) // …while B drags it+ bus.settle()++ // Whatever the total order decided, BOTH clients agree — that is the save-safety property.+ // Here A's remove was ordered first, so B's later drag frame wins and the node survives on both+ // (an honest last-write-wins outcome; see docs/team-presence.md). What can no longer happen is+ // A holding the node while B does not — the split-brain that made A's save resurrect it on disk.+ expect(a.ids()).toEqual(b.ids())+ expect(a.ids()).toEqual(['n1', 'n2'])+ expect(canon(a)).toEqual(canon(b)) // same node set, same values (A re-appended n1: see `canon`)+ expect(a.x('n1')).toBe(50) // B's drag frame is the last write+ })++ it('delete wins when it is the later write, and stays deleted on both', () => {+ a.edit([node('n1', 0), node('n2', 0)])+ bus.settle()++ b.edit(b.states.map((n) => (n.id === 'n1' ? node('n1', 50) : n))) // B's move is cast first…+ a.edit(a.states.filter((n) => n.id !== 'n1')) // …A's delete is ordered after it+ bus.settle()++ expect(a.ids()).toEqual(['n2'])+ expect(b.ids()).toEqual(['n2'])+ expect(a.persisted()).toEqual(b.persisted())+ })++ // A drag is a STREAM of concurrent writes: 20 Hz of frames from each side, all in flight at once.+ it('two clients dragging the same node for many frames still converge', () => {+ a.edit([node('n1', 0)])+ bus.settle()+ for (let i = 1; i <= 20; i++) {+ a.edit([node('n1', i * 10)])+ b.edit([node('n1', 1000 - i * 10)])+ if (i % 3 === 0) bus.settle() // …with the network catching up only sometimes+ }+ bus.settle()++ expect(a.states).toEqual(b.states)+ expect(a.persisted()).toEqual(b.persisted())+ })+it('interleaved mutations from two clients leave identical node sets', () => {a.edit([node('n1', 0)]) // A adds n1+ bus.settle()b.edit([...b.states, node('n2', 0)]) // B adds n2+ bus.settle()a.edit(a.states.map((n) => (n.id === 'n1' ? node('n1', 40) : n))) // A drags n1b.edit(b.states.map((n) => (n.id === 'n2' ? node('n2', 0, 'B') : n))) // B renames n2+ bus.settle()a.edit(a.states.filter((n) => n.id !== 'n2')) // A deletes B's node+ bus.settle()expect(a.ids()).toEqual(b.ids())expect(a.ids()).toEqual(['n1'])expect(a.states).toEqual(b.states)- expect(a.states.find((n) => n.id === 'n1')!.position.x).toBe(40)+ expect(a.x('n1')).toBe(40)// The whole point: whichever client saves, it writes the same bytes.expect(a.persisted()).toEqual(b.persisted())})- it('converges under EVERY interleaving of the same edit set', () => {- // Six independent edits, replayed in a batch of different orders. The reflector is stateless- // and the apply is deterministic, so every order must land on one node set — the only variable- // is WHICH value survives on a node both clients touched (last write wins, checked below).+ it('converges under every interleaving AND every settle point of the same edit set', () => {+ // Six edits, replayed in different orders AND with the network settling at different points —+ // `settleEvery: 6` means all six are cast before a single one is delivered, i.e. maximum+ // concurrency. Both clients must land on one node set every time.const orders = [[0, 1, 2, 3, 4, 5],[5, 4, 3, 2, 1, 0],@@ -154,50 +316,72 @@ describe('canvas convergence', () => {[4, 2, 0, 3, 5, 1]]for (const order of orders) {- bus = new Bus()- initPlatform(bus.platform)- initCanvasSync()- a = new Client(1, bus)- b = new Client(2, bus)- bus.clients = [1, 2]-- const edits: Array<() => void> = [- () => a.edit([...a.states.filter((n) => n.id !== 'n1'), node('n1', 10)]),- () => b.edit([...b.states.filter((n) => n.id !== 'n2'), node('n2', 20)]),- () => a.edit(a.states.map((n) => (n.id === 'n2' ? node('n2', 99) : n))),- () => b.edit(b.states.map((n) => (n.id === 'n1' ? node('n1', 10, 'renamed') : n))),- () => a.edit([...a.states.filter((n) => n.id !== 'n3'), node('n3', 30)]),- () => b.edit(b.states.filter((n) => n.id !== 'n3'))- ]- for (const i of order) edits[i]()-- expect(a.states, `order ${order.join('')}`).toEqual(b.states)- expect(a.ids(), `order ${order.join('')}`).toEqual(b.ids())- expect(a.persisted(), `order ${order.join('')}`).toEqual(b.persisted())- resetPlatformForTests()+ for (const settleEvery of [1, 2, 6]) {+ resetPlatformForTests()+ boot()++ const edits: Array<() => void> = [+ () => a.edit([...a.states.filter((n) => n.id !== 'n1'), node('n1', 10)]),+ () => b.edit([...b.states.filter((n) => n.id !== 'n2'), node('n2', 20)]),+ () => a.edit(a.states.map((n) => (n.id === 'n2' ? node('n2', 99) : n))),+ () => b.edit(b.states.map((n) => (n.id === 'n1' ? node('n1', 10, 'renamed') : n))),+ () => a.edit([...a.states.filter((n) => n.id !== 'n3'), node('n3', 30)]),+ () => b.edit(b.states.filter((n) => n.id !== 'n3'))+ ]+ let n = 0+ for (const i of order) {+ edits[i]()+ if (++n % settleEvery === 0) bus.settle()+ }+ bus.settle()++ const tag = `order ${order.join('')} settle/${settleEvery}`+ // `canon`, not raw array equality: this set contains a delete that can lose the order race,+ // and the client that issued it re-appends the node in a different slot (see `canon`).+ expect(a.ids(), tag).toEqual(b.ids())+ expect(canon(a), tag).toEqual(canon(b))+ }}})+ it('three clients editing the same node concurrently converge on one value', () => {+ const c = new Client(3, bus)+ bus.clients = [1, 2, 3]+ a.edit([node('n1', 0)])+ bus.settle()++ a.edit([node('n1', 1)])+ b.edit([node('n1', 2)])+ c.edit([node('n1', 3)])+ bus.settle()++ expect(a.states).toEqual(b.states)+ expect(b.states).toEqual(c.states)+ expect(a.x('n1')).toBe(3) // C's cast was ordered last+ })+it('last write wins on a concurrent edit to the same node (no CRDT, no merge, no duplicate)', () => {a.edit([node('n1', 0)])a.edit([node('n1', 10)])b.edit(b.states.map((n) => (n.id === 'n1' ? node('n1', 20) : n)))+ bus.settle()expect(a.states).toEqual(b.states)expect(a.states).toHaveLength(1) // one node, not two — upsert replaces by id- expect(a.states[0].position.x).toBe(20) // B wrote last})- it('no infinite loop: a peer mutation is applied once and re-published NEVER', () => {+ it('no infinite loop: an applied mutation is never re-published', () => {a.edit([node('n1', 0)])- expect(b.received).toBe(1)- expect(a.received).toBe(0) // echo suppression: A never gets its own mutation back- expect(bus.casts).toBe(1) // one local edit → exactly one cast; B did not re-emit it+ bus.settle()+ expect(b.applied).toBe(1)+ expect(a.applied).toBe(0) // A's own echo is an ACK, not an edit — applied optimistically already+ expect(bus.castCount).toBe(1) // one local edit → exactly one cast; B did not re-emit itb.edit(b.states.map((n) => (n.id === 'n1' ? node('n1', 5) : n)))- expect(a.received).toBe(1)- expect(b.received).toBe(1) // B's own edit did not come back, and A did not re-emit it- expect(bus.casts).toBe(2) // still one cast per local edit — the adopt() guard holds+ bus.settle()+ expect(a.applied).toBe(1)+ expect(b.applied).toBe(1) // B did not apply its own echo, and A did not re-emit it+ expect(bus.castCount).toBe(2) // still one cast per local edit — the adopt() guard holdsexpect(a.states).toEqual(b.states)})@@ -205,26 +389,30 @@ describe('canvas convergence', () => {const c = new Client(3, bus)bus.clients = [1, 2, 3]a.edit([node('n1', 0), node('n2', 0), node('n3', 0)])- expect(bus.casts).toBe(3) // three upserts, from A only+ bus.settle()+ expect(bus.castCount).toBe(3) // three upserts, from A onlya.edit([]) // bulk delete — three removes in one tick- expect(bus.casts).toBe(6) // three removes, from A only: B and C reflected nothing back+ bus.settle()+ expect(bus.castCount).toBe(6) // three removes, from A only: B and C reflected nothing backexpect(b.states).toEqual([])expect(c.states).toEqual([])- expect(a.received + b.received + c.received).toBe(12) // 6 mutations × 2 peers each+ expect(b.applied + c.applied).toBe(12) // 6 mutations × 2 peers each})it('ephemeral subagent / loop cards are never published', () => {a.ephemeral.add('subagent-abc')a.edit([node('n1', 0), node('subagent-abc', 5), node('loop-n1', 9)])+ bus.settle()expect(a.ids()).toEqual(['loop-n1', 'n1', 'subagent-abc']) // A still renders its own cardsexpect(b.ids()).toEqual(['n1']) // …and the peer got only the real node- expect(b.received).toBe(1)+ expect(b.applied).toBe(1)// Moving an ephemeral card emits nothing at all (it is not in the published baseline).- const casts = bus.casts+ const casts = bus.castCounta.edit(a.states.map((n) => (n.id === 'subagent-abc' ? node('subagent-abc', 77) : n)))- expect(bus.casts).toBe(casts)+ bus.settle()+ expect(bus.castCount).toBe(casts)expect(b.ids()).toEqual(['n1'])// …and the real nodes still converge.expect(a.persisted()).toEqual(b.persisted())@@ -234,16 +422,18 @@ describe('canvas convergence', () => {a.edit([node('n1', 0)])a.edit([...a.states, node('n2', 0)])a.edit(a.states.filter((n) => n.id !== 'n1')) // n1 deleted before C ever connects+ bus.settle()const c = new Client(3, bus)bus.clients = [1, 2, 3]c.states = [...a.states] // a fresh client loads the canvas from disk/store on mountc.pubAdopt() // …and adopts it as the baseline, without republishing it- expect(bus.casts).toBe(3) // the join itself cast nothing+ expect(bus.castCount).toBe(3) // the join itself cast nothinga.edit(a.states.map((n) => (n.id === 'n2' ? node('n2', 7) : n)))b.edit([...b.states, node('n4', 1)])c.edit(c.states.map((n) => (n.id === 'n2' ? node('n2', 7, 'from C') : n)))+ bus.settle()expect(c.states).toEqual(a.states)expect(b.states).toEqual(a.states)@@ -253,7 +443,9 @@ describe('canvas convergence', () => {it('a peer delete is not resurrected by the surviving client (the save-safety property)', () => {a.edit([node('n1', 0), node('n2', 0)])+ bus.settle()b.edit(b.states.filter((n) => n.id !== 'n1')) // B deletes n1+ bus.settle()// A's canvas — the one that would be written by ITS next whole-file workspace.save — no longer// carries n1. Before Stage 3, A's save would have written the deleted node straight back.@@ -262,6 +454,7 @@ describe('canvas convergence', () => {// And A's subsequent edit does not reintroduce it either.a.edit(a.states.map((n) => (n.id === 'n2' ? node('n2', 3) : n)))+ bus.settle()expect(b.ids()).toEqual(['n2'])})})diff --git a/src/core/canvas-sync.test.ts b/src/core/canvas-sync.test.tsindex b15392c70..7d6caa88d 100644--- a/src/core/canvas-sync.test.ts+++ b/src/core/canvas-sync.test.ts@@ -1,7 +1,13 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest'import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'import { fakePlatform } from './platform-fake'-import { initCanvasSync, reflectTargets, isCanvasMutation, MUTATION_MAX_BYTES } from './canvas-sync'+import {+ initCanvasSync,+ reflectTargets,+ stampMutation,+ isCanvasMutation,+ MUTATION_MAX_BYTES+} from './canvas-sync'import { IPC } from '../shared/ipc'import type { CanvasMutation, CanvasNodeState } from '../shared/types'@@ -57,13 +63,38 @@ beforeEach(() => {afterEach(() => resetPlatformForTests())describe('reflectTargets', () => {- it('is every attached client except the sender', () => {- expect(reflectTargets([1, 2, 3], 2)).toEqual([1, 3])- expect(reflectTargets([1], 1)).toEqual([])+ // The sender IS a target: its copy is the ACK that tells it where its own edit landed in the+ // total order — without which two clients editing one node cannot converge (canvas-order rule 2).+ it('is every attached client, the sender included', () => {+ expect(reflectTargets([1, 2, 3], 2)).toEqual([1, 2, 3])+ expect(reflectTargets([1], 1)).toEqual([1])expect(reflectTargets([], 1)).toEqual([])})})+describe('stampMutation', () => {+ it('stamps the total order and keeps the sender tag', () => {+ expect(stampMutation({ op: 'remove', id: 'n1', src: 'cv-abc' }, 7)).toEqual({+ op: 'remove',+ id: 'n1',+ src: 'cv-abc',+ seq: 7+ })+ })++ it('overwrites a client-supplied seq: the order is the server\'s, never the client\'s', () => {+ expect(stampMutation({ op: 'remove', id: 'n1', seq: 999_999 }, 3).seq).toBe(3)+ })++ it('drops a malformed src rather than reflecting it to every peer', () => {+ expect(stampMutation({ op: 'remove', id: 'n1', src: 'x'.repeat(129) }, 1).src).toBeUndefined()+ expect(stampMutation({ op: 'remove', id: 'n1', src: '' }, 1).src).toBeUndefined()+ expect(+ stampMutation({ op: 'remove', id: 'n1', src: 42 as unknown as string }, 1).src+ ).toBeUndefined()+ })+})+describe('isCanvasMutation', () => {it('accepts well-formed mutations and rejects malformed ones', () => {expect(isCanvasMutation({ op: 'remove', id: 'n1' })).toBe(true)@@ -92,20 +123,35 @@ describe('isCanvasMutation', () => {})describe('initCanvasSync (reflector)', () => {- it('echo suppression: the sender never receives its own mutation', () => {+ // Every client, sender included — the sender's copy is its ack (see reflectTargets above). The+ // client drops its own echo instead of re-applying it (canvas-order rule 1), so this is not a+ // loop: the publisher's adopt guard means nothing is ever re-published.+ it('fans a mutation to every attached client, stamped with the total order', () => {t.setClients([1, 2, 3])- const m: CanvasMutation = { op: 'upsert', node: node('n1', 42) }+ const m: CanvasMutation = { op: 'upsert', node: node('n1', 42), src: 'cv-b' }t.cast(2, 'p1', m)+ const stamped = { ...m, seq: 1 }expect(t.sent).toEqual([- { to: 1, channel: IPC.canvasMut, args: ['p1', m] },- { to: 3, channel: IPC.canvasMut, args: ['p1', m] }+ { to: 1, channel: IPC.canvasMut, args: ['p1', stamped] },+ { to: 2, channel: IPC.canvasMut, args: ['p1', stamped] },+ { to: 3, channel: IPC.canvasMut, args: ['p1', stamped] }])})- it('sends nothing when the sender is the only attached client', () => {+ it('seq is monotone across senders and projects — one total order for everyone', () => {+ t.setClients([1, 2])+ t.cast(1, 'p1', { op: 'remove', id: 'n1' })+ t.cast(2, 'p2', { op: 'remove', id: 'n2' })+ t.cast(2, 'p1', { op: 'remove', id: 'n3' })+ expect(t.sent.map((s) => (s.args[1] as CanvasMutation).seq)).toEqual([1, 1, 2, 2, 3, 3])+ })++ it('a solo client still gets its own mutation back (the ack), and nothing else happens', () => {t.setClients([1])t.cast(1, 'p1', { op: 'remove', id: 'n1' })- expect(t.sent).toEqual([])+ expect(t.sent).toEqual([+ { to: 1, channel: IPC.canvasMut, args: ['p1', { op: 'remove', id: 'n1', seq: 1 }] }+ ])})it('drops a malformed mutation instead of reflecting it', () => {@@ -117,21 +163,27 @@ describe('initCanvasSync (reflector)', () => {expect(t.sent).toEqual([])})- it('holds no canvas state: it reflects each mutation verbatim, in order', () => {+ it('holds no canvas state: it reflects each mutation verbatim (bar the stamp), in order', () => {t.setClients([1, 2])t.cast(1, 'p1', { op: 'upsert', node: node('a') })t.cast(2, 'p1', { op: 'remove', id: 'a' })expect(t.sent).toEqual([- { to: 2, channel: IPC.canvasMut, args: ['p1', { op: 'upsert', node: node('a') }] },- { to: 1, channel: IPC.canvasMut, args: ['p1', { op: 'remove', id: 'a' }] }+ { to: 1, channel: IPC.canvasMut, args: ['p1', { op: 'upsert', node: node('a'), seq: 1 }] },+ { to: 2, channel: IPC.canvasMut, args: ['p1', { op: 'upsert', node: node('a'), seq: 1 }] },+ { to: 1, channel: IPC.canvasMut, args: ['p1', { op: 'remove', id: 'a', seq: 2 }] },+ { to: 2, channel: IPC.canvasMut, args: ['p1', { op: 'remove', id: 'a', seq: 2 }] }])})it('is NOT rate-limited: a bulk delete of many nodes reflects every one', () => {t.setClients([1, 2])for (let i = 0; i < 200; i++) t.cast(1, 'p1', { op: 'remove', id: `n${i}` })- expect(t.sent).toHaveLength(200)- expect(t.sent[199]).toEqual({ to: 2, channel: IPC.canvasMut, args: ['p1', { op: 'remove', id: 'n199' }] })+ expect(t.sent).toHaveLength(400) // 200 mutations × (peer + sender ack)+ expect(t.sent[399]).toEqual({+ to: 2,+ channel: IPC.canvasMut,+ args: ['p1', { op: 'remove', id: 'n199', seq: 200 }]+ })})// `on` and `onWithSender` COMPOSE on the same channel — on BOTH shells (seediff --git a/src/core/canvas-sync.ts b/src/core/canvas-sync.tsindex 6742466a4..744193b9c 100644--- a/src/core/canvas-sync.ts+++ b/src/core/canvas-sync.ts@@ -1,16 +1,27 @@// Canvas sync — the reflector.//// Every attached client (an Electron renderer, a Server-Edition browser tab) casts its LOCAL node-// mutations on `canvas:mut`. This service sends each one back out on the same channel to every-// OTHER attached client, so all clients converge on the same node set — a teammate's cursor never-// hovers over stale geometry, and a client whose canvas still held a node someone else deleted can-// no longer write it back on the next whole-file workspace.save.+// mutations on `canvas:mut`. This service stamps each one with a monotone `seq` and sends it back+// out on the same channel to EVERY attached client, so all clients converge on the same node set —+// a teammate's cursor never hovers over stale geometry, and a client whose canvas still held a node+// someone else deleted can no longer write it back on the next whole-file workspace.save.//-// 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. Echo suppression is by sender ClientId: a client must never-// receive its own mutation back (it would fight its own optimistic state, and with the renderer's-// diff-publisher it would loop).+// THE `seq` IS THE POINT, and it is the one piece of state here. Without a total order, two clients+// that edit the same node while each other's mutation is in flight apply them in OPPOSITE orders+// and diverge permanently — see the derivation in src/shared/canvas-order.ts, which is the client+// half of this contract. `seq` is server-authoritative: whatever the client put there is+// overwritten at ingest, so a client cannot forge its way to the front of the order.+//+// IT ECHOES TO THE SENDER TOO — that is deliberate, and it replaced the earlier sender-suppression.+// A sender's own echo is its ACK: it is the only way it learns where its edit landed in the total+// order, which is what lets it decide whether a peer's mutation supersedes its own optimistic+// state. The client drops the echo instead of re-applying it (canvas-order rule 1), so it does not+// 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.//// 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@@ -38,9 +49,26 @@ import type { CanvasMutation } from '../shared/types'*/export const MUTATION_MAX_BYTES = 256_000-/** Every attached client except the sender. Pure — exported for the test. */-export function reflectTargets(all: ClientId[], sender: ClientId): ClientId[] {- return all.filter((id) => id !== sender)+/**+ * Every attached client the mutation goes to — INCLUDING the sender, whose copy is its ack (see the+ * header). Pure — exported for the test. `sender` is kept in the signature: it is the seam a policy+ * would need, and dropping it would make "the sender is included" look accidental rather than+ * chosen.+ */+export function reflectTargets(all: ClientId[], _sender: ClientId): ClientId[] {+ return all.slice()+}++/**+ * 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+ * 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.+ */+export function stampMutation(m: CanvasMutation, seq: number): CanvasMutation {+ const stamped: CanvasMutation = { ...m, seq }+ if (!isRefId(stamped.src)) delete stamped.src+ return stamped}/** An id off the wire: non-empty and bounded by the shared ref cap (node ids and project ids are@@ -87,17 +115,30 @@ function withinSizeLimit(m: unknown): boolean {* boot (or a fresh test platform) registers again. */let registeredOn: CorePlatform | null = null+/**+ * The total order. One counter for the whole process (not per project): `seq` is only ever compared+ * between mutations addressing the SAME node, and node ids are globally unique (a node id is a tmux+ * session name), so a single counter orders every canvas correctly and cannot be confused by a+ * client that switches projects. Reset with the registration, so a fresh boot starts from 0 — which+ * is safe because a client's ordering state (canvas-order) is per Canvas mount and starts empty too.+ */+let seq = 0+/** Install the `canvas:mut` reflector. Call once at boot, after initPlatform(). */export function initCanvasSync(): void {const p = platform()if (registeredOn === p) returnregisteredOn = p+ seq = 0p.onWithSender(IPC.canvasMut, (senderId: number, projectId: unknown, mutation: unknown) => {// Which canvas the edit belongs to is client-supplied too, and it is reflected verbatim.if (!isRefId(projectId)) returnif (!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).+ const stamped = stampMutation(mutation, ++seq)for (const id of reflectTargets(p.clientIds(), senderId)) {- p.sendTo(id, IPC.canvasMut, projectId, mutation)+ p.sendTo(id, IPC.canvasMut, projectId, stamped)}})}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 1b0abe8b2..b83b28a60 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -295,7 +295,9 @@ const api: NodeTerminalApi = {ipcRenderer.send(IPC.contextEnsure, sessionId, cwd, accountId)},// Canvas sync: one channel in both directions. The cast goes to the reflector (src/core/canvas-sync),- // which fans it to every OTHER attached client — so what arrives here is always a peer's mutation.+ // which stamps it with the total order (`seq`) and fans it to every attached client — INCLUDING us.+ // Our own mutation coming back is the ACK that tells us where it landed in that order; the renderer+ // recognizes it by `src` and does not re-apply it (src/shared/canvas-order.ts).canvas: {mutate: (projectId, mutation) => ipcRenderer.send(IPC.canvasMut, projectId, mutation),onMutation: (listener) => {diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 0f34846a9..0f4a9ca18 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -343,8 +343,10 @@ export function buildAgentApi(/*** Build the `canvas` namespace over an RpcClient: a cast out (`canvas:mut`) and a subscription in on- * the same channel. The server reflects each mutation to every OTHER client, so the `ev` frames we- * receive here are always a peer's — never our own echo. This is a REAL implementation, not a stub:+ * the same channel. The server stamps each mutation with the total order (`seq`) and reflects it to+ * every client, us included — our own frame coming back is the ACK that carries our place in that+ * order (the renderer recognizes it by `src`; see src/shared/canvas-order.ts). This is a REAL+ * implementation, not a stub:* the Server Edition (two browsers on one workspace) is the surface that needs canvas sync most.*/export function buildCanvasApi(client: RpcClient): Pick<NodeTerminalApi, 'canvas'> {diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex b8f7fad9a..7c6dd11ff 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -81,7 +81,7 @@ import { UsageIndicator } from '../components/UsageIndicator'import { PresenceLayer } from '../components/PresenceLayer'import { Facepile } from '../components/Facepile'import { PresenceNamePrompt } from '../components/PresenceNamePrompt'-import { connectPresence, reportProject } from '../state/presence'+import { connectPresence, reportProject, usePresence } from '../state/presence'import { nodeTravel, projectTravel } from '../lib/presenceTravel'import { RemoteSessionView } from './RemoteSessionView'import { RemoteAccessDialog } from '../components/RemoteAccessDialog'@@ -132,8 +132,10 @@ import {publishableStates,type CanvasPublisher} from '@shared/canvas-publish'+import { createCanvasOrder, type CanvasOrder } from '@shared/canvas-order'import {applyCanvasMutation,+ applyMutationToFlow,claudeLaunchCommand,COLLAPSED_HEIGHT,alignNodes,@@ -380,6 +382,16 @@ export function Canvas() {const draggingRef = useRef(false)// Canvas sync (emitting side) — see the publish effect below.const publisherRef = useRef<CanvasPublisher | null>(null)+ // Canvas sync (ordering) — decides which incoming mutations to apply (see @shared/canvas-order).+ const orderRef = useRef<CanvasOrder | null>(null)+ /**+ * Is anyone else attached? The solo gate for the publisher (a solo user must not pay to diff and+ * cast a canvas nobody receives). A REF, fed by a non-reactive presence subscription: the peer+ * table also carries cursors at 20 Hz, and Canvas is ~4000 lines — reading it reactively would+ * re-render the whole canvas on every remote mouse move (docs/team-presence.md, PERF CONTRACT).+ * Sticky once a peer mutation actually arrives: proof of a peer that outranks any table.+ */+ const hasPeersRef = useRef(false)const [, bumpHist] = useState(0)const { setViewport, getViewport, fitView, zoomIn, zoomOut, screenToFlowPosition, setCenter, getZoom } =useReactFlow()@@ -963,15 +975,41 @@ export function Canvas() {// cursor hovering over stale geometry, and no client writing back a node someone else deleted on// its next whole-file workspace.save. Declared BEFORE the [nodes] publish effect so the publisher// exists by the time that one first runs on mount.+ //+ // The publisher stamps every mutation with `src` (this Canvas's tag) so the reflector's echo of+ // our OWN mutation is recognizable as an ack rather than an edit, and `orderRef` turns those acks+ // + the reflector's `seq` into the per-node total order that makes two clients editing one node+ // CONVERGE (@shared/canvas-order). Cast → order.onLocal(m) → the mutation is "pending" until its+ // ack returns; while it is, a peer's edit to that node loses to ours (it must — ours is later in+ // the reflector's order, so it wins on every other client too).useEffect(() => {- const pub = createCanvasPublisher((m) => {- const projectId = useProjects.getState().activeProjectId- if (projectId) window.nodeTerminal.canvas.mutate(projectId, m)- })+ const src = `cv-${Math.random().toString(36).slice(2, 10)}`+ const order = createCanvasOrder(src)+ orderRef.current = order+ // Solo gate: publish only once someone else is attached. The presence hub's peer table includes+ // US, so >1 means a peer. Subscribed imperatively (no useStore selector) — this must never+ // re-render Canvas.+ const readPeers = (): void => {+ hasPeersRef.current =+ hasPeersRef.current || Object.keys(usePresence.getState().peers).length > 1+ }+ readPeers()+ const unsub = usePresence.subscribe(readPeers)+ const pub = createCanvasPublisher(+ (m) => {+ const projectId = useProjects.getState().activeProjectId+ if (!projectId) return // no active canvas → the cast would be dropped at ingest, un-acked+ order.onLocal(m)+ window.nodeTerminal.canvas.mutate(projectId, m)+ },+ { src, shouldPublish: () => hasPeersRef.current }+ )publisherRef.current = pubreturn () => {+ unsub()pub.dispose()publisherRef.current = null+ orderRef.current = null}}, [])@@ -994,12 +1032,18 @@ export function Canvas() {pub.publish(states, { throttle: draggingRef.current })}, [nodes, publishableNow])- // Receiving side: apply a PEER's mutation. Deliberately separate from the relay+ // Receiving side: apply an incoming mutation. Deliberately separate from the relay// `remoteHost.onApplyMutation` effect above — that one is host↔client, this one is peer↔peer.//+ // `order.accept` is the gate, and it is what makes concurrent edits converge rather than split the+ // canvas in two (@shared/canvas-order): it drops our OWN echo (already applied optimistically —+ // re-applying it would rubber-band a node we are still dragging), drops a straggler the total+ // order has superseded, and drops a peer's edit to a node whose newer edit of ours is still in+ // flight. Everything it lets through is, by the reflector's `seq`, the current truth for that node.+ //// `adopt` is the loop guard: the publisher takes the resulting snapshot as its baseline BEFORE// the [nodes] effect above can diff it, so the applied mutation diffs to nothing and cannot be- // re-published (A→B→C→A forever). The reflector's sender-id echo suppression is the other half.+ // re-published (A→B→C→A forever).//// A mutation for a project that is loaded but NOT active is applied to that project's SERIALIZED// nodes in the projects store (React Flow only ever holds the active project's nodes). Dropping@@ -1011,23 +1055,38 @@ export function Canvas() {// clients saving the same converged state is harmless; never saving it is not.useEffect(() => {return window.nodeTerminal.canvas.onMutation((projectId, mutation) => {+ hasPeersRef.current = true // proof of a peer, whatever the presence table says+ if (!orderRef.current?.accept(mutation)) returnif (projectId !== useProjects.getState().activeProjectId) {+ // 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') disposeTerminalOnUnmount(mutation.id)if (useProjects.getState().applyNodeMutation(projectId, mutation)) markDirty()return}- const next = applyCanvasMutation(flowToNodeStates(nodesRef.current), mutation)- // Adopt the ROUND-TRIPPED snapshot (nodeStatesToFlow defaults a few fields), so the baseline- // is byte-identical to what the [nodes] effect will serialize next.- const flow = nodeStatesToFlow(next)+ // PATCH THE LIVE ARRAY — do not round-trip the canvas through the (lossy) serializers. That+ // wiped your selection, deleted your relay-remote nodes and re-rendered every node component,+ // ~20 times a second while a teammate dragged. See applyMutationToFlow.+ const flow = applyMutationToFlow(nodesRef.current, mutation)+ if (flow === nodesRef.current) return // nothing to do (a remove for a node we do not have)+ if (mutation.op === 'remove') {+ // The peer's delete must also dispose OUR terminal co-state for that node — otherwise the+ // module-level state survives the node, and if the owner UNDOES the delete we are left+ // holding a node that reads "closed by another user" while its session is alive again.+ const gone = nodesRef.current.find((n) => n.id === mutation.id)+ if (gone?.type === 'terminal') disposeTerminalOnUnmount(gone.id)+ }// Keep the ref in step immediately: a burst (a peer's bulk delete) arrives within one tick,// before React re-renders, and each mutation must build on the previous one.nodesRef.current = flowpublisherRef.current?.adopt(publishableNow(flow))- // Undo stays LOCAL: a peer's edit is not something YOU did, so it must not become an entry in- // your undo stack. Taking it as the committed baseline makes the debounced snapshot effect- // see `nodes === committedRef.current` and record nothing. (Your own undo still publishes —- // it goes through setNodes → the [nodes] effect → a normal diff.)- committedRef.current = flow+ // Undo stays LOCAL — but it must not EAT a local entry either. REBASE the committed baseline+ // by applying the peer's mutation to it, rather than replacing it with the current nodes:+ // replacing it made `nodes === committedRef.current`, so a local edit still inside the 300 ms+ // undo debounce was silently dropped from the undo stack whenever a peer's mutation landed+ // 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)markDirty()})diff --git a/src/renderer/state/presence.ts b/src/renderer/state/presence.tsindex e27762d7d..fb85eb0ce 100644--- a/src/renderer/state/presence.ts+++ b/src/renderer/state/presence.ts@@ -36,9 +36,12 @@ import {* facepile and chase our own ghost cursor.** PERF CONTRACT: only the presence components (PresenceLayer / Facepile / PresenceChips) may- * subscribe to this store. Canvas.tsx is ~4000 lines — if a cursor at 20 Hz re-rendered it, every- * mouse move would redraw the whole canvas. Canvas mounts the components and calls- * connectPresence(); it never reads the store.+ * subscribe to this store REACTIVELY. Canvas.tsx is ~4000 lines — if a cursor at 20 Hz re-rendered+ * it, every mouse move would redraw the whole canvas. Canvas mounts the components and calls+ * connectPresence(); it never uses the `usePresence(selector)` hook. It does read the peer table+ * IMPERATIVELY — `getState()` + a plain `subscribe()` into a ref — for the canvas-sync solo gate+ * ("is anyone else attached?"). That is not a subscription React can re-render on: no hook, no+ * selector, no component state. Keep it that way.*/export const ME_KEY = 'nodeterm.presence.me'diff --git a/src/renderer/state/workspace.mutation.test.ts b/src/renderer/state/workspace.mutation.test.tsnew file mode 100644index 000000000..b66309cf9--- /dev/null+++ b/src/renderer/state/workspace.mutation.test.ts@@ -0,0 +1,123 @@+// applyMutationToFlow — a peer's canvas-sync mutation applied to the LIVE React Flow array.+//+// The first cut round-tripped the whole canvas through the serializers on every peer mutation+// (nodeStatesToFlow(applyCanvasMutation(flowToNodeStates(nodes), m))). The serializers are lossy BY+// DESIGN, so that destroyed live state ~20 times a second while a teammate dragged. Each `it` below+// is one of the things it destroyed.++import { describe, it, expect } from 'vitest'+import { applyMutationToFlow, flowToNodeStates, type CanvasNode } from './workspace'+import type { CanvasMutation, CanvasNodeState } from '@shared/types'++const flowNode = (id: string, x: number, extra: Partial<CanvasNode> = {}): CanvasNode =>+ ({+ id,+ type: 'terminal',+ position: { x, y: 0 },+ width: 400,+ height: 300,+ style: { width: 400, height: 300 },+ data: { title: id, color: '#fff', group: null, tags: [] },+ ...extra+ }) as CanvasNode++const state = (id: string, x: number, over: Partial<CanvasNodeState> = {}): CanvasNodeState =>+ ({+ id,+ kind: 'terminal',+ position: { x, y: 0 },+ size: { width: 400, height: 300 },+ title: id,+ color: '#fff',+ group: null,+ tags: [],+ ...over+ }) as CanvasNodeState++const upsert = (n: CanvasNodeState): CanvasMutation => ({ op: 'upsert', node: n })+const remove = (id: string): CanvasMutation => ({ op: 'remove', id })++describe('applyMutationToFlow', () => {+ it('patches the addressed node and leaves every other node OBJECT untouched (no re-render)', () => {+ const nodes = [flowNode('a', 0), flowNode('b', 10)]+ const out = applyMutationToFlow(nodes, upsert(state('b', 99)))+ expect(out[0]).toBe(nodes[0]) // same reference → React.memo holds → `a` does not re-render+ expect(out[1]).not.toBe(nodes[1])+ expect(out[1].position).toEqual({ x: 99, y: 0 })+ })++ // While a teammate drags, mutations land at ~20 Hz. Round-tripping wiped `selected` every time,+ // so you could not hold a box-select / shift-click long enough to group anything.+ it('preserves YOUR selection on the node the peer touched', () => {+ const nodes = [flowNode('a', 0, { selected: true })]+ const out = applyMutationToFlow(nodes, upsert(state('a', 50)))+ expect(out[0].selected).toBe(true)+ expect(out[0].position).toEqual({ x: 50, y: 0 })+ })++ // flowToNodeStates FILTERS remote nodes (transient to a relay connection, never persisted), so+ // the round trip deleted every relay terminal on your canvas on each peer mutation.+ it('keeps relay-remote nodes, which a serialize round trip would delete', () => {+ const nodes = [flowNode('r1', 0, { data: { title: 'r', color: '#fff', group: null, remote: { connectionId: 'c1' } } } as Partial<CanvasNode>), flowNode('a', 0)]+ expect(flowToNodeStates(nodes).map((n) => n.id)).toEqual(['a']) // …the lossy bit, pinned+ const out = applyMutationToFlow(nodes, upsert(state('a', 5)))+ expect(out.map((n) => n.id)).toEqual(['r1', 'a'])+ expect(out[0]).toBe(nodes[0])+ })++ // initialCommand / respawnNonce / forkFrom are deliberately not serialized. A peer's rename must+ // not silently drop them from a node that has not consumed them yet.+ it('keeps local-only node data (initialCommand) while applying the peer\'s fields', () => {+ const nodes = [+ flowNode('a', 0, {+ data: { title: 'old', color: '#fff', group: null, initialCommand: 'claude\r' }+ } as Partial<CanvasNode>)+ ]+ const out = applyMutationToFlow(nodes, upsert(state('a', 0, { title: 'renamed by peer' })))+ expect(out[0].data.initialCommand).toBe('claude\r')+ expect(out[0].data.title).toBe('renamed by peer')+ })++ it('applies a peer CLEARING a serialized field (tags removed, not merged back in)', () => {+ const nodes = [flowNode('a', 0, { data: { title: 'a', color: '#fff', group: null, tags: ['x'] } } as Partial<CanvasNode>)]+ const out = applyMutationToFlow(nodes, upsert(state('a', 0, { tags: undefined })))+ expect(out[0].data.tags).toBeUndefined()+ })++ // React Flow's `measured` wins over width/height when we serialize. Carrying a stale one would+ // make us re-publish the OLD size right back at the peer who just resized the node.+ it('drops the stale measured size so a peer resize is not fought', () => {+ const nodes = [flowNode('a', 0, { measured: { width: 400, height: 300 } } as Partial<CanvasNode>)]+ const out = applyMutationToFlow(nodes, upsert(state('a', 0, { size: { width: 900, height: 700 } })))+ expect(out[0].measured).toBeUndefined()+ expect(flowToNodeStates(out)[0].size).toEqual({ width: 900, height: 700 })+ })++ it('appends a node the peer created', () => {+ const nodes = [flowNode('a', 0)]+ const out = applyMutationToFlow(nodes, upsert(state('b', 20)))+ expect(out.map((n) => n.id)).toEqual(['a', 'b'])+ })++ it('removes a node the peer deleted, and is a no-op (same array) for one we do not have', () => {+ const nodes = [flowNode('a', 0), flowNode('b', 0)]+ expect(applyMutationToFlow(nodes, remove('b')).map((n) => n.id)).toEqual(['a'])+ expect(applyMutationToFlow(nodes, remove('zz'))).toBe(nodes) // identity → no setNodes churn+ })++ // React Flow REQUIRES a parent to appear before its children. A peer grouping nodes sends the new+ // group frame plus the (already present) children, so the frame arrives as an append.+ it('keeps parents before children when a peer creates a group around existing nodes', () => {+ const nodes = [flowNode('a', 0), flowNode('b', 0)]+ const withGroup = applyMutationToFlow(+ nodes,+ upsert(state('g1', 0, { kind: 'group' }))+ )+ const parented = applyMutationToFlow(+ withGroup,+ upsert(state('a', 0, { parentId: 'g1' }))+ )+ expect(parented.map((n) => n.id)).toEqual(['g1', 'a', 'b'])+ expect(parented.find((n) => n.id === 'a')!.parentId).toBe('g1')+ })+})diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 0b5d2a87b..1dfd57d27 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -1002,3 +1002,50 @@ export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {}})}++/**+ * Apply ONE peer mutation (canvas sync) to the LIVE React Flow node array — patch/append/remove+ * just that node, and leave every other node object untouched.+ *+ * NOT `nodeStatesToFlow(applyCanvasMutation(flowToNodeStates(nodes), m))`. That whole-canvas round+ * trip was the first cut, and the serializers are lossy BY DESIGN, so it destroyed live state on+ * every peer mutation — 20 times a second while a teammate drags:+ * - SELECTION. `nodeStatesToFlow` never sets `selected`, so a teammate's drag wiped your+ * box-select / shift-click / select-then-group the instant it landed.+ * - REMOTE NODES. `flowToNodeStates` filters `!n.data.remote` (they are transient to a relay+ * connection and must never persist), so round-tripping DELETED every relay terminal on your+ * canvas.+ * - LOCAL-ONLY DATA. `initialCommand`, `respawnNonce`, `forkFrom` never survive a serialize.+ * - IDENTITY. Every node object was rebuilt → every node component re-rendered, per mutation.+ * Patching in place keeps all four: untouched nodes keep their object identity (React.memo holds),+ * and the touched one keeps `selected` and its local-only data.+ *+ * `measured` is deliberately NOT carried over on the patched node: React Flow's measured size wins+ * over `width`/`height` in flowToNodeStates, so keeping a stale one would make us serialize the OLD+ * size after a peer resized the node — and re-publish it, fighting the peer. Dropping it lets React+ * Flow re-measure from the incoming `style`, which is what the peer sent.+ */+export function applyMutationToFlow(nodes: CanvasNode[], m: import('@shared/types').CanvasMutation): CanvasNode[] {+ if (m.op === 'remove') {+ if (!nodes.some((n) => n.id === m.id)) return nodes // already gone — keep identity, skip render+ return nodes.filter((n) => n.id !== m.id)+ }+ const incoming = nodeStatesToFlow([m.node])[0]+ const idx = nodes.findIndex((n) => n.id === m.node.id)+ if (idx === -1) {+ // Append, then re-sort: React Flow requires a parent to appear BEFORE its children, and a peer+ // grouping nodes sends the new group frame and its (already present) children in one burst.+ return groupsFirst([...nodes, incoming])+ }+ const prev = nodes[idx]+ const next = nodes.slice()+ next[idx] = {+ ...incoming,+ selected: prev.selected,+ // Local-only data (initialCommand / respawnNonce / remote / forkFrom) is not serialized, so it+ // is not in `incoming` — carry it. Every serialized key IS present on incoming.data (as a value+ // or an explicit undefined), so the spread still applies the peer's clears.+ data: { ...prev.data, ...incoming.data }+ }+ return prev.parentId === incoming.parentId ? next : groupsFirst(next)+}diff --git a/src/shared/canvas-order.test.ts b/src/shared/canvas-order.test.tsnew file mode 100644index 000000000..b37f67f52--- /dev/null+++ b/src/shared/canvas-order.test.ts@@ -0,0 +1,128 @@+// The ordering state — the client half of the convergence contract (the other half is the+// reflector's `seq`). The end-to-end proof lives in src/core/canvas-sync.convergence.test.ts+// (two clients, async bus); this pins the rules one at a time.++import { describe, it, expect } from 'vitest'+import { createCanvasOrder, mutationNodeId, PENDING_TTL_MS } from './canvas-order'+import type { CanvasMutation, CanvasNodeState } from './types'++const node = (id: string, x = 0): CanvasNodeState =>+ ({+ id,+ kind: 'terminal',+ title: 't',+ color: '#fff',+ group: null,+ position: { x, y: 0 },+ size: { width: 10, height: 10 }+ }) as CanvasNodeState++const up = (id: string, x: number, src: string | undefined, seq: number): CanvasMutation => ({+ op: 'upsert',+ node: node(id, x),+ ...(src ? { src } : {}),+ seq+})+const rm = (id: string, src: string | undefined, seq: number): CanvasMutation => ({+ op: 'remove',+ id,+ ...(src ? { src } : {}),+ seq+})++describe('mutationNodeId', () => {+ it('is the node a mutation addresses, whichever op', () => {+ expect(mutationNodeId(up('n1', 0, 'x', 1))).toBe('n1')+ expect(mutationNodeId(rm('n2', 'x', 1))).toBe('n2')+ })+})++describe('createCanvasOrder', () => {+ it('applies a peer mutation', () => {+ const o = createCanvasOrder('me')+ expect(o.accept(up('n1', 5, 'peer', 1))).toBe(true)+ })++ // Rule 1. Our own mutation comes back stamped (the reflector echoes to the sender — that echo is+ // the ack). It must NOT be re-applied: we applied it optimistically, and by the time it returns+ // the user may already have dragged the node further — re-applying would rubber-band it.+ it('never re-applies our own echo (it is an ack, not an edit)', () => {+ const o = createCanvasOrder('me')+ const mine = up('n1', 10, 'me', 1)+ o.onLocal(mine)+ expect(o.accept(mine)).toBe(false)+ })++ // Rule 2. While one of OUR mutations for a node is unacked, a peer's mutation for that node is+ // necessarily EARLIER in the total order (FIFO: had the reflector ordered ours first, our ack+ // would already be here). Ours will therefore win on every other client — so we keep ours.+ it('a peer mutation loses to an unacked local edit of the same node', () => {+ const o = createCanvasOrder('me')+ o.onLocal(up('n1', 200, 'me', 0)) // cast, not yet acked+ expect(o.accept(up('n1', 100, 'peer', 7))).toBe(false) // peer's edit: dropped, ours wins+ expect(o.accept(up('n1', 100, 'me', 8))).toBe(false) // …our ack arrives+ expect(o.accept(up('n1', 300, 'peer', 9))).toBe(true) // …and now peers land again+ })++ it('does not let one node\'s pending edit suppress another node', () => {+ const o = createCanvasOrder('me')+ o.onLocal(up('n1', 1, 'me', 0))+ expect(o.accept(up('n2', 1, 'peer', 4))).toBe(true)+ })++ it('counts pending edits per node (a drag casts many frames before the first ack)', () => {+ const o = createCanvasOrder('me')+ o.onLocal(up('n1', 1, 'me', 0))+ o.onLocal(up('n1', 2, 'me', 0))+ expect(o.accept(up('n1', 9, 'peer', 5))).toBe(false)+ expect(o.accept(up('n1', 1, 'me', 6))).toBe(false) // ack 1 of 2 — still one frame in flight+ expect(o.accept(up('n1', 9, 'peer', 7))).toBe(false)+ expect(o.accept(up('n1', 2, 'me', 8))).toBe(false) // ack 2 of 2+ expect(o.accept(up('n1', 9, 'peer', 9))).toBe(true)+ })++ // Deliveries are FIFO per connection, but a client applies mutations from SEVERAL senders, so a+ // straggler can still arrive after a newer mutation for the same node has landed (e.g. it was+ // held while one of ours was pending). Applying it would drag the node backwards out of the order.+ it('drops a mutation the total order has already superseded', () => {+ const o = createCanvasOrder('me')+ expect(o.accept(up('n1', 10, 'peer', 5))).toBe(true)+ expect(o.accept(up('n1', 99, 'other', 3))).toBe(false) // older seq → superseded+ expect(o.accept(up('n1', 99, 'other', 5))).toBe(false) // same seq → duplicate+ expect(o.accept(up('n1', 99, 'other', 6))).toBe(true) // newer → wins+ })++ it('a remove and an upsert of one node share the order (a remove is not special-cased)', () => {+ const o = createCanvasOrder('me')+ expect(o.accept(rm('n1', 'peer', 4))).toBe(true)+ expect(o.accept(up('n1', 1, 'peer', 3))).toBe(false) // an older upsert cannot resurrect it+ expect(o.accept(up('n1', 1, 'other', 5))).toBe(true) // a NEWER one can (that is undo-of-delete)+ })++ // The pending gate assumes the ack always comes back. It usually does — but the reflector drops+ // a mutation it refuses (oversized), and that would otherwise deafen the node to its peers for+ // the rest of the session.+ it('an ack that never arrives expires — a lost cast cannot deafen a node forever', () => {+ let t = 1000+ const o = createCanvasOrder('me', { now: () => t })+ o.onLocal(up('n1', 1, 'me', 0)) // cast… and the reflector refuses it: no ack, ever+ expect(o.accept(up('n1', 5, 'peer', 2))).toBe(false)+ t += PENDING_TTL_MS + 1+ expect(o.accept(up('n1', 6, 'peer', 3))).toBe(true)+ })++ it('an unstamped mutation (no reflector in the path) is never treated as stale', () => {+ const o = createCanvasOrder('me')+ const unstamped: CanvasMutation = { op: 'upsert', node: node('n1', 1) }+ expect(o.accept(unstamped)).toBe(true)+ expect(o.accept(unstamped)).toBe(true)+ })++ it('reset forgets the order and the pending edits (project switch / reconnect)', () => {+ const o = createCanvasOrder('me')+ o.onLocal(up('n1', 1, 'me', 0))+ expect(o.accept(up('n1', 5, 'peer', 9))).toBe(false)+ o.reset()+ expect(o.accept(up('n1', 5, 'peer', 1))).toBe(true) // pending gone AND the seq floor gone+ })+})diff --git a/src/shared/canvas-order.ts b/src/shared/canvas-order.tsnew file mode 100644index 000000000..4d8fb2a36--- /dev/null+++ b/src/shared/canvas-order.ts@@ -0,0 +1,139 @@+// Canvas sync — the ordering state. This is what makes two people editing the SAME node converge.+//+// THE PROBLEM. Stage 3's first cut was pure optimistic last-write-wins with no order: each client+// applied its own edit immediately, cast it, and applied whatever arrived from a peer. That is only+// safe if two edits are never in flight at once — and on a real (asynchronous) bus, two people+// dragging one node cross on EVERY frame:+//+// A drags n1 to x=200 ─┐ ┌─ B drags n1 to x=100+// ├─ both in flight ───┤+// A applies B's 100 ───┘ └─ B applies A's 200+// → A shows 100, B shows 200. FOREVER. And both publishers have `adopt`ed, so neither+// re-publishes — the divergence is permanent, and the next whole-file workspace.save from+// either side overwrites the other's canvas on disk. Worse with a delete: A deletes a node,+// B (mid-drag) sends the next frame, A applies it and RESURRECTS the node it just deleted —+// the exact "a client writes back a node someone else deleted" bug Stage 3 exists to kill.+//+// THE FIX (no CRDT). The reflector stamps every mutation with a monotone `seq` — one total order,+// the same for everyone — and echoes it to EVERY client, the sender included. Per node, the highest+// `seq` wins. Two rules, and they are the whole algorithm:+//+// 1. OUR OWN ECHO IS AN ACK, NOT AN EDIT. We already applied it optimistically; re-applying it+// would rubber-band a node we are still dragging (the echo carries the position from ~50 ms+// ago). So we consume it for its `seq` and drop it.+// 2. WHILE ONE OF OUR OWN MUTATIONS FOR A NODE IS UNACKED, WE IGNORE PEERS' MUTATIONS FOR THAT+// NODE. Not a heuristic — a consequence of FIFO delivery, which IPC and WebSocket both+// guarantee: if the reflector had ordered our mutation BEFORE the peer's, our ack would+// already have arrived (the reflector sent it to us first). So an unacked local mutation is+// necessarily LATER in the total order than anything we are hearing now — it will win on every+// other client, and keeping it here is what agrees with them.+//+// Together those give: every client ends on the mutation with the highest `seq` for that node.+// Convergence, on any interleaving. What it deliberately does NOT give is intent preservation —+// two people dragging one node still fight, and a delete concurrent with an edit is decided by the+// total order, not by "delete wins" (see docs/team-presence.md, which states the resolution).+//+// Pure: no React, no DOM, no timers (the pending TTL below is a lazy clock read, not a timer).++import type { CanvasMutation } from './types'++/**+ * How long an unacked local mutation keeps suppressing peers' mutations for that node.+ *+ * Rule 2 above assumes the ack ALWAYS comes back. Almost always it does — but the reflector drops+ * a mutation it cannot validate (an oversized sticky body: MUTATION_MAX_BYTES) and a cast made with+ * no project active never reaches it at all. Without a bound, one such drop would silently deafen+ * that node to its peers for the rest of the session. So a pending entry expires: after this long,+ * the node listens again. Generous next to a round trip (sub-millisecond in-process, single-digit+ * ms over a LAN WS) and short next to a human noticing.+ */+export const PENDING_TTL_MS = 5000++/** The node a mutation addresses. */+export function mutationNodeId(m: CanvasMutation): string {+ return m.op === 'remove' ? m.id : m.node.id+}++export interface CanvasOrder {+ /** Record a mutation WE are casting (it becomes pending until its echo comes back). */+ onLocal(m: CanvasMutation): void+ /**+ * Decide an incoming mutation (a peer's, or our own echoed back).+ * `true` → apply it to the canvas.+ * `false` → drop it: our own echo (already applied), a straggler the total order has superseded,+ * or a peer's edit to a node whose newer local edit of ours is still in flight.+ */+ accept(m: CanvasMutation): boolean+ /** Forget everything (project switch / disconnect). */+ reset(): void+}++interface Pending {+ count: number+ /** When the OLDEST still-unacked mutation for this node was cast (for PENDING_TTL_MS). */+ since: number+}++/**+ * Ordering state for one client. `src` is this client's publisher tag — the mutations it stamps,+ * and therefore the echoes it must recognize as its own.+ */+export function createCanvasOrder(+ src: string,+ opts: { now?: () => number; ttlMs?: number } = {}+): CanvasOrder {+ const now = opts.now ?? (() => Date.now())+ const ttlMs = opts.ttlMs ?? PENDING_TTL_MS+ /** Highest `seq` this client has SEEN for a node (applied or deliberately dropped). */+ const seen = new Map<string, number>()+ /** Our own casts for a node that have not been echoed back yet. */+ const pending = new Map<string, Pending>()++ const hasPending = (id: string): boolean => {+ const p = pending.get(id)+ if (!p) return false+ if (now() - p.since > ttlMs) {+ // The ack never came (the reflector refused the cast, or the project went away). Stop+ // suppressing this node's peers — a lost ack must not cost us the node forever.+ pending.delete(id)+ return false+ }+ return true+ }++ return {+ onLocal(m) {+ const id = mutationNodeId(m)+ const p = pending.get(id)+ if (p) p.count+++ else pending.set(id, { count: 1, since: now() })+ },++ accept(m) {+ const id = mutationNodeId(m)+ const seq = m.seq ?? 0+ const highest = seen.get(id) ?? 0+ if (seq > highest) seen.set(id, seq)++ if (m.src && m.src === src) {+ // Rule 1: our own mutation, echoed back. It is the ack — consume it, apply nothing.+ const p = pending.get(id)+ if (p && --p.count <= 0) pending.delete(id)+ return false+ }+ // A straggler: a mutation the total order has already superseded on this client (applied, or+ // deliberately dropped). Applying it would move the node BACKWARDS out of the total order.+ // `seq` 0 means an unstamped mutation (no reflector in the path) — never treat it as stale.+ if (seq !== 0 && seq <= highest) return false+ // Rule 2: an edit of ours for this node is still in flight, so it is later in the total order+ // than this one and will win everywhere. Keep ours; the peers will land on it.+ if (hasPending(id)) return false+ return true+ },++ reset() {+ seen.clear()+ pending.clear()+ }+ }+}diff --git a/src/shared/canvas-publish.test.ts b/src/shared/canvas-publish.test.tsindex e849d2709..e9bc05ebb 100644--- a/src/shared/canvas-publish.test.ts+++ b/src/shared/canvas-publish.test.ts@@ -119,6 +119,56 @@ describe('createCanvasPublisher', () => {})})+describe('src (the sender tag)', () => {+ // The reflector echoes a mutation back to its sender too — that echo is the ack that carries the+ // total order. `src` is how the sender recognizes it as its own rather than re-applying it.+ it('stamps every emitted mutation with the publisher tag', () => {+ const c = collect()+ const p = createCanvasPublisher(c.send, { src: 'cv-1' })+ p.publish([node('a')])+ p.publish([])+ expect(c.sent).toEqual([+ { op: 'upsert', node: node('a'), src: 'cv-1' },+ { op: 'remove', id: 'a', src: 'cv-1' }+ ])+ })+})++// A solo user must not pay for team sync: diffing stableStringifies every node twice (~1.4 ms at+// 100 nodes) and the `nodes` array changes at 60 Hz during a drag, all to cast into a void.+describe('shouldPublish (the solo gate)', () => {+ it('publishes nothing while no peer is attached', () => {+ const c = collect()+ const p = createCanvasPublisher(c.send, { shouldPublish: () => false })+ p.publish([node('a')])+ p.publish([node('a', 5)], { throttle: true })+ p.flush()+ vi.advanceTimersByTime(PUBLISH_INTERVAL_MS * 4)+ expect(c.sent).toEqual([])+ })++ it('does not even arm the drag throttle timer while solo', () => {+ const c = collect()+ const p = createCanvasPublisher(c.send, { shouldPublish: () => false })+ p.publish([node('a')], { throttle: true })+ expect(vi.getTimerCount()).toBe(0)+ })++ it('the baseline still tracks the canvas: the first edit after a peer joins diffs correctly', () => {+ const c = collect()+ let peers = false+ const p = createCanvasPublisher(c.send, { shouldPublish: () => peers })+ p.publish([node('a'), node('b')]) // solo: nothing sent…+ p.publish([node('a', 7), node('b')]) // …and edits keep updating the baseline+ expect(c.sent).toEqual([])++ peers = true // a teammate opens the canvas+ p.publish([node('a', 7), node('b', 3)])+ // ONLY the node that actually changed — no whole-canvas replay, no stale re-send of `a`.+ expect(c.sent).toEqual([{ op: 'upsert', node: node('b', 3) }])+ })+})+describe('ephemeral nodes are never published', () => {it('isEphemeralNodeId matches subagent cards (by id set) and loop cards (by prefix)', () => {const eph = new Set(['sub-123'])diff --git a/src/shared/canvas-publish.ts b/src/shared/canvas-publish.tsindex bf87bb02e..1ada3e30c 100644--- a/src/shared/canvas-publish.ts+++ b/src/shared/canvas-publish.ts@@ -15,9 +15,9 @@// `adopt` is what stops an infinite echo: when a mutation arrives FROM a peer, Canvas applies it and// adopts the result, so the React effect that fires for the resulting `nodes` change diffs to nothing.// (Same shape as the existing `loadingRef` suppression that keeps a programmatic project load from-// marking the project dirty.) The reflector already suppresses a client's OWN echo by ClientId; this-// guard is the other half — without it, A's mutation applied on B would be re-published by B to C-// (and back at A) forever.+// marking the project dirty.) Without it, A's mutation applied on B would be re-published by B to C+// (and back at A) forever. The other half of the anti-loop is canvas-order, which never *applies* a+// client's own echoed-back mutation in the first place.//// Pure + DOM-free (vitest runs in the node environment): only setTimeout, no React, no window.@@ -29,7 +29,9 @@ export const PUBLISH_INTERVAL_MS = 50export interface CanvasPublisher {/** Diff `next` against the last published snapshot and send the mutations.- * `throttle` (drag frames) coalesces to at most one send per PUBLISH_INTERVAL_MS. */+ * `throttle` (drag frames) coalesces to at most one send per PUBLISH_INTERVAL_MS.+ * With no peer attached (`shouldPublish` false) this DEGRADES TO adopt(): the snapshot becomes+ * the baseline and nothing is diffed or sent — a solo user pays nothing for team sync. */publish(next: CanvasNodeState[], opts?: { throttle?: boolean }): void/** Take `next` as the new baseline WITHOUT sending — the loop guard (a peer's mutation, or a* programmatic project load). The next diff against it is empty. */@@ -39,19 +41,37 @@ export interface CanvasPublisher {dispose(): void}+/**+ * @param send casts one mutation (already stamped with `src`).+ * @param opts.src this client's publisher tag, stamped onto every mutation it sends, so it can+ * recognize its own echo coming back (see canvas-order). Omitted in tests that+ * only care about the diff.+ * @param opts.shouldPublish+ * THE SOLO GATE. When it returns false — nobody else is attached — publish() takes the snapshot+ * as the baseline and returns: no stableStringify of every node (~1.4 ms at 100 nodes, and the+ * `nodes` array changes at 60 Hz during a drag), no IPC cast, no work in the main process. A solo+ * user must not pay for a feature they cannot use. The baseline still tracks the canvas, so the+ * instant a peer joins the very next edit diffs correctly against what is actually on screen —+ * there is no resync step and no missed mutation. Default: always publish.+ */export function createCanvasPublisher(send: (m: CanvasMutation) => void,- opts: { intervalMs?: number } = {}+ opts: { intervalMs?: number; src?: string; shouldPublish?: () => boolean } = {}): CanvasPublisher {const intervalMs = opts.intervalMs ?? PUBLISH_INTERVAL_MS+ const shouldPublish = opts.shouldPublish ?? (() => true)let last: CanvasNodeState[] = []let pending: CanvasNodeState[] | null = nulllet timer: ReturnType<typeof setTimeout> | null = nullconst emit = (next: CanvasNodeState[]): void => {+ if (!shouldPublish()) {+ last = next // solo: adopt as baseline, diff nothing, send nothing+ return+ }const mutations = diffToMutations(last, next)last = next- for (const m of mutations) send(m)+ for (const m of mutations) send(opts.src ? { ...m, src: opts.src } : m)}const onTimer = (): void => {@@ -64,6 +84,14 @@ export function createCanvasPublisher(return {publish(next, o) {+ if (!shouldPublish()) {+ // Solo: not even a throttle timer. Just keep the baseline current for the peer who joins.+ if (timer) clearTimeout(timer)+ timer = null+ pending = null+ last = next+ return+ }if (o?.throttle) {// Leading edge sends at once; further frames inside the window coalesce into one trailing send.if (timer) {diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 4b682abaf..a864bb71e 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -44,8 +44,9 @@ export const IPC = {agentControl: 'agent:control',agentControlResult: 'agent:control-result',/** Canvas sync: a client casts its local node mutations here; the core reflector- * (src/core/canvas-sync.ts) sends them back out on the SAME channel to every OTHER attached- * client. Args (both directions): [projectId: string, CanvasMutation]. */+ * (src/core/canvas-sync.ts) stamps each with the total order (`seq`) and sends it back out on the+ * SAME channel to EVERY attached client — the sender included, whose copy is its ack (see+ * src/shared/canvas-order.ts). Args (both directions): [projectId: string, CanvasMutation]. */canvasMut: 'canvas:mut',contextLinkSetLinks: 'context-link:set-links',contextLinkInfo: 'context-link:info',diff --git a/src/shared/types.ts b/src/shared/types.tsindex f8117d444..121652a71 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -151,10 +151,19 @@ export interface CanvasState {/*** A minimal change to a canvas node list: replace-or-append a node by id, or drop one by id.* Used for the client's optimistic edits and host-side diffing (see `applyMutation`/`diffToMutations`).+ *+ * `src` and `seq` exist ONLY on the team canvas-sync path (`canvas:mut`), and they are what makes+ * two people editing one node CONVERGE instead of splitting brain (see src/shared/canvas-order.ts):+ * - `src` is stamped by the sending client's publisher — a random per-Canvas tag, so a client can+ * recognize its OWN mutation coming back (the reflector echoes to everyone, sender included:+ * 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.+ * The relay's host↔client mirror (src/main/remote) uses the same vocabulary and simply omits both.*/export type CanvasMutation =- | { op: 'upsert'; node: CanvasNodeState }- | { op: 'remove'; id: string }+ | { op: 'upsert'; node: CanvasNodeState; src?: string; seq?: number }+ | { op: 'remove'; id: string; src?: string; seq?: number }/** Canvas pan/zoom state. */export interface Viewport {