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): --project targeted opens — live insertion or cold-open store write

enes4e15fdb6a31f
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index d23692713..ff766e909 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -212,7 +212,8 @@ import {
recordAttachConsent,
openProjectReply,
findProjectByCwd,
- nextFreePosition
+ nextFreePosition,
+ armForColdOpen
} from '../lib/projectOpen'
import {
FIT_NODE_OPTIONS,
@@ -346,7 +347,7 @@ import { pushSessionRename } from '../lib/sessionRename'
import { oneLine } from '@shared/one-line'
import { parseLenses, verifyLensPrompt, verifySynthesisPrompt } from '../lib/verifyPanel'
import { useSettings } from '../state/settings'
-import { activePermissionMode } from '../state/permissionMode'
+import { activePermissionMode, projectPermissionMode } from '../state/permissionMode'
import { useContextWindow } from '../state/contextWindow'
import { useSessionNaming } from '../state/sessionNaming'
import { useSshServers } from '../state/sshServers'
@@ -7249,6 +7250,155 @@ export function Canvas() {
})
return
}
+
+ // ── `--project` targeted opens (issue #338 Task 2.3) — the three open verbs, early ──────
+ // Main's gateProjectTarget already enforced own-or-granted BEFORE forwarding (spec §3):
+ // the renderer never sees an unauthorized target — the checks below are belt, not the
+ // boundary. This block routes an AUTHORIZED target to the right DATA OWNER without
+ // travelling (B4): the live canvas owns the ACTIVE project (a store write there would be
+ // clobbered by the next commitCanvas), the projects store owns every other. A target equal
+ // to the caller's OWN project falls through to the legacy path unchanged — exactly as if
+ // the flag were omitted (B3a), travel included.
+ if (
+ (verb === 'open-terminal' || verb === 'open-claude' || verb === 'open-agent') &&
+ args.project !== undefined
+ ) {
+ const targetId = args.project
+ // v1 excludes the flags that name ids inside another project (spec §2.2): validating a
+ // group frame or a dependency station across a project boundary is exactly the surface
+ // v1 leaves out. Uniformly refused — own-project callers just omit --project.
+ if (args.group || args.after) {
+ reply({
+ ok: false,
+ error:
+ 'project-target-flag-unsupported: --group/--after cannot be combined with --project'
+ })
+ return
+ }
+ const tgStore = useProjects.getState()
+ const tgLiveSrc = nodesRef.current.find((n) => n.id === sourceNodeId)
+ const tgStoredSrc = tgStore.projects
+ .flatMap((p) => p.nodes.map((n) => ({ node: n, projectId: p.id })))
+ .find((x) => x.node.id === sourceNodeId)
+ const callerProjectId = tgLiveSrc ? tgStore.activeProjectId : tgStoredSrc?.projectId
+ if (targetId !== callerProjectId) {
+ if (!tgLiveSrc && !tgStoredSrc) {
+ reply({ ok: false, error: 'source node is not in any open project' })
+ return
+ }
+ if (!sourceIsControlCapable(tgLiveSrc?.data.agentId ?? tgStoredSrc?.node.agentId)) {
+ reply({ ok: false, error: 'source node is not a control-capable agent' })
+ return
+ }
+ // Belt only — main already refused every stranger id with one byte-identical sentence
+ // (no existence oracle). This fires for a target main authorized that this renderer's
+ // store cannot see yet (mid-hydration), so it is worded transient.
+ const target = tgStore.getProject(targetId)
+ if (!target) {
+ reply({
+ ok: false,
+ error: 'project-target-refused: the target project is not available here — try again'
+ })
+ return
+ }
+ // Belt for the SSH invariant: a granted SSH id cannot exist (grants are minted only by
+ // local open-project) and main refuses ungranted ones — but if that ever breaks, the
+ // target is refused, not opened. A relay tab is another machine's project entirely.
+ if (target.ssh || target.remote) {
+ reply({
+ ok: false,
+ error:
+ 'project-target-ssh-unsupported: opening sessions into an SSH project is not supported — do not retry'
+ })
+ return
+ }
+ const tgAgentId = (verb === 'open-agent' ? args.agent : 'claude') as AgentId
+ const tgIsTerminal = verb === 'open-terminal'
+ const tgCount = Math.max(
+ 1,
+ Math.min(tgIsTerminal ? 8 : 5, parseInt(args.count || '1', 10) || 1)
+ )
+ // Defaults come from the TARGET, never the caller (spec §2.2): cwd falls back to the
+ // target project's root; the account funnel runs with the TARGET project (an account
+ // must not silently cross a project boundary, so the source node's account is NOT
+ // consulted); permission mode and launch-command overrides are the target's too.
+ const tgCwd = args.cwd || target.cwd
+ const tgAccount = tgIsTerminal
+ ? undefined
+ : resolveNewNodeAccount(undefined, target, useSettings.getState().settings.claudeAccounts)
+ const tgMode = tgIsTerminal ? undefined : projectPermissionMode(target, tgAgentId)
+ const tgActive = target.id === tgStore.activeProjectId
+ // Placement: below the lowest existing node in the TARGET (placeBelow(src) is
+ // meaningless in a project that does not contain the source). The live canvas is the
+ // truthful node set for the active project, the serialized store for any other.
+ const tgPlacedNodes = tgActive ? nodesRef.current : target.nodes
+ const tgMade: CanvasNode[] = []
+ let tgBase = { x: 0, y: 0 }
+ const tgIndexBase = tgActive ? nodesRef.current.length : target.nodes.length
+ for (let i = 0; i < tgCount; i++) {
+ const node = tgIsTerminal
+ ? createTerminalNode(tgIndexBase + i, tgCwd, { x: 0, y: 0 }, args.cmd)
+ : createAgentNode(
+ tgAgentId,
+ tgIndexBase + i,
+ tgCwd,
+ { x: 0, y: 0 },
+ args.prompt,
+ undefined,
+ tgAccount,
+ tgMode,
+ // The TARGET project: its `.nodeterm/settings.json` launch override applies to
+ // what runs in it, not the caller's.
+ target.id
+ )
+ const w = (node.width as number) ?? 640
+ const h = (node.height as number) ?? 440
+ if (i === 0) tgBase = nextFreePosition(tgPlacedNodes, { width: w, height: h })
+ node.position = { x: tgBase.x + i * (w + 60) - w / 2, y: tgBase.y - h / 2 }
+ tgMade.push(node)
+ }
+ const tgIds = tgMade.map((n) => n.id)
+ const tgWhat = tgIsTerminal ? 'terminal' : tgAgentId
+ // No ropes and no context-links in either branch: both are per-project arrays, and an
+ // edge to a node in another project has no representation (v1 — #284's linking half).
+ // The skill text names the workaround (open a reader agent inside the target project).
+ if (tgActive) {
+ // The human is looking at the target (the caller is a background orchestrator):
+ // live-canvas insertion, normal initialCommand — the session starts immediately.
+ setNodes((ns) => [...ns, ...tgMade])
+ markDirty()
+ reply({
+ ok: true,
+ message: `opened ${tgCount} ${tgWhat} session(s) in "${target.name}" (${tgIds.join(', ')})`,
+ result: { ids: tgIds, id: tgIds[0], projectId: target.id }
+ })
+ return
+ }
+ // The normal orchestration case: the target is NOT active, so its serialized store is
+ // the source of truth. The launch command MOVES into pendingLaunch (armForColdOpen —
+ // initialCommand is deliberately never serialized) and the node is upserted through
+ // the same store path sticky uses, then persisted. Cold-open contract: the session
+ // starts when that project's canvas is next shown (mount spawns the PTY, the
+ // armed-launch effect delivers with its retry loop — Task 2.0's measured round-trip).
+ for (const node of tgMade) {
+ tgStore.applyNodeMutation(target.id, {
+ op: 'upsert',
+ node: flowToNodeStates([armForColdOpen(node)])[0]
+ })
+ }
+ void writeDisk()
+ reply({
+ ok: true,
+ message:
+ `opened ${tgCount} ${tgWhat} session(s) in "${target.name}" (${tgIds.join(', ')}) — ` +
+ 'starts when that project is next viewed',
+ result: { ids: tgIds, id: tgIds[0], projectId: target.id }
+ })
+ return
+ }
+ // targetId === the caller's own project: fall through to the legacy path unchanged
+ // (B3a — behaves exactly as if --project were omitted).
+ }
// ── end of the early-handled (store-answered) verbs ─────────────────────────────────────
// Which canvas answers? React Flow holds only the ACTIVE project's nodes, but every OTHER
diff --git a/src/renderer/canvas/control-open-project.source.test.ts b/src/renderer/canvas/control-open-project.source.test.ts
index 5bee8e905..478809f34 100644
--- a/src/renderer/canvas/control-open-project.source.test.ts
+++ b/src/renderer/canvas/control-open-project.source.test.ts
@@ -72,3 +72,79 @@ describe('the open-project dispatch block (source pins)', () => {
expect(finish).toContain('writeDisk()')
})
})
+
+/** The `--project` targeted-opens block (Task 2.3): from its section rule to the end-of-early
+ * marker. */
+function targetedOpensBody(): string {
+ const start = src.indexOf('// ── `--project` targeted opens')
+ expect(start).toBeGreaterThan(-1)
+ const rest = src.slice(start)
+ const end = rest.indexOf('// ── end of the early-handled')
+ expect(end).toBeGreaterThan(-1)
+ return rest.slice(0, end)
+}
+
+describe('the --project targeted-opens block (source pins)', () => {
+ it('sits BEFORE the source-routing machinery, like open-project', () => {
+ const block = src.indexOf('// ── `--project` targeted opens')
+ const routing = src.indexOf('routeControlSource(projects, activeId, sourceNodeId)')
+ expect(block).toBeGreaterThan(-1)
+ expect(block).toBeLessThan(routing)
+ })
+
+ it('never activates or travels (B4)', () => {
+ const body = targetedOpensBody()
+ expect(body).not.toContain('setActive')
+ expect(body).not.toContain('travelToProject')
+ })
+
+ it('the gate order is refusal-before-write: every refusal precedes every store/canvas write', () => {
+ // A refused target must write NOTHING. The flag refusal, the source checks, the
+ // unknown-target belt and the SSH belt all return before the first applyNodeMutation or
+ // setNodes — moving a write above any of them is the gate-before-write mutation.
+ const body = targetedOpensBody()
+ const firstWrite = Math.min(
+ ...['applyNodeMutation', 'setNodes'].map((s) => {
+ const i = body.indexOf(s)
+ return i === -1 ? body.length : i
+ })
+ )
+ for (const refusal of [
+ 'project-target-flag-unsupported',
+ 'project-target-refused',
+ 'project-target-ssh-unsupported',
+ 'source node is not a control-capable agent'
+ ]) {
+ const at = body.indexOf(refusal)
+ expect(at, refusal).toBeGreaterThan(-1)
+ expect(at, `${refusal} after a write`).toBeLessThan(firstWrite)
+ }
+ })
+
+ it('the store path arms through armForColdOpen — the launch survives serialization', () => {
+ // flowToNodeStates drops initialCommand by design; upserting a node without moving its
+ // command into pendingLaunch is the silent-never-starts mutation (Task 2.0's pins prove the
+ // round-trip; this pins that the store path actually uses the mover).
+ const body = targetedOpensBody()
+ expect(body).toMatch(/flowToNodeStates\(\[armForColdOpen\(node\)\]\)\[0\]/)
+ })
+
+ it('the store path persists (writeDisk) and states the cold-open contract in the reply', () => {
+ const body = targetedOpensBody()
+ expect(body).toContain('writeDisk()')
+ expect(body).toContain('starts when that project is next viewed')
+ })
+
+ it('the caller’s OWN project id falls through to the legacy path (B3a) — no return on that leg', () => {
+ const body = targetedOpensBody()
+ expect(body).toContain('if (targetId !== callerProjectId)')
+ expect(body).toContain('fall through to the legacy path unchanged')
+ })
+
+ it('draws no ropes and no context-links in either branch (v1 — #284’s half)', () => {
+ const body = targetedOpensBody()
+ expect(body).not.toContain('addAndConnect')
+ expect(body).not.toContain('bridgeTo')
+ expect(body).not.toContain('connect(')
+ })
+})
diff --git a/src/renderer/lib/projectOpen.test.ts b/src/renderer/lib/projectOpen.test.ts
index a85136d89..86fd145e7 100644
--- a/src/renderer/lib/projectOpen.test.ts
+++ b/src/renderer/lib/projectOpen.test.ts
@@ -7,6 +7,7 @@ import {
findProjectByCwd,
openProjectReply,
nextFreePosition,
+ armForColdOpen,
type PlacedNode
} from './projectOpen'
@@ -189,3 +190,27 @@ describe('nextFreePosition — placement into a project the caller is not on (sp
expect(c.y).toBeGreaterThan(0)
})
})
+
+describe('armForColdOpen — the launch moves (never copies) into pendingLaunch (spec §2.2)', () => {
+ const like = (
+ initialCommand?: string
+ ): { id: string; data: { initialCommand?: string; pendingLaunch?: unknown; title: string } } => ({
+ id: 'term-x',
+ data: { initialCommand, title: 'T' }
+ })
+
+ it('moves initialCommand into pendingLaunch { after: [], command }', () => {
+ const armed = armForColdOpen(like('claude "go"'))
+ expect(armed.data.pendingLaunch).toEqual({ after: [], command: 'claude "go"' })
+ // MOVED, not copied: initialCommand is deliberately never serialized (workspace.ts), so a
+ // copy left behind is dead weight and a command left ONLY there is silently dropped — the
+ // node would never start. The serialization round-trip pin lives in
+ // workspace.cold-open.test.ts; this is the construction-site half.
+ expect(armed.data.initialCommand).toBeUndefined()
+ })
+
+ it('a node with no command is returned unchanged (a plain terminal just opens)', () => {
+ const node = like(undefined)
+ expect(armForColdOpen(node)).toBe(node)
+ })
+})
diff --git a/src/renderer/lib/projectOpen.ts b/src/renderer/lib/projectOpen.ts
index 7dbc72bcb..1d4cdcca0 100644
--- a/src/renderer/lib/projectOpen.ts
+++ b/src/renderer/lib/projectOpen.ts
@@ -141,6 +141,26 @@ export function openProjectReply(
}
}
+/**
+ * Re-arm a freshly-built node for a COLD open (spec §2.2): its composed launch command is MOVED —
+ * never copied — from `initialCommand` into `pendingLaunch: { after: [], command }`.
+ * `initialCommand` is deliberately never serialized (workspace.ts), while `pendingLaunch` is: a
+ * command left in `initialCommand` on the store path would be silently dropped by serialization
+ * and the node would never start; a copy left behind would double-deliver if that ever changed.
+ * An empty `after` is vacuously ready (`launchesToFire`), so the armed-launch effect fires it on
+ * the target project's first view — the cold-open contract.
+ */
+export function armForColdOpen<
+ T extends { data: { initialCommand?: string; pendingLaunch?: unknown } }
+>(node: T): T {
+ const command = node.data.initialCommand
+ if (!command) return node
+ return {
+ ...node,
+ data: { ...node.data, initialCommand: undefined, pendingLaunch: { after: [], command } }
+ }
+}
+
/** A node as either the serialized store or the live canvas holds it — enough for placement. */
export interface PlacedNode {
id?: string
diff --git a/src/renderer/state/permissionMode.ts b/src/renderer/state/permissionMode.ts
index 70fb937f7..a0cdf152c 100644
--- a/src/renderer/state/permissionMode.ts
+++ b/src/renderer/state/permissionMode.ts
@@ -95,9 +95,20 @@ function autoSupportedFor(project: Project | undefined): boolean {
* (createProject) — importing the projects store from workspace.ts would close that cycle.
*/
export function activePermissionMode(agentId: AgentId = 'claude'): AgentPermissionMode {
- const { settings } = useSettings.getState()
const { getProject, activeProjectId } = useProjects.getState()
- const project = getProject(activeProjectId)
+ return projectPermissionMode(getProject(activeProjectId), agentId)
+}
+
+/**
+ * The same resolution for an EXPLICIT project — the `--project`-targeted opens (issue #338) need
+ * the TARGET project's override + gate, not the active one's: a node opened into another project
+ * must start with that project's permission mode (spec §2.2 defaults), never the caller's.
+ */
+export function projectPermissionMode(
+ project: Project | undefined,
+ agentId: AgentId = 'claude'
+): AgentPermissionMode {
+ const { settings } = useSettings.getState()
const mode = resolvePermissionMode(project, settings)
// The version gate is CLAUDE-specific BY CONSTRUCTION: it exists because Claude Code < 2.1.71
// exits 1 on `--permission-mode auto`, and it is fed by a `claude --version` probe (local, or the