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(canvas-control): --dry-run validates a spawn call without performing it (#532)

enes3f073c3bb24e
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 3d5a10e40..33e3a25da 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -14,6 +14,7 @@ import {
} from '../core/agents/hook-sandbox-hint-sh'
import { RETRYABLE } from '../core/agents/agent-message-decide'
import { PROJECT_TARGETABLE_VERBS } from './project-grants'
+import { DRY_RUN_VERBS } from '../shared/control-verbs'
import { STRICT_CONTROL_VERBS } from '../core/agents/node-identity-policy'
import { BROWSER_ACTION_KEYS } from '../core/browser-verb'
import { BROWSER_RETRYABLE, BROWSER_OUTCOME_LABEL } from '../core/browser-outcomes'
@@ -315,6 +316,19 @@ describe('parseControlRequest', () => {
}
})
+ it('both agent-facing texts document --dry-run, derived from DRY_RUN_VERBS (issue #532)', () => {
+ for (const body of [buildCanvasSkillBody('/x/shim.sh'), buildCanvasControlInstructions('/tmp/nodeterm.sh')]) {
+ expect(body).toContain('--dry-run')
+ // The verb list is RENDERED from the set (dryRunDocLines) — walk the real set so a verb
+ // added to the gate lands in the text the day it is added, and a removed one reds here.
+ for (const v of DRY_RUN_VERBS) expect(body).toContain(v)
+ // Both hard edges must be stated, or an agent discovers them by losing a call to each:
+ // unsupported verbs refuse, and --project cannot be combined.
+ expect(body.toLowerCase()).toContain('refuses `--dry-run`')
+ expect(body).toContain('cannot be combined with `--project`')
+ }
+ })
+
it('both agent-facing texts document --prompt-file and the one-line --prompt fact (issue #520)', () => {
for (const body of [buildCanvasSkillBody('/x/shim.sh'), buildCanvasControlInstructions('/tmp/nodeterm.sh')]) {
// `assembleLaunchCommand` collapses every whitespace run in a --prompt literal (it rides
diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.ts
index 62d121fd6..2c25a2238 100644
--- a/src/main/canvas-control-core.ts
+++ b/src/main/canvas-control-core.ts
@@ -185,6 +185,23 @@ const VERBS: ControlVerb[] = [
* dispatch stop agreeing.
*/
export { isDestructiveVerb, DESTRUCTIVE_VERBS } from '../shared/control-verbs'
+// Imported (not only re-exported) because the agent-facing bodies RENDER the dry-run verb list
+// from the set — the same derive-don't-retype rule as `messagingGuidanceLines`, so the docs can
+// never name a verb the gate does not honour.
+import { DRY_RUN_VERBS } from '../shared/control-verbs'
+
+/** The `--dry-run` paragraph both agent-facing bodies share, rendered from `DRY_RUN_VERBS`. */
+function dryRunDocLines(): string[] {
+ return [
+ `Add \`--dry-run\` to a spawn verb (${[...DRY_RUN_VERBS].join(', ')}) to validate the call`,
+ 'WITHOUT opening anything: it runs the same validation as a real call — ids resolved against',
+ 'the live canvas, the team JSON parsed role by role, the worktree path computed — and replies',
+ 'with what WOULD happen, or the exact refusal. Use it to vet a `spawn-team` payload, a',
+ '`--group`/`--after` id or a `--prompt-file` path before fanning out: these verbs are cheap to',
+ 'call and expensive to undo, and the dry run moves the mistake to the cheap side. Every other',
+ 'verb refuses `--dry-run` (nothing is done), and it cannot be combined with `--project`.'
+ ]
+}
/** Validate a raw (verb, args) pair into a ControlCommand, or return an { error }. */
export function parseControlRequest(
@@ -286,6 +303,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {
'starts with `--` (`--cmd=--version`); written as two tokens, a leading `--` is read as the next',
'flag. A flag with no value is allowed anywhere on the line.',
'',
+ ...dryRunDocLines(),
+ '',
'Verbs:',
'- `list` — current nodes (id, kind, title). Start here when you need a node id.',
'- `help` — print the verb list. Answered by the shim itself, so it works even if the app is down.',
@@ -657,6 +676,8 @@ starts with \`--\` (\`--cmd=--version\`); written as two tokens, a leading \`--\
next flag, so \`--text --oops\` sends an empty \`--text\` plus a stray \`--oops\`. A flag with no
value is allowed anywhere on the line, not only at the end.
+${dryRunDocLines().join('\n')}
+
Verbs:
- \`list\` — list current nodes (id, kind, title). Start here when you need a node id.
- \`help\` — print the verb list. The shim answers this itself, without reaching the app, so it
diff --git a/src/main/canvas-control-shim.test.ts b/src/main/canvas-control-shim.test.ts
index cb0bea9d3..cc3582ef7 100644
--- a/src/main/canvas-control-shim.test.ts
+++ b/src/main/canvas-control-shim.test.ts
@@ -679,6 +679,14 @@ describe('parseControlBody', () => {
it('degrades to an empty command on garbage rather than throwing', () => {
expect(parseControlBody('not json', 'application/json')).toEqual({ nodeId: '', args: {} })
})
+
+ it("reads the shim's valueless --dry-run as an empty-string arg (issue #532)", () => {
+ // The sh loop translates a valueless `--dry-run` to `arg.dry-run=`; the server must land it
+ // as `args['dry-run'] === ''`, which `dryRunRequested` reads as ON.
+ expect(
+ parseControlBody('nodeId=n1&arg.dry-run=&arg.team=%5B%5D', 'application/x-www-form-urlencoded')
+ ).toEqual({ nodeId: 'n1', args: { 'dry-run': '', team: '[]' } })
+ })
})
describe('sticky through the shim (verified-only verb)', () => {
diff --git a/src/main/control-shim-parse.test.ts b/src/main/control-shim-parse.test.ts
index 648f073de..319901c1f 100644
--- a/src/main/control-shim-parse.test.ts
+++ b/src/main/control-shim-parse.test.ts
@@ -82,6 +82,15 @@ describe('the control shim translates flags', () => {
expect(run(['rename', '--node', 'n1', '--title='])).toEqual(['arg.node=n1', 'arg.title='])
})
+ // `--dry-run` is valueless and usually mid-line (issue #532): the peek must leave the next
+ // `--flag` alone and translate it to an explicit empty `arg.dry-run=`.
+ it('--dry-run rides as a valueless flag anywhere on the line', () => {
+ expect(run(['spawn-team', '--dry-run', '--team', '[]'])).toEqual([
+ 'arg.dry-run=',
+ 'arg.team=[]'
+ ])
+ })
+
// Hyphenated flag names ride through as-is — the loop strips only the leading `--`, so
// `--prompt-file` lands as `arg.prompt-file` and the server reads args['prompt-file'].
it('a hyphenated flag name (--prompt-file) keeps its hyphen in the arg key', () => {
diff --git a/src/main/index.ts b/src/main/index.ts
index 70f2b3b8a..bf48bf398 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -216,6 +216,7 @@ import { buildHandoff, type HandoffRemote } from './handoff'
import { initContextLink, setNodeTranscript } from '../core/context-link'
import { transcriptPathOf } from '../core/context-link-core'
import { initCanvasControl, installCanvasSkillInto } from './canvas-control'
+import { DRY_RUN_VERBS, dryRunRequested, dryRunRefusal } from '../shared/control-verbs'
import { initTranscriptIndex, searchTranscripts } from '../core/transcript-index'
import { initTelemetry } from './telemetry'
import { initClaudeUsage } from './claude-usage'
@@ -3102,6 +3103,15 @@ app.whenReady().then(async () => {
const projectIdOfNode = (id: string): string | undefined =>
workspaceStore.persistedCanvases().find((c) => c.nodes.some((n) => n.id === id))?.id
hookServer.setControlHandler(async ({ verb, nodeId, args, verified }) => {
+ // `--dry-run` (issue #532) is honoured by the spawn verbs only, and this gate runs FIRST —
+ // before the browser intercept, the open-project gates and the renderer forward — because a
+ // verb that cannot dry-run must REFUSE rather than silently perform: a `close --dry-run`
+ // that closes is worse than no flag at all. Supported verbs pass through with the flag
+ // intact; their renderer dispatch case stops before the mutation.
+ if (dryRunRequested(args) && !DRY_RUN_VERBS.has(verb)) {
+ const msg = dryRunRefusal(verb)
+ return { ok: false, error: msg, message: msg }
+ }
// `browser` is answered in MAIN and never forwarded to the renderer's agent-control dispatch:
// the debugger handle and the CDP allowlist are main-side, and the renderer is the more
// attackable half. Every other verb still round-trips to the renderer below.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 6eff80499..e47f02c3c 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -367,6 +367,7 @@ import {
} from '@shared/agents/config'
import { withPermissionMode } from '@shared/agents/approval-mode'
import { promptFilePathError } from '@shared/agents/launch'
+import { parseTeamSpec } from '../lib/teamSpec'
import { relativeTime } from '../lib/relativeTime'
import { AgentIcon } from '../lib/agentIcons'
import { branchClaudeSession } from '../lib/claudeBranch'
@@ -436,7 +437,7 @@ import { chordHeld, isHoldChord, isModifierEventKey, matchesShortcut } from '@sh
// The dispatch below is the CONSUMER of the confirm-gated set. Before this import the set named
// write/close as "the confirm-gated pair" from inside `src/main` — which this project cannot see —
// while the gating lived in two hand-written blocks here, so the set decided nothing.
-import { isDestructiveVerb } from '@shared/control-verbs'
+import { isDestructiveVerb, dryRunRequested } from '@shared/control-verbs'
import { canvasSyncTarget } from './collab-sync'
import {
applyCanvasMutation,
@@ -7912,6 +7913,12 @@ export function Canvas() {
return api.onAgentControl(async ({ requestId, sourceNodeId, verb, args }) => {
const reply = (r: { ok: boolean; message?: string; result?: unknown; error?: string }) =>
api.sendAgentControlResult({ requestId, ...r })
+ // `--dry-run` (issue #532): validate + report, mutate nothing. Only DRY_RUN_VERBS reach
+ // this process with the flag set — main's setControlHandler refuses it for every other
+ // verb before forwarding — so the per-case branches below are the whole renderer story:
+ // each runs the SAME validation as a real call and stops just before the mutation.
+ const dryRun = dryRunRequested(args)
+ const DRY_RUN_PREFIX = 'DRY RUN — nothing was opened or changed.'
// ── Agent messaging (`send`/`reply`) — handled BEFORE the source-routing machinery ──────
// These are STORE_ANSWERED_VERBS (lib/controlRouting): routing by source must never travel
@@ -8080,6 +8087,13 @@ export function Canvas() {
(verb === 'open-terminal' || verb === 'open-claude' || verb === 'open-agent') &&
args.project !== undefined
) {
+ // `--dry-run` validates against the LIVE canvas; a `--project` open lands in another
+ // project's serialized store through a different code path, and a "validate only" copy of
+ // that path is exactly the rot #532 warns about. Refused, not silently run.
+ if (dryRun) {
+ reply({ ok: false, error: `${verb}: --dry-run cannot be combined with --project` })
+ return
+ }
const targetId = args.project
// v1 excludes the flags that name ids inside another project (spec §2.2). The decision is
// the PURE projectTargetFlagRefusal — red-capable in projectOpen.test.ts (review #363
@@ -8593,6 +8607,27 @@ export function Canvas() {
const after = resolveAfter()
if (after === null) return // bad --after, already replied
const termCwd = args.cwd || groupCwd || srcCwd
+ if (dryRun) {
+ reply({
+ ok: true,
+ message: [
+ DRY_RUN_PREFIX,
+ `open-terminal would open ${count} terminal(s)` +
+ (intoGroupId ? ` in group ${intoGroupId}` : '') +
+ (termCwd ? `, cwd ${termCwd}` : '') +
+ (args.cmd ? `, running: ${args.cmd}` : ''),
+ ...(after?.length ? [`armed to wait for: ${after.join(', ')}`] : [])
+ ].join('\n'),
+ result: {
+ dryRun: true,
+ count,
+ group: intoGroupId ?? null,
+ cwd: termCwd ?? null,
+ after: after ?? []
+ }
+ })
+ return
+ }
const make = (i: number): CanvasNode =>
armAfter(
createTerminalNode(
@@ -8669,6 +8704,47 @@ export function Canvas() {
}
}
const agentCwd = args.cwd || groupCwd || srcCwd
+ if (dryRun) {
+ // The dry run is deliberately STRICTER than the real open here: an unknown agent id
+ // today opens a node whose launch command is the typo, failing only inside its pane
+ // — precisely the "validated by running it" cost #532 names. Catch it when asked.
+ const dryKnownAgent =
+ !!agentConfig(agentId) ||
+ useSettings.getState().settings.customAgents.some((c) => c.id === agentId)
+ if (!dryKnownAgent) {
+ reply({
+ ok: false,
+ error: `${verb}: unknown agent "${agentId}" — pass a builtin id or a custom agent id from Settings`
+ })
+ return
+ }
+ reply({
+ ok: true,
+ message: [
+ DRY_RUN_PREFIX,
+ `${verb} would open ${count} ${agentId} session(s)` +
+ (intoGroupId ? ` in group ${intoGroupId}` : '') +
+ (agentCwd ? `, cwd ${agentCwd}` : '') +
+ (args.model ? `, model ${args.model}` : '') +
+ (promptFile
+ ? `, prompt from file ${promptFile}`
+ : args.prompt
+ ? `, prompt: "${args.prompt.slice(0, 80)}${args.prompt.length > 80 ? '…' : ''}"`
+ : ''),
+ ...(after?.length ? [`armed to wait for: ${after.join(', ')}`] : []),
+ 'Each session would be connected + context-linked to you.'
+ ].join('\n'),
+ result: {
+ dryRun: true,
+ agent: agentId,
+ count,
+ group: intoGroupId ?? null,
+ cwd: agentCwd ?? null,
+ after: after ?? []
+ }
+ })
+ return
+ }
const make = (i: number): CanvasNode =>
armAfter(
createAgentNode(
@@ -9111,59 +9187,54 @@ export function Canvas() {
return
}
case 'spawn-team': {
- let roles: {
- title?: string
- prompt?: string
- promptFile?: string
- agent?: string
- model?: string
- }[]
- try {
- const parsed = JSON.parse(args.team ?? '')
- roles = Array.isArray(parsed) ? parsed : []
- } catch {
- reply({
- ok: false,
- error:
- 'spawn-team: --team must be a JSON array of {title?, prompt|promptFile, agent?, model?}'
- })
+ // Parse + validate through the ONE pure parser (lib/teamSpec.ts) the dry run shares —
+ // named refusals for bad JSON, a role missing its prompt, a ninth role, an unknown
+ // agent id — instead of the old silent filter-and-slice, where a role without a
+ // prompt simply vanished and a typo'd agent opened a broken node (issue #532).
+ const teamKnownAgents = new Set<string>([
+ ...BUILTIN_AGENT_IDS,
+ ...useSettings.getState().settings.customAgents.map((c) => c.id)
+ ])
+ const teamSpec = parseTeamSpec(args.team ?? '', teamKnownAgents)
+ if (!teamSpec.ok) {
+ reply({ ok: false, error: `spawn-team: ${teamSpec.error}` })
return
}
- roles = roles
- .filter(
- (r) =>
- r &&
- ((typeof r.prompt === 'string' && r.prompt.trim()) ||
- (typeof r.promptFile === 'string' && r.promptFile.trim()))
- )
- .slice(0, 8)
- if (roles.length === 0) {
- reply({
- ok: false,
- error: 'spawn-team: --team needs at least one role with a prompt (or promptFile)'
- })
- return
- }
- // Per-role `promptFile` — the same contract as `--prompt-file` on the open verbs
- // (issue #520): path shape by the pure rule, existence against the filesystem the new
- // node reads it from, missing file refused (an empty `$(cat …)` would silently start
- // the member with no task), a check that errors fails open.
+ const roles = teamSpec.roles
+ // Per-role `promptFile` existence — the same contract as `--prompt-file` on the open
+ // verbs (issue #520): checked against the filesystem the new node reads it from,
+ // missing refused (an empty `$(cat …)` would silently start the member with no task),
+ // a check that errors fails open. Path SHAPE is the parser's job.
for (const [ri, r] of roles.entries()) {
- const rf = typeof r.promptFile === 'string' ? r.promptFile.trim() : ''
- if (!rf) continue
- const roleName = r.title?.trim() ? `"${r.title.trim()}"` : `#${ri + 1}`
- const rfErr = promptFilePathError(rf)
- if (rfErr) {
- reply({ ok: false, error: `spawn-team: role ${roleName} promptFile ${rfErr}` })
- return
- }
+ if (!r.promptFile) continue
+ const rName = r.title ? `"${r.title}"` : `#${ri + 1}`
const rfFs = ctlSsh && ctlProject ? sshFs(ctlProject.id) : api.fs
- const rfExists = await rfFs.exists(rf).catch(() => true)
+ const rfExists = await rfFs.exists(r.promptFile).catch(() => true)
if (!rfExists) {
- reply({ ok: false, error: `spawn-team: role ${roleName} promptFile not found: ${rf}` })
+ reply({
+ ok: false,
+ error: `spawn-team: role ${rName} promptFile not found: ${r.promptFile}`
+ })
return
}
}
+ if (dryRun) {
+ reply({
+ ok: true,
+ message: [
+ DRY_RUN_PREFIX,
+ `spawn-team would open ${roles.length} member(s) in a new group "${args.label || 'Team'}", each connected + context-linked to you:`,
+ ...roles.map((r, i) => {
+ const brief = r.promptFile
+ ? `prompt from file ${r.promptFile}`
+ : `prompt: "${(r.prompt ?? '').slice(0, 80)}${(r.prompt ?? '').length > 80 ? '…' : ''}"`
+ return ` ${i + 1}. ${r.title ?? r.agent} — agent ${r.agent}${r.model ? `, model ${r.model}` : ''} — ${brief}`
+ })
+ ].join('\n'),
+ result: { dryRun: true, label: args.label || 'Team', roles }
+ })
+ return
+ }
const live = nodesRef.current as CanvasNode[]
// Same account funnel as open-claude/open-agent above; per-role the factory
// drops the account for non-claude agents.
@@ -9177,7 +9248,8 @@ export function Canvas() {
const members = roles.map((r, i) => {
// Roles may name different agents, so the mode is resolved PER member: claude's
// `auto` version gate must not decide what a grok teammate launches with.
- const memberAgent = (r.agent ?? 'claude') as AgentId
+ // (`agent` is parser-defaulted to 'claude' and validated against the known set.)
+ const memberAgent = r.agent as AgentId
const node = createAgentNode(
memberAgent,
live.length + i,
@@ -9190,11 +9262,10 @@ export function Canvas() {
teamStore.activeProjectId,
// Per-role model, so one team can mix tiers in a single call. A role naming a
// model its agent cannot switch simply launches bare (withAgentModel no-ops).
- typeof r.model === 'string' ? r.model : undefined,
- // Per-role promptFile (validated above); wins over `prompt` in the assembler.
- typeof r.promptFile === 'string' && r.promptFile.trim()
- ? r.promptFile.trim()
- : undefined
+ r.model,
+ // Per-role promptFile (parser-validated + existence-checked above); wins over
+ // `prompt` in the assembler.
+ r.promptFile
)
return r.title ? { ...node, data: { ...node.data, title: r.title, titleAuto: false } } : node
})
@@ -9287,6 +9358,25 @@ export function Canvas() {
reply({ ok: false, error: 'open-worktree: could not derive a worktree path — pass --path' })
return
}
+ if (dryRun) {
+ reply({
+ ok: true,
+ message: [
+ DRY_RUN_PREFIX,
+ `open-worktree would create branch "${branch}" off ${baseRef || 'the repo default branch'} at ${wtPath}, ` +
+ `bound to ${bindGroupId ? `group ${bindGroupId}` : 'a new group frame'}.`,
+ 'The base ref is not verified against git in a dry run — a bad ref still fails at create time.'
+ ].join('\n'),
+ result: {
+ dryRun: true,
+ branch,
+ baseRef: baseRef || null,
+ path: wtPath,
+ group: bindGroupId
+ }
+ })
+ return
+ }
const res = await api.git
.worktreeAdd(repoRoot, wtPath, branch, baseRef, true)
.catch((e: unknown) => ({
diff --git a/src/renderer/lib/teamSpec.test.ts b/src/renderer/lib/teamSpec.test.ts
new file mode 100644
index 000000000..424656738
--- /dev/null
+++ b/src/renderer/lib/teamSpec.test.ts
@@ -0,0 +1,84 @@
+import { describe, it, expect } from 'vitest'
+import { parseTeamSpec, TEAM_MAX_ROLES } from './teamSpec'
+
+const KNOWN = new Set(['claude', 'codex', 'gemini', 'custom:mine'])
+
+const err = (raw: string): string => {
+ const r = parseTeamSpec(raw, KNOWN)
+ if (r.ok) throw new Error('expected a refusal')
+ return r.error
+}
+
+describe('parseTeamSpec — the happy path', () => {
+ it('parses roles, defaulting agent to claude and trimming fields', () => {
+ const r = parseTeamSpec(
+ '[{"title":" UI ","prompt":"build it","model":" sonnet "},{"prompt":"test it","agent":"codex"}]',
+ KNOWN
+ )
+ expect(r).toEqual({
+ ok: true,
+ roles: [
+ { title: 'UI', prompt: 'build it', agent: 'claude', model: 'sonnet' },
+ { prompt: 'test it', agent: 'codex' }
+ ]
+ })
+ })
+ it('accepts promptFile in place of prompt', () => {
+ const r = parseTeamSpec('[{"title":"UI","promptFile":"/tmp/brief.md"}]', KNOWN)
+ expect(r).toEqual({
+ ok: true,
+ roles: [{ title: 'UI', promptFile: '/tmp/brief.md', agent: 'claude' }]
+ })
+ })
+ it('accepts a custom agent id when it is in the known set', () => {
+ const r = parseTeamSpec('[{"prompt":"x","agent":"custom:mine"}]', KNOWN)
+ expect(r.ok).toBe(true)
+ })
+})
+
+describe('parseTeamSpec — every mistake is a NAMED refusal (issue #532)', () => {
+ it('empty payload', () => {
+ expect(err('')).toMatch(/--team is empty/)
+ })
+ it('invalid JSON names the parse error and shows the expected shape', () => {
+ const e = err('[{"title":"UI"')
+ expect(e).toMatch(/not valid JSON/)
+ expect(e).toContain('promptFile')
+ })
+ it('a bare object is refused as not-an-array', () => {
+ expect(err('{"prompt":"x"}')).toMatch(/ARRAY/)
+ })
+ it('an empty array is refused', () => {
+ expect(err('[]')).toMatch(/at least one role/)
+ })
+ it(`a ${TEAM_MAX_ROLES + 1}th role is refused, not silently sliced off`, () => {
+ const roles = JSON.stringify(
+ Array.from({ length: TEAM_MAX_ROLES + 1 }, (_, i) => ({ prompt: `t${i}` }))
+ )
+ expect(err(roles)).toMatch(new RegExp(`${TEAM_MAX_ROLES + 1} roles — max ${TEAM_MAX_ROLES}`))
+ })
+ it('a role missing its prompt is refused BY NAME, not silently dropped', () => {
+ // The old inline parse filtered this role out: the team opened short and nobody said which
+ // role vanished. Now the reply names it.
+ expect(err('[{"prompt":"a"},{"title":"Docs"}]')).toContain('"Docs"')
+ expect(err('[{"prompt":"a"},{}]')).toContain('#2')
+ })
+ it('a role with both prompt and promptFile is refused', () => {
+ expect(err('[{"title":"UI","prompt":"a","promptFile":"/x"}]')).toMatch(/not both/)
+ })
+ it('a non-string field is refused by field name', () => {
+ expect(err('[{"prompt":42}]')).toContain('"prompt" must be a string')
+ expect(err('[{"prompt":"a","model":7}]')).toContain('"model" must be a string')
+ })
+ it('a relative promptFile is refused (same rule as --prompt-file)', () => {
+ expect(err('[{"title":"UI","promptFile":"brief.md"}]')).toMatch(/absolute/)
+ })
+ it('an unknown agent id is refused with the known list', () => {
+ const e = err('[{"prompt":"x","agent":"claudee"}]')
+ expect(e).toContain('unknown agent "claudee"')
+ expect(e).toContain('codex')
+ })
+ it('a non-object role is refused by position', () => {
+ expect(err('["just a string"]')).toContain('#1')
+ })
+})
diff --git a/src/renderer/lib/teamSpec.ts b/src/renderer/lib/teamSpec.ts
new file mode 100644
index 000000000..c7b537598
--- /dev/null
+++ b/src/renderer/lib/teamSpec.ts
@@ -0,0 +1,109 @@
+// Pure parser for `spawn-team --team <json>` (issue #532). One parser, two consumers — the REAL
+// spawn path and `--dry-run` — so the dry run can never validate a different grammar than the run
+// it stands in for (the rot the issue warns about: a hand-maintained "validate only" copy drifts).
+//
+// It exists because the old inline parse made every mistake SILENT: a role missing a `prompt` was
+// filtered out (the team opened short, nobody said which role vanished), a ninth role was sliced
+// off, a typo'd `agent` id opened a broken node that failed only inside its pane. Each of those is
+// now a named refusal — the caller learns which role and which field, before anything opens.
+import { promptFilePathError } from '@shared/agents/launch'
+
+export const TEAM_MAX_ROLES = 8
+
+export interface TeamRole {
+ title?: string
+ prompt?: string
+ promptFile?: string
+ /** Defaulted to 'claude' when the role names none — the historical behavior, made explicit. */
+ agent: string
+ model?: string
+}
+
+export type TeamSpecResult = { ok: true; roles: TeamRole[] } | { ok: false; error: string }
+
+const SHAPE = '{title?, prompt|promptFile, agent?, model?}'
+
+/** A role's name for an error message: its title when it has one, else its 1-based position. */
+function roleName(r: { title?: unknown }, i: number): string {
+ return typeof r.title === 'string' && r.title.trim() ? `"${r.title.trim()}"` : `#${i + 1}`
+}
+
+/**
+ * Parse + validate a `--team` payload. `knownAgentIds` is the full agent inventory (builtins +
+ * the user's custom agents): a role naming anything else is refused HERE, at parse time, instead
+ * of opening a node whose launch command is a typo — the exact "validated by running it" cost
+ * issue #532 names. Error messages are bare (no `spawn-team:` prefix — the caller adds it).
+ */
+export function parseTeamSpec(raw: string, knownAgentIds: ReadonlySet<string>): TeamSpecResult {
+ const trimmed = (raw ?? '').trim()
+ if (!trimmed) {
+ return { ok: false, error: `--team is empty — pass a JSON array of ${SHAPE} role objects` }
+ }
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(trimmed)
+ } catch (e) {
+ const why = e instanceof Error ? e.message : String(e)
+ return {
+ ok: false,
+ error:
+ `--team is not valid JSON (${why}). Expected a JSON array of ${SHAPE} role objects — ` +
+ `quote the whole value in the shell: --team '[{"title":"UI","prompt":"..."}]'`
+ }
+ }
+ if (!Array.isArray(parsed)) {
+ return { ok: false, error: `--team must be a JSON ARRAY of ${SHAPE} role objects, not a ${typeof parsed === 'object' ? 'single object' : typeof parsed}` }
+ }
+ if (parsed.length === 0) {
+ return { ok: false, error: '--team needs at least one role with a prompt (or promptFile)' }
+ }
+ if (parsed.length > TEAM_MAX_ROLES) {
+ return {
+ ok: false,
+ error: `--team has ${parsed.length} roles — max ${TEAM_MAX_ROLES} per call; split into two calls`
+ }
+ }
+ const roles: TeamRole[] = []
+ for (const [i, r] of parsed.entries()) {
+ if (typeof r !== 'object' || r === null || Array.isArray(r)) {
+ return { ok: false, error: `role #${i + 1} is not an object (${SHAPE})` }
+ }
+ const role = r as Record<string, unknown>
+ const name = roleName(role, i)
+ for (const field of ['title', 'prompt', 'promptFile', 'agent', 'model'] as const) {
+ if (role[field] !== undefined && typeof role[field] !== 'string') {
+ return { ok: false, error: `role ${name}: "${field}" must be a string` }
+ }
+ }
+ const prompt = typeof role.prompt === 'string' ? role.prompt.trim() : ''
+ const promptFile = typeof role.promptFile === 'string' ? role.promptFile.trim() : ''
+ if (prompt && promptFile) {
+ return { ok: false, error: `role ${name}: pass either "prompt" or "promptFile", not both` }
+ }
+ if (!prompt && !promptFile) {
+ return {
+ ok: false,
+ error: `role ${name} is missing a non-empty "prompt" (or "promptFile") — every member needs a starting task`
+ }
+ }
+ if (promptFile) {
+ const pfErr = promptFilePathError(promptFile)
+ if (pfErr) return { ok: false, error: `role ${name}: promptFile ${pfErr}` }
+ }
+ const agent = typeof role.agent === 'string' && role.agent.trim() ? role.agent.trim() : 'claude'
+ if (!knownAgentIds.has(agent)) {
+ return {
+ ok: false,
+ error: `role ${name}: unknown agent "${agent}" — known agents: ${[...knownAgentIds].join(', ')}`
+ }
+ }
+ roles.push({
+ ...(typeof role.title === 'string' && role.title.trim() ? { title: role.title.trim() } : {}),
+ ...(prompt ? { prompt } : {}),
+ ...(promptFile ? { promptFile } : {}),
+ agent,
+ ...(typeof role.model === 'string' && role.model.trim() ? { model: role.model.trim() } : {})
+ })
+ }
+ return { ok: true, roles }
+}
diff --git a/src/shared/control-verbs.test.ts b/src/shared/control-verbs.test.ts
new file mode 100644
index 000000000..4db4d27ef
--- /dev/null
+++ b/src/shared/control-verbs.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect } from 'vitest'
+import { DRY_RUN_VERBS, dryRunRequested, dryRunRefusal } from './control-verbs'
+
+describe('dryRunRequested', () => {
+ it('absent means no dry run', () => {
+ expect(dryRunRequested({})).toBe(false)
+ expect(dryRunRequested({ count: '2' })).toBe(false)
+ })
+ it("the shim's valueless flag (empty string) means ON", () => {
+ // `sh nodeterm.sh spawn-team --dry-run --team …` translates to `arg.dry-run=` — an empty
+ // string. Reading that as off would run the real mutation under a flag that asked it not to.
+ expect(dryRunRequested({ 'dry-run': '' })).toBe(true)
+ })
+ it('explicit truthy spellings are ON', () => {
+ for (const v of ['true', 'yes', '1']) expect(dryRunRequested({ 'dry-run': v })).toBe(true)
+ })
+ it('explicit off-values are OFF', () => {
+ for (const v of ['false', 'no', '0', 'FALSE', ' No ']) {
+ expect(dryRunRequested({ 'dry-run': v })).toBe(false)
+ }
+ })
+ it('an unrecognized value fails toward DRY (the safe direction)', () => {
+ expect(dryRunRequested({ 'dry-run': 'maybe' })).toBe(true)
+ })
+})
+
+describe('DRY_RUN_VERBS', () => {
+ it('covers exactly the spawn verbs', () => {
+ expect([...DRY_RUN_VERBS].sort()).toEqual(
+ ['open-agent', 'open-claude', 'open-terminal', 'open-worktree', 'spawn-team'].sort()
+ )
+ })
+ it('never contains a destructive or read verb', () => {
+ for (const v of ['write', 'close', 'open-project', 'list', 'board', 'browser']) {
+ expect(DRY_RUN_VERBS.has(v)).toBe(false)
+ }
+ })
+})
+
+describe('dryRunRefusal', () => {
+ it('names the verb and derives the supported list from the set', () => {
+ const msg = dryRunRefusal('close')
+ expect(msg).toContain('close')
+ for (const v of DRY_RUN_VERBS) expect(msg).toContain(v)
+ expect(msg).toContain('Nothing was done')
+ })
+})
diff --git a/src/shared/control-verbs.ts b/src/shared/control-verbs.ts
index 7e3609248..1fa41fce7 100644
--- a/src/shared/control-verbs.ts
+++ b/src/shared/control-verbs.ts
@@ -53,3 +53,46 @@ export const DESTRUCTIVE_VERBS: ReadonlySet<string> = new Set(['write', 'close',
export function isDestructiveVerb(verb: string): boolean {
return DESTRUCTIVE_VERBS.has(verb)
}
+
+/**
+ * Verbs that honour `--dry-run` (issue #532): validate the call — the SAME validation a real call
+ * runs, ids resolved against the live canvas — and report what would happen, changing nothing.
+ *
+ * Deliberately only the SPAWN verbs. The asymmetry the issue names is that these are easy to call
+ * and expensive to undo (a mis-spawned team is N nodes to clean up by hand; a bad `--after` id
+ * arms a station against nothing); `list`/`board` are already reads, and the mutating verbs
+ * outside this set are either cheap to reverse (`rename`, `assign`) or human-confirmed
+ * (`write`/`close`). A verb OUTSIDE this set must REFUSE `--dry-run`, never silently perform —
+ * a `close --dry-run` that closes is strictly worse than no flag at all. That refusal is decided
+ * in MAIN's control handler (src/main/index.ts, setControlHandler's first gate), which every
+ * control dispatch passes through, `browser` and `open-project` included.
+ *
+ * Same `string` typing rationale as DESTRUCTIVE_VERBS above: both sides read this set, and the
+ * renderer's dispatch receives a raw `verb: string` off IPC.
+ */
+export const DRY_RUN_VERBS: ReadonlySet<string> = new Set([
+ 'open-terminal',
+ 'open-claude',
+ 'open-agent',
+ 'spawn-team',
+ 'open-worktree'
+])
+
+/**
+ * Did the caller ask for a dry run? Presence-based, because the sh shim translates a valueless
+ * `--dry-run` to `arg.dry-run=` (empty string) — so `''` MUST read as on. The explicit
+ * off-values exist for the `--dry-run=false` a caller writes to be safe; anything else present
+ * is on (guessing "off" for an unrecognized value would run the real mutation under a flag that
+ * asked it not to — the unsafe direction).
+ */
+export function dryRunRequested(args: Record<string, string | undefined>): boolean {
+ const v = args['dry-run']
+ if (v === undefined) return false
+ return !/^(false|no|0)$/i.test(v.trim())
+}
+
+/** The refusal for `--dry-run` on a verb outside DRY_RUN_VERBS — derived from the set so the
+ * sentence can never name a verb the gate does not honour. */
+export function dryRunRefusal(verb: string): string {
+ return `--dry-run is not supported for ${verb} — it applies to: ${[...DRY_RUN_VERBS].join(', ')}. Nothing was done.`
+}