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): a peer op in the switch window cannot mix two projects' nodes

review7230247344d2
diff --git a/CLAUDE.md b/CLAUDE.md
index d076b44de..e3b209a2d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -480,6 +480,15 @@ project's nodes only.** The contract:
with the NEW project's tag. A commit in that window wrote an SSH project's 7 nodes over a local
project's 18 in its `.nodeterm/project.json` (2026-09-26). `nodesEpoch.test.tsx` reproduces the
interleaving with real React (no `act`, which would flush both lanes together and hide it).
+ **The refs are the LATEST pair, not the last rendered one**: the tag ref is written only by
+ `installEpoch`, and a render copies its `nodes` into `nodesRef` only when that state CHANGED and
+ the render belongs to the installed epoch. An unconditional mirror rewound both refs to the
+ outgoing project in that window, and a peer's `canvas:mut` for the incoming (active) project was
+ applied to the outgoing nodes and queued after the load — the canvas ended on A's nodes plus the
+ op, tagged B, and the next commit wrote them into B. So the receive path routes by
+ `liveCanvasHolds` (tag AND active id; otherwise the store) and queues a FUNCTIONAL update
+ (`rebaseOnLatest`). Consequence for readers: code pairing the tag with the RENDERED `nodes`
+ (a render-time publish, an effect keyed on `nodes`) reads `renderedProjectId`, never the ref.
- Switching away unmounts the old project's `TerminalNode`s → their tmux clients detach but
the sessions keep running; switching back reattaches. tmux session names are per-node-id
(globally unique), so projects never collide.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a32e55b4d..c328ad85a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -876,6 +876,16 @@ examples). If the same effect also WRITES, latch its first run: otherwise switch
mid-session applies stored state to whatever the user is doing right then, which is a different
feature from the one they asked for.
+**Canvas's `nodesRef` / `nodesProjectIdRef` are the LATEST pair, not the rendered one.** During a
+project switch a zustand write re-renders Canvas at SyncLane before the load's DefaultLane
+`setNodes` lands, so for a moment the ref names the incoming project while the render's `nodes`
+are still the outgoing one's (`canvas/nodesEpoch.ts`). Event-time code (commits, the `canvas:mut`
+receive path, creates) reads the refs; code that pairs the tag with the RENDERED `nodes` (a
+render-time publish, an effect keyed on `nodes`) reads `renderedProjectId`. A peer op goes live
+only when `liveCanvasHolds` says React Flow has that project, and its `setNodes` is functional
+(`rebaseOnLatest`). `nodesEpoch.test.tsx` reproduces the window with real React; never wrap it in
+`act`, which flushes both lanes together and hides it.
+
Maximize placement and refocusing must use the same measured usable rectangle
(`measureMaximizeInsets`): pinned side panels plus persistent top controls and bottom dock.
Do not hardcode chrome heights or add the outer margin twice; transient menus must not resize
diff --git a/docs/team-presence.md b/docs/team-presence.md
index de08ff839..47927ad97 100644
--- a/docs/team-presence.md
+++ b/docs/team-presence.md
@@ -494,7 +494,8 @@ They are in the vocabulary now, and everything around them is the node machinery
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). 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
+update (the node path no longer does: its receive `setNodes` is functional, `rebaseOnLatest`); 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
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index bd9e184ff..6339e0f1c 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -615,8 +615,8 @@ import { assignNode, assignedTo, defaultKanban, labelsForCard, migrateProjectTag
import { registerWorkspaceDirty } from '../state/workspaceDirty'
import { snapNodeToGrid } from '../lib/nodeSizing'
import { snapResizeChanges } from '../lib/resizeSnap'
-import { canClearDirty, canCommitCanvas, canCreateOnCanvas } from '../state/persistGuards'
-import { useNodesEpoch } from './nodesEpoch'
+import { canClearDirty, canCommitCanvas, canCreateOnCanvas, liveCanvasHolds } from '../state/persistGuards'
+import { rebaseOnLatest, useNodesEpoch } from './nodesEpoch'
import { isHidden } from '../lib/ui-visibility'
import { boardLogEvents } from '../lib/boardLogDiff'
import { useBoardLog } from '../state/boardLog'
@@ -1664,7 +1664,7 @@ export function Canvas() {
* load effect, cleared (null) on its bail-out paths; null until the first load, so the initial
* empty `useNodesState([])` can never be committed as some project's canvas.
*/
- const { nodesRef, nodesProjectIdRef, installEpoch } = useNodesEpoch(nodes)
+ const { nodesRef, nodesProjectIdRef, renderedProjectId, installEpoch } = useNodesEpoch(nodes)
/**
* The project whose webview nodes the NEXT load must retire into the keep-alive pool. Separate
* from `nodesProjectIdRef` on purpose: the epoch tag is invalidated on the load effect's
@@ -2125,7 +2125,8 @@ export function Canvas() {
// per episode) while the window is visible, because a finished check run does not move the
// heartbeat. Everything is released the moment no node waits any more.
const prWatchNeeded = nodes.some((n) => !!(n.data.pendingLaunch as PendingLaunch | undefined)?.afterPr)
- const prWatchProjectId = prWatchNeeded ? (nodesProjectIdRef.current ?? '') : ''
+ // Paired with the rendered `nodes` it was derived from — the rendered epoch, not the latest one.
+ const prWatchProjectId = prWatchNeeded ? (renderedProjectId ?? '') : ''
useEffect(() => {
if (!prWatchProjectId) return
let cancelled = false
@@ -2225,10 +2226,13 @@ export function Canvas() {
// sitting in a poll loop burning context.
useEffect(() => {
const live = new Set(nodes.map((n) => n.id))
+ // The project THIS render's `nodes` belong to (`renderedProjectId`), not the latest installed
+ // epoch: in a project switch's window the ref already names the incoming project while `nodes`
+ // are still the outgoing one's (see useNodesEpoch).
const briefPresent = (path: string | undefined): Promise<boolean> =>
launchBriefPresent(
path,
- useProjects.getState().getProject(nodesProjectIdRef.current ?? ''),
+ useProjects.getState().getProject(renderedProjectId ?? ''),
(p) => activeSession.api.fs.exists(p)
)
const ready = launchesToFire(
@@ -2238,7 +2242,7 @@ export function Canvas() {
setupDoneForGroup,
useLaunchDelivery.getState().byId,
// The `--after-pr` gate: this canvas's pull request status and the clock its deadlines are on.
- { board: pullBoardFor(useGitHubIssues.getState(), nodesProjectIdRef.current ?? ''), now: Date.now() }
+ { board: pullBoardFor(useGitHubIssues.getState(), renderedProjectId ?? ''), now: Date.now() }
).filter((f) => !launchInFlight.current.has(f.id))
// Anything we were reporting on that is no longer an armed node — delivered, run by hand with
// ▶, or deleted — stops being reported. Timers go with it: a stall warning for a node that has
@@ -3846,7 +3850,9 @@ export function Canvas() {
// 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) {
+ // Live only while React Flow holds that project (the epoch tag), not merely while it is the
+ // active one — the same rule as the node branch below (`liveCanvasHolds`).
+ if (!liveCanvasHolds(nodesProjectIdRef.current, useProjects.getState().activeProjectId, projectId)) {
if (useProjects.getState().applyEdgeMutation(projectId, mutation)) markDirty()
return
}
@@ -3888,7 +3894,12 @@ export function Canvas() {
markDirty()
return
}
- if (projectId !== useProjects.getState().activeProjectId) {
+ // Live only while React Flow holds that project's canvas (`liveCanvasHolds` — the epoch tag
+ // AND the active id). During a switch the store already says B while React Flow still holds
+ // A, or nothing after a bail-out; B's op applied to that array ended the canvas on A's nodes
+ // plus the op, tagged B, and the next commit wrote them into B's file (Task 2 review, risk
+ // E). In that case B's serialized nodes are the right target: the load reads them.
+ if (!liveCanvasHolds(nodesProjectIdRef.current, useProjects.getState().activeProjectId, projectId)) {
// Not on screen (a parked / background project): no terminal is mounted, but one may be
// PARKED from a recent project switch — dispose it, as an active-project remove does.
if (mutation.op === 'remove') {
@@ -3903,8 +3914,9 @@ export function Canvas() {
// PATCH THE LIVE ARRAY — do not round-trip the canvas through the (lossy) serializers. That
// wiped your selection, deleted your relay-remote nodes and re-rendered every node component,
// ~20 times a second while a teammate dragged. See applyMutationToFlow.
- const flow = applyMutationToFlow(nodesRef.current, mutation)
- if (flow === nodesRef.current) return // nothing to do (a remove for a node we do not have)
+ const base = nodesRef.current
+ const flow = applyMutationToFlow(base, mutation)
+ if (flow === base) return // nothing to do (a remove for a node we do not have)
if (mutation.op === 'remove') {
// The peer's delete must also dispose OUR terminal co-state for that node — otherwise the
// module-level state survives the node, and if the owner UNDOES the delete we are left
@@ -3927,7 +3939,10 @@ export function Canvas() {
// first (i.e. constantly, while anyone else was dragging). Rebasing keeps the difference that
// IS yours, and adds nothing that is theirs.
committedRef.current = applyMutationToFlow(committedRef.current, mutation)
- setNodes(flow)
+ // FUNCTIONAL, a second guard behind the epoch refs: applied to whatever the state is when it
+ // lands. A plain `setNodes(flow)` overwrote every update queued since the last render — a local
+ // edit mid-drag, or the load's own `setNodes` if the ref were ever stale again.
+ setNodes(rebaseOnLatest(base, flow, (ns) => applyMutationToFlow(ns as CanvasNode[], mutation)))
markDirty()
})
}, [activeSession.api, setNodes, setLinkEdges, setControlEdges, markDirty, publishableLater])
@@ -4234,7 +4249,10 @@ export function Canvas() {
setControlEdges((es) => pruneRopes(es, ids))
}, [nodes])
- useContextLinkSync({ projectId: nodesProjectIdRef.current, nodes, edges: linkEdges })
+ // The RENDERED epoch, not the ref: in a project switch's window the ref already names the incoming
+ // project while `nodes` / `linkEdges` are still the outgoing one's (see useNodesEpoch), and this map
+ // authorizes context reads.
+ useContextLinkSync({ projectId: renderedProjectId, nodes, edges: linkEdges })
// Phone chat: tell the core's agent-status mirror which session each node was last running, for
// nodes it learned nothing about this run (see useMirrorIdentitySeed).
useMirrorIdentitySeed()
diff --git a/src/renderer/canvas/canvas-sync-ordering.source.test.ts b/src/renderer/canvas/canvas-sync-ordering.source.test.ts
index 52b83517c..2e442e2b3 100644
--- a/src/renderer/canvas/canvas-sync-ordering.source.test.ts
+++ b/src/renderer/canvas/canvas-sync-ordering.source.test.ts
@@ -50,3 +50,37 @@ describe('the re-creation gate (canvas-order hasPendingRemove)', () => {
expect(body).toMatch(/pub\.publish\(publishableLater\(nodesRef\.current\)\)/)
})
})
+
+// The switch-window race (Task 2 review, risk E) — behaviour in nodesEpoch.test.tsx, which runs the
+// real hook against a replica of this receive path; these pin that Canvas IS that replica.
+describe('the canvas:mut receive path routes by the epoch tag', () => {
+ it('both branches go live only when liveCanvasHolds says React Flow has that project', () => {
+ const body = receiveHandler()
+ const route = /if \(!liveCanvasHolds\(nodesProjectIdRef\.current, useProjects\.getState\(\)\.activeProjectId, projectId\)\) \{/g
+ expect(body.match(route) ?? []).toHaveLength(2) // the edge branch and the node branch
+ // …and the old active-id-only test is gone from both.
+ expect(body).not.toMatch(/if \(projectId !== useProjects\.getState\(\)\.activeProjectId\)/)
+ })
+
+ it('the node branch queues a FUNCTIONAL update built on the latest state', () => {
+ const body = receiveHandler()
+ expect(body).toMatch(
+ /setNodes\(rebaseOnLatest\(base, flow, \(ns\) => applyMutationToFlow\(ns as CanvasNode\[\], mutation\)\)\)/
+ )
+ expect(body).not.toMatch(/\n\s*setNodes\(flow\)\n/)
+ })
+})
+
+describe('render-time readers pair the rendered nodes with the rendered epoch', () => {
+ // `nodesProjectIdRef` is the LATEST installed epoch now (useNodesEpoch): in the switch window it
+ // already names the incoming project while this render's `nodes` are still the outgoing one's.
+ // The context-link map (which authorizes context reads) must not pair A's links with B's id.
+ it('the context-link sync takes the rendered epoch', () => {
+ expect(src).toContain('useContextLinkSync({ projectId: renderedProjectId, nodes, edges: linkEdges })')
+ expect(src).not.toContain('useContextLinkSync({ projectId: nodesProjectIdRef.current')
+ })
+
+ it('the pull-request watch takes the rendered epoch', () => {
+ expect(src).toContain("const prWatchProjectId = prWatchNeeded ? (renderedProjectId ?? '') : ''")
+ })
+})
diff --git a/src/renderer/canvas/control-after-pr.source.test.ts b/src/renderer/canvas/control-after-pr.source.test.ts
index 7bef577a2..277f8df22 100644
--- a/src/renderer/canvas/control-after-pr.source.test.ts
+++ b/src/renderer/canvas/control-after-pr.source.test.ts
@@ -100,8 +100,11 @@ describe('every open path attaches the wait through withPrHold', () => {
describe('the launch loop judges the wait on the ACTIVE project’s pull request status', () => {
const effect = (): string => slice('const ready = launchesToFire(', '}, [nodes, armedDepSig')
+ // The board of the project the effect's `nodes` belong to — `renderedProjectId`, not the ref: the
+ // ref is the LATEST installed epoch and, in a project switch's window, already names the incoming
+ // project while `nodes` are still the outgoing one's (useNodesEpoch, Task 3).
it('passes the board and the clock to launchesToFire', () => {
- expect(effect()).toMatch(/\{ board: pullBoardFor\(useGitHubIssues\.getState\(\), nodesProjectIdRef\.current \?\? ''\), now: Date\.now\(\) \}/)
+ expect(effect()).toMatch(/\{ board: pullBoardFor\(useGitHubIssues\.getState\(\), renderedProjectId \?\? ''\), now: Date\.now\(\) \}/)
})
it('re-runs when a waited-on pull request changes, off a PRIMITIVE signature', () => {
diff --git a/src/renderer/canvas/control-prompt-spill.source.test.ts b/src/renderer/canvas/control-prompt-spill.source.test.ts
index 8fd5108c9..93fb3ff88 100644
--- a/src/renderer/canvas/control-prompt-spill.source.test.ts
+++ b/src/renderer/canvas/control-prompt-spill.source.test.ts
@@ -150,9 +150,11 @@ describe('the brief file is checked when the launch is DELIVERED (#1014 review)'
expect(missing).toContain('markBriefMissing(f.id')
// Typing happens only on the "present" branch.
expect(missing).toMatch(/return deliverHeld\(\)/)
- // …on the node's own project, with the local fs (the rule itself: `launchBriefPresent`).
+ // …on the node's own project, with the local fs (the rule itself: `launchBriefPresent`). The
+ // node's own project is the RENDERED epoch (`renderedProjectId`), the one its `nodes` came from —
+ // the ref is the latest installed epoch and may already name the next project (useNodesEpoch).
const effect = slice('const briefPresent = ', 'const ready = launchesToFire(')
expect(effect).toContain('launchBriefPresent(')
- expect(effect).toContain('getProject(nodesProjectIdRef.current')
+ expect(effect).toContain('getProject(renderedProjectId')
})
})
diff --git a/src/renderer/canvas/nodesEpoch.test.tsx b/src/renderer/canvas/nodesEpoch.test.tsx
index fcdaa4858..9960e0282 100644
--- a/src/renderer/canvas/nodesEpoch.test.tsx
+++ b/src/renderer/canvas/nodesEpoch.test.tsx
@@ -1,9 +1,11 @@
// @vitest-environment jsdom
import { useEffect, useState } from 'react'
+import { flushSync } from 'react-dom'
import { createRoot } from 'react-dom/client'
import { create } from 'zustand'
-import { afterEach, expect, it } from 'vitest'
-import { useNodesEpoch } from './nodesEpoch'
+import { afterEach, beforeEach, expect, it } from 'vitest'
+import { rebaseOnLatest, useNodesEpoch } from './nodesEpoch'
+import { canCommitCanvas, liveCanvasHolds } from '../state/persistGuards'
// The field bug (2026-09-26): a project switch loaded project B, but a zustand store the load
// effect writes (worktrees reset, keep-alive pool, …) re-rendered Canvas at SyncLane BEFORE the
@@ -11,27 +13,44 @@ import { useNodesEpoch } from './nodesEpoch'
// while the epoch tag already said B — and the next commit wrote A's nodes into B's
// .nodeterm/project.json. These tests run real React (createRoot, no act batching) because the
// interleaving IS the bug: act() would flush both lanes together and hide it.
+//
+// The replica below is Canvas's load effect, its commit (`commitActiveToStore`) and its peer
+// receive path (`canvas:mut`) cut down to string ids; `store` stands in for the projects store.
const useActive = create<{ id: string | null }>(() => ({ id: 'A' }))
const useOther = create<{ n: number }>(() => ({ n: 0 }))
-interface Seen { nodes: string[]; epoch: string | null }
+/** One render: the `nodes` STATE it rendered, and the ref pair as that render left it. */
+interface Seen { state: string[]; nodes: string[]; epoch: string | null }
let seen: Seen[] = []
let root: ReturnType<typeof createRoot> | null = null
+/** The projects store: each project's serialized nodes. */
+let store: Record<string, string[]> = {}
+/** The project the load effect last ran for, and how many renders there were at that moment. */
+let loaded: { id: string | null; at: number } = { id: null, at: 0 }
+let live: {
+ nodesRef: { current: string[] }
+ nodesProjectIdRef: { current: string | null }
+ setNodes: (next: string[] | ((ns: string[]) => string[])) => void
+} | null = null
function Canvas() {
const active = useActive((s) => s.id)
useOther((s) => s.n)
const [nodes, setNodes] = useState<string[]>([])
const { nodesRef, nodesProjectIdRef, installEpoch } = useNodesEpoch(nodes)
- seen.push({ nodes: nodesRef.current, epoch: nodesProjectIdRef.current })
+ seen.push({ state: nodes, nodes: nodesRef.current, epoch: nodesProjectIdRef.current })
+ live = { nodesRef, nodesProjectIdRef, setNodes }
useEffect(() => {
- if (!active) {
+ loaded = { id: active, at: seen.length }
+ const saved = active ? store[active] : undefined
+ if (!saved) {
+ // Canvas's bail-outs (welcome screen, unknown project): the previous nodes stay MOUNTED.
installEpoch(null)
useOther.setState((s) => ({ n: s.n + 1 }))
return
}
- const flow = [`${active}-node`]
+ const flow = [...saved]
setNodes(flow)
installEpoch(active, flow)
// Canvas subscribes to stores its load effect writes; each write is a SyncLane re-render.
@@ -40,12 +59,48 @@ function Canvas() {
return null
}
+/** `commitActiveToStore`: write the live canvas into the ACTIVE project, if the epoch pairs. */
+function commit() {
+ const active = useActive.getState().id
+ if (!active || !live || !canCommitCanvas(live.nodesProjectIdRef.current, active)) return
+ store[active] = live.nodesRef.current
+}
+
+/** The `canvas:mut` receive path for a node upsert — Canvas's: the same route and the same updater. */
+function receive(projectId: string, id: string) {
+ if (!live) return
+ const { nodesRef, nodesProjectIdRef, setNodes } = live
+ if (!liveCanvasHolds(nodesProjectIdRef.current, useActive.getState().id, projectId)) {
+ // Not on screen: the serialized nodes (an unknown project has none to patch).
+ if (store[projectId]) store[projectId] = [...store[projectId], id]
+ return
+ }
+ const apply = (ns: string[]) => (ns.includes(id) ? ns : [...ns, id])
+ const base = nodesRef.current
+ const flow = apply(base)
+ if (flow === base) return
+ nodesRef.current = flow
+ setNodes(rebaseOnLatest(base, flow, apply))
+}
+
const settle = () => new Promise((r) => setTimeout(r, 30))
async function until(ok: () => boolean) {
for (let i = 0; i < 200 && !ok(); i++) await settle()
expect(ok()).toBe(true)
}
+/**
+ * Wait — on MICROTASKS only, so the DefaultLane render (a macrotask) cannot run — for the window
+ * itself: the load effect for `id` has run, and a render after it still shows the previous nodes.
+ * Fails loudly if the window never opened, rather than passing a test that never exercised it.
+ */
+async function untilWindow(id: string) {
+ const open = () =>
+ loaded.id === id && seen.length > loaded.at && !seen.at(-1)?.state.includes(`${id}-node`)
+ for (let i = 0; i < 100 && !open(); i++) await Promise.resolve()
+ expect(open(), 'the SyncLane window never opened').toBe(true)
+}
+
async function mount() {
useActive.setState({ id: 'A' })
const el = document.createElement('div')
@@ -55,15 +110,22 @@ async function mount() {
seen = []
}
+beforeEach(() => {
+ store = { A: ['A-node'], B: ['B-node'] }
+ loaded = { id: null, at: 0 }
+})
+
afterEach(() => {
root?.unmount()
root = null
+ live = null
})
/** Every render must pair the nodes it mirrors with the project they belong to. */
function expectPaired() {
for (const s of seen) {
- if (s.epoch !== null) expect(s.nodes).toEqual([`${s.epoch}-node`])
+ if (s.epoch === null) continue
+ expect(s.nodes.every((n) => n.startsWith(`${s.epoch}-`)), JSON.stringify(s)).toBe(true)
}
}
@@ -73,7 +135,7 @@ it('never pairs the previous project nodes with the incoming project epoch', asy
await until(() => seen.at(-1)?.epoch === 'B')
await settle()
expectPaired()
- expect(seen.at(-1)).toEqual({ nodes: ['B-node'], epoch: 'B' })
+ expect(seen.at(-1)).toEqual({ state: ['B-node'], nodes: ['B-node'], epoch: 'B' })
})
it('keeps the tag cleared after a bail-out (welcome screen) instead of re-mirroring the old project', async () => {
@@ -83,3 +145,67 @@ it('keeps the tag cleared after a bail-out (welcome screen) instead of re-mirror
await settle()
expect(seen.at(-1)?.epoch).toBeNull()
})
+
+// THE PERSISTED-CORRUPTION HALF (Task 2 review, risk E). In the window above, the render-time mirror
+// put A's nodes back into `nodesRef` (paired with A's tag, so no commit took them) — but a peer's op
+// for B, the ACTIVE project, was applied to that array and `setNodes`'d as a plain value queued
+// AFTER the load's: the canvas ended on A's nodes plus the op, tagged B, and the next commit wrote
+// them into B's project file.
+it('a peer op in the switch window lands on the incoming project, never on the outgoing nodes', async () => {
+ await mount()
+ commit() // every switch handler commits before it switches
+ useActive.setState({ id: 'B' })
+ await untilWindow('B')
+ receive('B', 'B-peer') // a teammate's upsert for B, in the window
+ commit() // an autosave / switch handler in the same window
+ await until(() => !!seen.at(-1)?.state.includes('B-peer'))
+ await settle()
+ commit()
+ expectPaired()
+ expect(seen.at(-1)).toEqual({ state: ['B-node', 'B-peer'], nodes: ['B-node', 'B-peer'], epoch: 'B' })
+ expect(store).toEqual({ A: ['A-node'], B: ['B-node', 'B-peer'] })
+})
+
+// A higher-priority update in the same window: a discrete event (a click, a key) renders its
+// `setNodes(fn)` at SyncLane on top of the OUTGOING nodes — a CHANGED array under A's tag state. A
+// mirror that copied every changed array would put it into `nodesRef` under B's tag, and a commit
+// would write it into B.
+it('a discrete update in the switch window never puts the outgoing nodes under the incoming tag', async () => {
+ await mount()
+ commit()
+ useActive.setState({ id: 'B' })
+ await untilWindow('B')
+ flushSync(() => live?.setNodes((ns) => [...ns, ns[0].replace('-node', '-local')]))
+ commit()
+ await until(() => seen.at(-1)?.epoch === 'B' && !!seen.at(-1)?.state.includes('B-node'))
+ await settle()
+ expectPaired()
+ expect(seen.at(-1)).toEqual({ state: ['B-node', 'B-local'], nodes: ['B-node', 'B-local'], epoch: 'B' })
+ expect(store.B.every((n) => n.startsWith('B-'))).toBe(true)
+})
+
+// Route by the TAG, not only by the active id: a peer's op for the active project belongs on React
+// Flow only if React Flow holds that project. After a bail-out (an unknown project) the previous
+// nodes stay mounted with the tag cleared; the op must not be mixed into them.
+it('a peer op for a project whose canvas is not mounted never lands on the nodes on screen', async () => {
+ await mount()
+ commit()
+ useActive.setState({ id: 'C' }) // not in the store: the load bails out, A's nodes stay mounted
+ await until(() => seen.at(-1)?.epoch === null)
+ receive('C', 'C-peer')
+ await settle()
+ expect(seen.at(-1)?.state).toEqual(['A-node'])
+ expect(store).toEqual({ A: ['A-node'], B: ['B-node'] })
+})
+
+// The receive `setNodes` is FUNCTIONAL: it applies the op to the latest QUEUED state, not only to
+// the ref. A local edit still queued when a peer's op lands (a React Flow change mid-drag) used to be
+// overwritten by the plain value built from the last rendered array.
+it('a peer op landing while a local edit is still queued keeps both', async () => {
+ await mount()
+ live?.setNodes((ns) => [...ns, 'A-local']) // queued, not yet rendered
+ receive('A', 'A-peer') // same tick
+ await until(() => !!seen.at(-1)?.state.includes('A-peer'))
+ await settle()
+ expect(seen.at(-1)?.state).toEqual(['A-node', 'A-local', 'A-peer'])
+})
diff --git a/src/renderer/canvas/nodesEpoch.ts b/src/renderer/canvas/nodesEpoch.ts
index c08cdc563..fe65e18d6 100644
--- a/src/renderer/canvas/nodesEpoch.ts
+++ b/src/renderer/canvas/nodesEpoch.ts
@@ -15,13 +15,33 @@ import { useCallback, useRef, useState, type MutableRefObject } from 'react'
* B's `.nodeterm/project.json` — field report 2026-09-26: an SSH project's seven nodes replaced a
* local project's eighteen.
*
- * The fix is to carry the tag in React STATE beside the nodes. `setNodes(flow)` and the tag
- * update are issued together, so they share a lane: every render sees both or neither, and the
- * render-time mirror can no longer pair one project's nodes with another's id.
+ * The first fix carried the tag in React STATE beside the nodes, so a render's pair could never be
+ * split. But the mirror still copied that pair into the refs UNCONDITIONALLY, so the window render
+ * put (A's nodes, A) back into the refs right after the load effect had installed (B's nodes, B).
+ * Consistent — no commit took it — and still wrong for everything that ACTS in that window: a peer's
+ * op for B (the active project) was applied to A's array and `setNodes`'d as a plain value queued
+ * AFTER the load's, so the canvas ended on A's nodes plus the op, tagged B, and the next commit wrote
+ * them into B's file (Task 2 review, risk E).
+ *
+ * So the refs are now the LATEST pair, not the last rendered one:
+ * - the tag ref is written ONLY by `installEpoch`, synchronously, and a render never rewinds it;
+ * - a render copies its `nodes` into `nodesRef` only when that state CHANGED (a render that skipped
+ * a pending update must not undo a synchronous write — the edge refs in Canvas.tsx follow the
+ * same rule) AND the render belongs to the latest epoch (`renderedProjectId` equals the tag ref).
+ * The second condition is what a higher-priority update in the window needs: a discrete event's
+ * `setNodes(fn)` renders fn(A's nodes) under A's tag state, a CHANGED array that must not land
+ * under B's tag.
+ *
+ * `renderedProjectId` is the other half: the project THIS render's `nodes` belong to. Code that
+ * pairs the ref tag with the rendered `nodes` state (a render-time publish, an effect keyed on
+ * `nodes`) reads it instead — in the window the ref already names the incoming project while the
+ * render still shows the outgoing one.
*/
export interface NodesEpoch<N> {
nodesRef: MutableRefObject<N[]>
nodesProjectIdRef: MutableRefObject<string | null>
+ /** The project whose nodes THIS render's `nodes` state holds (null: none). For render-time pairing. */
+ renderedProjectId: string | null
/**
* Declare that `flow` — already handed to `setNodes` in the SAME tick — is `projectId`'s canvas,
* or `null` for "no project's canvas is mounted" (a bail-out). Updates the refs synchronously, so
@@ -31,17 +51,32 @@ export interface NodesEpoch<N> {
installEpoch: (projectId: string | null, flow?: N[]) => void
}
+/**
+ * The state updater for a change computed off `nodesRef`: `next` when the state it lands on is still
+ * `base` (the array the change was built from — the common case, identity kept), else `apply` run
+ * again on whatever the state has become by then. A plain `setNodes(next)` overwrote every update
+ * queued in between: a local edit not yet rendered, and — in the switch window — the load's own
+ * `setNodes(flow)`. A second guard behind the epoch refs, not a replacement for them: the adopt and
+ * the next event still build on `nodesRef`, so the ref must already be right.
+ */
+export function rebaseOnLatest<N>(base: N[], next: N[], apply: (ns: N[]) => N[]): (ns: N[]) => N[] {
+ return (ns) => (ns === base ? next : apply(ns))
+}
+
export function useNodesEpoch<N>(nodes: N[]): NodesEpoch<N> {
- const [nodesProjectId, setNodesProjectId] = useState<string | null>(null)
+ const [renderedProjectId, setRenderedProjectId] = useState<string | null>(null)
const nodesRef = useRef<N[]>(nodes)
const nodesProjectIdRef = useRef<string | null>(null)
- // Render-time mirror, as before — but of the PAIR. Both values come from the same render.
- nodesRef.current = nodes
- nodesProjectIdRef.current = nodesProjectId
+ /** The last `nodes` state copied into `nodesRef`. */
+ const mirroredRef = useRef<N[]>(nodes)
+ if (nodes !== mirroredRef.current && renderedProjectId === nodesProjectIdRef.current) {
+ mirroredRef.current = nodes
+ nodesRef.current = nodes
+ }
const installEpoch = useCallback((projectId: string | null, flow?: N[]) => {
if (flow) nodesRef.current = flow
nodesProjectIdRef.current = projectId
- setNodesProjectId(projectId)
+ setRenderedProjectId(projectId)
}, [])
- return { nodesRef, nodesProjectIdRef, installEpoch }
+ return { nodesRef, nodesProjectIdRef, renderedProjectId, installEpoch }
}
diff --git a/src/renderer/state/persistGuards.test.ts b/src/renderer/state/persistGuards.test.ts
index 7a9a39c8f..24b87d3fe 100644
--- a/src/renderer/state/persistGuards.test.ts
+++ b/src/renderer/state/persistGuards.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { canCommitCanvas, canClearDirty, canCreateOnCanvas } from './persistGuards'
+import { canCommitCanvas, canClearDirty, canCreateOnCanvas, liveCanvasHolds } from './persistGuards'
describe('canCommitCanvas', () => {
it('commits while the nodes in hand belong to the active project', () => {
@@ -69,3 +69,25 @@ describe('canClearDirty', () => {
expect(canClearDirty(0, 12)).toBe(false)
})
})
+
+describe('liveCanvasHolds', () => {
+ it('a peer op for the project React Flow holds, which is also the active one, goes live', () => {
+ expect(liveCanvasHolds('b', 'b', 'b')).toBe(true)
+ })
+
+ // Task 2 review, risk E: the store already says B while React Flow still holds A (or nothing).
+ // Applying B's op to that array mixed it into A's nodes; the next commit wrote the mix into B.
+ it('never while React Flow holds another project, or none', () => {
+ expect(liveCanvasHolds('a', 'b', 'b')).toBe(false)
+ expect(liveCanvasHolds(null, 'b', 'b')).toBe(false) // a bail-out left the old nodes mounted
+ })
+
+ // …and never for a project that is no longer active, even if its nodes are still in hand: the
+ // switch has committed them, and the load that follows replaces them — the store is the copy
+ // that survives.
+ it('never for a project that is not the active one', () => {
+ expect(liveCanvasHolds('a', 'b', 'a')).toBe(false)
+ expect(liveCanvasHolds('a', null, 'a')).toBe(false)
+ expect(liveCanvasHolds('', '', '')).toBe(false)
+ })
+})
diff --git a/src/renderer/state/persistGuards.ts b/src/renderer/state/persistGuards.ts
index a1f938ee8..8a3e6ffa1 100644
--- a/src/renderer/state/persistGuards.ts
+++ b/src/renderer/state/persistGuards.ts
@@ -39,6 +39,28 @@ export function canCreateOnCanvas(nodesProjectId: string | null, activeProjectId
return canCommitCanvas(nodesProjectId, activeProjectId)
}
+/**
+ * Does React Flow hold `projectId`'s canvas, so a peer's `canvas:mut` for it is applied LIVE? Else it
+ * goes to the project's serialized copy in the store.
+ *
+ * Same epoch pairing, third direction (Task 2 review, risk E). The receive path used to ask only
+ * "is `projectId` the active project?" — but during a switch the store already says B while React
+ * Flow still holds A (or nothing, after a bail-out), and B's op was then applied to A's array: the
+ * canvas ended on A's nodes plus the op, tagged B, and the next commit wrote them into B's file.
+ * Live only when BOTH hold: the tag says React Flow has `projectId`'s nodes, and `projectId` is the
+ * active one (a project we just switched away from was committed before the switch, and the load
+ * that follows replaces its nodes — the store is the copy that survives). The tag must be the
+ * LATEST installed epoch (`nodesProjectIdRef`, see useNodesEpoch): a tag that rewound to the
+ * previous project in a render would send the op to the store AFTER the load had already read it.
+ */
+export function liveCanvasHolds(
+ nodesProjectId: string | null,
+ activeProjectId: string | null,
+ projectId: string
+): boolean {
+ return projectId === activeProjectId && canCommitCanvas(nodesProjectId, projectId)
+}
+
/**
* May `dirty` be cleared now that a save has finished?
*