Skip to content

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

feat(team): sync canvas EDGES — a peer's link is no longer deleted by your next save

enese9f145248703
diff --git a/docs/team-presence.md b/docs/team-presence.md
index 3c73d2406..fcf948da4 100644
--- a/docs/team-presence.md
+++ b/docs/team-presence.md
@@ -412,6 +412,45 @@ independently on each client from the already-broadcast `agent:status` stream; a
(`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.
+## Edge sync (bridges + ropes)
+
+Stage 3 addressed **nodes**. Edges — `bridges` (context links, which an agent actually reads
+through) and `ropes` (display-only "spawned by" lineage) — were left out, and that was the worst
+gap the stage shipped with, because they are **persisted in the same whole-file `workspace.save`**.
+An edge you drew never reached your teammate, and their next save — of a canvas that never had it —
+**deleted it**. Same in reverse. The advice was "draw links when you are alone on the canvas".
+
+They are in the vocabulary now, and everything around them is the node machinery unchanged:
+
+- **Vocabulary** — `CanvasMutation` gains `edge-upsert` / `edge-remove`, each carrying a
+ `kind: 'bridge' | 'rope'` (which persisted list to write) and the edge's three ids. **Only the ids
+ travel.** Colour, markers and handles are re-derived on each client from its own copy of the
+ source node — a rope's colour comes from the source agent, so sending it would ship one client's
+ palette to another.
+- **Ordering** — the same `CanvasOrder`, keyed by `mutationKey`: `n:<id>` for nodes, `e:<id>` for
+ edges, one key space with a prefix (a node id and an edge id are generated independently and could
+ collide). The `kind` is deliberately **not** in the key: one id is one edge, and a bridge and a
+ rope claiming the same id must be resolved to one thing rather than held as two. Rule 4 (the
+ causal delete) therefore covers an edge exactly as it covers a node.
+- **Publisher** — the snapshot became a `CanvasScene` (`{nodes, bridges, ropes}`), so one diff, one
+ throttle and one baseline cover both. The Canvas publish effect has the edge arrays in its deps:
+ drawing a link never touches `nodes`, so without that the edit would never be published. React
+ Flow rebuilds those arrays on a mere **selection** change too — that costs one diff yielding no
+ mutation (the diff compares id/source/target only), and the solo gate means a solo user does not
+ pay even that.
+- **Batch order is load-bearing.** A peer applies mutations one at a time, so `diffToMutations`
+ emits **node adds → edge adds → edge removes → node removes**: an edge naming a node that has not
+ arrived yet would draw into nothing, and an edge whose node dies in the same batch has to be
+ removed while it is still there.
+- **Ephemeral endpoints are filtered** (`publishableScene`). An edge naming a subagent / loop card
+ addresses a node the peer derives itself, with its own lifetime — it would be pruned there at a
+ moment we do not control and re-published back at us.
+- **Background projects** get `useProjects.applyEdgeMutation`, for the same reason nodes do: that
+ project's serialized edges are what our next whole-file save writes.
+
+What this does **not** change: an edge is still pruned locally when an endpoint disappears, so a
+peer's node delete can leave one drawn against nothing for a tick (see Known risks).
+
## UI
`PresenceLayer` renders inside React Flow's `<ViewportPortal>`, so cursors sit in flow
@@ -618,13 +657,11 @@ 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, 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.
+ - ~~**Edges are NOT in the mutation vocabulary**~~ — **closed; see
+ [Edge sync](#edge-sync-bridges--ropes) below.** This was the worst of the gaps and not a
+ cosmetic one: edges rode the whole-file `workspace.save` without being in the vocabulary, so an
+ edge you drew never reached your peer **and their next save — of a canvas that never had it —
+ DELETED it**.
- **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
@@ -665,6 +702,9 @@ concurrently with a peer's delete.
- **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).
+- **Edge array ORDER**, for the same reason and with even less consequence: two clients that draw
+ an edge at the same time each append the peer's to their own, so the two arrays hold the same
+ edges in different slots. Nothing lists edges in order; they are rendered as a set.
- **Anything outside the node/edge vocabulary** — project lifecycle (see item 5 above).
### A delete beats a concurrent edit — CAUSALLY, not by a tiebreak (rule 4)
@@ -937,9 +977,8 @@ logged in, named, and on the **same project**.
people dragging one node fight over it and the last-ordered frame decides. (A delete no longer
loses that race — see rule 4 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).
+- ~~**A peer's edge (context link / note link) is deleted by your next save.**~~ Closed — edges are
+ in the vocabulary now ([Edge sync](#edge-sync-bridges--ropes)).
- **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
@@ -968,6 +1007,8 @@ logged in, named, and on the **same project**.
- **The tombstone remains in-memory**, so it dies with the core process; across a core restart both
of the above degrade to "the node comes back". Bounded and honestly named, not a promise. See
[What Stage 3 changed](#what-stage-3-changed-relative-to-this-spec) (item 4).
-- **A peer's node delete can leave a dangling edge.** Edges are not in the mutation vocabulary — only
- nodes are — so a context-link / note-link edge whose endpoint a peer deleted stays drawn on your
- canvas until the next save/load drops it. Drawing an edge is likewise not synced.
+- **A peer's node delete can still leave a dangling edge for a moment.** The delete and the edge
+ removal are two mutations, and the peer that owns the edge prunes it on its next node change, so
+ an edge whose endpoint a peer deleted can be drawn against nothing for a tick. It is dropped by
+ the same prune that has always handled a locally-deleted endpoint — the durable half (your save
+ erasing their edge) is what closed.
diff --git a/src/core/canvas-sync.convergence.test.ts b/src/core/canvas-sync.convergence.test.ts
index 40ab29bf9..26a04a7c8 100644
--- a/src/core/canvas-sync.convergence.test.ts
+++ b/src/core/canvas-sync.convergence.test.ts
@@ -20,11 +20,16 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'
import { initCanvasSync, MUTATION_MAX_BYTES } from './canvas-sync'
-import { applyCanvasMutation, isCanvasMutation } from '../shared/canvas-mutations'
+import {
+ applyCanvasMutation,
+ applyEdgeMutation,
+ isCanvasMutation,
+ type CanvasScene
+} from '../shared/canvas-mutations'
import { createCanvasOrder, createReconnectWatch, PENDING_TTL_MS } from '../shared/canvas-order'
-import { createCanvasPublisher, publishableStates } from '../shared/canvas-publish'
+import { createCanvasPublisher, publishableScene } from '../shared/canvas-publish'
import { IPC } from '../shared/ipc'
-import type { CanvasMutation, CanvasNodeState } from '../shared/types'
+import type { BridgeLink, CanvasMutation, CanvasNodeState } from '../shared/types'
const node = (id: string, x: number, title = 't', color = '#fff'): CanvasNodeState =>
({
@@ -139,6 +144,10 @@ class Bus {
* mutation ask the ordering state whether to apply it, then adopt (never re-publish) the result. */
class Client {
states: CanvasNodeState[] = []
+ /** The two PERSISTED edge lists, alongside the nodes — they ride the same whole-file save, so
+ * they are part of what has to converge (see the edge tests at the bottom). */
+ bridges: BridgeLink[] = []
+ ropes: BridgeLink[] = []
/** Ephemeral cards (subagent / loop) this client renders — derived locally, never published. */
ephemeral = new Set<string>()
/** Mutations APPLIED from the wire (an own echo, or one the order supersedes, is not applied). */
@@ -185,12 +194,17 @@ class Client {
if (!this.order.accept(m)) return
this.applied++
this.states = applyCanvasMutation(this.states, m)
+ this.bridges = applyEdgeMutation(this.bridges, 'bridge', m)
+ this.ropes = applyEdgeMutation(this.ropes, 'rope', m)
this.pub.adopt(this.publishable()) // loop guard — never re-publish someone else's change
})
}
- private publishable(): CanvasNodeState[] {
- return publishableStates(this.states, this.ephemeral)
+ private publishable(): CanvasScene {
+ return publishableScene(
+ { nodes: this.states, bridges: this.bridges, ropes: this.ropes },
+ this.ephemeral
+ )
}
/** A local edit: take the new node list, then publish the diff (what the Canvas effect does). */
@@ -199,6 +213,14 @@ class Client {
this.pub.publish(this.publishable())
}
+ /** A local EDGE edit — drawing or deleting a context link / rope. Same effect, same publisher:
+ * the Canvas publish effect has the edge arrays in its deps for exactly this. */
+ editEdges(next: { bridges?: BridgeLink[]; ropes?: BridgeLink[] }): void {
+ if (next.bridges) this.bridges = next.bridges
+ if (next.ropes) this.ropes = next.ropes
+ this.pub.publish(this.publishable())
+ }
+
/** Our presence clientId resolved (or changed). What Canvas's presence subscription does: the
* ordering state is forgotten ONLY when a NEW clientId replaces an OLD one — a fresh connection
* to a core whose `seq` may have restarted at 0. The first `null → myId` hello is not that. */
@@ -214,7 +236,7 @@ class Client {
/** The node set that would be written by this client's workspace.save (ephemeral cards excluded,
* as flowToNodeStates already excludes them). */
- persisted(): CanvasNodeState[] {
+ persisted(): CanvasScene {
return this.publishable()
}
@@ -238,7 +260,7 @@ class Client {
* 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))
+ [...c.persisted().nodes].sort((x, y) => x.id.localeCompare(y.id))
let bus: Bus
let a: Client
@@ -328,6 +350,109 @@ describe('canvas convergence (async bus)', () => {
expect(a.persisted()).toEqual(b.persisted())
})
+ // ── Edges ──────────────────────────────────────────────────────────────────────────────────────
+ // The sharpest data-loss shape this stage had left open, and it was WORSE than a cosmetic gap:
+ // edges were not in the mutation vocabulary but they ARE in the whole-file save, so an edge you
+ // drew never reached your teammate — and their next save, of a canvas that never had it, deleted
+ // it for everyone. (Same in reverse.)
+ describe('edges converge like nodes', () => {
+ it("a link A draws reaches B — and B's save no longer deletes it", () => {
+ a.edit([node('n1', 0), node('n2', 0)])
+ bus.settle()
+
+ a.editEdges({ bridges: [{ id: 'b1', source: 'n1', target: 'n2' }] })
+ bus.settle()
+
+ expect(b.bridges).toEqual([{ id: 'b1', source: 'n1', target: 'n2' }])
+ // THE assertion: B's whole-file save now writes A's edge, instead of erasing it.
+ expect(b.persisted().bridges).toEqual(a.persisted().bridges)
+
+ // …and an unrelated edit by B does not lose it either (the publisher's baseline carries it).
+ b.edit([...b.states, node('n3', 0)])
+ bus.settle()
+ expect(b.persisted().bridges).toEqual(a.persisted().bridges)
+ })
+
+ it('a deleted link stays deleted on both', () => {
+ a.edit([node('n1', 0), node('n2', 0)])
+ a.editEdges({ bridges: [{ id: 'b1', source: 'n1', target: 'n2' }] })
+ bus.settle()
+
+ b.editEdges({ bridges: [] })
+ bus.settle()
+
+ expect(a.bridges).toEqual([])
+ expect(a.persisted()).toEqual(b.persisted())
+ })
+
+ it('bridges and ropes are two lists, and a mutation only touches its own kind', () => {
+ a.edit([node('n1', 0), node('n2', 0)])
+ a.editEdges({ ropes: [{ id: 'ctrl-1', source: 'n1', target: 'n2' }] })
+ bus.settle()
+
+ expect(b.ropes).toEqual([{ id: 'ctrl-1', source: 'n1', target: 'n2' }])
+ expect(b.bridges).toEqual([])
+ })
+
+ it('a peer edge is applied once and re-published NEVER (the adopt loop guard covers edges)', () => {
+ a.edit([node('n1', 0), node('n2', 0)])
+ bus.settle()
+ const before = bus.castCount
+
+ a.editEdges({ bridges: [{ id: 'b1', source: 'n1', target: 'n2' }] })
+ bus.settle()
+
+ expect(bus.castCount - before).toBe(1) // one local edit, one cast, no counter-cast from B
+ })
+
+ // Both edges survive on both clients. Compared as a SET, not as an array: each client appended
+ // the peer's edge to its own, so the two arrays hold the same edges in different SLOTS — the
+ // same array-order caveat docs/team-presence.md already names for nodes, and it matters even
+ // less here (edges are rendered as a set; nothing lists them in order).
+ it('two clients drawing edges at the same time keep BOTH', () => {
+ a.edit([node('n1', 0), node('n2', 0), node('n3', 0)])
+ bus.settle()
+
+ a.editEdges({ bridges: [{ id: 'b1', source: 'n1', target: 'n2' }] })
+ b.editEdges({ bridges: [{ id: 'b2', source: 'n2', target: 'n3' }] })
+ bus.settle()
+
+ const byId = (es: BridgeLink[]) => [...es].sort((x, y) => x.id.localeCompare(y.id))
+ expect(byId(a.persisted().bridges)).toEqual(byId(b.persisted().bridges))
+ expect(a.bridges.map((e) => e.id).sort()).toEqual(['b1', 'b2'])
+ })
+
+ // Rule 4 is keyed on `mutationKey`, so it covers an edge exactly as it covers a node: a client
+ // re-pointing an edge in ignorance of its delete must not bring it back.
+ it('a stale edge frame cannot resurrect a deleted edge', () => {
+ a.edit([node('n1', 0), node('n2', 0)])
+ a.editEdges({ bridges: [{ id: 'b1', source: 'n1', target: 'n2' }] })
+ bus.settle()
+
+ b.editEdges({ bridges: [{ id: 'b1', source: 'n1', target: 'n1' }] }) // B re-points it…
+ a.editEdges({ bridges: [] }) // …while A deletes it
+ bus.settle()
+
+ expect(a.bridges).toEqual([])
+ expect(b.bridges).toEqual([])
+ })
+
+ // An edge whose endpoint is an ephemeral card (a subagent / loop node) must not go on the wire
+ // for the same reason the card itself must not: the peer derives that node independently.
+ it('an edge to an ephemeral card is never published', () => {
+ a.ephemeral.add('sub-1')
+ a.edit([node('n1', 0), node('sub-1', 0)])
+ bus.settle()
+ const before = bus.castCount
+
+ a.editEdges({ bridges: [{ id: 'b1', source: 'n1', target: 'sub-1' }] })
+ bus.settle()
+
+ expect(bus.castCount - before).toBe(0)
+ expect(b.bridges).toEqual([])
+ })
+ })
+
// A stale frame from a client whose socket was stalled must not resurrect the node either — this
// is the "disconnected peer erases / revives what everyone else settled" hazard, and it is the one
// a TIME-based delete-wins window would get wrong (the frame arrives long after any window).
@@ -645,7 +770,7 @@ describe('canvas convergence (async bus)', () => {
// 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.
- expect(a.persisted().map((n) => n.id)).toEqual(['n2'])
+ expect(a.persisted().nodes.map((n) => n.id)).toEqual(['n2'])
expect(a.persisted()).toEqual(b.persisted())
// And A's subsequent edit does not reintroduce it either.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index bfcd037f5..c683c761d 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -627,11 +627,16 @@ import { focusTargetId } from '../lib/focusTarget'
import {
createCanvasPublisher,
isEphemeralNodeId,
- publishableStates,
+ publishableScene,
type CanvasPublisher
} from '@shared/canvas-publish'
import { createCanvasOrder, createReconnectWatch, type CanvasOrder } from '@shared/canvas-order'
-import { createMutationGuard } from '@shared/canvas-mutations'
+import {
+ applyEdgeMutation,
+ createMutationGuard,
+ isEdgeMutation,
+ type CanvasScene
+} from '@shared/canvas-mutations'
import { chordHeld, isHoldChord, isModifierEventKey, matchesShortcut } from '@shared/shortcut'
// The dispatch below is the CONSUMER of the confirm-gated set. Before this import the set named
@@ -1035,6 +1040,10 @@ const ropeEdge = (id: string, source: string, target: string): Edge => ({
/** The one edge renderer — every family routes between nearest borders (see FloatingEdge). */
const edgeTypes = { floating: FloatingEdge }
+/** A React Flow edge reduced to what is PERSISTED (and what goes on the wire). The decoration —
+ * colour, markers, the waiting look — is re-derived on every client at render time
+ * (`displayEdges` / `ropeVisual`), so it never travels. */
+const toBridgeLink = (e: Edge): BridgeLink => ({ id: e.id, source: e.source, target: e.target })
const minimapNodeColor = (n: Node): string =>
(n.data as { color?: string })?.color ?? '#0a84ff'
@@ -3113,11 +3122,35 @@ export function Canvas() {
// once per drag FRAME — so handing over an array meant a solo user paid the whole cost of a
// feature the publisher's own solo gate then declined to use. What must NOT be deferred is the
// ephemeral-id set: it is read from a live store, so it is captured here, as of this call.
- const publishableLater = useCallback((flow: CanvasNode[]): (() => CanvasNodeState[]) => {
- const ephIds = new Set(Object.keys(useAgentNodes.getState().byId))
- const retainInitial = sessionForProject(nodesProjectIdRef.current ?? '').source !== 'relay'
- return () => publishableStates(flowToNodeStates(flow, retainInitial), ephIds)
- }, [])
+ //
+ // The two PERSISTED edge lists ride along, because they ride the same whole-file save and were
+ // the one thing canvas sync did not carry: an edge you drew never reached your teammate, and
+ // their next save — of a canvas that never had it — DELETED it. The edge ARRAYS are captured
+ // NOW, as of this call, like the ephemeral ids: the publisher may resolve this thunk much later
+ // (an `adopt` baseline stays lazy until the NEXT publish), and by then the refs have moved on.
+ // Reading them late made a link drawn right after a peer op (or a project load) diff against
+ // itself — nothing cast, and the teammate's next save deleted it (port of feat/team-sync-gaps,
+ // fixed). Capturing a reference is free and React state arrays are never mutated in place, so
+ // only the `.map` is deferred and the solo gate still skips the whole cost. `edges` is for a
+ // caller that already holds the arrays (the publish effect's own deps); the rest read the refs.
+ const publishableLater = useCallback(
+ (flow: CanvasNode[], edges?: { bridges: Edge[]; ropes: Edge[] }): (() => CanvasScene) => {
+ const ephIds = new Set(Object.keys(useAgentNodes.getState().byId))
+ const retainInitial = sessionForProject(nodesProjectIdRef.current ?? '').source !== 'relay'
+ const bridges = edges?.bridges ?? linkEdgesRef.current
+ const ropes = edges?.ropes ?? controlEdgesRef.current
+ return () =>
+ publishableScene(
+ {
+ nodes: flowToNodeStates(flow, retainInitial),
+ bridges: bridges.map(toBridgeLink),
+ ropes: ropes.map(toBridgeLink)
+ },
+ ephIds
+ )
+ },
+ []
+ )
// ---- persistence helpers ----
const commitActiveToStore = useCallback(() => {
@@ -3133,8 +3166,8 @@ export function Canvas() {
id,
flowToNodeStates(nodesRef.current, sessionForProject(nodesProjectIdRef.current ?? '').source !== 'relay'),
viewportRef.current,
- linkEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target })),
- controlEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target }))
+ linkEdgesRef.current.map(toBridgeLink),
+ controlEdgesRef.current.map(toBridgeLink)
)
}, [])
@@ -3700,13 +3733,18 @@ export function Canvas() {
useEffect(() => {
const pub = publisherRef.current
if (!pub) return
- const states = publishableLater(nodes)
+ const states = publishableLater(nodes, { bridges: linkEdges, ropes: controlEdges })
if (loadingRef.current) {
pub.adopt(states)
return
}
pub.publish(states, { throttle: draggingRef.current })
- }, [nodes, publishableLater])
+ // Edges are in the deps for the same reason the publisher diffs them: drawing (or deleting) a
+ // context link / rope never touches `nodes`, so without this the edit would never be published
+ // — and the peer's next whole-file save would delete it. React Flow also re-creates these
+ // arrays on a mere SELECTION change; that costs one diff which yields no mutation (the diff
+ // compares id/source/target only), and a solo user does not even pay that (the solo gate).
+ }, [nodes, linkEdges, controlEdges, publishableLater])
// 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.
@@ -3737,6 +3775,47 @@ export function Canvas() {
return activeSession.api.canvas.onMutation((projectId, mutation) => {
hasPeersRef.current = true // proof of a peer, whatever the presence table says
if (!orderRef.current?.accept(mutation)) return
+ // ---- edges (context links + "spawned by" ropes) ----
+ // They live outside React Flow's `nodes` array, in their own state, so they take their own
+ // apply path — but everything around it is the node path's contract, unchanged: the ordering
+ // gate above has already decided this mutation wins, `adopt` is still the loop guard, and a
+ // background project is still patched in the store so our next save cannot delete the edge.
+ if (isEdgeMutation(mutation)) {
+ if (projectId !== useProjects.getState().activeProjectId) {
+ if (useProjects.getState().applyEdgeMutation(projectId, mutation)) markDirty()
+ return
+ }
+ // Rebuilt EDGE-BY-EDGE, reusing the existing object whenever its three ids are unchanged —
+ // the same discipline `applyMutationToFlow` follows for nodes, and for the same reason: a
+ // freshly built object loses `selected`, so re-creating the whole list would wipe the
+ // user's edge selection every time a teammate touched any OTHER edge.
+ const keep = <T extends Edge>(prev: T[], link: BridgeLink): T | undefined => {
+ const e = prev.find((x) => x.id === link.id)
+ return e && e.source === link.source && e.target === link.target ? e : undefined
+ }
+ if (mutation.kind === 'bridge') {
+ const next = applyEdgeMutation(linkEdgesRef.current.map(toBridgeLink), 'bridge', mutation)
+ // No `type`: a bridge carries none in state — `displayEdges` makes every link `floating`.
+ const edges = next.map(
+ (b) => keep(linkEdgesRef.current, b) ?? { id: b.id, source: b.source, target: b.target }
+ )
+ linkEdgesRef.current = edges
+ setLinkEdges(edges)
+ publisherRef.current?.adopt(publishableLater(nodesRef.current))
+ } else {
+ const next = applyEdgeMutation(controlEdgesRef.current.map(toBridgeLink), 'rope', mutation)
+ // Nothing but the three ids travels: a rope's colour and its waiting look are derived at
+ // render time from this client's own nodes (`displayEdges` / `ropeVisual`).
+ const edges = next.map(
+ (r) => keep(controlEdgesRef.current, r) ?? ropeEdge(r.id, r.source, r.target)
+ )
+ controlEdgesRef.current = edges
+ setControlEdges(edges)
+ publisherRef.current?.adopt(publishableLater(nodesRef.current))
+ }
+ markDirty()
+ return
+ }
if (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.
@@ -3779,7 +3858,7 @@ export function Canvas() {
setNodes(flow)
markDirty()
})
- }, [activeSession.api, setNodes, markDirty, publishableLater])
+ }, [activeSession.api, setNodes, setLinkEdges, setControlEdges, markDirty, publishableLater])
// Record an undo snapshot when the canvas settles (debounced; skips drag frames/loads).
useEffect(() => {
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 1b02d773b..4d411c7ad 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -22,6 +22,7 @@ import {
pruneLayoutViewports,
type CanvasLayout
} from '@shared/canvas-layout'
+import { applyEdgeMutation } from '@shared/canvas-mutations'
import { applyCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'
import { markWorkspaceDirty } from './workspaceDirty'
import { folderName } from '../lib/projectOpen'
@@ -154,6 +155,15 @@ interface ProjectsState {
* they deleted on the very next save — the data-loss shape canvas sync exists to fix.
*/
applyNodeMutation(projectId: string, mutation: CanvasMutation): boolean
+ /**
+ * The EDGE counterpart, for the same background-project path. Edges (`bridges` = context links,
+ * `ropes` = display-only lineage) ride the same whole-file save as the nodes, so dropping a
+ * peer's edge mutation for a project we are not looking at has the identical failure mode: our
+ * next save writes a project without their edge, deleting it for everyone.
+ *
+ * Returns false if the project is unknown here (nothing applied).
+ */
+ applyEdgeMutation(projectId: string, mutation: CanvasMutation): boolean
/** Renames a node within a project (source of truth for inactive projects). */
renameNode(projectId: string, nodeId: string, title: string): void
/** Recolors a node within a project. */
@@ -591,6 +601,26 @@ export const useProjects = create<ProjectsState>((set, get) => ({
return true
},
+ applyEdgeMutation(projectId, mutation) {
+ if (!get().projects.some((p) => p.id === projectId)) return false
+ set((s) => ({
+ projects: s.projects.map((p) => {
+ if (p.id !== projectId) return p
+ const bridges = applyEdgeMutation(p.bridges ?? [], 'bridge', mutation)
+ const ropes = applyEdgeMutation(p.ropes ?? [], 'rope', mutation)
+ // `applyEdgeMutation` returns the SAME array when the mutation is not about that list, so
+ // the untouched kind keeps its identity — and a project whose stored list was `undefined`
+ // stays `undefined` rather than being materialized as an empty array on every peer edge
+ // (which would dirty the file with `"bridges": []` on projects that have never had one).
+ const nextBridges = bridges === (p.bridges ?? []) ? p.bridges : bridges
+ const nextRopes = ropes === (p.ropes ?? []) ? p.ropes : ropes
+ if (nextBridges === p.bridges && nextRopes === p.ropes) return p
+ return { ...p, bridges: nextBridges, ropes: nextRopes }
+ })
+ }))
+ return true
+ },
+
renameNode(projectId, nodeId, title) {
set((s) => ({
projects: mapProjectNodes(s.projects, projectId, (nodes) =>
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index c3e566d24..e0a4b2242 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -2109,6 +2109,10 @@ export function flowToNodeStates(nodes: CanvasNode[], retainInitialCommand = tru
* Flow re-measure from the incoming `style`, which is what the peer sent.
*/
export function applyMutationToFlow(nodes: CanvasNode[], m: CanvasMutation): CanvasNode[] {
+ // An edge mutation addresses neither of these nodes — Canvas routes those to the edge state.
+ // Returned by REFERENCE so the caller's `next === prev` short-circuit still fires (same contract
+ // as `applyCanvasMutation`), rather than trusting every call site to have pre-filtered.
+ if (m.op === 'edge-upsert' || m.op === 'edge-remove') return nodes
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)
diff --git a/src/shared/canvas-mutations.test.ts b/src/shared/canvas-mutations.test.ts
index 295bd881e..490ee70fa 100644
--- a/src/shared/canvas-mutations.test.ts
+++ b/src/shared/canvas-mutations.test.ts
@@ -1,12 +1,13 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import {
applyCanvasMutation,
+ applyEdgeMutation,
createMutationGuard,
diffToMutations,
isCanvasMutation,
MUTATION_MAX_BYTES
} from './canvas-mutations'
-import type { CanvasNodeState } from './types'
+import type { BridgeLink, CanvasNodeState } from './types'
const n = (id: string, x = 0, title = 't'): CanvasNodeState =>
({
@@ -149,3 +150,137 @@ describe('createMutationGuard', () => {
expect(calls()).toBe(0) // both refusals are remembered, neither is re-serialized
})
})
+
+// ── Edges ────────────────────────────────────────────────────────────────────────────────────────
+// Edges (`bridges` = context links, `ropes` = display-only lineage) ride the same whole-file save as
+// the nodes but were NOT in the mutation vocabulary. So an edge you drew never reached your
+// teammate — and their next save, of a canvas that never had it, DELETED it. Syncing them is what
+// makes the file both clients converge on the file they both agree with.
+
+const e = (id: string, source = 'a', target = 'b'): BridgeLink => ({ id, source, target })
+
+describe('applyEdgeMutation', () => {
+ it('appends, replaces and removes by id without mutating the input', () => {
+ const list = [e('x')]
+ expect(
+ applyEdgeMutation(list, 'bridge', { op: 'edge-upsert', kind: 'bridge', edge: e('y') })
+ ).toHaveLength(2)
+ expect(
+ applyEdgeMutation(list, 'bridge', {
+ op: 'edge-upsert',
+ kind: 'bridge',
+ edge: e('x', 'a', 'z')
+ })[0].target
+ ).toBe('z')
+ expect(
+ applyEdgeMutation(list, 'bridge', { op: 'edge-remove', kind: 'bridge', id: 'x' })
+ ).toEqual([])
+ expect(list).toEqual([e('x')]) // untouched
+ })
+
+ it('leaves the OTHER kind alone, by reference (a rope mutation is not a bridge edit)', () => {
+ const list = [e('x')]
+ expect(applyEdgeMutation(list, 'bridge', { op: 'edge-upsert', kind: 'rope', edge: e('r') })).toBe(
+ list
+ )
+ expect(applyEdgeMutation(list, 'bridge', { op: 'remove', id: 'x' })).toBe(list)
+ })
+
+ it('keeps identity when a remove names an edge we do not have', () => {
+ const list = [e('x')]
+ expect(applyEdgeMutation(list, 'bridge', { op: 'edge-remove', kind: 'bridge', id: 'q' })).toBe(
+ list
+ )
+ })
+
+ it('carries only the three ids — decoration is re-derived per client, never sent', () => {
+ const fat = { ...e('x'), style: { stroke: 'red' } } as unknown as BridgeLink
+ const [out] = applyEdgeMutation([], 'bridge', { op: 'edge-upsert', kind: 'bridge', edge: fat })
+ expect(Object.keys(out).sort()).toEqual(['id', 'source', 'target'])
+ })
+})
+
+describe('applyCanvasMutation with an edge mutation', () => {
+ it('is a no-op that keeps the array identity (the caller short-circuit still fires)', () => {
+ const nodes = [n('1')]
+ expect(applyCanvasMutation(nodes, { op: 'edge-remove', kind: 'bridge', id: 'x' })).toBe(nodes)
+ expect(applyCanvasMutation(nodes, { op: 'edge-upsert', kind: 'rope', edge: e('x') })).toBe(nodes)
+ })
+})
+
+describe('isCanvasMutation — edge ops', () => {
+ it('accepts well-formed edge mutations', () => {
+ expect(isCanvasMutation({ op: 'edge-upsert', kind: 'bridge', edge: e('x') })).toBe(true)
+ expect(isCanvasMutation({ op: 'edge-remove', kind: 'rope', id: 'x' })).toBe(true)
+ })
+
+ it('rejects an unknown kind — the kind picks which persisted list is written', () => {
+ expect(isCanvasMutation({ op: 'edge-upsert', kind: 'bridges', edge: e('x') })).toBe(false)
+ expect(isCanvasMutation({ op: 'edge-remove', id: 'x' })).toBe(false)
+ })
+
+ it('rejects a malformed or over-long endpoint — an edge id is an ADDRESS, never truncated', () => {
+ expect(isCanvasMutation({ op: 'edge-upsert', kind: 'bridge', edge: { id: 'x', source: 'a' } })).toBe(
+ false
+ )
+ expect(isCanvasMutation({ op: 'edge-upsert', kind: 'bridge', edge: e('x', '', 'b') })).toBe(false)
+ expect(
+ isCanvasMutation({ op: 'edge-upsert', kind: 'bridge', edge: e('x', 'a'.repeat(129), 'b') })
+ ).toBe(false)
+ expect(isCanvasMutation({ op: 'edge-upsert', kind: 'bridge' })).toBe(false)
+ })
+})
+
+describe('diffToMutations — scenes', () => {
+ const scene = (
+ nodes: CanvasNodeState[],
+ bridges: BridgeLink[] = [],
+ ropes: BridgeLink[] = []
+ ) => ({ nodes, bridges, ropes })
+
+ it('reads a bare node array as a scene with no edges (every pre-edge caller is unchanged)', () => {
+ expect(diffToMutations([n('1')], [n('1')])).toEqual([])
+ expect(diffToMutations([], [n('1')])).toEqual([{ op: 'upsert', node: n('1') }])
+ })
+
+ it('emits an edge-upsert for a drawn edge and an edge-remove for a deleted one', () => {
+ expect(diffToMutations(scene([]), scene([], [e('x')]))).toEqual([
+ { op: 'edge-upsert', kind: 'bridge', edge: e('x') }
+ ])
+ expect(diffToMutations(scene([], [e('x')]), scene([]))).toEqual([
+ { op: 'edge-remove', kind: 'bridge', id: 'x' }
+ ])
+ })
+
+ it('tags each list with its own kind', () => {
+ expect(diffToMutations(scene([]), scene([], [], [e('r')]))).toEqual([
+ { op: 'edge-upsert', kind: 'rope', edge: e('r') }
+ ])
+ })
+
+ it('emits nothing when only the decoration would have differed (three ids are the value)', () => {
+ const before = scene([], [e('x')])
+ const after = scene([], [{ ...e('x') }])
+ expect(diffToMutations(before, after)).toEqual([])
+ })
+
+ it('re-emits an edge whose endpoint was re-pointed', () => {
+ expect(diffToMutations(scene([], [e('x', 'a', 'b')]), scene([], [e('x', 'a', 'c')]))).toEqual([
+ { op: 'edge-upsert', kind: 'bridge', edge: e('x', 'a', 'c') }
+ ])
+ })
+
+ // A peer applies these ONE AT A TIME, so the batch order decides whether an edge ever lands: an
+ // edge-upsert naming a node that has not arrived yet draws into nothing, and an edge-remove for an
+ // edge whose node dies in the same batch has to land while the edge is still there.
+ it('orders the batch: node adds → edge adds → edge removes → node removes', () => {
+ const before = scene([n('old')], [e('gone', 'old', 'old')])
+ const after = scene([n('new')], [e('fresh', 'new', 'new')])
+ expect(diffToMutations(before, after).map((m) => m.op)).toEqual([
+ 'upsert',
+ 'edge-upsert',
+ 'edge-remove',
+ 'remove'
+ ])
+ })
+})
diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.ts
index e1c53f028..cdc815d48 100644
--- a/src/shared/canvas-mutations.ts
+++ b/src/shared/canvas-mutations.ts
@@ -4,7 +4,39 @@
import { carryLocalNodeExec, sanitizeInboundNode } from './node-exec'
import { REF_MAX_LEN } from './presence'
-import type { CanvasMutation, CanvasNodeState } from './types'
+import type { BridgeLink, CanvasEdgeKind, CanvasMutation, CanvasNodeState } from './types'
+
+/**
+ * A canvas as the publisher sees it: the nodes React Flow manages, plus the two PERSISTED edge
+ * lists (`bridges` = context links, `ropes` = display-only "spawned by" lineage).
+ *
+ * The edges are in here for one reason, and it is a data-loss reason rather than a cosmetic one.
+ * They ride the same whole-file `workspace.save` as the nodes but were NOT in the mutation
+ * vocabulary, so an edge you drew never reached your teammate — and their next save, of a canvas
+ * that never had it, DELETED it. (Same in reverse.) Syncing them is what makes the file the two
+ * clients converge on the file they both agree with.
+ */
+export interface CanvasScene {
+ nodes: CanvasNodeState[]
+ bridges: BridgeLink[]
+ ropes: BridgeLink[]
+}
+
+/** A bare node array read as a scene with no edges — the shape every pre-edge caller passes. */
+export function asScene(s: CanvasScene | CanvasNodeState[]): CanvasScene {
+ return Array.isArray(s) ? { nodes: s, bridges: [], ropes: [] } : s
+}
+
+/** Does this mutation address an edge (rather than a node)? */
+export function isEdgeMutation(
+ m: CanvasMutation
+): m is Extract<CanvasMutation, { op: 'edge-upsert' | 'edge-remove' }> {
+ return m.op === 'edge-upsert' || m.op === 'edge-remove'
+}
+
+function isEdgeKind(value: unknown): value is CanvasEdgeKind {
+ return value === 'bridge' || value === 'rope'
+}
/**
* Ceiling on one mutation's serialized size. A node carries free text (a sticky's body, an
@@ -37,8 +69,18 @@ export function isRefId(value: unknown): value is string {
*/
export function isCanvasMutation(value: unknown): value is CanvasMutation {
if (!value || typeof value !== 'object') return false
- const m = value as { op?: unknown; id?: unknown; node?: unknown }
+ const m = value as { op?: unknown; id?: unknown; node?: unknown; kind?: unknown; edge?: unknown }
if (m.op === 'remove') return isRefId(m.id)
+ if (m.op === 'edge-remove') return isEdgeKind(m.kind) && isRefId(m.id)
+ if (m.op === 'edge-upsert') {
+ if (!isEdgeKind(m.kind)) return false
+ const edge = m.edge as { id?: unknown; source?: unknown; target?: unknown } | undefined
+ if (!edge || typeof edge !== 'object') return false
+ // All three ids are ADDRESSES — an edge with a truncated endpoint would attach to the wrong
+ // node on every peer — so they are rejected rather than capped, exactly like a node id.
+ if (!isRefId(edge.id) || !isRefId(edge.source) || !isRefId(edge.target)) return false
+ return withinSizeLimit(m)
+ }
if (m.op !== 'upsert') return false
const node = m.node as { id?: unknown; position?: { x?: unknown; y?: unknown } } | undefined
if (!node || typeof node !== 'object') return false
@@ -120,7 +162,8 @@ function sameNodeValue(a: CanvasNodeState, b: CanvasNodeState): boolean {
export function createMutationGuard(): (m: CanvasMutation) => boolean {
const refused = new Map<string, CanvasNodeState>()
return (m) => {
- // A `remove` is a couple of dozen bytes: nothing to amortize, and nothing that can grow.
+ // A `remove` and both edge ops are a couple of dozen bytes (ids only): nothing to amortize,
+ // and nothing that can grow. Only a node `upsert` carries free text.
if (!m || typeof m !== 'object' || (m as { op?: unknown }).op !== 'upsert')
return isCanvasMutation(m)
const node = (m as { node?: CanvasNodeState }).node
@@ -151,6 +194,11 @@ export function applyCanvasMutation(
states: CanvasNodeState[],
m: CanvasMutation
): CanvasNodeState[] {
+ // An edge mutation addresses neither of these nodes. Returned UNCHANGED (by reference, so a
+ // caller's `next === prev` short-circuit still fires) rather than trusted to be pre-filtered:
+ // every caller here is applying something that came off the wire, and a silent no-op is the only
+ // safe reading of "this list is not what that mutation is about".
+ if (isEdgeMutation(m)) return states
if (m.op === 'remove') return states.filter((n) => n.id !== m.id)
const node = sanitizeInboundNode(m.node)
const idx = states.findIndex((n) => n.id === node.id)
@@ -162,6 +210,36 @@ export function applyCanvasMutation(
return next
}
+/**
+ * Apply one EDGE mutation to one of a project's edge lists, returning a NEW array (the input is
+ * never mutated). A mutation for the other kind — or for a node — leaves the list untouched, by
+ * reference, so the caller's `next === prev` check still short-circuits.
+ *
+ * There is nothing to sanitize here the way `sanitizeInboundNode` sanitizes a node: an edge is
+ * three ids and carries no exec-enabling field, and `isCanvasMutation` has already bounded all
+ * three. What it CAN carry is a dangling endpoint (the peer deleted that node a moment ago) —
+ * deliberately not filtered here, because this function does not know the node list. Canvas's
+ * existing prune effects drop a dangling edge on the next node change, which is the same treatment
+ * a locally-drawn edge gets.
+ */
+export function applyEdgeMutation(
+ edges: BridgeLink[],
+ kind: CanvasEdgeKind,
+ m: CanvasMutation
+): BridgeLink[] {
+ if (!isEdgeMutation(m) || m.kind !== kind) return edges
+ if (m.op === 'edge-remove') {
+ const next = edges.filter((e) => e.id !== m.id)
+ return next.length === edges.length ? edges : next
+ }
+ const edge: BridgeLink = { id: m.edge.id, source: m.edge.source, target: m.edge.target }
+ const idx = edges.findIndex((e) => e.id === edge.id)
+ if (idx === -1) return [...edges, edge]
+ const next = edges.slice()
+ next[idx] = edge
+ return next
+}
+
/** Stable JSON stringify (keys sorted) so deep-equality is order-independent. */
function stableStringify(value: unknown): string {
return JSON.stringify(value, (_key, val) => {
@@ -176,29 +254,70 @@ function stableStringify(value: unknown): string {
})
}
+/** The edge half of `diffToMutations`, for one kind. Same shape: changed/added → upsert (in
+ * next-array order), dropped → remove (in prev-array order). An edge is three short ids, so the
+ * compare is a plain field compare rather than a stringify. */
+function diffEdges(
+ prev: BridgeLink[],
+ next: BridgeLink[],
+ kind: CanvasEdgeKind,
+ upserts: CanvasMutation[],
+ removes: CanvasMutation[]
+): void {
+ const prevById = new Map(prev.map((e) => [e.id, e]))
+ const nextIds = new Set(next.map((e) => e.id))
+ for (const edge of next) {
+ const before = prevById.get(edge.id)
+ if (!before || before.source !== edge.source || before.target !== edge.target) {
+ upserts.push({ op: 'edge-upsert', kind, edge })
+ }
+ }
+ for (const edge of prev) {
+ if (!nextIds.has(edge.id)) removes.push({ op: 'edge-remove', kind, id: edge.id })
+ }
+}
+
/**
- * Diff two node snapshots into the minimal mutation list (deterministic): an `upsert` for every
- * node that was added or changed (deep-equal via stable stringify), and a `remove` for every node
- * that was dropped. Never throws on normal input.
+ * Diff two canvas snapshots into the minimal mutation list (deterministic): an `upsert` for every
+ * node that was added or changed (deep-equal via stable stringify), a `remove` for every node that
+ * was dropped, and the same for both edge lists. Never throws on normal input.
+ *
+ * A bare node array is accepted as a scene with no edges, so every caller that predates edge sync
+ * keeps its exact behaviour.
+ *
+ * THE ORDER OF THE BATCH IS LOAD-BEARING: additions before removals, and within each half nodes
+ * before edges. A peer applies these one at a time, so an `edge-upsert` naming a node that has not
+ * arrived yet would draw an edge into nothing (React Flow drops it and warns) — and an
+ * `edge-remove` for an edge whose node is removed in the SAME batch has to land while the edge is
+ * still there. Adds: nodes, then edges. Removes: edges, then nodes.
*/
export function diffToMutations(
- prev: CanvasNodeState[],
- next: CanvasNodeState[]
+ prev: CanvasScene | CanvasNodeState[],
+ next: CanvasScene | CanvasNodeState[]
): CanvasMutation[] {
- const mutations: CanvasMutation[] = []
- const prevById = new Map(prev.map((node) => [node.id, node]))
- const nextIds = new Set(next.map((node) => node.id))
+ const a = asScene(prev)
+ const b = asScene(next)
+ const upserts: CanvasMutation[] = []
+ const removes: CanvasMutation[] = []
+ const prevById = new Map(a.nodes.map((node) => [node.id, node]))
+ const nextIds = new Set(b.nodes.map((node) => node.id))
// upserts: added or changed nodes (in next-array order for determinism).
- for (const node of next) {
+ for (const node of b.nodes) {
const before = prevById.get(node.id)
if (!before || stableStringify(before) !== stableStringify(node)) {
- mutations.push({ op: 'upsert', node })
+ upserts.push({ op: 'upsert', node })
}
}
// removes: nodes present in prev but gone from next (in prev-array order).
- for (const node of prev) {
- if (!nextIds.has(node.id)) mutations.push({ op: 'remove', id: node.id })
+ for (const node of a.nodes) {
+ if (!nextIds.has(node.id)) removes.push({ op: 'remove', id: node.id })
}
- return mutations
+
+ const edgeUpserts: CanvasMutation[] = []
+ const edgeRemoves: CanvasMutation[] = []
+ diffEdges(a.bridges, b.bridges, 'bridge', edgeUpserts, edgeRemoves)
+ diffEdges(a.ropes, b.ropes, 'rope', edgeUpserts, edgeRemoves)
+
+ return [...upserts, ...edgeUpserts, ...edgeRemoves, ...removes]
}
diff --git a/src/shared/canvas-order.ts b/src/shared/canvas-order.ts
index 3195c37a5..0f02548df 100644
--- a/src/shared/canvas-order.ts
+++ b/src/shared/canvas-order.ts
@@ -97,9 +97,40 @@ export const PENDING_TTL_MS = 5000
*/
export const REMOVED_MAX = 512
-/** The node a mutation addresses. */
-export function mutationNodeId(m: CanvasMutation): string {
- return m.op === 'remove' ? m.id : m.node.id
+/**
+ * The THING a mutation addresses — the key everything below orders by.
+ *
+ * Nodes and edges live in ONE key space with a prefix, not two maps: a node id and an edge id are
+ * generated independently and could collide, and the rules here (highest `seq` wins, our unacked
+ * cast suppresses peers, a remove tombstones the key) are the same for both. The prefix is what
+ * keeps them from being confused for one another.
+ *
+ * Edges key on the id ALONE — the `kind` is deliberately not in the key. One id is one edge; a
+ * bridge and a rope claiming the same id must fight in the total order and be resolved to one
+ * thing, not held as two independent entities on different clients.
+ */
+export function mutationKey(m: CanvasMutation): string {
+ if (m.op === 'edge-remove') return `e:${m.id}`
+ if (m.op === 'edge-upsert') return `e:${m.edge.id}`
+ return `n:${m.op === 'remove' ? m.id : m.node.id}`
+}
+
+/** The node a mutation addresses. Node ops only — an edge mutation addresses no node. */
+export function mutationNodeId(m: CanvasMutation): string | null {
+ if (m.op === 'remove') return m.id
+ if (m.op === 'upsert') return m.node.id
+ return null
+}
+
+/** Does this mutation ADD-OR-REPLACE its subject (as opposed to dropping it)? Nodes and edges are
+ * ordered by the same rules, so every rule below asks this rather than `op === 'upsert'`. */
+function isUpsert(m: CanvasMutation): boolean {
+ return m.op === 'upsert' || m.op === 'edge-upsert'
+}
+
+/** Does this mutation DROP its subject? The mirror of `isUpsert`. */
+function isRemove(m: CanvasMutation): boolean {
+ return m.op === 'remove' || m.op === 'edge-remove'
}
export interface CanvasOrder {
@@ -199,7 +230,7 @@ export function createCanvasOrder(
* legitimate edit. Degrade to the pre-rule-4 behaviour rather than break.
*/
const supersededByRemove = (m: CanvasMutation, id: string): boolean => {
- if (m.op !== 'upsert') return false
+ if (!isUpsert(m)) return false
const at = removed.get(id)
if (at === undefined) return false
return typeof m.seen === 'number' && m.seen < at
@@ -226,7 +257,7 @@ export function createCanvasOrder(
},
onLocal(m) {
- const id = mutationNodeId(m)
+ const id = mutationKey(m)
const p = pending.get(id)
if (p) {
p.count++
@@ -242,7 +273,7 @@ export function createCanvasOrder(
},
accept(m) {
- const id = mutationNodeId(m)
+ const id = mutationKey(m)
const seq = m.seq ?? 0
const highest = seen.get(id) ?? 0
// `seq` 0 means an unstamped mutation (no reflector in the path) — never treat it as stale.
@@ -257,7 +288,7 @@ export function createCanvasOrder(
// it: a straggler describes a state the total order has already left behind.
const stale = supersededByRemove(m, id)
if (current) {
- if (m.op === 'remove') noteRemoved(id, seq)
+ if (isRemove(m)) noteRemoved(id, seq)
else if (!stale) removed.delete(id) // a deliberate re-creation: this node is alive again
}
@@ -288,7 +319,7 @@ export function createCanvasOrder(
// NEVER for a `remove`. Rule 2 rests on our unacked mutation winning everywhere, and under
// rule 4 it does not: every other client is about to drop it for being older than this
// delete. Holding the remove off here is the one way to end up disagreeing with them.
- if (m.op !== 'remove' && suppressing(id)) return false
+ if (!isRemove(m) && suppressing(id)) return false
// Applying a peer's mutation over an unacked cast of ours (the TTL lapsed — `suppressing`
// just said so, but the entry is still there): remember that our value is gone, so the late
// ack can repair it (rule 3).
diff --git a/src/shared/canvas-publish.test.ts b/src/shared/canvas-publish.test.ts
index 0c8fcb6dd..9042ef08a 100644
--- a/src/shared/canvas-publish.test.ts
+++ b/src/shared/canvas-publish.test.ts
@@ -3,8 +3,10 @@ import {
createCanvasPublisher,
isEphemeralNodeId,
publishableStates,
- PUBLISH_INTERVAL_MS
+ PUBLISH_INTERVAL_MS,
+ publishableScene
} from './canvas-publish'
+import { mutationNodeId } from './canvas-order'
import type { CanvasMutation, CanvasNodeState } from './types'
const node = (id: string, x = 0): CanvasNodeState =>
@@ -131,7 +133,7 @@ describe('a refused cast (send → false)', () => {
const sent: CanvasMutation[] = []
const send = (m: CanvasMutation): boolean => {
tried.push(m)
- const id = m.op === 'remove' ? m.id : m.node.id
+ const id = mutationNodeId(m)
if (id === bad) return false
sent.push(m)
return true
@@ -153,7 +155,7 @@ describe('a refused cast (send → false)', () => {
let bad = 'a'
const sent: CanvasMutation[] = []
const p = createCanvasPublisher((m) => {
- const id = m.op === 'remove' ? m.id : m.node.id
+ const id = mutationNodeId(m)
if (id === bad) return false
sent.push(m)
return true
@@ -335,3 +337,42 @@ describe('ephemeral nodes are never published', () => {
expect(c.sent).toHaveLength(1)
})
})
+
+describe('publishableScene', () => {
+ const link = (id: string, source: string, target: string) => ({ id, source, target })
+
+ it('carries the nodes and both edge lists', () => {
+ const scene = {
+ nodes: [node('a'), node('b')],
+ bridges: [link('e1', 'a', 'b')],
+ ropes: [link('ctrl-1', 'a', 'b')]
+ }
+ const out = publishableScene(scene, new Set())
+ expect(out.nodes.map((n) => n.id)).toEqual(['a', 'b'])
+ expect(out.bridges).toEqual(scene.bridges)
+ expect(out.ropes).toEqual(scene.ropes)
+ })
+
+ // The edge half of the ephemeral rule. A subagent / loop card is DERIVED per client from the
+ // agent:status stream, so an edge naming one addresses a node with a different lifetime on the
+ // peer — it would be pruned there at a moment we do not control and re-published back at us.
+ it('drops an edge whose endpoint is an ephemeral card', () => {
+ const scene = {
+ nodes: [node('a'), node('sub-1'), node('loop-a')],
+ bridges: [link('e1', 'a', 'sub-1'), link('e2', 'a', 'a')],
+ ropes: [link('ctrl-1', 'loop-a', 'a')]
+ }
+ const out = publishableScene(scene, new Set(['sub-1']))
+ expect(out.nodes.map((n) => n.id)).toEqual(['a'])
+ expect(out.bridges).toEqual([link('e2', 'a', 'a')])
+ expect(out.ropes).toEqual([])
+ })
+
+ it('drops an edge whose endpoint is not on the canvas at all (a dangling link)', () => {
+ const out = publishableScene(
+ { nodes: [node('a')], bridges: [link('e1', 'a', 'ghost')], ropes: [] },
+ new Set()
+ )
+ expect(out.bridges).toEqual([])
+ })
+})
diff --git a/src/shared/canvas-publish.ts b/src/shared/canvas-publish.ts
index 8d1dbc3ad..6e57ccac1 100644
--- a/src/shared/canvas-publish.ts
+++ b/src/shared/canvas-publish.ts
@@ -22,9 +22,9 @@
// Pure + DOM-free (vitest runs in the node environment): only setTimeout, no React, no window.
import { stripSharedNodeExec } from './node-exec'
-import { diffToMutations } from './canvas-mutations'
-import { mutationNodeId } from './canvas-order'
-import type { CanvasMutation, CanvasNodeState } from './types'
+import { asScene, diffToMutations, type CanvasScene } from './canvas-mutations'
+import { mutationKey } from './canvas-order'
+import type { BridgeLink, CanvasMutation, CanvasNodeState } from './types'
/** ~20 Hz while dragging — the same budget the presence cursor stream uses. */
export const PUBLISH_INTERVAL_MS = 50
@@ -42,7 +42,10 @@ export const PUBLISH_INTERVAL_MS = 50
* immutable array per change, so `() => serialize(nodes)` satisfies this): the publisher may
* resolve it later — at the trailing edge of a throttle window, or when the first peer arrives.
*/
-export type CanvasSnapshot = CanvasNodeState[] | (() => CanvasNodeState[])
+export type CanvasSnapshot =
+ | CanvasScene
+ | CanvasNodeState[]
+ | (() => CanvasScene | CanvasNodeState[])
export interface CanvasPublisher {
/** Diff `next` against the last published snapshot and send the mutations.
@@ -70,16 +73,17 @@ export interface CanvasPublisher {
* A refused node that had no previous entry is simply left OUT of the baseline (so it re-diffs as an
* add); a refused `remove` keeps its node in the baseline (so the remove is re-emitted).
*/
-function rebaseRefused(
- prev: CanvasNodeState[],
- next: CanvasNodeState[],
- refused: Set<string>
-): CanvasNodeState[] {
+function rebaseList<T extends { id: string }>(
+ prev: T[],
+ next: T[],
+ refused: Set<string>,
+ prefix: string
+): T[] {
const prevById = new Map(prev.map((n) => [n.id, n]))
const nextIds = new Set(next.map((n) => n.id))
- const out: CanvasNodeState[] = []
+ const out: T[] = []
for (const n of next) {
- if (!refused.has(n.id)) {
+ if (!refused.has(prefix + n.id)) {
out.push(n)
continue
}
@@ -87,11 +91,24 @@ function rebaseRefused(
if (before) out.push(before)
}
for (const n of prev) {
- if (refused.has(n.id) && !nextIds.has(n.id)) out.push(n) // a refused remove: still owed
+ if (refused.has(prefix + n.id) && !nextIds.has(n.id)) out.push(n) // a refused remove: still owed
}
return out
}
+/** The refusal rebase, over the whole scene. `refused` holds `mutationKey`s, so the two edge lists
+ * share the `e:` prefix — an edge id is one edge whichever list it is in (see mutationKey). */
+function rebaseRefused(prev: CanvasScene, next: CanvasScene, refused: Set<string>): CanvasScene {
+ return {
+ nodes: rebaseList(prev.nodes, next.nodes, refused, 'n:'),
+ bridges: rebaseList(prev.bridges, next.bridges, refused, 'e:'),
+ ropes: rebaseList(prev.ropes, next.ropes, refused, 'e:')
+ }
+}
+
+/** The empty baseline — a scene, so the first diff after mount is against a real shape. */
+const EMPTY_SCENE: CanvasScene = { nodes: [], bridges: [], ropes: [] }
+
/**
* @param send casts one mutation (already stamped with `src`). Returning `false` means the
* cast did NOT happen (refused / no project): the mutation is then owed — its
@@ -120,15 +137,16 @@ export function createCanvasPublisher(
const intervalMs = opts.intervalMs ?? PUBLISH_INTERVAL_MS
const shouldPublish = opts.shouldPublish ?? (() => true)
/** The baseline, held EITHER resolved (`last`) or unresolved (`lastLazy`) — never both. */
- let last: CanvasNodeState[] = []
- let lastLazy: (() => CanvasNodeState[]) | null = null
+ let last: CanvasScene = EMPTY_SCENE
+ let lastLazy: (() => CanvasScene) | null = null
let pending: CanvasSnapshot | null = null
let timer: ReturnType<typeof setTimeout> | null = null
- const resolve = (s: CanvasSnapshot): CanvasNodeState[] => (typeof s === 'function' ? s() : s)
+ const resolve = (s: CanvasSnapshot): CanvasScene =>
+ asScene(typeof s === 'function' ? s() : s)
/** The baseline to diff against, resolving a deferred one exactly once. */
- const baseline = (): CanvasNodeState[] => {
+ const baseline = (): CanvasScene => {
if (lastLazy) {
last = lastLazy()
lastLazy = null
@@ -140,9 +158,9 @@ export function createCanvasPublisher(
* and, for a solo user, nothing ever will. */
const setBaseline = (s: CanvasSnapshot): void => {
if (typeof s === 'function') {
- lastLazy = s
+ lastLazy = () => asScene(s())
} else {
- last = s
+ last = asScene(s)
lastLazy = null
}
}
@@ -157,7 +175,7 @@ export function createCanvasPublisher(
const mutations = diffToMutations(prev, next)
const refused = new Set<string>()
for (const m of mutations) {
- if (send(opts.src ? { ...m, src: opts.src } : m) === false) refused.add(mutationNodeId(m))
+ if (send(opts.src ? { ...m, src: opts.src } : m) === false) refused.add(mutationKey(m))
}
last = refused.size ? rebaseRefused(prev, next, refused) : next
lastLazy = null
@@ -232,6 +250,28 @@ export function isEphemeralNodeId(id: string, ephemeralIds: ReadonlySet<string>)
return ephemeralIds.has(id) || id.startsWith('loop-')
}
+/**
+ * The whole canvas as it may go on the wire: publishable nodes (above) plus the two PERSISTED edge
+ * lists, with every edge whose endpoint is an ephemeral card dropped.
+ *
+ * That last filter is the edge half of the same rule. The ephemeral subagent / loop cards are
+ * derived per client from the `agent:status` stream, so an edge pointing at one addresses a node id
+ * that exists on the peer with a DIFFERENT lifetime (or not at all yet) — and unlike a node, an
+ * edge is not visibly duplicated by the mistake, it just gets pruned on the peer at a moment we do
+ * not control and then re-published back at us. The ephemeral edges Canvas draws to those cards are
+ * built and merged at the `<ReactFlow>` prop and are not in these lists at all; this is the guard
+ * for a PERSISTED edge that happens to name one.
+ */
+export function publishableScene(
+ scene: CanvasScene,
+ ephemeralIds: ReadonlySet<string>
+): CanvasScene {
+ const nodes = publishableStates(scene.nodes, ephemeralIds)
+ const live = new Set(nodes.map((n) => n.id))
+ const keep = (e: BridgeLink): boolean => live.has(e.source) && live.has(e.target)
+ return { nodes, bridges: scene.bridges.filter(keep), ropes: scene.ropes.filter(keep) }
+}
+
/** The node states that may go on the wire: everything except the ephemeral cards. */
export function publishableStates(
states: CanvasNodeState[],
diff --git a/src/shared/node-exec.ts b/src/shared/node-exec.ts
index a71f25ac3..b28d727ea 100644
--- a/src/shared/node-exec.ts
+++ b/src/shared/node-exec.ts
@@ -127,8 +127,10 @@ export function carryLocalNodeExec(
return out
}
-/** `sanitizeInboundNode` for a whole mutation (the stamps — `src`, `seq` — are preserved). */
-export function sanitizeInboundMutation<T extends { op: 'upsert' | 'remove' }>(m: T): T {
+/** `sanitizeInboundNode` for a whole mutation (the stamps — `src`, `seq`, `seen` — are preserved).
+ * Only `upsert` carries a node; every other op (`remove`, and the edge ops, which carry nothing
+ * but ids) passes through untouched. */
+export function sanitizeInboundMutation<T extends { op: string }>(m: T): T {
if (m.op !== 'upsert') return m
const up = m as unknown as { node: CanvasNodeState }
const node = sanitizeInboundNode(up.node)
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 9f7c19cb1..d63941723 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -660,6 +660,24 @@ export interface CanvasState {
export type CanvasMutation =
| { op: 'upsert'; node: CanvasNodeState; src?: string; seq?: number; seen?: number }
| { op: 'remove'; id: string; src?: string; seq?: number; seen?: number }
+ | {
+ op: 'edge-upsert'
+ kind: CanvasEdgeKind
+ edge: BridgeLink
+ src?: string
+ seq?: number
+ seen?: number
+ }
+ | { op: 'edge-remove'; kind: CanvasEdgeKind; id: string; src?: string; seq?: number; seen?: number }
+
+/**
+ * Which persisted edge list a mutation addresses — `bridges` (context links, which an agent can
+ * actually READ through) or `ropes` (display-only "spawned by" lineage). They are two arrays on
+ * the project with two different meanings, so the kind travels with the mutation; the ORDER,
+ * however, is keyed on the edge id alone (canvas-order's `e:<id>`), because one id is one edge and
+ * two clients must never end up holding it as both a bridge and a rope.
+ */
+export type CanvasEdgeKind = 'bridge' | 'rope'
/** Canvas pan/zoom state. */
export interface Viewport {