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): resolve node creation against the live active project, not a render closure (#443)
enesdabdfe674256
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 49f76fb64..7b4f3272d 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -399,7 +399,7 @@ import type { KanbanCreateChoice, KanbanSession } from '../components/kanban/Kanimport { assignNode, assignedTo, defaultKanban, labelsForCard, migrateProjectTags, resolveColumnRef, unassigned } from '../lib/kanban'import { registerWorkspaceDirty } from '../state/workspaceDirty'import { snapNodeToGrid } from '../lib/nodeSizing'-import { canClearDirty, canCommitCanvas } from '../state/persistGuards'+import { canClearDirty, canCommitCanvas, canCreateOnCanvas } from '../state/persistGuards'import { isHidden } from '../lib/ui-visibility'import { boardLogEvents } from '../lib/boardLogDiff'import { useBoardLog } from '../state/boardLog'@@ -3281,8 +3281,24 @@ export function Canvas() {/** Force the working directory (e.g. a Source Control action running in a worktree scope). */cwdOverride?: string) => {- const project = useProjects.getState().getProject(activeProjectId)+ // Live read + epoch guard: same rule as addAgentNode (issue #443) — a menu closure built+ // under the previous project must not root a terminal in that project's folder.+ const targetProjectId = useProjects.getState().activeProjectId+ if (!canCreateOnCanvas(nodesProjectIdRef.current, targetProjectId)) {+ console.warn(+ `[nodeterm] node-create refused: canvas holds ${nodesProjectIdRef.current ?? 'nothing'} but the active project is ${targetProjectId || 'none'}`+ )+ setNotice({+ kind: 'error',+ text: 'Could not create the node: the canvas on screen is not the active project’s. Switch tabs once and try again.'+ })+ return+ }+ const project = useProjects.getState().getProject(targetProjectId)const cwd = cwdOverride ?? cwdForNewNodeIn(groupId) ?? project?.cwd+ console.info(+ `[nodeterm] node-create agent=- project=${targetProjectId} group=${groupId ?? '-'} cwd=${cwd ?? '-'}`+ )setNodes((ns) => {// In an SSH project the node is stamped remote (runs over the project's master); the// factory takes the project's ssh and roots the terminal at its remoteCwd.@@ -3291,7 +3307,7 @@ export function Canvas() {})markDirty()},- [setNodes, markDirty, activeProjectId, emptyNodePos, cwdForNewNodeIn, parentInto]+ [setNodes, markDirty, emptyNodePos, cwdForNewNodeIn, parentInto])/** Open a new terminal that runs a command on start (e.g. gh auth login). `cwd` lets a caller@@ -3694,7 +3710,19 @@ export function Canvas() {* the `git show` it is told to run inspects the checkout the commit was read from. */const explainCommit = useCallback((prompt: string, scopeCwd?: string) => {- const project = useProjects.getState().getProject(activeProjectId)+ // Live read + epoch guard, like every other creation funnel (issue #443).+ const targetProjectId = useProjects.getState().activeProjectId+ if (!canCreateOnCanvas(nodesProjectIdRef.current, targetProjectId)) {+ console.warn(+ `[nodeterm] node-create refused: canvas holds ${nodesProjectIdRef.current ?? 'nothing'} but the active project is ${targetProjectId || 'none'}`+ )+ setNotice({+ kind: 'error',+ text: 'Could not create the node: the canvas on screen is not the active project’s. Switch tabs once and try again.'+ })+ return+ }+ const project = useProjects.getState().getProject(targetProjectId)const account = resolveNewNodeAccount(undefined,project,@@ -3715,12 +3743,12 @@ export function Canvas() {activePermissionMode(),// The owning project, for its own `.nodeterm/settings.json` launch command — the same// project the account/cwd above are resolved from.- activeProjectId+ targetProjectId)])markDirty()},- [setNodes, markDirty, activeProjectId, viewCenter, scmCwd]+ [setNodes, markDirty, viewCenter, scmCwd])/** Pick a file via the native dialog and open it as an editor node. */@@ -3736,7 +3764,10 @@ export function Canvas() {* open it as an editor node. SSH projects create on the remote host. */const newProjectFile = useCallback(async (center?: { x: number; y: number }) => {- const project = useProjects.getState().getProject(activeProjectId ?? '')+ // Live read (issue #443): this is reachable from the sessions-sidebar "+" menu, whose+ // closures were built under the PREVIOUS active project — a closure id here would create+ // the file inside that project's folder.+ const project = useProjects.getState().getProject(useProjects.getState().activeProjectId)const cwd = project?.ssh?.remoteCwd ?? project?.cwdif (!project || !cwd) returnconst name = await promptDialog({@@ -3764,7 +3795,7 @@ export function Canvas() {}openFile(dest, center, !!project.ssh)},- [activeProjectId, openFile]+ [openFile])/** Open the clone dialog; project creation happens in onRepoCloned below. */@@ -3958,7 +3989,24 @@ export function Canvas() {accountId?: string | null,initialPrompt?: string) => {- const project = useProjects.getState().getProject(activeProjectId)+ // Resolve the target project LIVE, at click time — never from this callback's render+ // closure. Menu onClick closures outlive the render that built them (`setMenu` freezes+ // them into state), and the sessions-sidebar "+" deliberately switches projects before+ // opening that menu — a closure id there is the PREVIOUS project, whose cwd / account /+ // launch command would be stamped onto a node inserted into the NEW project's canvas+ // (issue #443: "New Codex opened in a different project's folder").+ const targetProjectId = useProjects.getState().activeProjectId+ if (!canCreateOnCanvas(nodesProjectIdRef.current, targetProjectId)) {+ console.warn(+ `[nodeterm] node-create refused: canvas holds ${nodesProjectIdRef.current ?? 'nothing'} but the active project is ${targetProjectId || 'none'}`+ )+ setNotice({+ kind: 'error',+ text: 'Could not create the node: the canvas on screen is not the active project’s. Switch tabs once and try again.'+ })+ return+ }+ const project = useProjects.getState().getProject(targetProjectId)const cwd = cwdForNewNodeIn(groupId) ?? project?.cwd// Codex accounts (S6) resolve through their OWN fail-closed gate: an explicitly picked account// that is missing/hostile/unconnected is REFUSED here rather than silently downgraded to the@@ -3991,6 +4039,11 @@ export function Canvas() {useSettings.getState().settings.claudeAccounts)}+ // The spawn triple, so the NEXT #443-shaped report is diagnosable: which project the node+ // was charged to, which frame resolved its cwd, and what cwd it will actually run in.+ console.info(+ `[nodeterm] node-create agent=${agentId} project=${targetProjectId} group=${groupId ?? '-'} cwd=${cwd ?? '-'}`+ )setNodes((ns) => {const node = createAgentNode(agentId,@@ -4003,7 +4056,7 @@ export function Canvas() {activePermissionMode(agentId),// Same funnel as the account above: the active project owns the node, so its own// `.nodeterm/settings.json` launch command layers over the global one.- activeProjectId+ targetProjectId)return [...ns, groupId ? parentInto(node, groupId) : node]})@@ -4012,7 +4065,6 @@ export function Canvas() {[setNodes,markDirty,- activeProjectId,emptyNodePos,cwdForNewNodeIn,parentInto,@@ -7486,7 +7538,21 @@ export function Canvas() {// list until the next render, and a pruned commit would strip the assignment right back off.const createNodeInColumn = useCallback((choice: KanbanCreateChoice, columnId: string | null) => {- const project = useProjects.getState().getProject(activeProjectId)+ // Live read + epoch guard, like addAgentNode/addTerminal (issue #443): board cards are the+ // active project's sessions, so a board-created node must be charged to the project whose+ // canvas React Flow actually holds under the overlay.+ const targetProjectId = useProjects.getState().activeProjectId+ if (!canCreateOnCanvas(nodesProjectIdRef.current, targetProjectId)) {+ console.warn(+ `[nodeterm] node-create refused: canvas holds ${nodesProjectIdRef.current ?? 'nothing'} but the active project is ${targetProjectId || 'none'}`+ )+ setNotice({+ kind: 'error',+ text: 'Could not create the node: the canvas on screen is not the active project’s. Switch tabs once and try again.'+ })+ return+ }+ const project = useProjects.getState().getProject(targetProjectId)const index = nodesRef.current.lengthconst at = emptyNodePos() // board has no cursor — drop it in free canvas space, not on a pileconst node =@@ -7510,12 +7576,12 @@ export function Canvas() {),activePermissionMode(choice.agentId),// Board-created nodes belong to the active project like any other.- activeProjectId+ targetProjectId)setNodes((ns) => [...ns, node])const board = project?.kanban ?? seedBoardif (columnId) {- useProjects.getState().setProjectKanban(activeProjectId, assignNode(board, node.id, columnId, null))+ useProjects.getState().setProjectKanban(targetProjectId, assignNode(board, node.id, columnId, null))}markDirty()// Log card-created directly here — the assignment above is written straight to the store@@ -7535,13 +7601,13 @@ export function Canvas() {?.label ??choice.agentIdconst title = (node.data.title as string) || kindLabel- useBoardLog.getState().append(api, activeProjectId, {+ useBoardLog.getState().append(api, targetProjectId, {kind: 'event',nodeId: node.id,event: { type: 'card-created', to: toName, title }})},- [activeProjectId, emptyNodePos, setNodes, markDirty, seedBoard, api]+ [emptyNodePos, setNodes, markDirty, seedBoard, api])// Delete a session from the board — same confirm + teardown as the canvas Delete key.@@ -9648,17 +9714,23 @@ export function Canvas() {// The sessions-sidebar project-header "+": opens the SAME content menu the pane right-click// uses (terminal + agents + browser/web/sticky/dino/file/worktree), so adding to a project from// the sidebar is no longer a bare-terminal-only affordance that lags the canvas menu. For a- // non-active project, switch FIRST (synchronous) so the menu's account rows resolve against the- // clicked project; the node is only added on the user's later click, well after that project's- // canvas has loaded, so there is no load-race.+ // non-active project it switches FIRST — see the closure caution inside (issue #443).const addToProject = useCallback((projectId: string, e?: { clientX: number; clientY: number }) => {// The sessions-sidebar "+" used to open a bare terminal. It now opens the SAME content menu// the pane right-click uses (terminal + agents + browser/web/sticky/dino/file/worktree), so// adding to a project from the sidebar is no longer a bare-terminal-only affordance that// lags the canvas menu. For a non-active project, switch FIRST (synchronous) so the menu's- // account rows resolve against the clicked project; the node is only added on the user's- // later click, well after that project's canvas has loaded, so there is no load-race.+ // account rows resolve against the clicked project.+ //+ // CAUTION: the menu items built below are closures from THIS render — the one where the+ // OLD project was still active — frozen into `setMenu` state. "The node is only added on the+ // user's later click" protects nothing on its own: a creation callback that closed over the+ // render's `activeProjectId` would still charge the node to the old project (its cwd, its+ // account default, its launch command) while inserting it into the new project's canvas.+ // That was issue #443 ("New Codex opened in a different project's folder"). The rule that+ // actually holds: every creation callback reachable from a frozen menu resolves the active+ // project LIVE (`useProjects.getState()`) at click time, guarded by `canCreateOnCanvas`.if (projectId !== activeProjectId) switchProject(projectId)const pos = e ? { x: e.clientX, y: e.clientY } : { x: 80, y: 120 }const [terminalItem, ...restContent] = contentAddItemsToMenuItems(diff --git a/src/renderer/canvas/canvas-wiring.test.tsx b/src/renderer/canvas/canvas-wiring.test.tsxindex fa33fde0c..68d269a9b 100644--- a/src/renderer/canvas/canvas-wiring.test.tsx+++ b/src/renderer/canvas/canvas-wiring.test.tsx@@ -218,3 +218,48 @@ describe('reopen-last-closed records and dispatches through the shared history sexpect(CANVAS_SRC).toContain("case 'reopenProject':")})})++describe('node creation resolves its project LIVE and only onto a matching canvas (issue #443)', () => {+ // The bug this pins: the sessions-sidebar "+" switches projects and THEN opens the creation+ // menu, whose onClick closures were built under the PREVIOUS render and frozen into setMenu+ // state. A creation callback that closed over that render's `activeProjectId` charged the new+ // node to the OLD project — its cwd, its account default, its `.nodeterm/settings.json` launch+ // command — while inserting it into the NEW project's canvas. For an agent session that is+ // silent read/write access to the wrong repo. The rule: every creation funnel reads the active+ // project from the store AT CLICK TIME and pairs it with the canvas epoch tag before creating.+ it('reads the active project from the store at call time in every creation funnel', () => {+ const liveReads =+ CANVAS_SRC.match(/const targetProjectId = useProjects\.getState\(\)\.activeProjectId/g) ?? []+ // addAgentNode, addTerminal, createNodeInColumn, explainCommit.+ expect(liveReads.length).toBe(4)+ })++ it('guards every creation funnel with canCreateOnCanvas against the canvas epoch tag', () => {+ const guards =+ CANVAS_SRC.match(/canCreateOnCanvas\(nodesProjectIdRef\.current, targetProjectId\)/g) ?? []+ expect(guards.length).toBe(4)+ })++ it('refuses a mismatch loudly — a dead click with no message is how #443 stayed undiagnosable', () => {+ expect(CANVAS_SRC).toContain('node-create refused: canvas holds')+ expect(CANVAS_SRC).toContain(+ 'the canvas on screen is not the active project’s. Switch tabs once and try again.'+ )+ })++ it('logs the spawn triple (project, group, cwd) so the next report is diagnosable', () => {+ const logs = CANVAS_SRC.match(/\[nodeterm\] node-create agent=/g) ?? []+ // addAgentNode + addTerminal.+ expect(logs.length).toBeGreaterThanOrEqual(2)+ })++ it('resolves the created node\'s project record from the live target id, never the closure', () => {+ // The exact stale read the bug shipped with: `getProject(activeProjectId)` inside a creation+ // funnel, where `activeProjectId` is the RENDER's value. Every creation funnel now pairs its+ // guard with `getProject(targetProjectId)`; a reintroduced closure read would bring #443 back+ // with the whole suite green.+ const liveRecordReads =+ CANVAS_SRC.match(/const project = useProjects\.getState\(\)\.getProject\(targetProjectId\)/g) ?? []+ expect(liveRecordReads.length).toBe(4)+ })+})diff --git a/src/renderer/state/persistGuards.test.ts b/src/renderer/state/persistGuards.test.tsindex 018686b4c..7a9a39c8f 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 } from './persistGuards'+import { canCommitCanvas, canClearDirty, canCreateOnCanvas } from './persistGuards'describe('canCommitCanvas', () => {it('commits while the nodes in hand belong to the active project', () => {@@ -27,6 +27,31 @@ describe('canCommitCanvas', () => {})})+describe('canCreateOnCanvas', () => {+ it('creates while the canvas on screen belongs to the active project', () => {+ expect(canCreateOnCanvas('a', 'a')).toBe(true)+ })++ // Issue #443: the store already says B (a tab switch, or a bailed load effect that left the+ // previous nodes mounted) while A's canvas is what the user sees. Creating here would insert+ // the node into A's canvas but stamp B's cwd / account default / launch command onto it — for+ // an agent session that is silent write access to the wrong repo. Refuse (the caller says so+ // loudly); never resolve the project from ambient state that disagrees with the screen.+ it('refuses to create while the canvas shows a different project than the active one', () => {+ expect(canCreateOnCanvas('a', 'b')).toBe(false)+ })++ // Before the first load effect, or after a bailed one, React Flow's nodes belong to NO project.+ it('refuses to create before any project canvas is installed', () => {+ expect(canCreateOnCanvas(null, 'a')).toBe(false)+ })++ it('refuses to create with no active project', () => {+ expect(canCreateOnCanvas('a', '')).toBe(false)+ expect(canCreateOnCanvas(null, '')).toBe(false)+ })+})+describe('canClearDirty', () => {it('clears dirty when nothing changed while the save was in flight', () => {expect(canClearDirty(7, 7)).toBe(true)diff --git a/src/renderer/state/persistGuards.ts b/src/renderer/state/persistGuards.tsindex 290521b7e..a1f938ee8 100644--- a/src/renderer/state/persistGuards.ts+++ b/src/renderer/state/persistGuards.ts@@ -23,6 +23,22 @@ export function canCommitCanvas(nodesProjectId: string | null, activeProjectId:return nodesProjectId === activeProjectId}+/**+ * May a node be created on the canvas right now, charged to `activeProjectId`?+ *+ * Same epoch pairing as `canCommitCanvas`, opposite direction (issue #443): node creation resolves+ * cwd / account default / launch-command project from the ACTIVE project record, and inserts the+ * node into whatever React Flow is showing. If the two disagree — the store already says B while+ * A's nodes are still (or permanently: a bailed load effect) on screen — the node would come up on+ * A's canvas but RUN in B's folder under B's account and launch command. For an agent session that+ * is silent wrong-repo write access, so unlike the commit guard the caller must refuse LOUDLY+ * (notice + console), never skip silently: a create is a user gesture, and a dead click with no+ * message is how #443 stayed undiagnosable.+ */+export function canCreateOnCanvas(nodesProjectId: string | null, activeProjectId: string): boolean {+ return canCommitCanvas(nodesProjectId, activeProjectId)+}+/*** May `dirty` be cleared now that a save has finished?*