Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(control): --after-pr holds an open until a pull request passes checks or merges

reviewb26a2a195829
diff --git a/CLAUDE.md b/CLAUDE.md
index 681ef4254..c42669937 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3440,6 +3440,55 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
so reporting it as "the error" would be a confident wrong fact. Reading the text, and the
*failed-to-start* watchdog (a station that never emits ANY hook event — the opposite failure,
which hangs dependents honestly rather than firing them wrongly), stay open.
+ **Pull request waits (`--after-pr`, 2026-09-29).** `open-terminal --cmd …` / `open-claude` /
+ `open-agent` take `--after-pr <N:checks|N:merged>[,…]` (N may be `#N` or `owner/repo#N`) and
+ `--pr-deadline <90m|12h|3d>`: the held launch ALSO waits for pull requests of the project's
+ board repository, ANDed with `after` and the setup gate. The grammar, the persisted shape
+ (`pendingLaunch.afterPr = {repository, waits, deadlineAt}`) and main's shape gate are ONE module,
+ `@shared/pr-wait`; when a wait is met is `renderer/lib/prWait.ts`. Rules a refactor must not undo:
+ - **No new poller, no new request path.** The status is #1008's `GitHubPullBoard` from the host's
+ memory. Canvas holds the board's own refcounted host subscription (`watchPulls`) while any live
+ node holds a PR wait, so #1008's conditional heartbeat (free while nothing changes) keeps it
+ fresh; a `checks` wait also asks the host's bounded chase (`usePullChase`, visible window only)
+ because a finished check run does not move the heartbeat. Past the chase cap (12 reads, about
+ 48 minutes) a still-running CI is noticed on the next repository change — the deadline and ▶
+ are the answer, never a timer of our own.
+ - **#1008's semantics, not new ones.** `checks` = `ci === 'passed'`, which `pullStatusFrom`
+ reports only for a SUCCESS rollup at the CURRENT head; a null rollup ("no checks") never passes;
+ a STALE board never passes `checks` (a push since the last read carries other checks) but may
+ pass `merged` (irreversible). A board whose repository differs from the hold's is `blocked`,
+ which holds rather than fires — that is also what makes a mid-switch board harmless.
+ - **Unknown is never satisfied, in both directions.** `launchesToFire` treats a caller that passes
+ no PR context as CLOSED for a PR hold (the opposite of the setup gate, whose absent probe is
+ open for a restart reason that does not apply here), and a malformed persisted hold becomes
+ `INVALID_PR_WAIT_HOLD` — present, expired, never satisfied — never `undefined`, because dropping
+ it would start the node on its `--after` deps alone. `normalizePendingLaunch`
+ (`@shared/pending-launch-shape`) now runs at BOTH serializer seams for the whole held launch: an
+ `after` that is not a list used to throw inside the canvas's dep-signature selector; an
+ unreadable gate turns the hold `manualOnly` instead of opening it.
+ - **Deadline, and the escape.** Default 24h, 1m–14d, refused (not clamped) outside it. Past it the
+ node never starts on its own: the badge reads ⚠ EXPIRED (TerminalNode sets its own timer — no
+ store changes at a deadline), `list` says EXPIRED, and ▶ / `run` start it anyway (`planRunVerb`
+ treats a PR hold like `--after`: the mount does not fire it). Exactly-once is unchanged:
+ `launchInFlight` plus clearing `pendingLaunch` on submit.
+ - **Refused at arm time, each with its reason** (`resolvePrWaitFor`, resolved ONCE next to
+ `issuePre`, against the project the node OPENS in — and only for a caller `issueFlagScope`
+ authorizes, since the lookup tells its caller whether a project's board exists): a relay tab; a board not connected to GitHub
+ (a cwd-less project says why); no repository or sync not approved on this machine; a full
+ `owner/repo#N` in another repository; a number the harvested PR list lacks — only from a WHOLE,
+ refreshed snapshot (`lookupPullRequests`), anything less is the retryable
+ `after-pr-unconfirmed`; a closed-unmerged PR; `:checks` on a merged PR. A `:merged` wait on an
+ already-merged PR is met now and not stored. An SSH project is NOT refused on its own account:
+ its board's status is read by this machine's GitHub client like any other.
+ - Main (`afterPrFlagRefusal` in its handler) and the Server Edition (`parseControlRequest`) share
+ the shape gate: `--run-now` with `--after-pr`, `--pr-deadline` alone, and `open-terminal` without
+ `--cmd` (nothing to hold) are refused. The Server Edition then refuses the well-formed flag by
+ name (its open allowlist) — it keeps no PR watch, and a silent drop would start the node at once.
+ - A node in a project that is not on screen is judged when that project is next viewed (the watch
+ follows the live canvas), the same contract as a cold-opened `--after` node. **Downgrade:** a
+ build older than this one keeps `afterPr` in the file but ignores it, releasing the node on
+ `after` alone. **Kanban / mobile:** the card does not show QUEUED for any held launch (a
+ pre-existing gap, not new here); the phone never sees `pendingLaunch`.
**Headless start (`--run-now`, `run`, #925):** `open-*` with `--run-now` into a project that is
not on screen starts the new node's held launch at once instead of "when next viewed". A node
with nothing held (an `open-terminal` without `--cmd`) has nothing to start, and gets the plain
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 7ac9bea6b..eb40f8762 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -684,6 +684,15 @@ reply carries it (`queued` / `queuedIds`), because a user who cannot see the fai
orchestrator that is told "opened" both act on a session that is not there. If you add a bounded
retry anywhere, ask what the clock actually starts on and where its exhaustion becomes visible.
+**A held launch is hostile input, and a gate nobody can read stays CLOSED.** `pendingLaunch` lives
+in the git-shared `.nodeterm/project.json`, so `normalizePendingLaunch`
+(`src/shared/pending-launch-shape.ts`) runs at both serializer seams: an `after` that is not a list
+used to throw inside the canvas's dependency-signature selector. Its rule, and the rule for any new
+gate you add (the `--after-pr` pull request wait is the latest): a value it cannot read turns the
+hold `manualOnly` or never-satisfied, never "no gate" — dropping it would start the node early, and
+a dependent that has launched cannot un-launch. A new gate field also goes in that module's `KNOWN`
+set, and `launchesToFire` must treat a missing context for it as closed.
+
**Never move the user's view on a background agent's say-so.** Canvas-control requests route by
SOURCE, and React Flow holds only the ACTIVE project's nodes — so the dispatch used to travel to the
caller's project before answering. For an OPEN that was a screen hijack: the user is looking at
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 02df72aa1..a90463228 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -22,6 +22,7 @@ import { nodeColorChoices } from '@shared/node-colors'
import { offScreenGuidanceLines } from '@shared/control-off-screen'
import { codexThreadIdentityResolverSh } from './codex-thread-identity-sh'
import { ISSUE_SESSION_COLUMNS, issueLaunchPrompt, parseIssueArg } from '../shared/github-issue-ref'
+import { PR_DEADLINE_DEFAULT_MS, PR_DEADLINE_MAX_MS, PR_WAIT_MAX, afterPrFlagRefusal } from '../shared/pr-wait'
/**
* The messaging verbs' retry guidance, RENDERED from `RETRYABLE` — the table is the source, and
@@ -88,6 +89,35 @@ function issueBindingDocLines(): string[] {
]
}
+/** The `--after-pr` paragraph both agent-facing bodies share. Its limits come from the one module
+ * that enforces them (`@shared/pr-wait`), so the text cannot promise a deadline the gate refuses. */
+function afterPrDocLines(): string[] {
+ const hours = PR_DEADLINE_DEFAULT_MS / 3_600_000
+ const days = PR_DEADLINE_MAX_MS / 86_400_000
+ return [
+ 'Pull request waits (`--after-pr`, on `open-terminal` / `open-claude` / `open-agent`):',
+ '- `--after-pr <N:checks|N:merged>[,<N:cond>…]` also holds the launch until pull requests of this',
+ ' project\'s repository are ready. `checks` = the PR\'s checks passed at its CURRENT head commit (a new',
+ ' push starts the wait over, and a PR that reports no checks never passes); `merged` = the PR is merged.',
+ ' It is ANDed with `--after` (and a worktree\'s setup wait), so "start the reviewer once CI is green',
+ ' AND the builder is done" is one open. Write the number bare (`1008:merged`): an unquoted leading',
+ ' `#` starts a shell comment and drops the rest of your line (`owner/repo#N:merged` works when quoted).',
+ ` At most ${PR_WAIT_MAX} pull requests, each named once.`,
+ `- \`--pr-deadline <90m|12h|3d>\` bounds the wait (default ${hours}h, at most ${days}d). Past it the node`,
+ ' never starts on its own: `list` marks it EXPIRED, and you start it with the `run` verb (the user can',
+ ' press ▶ on the node). Before it, a closed PR or failing checks keep it waiting, never fire it.',
+ '- Refused, with the reason: the pull request must exist in the repository this project\'s kanban board',
+ ' syncs with (not another repository; a PR closed without merging and `:checks` on a merged PR are',
+ ' refused, and a `:merged` wait on an already-merged PR is simply met); a project whose board is not',
+ ' connected to GitHub, or whose GitHub sync is not approved on this machine; a relay tab.',
+ ' `--run-now` cannot be combined with `--after-pr`, and `open-terminal` needs `--cmd` for it.',
+ '- The status is the board\'s own GitHub sync, read on this machine: a merge is noticed on its next',
+ ' sync (about a minute while the app runs), finished checks are re-read on a backoff while the window',
+ ' is visible, and a node in a project that is not on screen starts once that project is next viewed.',
+ ' The Server Edition refuses `--after-pr`.'
+ ]
+}
+
function settingsVerbDocLines(): string[] {
const keys = SETTINGS_VERB_KEY_LIST.map((key) => {
const { scope, type } = SETTINGS_VERB_KEYS[key]
@@ -388,6 +418,10 @@ export function parseControlRequest(
if (v === 'open-agent' && !args.agent) return { error: 'open-agent requires --agent <id>' }
const issueRefusal = issueFlagRefusal(v, args)
if (issueRefusal) return { error: issueRefusal }
+ // `--after-pr`: the same shape gate desktop main runs before forwarding. The Server Edition then
+ // refuses the well-formed flag as unsupported (its open allowlist), since it keeps no PR watch.
+ const afterPrRefusal = afterPrFlagRefusal(v, args)
+ if (afterPrRefusal) return { error: afterPrRefusal }
if ((v === 'group' || v === 'arrange') && !args.nodes) return { error: `${v} requires --nodes <id,id>` }
if (v === 'ungroup' && !args.group) return { error: 'ungroup requires --group <id>' }
if (v === 'move' && !args.nodes) return { error: 'move requires --nodes <id,id>' }
@@ -498,9 +532,9 @@ export function buildCanvasControlInstructions(shimPath: string): string {
'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.',
- '- `open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--project <id>] [--run-now]` — open N plain terminals. `--cmd` requires verified node identity.',
- '- `open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]` — open N Claude sessions.',
- `- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open`,
+ '- `open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--run-now]` — open N plain terminals. `--cmd` requires verified node identity.',
+ '- `open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]` — open N Claude sessions.',
+ `- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open`,
' any agent CLI. `--group` parents the node(s) into a group frame; a worktree-bound group also',
' hands its worktree path down as the cwd. `--after <id,id>` opens the node ARMED: it does not',
' start until every listed station has finished a turn SUCCESSFULLY. It is',
@@ -542,8 +576,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' then reports through the ordinary status hooks — there is nothing to poll.',
' With `--run-now` a started node is listed in `startedIds`, not `queuedIds`.',
' `queued: false` is not proof the agent is running. `deliveredIds` confirms command delivery only.',
- ' `list` names QUEUED, STARTING, LAUNCH FAILED, DROPPED and AGENT STATUS UNCONFIRMED where',
- ' observed. STARTING means a background start is in flight: do not `run` that node again.',
+ ' `list` names QUEUED, STARTING, LAUNCH FAILED, EXPIRED, DROPPED and AGENT STATUS UNCONFIRMED',
+ ' where observed. STARTING means a background start is in flight: do not `run` that node again.',
' `--prompt` arrives on ONE LINE: every run of whitespace in it, newlines included, is',
' collapsed to a single space before the session starts (the prompt rides the launch command',
' line typed into the pane). For a structured or multi-line brief use `--prompt-file <abs',
@@ -564,6 +598,7 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' exactly as it would without the flag. The id is passed to the CLI as-is, so a name that',
' agent does not recognise fails inside the session, not at open time — name a model you know.',
...issueBindingDocLines(),
+ ...afterPrDocLines(),
'- `open-project --cwd </abs/path> [--name N] [--color C]` — register (or find) the project for a',
' local directory; the reply carries `{ projectId, name, cwd, created }`. Idempotent: the same',
' cwd always returns the same project, never a duplicate. Creating/adding asks the user to',
@@ -989,9 +1024,9 @@ Verbs:
not seven. It clears itself the moment that station completes another turn.
- \`help\` — print the verb list. The shim answers this itself, without reaching the app, so it
is also what to run when you are unsure whether the control endpoint is alive.
-- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--project <id>] [--run-now]\` — open N plain terminals (default 1). \`--cmd\` requires verified node identity.
-- \`open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open N Claude sessions (default 1).
-- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open N sessions of any agent CLI.
+- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--run-now]\` — open N plain terminals (default 1). \`--cmd\` requires verified node identity.
+- \`open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open N Claude sessions (default 1).
+- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open N sessions of any agent CLI.
\`--group\` parents the node(s) into an existing group frame; a worktree-bound group also
hands its worktree path down as the cwd.
\`--after <id,id>\` opens the node **armed**: it does NOT start yet, and launches itself once
@@ -1038,8 +1073,8 @@ Verbs:
to it, do not \`send\` to it and do not report it as started. It launches itself when its wait
ends and then reports through the ordinary status hooks, so there is nothing to poll.
\`queued: false\` does not prove the agent is running. \`deliveredIds\` confirms command delivery only.
- \`list\` names QUEUED, STARTING, LAUNCH FAILED, DROPPED and AGENT STATUS UNCONFIRMED where
- observed. STARTING means a background start is in flight: do not \`run\` that node again.
+ \`list\` names QUEUED, STARTING, LAUNCH FAILED, EXPIRED, DROPPED and AGENT STATUS UNCONFIRMED
+ where observed. STARTING means a background start is in flight: do not \`run\` that node again.
\`--prompt\` arrives on ONE LINE. Every run of whitespace in it — newlines included — is
collapsed to a single space before the session starts, because the prompt is passed as an
argument on the agent CLI's launch command line and that line is typed into the pane. Two
@@ -1073,6 +1108,7 @@ Verbs:
id goes to the CLI verbatim: an unknown name fails inside the session on its first turn, not at
open time, so name a model you know that CLI accepts rather than guessing.
${issueBindingDocLines().join('\n')}
+${afterPrDocLines().join('\n')}
- \`open-project --cwd </abs/path> [--name N] [--color C]\` — register (or find) the project for a
local directory; the reply carries \`{ projectId, name, cwd, created }\`. Idempotent: the same
cwd always returns the same project, never a duplicate — and \`--name\`/\`--color\` apply only
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index e1a01823d..a26087b21 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -1218,3 +1218,70 @@ describe('--issue: GitHub issue-bound sessions', () => {
expect(body).not.toMatch(/nodeterm (posts|comments|closes)/i)
})
})
+
+describe('--after-pr: open a node that waits on a pull request', () => {
+ it('passes a well-formed wait through the shape gate on the open verbs', () => {
+ expect(parseControlRequest('open-agent', { agent: 'claude', 'after-pr': '1008:checks' })).toEqual({
+ verb: 'open-agent',
+ args: { agent: 'claude', 'after-pr': '1008:checks' }
+ })
+ expect(parseControlRequest('open-claude', { 'after-pr': '#7:merged', 'pr-deadline': '3d' })).toMatchObject({
+ verb: 'open-claude'
+ })
+ expect(parseControlRequest('open-terminal', { 'after-pr': '7:merged', cmd: 'make' })).toMatchObject({
+ verb: 'open-terminal'
+ })
+ })
+
+ it.each([
+ [{ 'after-pr': '7' }, /--after-pr must be/],
+ [{ 'after-pr': '7:green' }, /--after-pr must be/],
+ [{ 'after-pr': '7:merged', 'run-now': '' }, /--run-now cannot be combined with --after-pr/],
+ [{ 'pr-deadline': '2d' }, /only with --after-pr/],
+ [{ 'after-pr': '7:merged', 'pr-deadline': '30d' }, /--pr-deadline must be/]
+ ])('refuses %j before the renderer sees it', (args, error) => {
+ const r = parseControlRequest('open-agent', { agent: 'claude', ...args })
+ expect((r as { error?: string }).error).toMatch(error)
+ })
+
+ it('refuses the flag on a verb that opens nothing, and on a terminal with nothing to run', () => {
+ expect((parseControlRequest('spawn-team', { team: '[]', 'after-pr': '7:merged' }) as { error: string }).error).toMatch(
+ /applies only to open-terminal/
+ )
+ expect((parseControlRequest('open-terminal', { 'after-pr': '7:merged' }) as { error: string }).error).toMatch(
+ /needs --cmd/
+ )
+ })
+
+ const bodies: Array<[string, string]> = [
+ ['skill body', buildCanvasSkillBody('/x/nodeterm.sh')],
+ ['instructions block', buildCanvasControlInstructions('/x/nodeterm.sh')]
+ ]
+
+ it.each(bodies)('%s lists the flag on all three open verbs', (_name, body) => {
+ expect(body).toMatch(/open-terminal [^\n]*\[--after-pr <N:checks\|N:merged>\] \[--pr-deadline <90m\|12h\|3d>\]/)
+ expect(body).toMatch(/open-claude [^\n]*\[--after-pr <N:checks\|N:merged>\] \[--pr-deadline <90m\|12h\|3d>\]/)
+ expect(body).toMatch(/open-agent --agent [^\n]*\[--after-pr <N:checks\|N:merged>\] \[--pr-deadline <90m\|12h\|3d>\]/)
+ })
+
+ it.each(bodies)('%s states what each condition means, the deadline and the refusals', (_name, body) => {
+ const flat = body.replace(/\s+/g, ' ')
+ // The two conditions, with #1008's own rules.
+ expect(flat).toContain('`checks` = the PR\'s checks passed at its CURRENT head commit')
+ expect(flat).toContain('a PR that reports no checks never passes')
+ expect(flat).toContain('`merged` = the PR is merged')
+ expect(flat).toContain('ANDed with `--after`')
+ // The deadline and the escape.
+ expect(flat).toContain('default 24h, at most 14d')
+ expect(flat).toContain('`list` marks it EXPIRED')
+ expect(flat).toContain('`list` names QUEUED, STARTING, LAUNCH FAILED, EXPIRED, DROPPED and AGENT STATUS UNCONFIRMED')
+ expect(flat).toContain('you start it with the `run` verb')
+ // What is refused.
+ expect(flat).toContain('the pull request must exist in the repository this project\'s kanban board syncs with')
+ expect(flat).toContain('a project whose board is not connected to GitHub')
+ expect(flat).toContain('`--run-now` cannot be combined with `--after-pr`')
+ expect(flat).toContain('The Server Edition refuses `--after-pr`')
+ // Quoting: an unquoted leading # starts a shell comment.
+ expect(flat).toContain('Write the number bare (`1008:merged`)')
+ })
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index fb8fa9c99..cf562566c 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -270,6 +270,7 @@ import { transcriptPathOf } from '../core/context-link-core'
import { initCanvasControl, installCanvasSkillInto } from './canvas-control'
import { DRY_RUN_VERBS, dryRunRequested, dryRunRefusal } from '../shared/control-verbs'
import { issueFlagRefusal } from '../core/canvas-control-core'
+import { afterPrFlagRefusal } from '../shared/pr-wait'
import { CONTROL_REQUEST_TIMEOUT_MS } from '../shared/control-confirm'
import { initTranscriptIndex, searchTranscripts } from '../core/transcript-index'
import { initTelemetry } from './telemetry'
@@ -3737,6 +3738,10 @@ app.whenReady().then(async () => {
// renderer resolves `#N` against the project's repository and re-parses with the same grammar.
const issueRefusal = issueFlagRefusal(verb, args)
if (issueRefusal) return { ok: false, error: issueRefusal, message: issueRefusal }
+ // `--after-pr` / `--pr-deadline`: same placement and same reason. Whether the pull request
+ // exists in the board's repository is the renderer's question (`resolvePrWaitFor`).
+ const afterPrRefusal = afterPrFlagRefusal(verb, args)
+ if (afterPrRefusal) return { ok: false, error: afterPrRefusal, message: afterPrRefusal }
// `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 2d1698d7d..b004395a2 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -507,9 +507,14 @@ import {
deliveriesToRetire,
launchesToFire,
queueControlLaunch,
+ withPrHold,
LAUNCH_STALL_MS,
type ArmedNode
} from '../lib/pendingLaunch'
+import { prHoldReports, prWaitReplyLine, resolvePrWaitFor, type PrWaitArmResult } from '../lib/prWait'
+import { RUN_NOW_AFTER_PR_REFUSAL } from '@shared/pr-wait'
+import { lookupPullRequests, pullBoardFor, useGitHubIssues } from '../state/githubIssues'
+import { usePullChase } from '../components/kanban/usePullAutoMove'
import { WAIT_LABEL, dropAfterDep, edgeHidden, hiddenEdgeNodeIds, missingDepRopes, ropeInfoOf, ropeVisual } from '../lib/edgeModel'
import { triggerEdges } from '../lib/triggerCard'
import {
@@ -2002,6 +2007,61 @@ export function Canvas() {
}
return sig
})
+ // ---- the pull requests an armed node waits on (`--after-pr`) ----
+ // Judged against the pull request status of the project whose nodes are on this canvas
+ // (`nodesProjectIdRef`, never a separately-read active id: during a switch the two disagree, and
+ // a board for the wrong repository answers "blocked", which holds rather than fires). A PRIMITIVE
+ // signature of each wait's state, the same discipline as `armedDepSig`: the launch effect re-runs
+ // when a waited-on PR changes, and nothing re-renders on an unrelated GitHub update.
+ const armedPrSig = useGitHubIssues((s) => {
+ let sig = ''
+ let board: ReturnType<typeof pullBoardFor>
+ let read = false
+ for (const n of nodesRef.current) {
+ const hold = (n.data.pendingLaunch as PendingLaunch | undefined)?.afterPr
+ if (!hold) continue
+ if (!read) {
+ board = pullBoardFor(s, nodesProjectIdRef.current ?? '')
+ read = true
+ }
+ sig += `${n.id}:${prHoldReports(hold, board).map((r) => r.state).join(',')}|`
+ }
+ return sig
+ })
+ // Keep the host's pull request status coming while any node here waits on a PR. It is the board's
+ // own refcounted host subscription and #1008's conditional heartbeat (free while nothing changes),
+ // not a poller; a `checks` wait also asks the host's bounded chase (30 s … 5 min, at most 12 reads
+ // per episode) while the window is visible, because a finished check run does not move the
+ // heartbeat. Everything is released the moment no node waits any more.
+ const prWatchNeeded = nodes.some((n) => !!(n.data.pendingLaunch as PendingLaunch | undefined)?.afterPr)
+ const prWatchProjectId = prWatchNeeded ? (nodesProjectIdRef.current ?? '') : ''
+ useEffect(() => {
+ if (!prWatchProjectId) return
+ let cancelled = false
+ let release: (() => void) | undefined
+ void useGitHubIssues
+ .getState()
+ .watchPulls(api.githubIssues, prWatchProjectId)
+ .then(
+ (r) => {
+ if (cancelled) r()
+ else release = r
+ },
+ () => undefined
+ )
+ return () => {
+ cancelled = true
+ release?.()
+ }
+ }, [api, prWatchProjectId])
+ const prChecksWaited = nodes.some((n) =>
+ (n.data.pendingLaunch as PendingLaunch | undefined)?.afterPr?.waits.some((w) => w.until === 'checks')
+ )
+ const prBoardUndecided = useGitHubIssues(
+ (s) => !!prWatchProjectId && !!pullBoardFor(s, prWatchProjectId)?.undecided
+ )
+ const prChaseNeeded = prChecksWaited && prBoardUndecided
+ usePullChase(api.githubIssues, prWatchProjectId, prChaseNeeded)
// Bumped to re-run the launch effect: after a refused delivery's backoff, and when a node
// reports its session ready (`subscribeSessionReady` below).
const [launchNudge, setLaunchNudge] = useState(0)
@@ -2053,7 +2113,9 @@ export function Canvas() {
useAgentStatus.getState().byId,
live,
setupDoneForGroup,
- useLaunchDelivery.getState().byId
+ useLaunchDelivery.getState().byId,
+ // The `--after-pr` gate: this canvas's pull request status and the clock its deadlines are on.
+ { board: pullBoardFor(useGitHubIssues.getState(), nodesProjectIdRef.current ?? ''), now: Date.now() }
).filter((f) => !launchInFlight.current.has(f.id))
// Anything we were reporting on that is no longer an armed node — delivered, run by hand with
// ▶, or deleted — stops being reported. Timers go with it: a stall warning for a node that has
@@ -2126,8 +2188,8 @@ export function Canvas() {
console.warn('[pending-launch] gave up delivering held launch for', f.id)
})
}
- // 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.
@@ -10483,6 +10545,7 @@ export function Canvas() {
// The authorization belt runs FIRST (`resolveIssueFlagForCall`): a caller the paths would
// refuse gets their refusal and never makes the host look up a project's board.
const issueOpen = verb === 'open-agent' || verb === 'open-claude'
+ const openVerb = verb === 'open-terminal' || issueOpen
const issuePre: IssueFlagResult = issueOpen
? await resolveIssueFlagForCall(
{
@@ -10513,7 +10576,7 @@ export function Canvas() {
// Which project that is comes from the SAME authorization belt `#N` runs behind
// (`issueFlagScope`): a caller the paths will refuse gets no project here, so nothing is
// spilled for it — its path refuses it with the same sentence.
- const openScopePre = issueOpen
+ const openScopePre = openVerb
? issueFlagScope({
targetId: args.project,
sourceNodeId,
@@ -10543,6 +10606,58 @@ export function Canvas() {
spillIo
)
: {}
+ // `--after-pr` (see @shared/pr-wait, lib/prWait): which pull requests of the board's repository
+ // the new node(s) also wait on. Resolved HERE for the same two reasons as `issuePre` — it costs
+ // host round trips (the GitHub controller, the harvested PR list), and it must be answered for
+ // the project the node OPENS in. Main refused a malformed value; this is where "that project's
+ // repository has no pull request #N", "its board is not connected to GitHub" and "that PR is
+ // closed" are refused, with the dry run getting the same answer as a real call.
+ // Behind the same belt as `#N`: the lookup asks the host whether a project's board exists and
+ // which pull requests its repository has, so a caller the paths would refuse gets their
+ // refusal here and nobody is asked.
+ const prWaitPre: PrWaitArmResult = !openVerb
+ ? { ok: true, alreadyMerged: [] }
+ : args['after-pr'] !== undefined && openScopePre && !openScopePre.ok
+ ? { ok: false, error: openScopePre.error }
+ : await resolvePrWaitFor(args['after-pr'], args['pr-deadline'], verb, {
+ project: openProjectPre,
+ controlStatus: (id) =>
+ api.githubControl
+ .status(id)
+ .then((view) =>
+ view.project ? { repository: view.project.repository, approved: view.project.approved } : null
+ ),
+ lookupPulls: (id, numbers) =>
+ lookupPullRequests(
+ api.githubIssues,
+ id,
+ (openProjectPre?.kanban?.columns ?? []).map((c) => c.id),
+ numbers
+ ),
+ now: () => Date.now()
+ })
+ if (!prWaitPre.ok) {
+ reply({ ok: false, error: prWaitPre.error })
+ return
+ }
+ const prHoldPre = prWaitPre.hold
+ // What the replies add: the wait, and any `:merged` wait that was already met when armed.
+ const prReplyLines = [
+ ...(prHoldPre ? [prWaitReplyLine(prHoldPre)] : []),
+ ...(prWaitPre.alreadyMerged.length
+ ? [`already merged, so not waited on: ${prWaitPre.alreadyMerged.map((n) => `PR #${n}`).join(', ')}`]
+ : [])
+ ]
+ const prReplyText = prReplyLines.map((l) => `\n${l}`).join('')
+ const prResult = prHoldPre
+ ? {
+ afterPr: {
+ repository: prHoldPre.repository,
+ waits: prHoldPre.waits,
+ deadline: new Date(prHoldPre.deadlineAt).toISOString()
+ }
+ }
+ : {}
// ── Agent messaging (`send`/`reply`) — handled BEFORE the source-routing machinery ──────
// These are STORE_ANSWERED_VERBS (lib/controlRouting): routing by source must never travel
@@ -10834,6 +10949,12 @@ export function Canvas() {
reply({ ok: false, error: RUN_NOW_AFTER_REFUSAL })
return
}
+ // …and "start when the pull request is ready" contradicts it the same way. Main's shape gate
+ // already refused this pair; the renderer never trusts that the gate in front of it ran.
+ if (openVerb && runNowRequested(args) && args['after-pr'] !== undefined) {
+ reply({ ok: false, error: RUN_NOW_AFTER_PR_REFUSAL })
+ return
+ }
// ── `--project` targeted opens (issue #338 Task 2.3) — the three open verbs, early ──────
// Main's gateProjectTarget already enforced own-or-granted BEFORE forwarding (spec §3):
@@ -10970,14 +11091,15 @@ 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) => withPrHold(queueControlLaunch(node), prHoldPre))])
markDirty()
reply({
ok: true,
message: `opened ${tgCount} ${tgWhat} session(s) in "${target.name}" (${tgIds.join(', ')})` +
- (tgQueuedIds.length ? ' — queued; awaiting launch delivery' : ''),
+ (tgQueuedIds.length ? ' — queued; awaiting launch delivery' : '') +
+ prReplyText,
// Being on screen is not proof of launch delivery.
- result: { ids: tgIds, id: tgIds[0], projectId: target.id, queued: tgQueuedIds.length > 0, queuedIds: tgQueuedIds }
+ result: { ids: tgIds, id: tgIds[0], projectId: target.id, queued: tgQueuedIds.length > 0, queuedIds: tgQueuedIds, ...prResult }
})
return
}
@@ -10990,7 +11112,7 @@ export function Canvas() {
for (const node of tgMade) {
tgStore.applyNodeMutation(target.id, {
op: 'upsert',
- node: flowToNodeStates([armForColdOpen(node)])[0]
+ node: flowToNodeStates([withPrHold(armForColdOpen(node), prHoldPre)])[0]
})
}
void writeDisk()
@@ -10999,7 +11121,7 @@ export function Canvas() {
// ONE sentence for "queued into a project you are not looking at", shared with the
// own-project cold open below (lib/coldOpen) so an orchestrator never meets two
// phrasings for one outcome.
- message: coldOpenMessage(tgCount, tgWhat, target.name, tgIds),
+ message: coldOpenMessage(tgCount, tgWhat, target.name, tgIds) + prReplyText,
// Every node on this branch is armed by `armForColdOpen`, so the whole batch is
// QUEUED. Said in the reply as a field, not only in the sentence, so an orchestrator
// does not have to report a session as started when it is not (#569 item 1).
@@ -11008,7 +11130,8 @@ export function Canvas() {
id: tgIds[0],
projectId: target.id,
queued: true,
- queuedIds: tgIds
+ queuedIds: tgIds,
+ ...prResult
} as Record<string, unknown>
}
// #925 `--run-now`: start the held launches now, headless. The nodes were upserted
@@ -11281,6 +11404,7 @@ export function Canvas() {
(coldCwd ? `, cwd ${coldCwd}` : ''),
...(coldIssueRef ? [`bound to GitHub issue ${formatIssueRef(coldIssueRef)}`] : []),
...(coldAfterIds.length ? [`armed to wait for: ${coldAfterIds.join(', ')}`] : []),
+ ...prReplyLines,
// #925: `--run-now` starts it headless instead — except on an SSH project, whose
// nodes a headless start refuses (they start on view, over SSH).
runNowRequested(args) && !owner.ssh
@@ -11338,13 +11462,16 @@ export function Canvas() {
// is vacuously ready, so a node with no deps fires on that project's first view.
const armed = armForColdOpen(built)
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,
data: { ...armed.data, pendingLaunch: { ...held, after: coldAfterIds } }
}
- : armed
+ : armed,
+ prHoldPre
+ )
if (coldGroup.groupId) {
const w = (node.width as number) ?? 600
const h = (node.height as number) ?? 400
@@ -11439,7 +11566,8 @@ export function Canvas() {
? `\nwaiting for ${coldAfterIds.join(', ')} before running` +
(coldDepLinked.length ? ' (and linked to read them)' : '')
: '') +
- (coldIssueRef ? `\nbound to GitHub issue ${formatIssueRef(coldIssueRef)}` : ''),
+ (coldIssueRef ? `\nbound to GitHub issue ${formatIssueRef(coldIssueRef)}` : '') +
+ prReplyText,
// Every node on this branch has no process behind it until that project is viewed,
// whether or not it holds a command — the same rule the `--project` branch states.
result: {
@@ -11449,6 +11577,7 @@ export function Canvas() {
linked: coldPlan.linked,
after: coldAfterIds,
...(coldIssueRef ? { issue: formatIssueRef(coldIssueRef) } : {}),
+ ...prResult,
queued: true,
queuedIds: coldIds
} as Record<string, unknown>
@@ -11786,7 +11915,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 withPrHold(queueControlLaunch(node, after, awaitSetupGroup), 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 slot
@@ -11860,14 +11989,16 @@ export function Canvas() {
(intoGroupId ? ` in group ${intoGroupId}` : '') +
(termCwd ? `, cwd ${termCwd}` : '') +
(args.cmd ? `, running: ${args.cmd}` : ''),
- ...(after?.length ? [`armed to wait for: ${after.join(', ')}`] : [])
+ ...(after?.length ? [`armed to wait for: ${after.join(', ')}`] : []),
+ ...prReplyLines
].join('\n'),
result: {
dryRun: true,
count,
group: intoGroupId ?? null,
cwd: termCwd ?? null,
- after: after ?? []
+ after: after ?? [],
+ ...prResult
}
})
return
@@ -11899,8 +12030,9 @@ export function Canvas() {
message:
`opened ${count} terminal(s): ${ids.join(', ')}` +
(queuedIds.length ? '\nqueued; awaiting launch delivery' : '') +
- (after?.length ? `\nwaiting for ${after.join(', ')} before running` : ''),
- result: openResult
+ (after?.length ? `\nwaiting for ${after.join(', ')} before running` : '') +
+ prReplyText,
+ result: { ...openResult, ...prResult }
})
return
}
@@ -11986,6 +12118,7 @@ export function Canvas() {
: ''),
...(issueRef ? [`bound to GitHub issue ${formatIssueRef(issueRef)}`] : []),
...(after?.length ? [`armed to wait for: ${after.join(', ')}`] : []),
+ ...prReplyLines,
'Each session would be connected + context-linked to you.'
].join('\n'),
result: {
@@ -11995,7 +12128,8 @@ export function Canvas() {
group: intoGroupId ?? null,
cwd: agentCwd ?? null,
after: after ?? [],
- ...(issueRef ? { issue: formatIssueRef(issueRef) } : {})
+ ...(issueRef ? { issue: formatIssueRef(issueRef) } : {}),
+ ...prResult
}
})
return
@@ -12070,11 +12204,13 @@ export function Canvas() {
(after?.length
? `\nwaiting for ${after.join(', ')} before running` +
(depLinked.length ? ` (and linked to read them)` : '')
- : ''),
+ : '') +
+ prReplyText,
result: {
...openResult,
linked: bridged,
- ...(issueRef ? { issue: formatIssueRef(issueRef) } : {})
+ ...(issueRef ? { issue: formatIssueRef(issueRef) } : {}),
+ ...prResult
}
})
return
diff --git a/src/renderer/canvas/control-after-pr.source.test.ts b/src/renderer/canvas/control-after-pr.source.test.ts
new file mode 100644
index 000000000..67407159d
--- /dev/null
+++ b/src/renderer/canvas/control-after-pr.source.test.ts
@@ -0,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\)/)
+ })
+
+ 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\)/)
+ })
+})
+
+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 --git a/src/renderer/canvas/control-open-project.source.test.ts b/src/renderer/canvas/control-open-project.source.test.ts
index d43936db1..c6342274e 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\]/)
+ // `withPrHold` attaches an `--after-pr` wait to the launch armForColdOpen already moved.
+ expect(body).toMatch(/flowToNodeStates\(\[withPrHold\(armForColdOpen\(node\), prHoldPre\)\]\)\[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.ts
index b993a46d7..223be12fc 100644
--- a/src/renderer/canvas/control-prompt-spill.source.test.ts
+++ b/src/renderer/canvas/control-prompt-spill.source.test.ts
@@ -72,7 +72,7 @@ describe('the open prompt is resolved ONCE, before any path reads the store', ()
it('asks the SAME authorization belt as `#N` which project that is — a refused caller spills nothing', () => {
const decided = src.indexOf('const openPrompt:')
const before = src.slice(src.indexOf('const issuePre: IssueFlagResult'), decided)
- expect(before).toMatch(/const openScopePre = issueOpen\s*\?\s*issueFlagScope\(/)
+ expect(before).toMatch(/const openScopePre = (issueOpen|openVerb)\s*\?\s*issueFlagScope\(/)
expect(src.slice(decided, decided + 400)).toContain('openScopePre?.ok')
})
diff --git a/src/renderer/canvas/pending-launch-delivery.source.test.ts b/src/renderer/canvas/pending-launch-delivery.source.test.ts
index e2fd88c6a..27eb59104 100644
--- a/src/renderer/canvas/pending-launch-delivery.source.test.ts
+++ b/src/renderer/canvas/pending-launch-delivery.source.test.ts
@@ -22,7 +22,7 @@ function launchEffect(): string {
const start = src.indexOf('const ready = launchesToFire(')
expect(start).toBeGreaterThan(-1)
const rest = src.slice(start)
- const end = rest.indexOf('armedSetupSig, launchNudge])')
+ const end = rest.indexOf('armedSetupSig, armedPrSig, launchNudge])')
expect(end).toBeGreaterThan(-1)
return rest.slice(0, end)
}
diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.ts
index 3c07ccfe3..2e6c16d25 100644
--- a/src/renderer/lib/controlRouting.test.ts
+++ b/src/renderer/lib/controlRouting.test.ts
@@ -469,3 +469,26 @@ it('lists a background start as STARTING, not as the failed launch its manualOnl
expect(rows[0].launchState).toBe('starting')
expect(controlListingText(rows)).toBe('bg [terminal] — STARTING')
})
+
+it('lists a PR wait on the row, and EXPIRED once its deadline has passed (--after-pr)', () => {
+ const hold = (deadlineAt: number) => ({
+ repository: 'o/r',
+ waits: [{ number: 7, until: 'checks' }, { number: 9, until: 'merged' }],
+ deadlineAt
+ })
+ const rows = storedNodeListing(
+ [
+ { id: 'waits', pendingLaunch: { after: [], command: 'claude', afterPr: hold(2_000) } },
+ { id: 'late', pendingLaunch: { after: [], command: 'claude', afterPr: hold(1_000) } },
+ { id: 'bad', pendingLaunch: { after: [], command: 'claude', afterPr: { invalid: true, waits: [] } } }
+ ],
+ {},
+ {},
+ 1_000
+ )
+ expect(rows.map((r) => r.launchState)).toEqual(['queued', 'expired', 'expired'])
+ const text = controlListingText(rows)
+ expect(text).toContain('waits [terminal] — QUEUED — waits on PR #7 checks, PR #9 merged')
+ expect(text).toContain('late [terminal] — EXPIRED (PR wait deadline passed; run it with `run`)')
+ expect(text).toContain('bad [terminal] — EXPIRED')
+})
diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.ts
index 701ea65d5..949863d74 100644
--- a/src/renderer/lib/controlRouting.ts
+++ b/src/renderer/lib/controlRouting.ts
@@ -15,6 +15,8 @@
import { canControlCanvas, type AgentId } from '@shared/agents/config'
import { formatIssueRef } from '@shared/github-issue-ref'
+import { formatPrWaits, normalizePrWaitHold } from '@shared/pr-wait'
+import { prHoldExpired } from './prWait'
import { controlLaunchState, type LaunchDelivery, type StatusById } from './pendingLaunch'
import { projectTravel } from './presenceTravel'
import {
@@ -175,11 +177,16 @@ export function answerBrowserResolve(
export function storedNodeListing(
nodes: readonly StoredNode[],
statuses: StatusById & Record<string, { dropped?: boolean } | undefined> = {},
- deliveries: Record<string, LaunchDelivery | undefined> = {}
+ deliveries: Record<string, LaunchDelivery | undefined> = {},
+ now: number = Date.now()
) {
return nodes.map((n) => {
const status = statuses[n.id]
- const launchState = controlLaunchState(!!n.pendingLaunch, deliveries[n.id] ?? ((n.pendingLaunch as { manualOnly?: boolean } | undefined)?.manualOnly ? { kind: 'failed', attempts: 1, at: 0 } : undefined), status) ??
+ // `--after-pr`: the row names what the node waits on (the pull request STATUS is the canvas's
+ // to judge; `list` states the wait and whether its deadline has passed, which needs no board).
+ const prHold = normalizePrWaitHold((n.pendingLaunch as { afterPr?: unknown } | undefined)?.afterPr)
+ const prExpired = !!prHold && prHoldExpired(prHold, now)
+ const launchState = controlLaunchState(!!n.pendingLaunch, deliveries[n.id] ?? ((n.pendingLaunch as { manualOnly?: boolean } | undefined)?.manualOnly ? { kind: 'failed', attempts: 1, at: 0 } : undefined), status, prExpired) ??
(n.agentId && !status?.state ? 'unconfirmed' as const : undefined)
// A session started on an issue is told so on its OWN row, so `list` is enough for an agent to
// learn it is bound (and which card to move). Only a reference `formatIssueRef` vouches for.
@@ -188,7 +195,8 @@ export function storedNodeListing(
id: n.id, kind: n.kind ?? 'terminal', title: n.title ?? '',
...(issue ? { issue } : {}),
...(status?.lastTurnError ? { lastTurnErrored: true } : {}),
- ...(launchState ? { launchState } : {})
+ ...(launchState ? { launchState } : {}),
+ ...(launchState === 'queued' && prHold && !prHold.invalid ? { prWait: formatPrWaits(prHold) } : {})
}
})
}
@@ -200,13 +208,15 @@ const launchLabels = {
starting: 'STARTING',
dropped: 'DROPPED',
working: 'WORKING',
- unconfirmed: 'AGENT STATUS UNCONFIRMED'
+ unconfirmed: 'AGENT STATUS UNCONFIRMED',
+ expired: 'EXPIRED (PR wait deadline passed; run it with `run`)'
} as const
export function controlListingText(rows: ReturnType<typeof storedNodeListing>): string {
return rows.map((n) => `${n.id} [${n.kind}] ${n.title}` +
(n.issue ? ` — issue ${n.issue}` : '') +
(n.launchState ? ` — ${launchLabels[n.launchState]}` : '') +
+ (n.prWait ? ` — waits on ${n.prWait}` : '') +
(n.lastTurnErrored ? ' — LAST TURN ERRORED' : '')
).join('\n')
}
diff --git a/src/renderer/lib/headlessRun.test.ts b/src/renderer/lib/headlessRun.test.ts
index 5add3e336..9e972867a 100644
--- a/src/renderer/lib/headlessRun.test.ts
+++ b/src/renderer/lib/headlessRun.test.ts
@@ -59,6 +59,9 @@ describe('planRunVerb', () => {
)
// Armed with --after: the canvas fires it when its deps report done, not on mount.
expect(planRunVerb({ ...onScreen, pending: { ...pending, after: ['dep-1'] } })).toBe('refuse-not-mounted')
+ // Armed with --after-pr: it fires when the pull request is ready, not on mount.
+ const afterPr = { repository: 'o/r', waits: [{ number: 7, until: 'merged' as const }], deadlineAt: 1 }
+ expect(planRunVerb({ ...onScreen, pending: { ...pending, afterPr } })).toBe('refuse-not-mounted')
// The plain, never-attempted, dependency-free launch does start on mount.
expect(planRunVerb({ ...onScreen, pending })).toBe('wait-for-mount')
})
diff --git a/src/renderer/lib/headlessRun.ts b/src/renderer/lib/headlessRun.ts
index 752bf3876..29f4dbb83 100644
--- a/src/renderer/lib/headlessRun.ts
+++ b/src/renderer/lib/headlessRun.ts
@@ -33,7 +33,8 @@ export function planRunVerb(input: {
if (input.projectActive) {
if (input.hasWriter) return 'mounted'
// `after` is required by the type, but the launch comes out of hand-editable project JSON.
- const waitsOnDeps = (input.pending.after?.length ?? 0) > 0
+ // A pull request wait (`--after-pr`) is a dependency too: the mount does not fire it.
+ const waitsOnDeps = (input.pending.after?.length ?? 0) > 0 || !!input.pending.afterPr
return input.pending.manualOnly || waitsOnDeps ? 'refuse-not-mounted' : 'wait-for-mount'
}
return 'headless'
diff --git a/src/renderer/lib/pendingLaunch.test.ts b/src/renderer/lib/pendingLaunch.test.ts
index 60c89b688..f5b5a4854 100644
--- a/src/renderer/lib/pendingLaunch.test.ts
+++ b/src/renderer/lib/pendingLaunch.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect } from 'vitest'
+import type { PendingLaunch } from '@shared/types'
import {
launchesToFire,
queueControlLaunch,
@@ -7,6 +8,7 @@ import {
launchTooltip,
unmetDeps,
LAUNCH_STALL_MS,
+ withPrHold,
type ArmedNode,
type StatusById
} from './pendingLaunch'
@@ -337,3 +339,106 @@ it('a refused relay launch explains host recovery rather than promising a workin
expect(text).toContain('claude brief')
expect(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)
+ })
+})
diff --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.ts
index 051dc6f14..a75eb84a2 100644
--- a/src/renderer/lib/pendingLaunch.ts
+++ b/src/renderer/lib/pendingLaunch.ts
@@ -4,7 +4,10 @@
// dependency edges to draw meanwhile. Kept free of React/store imports so the satisfaction
// matrix is unit-testable — Canvas.tsx only wraps these in an effect and a setState.
import type { AgentState } from '@shared/agents/normalize'
+import type { GitHubPullBoard } from '@shared/github-pull-status'
+import type { PrWaitHold } from '@shared/pr-wait'
import type { PendingLaunch } from '@shared/types'
+import { prHoldSatisfied } from './prWait'
/** The subset of a canvas node this module reads. */
export interface ArmedNode {
@@ -23,6 +26,13 @@ export interface LaunchToFire {
command: string
}
+/** 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 } }>(
@@ -42,13 +52,30 @@ export function queueControlLaunch<T extends { data: { initialCommand?: string;
}
}
+/**
+ * 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 } } }
+}
+
/** 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 {
- 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 {
+ if (pending) return delivery?.kind ?? (prExpired ? 'expired' : 'queued')
if (status?.dropped) return 'dropped'
if (status?.state === 'working') return 'working'
return undefined
@@ -119,7 +146,8 @@ export function launchesToFire(
status: StatusById,
live: ReadonlySet<string>,
setupDone?: (groupId: string) => boolean,
- deliveries?: Record<string, LaunchDelivery | undefined>
+ deliveries?: Record<string, LaunchDelivery | undefined>,
+ pr?: PrGateContext
): LaunchToFire[] {
const out: LaunchToFire[] = []
for (const n of nodes) {
@@ -131,6 +159,10 @@ export function launchesToFire(
// caught up with the claim yet while the store already says so.
if (deliveries?.[n.id]?.kind === 'starting') continue
if (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 })
}
return out
@@ -201,7 +233,10 @@ export function launchTooltip(
waitingOn: string,
command: string,
erroredOn?: string,
- relay = false
+ relay = false,
+ /** The node's `--after-pr` wait: what is still unmet (`prHoldSummary`), whether it has passed
+ * its deadline, and that deadline as the caller formats it (a locale string is not pure). */
+ pr?: { expired: boolean; summary: string; deadline: string }
): string {
if (delivery?.kind === 'starting') return 'Starting in the background — an agent asked for this session to run now.'
const runs = `Runs:\n${command}`
@@ -220,12 +255,24 @@ export function launchTooltip(
'what it did not produce.\n' +
`Retry or nudge it — a successful turn releases this — or press ▶ to run it now.\n${runs}`
)
+ // A wait that passed its deadline will not end on its own either — the one other case where
+ // "waiting for" would be a promise nobody keeps.
+ if (pr?.expired)
+ return (
+ `The wait on pull requests passed its deadline (${pr.deadline}), so this will not start on ` +
+ 'its own.\n' +
+ `Press \u25b6 to run it now.\n${runs}`
+ )
if (delivery?.kind === 'stalled')
return (
'Ready to run, but this terminal has not started yet — the launch is still held and ' +
'fires as soon as it does.\n' +
`Press \u25b6 to try it now.\n${runs}`
)
+ if (pr?.summary) {
+ const stations = waitingOn ? `${waitingOn} to finish and for ` : ''
+ return `Waiting for ${stations}${pr.summary}, until ${pr.deadline}, then runs:\n${command}`
+ }
return waitingOn
? `Waiting for ${waitingOn} to finish, then runs:\n${command}`
: `Queued; waiting for launch delivery.\n${runs}`
diff --git a/src/renderer/lib/prWait.test.ts b/src/renderer/lib/prWait.test.ts
new file mode 100644
index 000000000..46fcadc6f
--- /dev/null
+++ b/src/renderer/lib/prWait.test.ts
@@ -0,0 +1,256 @@
+import { describe, expect, it, vi } from 'vitest'
+import { EMPTY_PULL_BOARD, type GitHubPullBoard, type GitHubPullStatus } from '@shared/github-pull-status'
+import { INVALID_PR_WAIT_HOLD, type PrWaitHold } from '@shared/pr-wait'
+import {
+ evaluatePrWait,
+ prHoldExpired,
+ prHoldSatisfied,
+ prHoldSummary,
+ resolvePrWaitFor,
+ type PrLookup,
+ type PrWaitArmDeps
+} from './prWait'
+
+const NOW = 1_000_000
+const hold = (waits: PrWaitHold['waits'], deadlineAt = NOW + 3_600_000): PrWaitHold => ({
+ repository: 'o/r',
+ waits,
+ deadlineAt
+})
+const pull = (number: number, patch: Partial<GitHubPullStatus> = {}): GitHubPullStatus => ({
+ number,
+ lifecycle: 'open',
+ headRefName: 'b',
+ headRefOid: 'abc',
+ closes: [],
+ ...patch
+})
+const board = (pulls: GitHubPullStatus[], patch: Partial<GitHubPullBoard> = {}): GitHubPullBoard => ({
+ ...EMPTY_PULL_BOARD,
+ repository: 'o/r',
+ pulls,
+ observedAt: NOW - 1000,
+ ...patch
+})
+
+describe('evaluatePrWait — merged', () => {
+ const w = { number: 7, until: 'merged' as const }
+ it('is met by a merged PR, even from a stale snapshot (a merge cannot be undone)', () => {
+ expect(evaluatePrWait(w, hold([w]), board([pull(7, { lifecycle: 'merged' })])).state).toBe('met')
+ expect(evaluatePrWait(w, hold([w]), board([pull(7, { lifecycle: 'merged' })], { stale: true })).state).toBe('met')
+ })
+ it('waits on an open or draft PR', () => {
+ expect(evaluatePrWait(w, hold([w]), board([pull(7)])).state).toBe('waiting')
+ expect(evaluatePrWait(w, hold([w]), board([pull(7, { lifecycle: 'draft' })])).state).toBe('waiting')
+ })
+ it('is blocked (named) by a PR closed without merging — a reopen would release it again', () => {
+ const r = evaluatePrWait(w, hold([w]), board([pull(7, { lifecycle: 'closed' })]))
+ expect(r.state).toBe('blocked')
+ expect(r.detail).toMatch(/closed without merging/)
+ })
+})
+
+describe('evaluatePrWait — checks (SUCCESS at the PR’s current head)', () => {
+ const w = { number: 7, until: 'checks' as const }
+ const h = hold([w])
+ it('is met by passed checks on a fresh board', () => {
+ expect(evaluatePrWait(w, h, board([pull(7, { ci: 'passed' })])).state).toBe('met')
+ expect(evaluatePrWait(w, h, board([pull(7, { ci: 'passed', lifecycle: 'draft' })])).state).toBe('met')
+ })
+ it('does NOT trust a stale snapshot: a push since the last read would carry other checks', () => {
+ expect(evaluatePrWait(w, h, board([pull(7, { ci: 'passed' })], { stale: true })).state).toBe('unknown')
+ })
+ it('waits while checks run, after they fail (a re-run or push can still pass), and with none reported', () => {
+ for (const ci of ['pending', 'failed', 'none'] as const) {
+ expect(evaluatePrWait(w, h, board([pull(7, { ci })])).state).toBe('waiting')
+ }
+ })
+ it('a missing rollup is never "passed" — no checks is not green', () => {
+ expect(evaluatePrWait(w, h, board([pull(7, { ci: 'none' })])).detail).toMatch(/no checks/)
+ })
+ it('an unknown ci (the host has not said) is unknown, not met', () => {
+ expect(evaluatePrWait(w, h, board([pull(7)])).state).toBe('unknown')
+ })
+ it('is blocked when the token cannot read checks at all', () => {
+ const r = evaluatePrWait(w, h, board([pull(7, { ci: 'passed' })], { access: { ci: false, merge: true } }))
+ expect(r.state).toBe('blocked')
+ expect(r.detail).toMatch(/cannot read checks/)
+ })
+ it('is blocked by a PR that merged before its checks were seen passing', () => {
+ expect(evaluatePrWait(w, h, board([pull(7, { lifecycle: 'merged' })])).state).toBe('blocked')
+ })
+})
+
+describe('evaluatePrWait — what the board does not know', () => {
+ const w = { number: 7, until: 'merged' as const }
+ it('no board yet is unknown', () => {
+ expect(evaluatePrWait(w, hold([w]), undefined).state).toBe('unknown')
+ })
+ it('a PR the board does not list is unknown, and a truncated board says why', () => {
+ expect(evaluatePrWait(w, hold([w]), board([])).state).toBe('unknown')
+ expect(evaluatePrWait(w, hold([w]), board([], { truncated: true })).detail).toMatch(/more open pull requests/)
+ })
+ it('a board that now syncs ANOTHER repository cannot satisfy the hold', () => {
+ const r = evaluatePrWait(w, hold([w]), board([pull(7, { lifecycle: 'merged' })], { repository: 'o/other' }))
+ expect(r.state).toBe('blocked')
+ })
+ it('compares repositories case-insensitively, as GitHub does', () => {
+ const r = evaluatePrWait(w, hold([w]), board([pull(7, { lifecycle: 'merged' })], { repository: 'O/R' }))
+ expect(r.state).toBe('met')
+ })
+})
+
+describe('prHoldSatisfied / prHoldExpired', () => {
+ const a = { number: 7, until: 'merged' as const }
+ const b = { number: 8, until: 'checks' as const }
+ const both = board([pull(7, { lifecycle: 'merged' }), pull(8, { ci: 'passed' })])
+ it('needs EVERY wait met', () => {
+ expect(prHoldSatisfied(hold([a, b]), both, NOW)).toBe(true)
+ expect(prHoldSatisfied(hold([a, b]), board([pull(7, { lifecycle: 'merged' }), pull(8, { ci: 'pending' })]), NOW)).toBe(false)
+ })
+ it('never fires past the deadline, however green the PR is', () => {
+ expect(prHoldExpired(hold([a], NOW), NOW)).toBe(true)
+ expect(prHoldSatisfied(hold([a], NOW), both, NOW)).toBe(false)
+ expect(prHoldExpired(hold([a], NOW + 1), NOW)).toBe(false)
+ })
+ it('an invalid (hostile or corrupt) hold is expired and never satisfied', () => {
+ expect(prHoldExpired(INVALID_PR_WAIT_HOLD, NOW)).toBe(true)
+ expect(prHoldSatisfied(INVALID_PR_WAIT_HOLD, both, NOW)).toBe(false)
+ })
+})
+
+describe('prHoldSummary', () => {
+ it('says, per pull request, what is still being waited for', () => {
+ const s = prHoldSummary(
+ hold([{ number: 7, until: 'merged' }, { number: 8, until: 'checks' }]),
+ board([pull(7), pull(8, { ci: 'pending' })])
+ )
+ expect(s).toMatch(/PR #7 merged/)
+ expect(s).toMatch(/PR #8 checks/)
+ expect(s).toMatch(/running/)
+ })
+})
+
+// ── Arming: what an open with --after-pr is allowed to store ──────────────────────────────────
+
+function deps(patch: Partial<PrWaitArmDeps> = {}): PrWaitArmDeps {
+ return {
+ project: { id: 'p1', cwd: '/w', kanban: { github: { repository: 'o/r' } } },
+ controlStatus: vi.fn(async () => ({ repository: 'o/r', approved: true })),
+ lookupPulls: vi.fn(async (_id: string, numbers: number[]) =>
+ new Map<number, PrLookup>(numbers.map((n) => [n, { found: true, lifecycle: 'open' }]))
+ ),
+ now: () => NOW,
+ ...patch
+ }
+}
+
+describe('resolvePrWaitFor — the refusal matrix', () => {
+ it('no flag, nothing to do (and nothing is asked)', async () => {
+ const d = deps()
+ expect(await resolvePrWaitFor(undefined, undefined, 'open-agent', d)).toEqual({ ok: true, alreadyMerged: [] })
+ expect(d.controlStatus).not.toHaveBeenCalled()
+ })
+
+ it('stores a hold on the board repository with the deadline on this clock', async () => {
+ const r = await resolvePrWaitFor('7:checks', '2h', 'open-agent', deps())
+ expect(r).toEqual({
+ ok: true,
+ hold: { repository: 'o/r', waits: [{ number: 7, until: 'checks' }], deadlineAt: NOW + 2 * 3_600_000 },
+ alreadyMerged: []
+ })
+ })
+
+ it('a relay tab is refused by name', async () => {
+ const r = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({ project: { id: 'p', remote: true } }))
+ expect(r).toMatchObject({ ok: false })
+ if (!r.ok) expect(r.error).toMatch(/^after-pr-unavailable: .*relay/)
+ })
+
+ it('a project whose board has no GitHub sync is refused by name — and a cwd-less one says why', async () => {
+ const plain = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({ project: { id: 'p', cwd: '/w' } }))
+ expect(!plain.ok && plain.error).toMatch(/^after-pr-unavailable: this project's kanban board is not connected to GitHub/)
+ const cwdless = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({ project: { id: 'p' } }))
+ expect(!cwdless.ok && cwdless.error).toMatch(/no folder/)
+ })
+
+ it('an SSH project with a GitHub board is NOT refused — the PR status is read on this machine', async () => {
+ const r = await resolvePrWaitFor(
+ '7:merged',
+ undefined,
+ 'open-agent',
+ deps({ project: { id: 'p', ssh: { host: 'h' }, kanban: { github: {} } } })
+ )
+ expect(r.ok).toBe(true)
+ })
+
+ it('a board with no repository, or an unapproved one, is refused by name', async () => {
+ const none = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({
+ controlStatus: vi.fn(async () => ({ approved: false }))
+ }))
+ expect(!none.ok && none.error).toMatch(/names no GitHub repository/)
+ const unapproved = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({
+ controlStatus: vi.fn(async () => ({ repository: 'o/r', approved: false }))
+ }))
+ expect(!unapproved.ok && unapproved.error).toMatch(/not approved on this machine/)
+ const threw = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({
+ controlStatus: vi.fn(async () => { throw new Error('boom') })
+ }))
+ expect(!threw.ok && threw.error).toMatch(/^after-pr-unavailable:/)
+ })
+
+ it('refuses a full reference into another repository', async () => {
+ const r = await resolvePrWaitFor('x/y#7:merged', undefined, 'open-agent', deps())
+ expect(!r.ok && r.error).toMatch(/^after-pr-other-repository: x\/y#7/)
+ // The same repository in another case is the same repository.
+ expect((await resolvePrWaitFor('O/R#7:merged', undefined, 'open-agent', deps())).ok).toBe(true)
+ })
+
+ it('refuses a number the repository does not have', async () => {
+ const r = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({
+ lookupPulls: vi.fn(async () => new Map<number, PrLookup>([[7, { found: false, complete: true }]]))
+ }))
+ expect(!r.ok && r.error).toMatch(/^after-pr-unknown: o\/r has no pull request #7/)
+ })
+
+ it('does not call an incomplete read evidence of absence — a retryable refusal instead', async () => {
+ const r = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({
+ lookupPulls: vi.fn(async () => new Map<number, PrLookup>([[7, { found: false, complete: false }]]))
+ }))
+ expect(!r.ok && r.error).toMatch(/^after-pr-unconfirmed:.*retry/)
+ const threw = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({
+ lookupPulls: vi.fn(async () => { throw new Error('offline') })
+ }))
+ expect(!threw.ok && threw.error).toMatch(/^after-pr-unconfirmed:/)
+ })
+
+ it('refuses a closed-unmerged PR, and checks on a merged one', async () => {
+ const closed = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({
+ lookupPulls: vi.fn(async () => new Map<number, PrLookup>([[7, { found: true, lifecycle: 'closed' }]]))
+ }))
+ expect(!closed.ok && closed.error).toMatch(/^after-pr-closed:/)
+ const merged = await resolvePrWaitFor('7:checks', undefined, 'open-agent', deps({
+ lookupPulls: vi.fn(async () => new Map<number, PrLookup>([[7, { found: true, lifecycle: 'merged' }]]))
+ }))
+ expect(!merged.ok && merged.error).toMatch(/^after-pr-merged:/)
+ })
+
+ it('a :merged wait on an already-merged PR is met now, reported, and not stored', async () => {
+ const r = await resolvePrWaitFor('7:merged,8:checks', undefined, 'open-agent', deps({
+ lookupPulls: vi.fn(async () => new Map<number, PrLookup>([
+ [7, { found: true, lifecycle: 'merged' }],
+ [8, { found: true, lifecycle: 'open' }]
+ ]))
+ }))
+ expect(r).toMatchObject({ ok: true, alreadyMerged: [7], hold: { waits: [{ number: 8, until: 'checks' }] } })
+ const all = await resolvePrWaitFor('7:merged', undefined, 'open-agent', deps({
+ lookupPulls: vi.fn(async () => new Map<number, PrLookup>([[7, { found: true, lifecycle: 'merged' }]]))
+ }))
+ expect(all).toEqual({ ok: true, alreadyMerged: [7] })
+ })
+
+ it('re-parses the flag: the renderer never trusts that main’s gate ran', async () => {
+ const r = await resolvePrWaitFor('7', undefined, 'open-agent', deps())
+ expect(!r.ok && r.error).toMatch(/^open-agent: --after-pr must be/)
+ })
+})
diff --git a/src/renderer/lib/prWait.ts b/src/renderer/lib/prWait.ts
new file mode 100644
index 000000000..104e306e4
--- /dev/null
+++ b/src/renderer/lib/prWait.ts
@@ -0,0 +1,246 @@
+// When an armed node's `--after-pr` wait is SATISFIED, and what an open may store — pure, beside
+// `pendingLaunch.ts`, which ANDs it with the `--after` and setup gates.
+//
+// The data is the pull request status #1008 already keeps (`GitHubPullBoard`, from the host's
+// memory, fed by the conditional heartbeat and the rate budget): this module never reads GitHub and
+// adds no poller. Its rules are #1008's, not new ones:
+// - `checks` = the rollup is SUCCESS at the PR's CURRENT head (`ci === 'passed'`, which
+// `pullStatusFrom` only reports for a rollup taken at the head commit). A missing rollup means
+// "no checks", which is never "passed": a PR with no CI would otherwise release its dependent
+// the moment it is opened, before any check has even been queued. The deadline is the way out.
+// - `merged` = merged. A merge cannot be undone, so a stale snapshot that says so is still true;
+// a stale snapshot that says "passed" is not (a push since the last read carries other checks).
+// - Unknown is never satisfied — no board yet, a PR the board does not list, a read that failed.
+//
+// The two safety rails beside those: a DEADLINE (past it the node never starts on its own; the
+// QUEUED badge reads EXPIRED and ▶ still runs it) and the existing exactly-once delivery
+// (`launchInFlight` + clearing `pendingLaunch`), which a PR wait does not change.
+
+import type { GitHubPullBoard, PullLifecycle } from '@shared/github-pull-status'
+import {
+ formatPrWaits,
+ parseAfterPrArg,
+ parsePrDeadlineArg,
+ type PrWait,
+ type PrWaitHold
+} from '@shared/pr-wait'
+
+export type PrWaitState = 'met' | 'waiting' | 'unknown' | 'blocked'
+
+export interface PrWaitReport {
+ number: number
+ until: PrWait['until']
+ state: PrWaitState
+ /** Short, human: what is true about this PR right now. Never a cause nobody measured. */
+ detail: string
+}
+
+const sameRepository = (a: string | undefined, b: string): boolean =>
+ !!a && a.toLowerCase() === b.toLowerCase()
+
+export function evaluatePrWait(
+ wait: PrWait,
+ hold: PrWaitHold,
+ board: GitHubPullBoard | undefined
+): PrWaitReport {
+ const report = (state: PrWaitState, detail: string): PrWaitReport => ({
+ number: wait.number,
+ until: wait.until,
+ state,
+ detail
+ })
+ if (!board) return report('unknown', 'status not loaded yet')
+ if (!board.repository) return report('unknown', 'status not loaded yet')
+ if (!sameRepository(board.repository, hold.repository)) {
+ return report('blocked', `the board now syncs ${board.repository}, not ${hold.repository}`)
+ }
+ const pull = board.pulls.find((p) => p.number === wait.number)
+ if (!pull) {
+ return report(
+ 'unknown',
+ board.truncated
+ ? 'not tracked — the repository has more open pull requests than one status read covers'
+ : 'not in the status read yet'
+ )
+ }
+ if (pull.lifecycle === 'closed') return report('blocked', 'closed without merging')
+ if (wait.until === 'merged') {
+ if (pull.lifecycle === 'merged') return report('met', 'merged')
+ return report('waiting', pull.lifecycle === 'draft' ? 'draft, not merged' : 'open, not merged')
+ }
+ // checks
+ if (pull.lifecycle === 'merged') return report('blocked', 'merged before its checks were seen passing')
+ if (!board.access.ci) return report('blocked', "this machine's GitHub token cannot read checks")
+ switch (pull.ci) {
+ case 'passed':
+ return board.stale
+ ? report('unknown', 'passed at the last read, but the latest status read failed')
+ : report('met', 'checks passed')
+ case 'pending':
+ return report('waiting', 'checks running')
+ case 'failed':
+ return report('waiting', 'checks failed')
+ case 'none':
+ return report('waiting', 'no checks reported yet')
+ default:
+ return report('unknown', 'check status not known yet')
+ }
+}
+
+/** An invalid hold (read from a corrupt or hostile file) is already past its deadline. */
+export function prHoldExpired(hold: PrWaitHold, now: number): boolean {
+ return !!hold.invalid || now >= hold.deadlineAt
+}
+
+export function prHoldReports(hold: PrWaitHold, board: GitHubPullBoard | undefined): PrWaitReport[] {
+ return hold.waits.map((w) => evaluatePrWait(w, hold, board))
+}
+
+/** EVERY wait met, and the deadline not passed. */
+export function prHoldSatisfied(
+ hold: PrWaitHold,
+ board: GitHubPullBoard | undefined,
+ now: number
+): boolean {
+ if (prHoldExpired(hold, now) || hold.waits.length === 0) return false
+ return prHoldReports(hold, board).every((r) => r.state === 'met')
+}
+
+/** "PR #7 merged (open, not merged); PR #8 checks (checks running)" — the unmet waits only. */
+export function prHoldSummary(hold: PrWaitHold, board: GitHubPullBoard | undefined): string {
+ return prHoldReports(hold, board)
+ .filter((r) => r.state !== 'met')
+ .map((r) => `PR #${r.number} ${r.until} (${r.detail})`)
+ .join('; ')
+}
+
+// ── Arming ────────────────────────────────────────────────────────────────────────────────────
+
+/** What the harvested issue list (the board's REST snapshot, #1008) knows about one number. */
+export type PrLookup =
+ | { found: true; lifecycle: PullLifecycle }
+ /** `complete` = the snapshot is whole, so "not found" is an answer, not a gap. */
+ | { found: false; complete: boolean }
+
+export interface PrWaitArmDeps {
+ /** The project the node OPENS in (the one `issuePre` resolves against). */
+ project:
+ | { id: string; remote?: boolean; ssh?: unknown; cwd?: string; kanban?: { github?: unknown } }
+ | undefined
+ /** The GitHub host controller's answer for that project (configured, else detected). */
+ controlStatus(projectId: string): Promise<{ repository?: string; approved: boolean } | null>
+ lookupPulls(projectId: string, numbers: number[]): Promise<Map<number, PrLookup>>
+ now(): number
+}
+
+export type PrWaitArmResult =
+ | { ok: true; hold?: PrWaitHold; alreadyMerged: number[] }
+ | { ok: false; error: string }
+
+/**
+ * What an open carrying `--after-pr` stores, or the refusal it gets. Every refusal names its
+ * reason; the `after-pr-unconfirmed` one is the only retryable one (a read that has not finished is
+ * never evidence that a pull request does not exist).
+ *
+ * An SSH project is NOT refused on its own account: its board's pull request status is read by
+ * this machine's GitHub client, like any other board. What is refused is a project whose board has
+ * no GitHub sync — which is where a cwd-less project lands, and says so — and a relay tab, whose
+ * canvas (and armed nodes) belong to the host.
+ */
+export async function resolvePrWaitFor(
+ raw: string | undefined,
+ deadlineRaw: string | undefined,
+ verb: string,
+ deps: PrWaitArmDeps
+): Promise<PrWaitArmResult> {
+ if (raw === undefined) return { ok: true, alreadyMerged: [] }
+ const parsed = parseAfterPrArg(raw)
+ if (!parsed.ok) return { ok: false, error: `${verb}: ${parsed.error}` }
+ const deadline = parsePrDeadlineArg(deadlineRaw)
+ if (!deadline.ok) return { ok: false, error: `${verb}: ${deadline.error}` }
+ const unavailable = (why: string): PrWaitArmResult => ({
+ ok: false,
+ error: `after-pr-unavailable: ${why} — do not retry`
+ })
+ const project = deps.project
+ if (!project) return unavailable('the project this node opens in is not open here')
+ if (project.remote) {
+ return unavailable('this is a relay tab; pull request waits run on the host that owns the project')
+ }
+ if (!project.kanban?.github) {
+ return unavailable(
+ "this project's kanban board is not connected to GitHub" +
+ (!project.cwd && !project.ssh ? ' (a project with no folder has no repository to detect)' : '')
+ )
+ }
+ let control: { repository?: string; approved: boolean } | null
+ try {
+ control = await deps.controlStatus(project.id)
+ } catch (error) {
+ return unavailable(`could not read this project's GitHub setup (${error instanceof Error ? error.message : 'error'})`)
+ }
+ const repository = control?.repository
+ if (!repository) return unavailable("this project's kanban board names no GitHub repository")
+ if (!control?.approved) {
+ return unavailable(`GitHub sync for ${repository} is not approved on this machine (Settings → GitHub)`)
+ }
+ for (const spec of parsed.specs) {
+ if (spec.repository && !sameRepository(spec.repository, repository)) {
+ return {
+ ok: false,
+ error:
+ `after-pr-other-repository: ${spec.repository}#${spec.number} is not in ${repository}, the ` +
+ "repository this project's board syncs with — a wait can only name that repository's pull requests"
+ }
+ }
+ }
+ let lookups: Map<number, PrLookup>
+ try {
+ lookups = await deps.lookupPulls(project.id, parsed.specs.map((s) => s.number))
+ } catch {
+ lookups = new Map()
+ }
+ const waits: PrWait[] = []
+ const alreadyMerged: number[] = []
+ for (const spec of parsed.specs) {
+ const found = lookups.get(spec.number)
+ if (!found || !found.found) {
+ if (found && found.complete) {
+ return { ok: false, error: `after-pr-unknown: ${repository} has no pull request #${spec.number} — do not retry` }
+ }
+ return {
+ ok: false,
+ error:
+ `after-pr-unconfirmed: could not confirm that ${repository} has pull request #${spec.number} ` +
+ '(GitHub sync has not finished reading it) — retry in a minute'
+ }
+ }
+ if (found.lifecycle === 'closed') {
+ return { ok: false, error: `after-pr-closed: ${repository}#${spec.number} is closed without merging — do not retry` }
+ }
+ if (found.lifecycle === 'merged') {
+ if (spec.until === 'checks') {
+ return {
+ ok: false,
+ error:
+ `after-pr-merged: ${repository}#${spec.number} is already merged, so its checks are no longer ` +
+ 'tracked — a :merged wait on it is already met'
+ }
+ }
+ alreadyMerged.push(spec.number)
+ continue
+ }
+ waits.push({ number: spec.number, until: spec.until })
+ }
+ if (!waits.length) return { ok: true, alreadyMerged }
+ return {
+ ok: true,
+ hold: { repository, waits, deadlineAt: deps.now() + deadline.ms },
+ alreadyMerged
+ }
+}
+
+/** The reply line for an armed PR wait. */
+export function prWaitReplyLine(hold: PrWaitHold): string {
+ return `waiting for ${formatPrWaits(hold)} in ${hold.repository} (until ${new Date(hold.deadlineAt).toISOString()})`
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index d33dcd434..76d6486d0 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -220,6 +220,8 @@ import { codexApprovalCaps } from '../state/codexCli'
import { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'
import { useLaunchDelivery } from '../state/launchDelivery'
import { erroredDeps, launchTooltip } from '../lib/pendingLaunch'
+import { prHoldExpired, prHoldSummary } from '../lib/prWait'
+import { pullBoardFor, useGitHubIssues } from '../state/githubIssues'
import type { AgentState } from '@shared/agents/normalize'
import type { ClientId } from '@shared/presence'
import { PresenceChips } from '../components/PresenceChips'
@@ -2025,7 +2027,8 @@ export function TerminalNode({
!!data.initialCommand &&
!observedLaunchDelivery &&
!(pendingLaunch?.after?.length) &&
- !pendingLaunch?.awaitSetupGroup
+ !pendingLaunch?.awaitSetupGroup &&
+ !pendingLaunch?.afterPr
const pendingWaitingOn = [
...(pendingLaunch?.after ?? []).map(
(depId) => ((getNode(depId) as CanvasNode | undefined)?.data.title as string) || depId
@@ -2046,6 +2049,28 @@ export function TerminalNode({
const live = new Set(after.filter((d) => !!getNode(d)))
return erroredDeps({ id, data: { pendingLaunch } }, s.byId, live).join(',')
})
+ // `--after-pr`: what the pull requests this node waits on look like, from the same status the
+ // launch loop judges (the canvas's watch keeps it coming). Selected only for a node that has a
+ // PR wait, so no other node re-renders on a GitHub update.
+ const prHold = pendingLaunch?.afterPr
+ const prProjectId = useProjects((s) => (prHold ? s.activeProjectId : null))
+ const prBoard = useGitHubIssues((s) => (prHold && prProjectId ? pullBoardFor(s, prProjectId) : undefined))
+ // Nothing in any store changes when a deadline passes, so the badge sets its own timer to turn
+ // EXPIRED on time (one per armed node, cleared with it).
+ const [, setPrClock] = useState(0)
+ useEffect(() => {
+ if (!prHold || prHoldExpired(prHold, Date.now())) return
+ const t = setTimeout(() => setPrClock((v) => v + 1), Math.min(prHold.deadlineAt - Date.now() + 50, 2 ** 31 - 1))
+ return () => clearTimeout(t)
+ }, [prHold])
+ const prExpired = !!prHold && prHoldExpired(prHold, Date.now())
+ const prTooltip = prHold
+ ? {
+ expired: prExpired,
+ summary: prHold.invalid ? 'a pull request wait that could not be read' : prHoldSummary(prHold, prBoard),
+ deadline: prHold.invalid ? 'the project file holds an unreadable one' : new Date(prHold.deadlineAt).toLocaleString()
+ }
+ : undefined
const pendingErroredOn = erroredDepIds
? erroredDepIds
.split(',')
@@ -5837,12 +5862,12 @@ export function TerminalNode({
{pendingLaunch && !firstOpenInFlight && (
<span
className={`term-node__status term-node__status--queued nodrag${
- launchDelivery && !startingNow ? ' term-node__status--queued-warn' : ''
+ (launchDelivery || prExpired) && !startingNow ? ' term-node__status--queued-warn' : ''
}`}
- title={launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay')}
+ title={launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay', prTooltip)}
>
<span className="term-node__status-dot" />
- {startingNow ? 'STARTING' : `${launchDelivery ? '⚠ ' : ''}QUEUED`}
+ {startingNow ? 'STARTING' : launchDelivery ? '⚠ QUEUED' : prExpired ? '⚠ EXPIRED' : 'QUEUED'}
<button
className="term-node__queued-run"
disabled={session.source === 'relay' || startingNow}
diff --git a/src/renderer/nodes/session-ready-signal.test.ts b/src/renderer/nodes/session-ready-signal.test.ts
index 982bba14b..416237681 100644
--- a/src/renderer/nodes/session-ready-signal.test.ts
+++ b/src/renderer/nodes/session-ready-signal.test.ts
@@ -98,17 +98,18 @@ describe('the QUEUED badge carries the delivery state (source pins)', () => {
expect(src).toContain('term-node__status--queued-warn')
// `pendingErroredOn` is the fourth argument since #521 — an errored upstream is idle, so
// without it the tooltip would promise a wait that never ends. The relay flag also
- // keeps unsupported queued delivery from promising a working Run now action.
+ // keeps unsupported queued delivery from promising a working Run now action, and the last
+ // argument names an `--after-pr` wait (and its deadline) beside the stations.
expect(src).toContain(
- "launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay')"
+ "launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay', prTooltip)"
)
})
it('a background start reads STARTING, without the warning, and disables ▶ (#925)', () => {
// Core is typing the launch into this pane; a ▶ click would splice a second copy into it.
expect(src).toContain("const startingNow = launchDelivery?.kind === 'starting'")
- expect(src).toContain("launchDelivery && !startingNow ? ' term-node__status--queued-warn' : ''")
- expect(src).toContain("{startingNow ? 'STARTING' : `${launchDelivery ? '⚠ ' : ''}QUEUED`}")
+ expect(src).toContain("(launchDelivery || prExpired) && !startingNow ? ' term-node__status--queued-warn' : ''")
+ expect(src).toContain("{startingNow ? 'STARTING' : launchDelivery ? '⚠ QUEUED' : prExpired ? '⚠ EXPIRED' : 'QUEUED'}")
expect(src).toContain("disabled={session.source === 'relay' || startingNow}")
})
diff --git a/src/renderer/state/githubIssues.test.ts b/src/renderer/state/githubIssues.test.ts
index 3c59db542..b5176df7e 100644
--- a/src/renderer/state/githubIssues.test.ts
+++ b/src/renderer/state/githubIssues.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { GitHubIssuesApi } from '@shared/github-issues'
-import { useGitHubIssues } from './githubIssues'
+import { lookupPullRequests, pullBoardFor, useGitHubIssues } from './githubIssues'
const page = (number: number, columnId: string | null, nextCursor?: string) => ({
items: [{
@@ -44,7 +44,7 @@ function api(): GitHubIssuesApi {
}
}
-beforeEach(() => useGitHubIssues.setState({ projects: {} }))
+beforeEach(() => useGitHubIssues.setState({ projects: {}, pullWatch: {} }))
describe('GitHub issue renderer state', () => {
it('lets only the newest overlapping connection publish or tear down project state', async () => {
@@ -242,3 +242,94 @@ describe('GitHub issue renderer state', () => {
disconnect()
})
})
+
+describe('the PR watch an armed --after-pr node keeps (no board open)', () => {
+ const pullBoard = (n: number) => ({
+ repository: 'o/r', now: n, pulls: [], stale: false, access: { ci: true, merge: true }, undecided: false, truncated: false
+ })
+
+ it('reads the host board, re-reads on every change, and shares the board’s host subscription', async () => {
+ const client = api()
+ let fire: (() => void) | undefined
+ vi.mocked(client.onChanged).mockImplementation((_p, listener) => {
+ fire = () => listener([])
+ return () => { fire = undefined }
+ })
+ vi.mocked(client.pullStatus).mockResolvedValueOnce(pullBoard(1)).mockResolvedValueOnce(pullBoard(2))
+ useGitHubIssues.setState({ projects: {}, pullWatch: {} })
+ const release = await useGitHubIssues.getState().watchPulls(client, 'p1')
+ expect(pullBoardFor(useGitHubIssues.getState(), 'p1')?.now).toBe(1)
+ fire?.()
+ await vi.waitFor(() => expect(pullBoardFor(useGitHubIssues.getState(), 'p1')?.now).toBe(2))
+ // A second watcher and a board connection ride the SAME host subscription.
+ const again = await useGitHubIssues.getState().watchPulls(client, 'p1')
+ const disconnect = await useGitHubIssues.getState().connect(client, 'p1', ['todo'])
+ expect(client.subscribe).toHaveBeenCalledTimes(1)
+ release()
+ again()
+ expect(client.unsubscribe).not.toHaveBeenCalled()
+ expect(useGitHubIssues.getState().pullWatch.p1).toBeUndefined()
+ disconnect()
+ expect(client.unsubscribe).toHaveBeenCalledTimes(1)
+ })
+
+ it('pullBoardFor prefers the newer of the watch and the open board', () => {
+ const state = {
+ projects: { p1: { pullBoard: pullBoard(5) } },
+ pullWatch: { p1: pullBoard(3) }
+ } as never
+ expect(pullBoardFor(state, 'p1')?.now).toBe(5)
+ expect(pullBoardFor({ projects: {}, pullWatch: { p1: pullBoard(3) } } as never, 'p1')?.now).toBe(3)
+ expect(pullBoardFor({ projects: {}, pullWatch: {} } as never, 'p1')).toBeUndefined()
+ })
+})
+
+describe('lookupPullRequests — does the board repository have these pull requests?', () => {
+ const item = (number: number, patch: Record<string, unknown> = {}) => ({
+ ...pullPage(number, null).items[0],
+ ...patch
+ })
+ const pg = (items: unknown[], extra: Record<string, unknown> = {}) => ({
+ items, counts: {}, partial: false, readOnly: true, lastSuccessfulRefreshAt: 1, ...extra
+ })
+
+ it('finds a PR in any column, following pages, and reads its lifecycle', async () => {
+ const client = api()
+ vi.mocked(client.query).mockImplementation(async (request) => {
+ if (request.columnId === 'done' && !request.cursor) return pg([item(17)], { nextCursor: '50' }) as never
+ if (request.columnId === 'done' && request.cursor === '50') {
+ return pg([item(7, { state: 'closed', pull: { draft: false, mergedAt: '2026-09-01T00:00:00Z' } })]) as never
+ }
+ return pg([]) as never
+ })
+ const found = await lookupPullRequests(client, 'p1', ['todo', 'done'], [7])
+ expect(found.get(7)).toEqual({ found: true, lifecycle: 'merged' })
+ expect(client.subscribe).toHaveBeenCalledTimes(1)
+ expect(client.unsubscribe).toHaveBeenCalledTimes(1)
+ })
+
+ it('reads open, draft and closed-unmerged too', async () => {
+ const client = api()
+ vi.mocked(client.query).mockResolvedValue(pg([
+ item(1),
+ item(2, { pull: { draft: true, mergedAt: null } }),
+ item(3, { state: 'closed', pull: { draft: false, mergedAt: null } })
+ ]) as never)
+ const found = await lookupPullRequests(client, 'p1', [], [1, 2, 3])
+ expect([1, 2, 3].map((n) => found.get(n))).toEqual([
+ { found: true, lifecycle: 'open' },
+ { found: true, lifecycle: 'draft' },
+ { found: true, lifecycle: 'closed' }
+ ])
+ })
+
+ it('only a whole, refreshed snapshot makes "not found" an answer', async () => {
+ const client = api()
+ vi.mocked(client.query).mockResolvedValue(pg([]) as never)
+ expect((await lookupPullRequests(client, 'p1', [], [9])).get(9)).toEqual({ found: false, complete: true })
+ vi.mocked(client.query).mockResolvedValue(pg([], { partial: true }) as never)
+ expect((await lookupPullRequests(client, 'p1', [], [9])).get(9)).toEqual({ found: false, complete: false })
+ vi.mocked(client.query).mockResolvedValue(pg([], { lastSuccessfulRefreshAt: undefined }) as never)
+ expect((await lookupPullRequests(client, 'p1', [], [9])).get(9)).toEqual({ found: false, complete: false })
+ })
+})
diff --git a/src/renderer/state/githubIssues.ts b/src/renderer/state/githubIssues.ts
index fb73a6f5d..81d411e18 100644
--- a/src/renderer/state/githubIssues.ts
+++ b/src/renderer/state/githubIssues.ts
@@ -6,8 +6,9 @@ import type {
GitHubIssuesApi,
GitHubMutationResult
} from '@shared/github-issues'
-import type { GitHubPullBoard } from '@shared/github-pull-status'
+import type { GitHubPullBoard, PullLifecycle } from '@shared/github-pull-status'
import { GITHUB_MAPPING_NOT_APPROVED } from '../lib/githubSyncStatus'
+import type { PrLookup } from '../lib/prWait'
export interface GitHubProjectPages {
pages: Record<string, GitHubIssuePage>
@@ -29,6 +30,12 @@ export interface GitHubProjectPages {
interface GitHubIssuesState {
projects: Record<string, GitHubProjectPages>
+ /** Pull request status kept for armed `--after-pr` nodes, whether or not a board is open. The
+ * SAME host memory the board reads (`pullStatus`, no request), refreshed on the same change
+ * events, and it rides the board's refcounted host subscription — the existing 60 s conditional
+ * heartbeat, not a poller of its own. */
+ pullWatch: Record<string, GitHubPullBoard>
+ watchPulls(api: GitHubIssuesApi, projectId: string): Promise<() => void>
connect(api: GitHubIssuesApi, projectId: string, columns: string[], labelFilter?: string[]): Promise<() => void>
reload(api: GitHubIssuesApi, projectId: string): Promise<void>
loadMore(
@@ -137,8 +144,129 @@ async function acquireHostSubscription(api: GitHubIssuesApi, projectId: string):
}
}
+type PullWatchRecord = { refs: number; ready: Promise<void>; teardown?: () => void }
+const pullWatches = new WeakMap<GitHubIssuesApi, Map<string, PullWatchRecord>>()
+
+/** The freshest pull request status known for a project: the open board's or the watch's, by the
+ * host clock each was answered at. */
+export function pullBoardFor(
+ state: Pick<GitHubIssuesState, 'projects' | 'pullWatch'>,
+ projectId: string
+): GitHubPullBoard | undefined {
+ const fromBoard = state.projects[projectId]?.pullBoard
+ const fromWatch = state.pullWatch[projectId]
+ if (!fromBoard) return fromWatch
+ if (!fromWatch) return fromBoard
+ return (fromWatch.now ?? 0) > (fromBoard.now ?? 0) ? fromWatch : fromBoard
+}
+
+function lifecycleOf(item: GitHubIssuePage['items'][number]): PullLifecycle {
+ if (item.state === 'open') return item.pull?.draft ? 'draft' : 'open'
+ return item.pull?.mergedAt ? 'merged' : 'closed'
+}
+
+/**
+ * Does the board's repository have these pull requests, and where are they in their life? Read
+ * from the host's harvested issue list (#1008: pull requests ride the same REST snapshot), every
+ * column, following pages. Holding the host subscription for the duration makes the host read the
+ * repository first when nothing has yet in this app run. "Not found" is an ANSWER only from a whole,
+ * refreshed snapshot; anything less is `complete: false`, which a caller must not read as absence.
+ */
+export async function lookupPullRequests(
+ api: GitHubIssuesApi,
+ projectId: string,
+ columns: string[],
+ numbers: number[]
+): Promise<Map<number, PrLookup>> {
+ const release = await acquireHostSubscription(api, projectId)
+ try {
+ const out = new Map<number, PrLookup>()
+ await Promise.all(numbers.map(async (number) => {
+ let complete = true
+ for (const columnId of [null, ...columns]) {
+ let cursor: string | undefined
+ do {
+ const page = await api.query({
+ projectId, columnId, kind: 'pull', pageSize: 50, search: String(number), ...(cursor ? { cursor } : {})
+ })
+ if (page.partial || page.lastSuccessfulRefreshAt === undefined) complete = false
+ const item = page.items.find((candidate) => candidate.number === number)
+ if (item) {
+ out.set(number, { found: true, lifecycle: lifecycleOf(item) })
+ return
+ }
+ cursor = page.nextCursor
+ } while (cursor)
+ }
+ out.set(number, { found: false, complete })
+ }))
+ return out
+ } finally {
+ release()
+ }
+}
+
export const useGitHubIssues = create<GitHubIssuesState>((set, get) => ({
projects: {},
+ pullWatch: {},
+
+ async watchPulls(api, projectId) {
+ let watches = pullWatches.get(api)
+ if (!watches) {
+ watches = new Map()
+ pullWatches.set(api, watches)
+ }
+ let record = watches.get(projectId)
+ if (!record) {
+ const fresh: PullWatchRecord = { refs: 0, ready: Promise.resolve() }
+ const load = async (): Promise<void> => {
+ const board = await loadPullBoard(api, projectId)
+ // A failed read keeps what was there (the host marks its own board stale).
+ if (board && watches!.get(projectId) === fresh) {
+ set((state) => ({ pullWatch: { ...state.pullWatch, [projectId]: board } }))
+ }
+ }
+ fresh.ready = (async () => {
+ const changed = api.onChanged(projectId, () => { void load() })
+ let releaseHost: (() => void) | undefined
+ fresh.teardown = () => {
+ changed()
+ releaseHost?.()
+ }
+ try {
+ releaseHost = await acquireHostSubscription(api, projectId)
+ } catch {
+ // No host subscription (sync not approved, offline): the memory may still answer, and a
+ // wait that never learns anything expires on its deadline rather than firing.
+ }
+ if (watches!.get(projectId) !== fresh) {
+ releaseHost?.()
+ return
+ }
+ await load()
+ })()
+ record = fresh
+ watches.set(projectId, record)
+ }
+ record.refs += 1
+ const current = record
+ await current.ready
+ let released = false
+ return () => {
+ if (released) return
+ released = true
+ current.refs -= 1
+ if (current.refs !== 0 || watches!.get(projectId) !== current) return
+ watches!.delete(projectId)
+ current.teardown?.()
+ set((state) => {
+ if (!(projectId in state.pullWatch)) return state
+ const pullWatch = { ...state.pullWatch }
+ delete pullWatch[projectId]
+ return { pullWatch }
+ })
+ }
+ },
async connect(api, projectId, columns, labelFilter = []) {
const generation = ++nextConnectionGeneration
diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.ts
index 9c5e7e34b..7ef6f34c4 100644
--- a/src/renderer/state/workspace.test.ts
+++ b/src/renderer/state/workspace.test.ts
@@ -1176,3 +1176,51 @@ describe('createAgentNode prompt injection', () => {
expect(createAgentNode('gemini', 0, undefined, undefined, 'do X').data.initialCommand).toBe("gemini 'do X'")
})
})
+
+describe('pendingLaunch at the serializer seams (a held launch is hostile input too)', () => {
+ const state = (pendingLaunch: unknown) =>
+ ({
+ id: 'a1',
+ kind: 'terminal' as const,
+ position: { x: 0, y: 0 },
+ size: { width: 320, height: 240 },
+ title: 'A',
+ color: '#888',
+ group: null,
+ agentId: 'claude',
+ pendingLaunch
+ }) as never
+ const live = (pendingLaunch: unknown): CanvasNode =>
+ ({
+ id: 'a1',
+ type: 'terminal',
+ position: { x: 0, y: 0 },
+ width: 320,
+ height: 240,
+ data: { title: 'A', color: '#888', group: null, agentId: 'claude', pendingLaunch }
+ }) as unknown as CanvasNode
+
+ it('round-trips a PR-held launch', () => {
+ const hold = {
+ after: ['b1'],
+ command: 'claude',
+ attempted: false,
+ afterPr: { repository: 'o/r', waits: [{ number: 7, until: 'checks' }], deadlineAt: 5 }
+ }
+ const flow = nodeStatesToFlow([state(hold)])
+ expect(flow[0].data.pendingLaunch).toEqual(hold)
+ expect(flowToNodeStates(flow)[0].pendingLaunch).toEqual(hold)
+ })
+
+ it('an `after` that is not a list loads as a MANUAL hold — the launch loop would throw on it', () => {
+ const flow = nodeStatesToFlow([state({ after: 'b1', command: 'claude' })])
+ expect(flow[0].data.pendingLaunch).toMatchObject({ after: [], manualOnly: true })
+ })
+
+ it('a malformed PR wait loads as the invalid hold, on the way in and on the way out', () => {
+ const flow = nodeStatesToFlow([state({ after: [], command: 'c', afterPr: { waits: 'all' } })])
+ expect((flow[0].data.pendingLaunch as { afterPr?: { invalid?: true } }).afterPr?.invalid).toBe(true)
+ const out = flowToNodeStates([live({ after: [], command: 'c', afterPr: 'soon' })])
+ expect(out[0].pendingLaunch?.afterPr?.invalid).toBe(true)
+ })
+})
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index faa7a0879..dfb60c6e3 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -33,6 +33,7 @@ import { folderTitle } from '../lib/explorerCreate'
import { sshHostKey } from '@shared/ssh'
import { normalizeNodeIcon } from '@shared/node-icon'
import { normalizeIssueRef, type IssueRef } from '@shared/github-issue-ref'
+import { normalizePendingLaunch } from '@shared/pending-launch-shape'
import { useSettings } from './settings'
// Re-exported so Canvas (and anything else in the renderer) keeps importing it from here, while the
@@ -1974,7 +1975,9 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
issueRef: normalizeIssueRef(n.issueRef),
accountId: n.accountId,
agentSessionId: n.agentSessionId,
- pendingLaunch: n.pendingLaunch,
+ // Same seam rule again: the launch loop iterates `after`, and a PR wait decides when a
+ // command is typed into a pane. An unreadable hold becomes one that waits for ▶.
+ pendingLaunch: normalizePendingLaunch(n.pendingLaunch),
ssh: n.ssh,
sshRemoteTmux: n.sshRemoteTmux,
sshFs: n.sshFs,
@@ -2058,7 +2061,7 @@ export function flowToNodeStates(nodes: CanvasNode[], retainInitialCommand = tru
agentSessionId: n.data.agentSessionId,
// Owning-core UI intent is durable. Relay snapshots opt out: their new UI command
// uses a transient one-shot writer, never a whole-workspace persistence claim.
- pendingLaunch: n.data.pendingLaunch ?? (retainInitialCommand && n.data.initialCommand
+ pendingLaunch: normalizePendingLaunch(n.data.pendingLaunch) ?? (retainInitialCommand && n.data.initialCommand
? { after: [], command: n.data.initialCommand, attempted: false }
: undefined),
ssh: n.data.ssh,
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index ca57b06a5..f9ca1aac8 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -1442,6 +1442,21 @@ describe('HeadlessNodeFactory', () => {
expect(pty.sends).toEqual([])
})
+ it('refuses --after-pr by name: the Server Edition keeps no pull request watch', async () => {
+ // A silent drop would open the node and start it at once — before the PR the caller named.
+ const save = vi.spyOn(store, 'save')
+ for (const reply of [
+ await factory.openAgent('term-source', { agent: 'claude', prompt: 'brief', 'after-pr': '7:merged' }, true),
+ await factory.openTerminal('term-source', { cwd: projectDir, cmd: 'make', 'after-pr': '7:merged' }, true)
+ ]) {
+ expect(reply).toMatchObject({ ok: false })
+ expect((reply as { error: string }).error).toMatch(/--after-pr is not supported by Server Edition canvas control/)
+ }
+ expect(save).not.toHaveBeenCalled()
+ expect(pty.creates).toEqual([])
+ expect(pty.sends).toEqual([])
+ })
+
it('an explicit --run-now 0 is off, so --after still arms (#925)', async () => {
states['term-upstream'] = 'working'
const reply = await factory.openAgent(
diff --git a/src/shared/github-issue-ref.ts b/src/shared/github-issue-ref.ts
index a3cf7388c..8c91f9e13 100644
--- a/src/shared/github-issue-ref.ts
+++ b/src/shared/github-issue-ref.ts
@@ -90,7 +90,7 @@ export function normalizeIssueRef(value: unknown): IssueRef | undefined {
}
/** `owner/repo` split into its halves, validated. Used for a project's configured repository. */
-function parseRepository(repository: unknown): { owner: string; repo: string } | undefined {
+export function parseRepository(repository: unknown): { owner: string; repo: string } | undefined {
if (typeof repository !== 'string') return undefined
const slash = repository.indexOf('/')
if (slash < 0 || repository.indexOf('/', slash + 1) >= 0) return undefined
diff --git a/src/shared/pending-launch-shape.test.ts b/src/shared/pending-launch-shape.test.ts
new file mode 100644
index 000000000..728bd160f
--- /dev/null
+++ b/src/shared/pending-launch-shape.test.ts
@@ -0,0 +1,70 @@
+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 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 --git a/src/shared/pending-launch-shape.ts b/src/shared/pending-launch-shape.ts
new file mode 100644
index 000000000..0dff68324
--- /dev/null
+++ b/src/shared/pending-launch-shape.ts
@@ -0,0 +1,61 @@
+// 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'
+])
+
+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
+ }
+ const afterPr = normalizePrWaitHold(v.afterPr)
+ if (afterPr) out.afterPr = afterPr
+ if (manual) out.manualOnly = true
+ return out as unknown as PendingLaunch
+}
diff --git a/src/shared/pr-wait.test.ts b/src/shared/pr-wait.test.ts
new file mode 100644
index 000000000..ce003eb2c
--- /dev/null
+++ b/src/shared/pr-wait.test.ts
@@ -0,0 +1,194 @@
+import { describe, expect, it } from 'vitest'
+import {
+ INVALID_PR_WAIT_HOLD,
+ PR_DEADLINE_DEFAULT_MS,
+ PR_DEADLINE_MAX_MS,
+ PR_WAIT_MAX,
+ RUN_NOW_AFTER_PR_REFUSAL,
+ afterPrFlagRefusal,
+ formatPrWaits,
+ normalizePrWaitHold,
+ parseAfterPrArg,
+ parsePrDeadlineArg
+} from './pr-wait'
+
+describe('parseAfterPrArg — the --after-pr grammar', () => {
+ it('reads N:checks and N:merged', () => {
+ expect(parseAfterPrArg('1008:checks')).toEqual({ ok: true, specs: [{ number: 1008, until: 'checks' }] })
+ expect(parseAfterPrArg('1008:merged')).toEqual({ ok: true, specs: [{ number: 1008, until: 'merged' }] })
+ })
+
+ it('accepts #N — quoted on the command line, since an unquoted leading # starts a shell comment', () => {
+ expect(parseAfterPrArg('#12:merged')).toEqual({ ok: true, specs: [{ number: 12, until: 'merged' }] })
+ })
+
+ it('accepts owner/repo#N and keeps the repository for the caller to compare', () => {
+ expect(parseAfterPrArg('eneskirca/nodeterm#1008:checks')).toEqual({
+ ok: true,
+ specs: [{ number: 1008, until: 'checks', repository: 'eneskirca/nodeterm' }]
+ })
+ })
+
+ it('reads a comma list, every condition must hold', () => {
+ expect(parseAfterPrArg('12:checks, 13:merged')).toEqual({
+ ok: true,
+ specs: [
+ { number: 12, until: 'checks' },
+ { number: 13, until: 'merged' }
+ ]
+ })
+ })
+
+ it.each([
+ ['', 'empty'],
+ ['1008', 'no condition'],
+ ['1008:', 'empty condition'],
+ ['1008:green', 'unknown condition'],
+ ['1008:Merged', 'case is not repaired'],
+ ['0:merged', 'zero'],
+ ['-3:merged', 'negative'],
+ ['12a:merged', 'not a number'],
+ ['owner/repo:merged', 'no number'],
+ ['owner/re po#3:merged', 'bad repository'],
+ ['1,2:merged', 'an item without a condition'],
+ ['12:merged,,13:merged', 'an empty item'],
+ ['12:merged;rm -rf /', 'trailing garbage']
+ ])('refuses %j (%s) and names the accepted forms', (raw) => {
+ const r = parseAfterPrArg(raw)
+ expect(r.ok).toBe(false)
+ if (!r.ok) expect(r.error).toMatch(/--after-pr must be/)
+ })
+
+ it('refuses a non-string (a hostile caller, never a shim)', () => {
+ expect(parseAfterPrArg(42).ok).toBe(false)
+ expect(parseAfterPrArg(undefined).ok).toBe(false)
+ })
+
+ it('refuses the same pull request named twice', () => {
+ const r = parseAfterPrArg('12:checks,12:merged')
+ expect(r.ok).toBe(false)
+ if (!r.ok) expect(r.error).toMatch(/once/)
+ })
+
+ it(`refuses more than ${PR_WAIT_MAX} pull requests`, () => {
+ const raw = Array.from({ length: PR_WAIT_MAX + 1 }, (_, i) => `${i + 1}:merged`).join(',')
+ expect(parseAfterPrArg(raw).ok).toBe(false)
+ const ok = Array.from({ length: PR_WAIT_MAX }, (_, i) => `${i + 1}:merged`).join(',')
+ expect(parseAfterPrArg(ok).ok).toBe(true)
+ })
+})
+
+describe('parsePrDeadlineArg', () => {
+ it('defaults to 24 h when absent', () => {
+ expect(parsePrDeadlineArg(undefined)).toEqual({ ok: true, ms: PR_DEADLINE_DEFAULT_MS })
+ expect(PR_DEADLINE_DEFAULT_MS).toBe(24 * 3600_000)
+ })
+
+ it('reads minutes, hours and days', () => {
+ expect(parsePrDeadlineArg('90m')).toEqual({ ok: true, ms: 90 * 60_000 })
+ expect(parsePrDeadlineArg('6h')).toEqual({ ok: true, ms: 6 * 3600_000 })
+ expect(parsePrDeadlineArg('3d')).toEqual({ ok: true, ms: 3 * 86_400_000 })
+ })
+
+ it.each(['', '0m', '6', 'h', '1.5h', '6 h', '-1h', '1w', 'forever'])('refuses %j', (raw) => {
+ expect(parsePrDeadlineArg(raw).ok).toBe(false)
+ })
+
+ it('refuses a deadline past 14 days rather than clamping it', () => {
+ expect(parsePrDeadlineArg('14d')).toEqual({ ok: true, ms: PR_DEADLINE_MAX_MS })
+ expect(parsePrDeadlineArg('15d').ok).toBe(false)
+ })
+})
+
+describe('afterPrFlagRefusal — the shape gate main and the Server Edition parser run', () => {
+ it('passes a call without the flags', () => {
+ expect(afterPrFlagRefusal('open-agent', {})).toBeNull()
+ expect(afterPrFlagRefusal('write', { node: 'n1', text: 'x' })).toBeNull()
+ })
+
+ it('passes a well-formed wait on every open verb', () => {
+ for (const verb of ['open-claude', 'open-agent']) {
+ expect(afterPrFlagRefusal(verb, { 'after-pr': '12:merged', 'pr-deadline': '2d' })).toBeNull()
+ }
+ expect(afterPrFlagRefusal('open-terminal', { 'after-pr': '12:merged', cmd: 'make release' })).toBeNull()
+ })
+
+ it('refuses open-terminal --after-pr with no --cmd: there is no launch to hold', () => {
+ // Accepting it would reply "waiting for PR #12" about a terminal that has nothing to run.
+ expect(afterPrFlagRefusal('open-terminal', { 'after-pr': '12:merged' })).toMatch(/needs --cmd/)
+ })
+
+ it('refuses --after-pr on any other verb, rather than ignoring it', () => {
+ expect(afterPrFlagRefusal('spawn-team', { 'after-pr': '12:merged' })).toMatch(
+ /applies only to open-terminal \/ open-claude \/ open-agent/
+ )
+ })
+
+ it('refuses a malformed value with the verb in front', () => {
+ expect(afterPrFlagRefusal('open-agent', { 'after-pr': '12' })).toMatch(/^open-agent: --after-pr must be/)
+ })
+
+ it('refuses --pr-deadline without --after-pr, and a bad duration', () => {
+ expect(afterPrFlagRefusal('open-agent', { 'pr-deadline': '2d' })).toMatch(/only with --after-pr/)
+ expect(afterPrFlagRefusal('open-agent', { 'after-pr': '12:merged', 'pr-deadline': 'soon' })).toMatch(
+ /--pr-deadline must be/
+ )
+ })
+
+ it('refuses --run-now with --after-pr: "start now" and "start when the PR is ready" contradict', () => {
+ expect(afterPrFlagRefusal('open-agent', { 'after-pr': '12:merged', 'run-now': '' })).toBe(
+ RUN_NOW_AFTER_PR_REFUSAL
+ )
+ // An explicit off is off, exactly as `runNowRequested` reads it.
+ expect(afterPrFlagRefusal('open-agent', { 'after-pr': '12:merged', 'run-now': 'false' })).toBeNull()
+ })
+})
+
+describe('normalizePrWaitHold — a git-shared, hand-editable project file is hostile input', () => {
+ const good = {
+ repository: 'eneskirca/nodeterm',
+ waits: [{ number: 12, until: 'checks' }],
+ deadlineAt: 1_900_000_000_000
+ }
+
+ it('absent stays absent', () => {
+ expect(normalizePrWaitHold(undefined)).toBeUndefined()
+ expect(normalizePrWaitHold(null)).toBeUndefined()
+ })
+
+ it('a valid hold comes back with only the fields this module vouches for', () => {
+ expect(normalizePrWaitHold({ ...good, extra: '<script>' })).toEqual(good)
+ })
+
+ it.each([
+ ['a string', 'x'],
+ ['an array', []],
+ ['a bad repository', { ...good, repository: 'not a repo' }],
+ ['waits not a list', { ...good, waits: 'all' }],
+ ['no waits', { ...good, waits: [] }],
+ ['a bad number', { ...good, waits: [{ number: -1, until: 'merged' }] }],
+ ['a bad condition', { ...good, waits: [{ number: 12, until: 'green' }] }],
+ ['a duplicate', { ...good, waits: [{ number: 12, until: 'merged' }, { number: 12, until: 'checks' }] }],
+ ['too many', { ...good, waits: Array.from({ length: PR_WAIT_MAX + 1 }, (_, i) => ({ number: i + 1, until: 'merged' })) }],
+ ['a NaN deadline', { ...good, deadlineAt: Number.NaN }],
+ ['a string deadline', { ...good, deadlineAt: '2030' }],
+ ['a hold already marked invalid', { ...good, invalid: true }]
+ ])('%s becomes the INVALID hold — present, never satisfied, never throws', (_label, value) => {
+ // Dropping a malformed hold would let the node start on its `--after` deps alone, i.e. EARLY:
+ // the unsafe direction. The invalid hold keeps it waiting for a human (▶).
+ expect(normalizePrWaitHold(value)).toEqual(INVALID_PR_WAIT_HOLD)
+ })
+})
+
+describe('formatPrWaits', () => {
+ it('names each pull request and its condition', () => {
+ expect(
+ formatPrWaits({
+ waits: [
+ { number: 12, until: 'checks' },
+ { number: 13, until: 'merged' }
+ ]
+ })
+ ).toBe('PR #12 checks, PR #13 merged')
+ })
+})
diff --git a/src/shared/pr-wait.ts b/src/shared/pr-wait.ts
new file mode 100644
index 000000000..4f5d7c4ea
--- /dev/null
+++ b/src/shared/pr-wait.ts
@@ -0,0 +1,205 @@
+// `--after-pr`: an armed node that ALSO waits on pull requests of its project's GitHub board.
+//
+// `--after <ids>` releases a node when upstream agent stations finish a turn. That covers "B needs
+// what A produced" inside the canvas, but not "start the reviewer once CI is green" or "start the
+// release notes once the PR is merged", which are facts about GitHub. This module owns the GRAMMAR
+// of that flag and the persisted SHAPE of the hold, and is shared by the three places that read
+// them: main's shape gate (and the Server Edition's parser, which then refuses the flag by name),
+// the renderer's control dispatch, and the load seam that sanitizes a hand-editable project file.
+// When a hold is SATISFIED is the renderer's question (`renderer/lib/prWait.ts`), answered from
+// the pull request status #1008 already keeps — nothing here reads GitHub.
+//
+// Grammar: `--after-pr <ref>:<checks|merged>[,<ref>:<checks|merged>…]`, where `<ref>` is `N`,
+// `#N` or `owner/repo#N` (which must be the board's own repository). One flag carries one whole
+// condition, so there is no second flag to pair with it, and every flag has a value — the SSH shim
+// rule (an older shim on a host takes the token after ANY flag as its value). `N` needs no quoting;
+// an unquoted `#N` at the start of a shell word begins a comment and swallows the rest of the line.
+
+import { runNowRequested } from './control-verbs'
+import { parseRepository } from './github-issue-ref'
+
+export type PrWaitUntil = 'checks' | 'merged'
+
+const UNTIL: ReadonlySet<string> = new Set<PrWaitUntil>(['checks', 'merged'])
+
+/** One parsed `--after-pr` item. `repository` is present only when the caller wrote the full form. */
+export interface PrWaitSpec {
+ number: number
+ until: PrWaitUntil
+ repository?: string
+}
+
+export interface PrWait {
+ number: number
+ until: PrWaitUntil
+}
+
+/** What an armed node persists in `pendingLaunch.afterPr`. */
+export interface PrWaitHold {
+ /** `owner/name` the numbers belong to: the board's repository when the node was armed. A board
+ * that later syncs another repository cannot satisfy this hold. */
+ repository: string
+ waits: PrWait[]
+ /** Epoch ms on this machine's clock. Past it the node never starts on its own (▶ still runs it). */
+ deadlineAt: number
+ /** A hold read from a project file that did not survive validation. Never satisfied. */
+ invalid?: true
+}
+
+/** How many pull requests one open may wait on. */
+export const PR_WAIT_MAX = 8
+export const PR_DEADLINE_DEFAULT_MS = 24 * 3_600_000
+export const PR_DEADLINE_MIN_MS = 60_000
+export const PR_DEADLINE_MAX_MS = 14 * 86_400_000
+
+/** The shape a malformed persisted hold becomes: present (the node stays held), never satisfied,
+ * already past its deadline so the node reads EXPIRED and offers ▶. */
+export const INVALID_PR_WAIT_HOLD: PrWaitHold = Object.freeze({
+ repository: '',
+ waits: [],
+ deadlineAt: 0,
+ invalid: true
+}) as PrWaitHold
+
+/** "Start now" and "start when the pull request is ready" contradict each other, exactly like
+ * `--run-now` with `--after`. */
+export const RUN_NOW_AFTER_PR_REFUSAL =
+ 'run-now-after-pr-unsupported: --run-now cannot be combined with --after-pr'
+
+const FORMS = 'N:checks or N:merged (N may be #N or owner/repo#N), comma-separated'
+
+const NUMBER = /^[1-9][0-9]{0,9}$/
+const MAX_NUMBER = 2 ** 31 - 1
+
+function validNumber(value: unknown): value is number {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 && value <= MAX_NUMBER
+}
+
+function parseNumber(text: string): number | undefined {
+ if (!NUMBER.test(text)) return undefined
+ const n = Number(text)
+ return validNumber(n) ? n : undefined
+}
+
+/** `N`, `#N` or `owner/repo#N`. Nothing is repaired: a guess could only name the wrong PR. */
+function parseRef(text: string): { number: number; repository?: string } | undefined {
+ const hash = text.indexOf('#')
+ if (hash < 0) {
+ const number = parseNumber(text)
+ return number === undefined ? undefined : { number }
+ }
+ if (text.indexOf('#', hash + 1) >= 0) return undefined
+ const number = parseNumber(text.slice(hash + 1))
+ if (number === undefined) return undefined
+ if (hash === 0) return { number }
+ const repo = parseRepository(text.slice(0, hash))
+ return repo ? { number, repository: `${repo.owner}/${repo.repo}` } : undefined
+}
+
+export function parseAfterPrArg(
+ raw: unknown
+): { ok: true; specs: PrWaitSpec[] } | { ok: false; error: string } {
+ const bad = (): { ok: false; error: string } => ({
+ ok: false,
+ error: `--after-pr must be ${FORMS} (got ${JSON.stringify(String(raw ?? '')).slice(0, 80)})`
+ })
+ if (typeof raw !== 'string') return bad()
+ const items = raw.split(',').map((item) => item.trim())
+ const specs: PrWaitSpec[] = []
+ for (const item of items) {
+ const colon = item.lastIndexOf(':')
+ if (colon <= 0) return bad()
+ const until = item.slice(colon + 1)
+ if (!UNTIL.has(until)) return bad()
+ const ref = parseRef(item.slice(0, colon))
+ if (!ref) return bad()
+ specs.push({ number: ref.number, until: until as PrWaitUntil, ...(ref.repository ? { repository: ref.repository } : {}) })
+ }
+ if (specs.length > PR_WAIT_MAX) {
+ return { ok: false, error: `--after-pr names at most ${PR_WAIT_MAX} pull requests` }
+ }
+ if (new Set(specs.map((s) => s.number)).size !== specs.length) {
+ return { ok: false, error: '--after-pr: name each pull request once' }
+ }
+ return { ok: true, specs }
+}
+
+const DURATION = /^([1-9][0-9]{0,4})([mhd])$/
+const UNIT_MS: Record<string, number> = { m: 60_000, h: 3_600_000, d: 86_400_000 }
+
+/** `--pr-deadline <duration>` (`90m`, `12h`, `3d`), 1 minute to 14 days; absent = 24 h. Refused, not
+ * clamped: a caller who asked for a month would otherwise be told nothing about getting two weeks. */
+export function parsePrDeadlineArg(
+ raw: string | undefined
+): { ok: true; ms: number } | { ok: false; error: string } {
+ if (raw === undefined) return { ok: true, ms: PR_DEADLINE_DEFAULT_MS }
+ const m = DURATION.exec(raw)
+ const ms = m ? Number(m[1]) * UNIT_MS[m[2]] : NaN
+ if (!m || ms < PR_DEADLINE_MIN_MS || ms > PR_DEADLINE_MAX_MS) {
+ return {
+ ok: false,
+ error: `--pr-deadline must be a duration like 90m, 12h or 3d, between 1m and 14d (got ${JSON.stringify(raw).slice(0, 40)})`
+ }
+ }
+ return { ok: true, ms }
+}
+
+const OPEN_VERBS: ReadonlySet<string> = new Set(['open-terminal', 'open-claude', 'open-agent'])
+
+/**
+ * The `--after-pr` / `--pr-deadline` SHAPE gate. Desktop main runs it in its control handler before
+ * forwarding (it does not run `parseControlRequest`), the Server Edition inside
+ * `parseControlRequest` — which then refuses the well-formed flag as unsupported, since that
+ * edition keeps no pull request watch. What a number MEANS (does the board's repository have that
+ * pull request?) is the renderer's question; this is the early half, never the only one.
+ */
+export function afterPrFlagRefusal(verb: string, args: Record<string, string | undefined>): string | null {
+ if (args['after-pr'] === undefined) {
+ return args['pr-deadline'] === undefined ? null : `${verb}: --pr-deadline applies only with --after-pr`
+ }
+ if (!OPEN_VERBS.has(verb)) {
+ return `${verb}: --after-pr applies only to open-terminal / open-claude / open-agent`
+ }
+ // A terminal with no `--cmd` has no launch to hold, so a reply saying it waits would be untrue.
+ if (verb === 'open-terminal' && !args.cmd) {
+ return 'open-terminal: --after-pr needs --cmd (a terminal with no command has nothing to hold)'
+ }
+ const parsed = parseAfterPrArg(args['after-pr'])
+ if (!parsed.ok) return `${verb}: ${parsed.error}`
+ const deadline = parsePrDeadlineArg(args['pr-deadline'])
+ if (!deadline.ok) return `${verb}: ${deadline.error}`
+ if (runNowRequested(args)) return RUN_NOW_AFTER_PR_REFUSAL
+ return null
+}
+
+/**
+ * The persisted hold, validated at both serializer seams. Absent stays absent. Anything present
+ * but malformed becomes `INVALID_PR_WAIT_HOLD`, never `undefined`: dropping it would let the node
+ * start on its `--after` deps alone — early, the unsafe direction. Only vouched-for fields survive.
+ */
+export function normalizePrWaitHold(value: unknown): PrWaitHold | undefined {
+ if (value === undefined || value === null) return undefined
+ if (typeof value !== 'object' || Array.isArray(value)) return INVALID_PR_WAIT_HOLD
+ const v = value as Record<string, unknown>
+ if (v.invalid !== undefined) return INVALID_PR_WAIT_HOLD
+ const repo = parseRepository(v.repository)
+ if (!repo) return INVALID_PR_WAIT_HOLD
+ if (!Array.isArray(v.waits) || v.waits.length === 0 || v.waits.length > PR_WAIT_MAX) {
+ return INVALID_PR_WAIT_HOLD
+ }
+ const waits: PrWait[] = []
+ for (const w of v.waits as unknown[]) {
+ if (!w || typeof w !== 'object') return INVALID_PR_WAIT_HOLD
+ const { number, until } = w as Record<string, unknown>
+ if (!validNumber(number) || typeof until !== 'string' || !UNTIL.has(until)) return INVALID_PR_WAIT_HOLD
+ if (waits.some((x) => x.number === number)) return INVALID_PR_WAIT_HOLD
+ waits.push({ number, until: until as PrWaitUntil })
+ }
+ if (typeof v.deadlineAt !== 'number' || !Number.isFinite(v.deadlineAt)) return INVALID_PR_WAIT_HOLD
+ return { repository: `${repo.owner}/${repo.repo}`, waits, deadlineAt: v.deadlineAt }
+}
+
+/** "PR #12 checks, PR #13 merged" — the one wording for replies, the badge and `list`. */
+export function formatPrWaits(hold: Pick<PrWaitHold, 'waits'>): string {
+ return hold.waits.map((w) => `PR #${w.number} ${w.until}`).join(', ')
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 92217b1f5..2e1884aae 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,5 +1,6 @@
import type { TextDeliveryResult } from './text-delivery'
import type { IdentitySeedEntry } from './agent-identity-seed'
+import type { PrWaitHold } from './pr-wait'
// Types shared across the main, preload, and renderer processes.
import { TABBAR_HEIGHT_PX } from './window-chrome-metrics'
@@ -431,6 +432,13 @@ 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
}
export interface CanvasNodeState {