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: address final review findings — commitActiveToStore, armForColdOpen, target permission mode, testable reopen planner, ShortcutsSection filter

Mina Sameh3917de6b98c0
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 4af8ae227..803ec1bb5 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -348,6 +348,7 @@ import { freeSpot } from '../lib/placement'
import { pushSessionRename } from '../lib/sessionRename'
import { useReopenHistory } from '../state/reopenHistory'
import { snapshotNode, recreateNodeFromSnapshot } from '../lib/reopenNode'
+import { planReopen } from '../lib/reopenPlan'
import { oneLine } from '@shared/one-line'
import { parseLenses, verifyLensPrompt, verifySynthesisPrompt } from '../lib/verifyPanel'
import { useSettings } from '../state/settings'
@@ -5700,62 +5701,77 @@ export function Canvas() {
/** `app.reopenLastClosed` (Cmd+Shift+T): pops the shared close-history stack and reopens a
* project tab or recreates a deleted node batch — whichever was closed more recently.
* Skips stale entries (already reopened another way, or the project was permanently
- * deleted since) and keeps walking back until it finds a usable one or the stack empties. */
+ * deleted since) and keeps walking back until it finds a usable one or the stack empties.
+ * The DECISION (which branch, staleness, active-vs-stored) is the pure `planReopen`
+ * (`lib/reopenPlan.ts`, unit-tested there); this loop only pops the real stack and executes
+ * whichever `ReopenPlan` comes back — the side-effecting parts that need live Canvas state. */
const reopenLastClosedCommand = useCallback((): boolean => {
for (;;) {
const entry = useReopenHistory.getState().popNext()
if (!entry) return false
- if (entry.kind === 'project') {
- const project = useProjects.getState().projects.find((p) => p.id === entry.projectId)
- if (project?.closed) {
- useProjects.getState().reopenProject(entry.projectId)
- return true
- }
- continue
- }
-
- const project = useProjects.getState().projects.find((p) => p.id === entry.projectId)
- if (!project) continue
-
- const isActive = project.id === useProjects.getState().activeProjectId
+ const { projects, activeProjectId } = useProjects.getState()
+ const project = projects.find((p) => p.id === entry.projectId)
const accounts = useSettings.getState().settings.claudeAccounts
- const liveIds = new Set(
- (isActive ? nodesRef.current : project.nodes).map((n) => n.id)
- )
- const created = entry.nodes
- .map((snap) =>
+ const plan = planReopen(
+ entry,
+ projects,
+ activeProjectId,
+ new Set(nodesRef.current.map((n) => n.id)),
+ (snap, liveIds) =>
recreateNodeFromSnapshot(snap, {
liveNodeIds: liveIds,
project,
resolveAccountId: (id) => resolveNewNodeAccount(id, project, accounts),
- permissionModeFor: (agentId) => activePermissionMode(agentId)
+ // The TARGET project's own permission mode, not the caller's active one — a node
+ // restored into project B must start under B's override, never A's.
+ permissionModeFor: (agentId) => projectPermissionMode(project, agentId)
})
- )
- .filter((n): n is CanvasNode => n !== null)
- // A snapshot that recreated to nothing (e.g. a kind this feature doesn't cover, or an
- // editor whose filePath is somehow missing) leaves this entry with nothing to do — treat
- // it as stale rather than switching/reopening a project for an empty result.
- if (!created.length) continue
-
- if (isActive) {
- setNodes((ns) => [...ns, ...created])
- markDirty()
- } else {
- // Not on screen: write straight into the project's SERIALIZED nodes (the store, not
- // React Flow) — the same mechanism canvas-control uses to create a node in a
- // non-active project (Canvas.tsx:6499, :6540). The switch/reopen below then loads
- // them through the ordinary active-project effect; there is no live array to race.
- for (const node of created) {
- useProjects.getState().applyNodeMutation(project.id, { op: 'upsert', node: flowToNodeStates([node])[0] })
- }
- void writeDisk()
- if (project.closed) useProjects.getState().reopenProject(project.id)
- else switchProject(project.id)
+ )
+
+ switch (plan.action) {
+ case 'skip':
+ continue
+ case 'reopenProject':
+ // A project switch — commit the live canvas back to the store first, or whatever the
+ // user was looking at is silently lost (the same invariant every other project switch/
+ // add/delete in this file honors via commitActiveToStore()).
+ commitActiveToStore()
+ useProjects.getState().reopenProject(plan.projectId)
+ setWelcomeOpen(false)
+ void writeDisk()
+ return true
+ case 'insertActive':
+ setNodes((ns) => [...ns, ...plan.nodes])
+ markDirty()
+ return true
+ case 'insertStored':
+ // Not on screen: write straight into the project's SERIALIZED nodes (the store, not
+ // React Flow) — the same mechanism canvas-control uses to create a node in a
+ // non-active project (Canvas.tsx:6499, :6540). armForColdOpen is required here: a bare
+ // `flowToNodeStates` drops `initialCommand` (never serialized on purpose), so an agent
+ // node restored this way would never launch its command on the eventual cold open.
+ for (const node of plan.nodes) {
+ useProjects
+ .getState()
+ .applyNodeMutation(plan.projectId, {
+ op: 'upsert',
+ node: flowToNodeStates([armForColdOpen(node)])[0]
+ })
+ }
+ void writeDisk()
+ if (plan.reopenProjectAfter) {
+ commitActiveToStore()
+ useProjects.getState().reopenProject(plan.projectId)
+ setWelcomeOpen(false)
+ void writeDisk()
+ } else {
+ switchProject(plan.projectId)
+ }
+ return true
}
- return true
}
- }, [switchProject, setNodes, markDirty, writeDisk])
+ }, [switchProject, setNodes, markDirty, writeDisk, commitActiveToStore])
// ---- global shortcuts ----
// The three trailing gestures below are registry-LESS chords (design D2: declared gestures,
diff --git a/src/renderer/canvas/canvas-wiring.test.tsx b/src/renderer/canvas/canvas-wiring.test.tsx
index 021456b4b..4ebbb9bb6 100644
--- a/src/renderer/canvas/canvas-wiring.test.tsx
+++ b/src/renderer/canvas/canvas-wiring.test.tsx
@@ -144,8 +144,36 @@ describe('reopen-last-closed records and dispatches through the shared history s
it('never live-inserts into a non-active project — routes through applyNodeMutation instead', () => {
// The bug this pins: a synchronous setNodes() right after switchProject()/reopenProject()
// races the active-project load effect and silently loses the recreated nodes.
- expect(CANVAS_SRC).toContain(
- "useProjects.getState().applyNodeMutation(project.id, { op: 'upsert', node: flowToNodeStates([node])[0] })"
- )
+ expect(CANVAS_SRC).toContain('.applyNodeMutation(plan.projectId, {')
+ })
+
+ it('arms a cold-open command before writing a restored node into a non-active project', () => {
+ // The bug this pins: flowToNodeStates alone drops initialCommand, so an agent node restored
+ // into a project that isn't on screen would never launch its command on the eventual cold
+ // open — armForColdOpen is what carries it through serialization.
+ expect(CANVAS_SRC).toContain('node: flowToNodeStates([armForColdOpen(node)])[0]')
+ })
+
+ it('commits the live canvas to the store before every reopenProject call — never a bare switch', () => {
+ // The bug this pins: useProjects.getState().reopenProject(...) is a project SWITCH, and every
+ // switch/add/delete elsewhere in this file calls commitActiveToStore() first so the live
+ // canvas isn't silently lost. Both reopen-a-project call sites inside reopenLastClosedCommand
+ // must do the same, rather than referencing the later `reopenProject` wrapper (a TDZ hazard
+ // from this callback's declaration point).
+ const calls = CANVAS_SRC.match(/useProjects\.getState\(\)\.reopenProject\(/g) ?? []
+ const guarded = CANVAS_SRC.match(/commitActiveToStore\(\)\n\s+useProjects\.getState\(\)\.reopenProject\(/g) ?? []
+ expect(calls.length).toBeGreaterThanOrEqual(2)
+ expect(guarded.length).toBe(calls.length)
+ })
+
+ it('resolves permission mode against the TARGET project being restored into, not the caller\'s active one', () => {
+ expect(CANVAS_SRC).toContain('permissionModeFor: (agentId) => projectPermissionMode(project, agentId)')
+ })
+
+ it('extracts the reopen decision into the pure, tested planReopen', () => {
+ expect(CANVAS_SRC).toContain('const plan = planReopen(')
+ expect(CANVAS_SRC).toContain("case 'insertActive':")
+ expect(CANVAS_SRC).toContain("case 'insertStored':")
+ expect(CANVAS_SRC).toContain("case 'reopenProject':")
})
})
diff --git a/src/renderer/components/settings/sections/ShortcutsSection.test.tsx b/src/renderer/components/settings/sections/ShortcutsSection.test.tsx
index 30d49368b..9306f3238 100644
--- a/src/renderer/components/settings/sections/ShortcutsSection.test.tsx
+++ b/src/renderer/components/settings/sections/ShortcutsSection.test.tsx
@@ -157,14 +157,17 @@ describe('ShortcutsSection rows', () => {
// body is `divide-y [&>*]:py-5`, so an empty wrapper is a visible empty block, not nothing.
it('drops a whole group when neither its header nor any of its rows match', () => {
render('close')
- expect([...host.querySelectorAll('h3')].map((h) => h.textContent)).toEqual(['Nodes'])
- expect(ids()).toEqual(['node.close'])
- // Exactly the policy row (its description names Close) and the ONE group wrapper holding the
- // heading + its row — no empty siblings. The rail is a searchable row of its own and 'close'
- // does not match it, so it is gone too.
+ // `app.reopenLastClosed`'s title "Reopen last closed" also matches 'close', so its group
+ // (General) now survives the filter too — General's group order precedes Nodes in the
+ // registry, matching the h3 order.
+ expect([...host.querySelectorAll('h3')].map((h) => h.textContent)).toEqual(['General', 'Nodes'])
+ expect(ids()).toEqual(['app.reopenLastClosed', 'node.close'])
+ // Exactly the policy row (its description names Close) and the TWO group wrappers (General,
+ // holding `app.reopenLastClosed`; Nodes, holding `node.close`) — no empty siblings. The rail
+ // is a searchable row of its own and 'close' does not match it, so it is gone too.
expect(pill()).toBeTruthy()
expect(statusPill()).toBeNull()
- expect(body().children).toHaveLength(2)
+ expect(body().children).toHaveLength(3)
expect([...body().children].every((c) => (c.textContent ?? '').trim() !== '')).toBe(true)
})
diff --git a/src/renderer/lib/reopenPlan.test.ts b/src/renderer/lib/reopenPlan.test.ts
new file mode 100644
index 000000000..b5f1289dd
--- /dev/null
+++ b/src/renderer/lib/reopenPlan.test.ts
@@ -0,0 +1,199 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { planReopen, type PlanReopenProject } from './reopenPlan'
+import { useReopenHistory } from '@renderer/state/reopenHistory'
+import type { ReopenNodeSnapshot } from './reopenNode'
+import type { CanvasNode } from '@renderer/state/workspace'
+
+const snap = (over: Partial<ReopenNodeSnapshot> = {}): ReopenNodeSnapshot => ({
+ type: 'sticky',
+ position: { x: 0, y: 0 },
+ absolutePosition: { x: 0, y: 0 },
+ data: { title: 'Note', color: '#ffd60a', group: null },
+ ...over
+})
+
+const node = (id: string): CanvasNode =>
+ ({ id, type: 'sticky', position: { x: 0, y: 0 }, data: { title: 'Note', color: '#ffd60a', group: null } }) as CanvasNode
+
+/** A `recreate` stand-in that always succeeds, tagging each output node with a counter so a
+ * multi-node batch is distinguishable in assertions. */
+function alwaysRecreates(): (s: ReopenNodeSnapshot) => CanvasNode | null {
+ let n = 0
+ return () => node(`recreated-${n++}`)
+}
+
+const neverRecreates = () => null
+
+beforeEach(() => {
+ useReopenHistory.setState({ stack: [] })
+})
+
+describe('planReopen', () => {
+ it('reopens a still-closed project', () => {
+ const projects: PlanReopenProject[] = [{ id: 'p1', closed: true, nodes: [] }]
+ const plan = planReopen(
+ { kind: 'project', projectId: 'p1', closedAt: 1 },
+ projects,
+ 'p2',
+ new Set(),
+ neverRecreates
+ )
+ expect(plan).toEqual({ action: 'reopenProject', projectId: 'p1' })
+ })
+
+ it('skips a project entry whose project was already reopened another way (no longer closed)', () => {
+ const projects: PlanReopenProject[] = [{ id: 'p1', closed: false, nodes: [] }]
+ const plan = planReopen(
+ { kind: 'project', projectId: 'p1', closedAt: 1 },
+ projects,
+ 'p2',
+ new Set(),
+ neverRecreates
+ )
+ expect(plan).toEqual({ action: 'skip' })
+ })
+
+ it('skips a project entry whose project was permanently deleted since', () => {
+ const plan = planReopen({ kind: 'project', projectId: 'gone', closedAt: 1 }, [], 'p2', new Set(), neverRecreates)
+ expect(plan).toEqual({ action: 'skip' })
+ })
+
+ it('skips a nodes entry whose project was permanently deleted since', () => {
+ const plan = planReopen(
+ { kind: 'nodes', projectId: 'gone', closedAt: 1, nodes: [snap()] },
+ [],
+ 'p2',
+ new Set(),
+ alwaysRecreates()
+ )
+ expect(plan).toEqual({ action: 'skip' })
+ })
+
+ it('skips a nodes entry that recreates to nothing, rather than switching for an empty result', () => {
+ const projects: PlanReopenProject[] = [{ id: 'p1', closed: false, nodes: [] }]
+ const plan = planReopen(
+ { kind: 'nodes', projectId: 'p1', closedAt: 1, nodes: [snap(), snap()] },
+ projects,
+ 'p1',
+ new Set(),
+ neverRecreates
+ )
+ expect(plan).toEqual({ action: 'skip' })
+ })
+
+ it('inserts live when the target project is the active one', () => {
+ const projects: PlanReopenProject[] = [{ id: 'p1', closed: false, nodes: [] }]
+ const plan = planReopen(
+ { kind: 'nodes', projectId: 'p1', closedAt: 1, nodes: [snap(), snap()] },
+ projects,
+ 'p1',
+ new Set(['live-1']),
+ alwaysRecreates()
+ )
+ expect(plan.action).toBe('insertActive')
+ if (plan.action !== 'insertActive') throw new Error('unreachable')
+ // A multi-node batch restores as ONE unit, not split across separate plans.
+ expect(plan.nodes.map((n) => n.id)).toEqual(['recreated-0', 'recreated-1'])
+ })
+
+ it('a batch that partially recreates still restores as one unit with only the survivors', () => {
+ const projects: PlanReopenProject[] = [{ id: 'p1', closed: false, nodes: [] }]
+ let call = 0
+ const recreate = () => (call++ === 0 ? null : node('survivor'))
+ const plan = planReopen(
+ { kind: 'nodes', projectId: 'p1', closedAt: 1, nodes: [snap(), snap()] },
+ projects,
+ 'p1',
+ new Set(),
+ recreate
+ )
+ expect(plan.action).toBe('insertActive')
+ if (plan.action !== 'insertActive') throw new Error('unreachable')
+ expect(plan.nodes).toHaveLength(1)
+ expect(plan.nodes[0].id).toBe('survivor')
+ })
+
+ it('routes a non-active OPEN project through insertStored with reopenProjectAfter false (plain switch)', () => {
+ const projects: PlanReopenProject[] = [{ id: 'p1', closed: false, nodes: [{ id: 'existing' }] }]
+ const plan = planReopen(
+ { kind: 'nodes', projectId: 'p1', closedAt: 1, nodes: [snap()] },
+ projects,
+ 'p-active-elsewhere',
+ new Set(['ignored-because-not-active']),
+ alwaysRecreates()
+ )
+ expect(plan).toMatchObject({ action: 'insertStored', projectId: 'p1', reopenProjectAfter: false })
+ })
+
+ it('routes a non-active CLOSED project through insertStored with reopenProjectAfter true', () => {
+ const projects: PlanReopenProject[] = [{ id: 'p1', closed: true, nodes: [] }]
+ const plan = planReopen(
+ { kind: 'nodes', projectId: 'p1', closedAt: 1, nodes: [snap()] },
+ projects,
+ 'p-active-elsewhere',
+ new Set(),
+ alwaysRecreates()
+ )
+ expect(plan).toMatchObject({ action: 'insertStored', projectId: 'p1', reopenProjectAfter: true })
+ })
+
+ it('uses the STORED project nodes (not the live set) as liveNodeIds for a non-active target', () => {
+ const projects: PlanReopenProject[] = [{ id: 'p1', closed: false, nodes: [{ id: 'stored-parent' }] }]
+ let seenLiveIds: ReadonlySet<string> | null = null
+ const plan = planReopen(
+ { kind: 'nodes', projectId: 'p1', closedAt: 1, nodes: [snap({ parentId: 'stored-parent' })] },
+ projects,
+ 'p-active-elsewhere',
+ new Set(['live-only-id']), // must NOT be what the recreate call sees
+ (s, liveIds) => {
+ seenLiveIds = liveIds
+ return node('n')
+ }
+ )
+ expect(plan.action).toBe('insertStored')
+ expect(seenLiveIds).toEqual(new Set(['stored-parent']))
+ })
+
+ it('uses the ACTIVE live node ids (not the stored copy) for the active target', () => {
+ const projects: PlanReopenProject[] = [{ id: 'p1', closed: false, nodes: [{ id: 'stale-stored-id' }] }]
+ let seenLiveIds: ReadonlySet<string> | null = null
+ planReopen(
+ { kind: 'nodes', projectId: 'p1', closedAt: 1, nodes: [snap()] },
+ projects,
+ 'p1',
+ new Set(['live-parent']),
+ (s, liveIds) => {
+ seenLiveIds = liveIds
+ return node('n')
+ }
+ )
+ expect(seenLiveIds).toEqual(new Set(['live-parent']))
+ })
+
+ // Spec scenario (a): repeated presses walk back through history in true chronological order,
+ // across interleaved entry kinds — driven through the REAL stack (Task 1's useReopenHistory),
+ // not a fake, so this exercises the actual pop order the command relies on.
+ it('walks back through interleaved project/nodes history in true chronological order, skipping stale entries', () => {
+ const projects: PlanReopenProject[] = [
+ { id: 'proj-old', closed: true, nodes: [] }, // still closed: reopenable
+ { id: 'proj-mid', closed: false, nodes: [] }, // reopened another way since: stale
+ { id: 'proj-new', closed: false, nodes: [] } // holds the recreatable node batch
+ ]
+ useReopenHistory.getState().push({ kind: 'project', projectId: 'proj-old', closedAt: 1 })
+ useReopenHistory.getState().push({ kind: 'project', projectId: 'proj-mid', closedAt: 2 })
+ useReopenHistory.getState().push({ kind: 'nodes', projectId: 'proj-new', closedAt: 3, nodes: [snap()] })
+
+ const plans: ReturnType<typeof planReopen>[] = []
+ let popped = useReopenHistory.getState().popNext()
+ while (popped) {
+ plans.push(planReopen(popped, projects, 'proj-new', new Set(['live-1']), alwaysRecreates()))
+ popped = useReopenHistory.getState().popNext()
+ }
+
+ // Most-recently-closed first: the nodes batch, then proj-mid (stale — skip), then proj-old.
+ expect(plans[0].action).toBe('insertActive')
+ expect(plans[1]).toEqual({ action: 'skip' })
+ expect(plans[2]).toEqual({ action: 'reopenProject', projectId: 'proj-old' })
+ expect(plans).toHaveLength(3)
+ })
+})
diff --git a/src/renderer/lib/reopenPlan.ts b/src/renderer/lib/reopenPlan.ts
new file mode 100644
index 000000000..fa1bc7b0a
--- /dev/null
+++ b/src/renderer/lib/reopenPlan.ts
@@ -0,0 +1,70 @@
+import type { ReopenEntry } from '@renderer/state/reopenHistory'
+import type { ReopenNodeSnapshot } from './reopenNode'
+import type { CanvasNode } from '@renderer/state/workspace'
+
+/** What `app.reopenLastClosed` (Cmd+Shift+T) should do for ONE popped history entry. Pure
+ * decision only — no store writes, no `setNodes`, no navigation. `Canvas.tsx` executes
+ * whichever variant comes back; `'skip'` means the entry was stale (already reopened another
+ * way, its project was permanently deleted, or every node it held recreated to nothing) and the
+ * caller should keep popping. */
+export type ReopenPlan =
+ | { action: 'reopenProject'; projectId: string }
+ | { action: 'insertActive'; nodes: CanvasNode[] }
+ | { action: 'insertStored'; projectId: string; reopenProjectAfter: boolean; nodes: CanvasNode[] }
+ | { action: 'skip' }
+
+/** The subset of `Project` this decision needs — kept minimal so tests can pass plain fixtures
+ * instead of a full `Project`. */
+export interface PlanReopenProject {
+ id: string
+ closed?: boolean
+ nodes: readonly { id: string }[]
+}
+
+/**
+ * Decides what reopening `entry` should do, given the CURRENT project list and active project —
+ * both may have changed since the entry was recorded, which is exactly why an entry can be
+ * stale. `activeLiveNodeIds` is the live React Flow node id set (`nodesRef.current` on the
+ * canvas) — it's only consulted when `entry`'s project turns out to be the active one; a
+ * non-active project's own `nodes` (its serialized snapshot) stands in otherwise, since there is
+ * no live array for it. `recreate` is `recreateNodeFromSnapshot` pre-bound with everything except
+ * the live-id set (account resolution, permission mode, the TARGET project) — kept as an
+ * injected function so this stays pure and the account/permission-mode plumbing doesn't leak
+ * into the decision logic under test.
+ */
+export function planReopen(
+ entry: ReopenEntry,
+ projects: readonly PlanReopenProject[],
+ activeProjectId: string | undefined,
+ activeLiveNodeIds: ReadonlySet<string>,
+ recreate: (snapshot: ReopenNodeSnapshot, liveNodeIds: ReadonlySet<string>) => CanvasNode | null
+): ReopenPlan {
+ if (entry.kind === 'project') {
+ const project = projects.find((p) => p.id === entry.projectId)
+ // Only stale if it isn't sitting closed right now — already reopened another way, or gone.
+ return project?.closed ? { action: 'reopenProject', projectId: entry.projectId } : { action: 'skip' }
+ }
+
+ const project = projects.find((p) => p.id === entry.projectId)
+ if (!project) return { action: 'skip' } // permanently deleted since the entry was recorded
+
+ const isActive = project.id === activeProjectId
+ const liveIds = isActive ? activeLiveNodeIds : new Set(project.nodes.map((n) => n.id))
+ const created = entry.nodes
+ .map((snap) => recreate(snap, liveIds))
+ .filter((n): n is CanvasNode => n !== null)
+ // A snapshot that recreated to nothing (a kind this feature doesn't cover, or e.g. an editor
+ // whose filePath is somehow missing) leaves the whole batch with nothing to insert — treat as
+ // stale rather than switching/reopening a project for an empty result. A multi-node batch that
+ // DID partially recreate still restores as ONE unit (whatever survived), never split across plans.
+ if (!created.length) return { action: 'skip' }
+
+ return isActive
+ ? { action: 'insertActive', nodes: created }
+ : {
+ action: 'insertStored',
+ projectId: project.id,
+ reopenProjectAfter: !!project.closed,
+ nodes: created
+ }
+}