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
fix(control): keep spilled launch prompts until launch, and check them before typing
review539c20eb80e0
diff --git a/CLAUDE.md b/CLAUDE.mdindex 02ac82b3d..f5eefbf42 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3328,6 +3328,17 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile~490-byte issue line made it likeliest to bite, and the `--project` path silently DROPPED`--prompt-file` (the session started with no brief) and `--model`. A new open path types`openPrompt`, never its own prompt — `control-prompt-spill.source.test.ts` pins each path.+ **A spilled prompt is read at LAUNCH, which for a cold open can be weeks away**, so it is not a+ paste: `saveUpload` puts a `LAUNCH_PROMPT_FILE_PREFIX` name under `<userData>/launch-prompts`+ (`@shared/launch-prompt`), owner-only, swept after `LAUNCH_PROMPT_TTL_MS` (30 days) by the next+ spill — under `uploads` the 7-day sweep of the next paste deleted it and `"$(cat '<path>')"`+ started the agent with nothing. And because a cold open can wait longer than ANY TTL, the held+ launch records the file (`pendingLaunch.promptFile`, via `withLaunchBrief` on every arming path)+ and the delivery loop checks it right before typing (`launchBriefPresent`: local projects only,+ a failed check answers "present"); a definite "gone" persists `manualOnly`, raises the+ `brief-missing` delivery state (tooltip names the path, `list` says HELD) and waits for ▶ / `run`,+ which still run it on purpose. The one residue: a refused open may leave a spill file behind+ (the spill is decided before the paths, to keep awaits out of them), swept with the rest.`--prompt` replaces the default task after the reference line; `--prompt-file` stays the whole brief. Bothgenerated agent bodies render the contract from `issueBindingDocLines` (the example first promptis rendered from `issueLaunchPrompt` itself): move your OWN card with `assign` (In Progress ondiff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex 46629eab9..7e2c891bb 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -551,7 +551,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {' path>` instead: write the brief to a file, pass the absolute path, and the session starts',' with the file\'s exact contents — newlines, numbered lists and headings preserved. The file',' is read when the session LAUNCHES (later than the call for an `--after`-armed node), so',- ' leave it in place until the station has started. A long `--prompt` is SAFE on a local',+ ' leave it in place until the station has started: a local node whose file is gone by then is',+ ' not started, `list` marks it HELD and it waits for `run`. A long `--prompt` is SAFE on a local',' project (nodeterm spills it to a file itself), but on an SSH project pass `--prompt-file`:',' a terminal line caps at 1024 bytes on macOS, and a launch line that cannot be delivered is',' refused with a message on the node rather than half-run. Never begin a prompt with `/`: once',@@ -1067,7 +1068,9 @@ Verbs:absolute path, and the session starts with the file's exact contents: the launch line staysone line and the pane's shell reads the file at execution. The file is read when the sessionLAUNCHES — for an \`--after\`-armed node that is later than your call — so leave it in place- until the station has started. On an SSH project the path is on the host (where you run).+ until the station has started. On a local project a node whose file is gone by then is not+ started with an empty brief: \`list\` marks it HELD and it waits for \`run\`. On an SSH project+ the path is on the host (where you run).Pass either \`--prompt\` or \`--prompt-file\`, not both.- **Never start a prompt with \`/\`.** Flattened, \`/model sonnet\` followed by your task readsto the agent as one slash command whose argument is the entire rest of the prompt. Thediff --git a/src/core/uploads.test.ts b/src/core/uploads.test.tsindex 172a8d52f..0356e3e00 100644--- a/src/core/uploads.test.ts+++ b/src/core/uploads.test.ts@@ -1,8 +1,16 @@-import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import fs from 'fs'import os from 'os'import path from 'path'-import { saveUpload, safeUploadName, uploadsRoot, UPLOAD_MAX_BYTES } from './uploads'+import {+ launchPromptsRoot,+ saveUpload,+ safeUploadName,+ uploadsRoot,+ UPLOAD_MAX_BYTES,+ UPLOAD_TTL_MS+} from './uploads'+import { LAUNCH_PROMPT_FILE_PREFIX, LAUNCH_PROMPT_TTL_MS } from '../shared/launch-prompt'describe('safeUploadName', () => {it('strips any directory part — the name is a renderer string, never a write target', () => {@@ -70,3 +78,54 @@ describe('saveUpload', () => {expect(await saveUpload(asFile, 'x.png', Buffer.from('x').toString('base64'))).toBeNull()})})++describe('a spilled launch prompt is not a paste (#1014 review)', () => {+ // The spill file is read when the node LAUNCHES, and a cold-opened node launches when its project+ // is next viewed — possibly weeks later. The uploads sweep deletes anything older than 7 days on+ // the next paste, and `"$(cat '<path>')"` over a deleted file starts the agent with NO brief.+ let dir: string+ const data = Buffer.from('the brief').toString('base64')+ const age = (p: string, ms: number): void => {+ const t = (Date.now() - ms) / 1000+ fs.utimesSync(p, t, t)+ }+ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'uploads-'))+ })+ afterEach(() => {+ fs.rmSync(dir, { recursive: true, force: true })+ })++ it('lands in its own root, never under uploads', async () => {+ const p = await saveUpload(dir, `${LAUNCH_PROMPT_FILE_PREFIX}abc.txt`, data)+ expect(p!.startsWith(launchPromptsRoot(dir))).toBe(true)+ expect(p!.startsWith(uploadsRoot(dir))).toBe(false)+ expect(fs.readFileSync(p!, 'utf8')).toBe('the brief')+ })++ it.skipIf(process.platform === 'win32')('is readable by its owner only (POSIX modes)', async () => {+ const p = await saveUpload(dir, `${LAUNCH_PROMPT_FILE_PREFIX}abc.txt`, data)+ expect(fs.statSync(p!).mode & 0o777).toBe(0o600)+ expect(fs.statSync(path.dirname(p!)).mode & 0o777).toBe(0o700)+ })++ it('survives the 7-day uploads sweep, and is swept only past its own TTL', async () => {+ expect(LAUNCH_PROMPT_TTL_MS).toBeGreaterThan(UPLOAD_TTL_MS)+ const spilled = await saveUpload(dir, `${LAUNCH_PROMPT_FILE_PREFIX}old.txt`, data)+ const spillDir = path.dirname(spilled!)+ const paste = await saveUpload(dir, 'shot.png', data)+ const pasteDir = path.dirname(paste!)+ age(spillDir, UPLOAD_TTL_MS + 86_400_000)+ age(pasteDir, UPLOAD_TTL_MS + 86_400_000)+ // A paste sweeps the old paste…+ await saveUpload(dir, 'next.png', data)+ await vi.waitFor(() => expect(fs.existsSync(pasteDir)).toBe(false))+ // …and a spill sweeps nothing younger than the spill TTL.+ await saveUpload(dir, `${LAUNCH_PROMPT_FILE_PREFIX}new.txt`, data)+ await new Promise((r) => setTimeout(r, 50))+ expect(fs.existsSync(spilled!)).toBe(true)+ age(spillDir, LAUNCH_PROMPT_TTL_MS + 86_400_000)+ await saveUpload(dir, `${LAUNCH_PROMPT_FILE_PREFIX}newer.txt`, data)+ await vi.waitFor(() => expect(fs.existsSync(spillDir)).toBe(false))+ })+})diff --git a/src/core/uploads.ts b/src/core/uploads.tsindex 4bcede468..a654ce9f0 100644--- a/src/core/uploads.ts+++ b/src/core/uploads.ts@@ -13,6 +13,7 @@import { promises as fs } from 'fs'import { basename, join } from 'path'+import { LAUNCH_PROMPT_FILE_PREFIX, LAUNCH_PROMPT_TTL_MS } from '../shared/launch-prompt'/** Anything bigger is refused rather than marshalled through the RPC layer as base64 (which is* itself ~4/3 of the bytes). Clipboard images and dropped documents sit far below this. */@@ -27,6 +28,15 @@ let seq = 0/** `<userData>/uploads` — exported so a caller can name the directory in a message/test. */export const uploadsRoot = (userDataDir: string): string => join(userDataDir, 'uploads')+/**+ * `<userData>/launch-prompts` — where a spilled launch prompt (`LAUNCH_PROMPT_FILE_PREFIX`) goes.+ * NOT a paste: it is read when its node launches, which for a cold-opened node is whenever that+ * project is next viewed. Under `uploads` it was deleted by the 7-day sweep of the next paste, and+ * the launch then expanded `"$(cat '<path>')"` to nothing — an agent started with no brief. Its own+ * root, its own longer TTL (`LAUNCH_PROMPT_TTL_MS`), swept only by the next spill, owner-only modes.+ */+export const launchPromptsRoot = (userDataDir: string): string => join(userDataDir, 'launch-prompts')+/*** A filename that is safe to JOIN — never to trust as given. `basename` strips any directory part* (`../../.bashrc` becomes `.bashrc`), and the leftovers that basename still allows through on@@ -40,7 +50,7 @@ export function safeUploadName(name: string): string {}/** Delete upload folders older than the TTL. Best-effort: a sweep that fails changes nothing. */-async function sweep(root: string): Promise<void> {+async function sweep(root: string, ttlMs: number): Promise<void> {try {const now = Date.now()for (const entry of await fs.readdir(root, { withFileTypes: true })) {@@ -48,7 +58,7 @@ async function sweep(root: string): Promise<void> {const dir = join(root, entry.name)try {const st = await fs.stat(dir)- if (now - st.mtimeMs > UPLOAD_TTL_MS) await fs.rm(dir, { recursive: true, force: true })+ if (now - st.mtimeMs > ttlMs) await fs.rm(dir, { recursive: true, force: true })} catch {/* a directory that vanished mid-sweep needs no removing */}@@ -74,13 +84,17 @@ export async function saveUpload(if (typeof dataBase64 !== 'string' || dataBase64.length > UPLOAD_MAX_BYTES * 1.4) return nullconst buf = Buffer.from(dataBase64, 'base64')if (!buf.length || buf.length > UPLOAD_MAX_BYTES) return null- const root = uploadsRoot(userDataDir)- void sweep(root)+ const fileName = safeUploadName(name)+ const launchPrompt = fileName.startsWith(LAUNCH_PROMPT_FILE_PREFIX)+ const root = launchPrompt ? launchPromptsRoot(userDataDir) : uploadsRoot(userDataDir)+ void sweep(root, launchPrompt ? LAUNCH_PROMPT_TTL_MS : UPLOAD_TTL_MS)const token = `${Date.now().toString(36)}${(seq++).toString(36)}`const dir = join(root, token)- await fs.mkdir(dir, { recursive: true })- const target = join(dir, safeUploadName(name))- await fs.writeFile(target, buf)+ // A launch prompt is an agent's brief (often an issue reference and the task): owner-only.+ // Pastes keep the modes they always had. Windows ignores both.+ await fs.mkdir(dir, { recursive: true, ...(launchPrompt ? { mode: 0o700 } : {}) })+ const target = join(dir, fileName)+ await fs.writeFile(target, buf, launchPrompt ? { mode: 0o600 } : undefined)return target} catch {return nulldiff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex e18463e56..f78bcfa7d 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -1146,6 +1146,17 @@ describe('trigger wording does not claim in-process subagent requests (issue #91})})+describe('a held launch whose prompt file is gone is not started (#1014 review)', () => {+ it.each([+ ['skill body', buildCanvasSkillBody('/x/nodeterm.sh')],+ ['instructions block', buildCanvasControlInstructions('/x/nodeterm.sh')]+ ])('%s says so, and names the list marker and the way out', (_name, body) => {+ const flat = body.replace(/\s+/g, ' ')+ expect(flat).toMatch(/whose file is gone by then is not started/)+ expect(flat).toContain('`list` marks it HELD and it waits for `run`')+ })+})+describe('--issue: GitHub issue-bound sessions', () => {it('accepts owner/repo#N and #N on the two agent-open verbs', () => {expect(parseControlRequest('open-agent', { agent: 'claude', issue: 'eneskirca/nodeterm#42' })).toEqual({diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 2d1698d7d..16e1f73fc 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -507,6 +507,8 @@ import {deliveriesToRetire,launchesToFire,queueControlLaunch,+ withLaunchBrief,+ launchBriefPresent,LAUNCH_STALL_MS,type ArmedNode} from '../lib/pendingLaunch'@@ -2048,6 +2050,12 @@ export function Canvas() {// sitting in a poll loop burning context.useEffect(() => {const live = new Set(nodes.map((n) => n.id))+ const briefPresent = (path: string | undefined): Promise<boolean> =>+ launchBriefPresent(+ path,+ useProjects.getState().getProject(nodesProjectIdRef.current ?? ''),+ (p) => activeSession.api.fs.exists(p)+ )const ready = launchesToFire(nodes as unknown as ArmedNode[],useAgentStatus.getState().byId,@@ -2101,7 +2109,7 @@ export function Canvas() {launchInFlight.current.add(f.id)const attempt = (launchAttempts.current.get(f.id) ?? 0) + 1launchAttempts.current.set(f.id, attempt)- void launchCommand(f.id, f.command, false, activeSession.api).then((outcome) => {+ const deliverHeld = (): Promise<void> => launchCommand(f.id, f.command, false, activeSession.api).then((outcome) => {if (outcome === 'submitted') {setNodes((ns) =>ns.map((n) => (n.id === f.id ? { ...n, data: { ...n.data, pendingLaunch: undefined } } : n))@@ -2125,6 +2133,24 @@ 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])@@ -10970,7 +10996,7 @@ export function Canvas() {// 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) => queueControlLaunch(node))])+ setNodes((ns) => [...ns, ...tgMade.map((node) => withLaunchBrief(queueControlLaunch(node), openPrompt.promptFile))])markDirty()reply({ok: true,@@ -10990,7 +11016,7 @@ export function Canvas() {for (const node of tgMade) {tgStore.applyNodeMutation(target.id, {op: 'upsert',- node: flowToNodeStates([armForColdOpen(node)])[0]+ node: flowToNodeStates([withLaunchBrief(armForColdOpen(node), openPrompt.promptFile)])[0]})}void writeDisk()@@ -11336,7 +11362,9 @@ export function Canvas() {// 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 | undefinedconst node =held && coldAfterIds.length@@ -11771,7 +11799,9 @@ export function Canvas() {const armAfter = (node: CanvasNode,after: string[],- intoGroup?: string | null+ intoGroup?: string | null,+ // The file the launch reads its prompt from, checked again right before delivery.+ promptFile?: string): CanvasNode => {const command = node.data.initialCommand as string | undefinedif (!command) return node@@ -11786,7 +11816,7 @@ export function Canvas() {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 queueControlLaunch(node, after, awaitSetupGroup)+ return withLaunchBrief(queueControlLaunch(node, after, awaitSetupGroup), promptFile)}// 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 slot@@ -12029,7 +12059,8 @@ export function Canvas() {openPrompt.promptFile),after ?? [],- intoGroupId+ intoGroupId,+ openPrompt.promptFile)const bound = bindIssue(node, issueRef)if (issueRef) issueNodes.push(bound)@@ -12425,7 +12456,9 @@ export function Canvas() {)return armAfter({ ...node, data: { ...node.data, title: `Verify: ${lens}`, titleAuto: false } },- [targetId]+ [targetId],+ undefined,+ lensLaunches[i].promptFile)})const reviewerIds = reviewers.map((r) => r.id)@@ -12455,7 +12488,9 @@ export function Canvas() {)return { ...j, data: { ...j.data, title: 'Verify: verdict', titleAuto: false } }})(),- reviewerIds+ reviewerIds,+ undefined,+ judgeLaunch.promptFile): nullconst panelIds = [...reviewerIds, ...(judge ? [judge.id] : [])]diff --git a/src/renderer/canvas/control-cold-open.source.test.ts b/src/renderer/canvas/control-cold-open.source.test.tsindex 90bcefbef..99947518f 100644--- a/src/renderer/canvas/control-cold-open.source.test.ts+++ b/src/renderer/canvas/control-cold-open.source.test.ts@@ -97,7 +97,7 @@ describe('the cold-open dispatch block (source pins)', () => {// `flowToNodeStates` drops `initialCommand` by design, so a node upserted without moving its// command into `pendingLaunch` is the silent-never-starts mutation.const body = coldOpenBody()- expect(body).toMatch(/const armed = armForColdOpen\(built\)/)+ expect(body).toMatch(/const armed = withLaunchBrief\(armForColdOpen\(built\), openPrompt\.promptFile\)/)expect(body).toMatch(/flowToNodeStates\(\[node\]\)\[0\]/)// `--after` rides that same held launch rather than a second mechanism.expect(body).toMatch(/pendingLaunch: \{ \.\.\.held, after: coldAfterIds \}/)diff --git a/src/renderer/canvas/control-open-project.source.test.ts b/src/renderer/canvas/control-open-project.source.test.tsindex d43936db1..1d2b70079 100644--- a/src/renderer/canvas/control-open-project.source.test.ts+++ b/src/renderer/canvas/control-open-project.source.test.ts@@ -159,7 +159,8 @@ describe('the --project targeted-opens block (source pins)', () => {// 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\]/)+ // `withLaunchBrief` records the prompt file on the launch armForColdOpen moved (#1014 review).+ expect(body).toMatch(/flowToNodeStates\(\[withLaunchBrief\(armForColdOpen\(node\), openPrompt\.promptFile\)\]\)\[0\]/)})it('the store path persists (writeDisk) and states the cold-open contract in the reply', () => {diff --git a/src/renderer/canvas/control-prompt-spill.source.test.ts b/src/renderer/canvas/control-prompt-spill.source.test.tsindex b993a46d7..3a5fc9449 100644--- a/src/renderer/canvas/control-prompt-spill.source.test.ts+++ b/src/renderer/canvas/control-prompt-spill.source.test.ts@@ -126,3 +126,33 @@ describe('each open path types openPrompt, never its own inline prompt', () => {expect(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)')+ // …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 --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.tsindex 701ea65d5..7856a9cc9 100644--- a/src/renderer/lib/controlRouting.ts+++ b/src/renderer/lib/controlRouting.ts@@ -198,6 +198,7 @@ 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'diff --git a/src/renderer/lib/pendingLaunch.test.ts b/src/renderer/lib/pendingLaunch.test.tsindex 60c89b688..2859b6f28 100644--- a/src/renderer/lib/pendingLaunch.test.ts+++ b/src/renderer/lib/pendingLaunch.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect } from 'vitest'+import { describe, it, expect, vi } from 'vitest'import {launchesToFire,queueControlLaunch,@@ -7,6 +7,8 @@ import {launchTooltip,unmetDeps,LAUNCH_STALL_MS,+ withLaunchBrief,+ launchBriefPresent,type ArmedNode,type StatusById} from './pendingLaunch'@@ -337,3 +339,54 @@ it('a refused relay launch explains host recovery rather than promising a workinexpect(text).toContain('claude brief')expect(text).not.toContain('press ▶')})++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 --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.tsindex 051dc6f14..89bc0b457 100644--- a/src/renderer/lib/pendingLaunch.ts+++ b/src/renderer/lib/pendingLaunch.ts@@ -21,6 +21,22 @@ export type StatusById = Record<export 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 } } }}/** Control opens reply before the PTY exists. Keep their command durable until delivery lands,@@ -42,12 +58,32 @@ export function queueControlLaunch<T extends { data: { initialCommand?: string;}}+/**+ * 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' | 'dropped' | 'working' | undefined {+): 'queued' | 'stalled' | 'failed' | 'starting' | 'brief-missing' | 'dropped' | 'working' | undefined {if (pending) return delivery?.kind ?? 'queued'if (status?.dropped) return 'dropped'if (status?.state === 'working') return 'working'@@ -131,7 +167,9 @@ 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- 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}@@ -166,6 +204,8 @@ export type LaunchDelivery =| { kind: 'failed'; attempts: number; at: number }/** A headless start (#925) is in flight: core owns the pane, so ▶ must not type into it. */| { kind: 'starting'; since: number }+ /** The file the launch reads its prompt from was gone at delivery: held for ▶, never typed. */+ | { kind: 'brief-missing'; path: string; at: number }/*** Which delivery records the Canvas sweep retires: every record whose node is no longer an armed@@ -206,6 +246,15 @@ export function launchTooltip(if (delivery?.kind === 'starting') return 'Starting in the background — an agent asked for this session to run now.'const runs = `Runs:\n${command}`if (relay) return `Launch delivery from a relay tab is unavailable. Open the host to run this command.\n${runs}`+ // Checked right before typing: the file the prompt is read from went away (a spill outlived its+ // TTL while a cold-opened node waited, or a `--prompt-file` was deleted). Typing the command would+ // start the agent with an empty prompt, so it is held, and ▶ is the human's call.+ if (delivery?.kind === 'brief-missing')+ return (+ `The file this launch reads its prompt from no longer exists:\n${delivery.path}\n` ++ 'It was not started, because the agent would get no brief. Open the node again with its ' ++ `prompt, or press \u25b6 to run it anyway.\n${runs}`+ )if (delivery?.kind === 'failed')return ('Launch delivery is unconfirmed; automatic retry is stopped.\n' +diff --git a/src/renderer/lib/promptSpill.test.ts b/src/renderer/lib/promptSpill.test.tsindex 73a4edef0..43ac1d581 100644--- a/src/renderer/lib/promptSpill.test.ts+++ b/src/renderer/lib/promptSpill.test.ts@@ -12,6 +12,7 @@ import { MAX_LAUNCH_LINE_BYTES, fitsLaunchLine, lineBytes } from '@shared/canoniimport { DEFAULT_LENSES, verifyLensPrompt, verifySynthesisPrompt } from './verifyPanel'import { assembleLaunchCommand } from '@shared/agents/launch'import { issueLaunchPrompt } from '@shared/github-issue-ref'+import { LAUNCH_PROMPT_FILE_PREFIX } from '@shared/launch-prompt'const io = (saveUpload: (n: string, d: string) => Promise<string | null>) => ({saveUpload,@@ -81,6 +82,15 @@ describe('spillPromptToFile', () => {).toBeNull()})+ it('names the file with the launch-prompt prefix, which keeps it out of the 7-day uploads sweep', async () => {+ let named = ''+ await spillPromptToFile('x', io(async (n) => {+ named = n+ return '/tmp/x'+ }))+ expect(named.startsWith(LAUNCH_PROMPT_FILE_PREFIX)).toBe(true)+ })+it('never reuses a name — two spills in the same millisecond are separate files', async () => {const names: string[] = []const sink = io(async (n) => {diff --git a/src/renderer/lib/promptSpill.ts b/src/renderer/lib/promptSpill.tsindex d35a2bd23..27630f267 100644--- a/src/renderer/lib/promptSpill.ts+++ b/src/renderer/lib/promptSpill.ts@@ -27,6 +27,7 @@// `shouldSpillPrompt` takes that as an explicit argument rather than guessing.import { MAX_LAUNCH_LINE_BYTES, lineBytes } from '@shared/canonical-line'+import { LAUNCH_PROMPT_FILE_PREFIX } from '@shared/launch-prompt'/*** How many bytes of PROMPT we will put on a typed line before spilling.@@ -110,7 +111,9 @@ export async function spillPromptToFile(io: PromptSpillIo): Promise<string | null> {try {- const name = `nodeterm-prompt-${Date.now().toString(36)}-${(spillSeq++).toString(36)}.txt`+ // The prefix is what makes the core keep this file out of the 7-day uploads sweep+ // (@shared/launch-prompt): it is read at LAUNCH, which for a cold open can be weeks away.+ const name = `${LAUNCH_PROMPT_FILE_PREFIX}${Date.now().toString(36)}-${(spillSeq++).toString(36)}.txt`const path = await io.saveUpload(name, io.encodeBase64(flattenPrompt(prompt)))return path || null} catch {diff --git a/src/renderer/state/launchDelivery.ts b/src/renderer/state/launchDelivery.tsindex 29d994dc1..d97de1476 100644--- a/src/renderer/state/launchDelivery.ts+++ b/src/renderer/state/launchDelivery.ts@@ -27,6 +27,9 @@ import type { LaunchDelivery } from '../lib/pendingLaunch'* click would splice a second copy of the command into the one core is typing. Its orchestrator* owns it end to end — `clear` on a start (or a refusal before any spawn), `markFailed` on any* other failure — which is why the Canvas sweep never retires it (`deliveriesToRetire`).+ * - `brief-missing` — the gate opened and the session is up, but the file the launch reads its+ * prompt from is gone. Typing the command would start the agent with no brief, so it is held+ * (the node is persisted `manualOnly`) and the tooltip names the path; ▶ runs it anyway.** No state is ever inferred from silence. `stalled` is raised by a timer that starts when the gate* opens, `failed` only after a delivery was actually attempted and refused, `starting` only by the@@ -42,6 +45,8 @@ interface LaunchDeliveryStore {markFailed: (nodeId: string, attempts: number) => void/** A headless start (#925) is about to type this node's launch: ▶ must stand aside until it settles. */markStarting: (nodeId: string) => void+ /** The launch's prompt file was gone at delivery: held for ▶, with the path, never typed. */+ markBriefMissing: (nodeId: string, path: string) => void/** Delivered, disarmed, or the node is gone — nothing left to report. */clear: (nodeId: string) => void}@@ -59,6 +64,8 @@ export const useLaunchDelivery = create<LaunchDeliveryStore>((set) => ({// Unconditional: a start replaces whatever an earlier attempt left behind, `failed` included —// that record described the attempt this one is retrying.set((s) => ({ byId: { ...s.byId, [nodeId]: { kind: 'starting', since: Date.now() } } })),+ markBriefMissing: (nodeId, path) =>+ set((s) => ({ byId: { ...s.byId, [nodeId]: { kind: 'brief-missing', path, at: Date.now() } } })),markFailed: (nodeId, attempts) =>set((s) => {// Never let a later, smaller count shrink the record: the manual ▶ reports its own singlediff --git a/src/shared/launch-prompt.ts b/src/shared/launch-prompt.tsnew file mode 100644index 000000000..e1e22c901--- /dev/null+++ b/src/shared/launch-prompt.ts@@ -0,0 +1,15 @@+// A launch prompt spilled to a file (#706) is read when the node LAUNCHES, not when it is opened.+// For a cold-opened node that is whenever its project is next viewed — possibly weeks later — so the+// file cannot live under the uploads staging area, which is swept after 7 days on the next paste.+// The renderer names its spills with this prefix; the core writing them (`saveUpload`) puts that+// name under its own root with its own, longer TTL. Shared so the two sides cannot disagree.++export const LAUNCH_PROMPT_FILE_PREFIX = 'nodeterm-prompt-'++/**+ * How long a spilled prompt is kept. Longer than the longest `--after-pr` deadline (14 days) with a+ * wide margin, but a cold open waits for a human to look at its project, which can be longer still:+ * the delivery loop therefore checks that the file is there before it types the launch+ * (`LaunchToFire.briefFile`) and holds the node for ▶ with the reason when it is not.+ */+export const LAUNCH_PROMPT_TTL_MS = 30 * 86_400_000diff --git a/src/shared/types.ts b/src/shared/types.tsindex 92217b1f5..b8837af06 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -431,6 +431,14 @@ export interface PendingLaunch {* outlives the run's event stream — an app restart — releases rather than strands the node.*/awaitSetupGroup?: string+ /**+ * 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 {