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.

fix(team): edge sync port fixes — eager thunk, synchronous edge refs, one id one edge, held edges

reviewe6182112b296
diff --git a/docs/team-presence.md b/docs/team-presence.md
index fcf948da4..898efe9fe 100644
--- a/docs/team-presence.md
+++ b/docs/team-presence.md
@@ -424,14 +424,16 @@ They are in the vocabulary now, and everything around them is the node machinery
- **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.
+ travel.** A rope's colour and its waiting look are derived at render time from each client's own
+ nodes (`displayEdges` / `ropeVisual`), so sending them 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.
+ causal delete) therefore covers an edge exactly as it covers a node. The apply and the diff agree:
+ `applyEdgeMutationToScene` takes an upserted id out of the other list and a remove drops it from
+ both, and `diffToMutations` casts no remove for an id that only moved between the lists (a trailing
+ remove would delete it from both).
- **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
@@ -447,9 +449,36 @@ They are in the vocabulary now, and everything around them is the node machinery
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.
+- **The snapshot thunk captures the edge arrays when it is CREATED** (`publishableLater`). The
+ publisher keeps an `adopt` baseline unresolved until the next publish, so a thunk that read the
+ edge refs when it RAN saw the link the user had drawn since the last peer op or project load: the
+ diff was empty, nothing was cast, and the teammate's next save deleted the link. Only the `.map`
+ is deferred (React state arrays are never mutated in place), so the solo gate still skips the cost.
+- **The edge refs move synchronously** with their setters on a project load and a server change,
+ and the render-time mirror copies the state only when it CHANGED. A zustand write re-renders on
+ the SyncLane and skips the pending DefaultLane setter (see `nodesEpoch.ts`), so an unconditional
+ mirror put the previous project's edges back into the ref — and a peer's edge op arriving before
+ the next render was applied to them and overwrote the load.
+- **An edge whose endpoint the peer does not have is held, not cast.** A node the size guard refuses
+ (an oversized sticky) never reaches the peer; an edge to it that did would be pruned there, and the
+ peer's `edge-remove` would delete the link on our canvas too. The publisher holds such an
+ `edge-upsert` inside the emit that refused the node (and on every later one while the node's last
+ cast stays refused, across adopts — `refusedNodeIds()`), keeps it owed, and casts it in the same
+ batch as the node once the node goes through. The hold is in the publisher, not a filter on the
+ scene: dropping an edge the baseline already holds would diff as an `edge-remove` — the same delete,
+ cast by us. It is conservative: an edge to a node whose EARLIER version the peer has also waits.
+- **"This note is too large" is said only for a node upsert.** An edge op is refused only for a
+ malformed or over-long id, so the sentence would name a cause nobody measured; the refusal is
+ logged instead.
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).
+peer's node delete can leave one drawn against nothing for a tick (see Known risks). Also still
+open: a peer edge op applied in the same task as a local functional edge update overwrites that
+update (the node path has the same hazard); a local node delete publishes its `remove` first and the
+pruned edges' `edge-remove`s one render later, and every peer prunes the same dangling edge itself
+(converges, with redundant casts); canvas-control writes into a project that is not on screen, and
+the Server Edition's headless edge writes, are not cast as edge ops (the latter reach browsers
+through `workspace:server-change`, which every tab with peers then re-casts).
## UI
diff --git a/src/core/canvas-sync.convergence.test.ts b/src/core/canvas-sync.convergence.test.ts
index 26a04a7c8..06bc0ca55 100644
--- a/src/core/canvas-sync.convergence.test.ts
+++ b/src/core/canvas-sync.convergence.test.ts
@@ -22,7 +22,7 @@ import { initPlatform, resetPlatformForTests, type CorePlatform } from './platfo
import { initCanvasSync, MUTATION_MAX_BYTES } from './canvas-sync'
import {
applyCanvasMutation,
- applyEdgeMutation,
+ applyEdgeMutationToScene,
isCanvasMutation,
type CanvasScene
} from '../shared/canvas-mutations'
@@ -194,8 +194,10 @@ 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)
+ // One id is one edge across both lists — what Canvas and the projects store apply.
+ const edges = applyEdgeMutationToScene({ bridges: this.bridges, ropes: this.ropes }, m)
+ this.bridges = edges.bridges
+ this.ropes = edges.ropes
this.pub.adopt(this.publishable()) // loop guard — never re-publish someone else's change
})
}
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index c683c761d..fdfbeb09e 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -632,7 +632,7 @@ import {
} from '@shared/canvas-publish'
import { createCanvasOrder, createReconnectWatch, type CanvasOrder } from '@shared/canvas-order'
import {
- applyEdgeMutation,
+ applyEdgeMutationToScene,
createMutationGuard,
isEdgeMutation,
type CanvasScene
@@ -1165,15 +1165,31 @@ export function Canvas() {
const [nodes, setNodes, onNodesChange] = useNodesState<CanvasNode>([])
// Persistent context links between Claude nodes (separate from ephemeral subagent/loop edges).
const [linkEdges, setLinkEdges, onLinkEdgesChange] = useEdgesState<Edge>([])
- const linkEdgesRef = useRef<Edge[]>([])
- linkEdgesRef.current = linkEdges
+ // The edge refs are the LATEST edges, which is not always the rendered state. Three writers — the
+ // project load, a server change, a peer's edge op (canvas sync) — assign a ref synchronously
+ // beside its setter, because the setter lands on a later render and the next event must build on
+ // the new edges. A render can come FIRST that skips that pending update: a zustand write is a
+ // SyncLane re-render and the setter a DefaultLane one (see nodesEpoch.ts). So the render-time
+ // mirror only copies the state when the STATE changed; an unconditional copy put the previous
+ // project's edges back into the ref in exactly the window the synchronous write closes.
+ const linkEdgesRef = useRef<Edge[]>(linkEdges)
+ const linkEdgesMirroredRef = useRef<Edge[]>(linkEdges)
+ if (linkEdgesMirroredRef.current !== linkEdges) {
+ linkEdgesMirroredRef.current = linkEdges
+ linkEdgesRef.current = linkEdges
+ }
// "Spawned by" ropes drawn from a control-capable agent to the nodes it opens via the
// `nodeterm` CLI (see the onAgentControl effect) and from browser popups to their opener.
// Merged only at the <ReactFlow> prop and never turned into context links, but PERSISTED
// per project (`ropes`) so the lineage survives restarts; deletable like a context link.
const [controlEdges, setControlEdges] = useState<Edge[]>([])
- const controlEdgesRef = useRef<Edge[]>([])
- controlEdgesRef.current = controlEdges
+ // Same latest-not-rendered mirror as linkEdgesRef above, for the same three writers.
+ const controlEdgesRef = useRef<Edge[]>(controlEdges)
+ const controlEdgesMirroredRef = useRef<Edge[]>(controlEdges)
+ if (controlEdgesMirroredRef.current !== controlEdges) {
+ controlEdgesMirroredRef.current = controlEdges
+ controlEdgesRef.current = controlEdges
+ }
const [dirty, setDirty] = useState(false)
// Bumped only when a save finished with `dirty` still set (an edit raced it). It exists purely to
// give the debounced-autosave effect a dependency that CHANGES in that case — `dirty` stays true
@@ -2919,7 +2935,13 @@ export function Canvas() {
if (project.cwd && !project.ssh) {
void useWorktrees.getState().refresh(project.cwd, boundGroups(flow))
}
- setLinkEdges((project.bridges ?? []).map((b) => ({ id: b.id, source: b.source, target: b.target })))
+ // The edge refs are assigned HERE, synchronously, beside their setters — the same reason
+ // installEpoch assigns nodesRef: the setters land on a later render, and a peer's edge op
+ // arriving in between would otherwise be built from the PREVIOUS project's edges and then
+ // overwrite this load's queued value (see the ref declarations for the render-time half).
+ const loadedBridges: Edge[] = (project.bridges ?? []).map((b) => ({ id: b.id, source: b.source, target: b.target }))
+ linkEdgesRef.current = loadedBridges
+ setLinkEdges(loadedBridges)
// A wait with no rope is a wait nothing on screen explains. Ropes for `--after` are written by
// the verbs that arm a node, so an arming that predates them (persisted `pendingLaunch`, no
// persisted rope) — or any future path that forgets one — is healed here on the next load.
@@ -2927,10 +2949,12 @@ export function Canvas() {
// append order, and it must run before the prune below can delete an opener's rope — after
// that, nothing left says which rope into a node was its opener (lib/teamProgress reads it).
const restoredRopes = markLegacyWaitRopes(project.ropes ?? []).map((r) => ropeEdge(r.id, r.source, r.target))
- setControlEdges([
+ const loadedRopes = [
...restoredRopes,
...missingDepRopes(flow, restoredRopes).map((r) => ropeEdge(r.id, r.source, r.target))
- ])
+ ]
+ controlEdgesRef.current = loadedRopes
+ setControlEdges(loadedRopes)
// Reset history for the newly loaded project.
committedRef.current = flow
pastRef.current = []
@@ -3449,10 +3473,18 @@ export function Canvas() {
// Only when the merge actually moved something: a fresh array of identical edges re-renders
// every edge on the canvas (displayEdges recomputes colour and the waiting look per edge)
// for no change at all, and these arrive in bursts.
- if (plan.ropesChanged)
- setControlEdges(plan.ropes.map((r) => ropeEdge(r.id, r.source, r.target)))
- if (plan.bridgesChanged)
- setLinkEdges(plan.bridges.map((b) => ({ id: b.id, source: b.source, target: b.target })))
+ // The refs move synchronously with their setters, as on a load: a peer's edge op landing
+ // before the re-render must build on the MERGED edges, not overwrite them with the old ones.
+ if (plan.ropesChanged) {
+ const ropes = plan.ropes.map((r) => ropeEdge(r.id, r.source, r.target))
+ controlEdgesRef.current = ropes
+ setControlEdges(ropes)
+ }
+ if (plan.bridgesChanged) {
+ const bridges: Edge[] = plan.bridges.map((b) => ({ id: b.id, source: b.source, target: b.target }))
+ linkEdgesRef.current = bridges
+ setLinkEdges(bridges)
+ }
// The store copy is our disk baseline, and the server has already written this file — so it
// moves to the incoming version exactly as the 'merge' branch above does.
useProjects.getState().replaceProject(project)
@@ -3690,12 +3722,15 @@ export function Canvas() {
// peer's delete landing in that window would be lost, and our next whole-file save would
// resurrect their node) nor the retry (the publisher keeps the node in its baseline). The
// only thing that can legitimately blow the cap is free text, i.e. a sticky's body — so say
- // so, instead of letting the note silently never sync.
+ // so, instead of letting the note silently never sync. ONLY for a node upsert, though: an
+ // edge op (or a remove) is refused only for a malformed / over-long id, and "this note is
+ // too large" would name a cause nobody measured.
if (!guard(stamped)) {
- setSyncNote(
+ if (stamped.op === 'upsert') setSyncNote(
'This note is too large to share with your teammates (over 250 KB). It stays on your ' +
'canvas, but they will not see it until you shorten it.'
)
+ else console.warn('[canvas-sync] refused an unsendable mutation', stamped.op)
return false
}
order.onLocal(stamped)
@@ -3785,6 +3820,16 @@ export function Canvas() {
if (useProjects.getState().applyEdgeMutation(projectId, mutation)) markDirty()
return
}
+ // One id is one edge (`applyEdgeMutationToScene`): an upsert of one kind also takes that id
+ // out of the other list, and a remove drops it from both — the same identity the ordering
+ // gate above keys on (`mutationKey` leaves the kind out).
+ const prevBridges = linkEdgesRef.current
+ const prevRopes = controlEdgesRef.current
+ const base = { bridges: prevBridges.map(toBridgeLink), ropes: prevRopes.map(toBridgeLink) }
+ const next = applyEdgeMutationToScene(base, mutation)
+ // Nothing to do — a remove for an edge we do not have, or the edge we already hold (every
+ // Server Edition tab re-casts a server-written edge): no setState, no markDirty, no save.
+ if (next.bridges === base.bridges && next.ropes === base.ropes) return
// Rebuilt EDGE-BY-EDGE, reusing the existing object whenever its three ids are unchanged —
// the same discipline `applyMutationToFlow` follows for nodes, and for the same reason: a
// freshly built object loses `selected`, so re-creating the whole list would wipe the
@@ -3793,26 +3838,23 @@ export function Canvas() {
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)
+ if (next.bridges !== base.bridges) {
// 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 }
+ const edges = next.bridges.map(
+ (b) => keep(prevBridges, 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)
+ }
+ if (next.ropes !== base.ropes) {
// Nothing but the three ids travels: a rope's colour and its waiting look are derived at
// render time from this client's own nodes (`displayEdges` / `ropeVisual`).
- const edges = next.map(
- (r) => keep(controlEdgesRef.current, r) ?? ropeEdge(r.id, r.source, r.target)
- )
+ const edges = next.ropes.map((r) => keep(prevRopes, r) ?? ropeEdge(r.id, r.source, r.target))
controlEdgesRef.current = edges
setControlEdges(edges)
- publisherRef.current?.adopt(publishableLater(nodesRef.current))
}
+ // The loop guard, AFTER both refs moved: publishableLater captures them as of this call.
+ publisherRef.current?.adopt(publishableLater(nodesRef.current))
markDirty()
return
}
diff --git a/src/renderer/canvas/edge-sync-wiring.test.ts b/src/renderer/canvas/edge-sync-wiring.test.ts
new file mode 100644
index 000000000..60877d010
--- /dev/null
+++ b/src/renderer/canvas/edge-sync-wiring.test.ts
@@ -0,0 +1,56 @@
+// Source pins for the edge half of canvas sync (port of feat/team-sync-gaps 7bcf4e3e, with the
+// fixes the port found). Canvas.tsx cannot be rendered in the node test environment, so the
+// load-bearing SHAPES are pinned here; the behaviour behind each one is tested where it lives
+// (canvas-publish.test.ts, canvas-mutations.test.ts, canvas-sync.convergence.test.ts).
+import { readFileSync } from 'node:fs'
+import { describe, it, expect } from 'vitest'
+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+describe('edge publish thunk', () => {
+ // The publisher resolves an adopted thunk LATE (on the next publish). A thunk that read
+ // linkEdgesRef/controlEdgesRef when it ran saw the link the user had drawn since, so the diff was
+ // empty and the link was never cast — the teammate's next save then deleted it.
+ it('captures the edge arrays when the thunk is CREATED, not when it runs', () => {
+ const body = src.slice(src.indexOf('const publishableLater'), src.indexOf('const publishableLater') + 1200)
+ expect(body).toMatch(/const bridges = [^\n]*linkEdges/)
+ expect(body).not.toMatch(/=>\s*publishableScene\([\s\S]*linkEdgesRef\.current/)
+ })
+})
+
+describe('edge refs on project load and server change', () => {
+ // setLinkEdges/setControlEdges land on a LATER render. A peer's edge op arriving in between was
+ // built from the PREVIOUS project's edges and then overwrote the load's queued value.
+ it('the load effect sets the edge refs synchronously', () => {
+ const load = src.slice(src.indexOf('installEpoch(project.id'), src.indexOf('installEpoch(project.id') + 4000)
+ expect(load).toMatch(/linkEdgesRef\.current = /)
+ expect(load).toMatch(/controlEdgesRef\.current = /)
+ })
+
+ it('the server-change path sets the edge refs synchronously', () => {
+ const start = src.indexOf('api.workspace.onServerChange(')
+ const body = src.slice(start, src.indexOf('bumpDirty()', start))
+ expect(body).toMatch(/controlEdgesRef\.current = /)
+ expect(body).toMatch(/linkEdgesRef\.current = /)
+ })
+})
+
+describe('edge ref render-time mirror', () => {
+ // A zustand write re-renders Canvas on the SyncLane, which SKIPS a pending DefaultLane
+ // setLinkEdges/setControlEdges (see nodesEpoch.ts). An unconditional `ref = state` mirror in that
+ // render put the previous project's edges back into the ref right after the load effect had
+ // assigned the new ones — reopening the window the synchronous assignment closes.
+ it('mirrors the edge state into the ref only when the state changed', () => {
+ expect(src).toMatch(/if \(linkEdgesMirroredRef\.current !== linkEdges\) \{\n\s*linkEdgesMirroredRef\.current = linkEdges\n\s*linkEdgesRef\.current = linkEdges/)
+ expect(src).toMatch(/if \(controlEdgesMirroredRef\.current !== controlEdges\) \{\n\s*controlEdgesMirroredRef\.current = controlEdges\n\s*controlEdgesRef\.current = controlEdges/)
+ expect(src).not.toMatch(/^ {2}linkEdgesRef\.current = linkEdges$/m)
+ expect(src).not.toMatch(/^ {2}controlEdgesRef\.current = controlEdges$/m)
+ })
+})
+
+describe('the guard refusal message', () => {
+ // Only a node upsert can be too large (a sticky's body is the one unbounded field). An edge op is
+ // refused only for a malformed / over-long id, and "this note is too large" would name a cause
+ // nobody measured.
+ it('names the note size only for a node upsert', () => {
+ expect(src).toMatch(/stamped\.op === 'upsert'\) setSyncNote/)
+ })
+})
diff --git a/src/renderer/state/projects.mutation.test.ts b/src/renderer/state/projects.mutation.test.ts
index e24c5878c..488e55ac0 100644
--- a/src/renderer/state/projects.mutation.test.ts
+++ b/src/renderer/state/projects.mutation.test.ts
@@ -75,3 +75,51 @@ describe('applyNodeMutation', () => {
expect(useProjects.getState().projects).toHaveLength(0)
})
})
+
+/** The edge twin of applyNodeMutation: a background project's serialized edges are what our next
+ * whole-file save writes, so a peer's edge op for it must land there. */
+describe('applyEdgeMutation', () => {
+ const link = (id: string, source = 'a', target = 'b') => ({ id, source, target })
+
+ it('reports false for an unknown project and creates nothing', () => {
+ expect(useProjects.getState().applyEdgeMutation('nope', { op: 'edge-remove', kind: 'bridge', id: 'x' })).toBe(false)
+ expect(useProjects.getState().projects).toHaveLength(0)
+ })
+
+ it('adds a peer edge to a background project', () => {
+ const p = useProjects.getState().addProject('p')
+ useProjects.getState().commitCanvas(p.id, [node('a'), node('b')], { x: 0, y: 0, zoom: 1 })
+ expect(
+ useProjects.getState().applyEdgeMutation(p.id, { op: 'edge-upsert', kind: 'bridge', edge: link('x') })
+ ).toBe(true)
+ expect(useProjects.getState().getProject(p.id)?.bridges).toEqual([link('x')])
+ })
+
+ // A project that never had a list must not have `"bridges": []` materialized into its file by a
+ // ROPE op (or by a remove of an edge it does not hold).
+ it('leaves an absent list absent and the untouched kind by reference', () => {
+ const p = useProjects.getState().addProject('p')
+ useProjects.getState().commitCanvas(p.id, [node('a'), node('b')], { x: 0, y: 0, zoom: 1 })
+ expect(useProjects.getState().getProject(p.id)?.bridges).toBeUndefined()
+ useProjects.getState().applyEdgeMutation(p.id, { op: 'edge-upsert', kind: 'rope', edge: link('ctrl-1') })
+ const after = useProjects.getState().getProject(p.id)
+ expect(after?.bridges).toBeUndefined()
+ expect(after?.ropes).toEqual([link('ctrl-1')])
+
+ const ropes = after?.ropes
+ useProjects.getState().applyEdgeMutation(p.id, { op: 'edge-upsert', kind: 'bridge', edge: link('x') })
+ expect(useProjects.getState().getProject(p.id)?.ropes).toBe(ropes)
+ })
+
+ it('an edge id lives in one list', () => {
+ const p = useProjects.getState().addProject('p')
+ useProjects
+ .getState()
+ .commitCanvas(p.id, [node('a'), node('b')], { x: 0, y: 0, zoom: 1 }, [link('x')], [])
+ useProjects.getState().applyEdgeMutation(p.id, { op: 'edge-upsert', kind: 'rope', edge: link('x') })
+ expect(useProjects.getState().getProject(p.id)?.bridges).toEqual([])
+ expect(useProjects.getState().getProject(p.id)?.ropes).toEqual([link('x')])
+ useProjects.getState().applyEdgeMutation(p.id, { op: 'edge-remove', kind: 'bridge', id: 'x' })
+ expect(useProjects.getState().getProject(p.id)?.ropes).toEqual([])
+ })
+})
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 4d411c7ad..5157788fe 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -22,7 +22,7 @@ import {
pruneLayoutViewports,
type CanvasLayout
} from '@shared/canvas-layout'
-import { applyEdgeMutation } from '@shared/canvas-mutations'
+import { applyEdgeMutationToScene } from '@shared/canvas-mutations'
import { applyCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'
import { markWorkspaceDirty } from './workspaceDirty'
import { folderName } from '../lib/projectOpen'
@@ -606,14 +606,17 @@ export const useProjects = create<ProjectsState>((set, get) => ({
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
+ // One id is one edge across BOTH lists (applyEdgeMutationToScene), which returns the SAME
+ // array for a list the mutation does not change — 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). The base is built ONCE for that
+ // compare: two separate `?? []` literals are never the same array, which is how the branch
+ // this was ported from wrote `[]` anyway.
+ const base = { bridges: p.bridges ?? [], ropes: p.ropes ?? [] }
+ const next = applyEdgeMutationToScene(base, mutation)
+ const nextBridges = next.bridges === base.bridges ? p.bridges : next.bridges
+ const nextRopes = next.ropes === base.ropes ? p.ropes : next.ropes
if (nextBridges === p.bridges && nextRopes === p.ropes) return p
return { ...p, bridges: nextBridges, ropes: nextRopes }
})
diff --git a/src/renderer/state/workspace.mutation.test.ts b/src/renderer/state/workspace.mutation.test.ts
index 551315d96..8f41935fe 100644
--- a/src/renderer/state/workspace.mutation.test.ts
+++ b/src/renderer/state/workspace.mutation.test.ts
@@ -97,6 +97,16 @@ describe('applyMutationToFlow', () => {
// 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.
+ // Edges live in their own state; an edge op must come back as the SAME array, so the peer path's
+ // `flow === nodesRef.current` short-circuit fires instead of a setNodes + adopt + markDirty.
+ it('is a no-op (same array) for an edge mutation', () => {
+ const nodes = [flowNode('a', 0)]
+ expect(applyMutationToFlow(nodes, { op: 'edge-remove', kind: 'bridge', id: 'x' })).toBe(nodes)
+ expect(
+ applyMutationToFlow(nodes, { op: 'edge-upsert', kind: 'rope', edge: { id: 'x', source: 'a', target: 'a' } })
+ ).toBe(nodes)
+ })
+
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(
diff --git a/src/shared/canvas-mutations.test.ts b/src/shared/canvas-mutations.test.ts
index 490ee70fa..461fedc97 100644
--- a/src/shared/canvas-mutations.test.ts
+++ b/src/shared/canvas-mutations.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, afterEach } from 'vitest'
import {
applyCanvasMutation,
applyEdgeMutation,
+ applyEdgeMutationToScene,
createMutationGuard,
diffToMutations,
isCanvasMutation,
@@ -186,6 +187,15 @@ describe('applyEdgeMutation', () => {
expect(applyEdgeMutation(list, 'bridge', { op: 'remove', id: 'x' })).toBe(list)
})
+ // A duplicate cast (every Server Edition tab re-casts a server-written edge) must not cost a
+ // setState + markDirty + save on every receiver.
+ it('keeps identity when an upsert carries the edge we already hold', () => {
+ const list = [e('x')]
+ expect(applyEdgeMutation(list, 'bridge', { op: 'edge-upsert', kind: 'bridge', edge: e('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(
@@ -200,6 +210,36 @@ describe('applyEdgeMutation', () => {
})
})
+// `mutationKey` leaves `kind` out (`e:<id>`): one id is one edge. The apply has to agree, or a
+// rope upsert for an id the bridge list already holds leaves that id in BOTH lists.
+describe('applyEdgeMutationToScene — one id is one edge', () => {
+ it('an edge id lives in one list', () => {
+ const s0 = { bridges: [{ id: 'x', source: 'a', target: 'b' }], ropes: [] }
+ const s1 = applyEdgeMutationToScene(s0, { op: 'edge-upsert', kind: 'rope', edge: { id: 'x', source: 'a', target: 'b' } })
+ expect(s1).toEqual({ bridges: [], ropes: [{ id: 'x', source: 'a', target: 'b' }] })
+ expect(applyEdgeMutationToScene(s1, { op: 'edge-remove', kind: 'bridge', id: 'x' })).toEqual({ bridges: [], ropes: [] })
+ })
+
+ it('keeps both lists by reference when nothing changes (the caller short-circuit fires)', () => {
+ const s = { bridges: [e('x')], ropes: [e('r')] }
+ const same = (m: Parameters<typeof applyEdgeMutationToScene>[1]) => {
+ const out = applyEdgeMutationToScene(s, m)
+ expect(out.bridges).toBe(s.bridges)
+ expect(out.ropes).toBe(s.ropes)
+ }
+ same({ op: 'edge-remove', kind: 'bridge', id: 'q' }) // an edge we do not have
+ same({ op: 'edge-upsert', kind: 'bridge', edge: e('x') }) // one we already hold, unchanged
+ same({ op: 'remove', id: 'x' }) // a NODE op
+ })
+
+ it('leaves the list it does not touch by reference', () => {
+ const s = { bridges: [e('x')], ropes: [e('r')] }
+ const out = applyEdgeMutationToScene(s, { op: 'edge-upsert', kind: 'bridge', edge: e('y') })
+ expect(out.bridges.map((b) => b.id)).toEqual(['x', 'y'])
+ expect(out.ropes).toBe(s.ropes)
+ })
+})
+
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')]
@@ -270,6 +310,15 @@ describe('diffToMutations — scenes', () => {
])
})
+ // One id is one edge (see applyEdgeMutationToScene): an id that moves from one list to the other
+ // is still on the canvas, so it is an upsert of its new kind and NOT also a remove of its old one.
+ // A receiver applies the batch in order, and a trailing `edge-remove` would delete it from both.
+ it('an edge moving between the lists casts its upsert and no remove', () => {
+ expect(diffToMutations(scene([], [e('x')]), scene([], [], [e('x')]))).toEqual([
+ { op: 'edge-upsert', kind: 'rope', edge: e('x') }
+ ])
+ })
+
// 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.
diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.ts
index cdc815d48..1d785a7d4 100644
--- a/src/shared/canvas-mutations.ts
+++ b/src/shared/canvas-mutations.ts
@@ -211,9 +211,11 @@ export function applyCanvasMutation(
}
/**
- * 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.
+ * Apply one EDGE mutation to one of a project's edge lists, returning a NEW array when it changes
+ * anything (the input is never mutated). A mutation for the other kind — or for a node — and one
+ * that changes nothing (a remove of an edge we lack, an upsert of the edge we hold) leave the list
+ * untouched, by reference, so the caller's `next === prev` check still short-circuits. For the
+ * whole scene (one id is one edge, across both lists) use `applyEdgeMutationToScene`.
*
* 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
@@ -235,11 +237,38 @@ export function applyEdgeMutation(
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]
+ // The edge we already hold, unchanged: same reference, so a duplicate cast (every Server Edition
+ // tab re-casts a server-written edge) costs a receiver no setState, no markDirty, no save.
+ const held = edges[idx]
+ if (held.source === edge.source && held.target === edge.target) return edges
const next = edges.slice()
next[idx] = edge
return next
}
+/** Apply an edge op to BOTH lists: one id is one edge, so an upsert of kind K removes that id from
+ * the other kind's list, and a remove drops it from both.
+ *
+ * `mutationKey` leaves `kind` out of the key for the same reason, so the ordering already treats a
+ * bridge and a rope with one id as one thing; applying per kind (`applyEdgeMutation` alone) would
+ * let the two lists each hold that id. A list the op does not change is returned BY REFERENCE, so
+ * a caller can tell a no-op (`out.bridges === scene.bridges && out.ropes === scene.ropes`). */
+export function applyEdgeMutationToScene(
+ scene: { bridges: BridgeLink[]; ropes: BridgeLink[] },
+ m: CanvasMutation
+): { bridges: BridgeLink[]; ropes: BridgeLink[] } {
+ if (!isEdgeMutation(m)) return scene
+ const id = m.op === 'edge-remove' ? m.id : m.edge.id
+ const drop = (list: BridgeLink[]) => {
+ const next = list.filter((e) => e.id !== id)
+ return next.length === list.length ? list : next
+ }
+ if (m.op === 'edge-remove') return { bridges: drop(scene.bridges), ropes: drop(scene.ropes) }
+ return m.kind === 'bridge'
+ ? { bridges: applyEdgeMutation(scene.bridges, 'bridge', m), ropes: drop(scene.ropes) }
+ : { bridges: drop(scene.bridges), ropes: applyEdgeMutation(scene.ropes, 'rope', m) }
+}
+
/** Stable JSON stringify (keys sorted) so deep-equality is order-independent. */
function stableStringify(value: unknown): string {
return JSON.stringify(value, (_key, val) => {
@@ -256,16 +285,20 @@ 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. */
+ * compare is a plain field compare rather than a stringify.
+ *
+ * "Dropped" means gone from the WHOLE next scene (`liveIds` = both lists), not just from this
+ * kind's list: one id is one edge (applyEdgeMutationToScene), so an id that moved to the other list
+ * is covered by that list's upsert — and a remove cast after it would delete it from both. */
function diffEdges(
prev: BridgeLink[],
next: BridgeLink[],
kind: CanvasEdgeKind,
+ liveIds: ReadonlySet<string>,
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) {
@@ -273,7 +306,7 @@ function diffEdges(
}
}
for (const edge of prev) {
- if (!nextIds.has(edge.id)) removes.push({ op: 'edge-remove', kind, id: edge.id })
+ if (!liveIds.has(edge.id)) removes.push({ op: 'edge-remove', kind, id: edge.id })
}
}
@@ -316,8 +349,9 @@ export function diffToMutations(
const edgeUpserts: CanvasMutation[] = []
const edgeRemoves: CanvasMutation[] = []
- diffEdges(a.bridges, b.bridges, 'bridge', edgeUpserts, edgeRemoves)
- diffEdges(a.ropes, b.ropes, 'rope', edgeUpserts, edgeRemoves)
+ const liveEdgeIds = new Set([...b.bridges, ...b.ropes].map((e) => e.id))
+ diffEdges(a.bridges, b.bridges, 'bridge', liveEdgeIds, edgeUpserts, edgeRemoves)
+ diffEdges(a.ropes, b.ropes, 'rope', liveEdgeIds, edgeUpserts, edgeRemoves)
return [...upserts, ...edgeUpserts, ...edgeRemoves, ...removes]
}
diff --git a/src/shared/canvas-order.test.ts b/src/shared/canvas-order.test.ts
index 64db32e84..466e97303 100644
--- a/src/shared/canvas-order.test.ts
+++ b/src/shared/canvas-order.test.ts
@@ -6,6 +6,7 @@ import { describe, it, expect } from 'vitest'
import {
createCanvasOrder,
createReconnectWatch,
+ mutationKey,
mutationNodeId,
PENDING_TTL_MS
} from './canvas-order'
@@ -40,6 +41,46 @@ describe('mutationNodeId', () => {
expect(mutationNodeId(up('n1', 0, 'x', 1))).toBe('n1')
expect(mutationNodeId(rm('n2', 'x', 1))).toBe('n2')
})
+
+ it('is null for an edge op (an edge addresses no node)', () => {
+ expect(mutationNodeId({ op: 'edge-remove', kind: 'bridge', id: 'e1' })).toBeNull()
+ expect(mutationNodeId({ op: 'edge-upsert', kind: 'rope', edge: { id: 'e1', source: 'a', target: 'b' } })).toBeNull()
+ })
+})
+
+// One key space for nodes and edges, with a prefix: a node id and an edge id are generated
+// independently and could be equal. The kind is NOT in the key — one id is one edge.
+describe('mutationKey', () => {
+ const edgeUp = (id: string, kind: 'bridge' | 'rope'): CanvasMutation => ({
+ op: 'edge-upsert',
+ kind,
+ edge: { id, source: 'a', target: 'b' }
+ })
+
+ it('prefixes nodes with n: and edges with e:, so equal ids do not collide', () => {
+ expect(mutationKey(up('x', 0, 'a', 1))).toBe('n:x')
+ expect(mutationKey(rm('x', 'a', 1))).toBe('n:x')
+ expect(mutationKey(edgeUp('x', 'bridge'))).toBe('e:x')
+ expect(mutationKey({ op: 'edge-remove', kind: 'bridge', id: 'x' })).toBe('e:x')
+ })
+
+ it('leaves the kind out of the key', () => {
+ expect(mutationKey(edgeUp('x', 'bridge'))).toBe(mutationKey(edgeUp('x', 'rope')))
+ })
+
+ it('an edge op and a node op with the same id are ordered independently', () => {
+ const o = createCanvasOrder('me')
+ o.onLocal(o.stamp(up('x', 1, 'me', 0))) // our own unacked NODE edit suppresses peers' n:x…
+ expect(o.accept(up('x', 5, 'peer', 7))).toBe(false)
+ expect(o.accept({ ...edgeUp('x', 'bridge'), src: 'peer', seq: 8 })).toBe(true) // …not e:x
+ })
+
+ it('rule 4 covers an edge key: a stale edge-upsert cannot resurrect a removed edge', () => {
+ const o = createCanvasOrder('me')
+ expect(o.accept({ op: 'edge-remove', kind: 'bridge', id: 'e1', src: 'a', seq: 10 })).toBe(true)
+ expect(o.accept({ ...edgeUp('e1', 'bridge'), src: 'b', seq: 11, seen: 9 })).toBe(false)
+ expect(o.accept({ ...edgeUp('e1', 'bridge'), src: 'b', seq: 12, seen: 11 })).toBe(true)
+ })
})
describe('createCanvasOrder', () => {
diff --git a/src/shared/canvas-order.ts b/src/shared/canvas-order.ts
index 0f02548df..dd1ca01a0 100644
--- a/src/shared/canvas-order.ts
+++ b/src/shared/canvas-order.ts
@@ -107,7 +107,8 @@ export const REMOVED_MAX = 512
*
* 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.
+ * thing, not held as two independent entities on different clients. The apply side enforces the
+ * same identity (`applyEdgeMutationToScene` in canvas-mutations).
*/
export function mutationKey(m: CanvasMutation): string {
if (m.op === 'edge-remove') return `e:${m.id}`
diff --git a/src/shared/canvas-publish.test.ts b/src/shared/canvas-publish.test.ts
index 9042ef08a..9e5e87604 100644
--- a/src/shared/canvas-publish.test.ts
+++ b/src/shared/canvas-publish.test.ts
@@ -7,7 +7,7 @@ import {
publishableScene
} from './canvas-publish'
import { mutationNodeId } from './canvas-order'
-import type { CanvasMutation, CanvasNodeState } from './types'
+import type { BridgeLink, CanvasMutation, CanvasNodeState } from './types'
const node = (id: string, x = 0): CanvasNodeState =>
({
@@ -376,3 +376,108 @@ describe('publishableScene', () => {
expect(out.bridges).toEqual([])
})
})
+
+// ── Edges and the lazy baseline ──────────────────────────────────────────────────────────────────
+// `adopt` keeps a thunk UNRESOLVED until the next emit. Canvas's thunk used to read the edge refs
+// when it RAN — so after a peer op (or a project load) the baseline, resolved at the next publish,
+// already held the link the user had just drawn: the diff was empty, nothing was cast, and the
+// teammate's next whole-file save deleted the link. The thunk must close over the edges AS OF THE
+// CALL (CanvasSnapshot's contract); this pins the publisher side of that contract.
+describe('edges in a lazy baseline', () => {
+ it('a link drawn right after an adopt is cast (the baseline thunk captured the edges eagerly)', () => {
+ const sent: CanvasMutation[] = []
+ const pub = createCanvasPublisher((m) => { sent.push(m) }, { src: 'a' })
+ const n1 = { id: 'n1', kind: 'terminal', position: { x: 0, y: 0 } } as CanvasNodeState
+ const n2 = { id: 'n2', kind: 'terminal', position: { x: 1, y: 0 } } as CanvasNodeState
+ let bridges: BridgeLink[] = []
+ // What Canvas does: a snapshot thunk that closes over the arrays AS OF THE CALL.
+ const snapshot = () => {
+ const b = bridges
+ return () => ({ nodes: [n1, n2], bridges: b, ropes: [] })
+ }
+ pub.adopt(snapshot()) // a peer op landed → lazy baseline
+ bridges = [{ id: 'bridge-n1-n2', source: 'n1', target: 'n2' }]
+ pub.publish(snapshot())
+ expect(sent).toEqual([
+ expect.objectContaining({ op: 'edge-upsert', kind: 'bridge', edge: { id: 'bridge-n1-n2', source: 'n1', target: 'n2' } })
+ ])
+ })
+})
+
+// A node the guard refuses (an oversized sticky) never reaches the peer. An edge to it that DID go
+// out would name a node the peer does not have; the peer's link-prune effect then drops it and casts
+// an `edge-remove` — deleting the link on OUR canvas too. So an edge-upsert waits for its endpoints.
+describe('an edge to a refused node', () => {
+ const link = (id: string, source: string, target: string): BridgeLink => ({ id, source, target })
+ const scene = (nodes: CanvasNodeState[], bridges: BridgeLink[] = [], ropes: BridgeLink[] = []) => ({
+ nodes,
+ bridges,
+ ropes
+ })
+ /** Refuses every node op for the ids in `bad`; records what was actually cast. */
+ function refusing(bad: Set<string>) {
+ const sent: CanvasMutation[] = []
+ const send = (m: CanvasMutation): boolean => {
+ const id = mutationNodeId(m)
+ if (id !== null && bad.has(id)) return false
+ sent.push(m)
+ return true
+ }
+ return { sent, send }
+ }
+
+ it('is not cast in the same emit that refused its endpoint', () => {
+ const c = refusing(new Set(['big']))
+ const p = createCanvasPublisher(c.send)
+ p.publish(scene([node('big'), node('t')], [link('b1', 'big', 't')], [link('ctrl-1', 't', 'big')]))
+ expect(c.sent).toEqual([{ op: 'upsert', node: node('t') }])
+ expect(p.refusedNodeIds()).toEqual(new Set(['big']))
+ })
+
+ it('follows its endpoint the moment the endpoint casts — in the same batch, after it', () => {
+ const bad = new Set(['big'])
+ const c = refusing(bad)
+ const p = createCanvasPublisher(c.send)
+ p.publish(scene([node('big'), node('t')], [link('b1', 'big', 't')]))
+ bad.clear() // the user trimmed the sticky
+ p.publish(scene([node('big', 1), node('t')], [link('b1', 'big', 't')]))
+ expect(c.sent.slice(1)).toEqual([
+ { op: 'upsert', node: node('big', 1) },
+ { op: 'edge-upsert', kind: 'bridge', edge: link('b1', 'big', 't') }
+ ])
+ expect(p.refusedNodeIds().size).toBe(0)
+ })
+
+ // Why the hold lives INSIDE the publisher rather than as a filter on the scene it is handed: a
+ // filtered-out edge that the baseline already holds diffs as an `edge-remove` — the exact delete
+ // this exists to prevent, cast by us instead of by the peer.
+ it('never removes an edge the peer already has when its endpoint later becomes unsendable', () => {
+ const bad = new Set<string>()
+ const c = refusing(bad)
+ const p = createCanvasPublisher(c.send)
+ p.publish(scene([node('n'), node('t')], [link('b1', 'n', 't')]))
+ const cast = c.sent.length
+ bad.add('n') // n's next edit is too large
+ p.publish(scene([node('n', 9), node('t')], [link('b1', 'n', 't')]))
+ p.publish(scene([node('n', 9), node('t')], [link('b1', 'n', 't')]))
+ expect(c.sent.slice(cast)).toEqual([])
+ })
+
+ it('stays held across an adopt that took the refused node into the baseline', () => {
+ const c = refusing(new Set(['big']))
+ const p = createCanvasPublisher(c.send)
+ p.publish(scene([node('big'), node('t')]))
+ p.adopt(scene([node('big'), node('t')])) // a peer op landed: the baseline now holds `big`
+ p.publish(scene([node('big'), node('t')], [link('b1', 'big', 't')]))
+ expect(c.sent.filter((m) => m.op === 'edge-upsert')).toEqual([])
+ expect(p.refusedNodeIds()).toEqual(new Set(['big']))
+ })
+
+ it('forgets a refused node once it is gone from the canvas', () => {
+ const c = refusing(new Set(['big']))
+ const p = createCanvasPublisher(c.send)
+ p.publish(scene([node('big'), node('t')]))
+ p.publish(scene([node('t')])) // the user deleted it before it ever synced
+ expect(p.refusedNodeIds().size).toBe(0)
+ })
+})
diff --git a/src/shared/canvas-publish.ts b/src/shared/canvas-publish.ts
index 6e57ccac1..52060b132 100644
--- a/src/shared/canvas-publish.ts
+++ b/src/shared/canvas-publish.ts
@@ -23,7 +23,7 @@
import { stripSharedNodeExec } from './node-exec'
import { asScene, diffToMutations, type CanvasScene } from './canvas-mutations'
-import { mutationKey } from './canvas-order'
+import { mutationKey, mutationNodeId } from './canvas-order'
import type { BridgeLink, CanvasMutation, CanvasNodeState } from './types'
/** ~20 Hz while dragging — the same budget the presence cursor stream uses. */
@@ -59,6 +59,10 @@ export interface CanvasPublisher {
/** Send any coalesced drag frame immediately (drag settle / unmount). */
flush(): void
dispose(): void
+ /** The node ids whose most recent cast was REFUSED (`send` → false: the size guard, no active
+ * project) and is still owed — the node half of the refusal rebase. An `edge-upsert` naming one
+ * of them is held back (see `emit`), because the peer does not have that node. A copy. */
+ refusedNodeIds(): ReadonlySet<string>
}
/**
@@ -141,6 +145,10 @@ export function createCanvasPublisher(
let lastLazy: (() => CanvasScene) | null = null
let pending: CanvasSnapshot | null = null
let timer: ReturnType<typeof setTimeout> | null = null
+ /** Node ids whose latest cast was refused and not yet made good (`refusedNodeIds`). Kept ACROSS
+ * emits and adopts: an adopt takes the refused node into the baseline (so it is no longer
+ * re-diffed) but the peer still does not have it — which is exactly when an edge to it must wait. */
+ const owedNodes = new Set<string>()
const resolve = (s: CanvasSnapshot): CanvasScene =>
asScene(typeof s === 'function' ? s() : s)
@@ -174,8 +182,32 @@ export function createCanvasPublisher(
const next = resolve(snapshot)
const mutations = diffToMutations(prev, next)
const refused = new Set<string>()
+ const refusedNow = new Set<string>()
for (const m of mutations) {
- if (send(opts.src ? { ...m, src: opts.src } : m) === false) refused.add(mutationKey(m))
+ // An edge whose endpoint the peer does not have is HELD, not cast: the peer's link prune would
+ // drop it and cast an `edge-remove`, deleting the link on our canvas too. Held = refused, so
+ // the rebase keeps it owed and it re-diffs until its endpoint casts. The batch order (node
+ // upserts first — diffToMutations) means this emit's node verdicts are already in, so an
+ // endpoint that finally casts takes its edges with it in the SAME batch, after it.
+ if (m.op === 'edge-upsert' && (owedNodes.has(m.edge.source) || owedNodes.has(m.edge.target))) {
+ refused.add(mutationKey(m))
+ continue
+ }
+ const cast = send(opts.src ? { ...m, src: opts.src } : m) !== false
+ if (!cast) refused.add(mutationKey(m))
+ const nodeId = mutationNodeId(m)
+ if (nodeId === null) continue
+ if (cast) owedNodes.delete(nodeId)
+ else {
+ owedNodes.add(nodeId)
+ refusedNow.add(nodeId)
+ }
+ }
+ // A refused node that has since left the canvas owes nothing — unless it is its REMOVE that was
+ // just refused (that one is still owed, and the rebase keeps it).
+ if (owedNodes.size) {
+ const live = new Set(next.nodes.map((n) => n.id))
+ for (const id of owedNodes) if (!live.has(id) && !refusedNow.has(id)) owedNodes.delete(id)
}
last = refused.size ? rebaseRefused(prev, next, refused) : next
lastLazy = null
@@ -235,6 +267,9 @@ export function createCanvasPublisher(
if (timer) clearTimeout(timer)
timer = null
pending = null
+ },
+ refusedNodeIds() {
+ return new Set(owedNodes)
}
}
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index d63941723..0a3df5f52 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -675,7 +675,9 @@ export type CanvasMutation =
* 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.
+ * two clients must never end up holding it as both a bridge and a rope. The apply agrees
+ * (`applyEdgeMutationToScene`: an upsert takes the id out of the other list, a remove drops it from
+ * both), and so does the diff (an id that moved lists casts its upsert and no remove).
*/
export type CanvasEdgeKind = 'bridge' | 'rope'