Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
Merge branch 'fix/spill-long-prompt-cold-open' into feat/after-until-pr
review41222a5eb271
diff --cc src/renderer/canvas/Canvas.tsxindex b004395a2,16e1f73fc..ec1f59237--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@@ -507,7 -507,8 +507,9 @@@ importdeliveriesToRetire,launchesToFire,queueControlLaunch,+ withPrHold,+ withLaunchBrief,+ launchBriefPresent,LAUNCH_STALL_MS,type ArmedNode} from '../lib/pendingLaunch'@@@ -2187,9 -2133,27 +2195,27 @@@ export function Canvas()useLaunchDelivery.getState().markFailed(f.id, attempt)console.warn('[pending-launch] gave up delivering held launch for', f.id)})+ // The file the launch reads its prompt from must still be there: a held launch may be+ // delivered weeks after it was armed (a cold open waits for its project to be viewed), and+ // `"$(cat '<path>')"` over a missing file starts the agent with an EMPTY prompt — the silent+ // failure the open-time existence check exists to catch. Only a definite "not there" holds it+ // (for ▶, persisted `manualOnly`, the path named on the badge); a check that errors answers+ // "present", as the open-time check does. Local projects only: a spill is never written for an+ // SSH project, and there `exists === false` cannot tell a gone file from a dropped master.+ void briefPresent(f.briefFile).then((present) => {+ if (!present) {+ setNodes((ns) => ns.map((n) => n.id === f.id && n.data.pendingLaunch+ ? { ...n, data: { ...n.data, pendingLaunch: { ...n.data.pendingLaunch, manualOnly: true } } }+ : n))+ markDirty()+ useLaunchDelivery.getState().markBriefMissing(f.id, f.briefFile as string)+ return+ }+ return deliverHeld()+ })}- // eslint-disable-next-line react-hooks/exhaustive-deps -- armedDepSig/armedSetupSig/launchNudge are the triggers- }, [nodes, armedDepSig, armedSetupSig, launchNudge])+ // eslint-disable-next-line react-hooks/exhaustive-deps -- armedDepSig/armedSetupSig/armedPrSig/launchNudge are the triggers+ }, [nodes, armedDepSig, armedSetupSig, armedPrSig, launchNudge])// Selection state for ephemeral nodes (they live outside React Flow's managed nodes), owned by// the agent-nodes store so the cards themselves can set it — see `selectable: false` below.@@@ -11091,7 -10996,7 +11117,7 @@@// The human is looking at the target (the caller is a background orchestrator):// live insertion still precedes PTY readiness: keep the launch queued.const tgQueuedIds = tgMade.filter((n) => !!n.data.initialCommand).map((n) => n.id)- setNodes((ns) => [...ns, ...tgMade.map((node) => withPrHold(queueControlLaunch(node), prHoldPre))])- setNodes((ns) => [...ns, ...tgMade.map((node) => withLaunchBrief(queueControlLaunch(node), openPrompt.promptFile))])++ setNodes((ns) => [...ns, ...tgMade.map((node) => withPrHold(withLaunchBrief(queueControlLaunch(node), openPrompt.promptFile), prHoldPre))])markDirty()reply({ok: true,@@@ -11112,7 -11016,7 +11138,7 @@@for (const node of tgMade) {tgStore.applyNodeMutation(target.id, {op: 'upsert',- node: flowToNodeStates([withPrHold(armForColdOpen(node), prHoldPre)])[0]- node: flowToNodeStates([withLaunchBrief(armForColdOpen(node), openPrompt.promptFile)])[0]++ node: flowToNodeStates([withPrHold(withLaunchBrief(armForColdOpen(node), openPrompt.promptFile), prHoldPre)])[0]})}void writeDisk()@@@ -11460,10 -11362,11 +11486,12 @@@// Arm it: the project is not mounted, so nothing would deliver an `initialCommand`// and serialization drops it. `--after` rides the same held launch — an empty `after`// is vacuously ready, so a node with no deps fires on that project's first view.- const armed = armForColdOpen(built)+ // The brief file rides the held launch, so delivery — whenever this project is next+ // viewed — checks it is still there before typing.+ const armed = withLaunchBrief(armForColdOpen(built), openPrompt.promptFile)const held = armed.data.pendingLaunch as PendingLaunch | undefined- const node =+ // `--after-pr` rides the same held launch (withPrHold — the one attach every path uses).+ const node = withPrHold(held && coldAfterIds.length? {...armed,@@@ -11915,7 -11816,7 +11945,7 @@@const awaitSetupGroup = holdsForSetup ? intoGroup ?? undefined : undefined// Always retain the command until the PTY-ready delivery loop acknowledges it.// Node creation (even on screen) is not command delivery.- return withPrHold(queueControlLaunch(node, after, awaitSetupGroup), prHoldPre)- return withLaunchBrief(queueControlLaunch(node, after, awaitSetupGroup), promptFile)++ return withPrHold(withLaunchBrief(queueControlLaunch(node, after, awaitSetupGroup), promptFile), prHoldPre)}// Open `count` nodes INTO a group frame: grow the frame FIRST (extent:'parent' would// clamp children landing outside it), then drop each node into the next grid slotdiff --cc src/renderer/canvas/control-after-pr.source.test.tsindex 67407159d,000000000..37206b4abmode 100644,000000..100644--- a/src/renderer/canvas/control-after-pr.source.test.ts+++ b/src/renderer/canvas/control-after-pr.source.test.ts@@@ -1,125 -1,0 +1,125 @@@+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'++/**+ * STRUCTURAL pins for `--after-pr` inside the desktop's control dispatch, launch loop and node+ * badge. Same reason as `control-prompt-spill.source.test.ts`: these live inside a 16,000-line+ * component with no unit seam. Every behavioural half is proven against real code elsewhere:+ * the grammar and the persisted shape in `shared/pr-wait.test.ts`, when a wait is met and what an+ * open may store in `lib/prWait.test.ts`, the AND with `--after` in `lib/pendingLaunch.test.ts`, the+ * watch and the lookup in `state/githubIssues.test.ts`, the load seam in `state/workspace.test.ts`.+ */+const read = (rel: string): string =>+ readFileSync(new URL(rel, import.meta.url), 'utf8').replace(/\r\n/g, '\n')+const src = read('./Canvas.tsx')+const node = read('../nodes/TerminalNode.tsx')+const mainSrc = read('../../main/index.ts')++const PROJECT_GUARD = "(verb === 'open-terminal' || verb === 'open-claude' || verb === 'open-agent') &&\n args.project !== undefined"+const RUN_PROJECT = "if (verb === 'run' && args.project !== undefined) {"++function slice(fromMarker: string, toMarker: string, text = src): string {+ const start = text.indexOf(fromMarker)+ expect(start, `marker: ${fromMarker}`).toBeGreaterThan(-1)+ const end = text.indexOf(toMarker, start + fromMarker.length)+ expect(end, `marker: ${toMarker}`).toBeGreaterThan(start)+ return text.slice(start, end)+}++describe('main refuses a malformed --after-pr before the renderer sees it', () => {+ it('runs the shared shape gate in the control handler, before the forward', () => {+ const handler = mainSrc.slice(mainSrc.indexOf('hookServer.setControlHandler('))+ const gate = handler.indexOf('afterPrFlagRefusal(verb, args)')+ expect(gate).toBeGreaterThan(-1)+ expect(gate).toBeLessThan(handler.indexOf("'window unavailable'"))+ })+})++describe('the wait is resolved ONCE, before any open path reads the store', () => {+ it('against the project the node OPENS in, for all three open verbs', () => {+ const at = src.indexOf('const prWaitPre')+ expect(at).toBeGreaterThan(-1)+ expect(src.indexOf('const prWaitPre', at + 1)).toBe(-1)+ const body = src.slice(at, at + 2000)+ expect(body).toContain('resolvePrWaitFor(')+ expect(body).toContain('project: openProjectPre')+ expect(body).toContain('lookupPullRequests(')+ expect(at).toBeGreaterThan(src.indexOf('const openPrompt:'))+ expect(at).toBeLessThan(src.indexOf(PROJECT_GUARD))+ expect(at).toBeLessThan(src.indexOf('routeControlSource(projects, activeId, sourceNodeId)'))+ // `openProjectIdPre` (and so `openProjectPre`) now covers open-terminal as well.+ expect(src).toMatch(/const openVerb = verb === 'open-terminal' \|\| issueOpen/)+ expect(src).toMatch(/const openScopePre = openVerb\s*\?\s*issueFlagScope\(/)+ })++ it('asks nobody for a caller the open paths would refuse (the same belt as `#N`)', () => {+ const at = src.indexOf('const prWaitPre')+ const body = src.slice(at, at + 600)+ const belt = body.indexOf('openScopePre && !openScopePre.ok')+ expect(belt).toBeGreaterThan(-1)+ expect(belt).toBeLessThan(body.indexOf('resolvePrWaitFor('))+ expect(body).toContain('error: openScopePre.error')+ })++ it('refuses on a failed resolution and replies exactly once', () => {+ const at = src.indexOf('const prWaitPre')+ const body = src.slice(at, at + 2500)+ expect(body).toMatch(/if \(!prWaitPre\.ok\) \{\s*reply\(\{ ok: false, error: prWaitPre\.error \}\)\s*return\s*\}/)+ })++ it('the renderer belt refuses --run-now with --after-pr too (main is not the only gate)', () => {+ expect(src).toContain('reply({ ok: false, error: RUN_NOW_AFTER_PR_REFUSAL })')+ })+})++describe('every open path attaches the wait through withPrHold', () => {+ it('the live paths, through armAfter (terminal and agent both use it)', () => {+ const armAfter = slice('const armAfter = (', 'const addGrouped = (')- expect(armAfter).toMatch(/withPrHold\(queueControlLaunch\(node, after, awaitSetupGroup\), prHoldPre\)/)++ expect(armAfter).toMatch(/withPrHold\(withLaunchBrief\(queueControlLaunch\(node, after, awaitSetupGroup\), promptFile\), prHoldPre\)/)+ })++ it('the cold open', () => {+ const cold = slice('if (canColdOpen(verb)) {', 'if (answersOffCanvas(verb) || answersFromStoredNodes(verb)) {')+ expect(cold).toMatch(/withPrHold\(/)+ expect(cold).toContain('prHoldPre')+ })++ it('both --project branches (on screen and stored)', () => {+ const block = slice(PROJECT_GUARD, RUN_PROJECT)- expect(block).toMatch(/withPrHold\(queueControlLaunch\(node\), prHoldPre\)/)- expect(block).toMatch(/withPrHold\(armForColdOpen\(node\), prHoldPre\)/)++ expect(block).toMatch(/withPrHold\(withLaunchBrief\(queueControlLaunch\(node\), openPrompt\.promptFile\), prHoldPre\)/)++ expect(block).toMatch(/withPrHold\(withLaunchBrief\(armForColdOpen\(node\), openPrompt\.promptFile\), prHoldPre\)/)+ })+})++describe('the launch loop judges the wait on the ACTIVE project’s pull request status', () => {+ const effect = (): string => slice('const ready = launchesToFire(', '}, [nodes, armedDepSig')++ it('passes the board and the clock to launchesToFire', () => {+ expect(effect()).toMatch(/\{ board: pullBoardFor\(useGitHubIssues\.getState\(\), nodesProjectIdRef\.current \?\? ''\), now: Date\.now\(\) \}/)+ })++ it('re-runs when a waited-on pull request changes, off a PRIMITIVE signature', () => {+ expect(src).toMatch(/\}, \[nodes, armedDepSig, armedSetupSig, armedPrSig, launchNudge\]\)/)+ const sig = slice('const armedPrSig = useGitHubIssues((s) => {', '})')+ expect(sig).toContain('prHoldReports(')+ expect(sig).toContain("sig +=")+ })++ it('keeps the host watch (and the checks chase) only while some node holds a PR wait', () => {+ const watch = slice('const prWatchNeeded =', 'usePullChase(')+ expect(watch).toContain('watchPulls(api.githubIssues,')+ expect(src).toMatch(/usePullChase\(api\.githubIssues, prWatchProjectId, prChaseNeeded\)/)+ })+})++describe('the node badge', () => {+ it('a PR hold is a real hold: it is never hidden as a first-open delivery', () => {+ const first = slice('const firstOpenInFlight =', '\n const ', node)+ expect(first).toContain('!pendingLaunch?.afterPr')+ })++ it('reads EXPIRED and hands the PR wait to the tooltip', () => {+ expect(node).toMatch(/prExpired \? '⚠ EXPIRED'/)+ expect(node).toMatch(/launchTooltip\([^)]*prTooltip\)/)+ })+})diff --cc src/renderer/canvas/control-open-project.source.test.tsindex c6342274e,1d2b70079..79a25703c--- a/src/renderer/canvas/control-open-project.source.test.ts+++ b/src/renderer/canvas/control-open-project.source.test.ts@@@ -159,8 -159,8 +159,9 @@@ describe('the --project targeted-opens// 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()- // `withPrHold` attaches an `--after-pr` wait to the launch armForColdOpen already moved.- expect(body).toMatch(/flowToNodeStates\(\[withPrHold\(armForColdOpen\(node\), prHoldPre\)\]\)\[0\]/)- // `withLaunchBrief` records the prompt file on the launch armForColdOpen moved (#1014 review).- expect(body).toMatch(/flowToNodeStates\(\[withLaunchBrief\(armForColdOpen\(node\), openPrompt\.promptFile\)\]\)\[0\]/)++ // `withLaunchBrief` records the prompt file and `withPrHold` the `--after-pr` wait, both on the++ // launch armForColdOpen already moved.++ expect(body).toMatch(/flowToNodeStates\(\[withPrHold\(withLaunchBrief\(armForColdOpen\(node\), openPrompt\.promptFile\), prHoldPre\)\]\)\[0\]/)})it('the store path persists (writeDisk) and states the cold-open contract in the reply', () => {diff --cc src/renderer/canvas/control-prompt-spill.source.test.tsindex 223be12fc,3a5fc9449..8fd5108c9--- a/src/renderer/canvas/control-prompt-spill.source.test.ts+++ b/src/renderer/canvas/control-prompt-spill.source.test.ts@@@ -126,3 -126,33 +126,33 @@@ describe('each open path types openPromexpect(body.slice(active, active + 200)).toContain('useProjects.getState().activeProjectId')})})++ describe('the brief file is checked when the launch is DELIVERED (#1014 review)', () => {+ // A cold-opened node launches when its project is next viewed, maybe weeks later; the file its+ // command `cat`s may be gone by then. Behaviour: `lib/pendingLaunch.test.ts` (briefFile, tooltip)+ // and `core/uploads.test.ts` (spills survive the paste sweep).+ it('every open path records the file on the held launch', () => {+ expect(projectBlock()).toContain('withLaunchBrief(queueControlLaunch(node), openPrompt.promptFile)')+ expect(projectBlock()).toContain('withLaunchBrief(armForColdOpen(node), openPrompt.promptFile)')+ expect(coldBlock()).toContain('withLaunchBrief(armForColdOpen(built), openPrompt.promptFile)')- expect(src).toContain('return withLaunchBrief(queueControlLaunch(node, after, awaitSetupGroup), promptFile)')++ expect(src).toContain('withLaunchBrief(queueControlLaunch(node, after, awaitSetupGroup), promptFile)')+ // …and the live open hands its file to armAfter.+ expect(liveAgentCase()).toMatch(/after \?\? \[\],\s*intoGroupId,\s*openPrompt\.promptFile\s*\)/)+ })++ it('the launch loop checks the file before typing, and holds the node for ▶ when it is gone', () => {+ const loop = slice('const ready = launchesToFire(', '}, [nodes, armedDepSig')+ const check = loop.indexOf('briefPresent(f.briefFile)')+ expect(check).toBeGreaterThan(-1)+ const missing = loop.slice(check, check + 700)+ expect(missing).toMatch(/\.then\(\(present\) => \{\s*if \(!present\) \{/)+ expect(missing).toContain('manualOnly: true')+ expect(missing).toContain('markBriefMissing(f.id')+ // Typing happens only on the "present" branch.+ expect(missing).toMatch(/return deliverHeld\(\)/)+ // …on the node's own project, with the local fs (the rule itself: `launchBriefPresent`).+ const effect = slice('const briefPresent = ', 'const ready = launchesToFire(')+ expect(effect).toContain('launchBriefPresent(')+ expect(effect).toContain('getProject(nodesProjectIdRef.current')+ })+ })diff --cc src/renderer/lib/controlRouting.tsindex 949863d74,7856a9cc9..e418207f0--- a/src/renderer/lib/controlRouting.ts+++ b/src/renderer/lib/controlRouting.ts@@@ -206,10 -198,10 +206,11 @@@ const launchLabels =failed: 'LAUNCH FAILED',stalled: 'QUEUED (terminal not ready)',starting: 'STARTING',+ 'brief-missing': 'HELD (its prompt file no longer exists; run it with `run` to start without it)',dropped: 'DROPPED',working: 'WORKING',- unconfirmed: 'AGENT STATUS UNCONFIRMED'+ unconfirmed: 'AGENT STATUS UNCONFIRMED',+ expired: 'EXPIRED (PR wait deadline passed; run it with `run`)'} as constexport function controlListingText(rows: ReturnType<typeof storedNodeListing>): string {diff --cc src/renderer/lib/pendingLaunch.test.tsindex f5b5a4854,2859b6f28..bef19b6fd--- a/src/renderer/lib/pendingLaunch.test.ts+++ b/src/renderer/lib/pendingLaunch.test.ts@@@ -1,5 -1,4 +1,5 @@@- import { describe, it, expect } from 'vitest'+ import { describe, it, expect, vi } from 'vitest'+import type { PendingLaunch } from '@shared/types'import {launchesToFire,queueControlLaunch,@@@ -8,7 -7,8 +8,9 @@@launchTooltip,unmetDeps,LAUNCH_STALL_MS,+ withPrHold,+ withLaunchBrief,+ launchBriefPresent,type ArmedNode,type StatusById} from './pendingLaunch'@@@ -340,105 -340,53 +342,156 @@@ it('a refused relay launch explains hosexpect(text).not.toContain('press ▶')})+describe('--after-pr: a PR wait is a third gate, ANDed with the deps and the setup script', () => {+ const NOW = 5_000_000+ const hold = (deadlineAt = NOW + 60_000) => ({+ repository: 'o/r',+ waits: [{ number: 7, until: 'merged' as const }],+ deadlineAt+ })+ const prNode = (after: string[], deadlineAt?: number): ArmedNode => ({+ id: 'c',+ data: { pendingLaunch: { after, command: 'echo c', afterPr: hold(deadlineAt) } }+ })+ const pull = (lifecycle: 'open' | 'merged') => ({+ number: 7, lifecycle, headRefName: 'b', closes: [] as number[]+ })+ const board = (lifecycle: 'open' | 'merged') => ({+ repository: 'o/r',+ pulls: [pull(lifecycle)],+ stale: false,+ access: { ci: true, merge: true },+ undecided: false,+ truncated: false+ })+ const live = new Set(['a', 'c'])+ const done: StatusById = { a: { state: 'done' } }++ it('fires once the deps are done AND the PR has merged', () => {+ expect(launchesToFire([prNode(['a'])], done, live, undefined, undefined, { board: board('merged'), now: NOW })).toEqual([+ { id: 'c', command: 'echo c' }+ ])+ })++ it('holds while the PR is open, however done the deps are', () => {+ expect(launchesToFire([prNode(['a'])], done, live, undefined, undefined, { board: board('open'), now: NOW })).toEqual([])+ })++ it('holds while the deps are working, however merged the PR is', () => {+ expect(+ launchesToFire([prNode(['a'])], { a: { state: 'working' } }, live, undefined, undefined, { board: board('merged'), now: NOW })+ ).toEqual([])+ })++ it('a caller that passes no PR context never releases a PR hold — unknown is not satisfied', () => {+ expect(launchesToFire([prNode([])], {}, live)).toEqual([])+ })++ it('never fires past the deadline', () => {+ expect(+ launchesToFire([prNode([], NOW)], {}, live, undefined, undefined, { board: board('merged'), now: NOW })+ ).toEqual([])+ })++ it('a node with no PR wait is unaffected by the PR context', () => {+ expect(launchesToFire([armed('c', ['a'])], done, live, undefined, undefined, { board: undefined, now: NOW })).toEqual([+ { id: 'c', command: 'echo c' }+ ])+ })++ it('the list row says EXPIRED once the deadline passes (a delivery record still wins)', () => {+ expect(controlLaunchState(true, undefined, undefined, true)).toBe('expired')+ expect(controlLaunchState(true, undefined, undefined, false)).toBe('queued')+ expect(controlLaunchState(true, { kind: 'failed', attempts: 1, at: 0 }, undefined, true)).toBe('failed')+ })++ it('the tooltip names the PR it waits on, beside any station', () => {+ const pr = { expired: false, summary: 'PR #7 merged (open, not merged)', deadline: '18:00' }+ expect(launchTooltip(undefined, 'Builder', 'claude', undefined, false, pr)).toBe(+ 'Waiting for Builder to finish and for PR #7 merged (open, not merged), until 18:00, then runs:\nclaude'+ )+ expect(launchTooltip(undefined, '', 'claude', undefined, false, pr)).toBe(+ 'Waiting for PR #7 merged (open, not merged), until 18:00, then runs:\nclaude'+ )+ })++ it('an expired wait says it will not start on its own and offers ▶', () => {+ const t = launchTooltip(undefined, 'Builder', 'claude', undefined, false, {+ expired: true,+ summary: 'PR #7 merged (open, not merged)',+ deadline: '18:00'+ })+ expect(t).toMatch(/passed its deadline/)+ expect(t).toMatch(/will not start on its own/)+ expect(t).toMatch(/▶/)+ })++ it('without a PR wait the existing sentences are byte-identical', () => {+ expect(launchTooltip(undefined, 'Builder', 'claude')).toBe('Waiting for Builder to finish, then runs:\nclaude')+ })+})++describe('withPrHold — one way every open path attaches a PR wait', () => {+ const hold = { repository: 'o/r', waits: [{ number: 7, until: 'merged' as const }], deadlineAt: 9 }+ it('adds the hold to a node that already holds its launch', () => {+ const node = { id: 'n', data: { pendingLaunch: { after: ['a'], command: 'c', attempted: false } } }+ expect(withPrHold(node, hold).data.pendingLaunch).toEqual({ after: ['a'], command: 'c', attempted: false, afterPr: hold })+ })+ it('leaves a node alone when there is no hold, or nothing is held to attach it to', () => {+ const held = { id: 'n', data: { pendingLaunch: { after: [], command: 'c' } } }+ expect(withPrHold(held, undefined)).toBe(held)+ const bare = { id: 'n', data: {} as { pendingLaunch?: PendingLaunch } }+ expect(withPrHold(bare, hold)).toBe(bare)+ })+})+++ describe('the launch brief file is verified at DELIVERY, not only at open (#1014 review)', () => {+ const node = { id: 'n', data: { pendingLaunch: { after: [], command: 'claude "$(cat \'/x/p.txt\')"' } } }++ it('withLaunchBrief records the file the command reads; nothing held, nothing recorded', () => {+ expect(withLaunchBrief(node, '/x/p.txt').data.pendingLaunch).toMatchObject({ promptFile: '/x/p.txt' })+ expect(withLaunchBrief(node, undefined)).toBe(node)+ const bare = { id: 'b', data: {} as { pendingLaunch?: { after: string[]; command: string } } }+ expect(withLaunchBrief(bare, '/x/p.txt')).toBe(bare)+ })++ it('launchesToFire hands the file to the loop, which checks it before typing', () => {+ const armedWithBrief = withLaunchBrief(node, '/x/p.txt')+ expect(launchesToFire([armedWithBrief], {}, new Set(['n']))).toEqual([+ { id: 'n', command: armedWithBrief.data.pendingLaunch.command, briefFile: '/x/p.txt' }+ ])+ })++ it('a missing brief is a named, manual hold — never an agent started with no brief', () => {+ const t = launchTooltip({ kind: 'brief-missing', path: '/x/p.txt', at: 1 }, '', 'claude')+ expect(t).toContain('/x/p.txt')+ expect(t).toMatch(/no longer exists/)+ expect(t).toMatch(/no brief/)+ expect(t).toMatch(/▶/)+ expect(controlLaunchState(true, { kind: 'brief-missing', path: '/x/p.txt', at: 1 })).toBe('brief-missing')+ })+ })++ describe('launchBriefPresent — only a definite "not there" holds a launch', () => {+ const local = { id: 'p' }+ it('no file to check is present', async () => {+ const exists = vi.fn(async () => false)+ expect(await launchBriefPresent(undefined, local, exists)).toBe(true)+ expect(exists).not.toHaveBeenCalled()+ })+ it('a local file that is gone is absent; one that is there is present', async () => {+ expect(await launchBriefPresent('/x', local, async () => false)).toBe(false)+ expect(await launchBriefPresent('/x', local, async () => true)).toBe(true)+ })+ it('a check that fails answers present — the open-time check fails open the same way', async () => {+ expect(await launchBriefPresent('/x', local, async () => { throw new Error('EIO') })).toBe(true)+ expect(await launchBriefPresent('/x', local, () => { throw new Error('sync') })).toBe(true)+ })+ it('an SSH or relay project is never judged from here (a false there is not evidence of absence)', async () => {+ const exists = vi.fn(async () => false)+ expect(await launchBriefPresent('/x', { id: 'p', ssh: {} }, exists)).toBe(true)+ expect(await launchBriefPresent('/x', { id: 'p', remote: true }, exists)).toBe(true)+ expect(await launchBriefPresent('/x', undefined, exists)).toBe(true)+ expect(exists).not.toHaveBeenCalled()+ })+ })diff --cc src/renderer/lib/pendingLaunch.tsindex a75eb84a2,89bc0b457..1e9cd6ce2--- a/src/renderer/lib/pendingLaunch.ts+++ b/src/renderer/lib/pendingLaunch.ts@@@ -24,15 -21,24 +24,31 @@@ export type StatusById = Recordexport interface LaunchToFire {id: stringcommand: string+ /** The file `command` reads its prompt from, which the loop checks before typing. */+ briefFile?: string+ }++ /**+ * Record the file a held launch reads its prompt from (`--prompt-file`, or a spilled `--prompt`).+ * Applied by every control open path after arming, so the delivery loop can check the file is still+ * there when the node finally launches — possibly weeks later, for a cold open.+ */+ export function withLaunchBrief<T extends { data: { pendingLaunch?: PendingLaunch } }>(+ node: T,+ promptFile: string | undefined+ ): T {+ const p = node.data.pendingLaunch+ if (!promptFile || !p) return node+ return { ...node, data: { ...node.data, pendingLaunch: { ...p, promptFile } } }}+/** What `launchesToFire` needs to judge a `--after-pr` wait: the ACTIVE project's pull request+ * status (#1008's board, absent until the watch has read it) and the clock deadlines are on. */+export interface PrGateContext {+ board?: GitHubPullBoard+ now: number+}+/** Control opens reply before the PTY exists. Keep their command durable until delivery lands,* even with no dependencies (or dependencies that are already done). */export function queueControlLaunch<T extends { data: { initialCommand?: string; pendingLaunch?: PendingLaunch } }>(@@@ -52,30 -58,33 +68,50 @@@}}+/**+ * Attach a `--after-pr` wait to a node whose launch is already held (by `queueControlLaunch`,+ * `armForColdOpen`, or `--after`). ONE helper for every open path — live, cold and `--project` —+ * so no path can arm a node that forgets the wait it was asked for. A node with nothing held has+ * nothing to wait with (the flag gate already refused `open-terminal` without `--cmd`).+ */+export function withPrHold<T extends { data: { pendingLaunch?: PendingLaunch } }>(+ node: T,+ hold: PrWaitHold | undefined+): T {+ const p = node.data.pendingLaunch+ if (!hold || !p) return node+ return { ...node, data: { ...node.data, pendingLaunch: { ...p, afterPr: hold } } }+}++ /**+ * Is the file a held launch reads its prompt from still there, right before the launch is typed?+ * Only a definite "not there" answers false. No file to check, a check that fails (sync or async),+ * and any project not on this machine's disk answer true: an SSH project never gets a spilled file,+ * and there `exists === false` cannot tell a gone file from a dropped ControlMaster; a relay tab's+ * launches are refused elsewhere. The open-time check fails open the same way.+ */+ export async function launchBriefPresent(+ path: string | undefined,+ project: { id: string; ssh?: unknown; remote?: boolean } | undefined,+ exists: (path: string) => Promise<boolean>+ ): Promise<boolean> {+ if (!path || !project || project.ssh || project.remote) return true+ try {+ return (await exists(path)) !== false+ } catch {+ return true+ }+ }+/** A list row states only observed facts; absence of a launch error is not proof of a live CLI. */export function controlLaunchState(pending: boolean,delivery: LaunchDelivery | undefined,- status?: { dropped?: boolean; state?: AgentState }-): 'queued' | 'stalled' | 'failed' | 'starting' | 'brief-missing' | 'dropped' | 'working' | undefined {- if (pending) return delivery?.kind ?? 'queued'+ status?: { dropped?: boolean; state?: AgentState },+ /** The node's `--after-pr` wait has passed its deadline: it will not start on its own. */+ prExpired = false- ): 'queued' | 'stalled' | 'failed' | 'starting' | 'dropped' | 'working' | 'expired' | undefined {++): 'queued' | 'stalled' | 'failed' | 'starting' | 'brief-missing' | 'dropped' | 'working' | 'expired' | undefined {+ if (pending) return delivery?.kind ?? (prExpired ? 'expired' : 'queued')if (status?.dropped) return 'dropped'if (status?.state === 'working') return 'working'return undefined@@@ -159,11 -167,9 +195,13 @@@ export function launchesToFire// caught up with the claim yet while the store already says so.if (deliveries?.[n.id]?.kind === 'starting') continueif (p.awaitSetupGroup && !(setupDone?.(p.awaitSetupGroup) ?? true)) continue+ // The THIRD gate (`--after-pr`). Unlike the setup gate, an absent context is CLOSED: a caller+ // that did not say what the pull requests look like has told us nothing, and "no news" is+ // exactly what must never release a launch (the same rule as an unknown agent state).+ if (p.afterPr && !(pr && prHoldSatisfied(p.afterPr, pr.board, pr.now))) continue- if (p.after.every((d) => depSatisfied(d, status, live))) out.push({ id: n.id, command: p.command })+ if (p.after.every((d) => depSatisfied(d, status, live))) {+ out.push({ id: n.id, command: p.command, ...(p.promptFile ? { briefFile: p.promptFile } : {}) })+ }}return out}diff --cc src/shared/pending-launch-shape.test.tsindex 728bd160f,000000000..75547af2fmode 100644,000000..100644--- a/src/shared/pending-launch-shape.test.ts+++ b/src/shared/pending-launch-shape.test.ts@@@ -1,70 -1,0 +1,81 @@@+import { describe, expect, it } from 'vitest'+import { normalizePendingLaunch } from './pending-launch-shape'+import { INVALID_PR_WAIT_HOLD } from './pr-wait'++describe('normalizePendingLaunch — the held launch as a hostile project file carries it', () => {+ it('absent, null and non-objects are no hold', () => {+ expect(normalizePendingLaunch(undefined)).toBeUndefined()+ expect(normalizePendingLaunch(null)).toBeUndefined()+ expect(normalizePendingLaunch('claude')).toBeUndefined()+ expect(normalizePendingLaunch([])).toBeUndefined()+ })++ it('a hold with no typeable command is no hold — there is nothing to launch', () => {+ expect(normalizePendingLaunch({ after: [], command: 42 })).toBeUndefined()+ })++ it('a well-formed hold round-trips unchanged', () => {+ const hold = {+ after: ['a', 'b'],+ command: 'claude "go"',+ attempted: false,+ awaitSetupGroup: 'g1',+ afterPr: { repository: 'o/r', waits: [{ number: 3, until: 'merged' as const }], deadlineAt: 99 }+ }+ expect(normalizePendingLaunch(hold)).toEqual(hold)+ })++ it('an `after` that is not a list becomes a MANUAL hold instead of throwing in the launch loop', () => {+ // `p.after.every(...)` and the canvas's dep signature both iterate it. A string would iterate+ // its characters; a number throws. An empty list would fire the node at once — early.+ const out = normalizePendingLaunch({ after: 'a,b', command: 'x' })+ expect(out).toMatchObject({ after: [], command: 'x', manualOnly: true })+ })++ it('non-string dependency ids are dropped AND the hold turns manual — the dep set is not what was armed', () => {+ const out = normalizePendingLaunch({ after: ['a', 7, { id: 'b' }], command: 'x' })+ expect(out).toMatchObject({ after: ['a'], manualOnly: true })+ })++ it('a malformed PR wait stays a hold that never fires by itself', () => {+ const out = normalizePendingLaunch({ after: [], command: 'x', afterPr: { repository: 5 } })+ expect(out?.afterPr).toEqual(INVALID_PR_WAIT_HOLD)+ })++ it('an unreadable setup gate or executor turns the hold manual rather than opening it early', () => {+ expect(normalizePendingLaunch({ after: [], command: 'x', awaitSetupGroup: 3 })).toMatchObject({+ manualOnly: true+ })+ expect(normalizePendingLaunch({ after: [], command: 'x', executor: 'robot' })).toMatchObject({+ manualOnly: true+ })+ })+++ it('keeps the launch brief file, and holds the launch when it is unreadable (#1014 review)', () => {++ // The delivery loop checks this file before typing; a hold whose file it cannot read must not++ // be typed unchecked, or a gone file starts the agent with an empty brief.++ expect(normalizePendingLaunch({ after: [], command: 'x', promptFile: '/p.txt' })).toMatchObject({++ promptFile: '/p.txt'++ })++ const bad = normalizePendingLaunch({ after: [], command: 'x', promptFile: 7 })++ expect(bad).toMatchObject({ manualOnly: true })++ expect(bad).not.toHaveProperty('promptFile')++ })+++ it('keeps a field this build does not know, so an older save does not erase a newer one', () => {+ expect(normalizePendingLaunch({ after: [], command: 'x', futureGate: { k: 1 } })).toMatchObject({+ futureGate: { k: 1 }+ })+ })++ it('never throws, whatever it is handed', () => {+ const weird: unknown[] = [+ { after: null, command: 'x' },+ { after: [], command: 'x', attempted: 'yes', manualOnly: 1 },+ { after: [], command: 'x', awaitWorking: 'a' },+ { after: [], command: 'x', afterPr: [] },+ Object.create(null)+ ]+ for (const w of weird) expect(() => normalizePendingLaunch(w)).not.toThrow()+ })+})diff --cc src/shared/pending-launch-shape.tsindex 0dff68324,000000000..6717ef011mode 100644,000000..100644--- a/src/shared/pending-launch-shape.ts+++ b/src/shared/pending-launch-shape.ts@@@ -1,61 -1,0 +1,66 @@@+// A held launch (`CanvasNodeState.pendingLaunch`) as a git-shared, hand-editable project file+// carries it. Nothing validated it before: the launch loop runs `p.after.every(...)` and the+// canvas's dependency signature iterates `p.after` inside a store selector, so an `after` that was+// not a list threw at render. Run at BOTH serializer seams (`nodeStatesToFlow`, `flowToNodeStates`).+//+// The rule every repair here follows: a hold this module cannot read in full must never fire by+// itself. Opening a gate early is the unsafe direction (a dependent that has launched cannot+// un-launch), so an unreadable gate turns the hold `manualOnly` — it waits for ▶ — instead of being+// dropped. Only a hold with no typeable command is dropped: there is nothing to launch.+//+// Fields this build does not know are KEPT, so saving from this build does not erase a field a+// newer build wrote.++import type { PendingLaunch } from './types'+import { normalizePrWaitHold } from './pr-wait'++const KNOWN = new Set([+ 'after',+ 'command',+ 'attempted',+ 'manualOnly',+ 'executor',+ 'awaitWorking',+ 'awaitSetupGroup',- 'afterPr'++ 'afterPr',++ 'promptFile'+])++export function normalizePendingLaunch(value: unknown): PendingLaunch | undefined {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined+ const v = value as Record<string, unknown>+ if (typeof v.command !== 'string') return undefined+ let manual = v.manualOnly === true+ const out: Record<string, unknown> = {}+ for (const key of Object.keys(v)) if (!KNOWN.has(key)) out[key] = v[key]++ let after: string[] = []+ if (Array.isArray(v.after)) {+ after = v.after.filter((d): d is string => typeof d === 'string')+ if (after.length !== v.after.length) manual = true+ } else if (v.after !== undefined) {+ manual = true+ }+ out.after = after+ out.command = v.command+ if (typeof v.attempted === 'boolean') out.attempted = v.attempted+ if (v.executor !== undefined) {+ if (v.executor === 'server' || v.executor === 'core') out.executor = v.executor+ else manual = true+ }+ if (Array.isArray(v.awaitWorking)) {+ out.awaitWorking = v.awaitWorking.filter((d): d is string => typeof d === 'string')+ }+ if (v.awaitSetupGroup !== undefined) {+ if (typeof v.awaitSetupGroup === 'string') out.awaitSetupGroup = v.awaitSetupGroup+ else manual = true+ }++ if (v.promptFile !== undefined) {++ if (typeof v.promptFile === 'string') out.promptFile = v.promptFile++ else manual = true++ }+ const afterPr = normalizePrWaitHold(v.afterPr)+ if (afterPr) out.afterPr = afterPr+ if (manual) out.manualOnly = true+ return out as unknown as PendingLaunch+}diff --cc src/shared/types.tsindex 2e1884aae,b8837af06..ea8402445--- a/src/shared/types.ts+++ b/src/shared/types.ts@@@ -432,13 -431,14 +432,21 @@@ export interface PendingLaunch* outlives the run's event stream — an app restart — releases rather than strands the node.*/awaitSetupGroup?: string+ /**+ * Also wait on GitHub pull requests of the project's board repository (`--after-pr`, see+ * @shared/pr-wait). ANDed with `after` and the setup gate. Validated at both serializer seams+ * (`normalizePendingLaunch`): a malformed value becomes a hold that never fires on its own.+ * A build older than this one does not know the field and releases the node on `after` alone.+ */+ afterPr?: PrWaitHold+ /**+ * The file `command` reads its prompt from (`"$(cat '<path>')"`): a `--prompt-file`, or a long+ * `--prompt` spilled to a file (#706). A held launch may be delivered weeks after it was armed, so+ * the delivery loop checks this file still exists before it types the command, and holds the node+ * for ▶ with the reason when it does not — an agent started with no brief is the failure the+ * open-time existence check exists to catch. Absent for a prompt that rides the command inline.+ */+ promptFile?: string}export interface CanvasNodeState {