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.

feat(control): the open-project dispatch — store-answered, human-confirmed, live

enesdd0c3bfe94fe
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index d23098906..f8aed63af 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -36,13 +36,11 @@ describe('parseControlRequest', () => {
})
})
- it('open-project is NOT in DESTRUCTIVE_VERBS yet — that membership lands with PR 2', () => {
- // Deliberate PR slicing, not an oversight: `control-destructive.test.ts` structurally
- // requires every member's `Canvas.tsx` case to read `isDestructiveVerb(verb)`, and the
- // dispatch case for open-project only exists in PR 2 (Task 2.2). Adding the verb to the set
- // now would trip the set↔dispatch drift alarm with no dispatch to agree with. This test goes
- // red the moment PR 2 adds the membership, which is the reminder to delete it.
- expect(isDestructiveVerb('open-project')).toBe(false)
+ it('open-project IS destructive — its create/adopt/first-attach dialog is confirm-gated (PR 2)', () => {
+ // PR 1 left a tripwire here asserting the opposite; PR 2 added the early-handled dispatch
+ // block that reads `isDestructiveVerb(verb)` before its `confirmBusy()` refusal, so the
+ // membership and the dispatch now exist together (control-destructive.test.ts is the alarm).
+ expect(isDestructiveVerb('open-project')).toBe(true)
})
it('requires a target for write/close', () => {
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 7a47446d4..d23692713 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -207,6 +207,13 @@ import {
type BrowserResolveProject
} from '../lib/controlRouting'
import { applyStickyWrite, parseStickyArgs, resolveStickyRef } from '../lib/stickyWrite'
+import {
+ planOpenProject,
+ recordAttachConsent,
+ openProjectReply,
+ findProjectByCwd,
+ nextFreePosition
+} from '../lib/projectOpen'
import {
FIT_NODE_OPTIONS,
absolutePosition,
@@ -7157,6 +7164,93 @@ export function Canvas() {
return
}
+ // ── `open-project` (issue #338 Task 2.2) — handled BEFORE the source-routing machinery ──
+ // A STORE_ANSWERED_VERBS member for the G5 reason (controlRouting.ts): routing is by
+ // SOURCE, and travelling would yank the human's view to the CALLER's project on every
+ // registration. Main already gated this request (gateOpenProject): the caller is verified,
+ // local, under the grant cap, and `args.cwd` is the RESOLVED path (P7) — the raw argument
+ // never reaches this process, so the dialog below can only ever show the resolved form
+ // (P5). The renderer's job: validate the source live-or-stored, decide the consent branch
+ // (planOpenProject — every grant passes a human decision exactly once, spec Q1), raise the
+ // dialog, apply the NON-ACTIVATING registerProject (P6 — no setActive/travel in any
+ // branch), and reply exactly once on confirm AND cancel (GC 12). The grant itself is
+ // recorded MAIN-side when this reply lands ok && verified (recordOpenProjectGrant) —
+ // nothing in this block authorizes anything.
+ if (verb === 'open-project') {
+ const resolvedCwd = args.cwd ?? ''
+ if (!resolvedCwd) {
+ reply({ ok: false, error: 'open-project requires --cwd' })
+ return
+ }
+ const opLive = nodesRef.current.find((n) => n.id === sourceNodeId)
+ const opStored = useProjects
+ .getState()
+ .projects.flatMap((p) => p.nodes)
+ .find((n) => n.id === sourceNodeId)
+ if (!opLive && !opStored) {
+ reply({ ok: false, error: 'source node is not in any open project' })
+ return
+ }
+ if (!sourceIsControlCapable(opLive?.data.agentId ?? opStored?.agentId)) {
+ reply({ ok: false, error: 'source node is not a control-capable agent' })
+ return
+ }
+ const opTitle =
+ oneLine((opLive?.data.title as string) ?? opStored?.title ?? '') || sourceNodeId
+ // Apply one consent decision: register (create/adopt/idempotent hit) without activating,
+ // persist, remember the (caller, project) pair for dialog dedupe — authorization stays
+ // main-side — and reply with the id the caller can feed `--project`.
+ const opFinish = (adoptProbed?: Project) => {
+ const r = useProjects.getState().registerProject({
+ resolvedCwd,
+ name: args.name,
+ color: args.color,
+ ...(adoptProbed ? { probed: adoptProbed } : {})
+ })
+ recordAttachConsent(sourceNodeId, r.project.id)
+ void writeDisk()
+ reply({ ok: true, ...openProjectReply(r.project, r.created, r.adopted) })
+ }
+ // The probe only matters when no project owns this cwd yet (adopt-vs-create copy) — an
+ // idempotent hit must not pay a folder read.
+ const opProjects = useProjects.getState().projects
+ const opProbed = findProjectByCwd(opProjects, resolvedCwd)
+ ? null
+ : await api.workspace.probeFolder(resolvedCwd).catch(() => null)
+ const opPlan = planOpenProject({
+ projects: opProjects,
+ callerNodeId: sourceNodeId,
+ srcTitle: opTitle,
+ resolvedCwd,
+ probedName: opProbed?.name,
+ requestedName: args.name
+ })
+ if (opPlan.kind === 'silent') {
+ // This caller already passed a human decision for this project (Q1): idempotent, quiet.
+ opFinish()
+ return
+ }
+ // One confirm dialog at a time — the write/close rule, read off the shared set.
+ if (isDestructiveVerb(verb) && confirmBusy()) {
+ reply({ ok: false, error: 'a confirmation is already pending — try again' })
+ return
+ }
+ setConfirm({
+ message: opPlan.message,
+ confirmLabel: opPlan.confirmLabel,
+ requestedBy: opTitle,
+ onConfirm: () => {
+ setConfirm(null)
+ opFinish(
+ opPlan.confirmKind === 'adopt' && opProbed ? { ...opProbed, closed: false } : undefined
+ )
+ },
+ onCancel: () => reply({ ok: false, error: 'denied by user' })
+ })
+ return
+ }
+ // ── end of the early-handled (store-answered) verbs ─────────────────────────────────────
+
// Which canvas answers? React Flow holds only the ACTIVE project's nodes, but every OTHER
// project's tmux sessions keep running and are re-adopted on the next app start — so after a
// restart the agents of every project the app did NOT come up on were answered by a canvas
diff --git a/src/renderer/canvas/control-destructive.test.ts b/src/renderer/canvas/control-destructive.test.ts
index e672a4a17..16d057b8b 100644
--- a/src/renderer/canvas/control-destructive.test.ts
+++ b/src/renderer/canvas/control-destructive.test.ts
@@ -33,21 +33,43 @@ function caseBody(verb: string): string {
return end === -1 ? rest : rest.slice(0, end)
}
+/**
+ * The body of an EARLY-HANDLED verb's block — `open-project` is dispatched before the
+ * source-routing machinery (a STORE_ANSWERED_VERBS member, spec §2.3), so it has no `case` label.
+ * Delimited by its `if (verb === '<verb>')` guard and the next section-comment rule (`// ──`),
+ * the same way the switch slice above is delimited by the next case label.
+ */
+function earlyBody(verb: string): string {
+ const start = src.indexOf(`if (verb === '${verb}')`)
+ if (start === -1) return ''
+ const rest = src.slice(start)
+ const end = rest.indexOf('// ──', 10)
+ return end === -1 ? rest : rest.slice(0, end)
+}
+
+/** A verb's dispatch body wherever it lives: its switch case, or its early-handled block. */
+function dispatchBody(verb: string): string {
+ return caseBody(verb) || earlyBody(verb)
+}
+
describe('the confirm-gated set and the dispatch that reads it stay in agreement', () => {
it('the dispatch imports the set rather than restating it', () => {
expect(src).toMatch(/import \{[^}]*isDestructiveVerb[^}]*\} from '@shared\/control-verbs'/)
})
- for (const verb of ['write', 'close'] as const) {
+ for (const verb of ['write', 'close', 'open-project'] as const) {
it(`${verb} reaches its confirm through isDestructiveVerb`, () => {
expect(isDestructiveVerb(verb)).toBe(true)
- const body = caseBody(verb)
+ const body = dispatchBody(verb)
expect(body).not.toBe('')
// The guard CALL, not a hardcoded truth: adding a verb to the set must change behaviour.
expect(body).toMatch(/isDestructiveVerb\(verb\) && confirmBusy\(\)/)
// …and no leftover bare gate beside it, which would make the set decorative again.
expect(body).not.toMatch(/\bif \(confirmBusy\(\)\)/)
expect(body).toContain('setConfirm({')
+ // Denial is honored on every confirm this set gates (spec P4): the cancel leg replies the
+ // shared refusal instead of hanging the CLI to its 120s timeout.
+ expect(body).toContain("'denied by user'")
})
}
@@ -61,6 +83,10 @@ describe('the confirm-gated set and the dispatch that reads it stay in agreement
// is confirm-gated"; it is "no other case claims to be gated by this set".
const labels = [...src.matchAll(/\n {10}case '([a-z-]+)': \{/g)].map((m) => m[1])
const gated = labels.filter((v) => /isDestructiveVerb\(verb\)/.test(caseBody(v)))
+ // The early-handled block (`open-project`) is counted the same way, off its own slice.
+ for (const early of ['open-project']) {
+ if (/isDestructiveVerb\(verb\)/.test(earlyBody(early))) gated.push(early)
+ }
expect(new Set(gated)).toEqual(new Set(DESTRUCTIVE_VERBS))
})
})
diff --git a/src/renderer/canvas/control-open-project.source.test.ts b/src/renderer/canvas/control-open-project.source.test.ts
new file mode 100644
index 000000000..5bee8e905
--- /dev/null
+++ b/src/renderer/canvas/control-open-project.source.test.ts
@@ -0,0 +1,74 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * STRUCTURAL pins for the `open-project` early-handled dispatch block (issue #338 Task 2.2) —
+ * the same class of test as `control-destructive.test.ts`, and for the same reason: the block
+ * lives inside a 7000-line React component's IPC listener with no unit seam, and the properties
+ * pinned here are properties of the SOURCE (what the block calls and what it never calls). Every
+ * behavioural half is separately proven against real primitives: the consent decision in
+ * `projectOpen.test.ts` (planOpenProject on the real ledger), the store action in
+ * `projects.register.test.ts` (registerProject never activates), the grant in main's
+ * `project-grants.test.ts`.
+ */
+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8')
+
+/** The early-handled open-project block: from its `if (verb === ...)` guard to the next
+ * section-rule comment (`// ──`) — the same delimiting `control-destructive.test.ts` uses. */
+function openProjectBody(): string {
+ const start = src.indexOf(`if (verb === 'open-project')`)
+ expect(start).toBeGreaterThan(-1)
+ const rest = src.slice(start)
+ const end = rest.indexOf('// ──', 10)
+ return end === -1 ? rest : rest.slice(0, end)
+}
+
+describe('the open-project dispatch block (source pins)', () => {
+ it('sits BEFORE the source-routing machinery — ahead of the routeControlSource lookup', () => {
+ // The store-answered declaration (controlRouting.ts) and this early-exit are the same
+ // decision stated once each (spec §2.3): the block must run before the dispatch ever
+ // consults routeControlSource, or a background caller's open-project would travel the
+ // human's view to the CALLER's project (G5).
+ const block = src.indexOf(`if (verb === 'open-project')`)
+ const routing = src.indexOf('routeControlSource(projects, activeId, sourceNodeId)')
+ expect(block).toBeGreaterThan(-1)
+ expect(routing).toBeGreaterThan(-1)
+ expect(block).toBeLessThan(routing)
+ })
+
+ it('never activates or travels (spec P6): no setActive, no travelToProject in any branch', () => {
+ const body = openProjectBody()
+ expect(body).not.toContain('setActive')
+ expect(body).not.toContain('travelToProject')
+ expect(body).not.toContain('reopenProject')
+ expect(body).not.toContain('openFolderProject')
+ expect(body).not.toContain('adoptProject')
+ })
+
+ it('every store change goes through the non-activating registerProject, and only in opFinish', () => {
+ const body = openProjectBody()
+ // registerProject is reached exactly once, inside the single opFinish closure both the
+ // silent hit and the confirmed dialog call — so a denial (onCancel) structurally cannot
+ // create anything: the only creation site is behind opFinish.
+ expect(body.match(/registerProject\(/g)?.length).toBe(1)
+ expect(body).toContain('const opFinish')
+ // The cancel leg replies the shared denial and calls nothing else.
+ expect(body).toMatch(/onCancel: \(\) => reply\(\{ ok: false, error: 'denied by user' \}\)/)
+ })
+
+ it('the dialog shows the plan message (built from the RESOLVED cwd, P5), not a re-derived path', () => {
+ const body = openProjectBody()
+ expect(body).toContain('message: opPlan.message')
+ // The block never re-resolves or re-derives the path: args.cwd (main's resolved form) is
+ // read once into resolvedCwd and that identifier is what the plan and the store see.
+ expect(body).toContain('const resolvedCwd = args.cwd')
+ })
+
+ it('persists after registering (writeDisk inside opFinish)', () => {
+ const body = openProjectBody()
+ const finishStart = body.indexOf('const opFinish')
+ const finishEnd = body.indexOf('// The probe only matters')
+ const finish = body.slice(finishStart, finishEnd)
+ expect(finish).toContain('writeDisk()')
+ })
+})
diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.ts
index a97fb7aa2..510642101 100644
--- a/src/renderer/lib/controlRouting.test.ts
+++ b/src/renderer/lib/controlRouting.test.ts
@@ -90,6 +90,16 @@ describe('needsLiveCanvas', () => {
// projects store (`applyNodeMutation`), not the live canvas.
expect(needsLiveCanvas('sticky')).toBe(false)
})
+
+ it('is false for open-project — registering a project must never travel the camera (issue #338)', () => {
+ // The G5 argument one more time: routing is by SOURCE, and open-project's headline caller is
+ // a background orchestrator registering repos one after another — travelling would yank the
+ // human's view to the CALLER's project on every call. The verb acts on the projects STORE
+ // (registerProject, non-activating by construction), so no live canvas is needed at either
+ // end; this membership and Canvas.tsx's early-exit dispatch are the same decision stated once
+ // each (spec §2.3, P6).
+ expect(needsLiveCanvas('open-project')).toBe(false)
+ })
})
describe('sourceIsControlCapable', () => {
diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.ts
index 4745bcb6b..e25069e52 100644
--- a/src/renderer/lib/controlRouting.ts
+++ b/src/renderer/lib/controlRouting.ts
@@ -101,7 +101,24 @@ export function routeControlSource(
* project's serialized nodes (`applyNodeMutation`, the same path peer mutations take) when that
* project is not the active one; the live canvas handles it when it is.
*/
-const STORE_ANSWERED_VERBS: ReadonlySet<string> = new Set(['list', 'send', 'reply', 'sticky'])
+/*
+ * `open-project` (issue #338) is store-answered for the G5 reason in its sharpest form: its
+ * headline caller is a background orchestrator registering one repo after another, and routing is
+ * by SOURCE — a live requirement would yank the human's view to the CALLER's project on every
+ * registration (and clear its unread badge via `setActive` on the way). The verb acts on the
+ * projects STORE through the non-activating `registerProject`, and its consent dialog is
+ * app-global (`ConfirmState` overlays the window), so no live canvas is needed at either end.
+ * Canvas.tsx handles it BEFORE the source-routing machinery — this declaration and that
+ * early-exit are the same decision stated once each (spec §2.3, P6), pinned by
+ * `controlRouting.test.ts`.
+ */
+const STORE_ANSWERED_VERBS: ReadonlySet<string> = new Set([
+ 'list',
+ 'send',
+ 'reply',
+ 'sticky',
+ 'open-project'
+])
/**
* Does this verb have to run against the LIVE canvas? Everything that creates, moves, writes to or
diff --git a/src/renderer/lib/projectOpen.test.ts b/src/renderer/lib/projectOpen.test.ts
new file mode 100644
index 000000000..a85136d89
--- /dev/null
+++ b/src/renderer/lib/projectOpen.test.ts
@@ -0,0 +1,191 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import {
+ planOpenProject,
+ recordAttachConsent,
+ attachConsentRecorded,
+ clearAttachConsentForTests,
+ findProjectByCwd,
+ openProjectReply,
+ nextFreePosition,
+ type PlacedNode
+} from './projectOpen'
+
+/**
+ * Issue #338 Task 2.2/2.3 — the pure halves of the `open-project` dispatch and the
+ * `--project`-targeted placement. Canvas.tsx only wires these (the dialog, the store calls, the
+ * reply); everything decidable without React is decided here so it is red-capable:
+ *
+ * - EVERY grant passes a human decision exactly once (spec Q1, adopted): a caller's FIRST
+ * open-project against an EXISTING project confirms too — the confirm-bypass mutation
+ * ("silent idempotent hit") turns this suite red.
+ * - The dialog copy always contains the RESOLVED path (spec P5).
+ * - The consent mirror is per-caller and session-scoped (dialog dedupe only — authorization is
+ * main's grant ledger, never this map).
+ */
+
+beforeEach(() => clearAttachConsentForTests())
+
+const projects = [
+ { id: 'project-a', name: 'repoA', cwd: '/home/me/dev/repoA' },
+ { id: 'project-b', name: 'repoB', cwd: '/home/me/dev/repoB' }
+]
+
+describe('planOpenProject — the consent decision (spec §2.1, Q1)', () => {
+ it('FIRST attach to an existing project confirms — an idempotent hit is not silent', () => {
+ const plan = planOpenProject({
+ projects,
+ callerNodeId: 'term-caller',
+ srcTitle: 'Orchestrator',
+ resolvedCwd: '/home/me/dev/repoA'
+ })
+ expect(plan.kind).toBe('confirm')
+ if (plan.kind !== 'confirm') return
+ expect(plan.confirmKind).toBe('attach')
+ expect(plan.project?.id).toBe('project-a')
+ // Lighter copy than create (Q1): names the project and the asking agent.
+ expect(plan.message).toContain('Orchestrator')
+ expect(plan.message).toContain('repoA')
+ })
+
+ it('after the consent is recorded, the SAME caller hits silently — once per caller+project', () => {
+ recordAttachConsent('term-caller', 'project-a')
+ const plan = planOpenProject({
+ projects,
+ callerNodeId: 'term-caller',
+ srcTitle: 'Orchestrator',
+ resolvedCwd: '/home/me/dev/repoA'
+ })
+ expect(plan.kind).toBe('silent')
+ if (plan.kind !== 'silent') return
+ expect(plan.project.id).toBe('project-a')
+ })
+
+ it('consent is PER-CALLER: another caller presenting the same cwd still confirms', () => {
+ recordAttachConsent('term-caller', 'project-a')
+ const plan = planOpenProject({
+ projects,
+ callerNodeId: 'term-other',
+ srcTitle: 'Other',
+ resolvedCwd: '/home/me/dev/repoA'
+ })
+ expect(plan.kind).toBe('confirm')
+ expect(attachConsentRecorded('term-other', 'project-a')).toBe(false)
+ })
+
+ it('no hit + a probed .nodeterm project → adopt-confirm showing the RESOLVED path (P5)', () => {
+ const plan = planOpenProject({
+ projects,
+ callerNodeId: 'term-caller',
+ srcTitle: 'Orchestrator',
+ resolvedCwd: '/home/me/dev/cloned',
+ probedName: 'cloned-app'
+ })
+ expect(plan.kind).toBe('confirm')
+ if (plan.kind !== 'confirm') return
+ expect(plan.confirmKind).toBe('adopt')
+ expect(plan.message).toContain('/home/me/dev/cloned')
+ expect(plan.message).toContain('existing project')
+ })
+
+ it('no hit, no probe → create-confirm showing the RESOLVED path and the name', () => {
+ const plan = planOpenProject({
+ projects,
+ callerNodeId: 'term-caller',
+ srcTitle: 'Orchestrator',
+ resolvedCwd: '/home/me/dev/fresh',
+ requestedName: 'Fresh One'
+ })
+ expect(plan.kind).toBe('confirm')
+ if (plan.kind !== 'confirm') return
+ expect(plan.confirmKind).toBe('create')
+ expect(plan.message).toContain('/home/me/dev/fresh')
+ expect(plan.message).toContain('Fresh One')
+ })
+
+ it('the create name defaults to the folder basename', () => {
+ const plan = planOpenProject({
+ projects: [],
+ callerNodeId: 'c',
+ srcTitle: 'A',
+ resolvedCwd: '/x/some-repo'
+ })
+ expect(plan.kind).toBe('confirm')
+ if (plan.kind !== 'confirm') return
+ expect(plan.message).toContain('some-repo')
+ })
+})
+
+describe('findProjectByCwd — the dedupe rule', () => {
+ it('matches exactly, with the trailing slash normalized away', () => {
+ expect(findProjectByCwd(projects, '/home/me/dev/repoA')?.id).toBe('project-a')
+ expect(findProjectByCwd(projects, '/home/me/dev/repoA/')?.id).toBe('project-a')
+ expect(findProjectByCwd(projects, '/home/me/dev/repoA-2')).toBeUndefined()
+ })
+})
+
+describe('openProjectReply — the reply shape', () => {
+ it('carries { projectId, name, cwd, created } and names the id in the message', () => {
+ const r = openProjectReply({ id: 'project-a', name: 'repoA', cwd: '/x' }, false, false)
+ expect(r.result).toEqual({ projectId: 'project-a', name: 'repoA', cwd: '/x', created: false })
+ expect(r.message).toContain('project-a')
+ expect(r.message).toContain('opened')
+ })
+
+ it('created and adopted both answer created: true (a new workspace entry either way)', () => {
+ expect(openProjectReply({ id: 'p', name: 'n', cwd: '/x' }, true, false).result.created).toBe(true)
+ const adopted = openProjectReply({ id: 'p', name: 'n', cwd: '/x' }, false, true)
+ expect(adopted.result.created).toBe(true)
+ expect(adopted.message).toContain('added')
+ })
+})
+
+describe('nextFreePosition — placement into a project the caller is not on (spec §2.2)', () => {
+ const rect = (center: { x: number; y: number }, w: number, h: number) => ({
+ left: center.x - w / 2,
+ top: center.y - h / 2,
+ right: center.x + w / 2,
+ bottom: center.y + h / 2
+ })
+ const overlaps = (
+ a: { left: number; top: number; right: number; bottom: number },
+ b: { left: number; top: number; right: number; bottom: number }
+ ) => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom
+
+ it('never overlaps any existing store node', () => {
+ const nodes: PlacedNode[] = [
+ { id: 'a', position: { x: 0, y: 0 }, size: { width: 600, height: 400 } },
+ { id: 'b', position: { x: 700, y: 120 }, size: { width: 240, height: 200 } },
+ { id: 'c', position: { x: -300, y: 900 }, size: { width: 860, height: 500 } }
+ ]
+ const size = { width: 640, height: 440 }
+ const center = nextFreePosition(nodes, size)
+ const mine = rect(center, size.width, size.height)
+ for (const n of nodes) {
+ const theirs = {
+ left: n.position.x,
+ top: n.position.y,
+ right: n.position.x + (n.size?.width ?? 0),
+ bottom: n.position.y + (n.size?.height ?? 0)
+ }
+ expect(overlaps(mine, theirs)).toBe(false)
+ }
+ })
+
+ it('resolves a group child to ROOT space before comparing (a nested node cannot be landed on)', () => {
+ const nodes: PlacedNode[] = [
+ { id: 'g', position: { x: 100, y: 100 }, size: { width: 800, height: 700 } },
+ // Child at group-relative (20, 500): its root bottom is 100+500+400 = 1000, far below the
+ // frame's own bottom (800) — placing "below the lowest" must use the child's ROOT rect.
+ { id: 'child', parentId: 'g', position: { x: 20, y: 500 }, size: { width: 600, height: 400 } }
+ ]
+ const size = { width: 640, height: 440 }
+ const center = nextFreePosition(nodes, size)
+ expect(center.y - size.height / 2).toBeGreaterThanOrEqual(1000)
+ })
+
+ it('an empty project gets a sane default near the origin', () => {
+ const c = nextFreePosition([], { width: 640, height: 440 })
+ expect(c.x).toBeGreaterThan(0)
+ expect(c.y).toBeGreaterThan(0)
+ })
+})
diff --git a/src/renderer/lib/projectOpen.ts b/src/renderer/lib/projectOpen.ts
new file mode 100644
index 000000000..7dbc72bcb
--- /dev/null
+++ b/src/renderer/lib/projectOpen.ts
@@ -0,0 +1,201 @@
+// Pure halves of the `open-project` control verb and the `--project`-targeted opens
+// (issue #338, spec §2.1/§2.2). Canvas.tsx's dispatch only wires these — the dialog, the store
+// calls and the reply — so every decision that does not need React is unit-testable here, the
+// same reasoning as controlRouting.ts / pendingLaunch.ts.
+
+/** The little these helpers need to know about a project. */
+export interface ProjectForOpen {
+ id: string
+ name: string
+ cwd?: string
+}
+
+/**
+ * The dedupe rule (spec B1): the exact-string match `openFolderProject` uses, with the trailing
+ * slash normalized away so `/a/b/` and `/a/b` cannot mint two tabs for one directory. `--cwd`
+ * arrives here ALREADY resolved by main (`path.resolve`, spec P7) — this is cosmetic-slash
+ * defense, never a second resolution.
+ */
+export function normalizeProjectCwd(resolvedCwd: string): string {
+ return resolvedCwd.length > 1 ? resolvedCwd.replace(/\/+$/, '') : resolvedCwd
+}
+
+export function findProjectByCwd<T extends { cwd?: string }>(
+ projects: readonly T[],
+ resolvedCwd: string
+): T | undefined {
+ const cwd = normalizeProjectCwd(resolvedCwd)
+ return projects.find((p) => p.cwd === cwd)
+}
+
+/**
+ * The renderer-session attach-consent mirror (spec §4.2 Q1, adopted): which (caller, project)
+ * pairs have already passed a human decision — creating, adopting, or the lighter first-attach
+ * "Allow?" — so an idempotent re-open by the SAME caller does not re-raise the dialog, while a
+ * DIFFERENT caller naming the same cwd still asks. DIALOG DEDUPE ONLY: authorization is main's
+ * grant ledger (src/main/project-grants.ts), keyed to main's own verified identity verdict; this
+ * map decides nothing but whether a dialog is shown. In-memory, per app run — the same lifetime
+ * as the grants it mirrors.
+ */
+const attachAsked = new Map<string, Set<string>>()
+
+export function attachConsentRecorded(callerNodeId: string, projectId: string): boolean {
+ return attachAsked.get(callerNodeId)?.has(projectId) ?? false
+}
+
+export function recordAttachConsent(callerNodeId: string, projectId: string): void {
+ const set = attachAsked.get(callerNodeId) ?? new Set<string>()
+ set.add(projectId)
+ attachAsked.set(callerNodeId, set)
+}
+
+export function clearAttachConsentForTests(): void {
+ attachAsked.clear()
+}
+
+export type OpenProjectPlan =
+ | { kind: 'silent'; project: ProjectForOpen }
+ | {
+ kind: 'confirm'
+ confirmKind: 'attach' | 'adopt' | 'create'
+ message: string
+ confirmLabel: string
+ /** Set for `attach` — the existing project the caller is asking into. */
+ project?: ProjectForOpen
+ }
+
+/**
+ * The whole consent decision for one `open-project` request (spec §2.1 steps 2–4 + Q1). Pure:
+ * the caller has already resolved the cwd (main), looked for a probe result (only needed when no
+ * cwd hit exists), and passes everything in. Every dialog message shows the RESOLVED path (P5) —
+ * the raw argument never reaches the renderer at all (main rewrites args.cwd).
+ *
+ * Q1 (adopted): an idempotent hit is silent ONLY for a caller that already passed a human
+ * decision for this project. The first attach confirms with lighter copy, so every grant main
+ * records traces back to exactly one human decision — a silent hit would let a verified caller
+ * reach BY CWD the very targeting rights B3 forbids reaching by id.
+ */
+export function planOpenProject(input: {
+ projects: readonly ProjectForOpen[]
+ callerNodeId: string
+ srcTitle: string
+ resolvedCwd: string
+ /** The probed .nodeterm project's name, when `probeFolder` answered (adopt path). */
+ probedName?: string
+ requestedName?: string
+}): OpenProjectPlan {
+ const { projects, callerNodeId, srcTitle, resolvedCwd, probedName, requestedName } = input
+ const existing = findProjectByCwd(projects, resolvedCwd)
+ if (existing) {
+ if (attachConsentRecorded(callerNodeId, existing.id)) return { kind: 'silent', project: existing }
+ return {
+ kind: 'confirm',
+ confirmKind: 'attach',
+ message: `Agent "${srcTitle}" wants to open sessions in project "${existing.name}". Allow?`,
+ confirmLabel: 'Allow',
+ project: existing
+ }
+ }
+ if (probedName !== undefined) {
+ return {
+ kind: 'confirm',
+ confirmKind: 'adopt',
+ message:
+ `Agent "${srcTitle}" wants to add the existing project at\n${resolvedCwd}\n` +
+ `to your workspace ("${probedName}"). Add it?`,
+ confirmLabel: 'Add project'
+ }
+ }
+ const name =
+ (requestedName ?? '').trim() ||
+ (normalizeProjectCwd(resolvedCwd).split('/').filter(Boolean).pop() || 'Project')
+ return {
+ kind: 'confirm',
+ confirmKind: 'create',
+ message:
+ `Agent "${srcTitle}" wants to create a project for\n${resolvedCwd}\n` +
+ `(name "${name}"). Create it?`,
+ confirmLabel: 'Create project'
+ }
+}
+
+/**
+ * The success reply (spec §2.1): `result` carries `{ projectId, name, cwd, created }` — the id is
+ * what the caller feeds `--project`, and `created` is true for anything that added a new
+ * workspace entry (create AND adopt; an idempotent hit answers false). The message carries the
+ * project's REAL name, so an agent whose `--name` was ignored on a hit learns what it is.
+ */
+export function openProjectReply(
+ project: ProjectForOpen,
+ created: boolean,
+ adopted: boolean
+): {
+ message: string
+ result: { projectId: string; name: string; cwd: string; created: boolean }
+} {
+ const verb = created ? 'created' : adopted ? 'added' : 'opened'
+ const cwd = project.cwd ?? ''
+ return {
+ message: `${verb} project "${project.name}" (${project.id}) for ${cwd}`,
+ result: { projectId: project.id, name: project.name, cwd, created: created || adopted }
+ }
+}
+
+/** A node as either the serialized store or the live canvas holds it — enough for placement. */
+export interface PlacedNode {
+ id?: string
+ parentId?: string
+ position: { x: number; y: number }
+ size?: { width: number; height: number }
+ width?: number | null
+ height?: number | null
+}
+
+const placedW = (n: PlacedNode): number => n.size?.width ?? (n.width as number) ?? 0
+const placedH = (n: PlacedNode): number => n.size?.height ?? (n.height as number) ?? 0
+
+/** A node's position in ROOT space: its own plus every ancestor frame's origin (a group child's
+ * stored position is frame-relative). Cycle-guarded like every other parent walk. */
+function rootPosition(n: PlacedNode, byId: Map<string, PlacedNode>): { x: number; y: number } {
+ let x = n.position.x
+ let y = n.position.y
+ const seen = new Set<string>(n.id ? [n.id] : [])
+ let parentId = n.parentId
+ while (parentId && !seen.has(parentId)) {
+ seen.add(parentId)
+ const parent = byId.get(parentId)
+ if (!parent) break
+ x += parent.position.x
+ y += parent.position.y
+ parentId = parent.parentId
+ }
+ return { x, y }
+}
+
+/**
+ * Where a node opened INTO another project lands (spec §2.2): centered below the lowest existing
+ * node, because `placeBelow(src)` is meaningless in a project that does not contain the source.
+ * Returns a CENTER point (the factories' `center` parameter — `placeAt` converts to top-left).
+ * Guaranteed non-overlapping: everything else ends above the returned rect's top edge. Positions
+ * are resolved to root space first, so a group child poking below its frame still counts.
+ */
+export function nextFreePosition(
+ nodes: readonly PlacedNode[],
+ size: { width: number; height: number } = { width: 640, height: 440 }
+): { x: number; y: number } {
+ if (!nodes.length) return { x: 40 + size.width / 2, y: 40 + size.height / 2 }
+ const byId = new Map<string, PlacedNode>()
+ for (const n of nodes) if (n.id) byId.set(n.id, n)
+ let left = Infinity
+ let bottom = -Infinity
+ for (const n of nodes) {
+ const at = rootPosition(n, byId)
+ if (Number.isFinite(at.x)) left = Math.min(left, at.x)
+ const b = at.y + placedH(n)
+ if (Number.isFinite(b)) bottom = Math.max(bottom, b)
+ }
+ if (!Number.isFinite(left) || !Number.isFinite(bottom)) {
+ return { x: 40 + size.width / 2, y: 40 + size.height / 2 }
+ }
+ return { x: left + size.width / 2, y: bottom + 80 + size.height / 2 }
+}
diff --git a/src/shared/control-verbs.ts b/src/shared/control-verbs.ts
index 59cfcb7c9..7e3609248 100644
--- a/src/shared/control-verbs.ts
+++ b/src/shared/control-verbs.ts
@@ -35,7 +35,10 @@
// exactly what the renderer cannot see, and the renderer's dispatch receives a raw `verb: string`
// off IPC anyway. `canvas-control-core.ts` re-exports this so main-side callers are unchanged.
-export const DESTRUCTIVE_VERBS: ReadonlySet<string> = new Set(['write', 'close'])
+// `open-project` (issue #338): create/adopt/first-attach all raise a human confirm (spec B2 +
+// Q1), and its early-handled block in Canvas.tsx reads `isDestructiveVerb(verb)` before its
+// `confirmBusy()` refusal exactly as write/close's cases do — the drift alarm covers all three.
+export const DESTRUCTIVE_VERBS: ReadonlySet<string> = new Set(['write', 'close', 'open-project'])
/**
* Does this verb's dispatch case take its `confirmBusy()` refusal from the shared set?