Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas): keep the project epoch tag in React state beside the nodes
enes5157ed136e38
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0e50da0d3..0e9b67ed6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -472,7 +472,14 @@ project's nodes only.** The contract:work) and latched to the first run, so switching the setting on mid-session never reaches intostorage and locks a canvas somebody is working on.- Before any project switch / add / delete, `commitActiveToStore()` serializes the live- React Flow nodes back into the store, so nothing is lost. Then disk is written.+ React Flow nodes back into the store, so nothing is lost. Then disk is written. The commit is+ guarded by the epoch tag `nodesProjectIdRef` (`canCommitCanvas`), and **that tag must live in+ React STATE beside the nodes** (`canvas/nodesEpoch.ts`), never in a ref alone: the load effect's+ `setNodes(flow)` is a DefaultLane update, every zustand write after it is a SyncLane re-render+ that skips it, and the render-time `nodesRef` mirror then paired the PREVIOUS project's nodes+ 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).- Switching away unmounts the old project's `TerminalNode`s → their tmux clients detach butthe sessions keep running; switching back reattaches. tmux session names are per-node-id(globally unique), so projects never collide.diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 237a224c6..a0d93ddc6 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -547,6 +547,7 @@ 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 { isHidden } from '../lib/ui-visibility'import { boardLogEvents } from '../lib/boardLogDiff'import { useBoardLog } from '../state/boardLog'@@ -1506,14 +1507,16 @@ export function Canvas() {clearModels])const viewportRef = useRef<Viewport>({ x: 0, y: 0, zoom: 1 })- const nodesRef = useRef<CanvasNode[]>(nodes)/**- * WHICH project's nodes `nodesRef` currently holds — the epoch tag that pairs with- * `activeProjectId` (see canCommitCanvas). Written only where the load effect installs a- * project's nodes, and invalidated (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.+ * `nodesRef` mirrors the live node array; `nodesProjectIdRef` says WHICH project's nodes it holds+ * — the epoch tag that pairs with `activeProjectId` (see canCommitCanvas). Both are mirrored from+ * React state as ONE pair (useNodesEpoch): the tag used to be a ref written only by the load+ * effect, and a SyncLane re-render between that effect and its `setNodes` landing re-mirrored the+ * PREVIOUS project's nodes under the NEW project's tag (field bug 2026-09-26). Installed by the+ * 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 nodesProjectIdRef = useRef<string | null>(null)+ const { nodesRef, nodesProjectIdRef, 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@@ -1715,7 +1718,6 @@ export function Canvas() {/** The active project runs on a remote host → every worktree affordance is off (see* WORKTREE_SSH_HINT). Reactive, so the menus rebuild when the user switches projects. */const isSshProject = !!activeSshServer- nodesRef.current = nodes/*** ONE confirm dialog at a time — mirrored into a ref so the []-dep agent-control effect sees the* CURRENT dialogs (it closes over a stale `confirm`).@@ -2565,12 +2567,12 @@ export function Canvas() {// Both bail-outs below leave the PREVIOUS project's nodes mounted in React Flow. Invalidate the// epoch tag on the way out so nothing commits them under the new id (field bug 2026-08-10).if (!activeProjectId) {- nodesProjectIdRef.current = null+ installEpoch(null)return}const project = useProjects.getState().getProject(activeProjectId)if (!project) {- nodesProjectIdRef.current = null+ installEpoch(null)return}// SSH project: (re)open its ControlMaster and record the controlPath so this project's@@ -2642,11 +2644,11 @@ export function Canvas() {)setNodes(flow)// React Flow now holds THIS project's canvas: the commit guard may pair it with the active id- // again. Both refs are assigned HERE, synchronously, because `setNodes` only lands on the next- // render — mirroring the nodes (same idiom as the peer-mutation path) keeps the array and its- // epoch tag atomic, so no timer firing in between can commit the previous project's nodes.- nodesRef.current = flow- nodesProjectIdRef.current = project.id+ // again. installEpoch assigns both refs HERE, synchronously, because `setNodes` only lands on a+ // later render — and queues the tag as STATE in the same lane as that `setNodes`, so a SyncLane+ // re-render in between (any store write below) mirrors the old nodes WITH the old tag instead+ // of pairing them with this project's id. See useNodesEpoch.+ installEpoch(project.id, flow)// Worktree facts are per project: drop the previous project's (reset also clears its// statuses), then re-resolve from this project's cwd. SSH projects are skipped — local git// cannot reason about a remote path. Fire-and-forget: the store is epoch-guarded + fails open.@@ -2749,7 +2751,7 @@ export function Canvas() {}, 0)return () => clearTimeout(t)// eslint-disable-next-line react-hooks/exhaustive-deps- }, [activeProjectId, reloadNonce, setNodes, setViewport])+ }, [activeProjectId, reloadNonce, setNodes, setViewport, installEpoch])// Keep-alive pool hygiene: a PERMANENTLY deleted project's ghosts must die now, not at the next// switch (an invisible page is still a live Chromium process). Keyed on the id signature — thediff --git a/src/renderer/canvas/nodesEpoch.test.tsx b/src/renderer/canvas/nodesEpoch.test.tsxnew file mode 100644index 000000000..fcdaa4858--- /dev/null+++ b/src/renderer/canvas/nodesEpoch.test.tsx@@ -0,0 +1,85 @@+// @vitest-environment jsdom+import { useEffect, useState } from 'react'+import { createRoot } from 'react-dom/client'+import { create } from 'zustand'+import { afterEach, expect, it } from 'vitest'+import { useNodesEpoch } from './nodesEpoch'++// 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+// DefaultLane `setNodes(flowB)` landed. That render mirrored the OLD `nodes` state into `nodesRef`+// 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.++const useActive = create<{ id: string | null }>(() => ({ id: 'A' }))+const useOther = create<{ n: number }>(() => ({ n: 0 }))++interface Seen { nodes: string[]; epoch: string | null }+let seen: Seen[] = []+let root: ReturnType<typeof createRoot> | 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 })+ useEffect(() => {+ if (!active) {+ installEpoch(null)+ useOther.setState((s) => ({ n: s.n + 1 }))+ return+ }+ const flow = [`${active}-node`]+ setNodes(flow)+ installEpoch(active, flow)+ // Canvas subscribes to stores its load effect writes; each write is a SyncLane re-render.+ useOther.setState((s) => ({ n: s.n + 1 }))+ }, [active, installEpoch])+ return null+}++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)+}++async function mount() {+ useActive.setState({ id: 'A' })+ const el = document.createElement('div')+ root = createRoot(el)+ root.render(<Canvas />)+ await until(() => seen.at(-1)?.epoch === 'A' && seen.at(-1)?.nodes[0] === 'A-node')+ seen = []+}++afterEach(() => {+ root?.unmount()+ root = 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`])+ }+}++it('never pairs the previous project nodes with the incoming project epoch', async () => {+ await mount()+ useActive.setState({ id: 'B' })+ await until(() => seen.at(-1)?.epoch === 'B')+ await settle()+ expectPaired()+ expect(seen.at(-1)).toEqual({ nodes: ['B-node'], epoch: 'B' })+})++it('keeps the tag cleared after a bail-out (welcome screen) instead of re-mirroring the old project', async () => {+ await mount()+ useActive.setState({ id: null })+ await until(() => seen.length > 1)+ await settle()+ expect(seen.at(-1)?.epoch).toBeNull()+})diff --git a/src/renderer/canvas/nodesEpoch.ts b/src/renderer/canvas/nodesEpoch.tsnew file mode 100644index 000000000..c08cdc563--- /dev/null+++ b/src/renderer/canvas/nodesEpoch.ts@@ -0,0 +1,47 @@+import { useCallback, useRef, useState, type MutableRefObject } from 'react'++/**+ * React Flow's live node array and the project it belongs to, mirrored into refs as ONE pair.+ *+ * `nodesProjectIdRef` is the epoch tag `canCommitCanvas` checks before any commit writes the+ * live canvas into a project. It used to be a plain ref written only by the load effect, while+ * `nodesRef` was re-mirrored from `nodes` STATE on every render. The load effect sets both refs+ * synchronously and calls `setNodes(flow)` — a DefaultLane update, because it is issued from a+ * passive effect — and then writes zustand stores Canvas subscribes to (worktrees reset, the+ * keep-alive pool, …). Each such write is a SyncLane re-render, and a SyncLane render SKIPS the+ * pending DefaultLane `setNodes`: it rendered the PREVIOUS project's nodes and mirrored them into+ * `nodesRef` while the tag already named the incoming project. Any commit in that window+ * (a switch/close handler, an autosave) passed the guard and wrote project A's nodes into project+ * 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.+ */+export interface NodesEpoch<N> {+ nodesRef: MutableRefObject<N[]>+ nodesProjectIdRef: MutableRefObject<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+ * a commit before the next render already sees the new pair, and queues the tag state so every+ * later render agrees with it.+ */+ installEpoch: (projectId: string | null, flow?: N[]) => void+}++export function useNodesEpoch<N>(nodes: N[]): NodesEpoch<N> {+ const [nodesProjectId, setNodesProjectId] = 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+ const installEpoch = useCallback((projectId: string | null, flow?: N[]) => {+ if (flow) nodesRef.current = flow+ nodesProjectIdRef.current = projectId+ setNodesProjectId(projectId)+ }, [])+ return { nodesRef, nodesProjectIdRef, installEpoch }+}