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.

fix(board-dispatch): review round — bound consent, re-checked queue, no armed leftovers

review2acf6bed89ee
diff --git a/CLAUDE.md b/CLAUDE.md
index a90275874..0cb5654d3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6313,19 +6313,21 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
project file, and nodeterm-ios ignores the unknown field (follow-up there).
**Board dispatch — a card THIS person moves into the dispatch column starts its own run**
(2026-09-30; `@shared/board-dispatch` consent, `renderer/lib/boardDispatch.ts` decisions,
- `state/boardDispatch.ts` queue, wired in Canvas `dispatchOnUserMove`). The run is exactly "Start
- with agent" — `issueRef` binding, the reference-only `issueLaunchPrompt`, `fileIssueSession`
- (card filed + `run-started`) — only nobody clicked it. The hard question is WHO may trigger a run
- on this machine, and the answer shapes everything else:
+ `state/boardDispatch.ts` queue, wired in Canvas `dispatchOnUserMove` / `drainDispatchQueue`). The
+ run is exactly "Start with agent" — `issueRef` binding, the reference-only `issueLaunchPrompt`,
+ `fileIssueSession` (card filed + `run-started`) — only nobody clicked it. The hard question is WHO
+ may trigger a run on this machine, and the answer shapes everything else:
- **The trigger is the person's own move in this app**, never a fact that arrives from outside.
`decideDispatch` answers `ignore` for every origin but `'user-move'`, and the only caller that
says `'user-move'` is the board's move-result path (`KanbanView.moveIssueByUser` →
`onIssueMoved`, reached only from `requestGitHubMove` and the close/reopen confirm). A label
set on GitHub (by anyone — on a public repository, ANYONE) reaches this app only as a refreshed
page, and a board change arriving by `git pull` only as a new project file; neither has a path
- in. `lib/board-dispatch.guard.test.ts` pins the whole chain line by line — a new caller of
- `decideDispatch`, a second `origin: 'user-move'`, or `onIssueMoved` fired from anywhere else
- fails it. A move GitHub did not CONFIRM (`stale`, `failed`, `read-only`, …) is not a dispatch.
+ in. A move GitHub did not CONFIRM (`stale`, `failed`, `read-only`, …) is not a dispatch.
+ `lib/board-dispatch.guard.test.ts` pins the WHOLE chain: `decideDispatch`'s one caller,
+ `onIssueMoved`'s one firing site, `dispatchStart`'s two callers (after `decideDispatch` in
+ `dispatchOnUserMove`, after `recheckQueued` in the drain), and that a `'queued'` entry — which
+ the drain starts without asking `decideDispatch` again — is created only in `dispatchOnUserMove`.
- **Why not a label with an actor allowlist** (the other design considered): it works from a
phone, but it needs one issue-events read per candidate issue (budget), compares an actor
against a credential that can change under it, and today the poll runs only while a board is
@@ -6334,39 +6336,66 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
- **Consent is machine-local** (`settings.boardDispatch`, the `kanbanPullAutoMove` / trigger arm
store tier), never `.nodeterm/project.json`: a switch in the project file would let a pull
request make every clone start agents. Per project: the column, the agent, an optional account
- (absent = the project default through the same funnel as "New <agent>"), and a cap (1–8,
- default 2). Read through `sanitizeBoardDispatch`: an unreadable entry is OFF, an unreadable cap
- is 1, the kill switch (`paused`) is on only for a literal `true`. `boardDispatch` is in
+ (absent = the project default through the same funnel as "New <agent>"), a cap (1–8, **default
+ 1**: dispatched runs are told to implement the fix in the project's own working tree, so two at
+ once are two agents editing one checkout), and a **binding**.
+ - **The consent binds what the column MEANS, not just its id** (`dispatchBinding`: repository +
+ column title + its GitHub label). Titles and labels live in the git-shared project file, and
+ titles are deliberately outside `githubMappingDigest` — so without it a pulled commit swapping
+ the titles of "Agent" and "In Progress" would turn the person's routine drag into "In Progress"
+ into a dispatch, and re-pointing the board at another repository (which needs only a mapping
+ re-approval) would carry the dispatch switch along. Any difference refuses (`consent-stale`, on
+ the card and in Settings) until the person presses "Re-confirm this column". Choosing a column
+ binds; changing the agent or the cap does not re-bind. An entry without a binding is OFF.
+ - Read through `sanitizeBoardDispatch`: an unreadable entry is OFF, an unreadable cap is 1, the
+ kill switch (`paused`) is on only for a literal `true`. `boardDispatch` is in
`SETTINGS_VERB_FORBIDDEN` — an agent that could switch the dispatcher on would grant itself more
agents, and the name pattern does not catch the key, so the set is its only fence. Model: the
same gateway default `addAgentNode` applies; there is no per-project model.
+ - **Only agents that report their state through hooks** (`dispatchableAgent` →
+ `hasHooks(capabilityAgentId(…))`, the `--after` rule) are offered or accepted. The cap counts
+ sessions by hook state; a hookless custom agent never reports, so after the startup grace its
+ slot would free and the cap would admit one more run every two minutes.
- **Bounds.** One run per issue: a bound session that still exists in ANY project, or a dispatch
already queued/starting, refuses the next with a reason on the card. The cap counts this
- project's bound sessions that are `working`/`waiting`/`blocked`, hold a launch, or were started
- by dispatch within `DISPATCH_STARTUP_GRACE_MS` (no hook yet) — `done` frees the slot (the cap
- limits concurrent WORK; an idle agent spends nothing), and an unknown state from before a
- restart does not hold one, or the cap would stay pinned. Over the cap, the dispatch QUEUES; the
- queue is drained on a 5 s timer that runs only while something is queued, oldest first. Moving
- a queued card out of the column withdraws it. The kill switch (Settings → GitHub Issues → Pause
- all dispatch) refuses new dispatches and drops the queue; running sessions are not touched.
+ project's bound sessions that are `working`/`waiting`/`blocked`, hold a launch that will start
+ BY ITSELF (a `manualOnly` one waiting for Run now does not), or were started by dispatch within
+ `DISPATCH_STARTUP_GRACE_MS` (no hook yet) — `done` frees the slot (the cap limits concurrent
+ WORK), and an unknown state from before a restart does not hold one, or the cap would stay
+ pinned. Over the cap the dispatch QUEUES; the drain runs on a 5 s timer only while something is
+ queued. **Every queued entry is re-asked before it starts** (`recheckQueued`): kill switch,
+ still switched on, project still open/local/not closed, binding unchanged, agent still
+ dispatchable, and the issue still OPEN and still in the dispatch column (read from the host's
+ issue cache with `githubIssues.query` — no GitHub request; an unreadable answer waits, it is
+ never evidence). A teammate closing or moving the issue while it waited drops it with its
+ reason. Moving a queued card out of the column withdraws it. The kill switch refuses new
+ dispatches and drops the queue; running sessions are not touched.
+ - **No dispatched node is ever left armed to start on its own.** The off-screen path writes the
+ node ALREADY CLAIMED (`claimForHeadless`: `manualOnly`, in the same tick as the node — no window
+ in which opening the project would auto-start it beside the headless start), then runs the #925
+ headless start. Whatever it answers, a node that did not start waits for Run now; a Pause or a
+ restart can therefore never be outrun by a held launch that fires on view. The failure notice
+ says exactly that (Run now, or close the node to dispatch the issue again — it keeps the issue's
+ one run until then).
- **The queue is in memory, on purpose**: a queue that survived a restart would start agents at
boot with nobody there. A restart drops it silently, and the drag (or Start with agent) can be
- repeated.
+ repeated. Each renderer keeps its own queue, so **two Server Edition tabs on one project can
+ each run up to the cap** (known; one tab per project is the supported use).
- **The card says what happened** (`DispatchChip`): "Queued for an agent (#2)", "Dispatching an
agent…", or "Not dispatched: <reason>" (`DISPATCH_REFUSAL_TEXT`). A started run shows as the
ordinary run chip.
- - **Where it runs: the renderer**, because the trigger is a UI gesture core never sees. When the
- dispatch is on screen (it always is at trigger time — the board is the active project's) it is
- `addAgentNode`. A queued run whose slot frees while its project is NOT on screen is a cold open
- into the stored project (the control verbs' path: `armForColdOpen`, `applyOwnNodeMutation`,
- `writeDisk`) plus the #925 headless start, which raises its "Go there" notice; a headless start
- that fails leaves the node queued to start on view and says so. **Server Edition**: on-screen
- dispatch works; an off-screen one is written as an armed node that starts when that project is
- next viewed (it has no headless launcher) and the notice says so. **SSH projects: refused by
- name** (the headless launcher is local-only). **Relay tabs: refused** (the board is the host's).
- **Mobile: N/A** (the phone board carries no issue cards). Never auto-posts to GitHub, never
- closes an issue, never moves a card on a turn `done` — the existing rules; the dispatch column
- may not be the completion column.
+ - **Where it runs: the renderer**, because the trigger is a UI gesture core never sees. On screen
+ it is `addAgentNode`. Off screen — a queued run whose slot freed later, or a project switch
+ during the move's GitHub round trip — it is a cold open into the stored project (the control
+ verbs' path) plus the headless start, which raises its "Go there" notice. A CLOSED project's
+ queued run is dropped, not started (the headless start would unhide its tab). **Server
+ Edition**: the browser renderer's `pty.launchHeadless` is unsupported (the server's own
+ headless launcher serves canvas control, not a browser tab), so a dispatch there starts only
+ for the project ON SCREEN; an off-screen one stays queued (still subject to Pause) until that
+ project is shown. **SSH projects: refused by name** (the headless launcher is local-only).
+ **Relay tabs: refused** (the board is the host's). **Mobile: N/A** (the phone board carries no
+ issue cards). Never auto-posts to GitHub, never closes an issue, never moves a card on a turn
+ `done` — the existing rules; the dispatch column may not be the completion column.
**Where a card comes from is a registry, not a branch per call site** (`renderer/lib/kanbanSources.ts`,
2026-08-30 — the same membership-plus-one-leaf discipline `AGENT_CONFIG` uses): each entry declares
its filter `label`, its `placement` (`assignment` = the board's own persisted assignments,
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 67ceda349..819cabe2c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -140,9 +140,12 @@ fires while typing or in a terminal.
Anything that **starts an agent by itself** (board dispatch is the first) takes its consent from
machine-local settings and its trigger from a gesture the person made in this app — never from a
-label, a column or a file that can arrive from GitHub or a `git pull`. Board dispatch's one
-trigger is `KanbanView.moveIssueByUser` → `onIssueMoved`; `lib/board-dispatch.guard.test.ts`
-fails if anything else reaches `decideDispatch` with `origin: 'user-move'`.
+label, a column or a file that can arrive from GitHub or a `git pull` — and its consent binds what
+it consented to (board dispatch binds repository + column title + label, not a bare column id).
+Board dispatch's one trigger is `KanbanView.moveIssueByUser` → `onIssueMoved` → `decideDispatch`,
+and a run starts only through `dispatchStart`, from that decision or from the queue drain after
+`recheckQueued`; `lib/board-dispatch.guard.test.ts` fails if a new caller of any link in that
+chain appears, or if anything but `dispatchOnUserMove` creates a queued entry.
A card chip that reads agent state subscribes to a **primitive signature** of the nodes it shows
(`teamProgressSig`, `issueRunChipSig`), never to the whole `agentStatus.byId` map — that map changes
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index f6904a86e..16aa2e7b5 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -486,15 +486,18 @@ import {
normalizeIssueRef,
type IssueRef
} from '@shared/github-issue-ref'
-import { sanitizeBoardDispatch, type BoardDispatchProject } from '@shared/board-dispatch'
+import { dispatchBinding, sanitizeBoardDispatch, type BoardDispatchProject } from '@shared/board-dispatch'
import {
DISPATCH_DRAIN_MS,
DISPATCH_REFUSAL_TEXT,
decideDispatch,
+ dispatchableAgent,
moveWithdrawsDispatch,
occupiesSlot,
queueToDrop,
- queueToStart
+ queueToStart,
+ recheckQueued,
+ type QueuedCardFact
} from '../lib/boardDispatch'
import { dispatchEntry, useBoardDispatch, type DispatchCardEntry } from '../state/boardDispatch'
import type { GitHubIssueCardView as DispatchIssueCard } from '@shared/github-issues'
@@ -682,6 +685,7 @@ import {
RUN_NOW_AFTER_REFUSAL
} from '@shared/control-verbs'
import {
+ claimForHeadless,
headlessStartNoticeText,
mergeRunNow,
planRunVerb,
@@ -10511,25 +10515,28 @@ export function Canvas() {
// (@shared/board-dispatch); the queue is transient (state/boardDispatch). The run itself is
// exactly "Start with agent": `issueRef` binding, the reference-only launch prompt,
// `fileIssueSession` (card filed + `run-started`). On screen it goes through `addAgentNode`; for a
- // project that is not on screen (a queued run whose slot freed later) it is a cold open plus the
- // #925 headless start.
+ // project that is not on screen (a queued run whose slot freed later, or a project switch during
+ // the move's round trip) it is a cold open, already CLAIMED, plus the #925 headless start — so no
+ // dispatched node is ever left armed to start on its own later (the kill switch could not reach it).
/** Every node of a project as the dispatcher needs it: the live canvas for the active project,
- * the stored copy for any other. */
+ * the stored copy for any other. `pending` = a launch that will start BY ITSELF. */
const dispatchNodesOf = useCallback(
(projectId: string): Array<{ id: string; issueRef?: unknown; pending: boolean }> => {
const st = useProjects.getState()
+ const selfStarting = (p: unknown): boolean =>
+ !!p && typeof p === 'object' && !(p as PendingLaunch).manualOnly
if (st.activeProjectId === projectId && nodesProjectIdRef.current === projectId) {
return nodesRef.current.map((n) => ({
id: n.id,
issueRef: n.data.issueRef,
- pending: !!n.data.pendingLaunch
+ pending: selfStarting(n.data.pendingLaunch)
}))
}
return (st.getProject(projectId)?.nodes ?? []).map((n) => ({
id: n.id,
issueRef: n.issueRef,
- pending: !!n.pendingLaunch
+ pending: selfStarting(n.pendingLaunch)
}))
},
[]
@@ -10564,14 +10571,31 @@ export function Canvas() {
[dispatchNodesOf]
)
- const dispatchAgentKnown = (agentId: string): boolean =>
- !!agentConfig(agentId) || useSettings.getState().settings.customAgents.some((c) => c.id === agentId)
+ const dispatchAgentOk = (agentId: string): boolean =>
+ dispatchableAgent(
+ agentId,
+ !!agentConfig(agentId) || useSettings.getState().settings.customAgents.some((c) => c.id === agentId)
+ )
+
+ /** The consent binding of a project's dispatch column as it is NOW (repository from the issue's
+ * own reference — the board's repository). */
+ const dispatchBindingNow = (project: Project | undefined, columnId: string, ref: IssueRef | undefined) =>
+ dispatchBinding(
+ ref ? `${ref.owner}/${ref.repo}` : undefined,
+ project?.kanban?.columns.find((c) => c.id === columnId)?.title,
+ project?.kanban?.github?.columnMappings.find((m) => m.columnId === columnId)?.label
+ )
- /** Start one dispatched run. Never throws; every failure lands on the card. */
+ /** The project's run may start from here now: always on screen; off screen only where a headless
+ * launcher exists (the desktop — the browser's renderer has none). */
+ const dispatchStartableNow = (projectId: string): boolean =>
+ !isBrowserRuntime() || useProjects.getState().activeProjectId === projectId
+
+ /** Start one dispatched run. Called ONLY by dispatchOnUserMove and drainDispatchQueue (pinned by
+ * board-dispatch.guard.test). Never throws; every failure lands on the card. */
const dispatchStart = useCallback(
async (entry: DispatchCardEntry, config: BoardDispatchProject): Promise<void> => {
- const board = useBoardDispatch.getState()
- board.put({ ...entry, status: 'starting' })
+ useBoardDispatch.getState().put({ ...entry, status: 'starting' })
const fail = (reason: string): void =>
useBoardDispatch.getState().put({ ...entry, status: 'refused', reason })
try {
@@ -10580,8 +10604,9 @@ export function Canvas() {
const agentId = config.agentId as AgentId
const st = useProjects.getState()
const project = st.getProject(entry.projectId)
- if (!project) return fail('The project is no longer open on this machine.')
+ if (!project) return fail(DISPATCH_REFUSAL_TEXT['project-gone'])
if (project.ssh) return fail(DISPATCH_REFUSAL_TEXT['remote-project'])
+ if (project.closed) return fail(DISPATCH_REFUSAL_TEXT['project-closed'])
let nodeId: string
if (st.activeProjectId === project.id && canCreateOnCanvas(nodesProjectIdRef.current, project.id)) {
const created = addAgentNode(agentId, undefined, undefined, config.accountId, prompt, {
@@ -10591,6 +10616,9 @@ export function Canvas() {
fileIssueSession(entry.columnId, entry.ref, created, agentId)
nodeId = created.node.id
} else {
+ // Callers never send an off-screen start to a runtime without a headless launcher; this
+ // is the belt, so nothing is ever left armed there.
+ if (!dispatchStartableNow(project.id)) return fail('Open the project to dispatch this issue.')
// Not on screen: a cold open into the stored project (the control verbs' path), then the
// headless start. Defaults come from THAT project, never the one on screen.
const settings = useSettings.getState().settings
@@ -10630,35 +10658,34 @@ export function Canvas() {
const h = (node.height as number) ?? 440
const at = nextFreePosition(stored, { width: w, height: h })
node.position = { x: at.x - w / 2, y: at.y - h / 2 }
+ // Written ALREADY CLAIMED (the #925 write-ahead claim, manualOnly): in the same tick as the
+ // node, so there is no window in which opening the project could auto-start it beside the
+ // headless start, and whatever the headless start answers, the node never becomes armed
+ // to start by itself later — past a Pause, past a restart.
+ const [armed] = flowToNodeStates([armForColdOpen(node)])
st.applyOwnNodeMutation(project.id, {
op: 'upsert',
- node: flowToNodeStates([armForColdOpen(node)])[0]
+ node: armed.pendingLaunch ? { ...armed, pendingLaunch: claimForHeadless(armed.pendingLaunch) } : armed
})
fileIssueSession(entry.columnId, entry.ref, { node, projectId: project.id }, agentId)
- await writeDisk()
nodeId = node.id
const held = useProjects.getState().getProject(project.id)?.nodes.find((n) => n.id === nodeId)
- // The Server Edition has no headless launcher (`pty.launchHeadless` is desktop-only): the
- // armed node starts when that project is next viewed, and the notice says so.
- if (held?.pendingLaunch && isBrowserRuntime()) {
- setNotice({
- kind: 'info',
- sticky: true,
- text: `Dispatched #${entry.number} in "${project.name}". It starts when you open that project.`,
- action: { label: 'Go there', run: () => travelToNodeRef.current(nodeId) }
- })
- } else if (held?.pendingLaunch) {
+ if (held?.pendingLaunch) {
const fresh = useProjects.getState().getProject(project.id) ?? project
const batch = await startNodesHeadlessRef.current(fresh, [held])
const outcome = batch.outcomes[0]
if (outcome && !outcome.started) {
+ // Every failure leaves the pre-claimed launch waiting for Run now (never armed): the
+ // node keeps the issue's one run until it is run or closed.
setNotice({
- kind: 'info',
+ kind: 'error',
sticky: true,
- text: `Dispatched #${entry.number} in "${project.name}", but it could not start in the background (${outcome.reason}). It starts when you open that project.`,
+ text: `Dispatched #${entry.number} in "${project.name}", but it could not start (${outcome.reason}). Use Run now on its node, or close the node to dispatch the issue again.`,
action: { label: 'Go there', run: () => travelToNodeRef.current(nodeId) }
})
}
+ } else {
+ void writeDisk()
}
}
const done = useBoardDispatch.getState()
@@ -10700,7 +10727,8 @@ export function Canvas() {
dispatch,
project: project ? { remote: !!project.ssh, relay: !!project.remote } : undefined,
completionColumnId: project?.kanban?.github?.completionColumnId,
- agentKnown: dispatchAgentKnown(config.agentId),
+ bindingNow: dispatchBindingNow(project, config.columnId, ref),
+ agentDispatchable: dispatchAgentOk(config.agentId),
boundRuns: key ? dispatchBoundRuns(key) : 0,
queuedOrStarting: current?.status === 'queued' || current?.status === 'starting',
occupying: dispatchOccupying(projectId)
@@ -10726,7 +10754,9 @@ export function Canvas() {
'queued',
now
)
- if (decision.kind === 'queue') {
+ // Over the cap — or a project that left the screen during the move's round trip in a runtime
+ // that cannot start it off screen (the drain starts it when it is shown again).
+ if (decision.kind === 'queue' || !dispatchStartableNow(projectId)) {
useBoardDispatch.getState().put(entry)
return
}
@@ -10735,7 +10765,36 @@ export function Canvas() {
[dispatchBoundRuns, dispatchOccupying, dispatchStart]
)
- /** Start what the queue's free slots allow, and drop entries whose project stopped dispatching. */
+ /** The card as the host's issue list for the dispatch column holds it now (a local read of the
+ * host's cache — no GitHub request). A failed read is `unreadable`, never absence. */
+ const dispatchReadCard = useCallback(
+ async (projectId: string, columnId: string, number: number): Promise<QueuedCardFact> => {
+ try {
+ let cursor: string | undefined
+ for (let page = 0; page < 10; page++) {
+ const res = await api.githubIssues.query({
+ projectId,
+ columnId,
+ pageSize: 50,
+ search: String(number),
+ ...(cursor ? { cursor } : {})
+ })
+ const hit = res.items.find((i) => i.number === number)
+ if (hit) return { kind: 'found', state: hit.state, columnId: hit.columnId }
+ if (!res.nextCursor) return { kind: 'absent' }
+ cursor = res.nextCursor
+ }
+ return { kind: 'unreadable' }
+ } catch {
+ return { kind: 'unreadable' }
+ }
+ },
+ [api]
+ )
+
+ /** Start what the queue's free slots allow, re-checking each issue first; drop entries whose
+ * project stopped dispatching. Called ONLY by the drain timer below. */
+ const dispatchRechecking = useRef(new Set<string>())
const drainDispatchQueue = useCallback(() => {
const dispatch = sanitizeBoardDispatch(useSettings.getState().settings.boardDispatch)
const queue = useBoardDispatch.getState().queue()
@@ -10745,27 +10804,59 @@ export function Canvas() {
useBoardDispatch.getState().put({
...entry,
status: 'refused',
- reason: dispatch.paused ? DISPATCH_REFUSAL_TEXT.paused : 'Dispatch was switched off for this project.'
+ reason: DISPATCH_REFUSAL_TEXT[dispatch.paused ? 'paused' : 'switched-off']
})
}
- for (const e of queueToStart(useBoardDispatch.getState().queue(), dispatch, dispatchOccupying)) {
- const entry = useBoardDispatch.getState().byKey[e.key]
- const config = dispatch.projects[e.projectId]
- if (!entry || !config) continue
- // The issue may have gained a run by hand while it waited.
- if (dispatchBoundRuns(e.key) > 0) {
- useBoardDispatch.getState().remove(e.key)
- continue
- }
- void dispatchStart(entry, config)
+ const candidates = queueToStart(
+ useBoardDispatch.getState().queue().filter((e) => !dispatchRechecking.current.has(e.key)),
+ dispatch,
+ dispatchOccupying,
+ (e) => dispatchStartableNow(e.projectId)
+ )
+ for (const e of candidates) {
+ dispatchRechecking.current.add(e.key)
+ void (async () => {
+ try {
+ const project = useProjects.getState().getProject(e.projectId)
+ const config = dispatch.projects[e.projectId]
+ const card = config ? await dispatchReadCard(e.projectId, config.columnId, e.number) : ({ kind: 'unreadable' } as const)
+ // Everything re-read AFTER the await: settings, the project and the queue entry itself.
+ const now = sanitizeBoardDispatch(useSettings.getState().settings.boardDispatch)
+ const cfg = now.projects[e.projectId]
+ const entry = useBoardDispatch.getState().byKey[e.key]
+ if (!entry || entry.status !== 'queued') return
+ const verdict = recheckQueued({
+ config: cfg,
+ paused: now.paused,
+ project: project ? { remote: !!project.ssh, relay: !!project.remote, closed: !!project.closed } : undefined,
+ bindingNow: cfg ? dispatchBindingNow(useProjects.getState().getProject(e.projectId), cfg.columnId, e.ref) : undefined,
+ agentDispatchable: cfg ? dispatchAgentOk(cfg.agentId) : false,
+ card
+ })
+ if (verdict.kind === 'wait') return
+ if (verdict.kind === 'drop') {
+ useBoardDispatch.getState().put({ ...entry, status: 'refused', reason: DISPATCH_REFUSAL_TEXT[verdict.reason] })
+ return
+ }
+ // The issue may have gained a run by hand while it waited.
+ if (dispatchBoundRuns(e.key) > 0) {
+ useBoardDispatch.getState().remove(e.key)
+ return
+ }
+ if (cfg) await dispatchStart(entry, cfg)
+ } finally {
+ dispatchRechecking.current.delete(e.key)
+ }
+ })()
}
- }, [dispatchOccupying, dispatchBoundRuns, dispatchStart])
+ }, [dispatchOccupying, dispatchBoundRuns, dispatchStart, dispatchReadCard])
const drainDispatchQueueRef = useRef(drainDispatchQueue)
useEffect(() => {
drainDispatchQueueRef.current = drainDispatchQueue
})
// Re-checked on a short timer ONLY while something is queued (a slot frees when a run's turn
- // ends, which no single store change says cheaply), and on every settings change (pause, off).
+ // ends, which no single store change says cheaply), on every settings change (pause, off), and
+ // on a project switch (the browser starts only the project on screen).
const dispatchQueued = useBoardDispatch((s) => Object.values(s.byKey).some((e) => e.status === 'queued'))
const boardDispatchSettings = useSettings((s) => s.settings.boardDispatch)
useEffect(() => {
@@ -10773,7 +10864,7 @@ export function Canvas() {
drainDispatchQueueRef.current()
const timer = setInterval(() => drainDispatchQueueRef.current(), DISPATCH_DRAIN_MS)
return () => clearInterval(timer)
- }, [dispatchQueued, boardDispatchSettings])
+ }, [dispatchQueued, boardDispatchSettings, activeProjectId])
// ---- GitHub issue → agent session in its OWN worktree ("Start with agent in a new worktree ▸") ----
/** The reuse-or-new question, when the issue already has a worktree (or its branch exists). */
diff --git a/src/renderer/components/settings/sections/GitHubIssuesSection.tsx b/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
index 3b9304b5e..ee25ff655 100644
--- a/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
+++ b/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
@@ -13,11 +13,13 @@ import { prunePullAutoMove, sanitizeKanbanPullAutoMove } from '@shared/kanban-pu
import {
BOARD_DISPATCH_DEFAULT_CONCURRENT,
BOARD_DISPATCH_MAX_CONCURRENT,
+ dispatchBinding,
pruneBoardDispatch,
sanitizeBoardDispatch,
type BoardDispatchProject
} from '@shared/board-dispatch'
import { AGENT_CONFIG, BUILTIN_AGENT_IDS } from '@shared/agents/config'
+import { dispatchableAgent } from '../../../lib/boardDispatch'
import { markWorkspaceDirty } from '../../../state/workspaceDirty'
import { SAVE_DEBOUNCE_MS } from '../../../lib/savePersistence'
import { SettingsSection } from '../SettingsSection'
@@ -177,7 +179,17 @@ export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.
/** Machine-local on purpose (see @shared/board-dispatch): a repository can never switch this on
* for anyone. `patch: null` switches the project off, `undefined` leaves it as it is (the kill
* switch alone). Every write prunes vanished projects. */
+ const [dispatchNotice, setDispatchNotice] = useState('')
+ /** What the person consents to when they pick a column: the repository and the column's title
+ * and GitHub label as they are NOW (@shared/board-dispatch `binding`). */
+ const dispatchBindingFor = (columnId: string): string | undefined =>
+ dispatchBinding(
+ repository,
+ board?.columns.find((column) => column.id === columnId)?.title,
+ githubConfig?.columnMappings.find((mapping) => mapping.columnId === columnId)?.label
+ )
const setDispatch = (patch: Partial<BoardDispatchProject> | null | undefined, paused?: boolean): void => {
+ setDispatchNotice('')
const live = new Set(useProjects.getState().projects.map((item) => item.id))
const current = pruneBoardDispatch(
sanitizeBoardDispatch(useSettings.getState().settings.boardDispatch), live)
@@ -187,23 +199,36 @@ export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.
const base: BoardDispatchProject = projects[projectId] ?? {
columnId: '',
agentId: 'claude',
- maxConcurrent: BOARD_DISPATCH_DEFAULT_CONCURRENT
+ maxConcurrent: BOARD_DISPATCH_DEFAULT_CONCURRENT,
+ binding: ''
}
const next = { ...base, ...patch }
if (!next.accountId) delete next.accountId
- if (next.columnId) projects[projectId] = next
+ // Choosing (or re-confirming) a column is the consent: bind it to what the column means now.
+ // Changing only the agent or the cap keeps the binding the person gave.
+ if (patch.columnId !== undefined || patch.binding !== undefined) {
+ const binding = dispatchBindingFor(next.columnId)
+ if (!binding) {
+ setDispatchNotice('That column has no GitHub label or the repository is not known yet, so dispatch cannot be switched on for it.')
+ return
+ }
+ next.binding = binding
+ }
+ if (next.columnId && next.binding) projects[projectId] = next
}
updateSettings({ boardDispatch: { paused: paused ?? current.paused, projects } })
}
+ // Only agents that report their state through hooks: the cap counts sessions by that state.
const dispatchAgentOptions = [
...BUILTIN_AGENT_IDS.map((id) => ({ id: id as string, label: AGENT_CONFIG[id].label })),
...customAgents.map((agent) => ({ id: agent.id, label: agent.label }))
- ]
+ ].filter((agent) => dispatchableAgent(agent.id, true))
const dispatchAccountOptions = dispatchConfig?.agentId === 'claude'
? claudeAccounts.filter((a) => !a.host && !a.pending).map((a) => ({ id: a.id, label: a.label }))
: dispatchConfig?.agentId === 'codex'
? codexAccounts.filter((a) => !a.host && !a.pending).map((a) => ({ id: a.id, label: a.label }))
: []
+ const dispatchStale = !!dispatchConfig && dispatchBindingFor(dispatchConfig.columnId) !== dispatchConfig.binding
/** `GitHubHostController.status(projectId)` MASKS the auth block for a project that is not
* approved on this machine (`ghAuthenticated: false, activeProvider: null, tokenPresent: false`)
@@ -721,6 +746,16 @@ export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.
</Select>
}
/>
+ {dispatchNotice && <p role="status" className="text-[13px] text-warn">{dispatchNotice}</p>}
+ {dispatchStale && dispatchConfig && (
+ <div className="flex flex-wrap items-center gap-2" role="status">
+ <p className="text-[13px] text-warn">
+ The dispatch column, its GitHub label or the repository changed since you switched this on
+ (possibly through a pulled project file). Nothing dispatches until you confirm it again.
+ </p>
+ <Button onClick={() => setDispatch({ binding: '' })}>Re-confirm this column</Button>
+ </div>
+ )}
{dispatchConfig && (
<>
<FieldRow
@@ -759,7 +794,7 @@ export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.
<FieldRow
label="Runs at once"
htmlFor="github-dispatch-cap"
- description="Sessions of this project that are working or waiting on you. More dispatches wait in a queue shown on their cards."
+ description="Sessions of this project that are working or waiting on you. More dispatches wait in a queue shown on their cards. Dispatched runs work in the project's own folder, so more than one at a time means several agents editing one checkout."
control={
<Select
id="github-dispatch-cap"
diff --git a/src/renderer/lib/board-dispatch.guard.test.ts b/src/renderer/lib/board-dispatch.guard.test.ts
index b1969050d..22f546657 100644
--- a/src/renderer/lib/board-dispatch.guard.test.ts
+++ b/src/renderer/lib/board-dispatch.guard.test.ts
@@ -21,10 +21,35 @@ const src = files(ROOT).map((p) => ({ p: p.slice(ROOT.length + 1), text: readFil
function sitesOf(pattern: RegExp): string[] {
return src.flatMap(({ p, text }) =>
- text.split('\n').flatMap((line) => (pattern.test(line) && !/^\s*(\/\/|\*)/.test(line) ? [p] : []))
+ text.split('\n').flatMap((line) => (pattern.test(line) && !/^\s*(\/\/|\/?\*)/.test(line) ? [p] : []))
)
}
+const CANVAS = () => src.find((f) => f.p === 'canvas/Canvas.tsx')!.text
+
+/** The body of a top-level `const <name> = useCallback(` in Canvas: up to the next 2-space `const`. */
+function bodyOf(name: string): { start: number; end: number } {
+ const text = CANVAS()
+ const start = text.indexOf(` const ${name} = useCallback`)
+ expect(start, name).toBeGreaterThan(-1)
+ const next = text.slice(start + 1).search(/\n {2}const /)
+ return { start, end: next === -1 ? text.length : start + 1 + next }
+}
+
+/** Offsets of non-comment lines matching `pattern` in Canvas. */
+function canvasHits(pattern: RegExp): number[] {
+ const text = CANVAS()
+ const out: number[] = []
+ let at = 0
+ for (const line of text.split('\n')) {
+ if (pattern.test(line) && !/^\s*(\/\/|\/?\*)/.test(line)) out.push(at)
+ at += line.length + 1
+ }
+ return out
+}
+
+const inside = (offset: number, r: { start: number; end: number }) => offset >= r.start && offset < r.end
+
describe('board dispatch: the trigger is the person\'s own move, and nothing else', () => {
it("only Canvas's dispatchOnUserMove asks decideDispatch, and only with origin 'user-move'", () => {
expect(sitesOf(/decideDispatch\(/)).toEqual(['canvas/Canvas.tsx', 'lib/boardDispatch.ts'])
@@ -39,7 +64,7 @@ describe('board dispatch: the trigger is the person\'s own move, and nothing els
const canvas = src.find((f) => f.p === 'canvas/Canvas.tsx')!.text
const uses = canvas
.split('\n')
- .filter((l) => /dispatchOnUserMove\b/.test(l) && !/const dispatchOnUserMove/.test(l) && !/^\s*(\/\/|\*)/.test(l))
+ .filter((l) => /dispatchOnUserMove\b/.test(l) && !/const dispatchOnUserMove/.test(l) && !/^\s*(\/\/|\/?\*)/.test(l))
expect(uses.map((l) => l.trim())).toEqual(['onIssueMoved={dispatchOnUserMove}'])
})
@@ -57,6 +82,35 @@ describe('board dispatch: the trigger is the person\'s own move, and nothing els
])
})
+ it('dispatchStart is called only from dispatchOnUserMove (after decideDispatch) and the queue drain', () => {
+ const calls = canvasHits(/\bdispatchStart\(/).filter((o) => !CANVAS().startsWith(' const dispatchStart', o))
+ const onMove = bodyOf('dispatchOnUserMove')
+ const drain = bodyOf('drainDispatchQueue')
+ expect(calls).toHaveLength(2)
+ expect(calls.filter((o) => inside(o, onMove))).toHaveLength(1)
+ expect(calls.filter((o) => inside(o, drain))).toHaveLength(1)
+ // Inside dispatchOnUserMove the start comes AFTER the decision.
+ const text = CANVAS()
+ expect(text.indexOf('decideDispatch(', onMove.start)).toBeLessThan(calls.find((o) => inside(o, onMove))!)
+ // And the drain starts nothing without re-asking recheckQueued first.
+ expect(text.indexOf('recheckQueued(', drain.start)).toBeGreaterThan(drain.start)
+ expect(text.indexOf('recheckQueued(', drain.start)).toBeLessThan(calls.find((o) => inside(o, drain))!)
+ })
+
+ it("a 'queued' entry — which the drain starts — is created only by dispatchOnUserMove", () => {
+ // Every line that PUTS a 'queued' status (not a comparison) must sit inside dispatchOnUserMove.
+ const puts = canvasHits(/'queued'/).filter((o) => {
+ const line = CANVAS().slice(o, CANVAS().indexOf('\n', o))
+ return !/[=!]==\s*'queued'|'queued'\s*[=!]==/.test(line)
+ })
+ const onMove = bodyOf('dispatchOnUserMove')
+ expect(puts.length).toBeGreaterThan(0)
+ expect(puts.every((o) => inside(o, onMove))).toBe(true)
+ // Nobody else in the renderer writes the dispatch store.
+ expect(sitesOf(/useBoardDispatch\.getState\(\)\.put\(|\.put\(\s*dispatchEntry/).every((p) => p === 'canvas/Canvas.tsx')).toBe(true)
+ expect(sitesOf(/useBoardDispatch\.setState/)).toEqual([])
+ })
+
it('the refresh / sync code never reaches the dispatcher', () => {
for (const file of ['state/githubIssues.ts']) {
const text = src.find((f) => f.p === file)!.text
diff --git a/src/renderer/lib/boardDispatch.test.ts b/src/renderer/lib/boardDispatch.test.ts
index 6492af184..a8e7a16c0 100644
--- a/src/renderer/lib/boardDispatch.test.ts
+++ b/src/renderer/lib/boardDispatch.test.ts
@@ -1,9 +1,12 @@
import { describe, expect, it } from 'vitest'
-import { sanitizeBoardDispatch } from '@shared/board-dispatch'
+import { dispatchBinding, sanitizeBoardDispatch } from '@shared/board-dispatch'
import {
DISPATCH_STARTUP_GRACE_MS,
decideDispatch,
+ dispatchableAgent,
moveWithdrawsDispatch,
+ recheckQueued,
+ type RecheckInput,
occupiesSlot,
queueToDrop,
queueToStart,
@@ -12,8 +15,9 @@ import {
type DispatchTrigger
} from './boardDispatch'
+const BINDING = dispatchBinding('acme/app', 'Agent', 'status:agent')!
const dispatch = sanitizeBoardDispatch({
- projects: { p1: { columnId: 'agent-col', agentId: 'claude', maxConcurrent: 2 } }
+ projects: { p1: { columnId: 'agent-col', agentId: 'claude', maxConcurrent: 2, binding: BINDING } }
})
function trigger(over: Partial<DispatchTrigger> = {}): DispatchTrigger {
@@ -32,7 +36,8 @@ function ctx(over: Partial<DispatchContext> = {}): DispatchContext {
dispatch,
project: { remote: false, relay: false },
completionColumnId: 'done',
- agentKnown: true,
+ bindingNow: BINDING,
+ agentDispatchable: true,
boundRuns: 0,
queuedOrStarting: false,
occupying: 0,
@@ -72,13 +77,13 @@ describe('decideDispatch — who may trigger a run', () => {
})
it('the kill switch refuses, and says so', () => {
- const paused = sanitizeBoardDispatch({ paused: true, projects: { p1: { columnId: 'agent-col', agentId: 'claude' } } })
+ const paused = sanitizeBoardDispatch({ paused: true, projects: { p1: { columnId: 'agent-col', agentId: 'claude', binding: BINDING } } })
expect(decideDispatch(trigger(), ctx({ dispatch: paused }))).toEqual({ kind: 'refuse', reason: 'paused' })
})
it('refuses a relay tab, an SSH project, a closed issue, an unreadable address and a missing agent', () => {
expect(decideDispatch(trigger(), ctx({ project: { remote: false, relay: true } }))).toMatchObject({ reason: 'relay' })
- expect(decideDispatch(trigger(), ctx({ project: undefined }))).toMatchObject({ reason: 'relay' })
+ expect(decideDispatch(trigger(), ctx({ project: undefined }))).toMatchObject({ reason: 'project-gone' })
expect(decideDispatch(trigger(), ctx({ project: { remote: true, relay: false } }))).toMatchObject({ reason: 'remote-project' })
expect(decideDispatch(trigger({ issue: { number: 7, htmlUrl: 'https://github.com/acme/app/issues/7', state: 'closed' } }), ctx()))
.toMatchObject({ reason: 'issue-closed' })
@@ -86,7 +91,7 @@ describe('decideDispatch — who may trigger a run', () => {
.toMatchObject({ reason: 'no-reference' })
expect(decideDispatch(trigger({ issue: { number: 8, htmlUrl: 'https://github.com/acme/app/issues/7', state: 'open' } }), ctx()))
.toMatchObject({ reason: 'no-reference' })
- expect(decideDispatch(trigger(), ctx({ agentKnown: false }))).toMatchObject({ reason: 'agent-unavailable' })
+ expect(decideDispatch(trigger(), ctx({ agentDispatchable: false }))).toMatchObject({ reason: 'agent-unavailable' })
})
it('refuses a dispatch column that is also the completion column', () => {
@@ -124,8 +129,8 @@ describe('occupiesSlot', () => {
describe('queue', () => {
const two = sanitizeBoardDispatch({
projects: {
- p1: { columnId: 'c', agentId: 'claude', maxConcurrent: 2 },
- p2: { columnId: 'c', agentId: 'claude', maxConcurrent: 1 }
+ p1: { columnId: 'c', agentId: 'claude', maxConcurrent: 2, binding: 'b' },
+ p2: { columnId: 'c', agentId: 'claude', maxConcurrent: 1, binding: 'b' }
}
})
const entry = (key: string, projectId: string, queuedAt: number): DispatchQueueEntry => ({
@@ -144,11 +149,15 @@ describe('queue', () => {
expect(queueToStart(queue, two, () => 9)).toEqual([])
})
+ it('an entry that may not start now (the browser, off screen) is skipped and takes no slot', () => {
+ expect(queueToStart(queue, two, () => 0, (e) => e.projectId === 'p2').map((e) => e.key)).toEqual(['y1'])
+ })
+
it('the kill switch starts nothing and drops everything; an opted-out project is dropped', () => {
const paused = { ...two, paused: true }
expect(queueToStart(queue, paused, () => 0)).toEqual([])
expect(queueToDrop(queue, paused)).toHaveLength(queue.length)
- const onlyP1 = sanitizeBoardDispatch({ projects: { p1: { columnId: 'c', agentId: 'claude' } } })
+ const onlyP1 = sanitizeBoardDispatch({ projects: { p1: { columnId: 'c', agentId: 'claude', binding: 'b' } } })
expect(queueToStart(queue, onlyP1, () => 0).every((e) => e.projectId === 'p1')).toBe(true)
expect(queueToDrop(queue, onlyP1).map((e) => e.key).sort()).toEqual(['y1', 'y2'])
})
@@ -164,3 +173,64 @@ describe('moveWithdrawsDispatch', () => {
expect(moveWithdrawsDispatch(trigger({ toColumnId: 'other', projectId: 'p9' }), dispatch)).toBe(false)
})
})
+
+describe('consent binding — what the column MEANS is git-shared', () => {
+ it('a pulled commit that swaps column titles turns a routine drag into nothing, not a dispatch', () => {
+ // The person consented to the column titled "Agent" with label status:agent. After the pull,
+ // the same column id is titled "In Progress".
+ const swapped = dispatchBinding('acme/app', 'In Progress', 'status:agent')
+ expect(decideDispatch(trigger(), ctx({ bindingNow: swapped }))).toEqual({ kind: 'refuse', reason: 'consent-stale' })
+ const relabelled = dispatchBinding('acme/app', 'Agent', 'status:in-progress')
+ expect(decideDispatch(trigger(), ctx({ bindingNow: relabelled }))).toMatchObject({ reason: 'consent-stale' })
+ })
+
+ it('a board re-pointed at another repository refuses until re-confirmed', () => {
+ const other = dispatchBinding('someone/else', 'Agent', 'status:agent')
+ expect(decideDispatch(trigger(), ctx({ bindingNow: other }))).toMatchObject({ reason: 'consent-stale' })
+ expect(decideDispatch(trigger(), ctx({ bindingNow: undefined }))).toMatchObject({ reason: 'consent-stale' })
+ // Repository case does not matter (GitHub names are case-insensitive).
+ expect(decideDispatch(trigger(), ctx({ bindingNow: dispatchBinding('ACME/App', 'Agent', 'status:agent') })).kind).toBe('start')
+ })
+})
+
+describe('dispatchableAgent', () => {
+ it('only an agent that exists AND reports status through hooks (a hookless one would break the cap)', () => {
+ expect(dispatchableAgent('claude', true)).toBe(true)
+ expect(dispatchableAgent('claude', false)).toBe(false)
+ expect(dispatchableAgent('custom:no-base-agent', true)).toBe(false)
+ })
+})
+
+describe('recheckQueued — a queued dispatch is re-asked before it starts', () => {
+ const config = dispatch.projects.p1
+ const ok: RecheckInput = {
+ config,
+ paused: false,
+ project: { remote: false, relay: false, closed: false },
+ bindingNow: BINDING,
+ agentDispatchable: true,
+ card: { kind: 'found', state: 'open', columnId: 'agent-col' }
+ }
+ it('starts only when everything still holds', () => {
+ expect(recheckQueued(ok)).toEqual({ kind: 'start' })
+ })
+ it('a teammate closing or moving the issue while it waited drops it', () => {
+ expect(recheckQueued({ ...ok, card: { kind: 'found', state: 'closed', columnId: 'agent-col' } }))
+ .toEqual({ kind: 'drop', reason: 'issue-closed' })
+ expect(recheckQueued({ ...ok, card: { kind: 'found', state: 'open', columnId: 'other' } }))
+ .toEqual({ kind: 'drop', reason: 'not-in-column' })
+ expect(recheckQueued({ ...ok, card: { kind: 'absent' } })).toEqual({ kind: 'drop', reason: 'not-in-column' })
+ })
+ it('an unreadable card waits — a failed read is never evidence', () => {
+ expect(recheckQueued({ ...ok, card: { kind: 'unreadable' } })).toEqual({ kind: 'wait' })
+ })
+ it('consent, agent, project and the kill switch are re-asked too', () => {
+ expect(recheckQueued({ ...ok, paused: true })).toMatchObject({ reason: 'paused' })
+ expect(recheckQueued({ ...ok, config: undefined })).toMatchObject({ reason: 'switched-off' })
+ expect(recheckQueued({ ...ok, bindingNow: 'x' })).toMatchObject({ reason: 'consent-stale' })
+ expect(recheckQueued({ ...ok, agentDispatchable: false })).toMatchObject({ reason: 'agent-unavailable' })
+ expect(recheckQueued({ ...ok, project: undefined })).toMatchObject({ reason: 'project-gone' })
+ expect(recheckQueued({ ...ok, project: { remote: false, relay: false, closed: true } })).toMatchObject({ reason: 'project-closed' })
+ expect(recheckQueued({ ...ok, project: { remote: true, relay: false, closed: false } })).toMatchObject({ reason: 'remote-project' })
+ })
+})
diff --git a/src/renderer/lib/boardDispatch.ts b/src/renderer/lib/boardDispatch.ts
index 66a8ed8ac..e88e9fa5b 100644
--- a/src/renderer/lib/boardDispatch.ts
+++ b/src/renderer/lib/boardDispatch.ts
@@ -17,9 +17,20 @@
// (another column, a project that is not switched on, a move GitHub did not confirm), which say
// nothing.
-import type { BoardDispatch } from '@shared/board-dispatch'
+import type { BoardDispatch, BoardDispatchProject } from '@shared/board-dispatch'
import type { AgentState } from '@shared/agents/normalize'
import { issueKey, issueRefFromHtmlUrl, type IssueRef } from '@shared/github-issue-ref'
+import { capabilityAgentId, hasHooks, type AgentId } from '@shared/agents/config'
+
+/**
+ * Which agents may be dispatched: one that exists on this machine AND reports its state through
+ * hooks (resolved through its base harness, like `--after`). The cap counts sessions by their hook
+ * state; a hookless agent never reports `done` nor `working`, so after the startup grace its slot
+ * would free and the cap would admit one more run every two minutes.
+ */
+export function dispatchableAgent(agentId: string, exists: boolean): boolean {
+ return exists && hasHooks(capabilityAgentId(agentId as AgentId))
+}
export type DispatchOrigin = 'user-move' | 'sync'
@@ -43,8 +54,12 @@ export interface DispatchContext {
dispatch: BoardDispatch
project: DispatchProjectFacts | undefined
completionColumnId?: string
- /** Whether the configured agent still exists on this machine (a custom agent may be deleted). */
- agentKnown: boolean
+ /** `dispatchBinding` of the repository + dispatch column as they are NOW; must equal the one the
+ * person consented to (`BoardDispatchProject.binding`). */
+ bindingNow: string | undefined
+ /** The configured agent still exists on this machine AND reports its state through hooks
+ * (`dispatchableAgent`) — a hookless agent never reports `done`, so the cap could not hold. */
+ agentDispatchable: boolean
/** Sessions bound to this issue that still exist, in any project. */
boundRuns: number
/** This issue is already queued or starting. */
@@ -55,6 +70,11 @@ export interface DispatchContext {
export type DispatchRefusal =
| 'paused'
+ | 'project-gone'
+ | 'project-closed'
+ | 'consent-stale'
+ | 'not-in-column'
+ | 'switched-off'
| 'remote-project'
| 'relay'
| 'completion-column'
@@ -82,17 +102,21 @@ export function decideDispatch(trigger: DispatchTrigger, ctx: DispatchContext):
if (trigger.toColumnId === null || trigger.toColumnId !== config.columnId) return { kind: 'ignore' }
if (!LANDED.has(trigger.moveStatus)) return { kind: 'ignore' }
if (ctx.dispatch.paused) return { kind: 'refuse', reason: 'paused' }
- if (!ctx.project || ctx.project.relay) return { kind: 'refuse', reason: 'relay' }
+ if (!ctx.project) return { kind: 'refuse', reason: 'project-gone' }
+ if (ctx.project.relay) return { kind: 'refuse', reason: 'relay' }
if (ctx.project.remote) return { kind: 'refuse', reason: 'remote-project' }
// A dispatch column that closes the issue would start work on an issue the same move closed.
if (ctx.completionColumnId && ctx.completionColumnId === config.columnId) {
return { kind: 'refuse', reason: 'completion-column' }
}
+ // The column's meaning (title, label) and the repository must still be what the person agreed
+ // to: all three can change under the consent through a pulled project file.
+ if (!ctx.bindingNow || ctx.bindingNow !== config.binding) return { kind: 'refuse', reason: 'consent-stale' }
if (trigger.issue.state !== 'open') return { kind: 'refuse', reason: 'issue-closed' }
const ref = issueRefFromHtmlUrl(trigger.issue.htmlUrl, trigger.issue.number)
const key = issueKey(ref)
if (!ref || !key) return { kind: 'refuse', reason: 'no-reference' }
- if (!ctx.agentKnown) return { kind: 'refuse', reason: 'agent-unavailable' }
+ if (!ctx.agentDispatchable) return { kind: 'refuse', reason: 'agent-unavailable' }
// At most one run per issue: an existing bound session (whatever its state) or one already on
// its way. A second drag of the same card is a no-op that says so.
if (ctx.queuedOrStarting) return { kind: 'refuse', reason: 'already-queued' }
@@ -111,12 +135,19 @@ export function moveWithdrawsDispatch(trigger: DispatchTrigger, dispatch: BoardD
export const DISPATCH_REFUSAL_TEXT: Record<DispatchRefusal, string> = {
paused: 'Dispatch is paused on this machine.',
+ 'project-gone': 'The project is no longer open on this machine.',
+ 'project-closed': 'The project was closed.',
+ 'consent-stale':
+ 'The dispatch column, its GitHub label or the repository changed since dispatch was switched on. Re-confirm it in Settings → GitHub Issues.',
+ 'not-in-column': 'The issue left the dispatch column while it waited.',
+ 'switched-off': 'Dispatch was switched off for this project.',
'remote-project': 'Dispatch runs only on local projects for now (this is an SSH project).',
relay: 'Dispatch is managed on the host of this shared project.',
'completion-column': 'The dispatch column is also the completion column, which closes the issue.',
'issue-closed': 'The issue is closed.',
'no-reference': "The issue's GitHub address could not be read.",
- 'agent-unavailable': 'The dispatch agent is not available on this machine. Choose one in Settings.',
+ 'agent-unavailable':
+ 'The dispatch agent is not available on this machine, or does not report its status. Choose one in Settings.',
'already-running': 'This issue already has a session. Close it to dispatch again.',
'already-queued': 'This issue is already queued or starting.'
}
@@ -131,7 +162,8 @@ export const DISPATCH_STARTUP_GRACE_MS = 120_000
export interface RunSlotFact {
state?: AgentState
- /** The node still holds a launch (queued, starting). */
+ /** The node holds a launch that will start BY ITSELF (not a `manualOnly` one waiting for Run
+ * now — that node is not going to spend anything until a person asks). */
pending: boolean
/** When dispatch started it, in this app run. */
startedAt?: number
@@ -169,14 +201,17 @@ export interface DispatchQueueEntry {
export function queueToStart(
queue: readonly DispatchQueueEntry[],
dispatch: BoardDispatch,
- occupying: (projectId: string) => number
+ occupying: (projectId: string) => number,
+ /** Whether this entry may start NOW (the browser starts only the project on screen: it has no
+ * headless launcher). A skipped entry stays queued and takes no slot. */
+ startable: (entry: DispatchQueueEntry) => boolean = () => true
): DispatchQueueEntry[] {
if (dispatch.paused) return []
const free = new Map<string, number>()
const out: DispatchQueueEntry[] = []
for (const entry of [...queue].sort((a, b) => a.queuedAt - b.queuedAt)) {
const config = dispatch.projects[entry.projectId]
- if (!config) continue
+ if (!config || !startable(entry)) continue
if (!free.has(entry.projectId)) free.set(entry.projectId, config.maxConcurrent - occupying(entry.projectId))
const left = free.get(entry.projectId)!
if (left <= 0) continue
@@ -190,3 +225,45 @@ export function queueToStart(
export function queueToDrop(queue: readonly DispatchQueueEntry[], dispatch: BoardDispatch): DispatchQueueEntry[] {
return queue.filter((e) => dispatch.paused || !dispatch.projects[e.projectId])
}
+
+// ── Re-checking a queued dispatch before it starts ────────────────────────────────────────────
+
+export type QueuedCardFact =
+ | { kind: 'found'; state: 'open' | 'closed'; columnId: string | null }
+ /** The host's issue list for the dispatch column does not hold it. */
+ | { kind: 'absent' }
+ /** The host could not be asked (a failed read is never evidence of absence). */
+ | { kind: 'unreadable' }
+
+export interface RecheckInput {
+ config: BoardDispatchProject | undefined
+ paused: boolean
+ project: (DispatchProjectFacts & { closed: boolean }) | undefined
+ bindingNow: string | undefined
+ agentDispatchable: boolean
+ card: QueuedCardFact
+}
+
+export type RecheckVerdict = { kind: 'start' } | { kind: 'wait' } | { kind: 'drop'; reason: DispatchRefusal }
+
+/**
+ * A queued dispatch can wait for hours behind a full cap; by then the issue may be closed or moved
+ * by a teammate, the agent deleted, the column re-titled. Everything `decideDispatch` checked about
+ * the ISSUE and the CONSENT is asked again right before the run starts. Only an unreadable card
+ * waits (and is asked again on the next drain); every other change drops the entry with its reason.
+ */
+export function recheckQueued(input: RecheckInput): RecheckVerdict {
+ if (input.paused) return { kind: 'drop', reason: 'paused' }
+ if (!input.config) return { kind: 'drop', reason: 'switched-off' }
+ if (!input.project) return { kind: 'drop', reason: 'project-gone' }
+ if (input.project.relay) return { kind: 'drop', reason: 'relay' }
+ if (input.project.remote) return { kind: 'drop', reason: 'remote-project' }
+ if (input.project.closed) return { kind: 'drop', reason: 'project-closed' }
+ if (!input.bindingNow || input.bindingNow !== input.config.binding) return { kind: 'drop', reason: 'consent-stale' }
+ if (!input.agentDispatchable) return { kind: 'drop', reason: 'agent-unavailable' }
+ if (input.card.kind === 'unreadable') return { kind: 'wait' }
+ if (input.card.kind === 'absent') return { kind: 'drop', reason: 'not-in-column' }
+ if (input.card.state !== 'open') return { kind: 'drop', reason: 'issue-closed' }
+ if (input.card.columnId !== input.config.columnId) return { kind: 'drop', reason: 'not-in-column' }
+ return { kind: 'start' }
+}
diff --git a/src/shared/board-dispatch.test.ts b/src/shared/board-dispatch.test.ts
index b16151167..9865f722d 100644
--- a/src/shared/board-dispatch.test.ts
+++ b/src/shared/board-dispatch.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest'
import {
+ BOARD_DISPATCH_DEFAULT_CONCURRENT,
BOARD_DISPATCH_MAX_CONCURRENT,
+ dispatchBinding,
clampConcurrent,
pruneBoardDispatch,
sanitizeBoardDispatch
@@ -16,26 +18,28 @@ describe('sanitizeBoardDispatch (settings.json is hand-editable)', () => {
it('keeps a well-formed entry', () => {
const out = sanitizeBoardDispatch({
paused: false,
- projects: { p1: { columnId: 'col-a', agentId: 'claude', accountId: 'acc1', maxConcurrent: 3 } }
+ projects: { p1: { columnId: 'col-a', agentId: 'claude', accountId: 'acc1', maxConcurrent: 3, binding: 'b' } }
})
- expect(out.projects.p1).toEqual({ columnId: 'col-a', agentId: 'claude', accountId: 'acc1', maxConcurrent: 3 })
+ expect(out.projects.p1).toEqual({ columnId: 'col-a', agentId: 'claude', accountId: 'acc1', maxConcurrent: 3, binding: 'b' })
})
- it('drops an entry with no column or an unsafe agent id — it is OFF, never guessed', () => {
+ it('drops an entry with no column, an unsafe agent id or no consent binding — it is OFF, never guessed', () => {
const out = sanitizeBoardDispatch({
projects: {
- a: { agentId: 'claude', maxConcurrent: 1 },
- b: { columnId: 'c', agentId: 'claude; rm -rf ~' },
- c: { columnId: 'c', agentId: 42 },
- d: { columnId: 'c', agentId: 'custom:3f2a' }
+ a: { agentId: 'claude', maxConcurrent: 1, binding: 'b' },
+ b: { columnId: 'c', agentId: 'claude; rm -rf ~', binding: 'b' },
+ c: { columnId: 'c', agentId: 42, binding: 'b' },
+ d: { columnId: 'c', agentId: 'custom:3f2a', binding: 'b' },
+ e: { columnId: 'c', agentId: 'claude' },
+ f: { columnId: 'c', agentId: 'claude', binding: 7 }
}
})
expect(Object.keys(out.projects)).toEqual(['d'])
})
it('drops an unsafe account id but keeps the entry (project default)', () => {
- const out = sanitizeBoardDispatch({ projects: { p: { columnId: 'c', agentId: 'codex', accountId: '../x' } } })
- expect(out.projects.p).toEqual({ columnId: 'c', agentId: 'codex', maxConcurrent: 1 })
+ const out = sanitizeBoardDispatch({ projects: { p: { columnId: 'c', agentId: 'codex', accountId: '../x', binding: 'b' } } })
+ expect(out.projects.p).toEqual({ columnId: 'c', agentId: 'codex', maxConcurrent: 1, binding: 'b' })
})
it('clamps the cap DOWN on anything unreadable, and never above the max', () => {
@@ -58,10 +62,23 @@ describe('pruneBoardDispatch', () => {
it('drops projects this machine no longer has, keeps the switch', () => {
const value = sanitizeBoardDispatch({
paused: true,
- projects: { keep: { columnId: 'c', agentId: 'claude' }, gone: { columnId: 'c', agentId: 'claude' } }
+ projects: { keep: { columnId: 'c', agentId: 'claude', binding: 'b' }, gone: { columnId: 'c', agentId: 'claude', binding: 'b' } }
})
const out = pruneBoardDispatch(value, new Set(['keep']))
expect(out.paused).toBe(true)
expect(Object.keys(out.projects)).toEqual(['keep'])
})
})
+
+describe('dispatchBinding / default cap', () => {
+ it('binds repository (case-insensitive), column title and label; any unknown part is no binding', () => {
+ expect(dispatchBinding('Acme/App', 'Agent', 'status:agent')).toBe(dispatchBinding('acme/app', 'Agent', 'status:agent'))
+ expect(dispatchBinding('acme/app', 'Agent', 'status:agent')).not.toBe(dispatchBinding('acme/app', 'In Progress', 'status:agent'))
+ expect(dispatchBinding(undefined, 'Agent', 'status:agent')).toBeUndefined()
+ expect(dispatchBinding('acme/app', undefined, 'status:agent')).toBeUndefined()
+ expect(dispatchBinding('acme/app', 'Agent', undefined)).toBeUndefined()
+ })
+ it('defaults to one run at a time: dispatched runs share one checkout', () => {
+ expect(BOARD_DISPATCH_DEFAULT_CONCURRENT).toBe(1)
+ })
+})
diff --git a/src/shared/board-dispatch.ts b/src/shared/board-dispatch.ts
index 098592bbc..9656b8c0c 100644
--- a/src/shared/board-dispatch.ts
+++ b/src/shared/board-dispatch.ts
@@ -14,7 +14,10 @@
// nothing, because no project is switched on.
export const BOARD_DISPATCH_MAX_CONCURRENT = 8
-export const BOARD_DISPATCH_DEFAULT_CONCURRENT = 2
+/** One by default: a dispatched run is told to implement the fix IN THIS WORKING TREE, and two at
+ * once would be two agents editing one checkout. Raise it only for a project whose issues do not
+ * collide (or whose agents work in their own worktrees). */
+export const BOARD_DISPATCH_DEFAULT_CONCURRENT = 1
export interface BoardDispatchProject {
/** The column a card must be dragged INTO. A column deleted since then dispatches nothing. */
@@ -25,6 +28,15 @@ export interface BoardDispatchProject {
accountId?: string
/** Live runs this project may have at once; further dispatches queue. 1..8. */
maxConcurrent: number
+ /**
+ * What the person consented to, not just which id: the repository and the column's TITLE and
+ * GitHub LABEL at the moment they chose it (`dispatchBinding`). The column's title and label live
+ * in the git-shared project file (and titles are deliberately outside the GitHub mapping
+ * approval), so a pulled commit could otherwise turn the person's routine drag into "In Progress"
+ * into a dispatch by swapping two titles, or re-point the board at another repository. Any
+ * difference refuses until the person re-confirms in Settings.
+ */
+ binding: string
}
export interface BoardDispatch {
@@ -64,8 +76,11 @@ export function sanitizeBoardDispatch(raw: unknown): BoardDispatch {
: null
if (!projectKey(projectId) || !entry) continue
if (!projectKey(entry.columnId) || !safeId(entry.agentId)) continue
+ // No binding = nothing was consented to that can be checked: OFF.
+ if (typeof entry.binding !== 'string' || !entry.binding || entry.binding.length > 2048) continue
projects[projectId] = {
columnId: entry.columnId,
+ binding: entry.binding,
agentId: entry.agentId,
...(safeId(entry.accountId) ? { accountId: entry.accountId } : {}),
maxConcurrent: clampConcurrent(entry.maxConcurrent)
@@ -81,3 +96,17 @@ export function pruneBoardDispatch(value: BoardDispatch, liveProjectIds: Readonl
projects: Object.fromEntries(Object.entries(value.projects).filter(([id]) => liveProjectIds.has(id)))
}
}
+
+/**
+ * The consent binding for a dispatch column: repository (case-insensitive, as GitHub names are),
+ * the column's title and the label it maps to on GitHub. `undefined` when any part is unknown —
+ * which can never match a stored binding, so an unknown refuses.
+ */
+export function dispatchBinding(
+ repository: string | undefined,
+ columnTitle: string | undefined,
+ columnLabel: string | undefined
+): string | undefined {
+ if (!repository || columnTitle === undefined || !columnLabel) return undefined
+ return JSON.stringify([repository.trim().toLowerCase(), columnTitle, columnLabel])
+}