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(kanban): board dispatch — a card you move into the dispatch column starts its own agent run

review9262bdbcec79
diff --git a/CLAUDE.md b/CLAUDE.md
index 11a32ad80..a90275874 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6311,6 +6311,62 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
already has one — see the Worktrees bullet ("A worktree per GitHub issue"). Surfaces: Desktop + Server Edition (renderer + core); Omni board shows no
issue lanes; **Mobile does not render the binding** — `issueRef` reaches the phone inside the
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:
+ - **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.
+ - **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
+ subscribed — a network-derived fact standing in for consent, and no run at all when nobody has
+ the board open. That is the follow-up, not v1.
+ - **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
+ `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.
+ - **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.
+ - **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.
+ - **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 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 d12f15adc..67ceda349 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -138,6 +138,12 @@ so the live-state chips can never be saved into one. Board keys are
registry commands in the `board` scope — the only scope allowed a bare letter, because it never
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'`.
+
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
on every hook event of every node. Before a card shows a fact, check that its place on the board
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index e2152bd09..f6904a86e 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -486,6 +486,18 @@ import {
normalizeIssueRef,
type IssueRef
} from '@shared/github-issue-ref'
+import { sanitizeBoardDispatch, type BoardDispatchProject } from '@shared/board-dispatch'
+import {
+ DISPATCH_DRAIN_MS,
+ DISPATCH_REFUSAL_TEXT,
+ decideDispatch,
+ moveWithdrawsDispatch,
+ occupiesSlot,
+ queueToDrop,
+ queueToStart
+} from '../lib/boardDispatch'
+import { dispatchEntry, useBoardDispatch, type DispatchCardEntry } from '../state/boardDispatch'
+import type { GitHubIssueCardView as DispatchIssueCard } from '@shared/github-issues'
import { planIssueWorktree } from '@shared/issue-worktree'
import { sharedBasePathOf, sharedWorktreeLocationRefusal } from '@shared/worktree-location'
import {
@@ -10406,7 +10418,7 @@ export function Canvas() {
*/
const fileIssueSession = useCallback(
(
- issue: GitHubIssueCardView,
+ columnId: string | null,
ref: IssueRef,
created: { node: CanvasNode; projectId: string },
agentId: AgentId
@@ -10415,7 +10427,7 @@ export function Canvas() {
const nodeId = node.id
// The project addAgentNode charged the node to (its guarded, live read) — not a second read.
const board = useProjects.getState().getProject(targetProjectId)?.kanban ?? seedBoard
- const column = issue.columnId ? board.columns.find((c) => c.id === issue.columnId) : undefined
+ const column = columnId ? board.columns.find((c) => c.id === columnId) : undefined
if (column) {
useProjects.getState().setProjectKanban(targetProjectId, assignNode(board, nodeId, column.id, null))
markDirty()
@@ -10478,7 +10490,7 @@ export function Canvas() {
issueRef: start.ref
})
if (!created) return // addAgentNode already said why
- fileIssueSession(issue, start.ref, created, agentId)
+ fileIssueSession(issue.columnId, start.ref, created, agentId)
},
[addAgentNode, issueStartPrompt, fileIssueSession]
)
@@ -10494,6 +10506,275 @@ export function Canvas() {
[agentCreationEntries, startIssueAgent]
)
+ // ---- Board dispatch: a card THIS person moves into the dispatch column starts its own run ----
+ // Decisions are lib/boardDispatch (pure, tested); consent is machine-local settings
+ // (@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.
+
+ /** Every node of a project as the dispatcher needs it: the live canvas for the active project,
+ * the stored copy for any other. */
+ const dispatchNodesOf = useCallback(
+ (projectId: string): Array<{ id: string; issueRef?: unknown; pending: boolean }> => {
+ const st = useProjects.getState()
+ if (st.activeProjectId === projectId && nodesProjectIdRef.current === projectId) {
+ return nodesRef.current.map((n) => ({
+ id: n.id,
+ issueRef: n.data.issueRef,
+ pending: !!n.data.pendingLaunch
+ }))
+ }
+ return (st.getProject(projectId)?.nodes ?? []).map((n) => ({
+ id: n.id,
+ issueRef: n.issueRef,
+ pending: !!n.pendingLaunch
+ }))
+ },
+ []
+ )
+
+ /** Sessions bound to this issue that still exist, in ANY project: one run per issue. */
+ const dispatchBoundRuns = useCallback(
+ (key: string): number => {
+ let count = 0
+ for (const p of useProjects.getState().projects) {
+ for (const n of dispatchNodesOf(p.id)) if (issueKey(n.issueRef) === key) count++
+ }
+ return count
+ },
+ [dispatchNodesOf]
+ )
+
+ /** Runs of this project holding a concurrency slot now, plus dispatches still starting. */
+ const dispatchOccupying = useCallback(
+ (projectId: string): number => {
+ const byId = useAgentStatus.getState().byId
+ const { startedAt, byKey } = useBoardDispatch.getState()
+ const now = Date.now()
+ let count = 0
+ for (const n of dispatchNodesOf(projectId)) {
+ if (!normalizeIssueRef(n.issueRef)) continue
+ if (occupiesSlot({ state: byId[n.id]?.state, pending: n.pending, startedAt: startedAt[n.id] }, now)) count++
+ }
+ for (const e of Object.values(byKey)) if (e.projectId === projectId && e.status === 'starting') count++
+ return count
+ },
+ [dispatchNodesOf]
+ )
+
+ const dispatchAgentKnown = (agentId: string): boolean =>
+ !!agentConfig(agentId) || useSettings.getState().settings.customAgents.some((c) => c.id === agentId)
+
+ /** Start one dispatched run. 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' })
+ const fail = (reason: string): void =>
+ useBoardDispatch.getState().put({ ...entry, status: 'refused', reason })
+ try {
+ const prompt = issueLaunchPrompt(entry.ref)
+ if (!prompt) return fail(DISPATCH_REFUSAL_TEXT['no-reference'])
+ 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.ssh) return fail(DISPATCH_REFUSAL_TEXT['remote-project'])
+ let nodeId: string
+ if (st.activeProjectId === project.id && canCreateOnCanvas(nodesProjectIdRef.current, project.id)) {
+ const created = addAgentNode(agentId, undefined, undefined, config.accountId, prompt, {
+ issueRef: entry.ref
+ })
+ if (!created) return fail('The agent could not be opened; the notice says why.')
+ fileIssueSession(entry.columnId, entry.ref, created, agentId)
+ nodeId = created.node.id
+ } else {
+ // 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
+ let account: string | undefined
+ if (agentId === 'codex') {
+ const decision = resolveNewCodexNodeAccount(
+ config.accountId,
+ settings.codexAccounts,
+ connectedProjectIdForHost
+ )
+ if (!decision.create) return fail('The dispatch Codex account is not usable.')
+ account = decision.accountId
+ } else {
+ account = resolveNewNodeAccount(config.accountId, project, settings.claudeAccounts)
+ }
+ const model =
+ settings.agentLaunchMode === 'gateway-model' &&
+ settings.modelGatewayDefaultModel &&
+ canSwitchModel(agentId)
+ ? settings.modelGatewayDefaultModel
+ : undefined
+ const stored = project.nodes
+ const built = createAgentNode(
+ agentId,
+ stored.length,
+ project.cwd,
+ { x: 0, y: 0 },
+ prompt,
+ undefined,
+ account,
+ projectPermissionMode(project, agentId),
+ project.id,
+ model
+ )
+ const node: CanvasNode = { ...built, data: { ...built.data, issueRef: entry.ref } }
+ const w = (node.width as number) ?? 640
+ 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 }
+ st.applyOwnNodeMutation(project.id, {
+ op: 'upsert',
+ node: flowToNodeStates([armForColdOpen(node)])[0]
+ })
+ 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) {
+ const fresh = useProjects.getState().getProject(project.id) ?? project
+ const batch = await startNodesHeadlessRef.current(fresh, [held])
+ const outcome = batch.outcomes[0]
+ if (outcome && !outcome.started) {
+ setNotice({
+ kind: 'info',
+ 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.`,
+ action: { label: 'Go there', run: () => travelToNodeRef.current(nodeId) }
+ })
+ }
+ }
+ }
+ const done = useBoardDispatch.getState()
+ done.markStarted(nodeId, Date.now())
+ done.remove(entry.key)
+ } catch (error) {
+ console.warn('[nodeterm] board dispatch failed', error)
+ fail('Starting the agent failed.')
+ }
+ },
+ [addAgentNode, fileIssueSession, connectedProjectIdForHost, writeDisk]
+ )
+
+ /** Board dispatch's ONE trigger: a GitHub card this person moved, with GitHub's answer
+ * (KanbanView `onIssueMoved`). Pinned as the only caller by board-dispatch.guard.test. */
+ const dispatchOnUserMove = useCallback(
+ (projectId: string, issue: DispatchIssueCard, toColumnId: string | null, status: string) => {
+ const dispatch = sanitizeBoardDispatch(useSettings.getState().settings.boardDispatch)
+ const config = dispatch.projects[projectId]
+ if (!config) return
+ const project = useProjects.getState().getProject(projectId)
+ const ref = issueRefFromHtmlUrl(issue.htmlUrl, issue.number)
+ const key = issueKey(ref)
+ const current = key ? useBoardDispatch.getState().byKey[key] : undefined
+ const trigger = {
+ origin: 'user-move' as const,
+ projectId,
+ toColumnId,
+ moveStatus: status,
+ issue: { number: issue.number, htmlUrl: issue.htmlUrl, state: issue.state }
+ }
+ if (key && current && current.status !== 'starting' && moveWithdrawsDispatch(trigger, dispatch)) {
+ useBoardDispatch.getState().remove(key)
+ return
+ }
+ const decision = decideDispatch(
+ trigger,
+ {
+ dispatch,
+ project: project ? { remote: !!project.ssh, relay: !!project.remote } : undefined,
+ completionColumnId: project?.kanban?.github?.completionColumnId,
+ agentKnown: dispatchAgentKnown(config.agentId),
+ boundRuns: key ? dispatchBoundRuns(key) : 0,
+ queuedOrStarting: current?.status === 'queued' || current?.status === 'starting',
+ occupying: dispatchOccupying(projectId)
+ }
+ )
+ if (decision.kind === 'ignore') return
+ const now = Date.now()
+ if (decision.kind === 'refuse') {
+ if (!key || !ref) {
+ setNotice({ kind: 'error', text: `#${issue.number} was not dispatched: ${DISPATCH_REFUSAL_TEXT[decision.reason]}` })
+ return
+ }
+ // A second drag of a card already on its way keeps its entry; everything else says why.
+ if (decision.reason === 'already-queued') return
+ useBoardDispatch.getState().put(
+ dispatchEntry({ key, projectId, ref, number: issue.number, columnId: config.columnId }, 'refused', now,
+ DISPATCH_REFUSAL_TEXT[decision.reason])
+ )
+ return
+ }
+ const entry = dispatchEntry(
+ { key: decision.key, projectId, ref: decision.ref, number: issue.number, columnId: config.columnId },
+ 'queued',
+ now
+ )
+ if (decision.kind === 'queue') {
+ useBoardDispatch.getState().put(entry)
+ return
+ }
+ void dispatchStart(entry, config)
+ },
+ [dispatchBoundRuns, dispatchOccupying, dispatchStart]
+ )
+
+ /** Start what the queue's free slots allow, and drop entries whose project stopped dispatching. */
+ const drainDispatchQueue = useCallback(() => {
+ const dispatch = sanitizeBoardDispatch(useSettings.getState().settings.boardDispatch)
+ const queue = useBoardDispatch.getState().queue()
+ for (const e of queueToDrop(queue, dispatch)) {
+ const entry = useBoardDispatch.getState().byKey[e.key]
+ if (!entry) continue
+ useBoardDispatch.getState().put({
+ ...entry,
+ status: 'refused',
+ reason: dispatch.paused ? DISPATCH_REFUSAL_TEXT.paused : 'Dispatch was switched off for this project.'
+ })
+ }
+ 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)
+ }
+ }, [dispatchOccupying, dispatchBoundRuns, dispatchStart])
+ 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).
+ const dispatchQueued = useBoardDispatch((s) => Object.values(s.byKey).some((e) => e.status === 'queued'))
+ const boardDispatchSettings = useSettings((s) => s.settings.boardDispatch)
+ useEffect(() => {
+ if (!dispatchQueued) return
+ drainDispatchQueueRef.current()
+ const timer = setInterval(() => drainDispatchQueueRef.current(), DISPATCH_DRAIN_MS)
+ return () => clearInterval(timer)
+ }, [dispatchQueued, boardDispatchSettings])
+
// ---- 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). */
const [issueWorktreeAsk, setIssueWorktreeAskState] = useState<IssueWorktreeAsk | null>(null)
@@ -10568,7 +10849,7 @@ export function Canvas() {
nodesRef.current = grow(nodesRef.current)
setNodes((ns) => grow(ns as CanvasNode[]))
}
- fileIssueSession(issue, start.ref, created, agentId)
+ fileIssueSession(issue.columnId, start.ref, created, agentId)
return true
},
[setNodes, addAgentNode, setupHoldGroup, fileIssueSession]
@@ -16687,6 +16968,7 @@ export function Canvas() {
issueAgentMenu={issueAgentMenu}
issueWorktreeMenu={issueWorktreeMenu}
teams={teamStations}
+ onIssueMoved={dispatchOnUserMove}
/>
)}
<UpdateCard />
diff --git a/src/renderer/canvas/issue-binding.source.test.ts b/src/renderer/canvas/issue-binding.source.test.ts
index 3c2a96375..82a10241b 100644
--- a/src/renderer/canvas/issue-binding.source.test.ts
+++ b/src/renderer/canvas/issue-binding.source.test.ts
@@ -140,7 +140,7 @@ describe('Start with agent (issue card)', () => {
const body = code(between('const startIssueAgent = useCallback(', 'const issueAgentMenu = useCallback('))
expect(body).toContain('issueStartPrompt(issue)')
expect(body).toContain('start.prompt, {\n issueRef: start.ref\n }')
- expect(body).toContain('fileIssueSession(issue, start.ref, created, agentId)')
+ expect(body).toContain('fileIssueSession(issue.columnId, start.ref, created, agentId)')
// The attacker-writable fields of the issue never reach this function's launch.
expect(body).not.toMatch(/issue\.title|issue\.body/)
})
diff --git a/src/renderer/components/kanban/DispatchChip.tsx b/src/renderer/components/kanban/DispatchChip.tsx
new file mode 100644
index 000000000..6341d4ca1
--- /dev/null
+++ b/src/renderer/components/kanban/DispatchChip.tsx
@@ -0,0 +1,37 @@
+import { memo, useMemo } from 'react'
+import { issueKey, issueRefFromHtmlUrl } from '@shared/github-issue-ref'
+import { dispatchChipSig, useBoardDispatch } from '../../state/boardDispatch'
+
+/**
+ * Board dispatch's line on an issue card: queued (with its place), starting, or why a dispatch did
+ * not start. Nothing at all when the card was never dispatched — a started run shows through the
+ * card's run chips, like any other bound session.
+ */
+export const DispatchChip = memo(function DispatchChip({
+ htmlUrl,
+ number
+}: {
+ htmlUrl: string
+ number: number
+}): React.JSX.Element | null {
+ const key = useMemo(() => issueKey(issueRefFromHtmlUrl(htmlUrl, number)), [htmlUrl, number])
+ const sig = useBoardDispatch((s) => dispatchChipSig(s, key))
+ if (!sig) return null
+ const [status, reason, position] = sig.split('|')
+ const text =
+ status === 'queued'
+ ? `Queued for an agent${Number(position) > 1 ? ` (#${position})` : ''}`
+ : status === 'starting'
+ ? 'Dispatching an agent…'
+ : 'Not dispatched'
+ return (
+ <div
+ className={`dispatch-chip dispatch-chip--${status}`}
+ role="status"
+ title={status === 'refused' ? reason : 'Board dispatch (Settings → GitHub Issues)'}
+ >
+ {text}
+ {status === 'refused' && reason ? <span className="dispatch-chip__reason">: {reason}</span> : null}
+ </div>
+ )
+})
diff --git a/src/renderer/components/kanban/GitHubIssueCard.tsx b/src/renderer/components/kanban/GitHubIssueCard.tsx
index 3369c1bb2..94bb08248 100644
--- a/src/renderer/components/kanban/GitHubIssueCard.tsx
+++ b/src/renderer/components/kanban/GitHubIssueCard.tsx
@@ -6,6 +6,7 @@ import { updatedRelative } from '../../lib/relativeTime'
import { PullRefChip } from './PullStatusBadges'
import { NO_ISSUE_RUNS, type IssueRun } from '../../lib/issueRuns'
import { IssueRunChips } from './IssueRunChips'
+import { DispatchChip } from './DispatchChip'
export const GitHubIssueCard = memo(function GitHubIssueCard({
issue,
@@ -100,6 +101,7 @@ export const GitHubIssueCard = memo(function GitHubIssueCard({
</div>
)}
{onOpenRun && <IssueRunChips runs={runs} onOpen={onOpenRun} />}
+ <DispatchChip htmlUrl={issue.htmlUrl} number={issue.number} />
<div className="github-issue-card__footer">
<span>{moving ? 'Syncing…' : updatedRelative(issue.updatedAt)}</span>
{issue.conflict && <span className="github-issue-conflict">Needs a column</span>}
diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsx
index d550c0ce2..69d9b4a46 100644
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@ -159,6 +159,12 @@ export interface KanbanViewProps {
* shows one.
*/
teams?: ReadonlyMap<string, readonly TeamStation[]>
+ /**
+ * A GitHub issue card this PERSON moved (drag, the card's Move control, the summary modal), with
+ * GitHub's answer. Board dispatch's one trigger (lib/boardDispatch): nothing a refresh or a pull
+ * delivers ever reaches it. Optional: a board with no canvas behind it dispatches nothing.
+ */
+ onIssueMoved?: (projectId: string, issue: GitHubIssueCardView, toColumnId: string | null, status: string) => void
}
type Drag =
@@ -229,7 +235,7 @@ function useCanvasCovered(): void {
export const KanbanView = memo(function KanbanView({
board, sessions, onChange, onOpenNode, onCreateNode, onRenameNode, onEditSticky, onDeleteNode,
onModalNodeChange, onBrowserNav, onSetIcon, accountMenuItems, onAutoMoveFromPulls, issueAgentMenu,
- issueWorktreeMenu, teams
+ issueWorktreeMenu, teams, onIssueMoved
}: KanbanViewProps) {
useCanvasCovered()
const { api } = useSession()
@@ -307,6 +313,19 @@ export const KanbanView = memo(function KanbanView({
}, [pullBoard])
const connectGitHub = useGitHubIssues((state) => state.connect)
const moveGitHubState = useGitHubIssues((state) => state.move)
+ // Every person-initiated GitHub move goes through here, so the dispatch hook sees each one with
+ // GitHub's answer — the issue as GitHub now reports it when the move landed (a reopen into the
+ // dispatch column is open afterwards, whatever the card said before).
+ const moveIssueByUser = useCallback(
+ async (issue: GitHubIssueCardView, columnId: string | null, closeReason?: GitHubCloseReason) => {
+ const result = await moveGitHubState(
+ api.githubIssues, projectId, issue.number, columnId, issue.updatedAt, closeReason
+ )
+ const after = 'issue' in result && result.issue ? { ...issue, ...result.issue } : issue
+ onIssueMoved?.(projectId, after, columnId, result.status)
+ },
+ [api.githubIssues, moveGitHubState, onIssueMoved, projectId]
+ )
const loadMoreGitHub = useGitHubIssues((state) => state.loadMore)
// Drop ids no longer in the palette so a deleted label can't keep the board filtered to nothing.
const paletteLabels = useMemo(() => boardLabels(board), [board])
@@ -563,9 +582,9 @@ export const KanbanView = memo(function KanbanView({
setPendingGitHubMove({ issue, columnId, confirmation, closeReason: confirmation.defaultCloseReason })
return
}
- void moveGitHubState(api.githubIssues, projectId, issue.number, columnId, issue.updatedAt)
+ void moveIssueByUser(issue, columnId)
},
- [api.githubIssues, board.github?.completionColumnId, githubReadOnly, moveGitHubState, projectId]
+ [board.github?.completionColumnId, githubReadOnly, moveIssueByUser]
)
// columnId null = the virtual Ungrouped column.
@@ -1332,9 +1351,7 @@ export const KanbanView = memo(function KanbanView({
onConfirm={() => {
const { issue, columnId, closeReason } = pendingGitHubMove
setPendingGitHubMove(null)
- void moveGitHubState(
- api.githubIssues, projectId, issue.number, columnId, issue.updatedAt, closeReason
- )
+ void moveIssueByUser(issue, columnId, closeReason)
}}
/>
)}
diff --git a/src/renderer/components/kanban/board-writers.guard.test.ts b/src/renderer/components/kanban/board-writers.guard.test.ts
index 8a577509a..566ce41d9 100644
--- a/src/renderer/components/kanban/board-writers.guard.test.ts
+++ b/src/renderer/components/kanban/board-writers.guard.test.ts
@@ -24,7 +24,9 @@ const BOARD_WRITERS: Record<string, string[]> = {
'onKanbanChange — the per-project board committing a person\'s drag/edit',
'createNodeInColumn — a person\'s "+ New" in a column',
'fileIssueSession — a person\'s "Start with agent" or "Start with agent in a new worktree" filing ' +
- 'the new session under the issue card\'s column',
+ 'the new session under the issue card\'s column; also board dispatch, whose only trigger is a ' +
+ 'person moving the issue card into the dispatch column they switched on for this machine ' +
+ '(lib/board-dispatch.guard.test pins that)',
'the `assign` control verb — a session moving its OWN card (the issue-bound contract)',
'autoMoveCardFromPulls — the merge-driven move: a person switched it on for this machine in ' +
'Settings, and it fires only on a pull request MERGE this machine observed after that (never on ' +
@@ -34,10 +36,10 @@ const BOARD_WRITERS: Record<string, string[]> = {
'components/kanban/NodeLabels.tsx': ['a person editing a node\'s labels'],
'components/settings/sections/GitHubIssuesSection.tsx': ['a person editing the board\'s GitHub config'],
'components/kanban/KanbanView.tsx': [
- 'requestGitHubMove — a person moving an issue card (drag, Move select, summary modal)',
- 'the close/reopen ConfirmDialog — a person confirming that move'
+ 'moveIssueByUser — called only by requestGitHubMove (a person moving an issue card: drag, Move ' +
+ 'select, summary modal) and the close/reopen ConfirmDialog (a person confirming that move)'
],
- 'state/githubIssues.ts': ['the store\'s `move`, called only by the two KanbanView sites above']
+ 'state/githubIssues.ts': ['the store\'s `move`, called only by the KanbanView site above']
}
const WRITER = /\bsetProjectKanban\(|\bmoveGitHubState\(|\.moveIssue\(/g
diff --git a/src/renderer/components/settings/sections/GitHubIssuesSection.tsx b/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
index f6194cd89..3b9304b5e 100644
--- a/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
+++ b/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
@@ -10,6 +10,14 @@ import { defaultCompletionColumnId } from '@shared/kanban-category'
import { useProjects } from '../../../state/projects'
import { useSettings } from '../../../state/settings'
import { prunePullAutoMove, sanitizeKanbanPullAutoMove } from '@shared/kanban-pull-links'
+import {
+ BOARD_DISPATCH_DEFAULT_CONCURRENT,
+ BOARD_DISPATCH_MAX_CONCURRENT,
+ pruneBoardDispatch,
+ sanitizeBoardDispatch,
+ type BoardDispatchProject
+} from '@shared/board-dispatch'
+import { AGENT_CONFIG, BUILTIN_AGENT_IDS } from '@shared/agents/config'
import { markWorkspaceDirty } from '../../../state/workspaceDirty'
import { SAVE_DEBOUNCE_MS } from '../../../lib/savePersistence'
import { SettingsSection } from '../SettingsSection'
@@ -50,6 +58,11 @@ const ROWS = {
description: 'When every pull request linked to a session card has merged, move the card to this column.',
keywords: ['github', 'pull request', 'merged', 'move', 'automation', 'worktree', 'session']
},
+ dispatch: {
+ title: 'Dispatch agents',
+ description: 'When you move an issue card into this column, an agent session starts on it by itself — the same run as “Start with agent”.',
+ keywords: ['github', 'dispatch', 'agent', 'automation', 'queue', 'start with agent', 'issue', 'pause']
+ },
data: {
title: 'Sync and local data',
keywords: ['github', 'refresh', 'cache', 'revoke', 'labels']
@@ -155,6 +168,43 @@ export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.
})
}
+ const dispatchRaw = useSettings((state) => state.settings.boardDispatch)
+ const customAgents = useSettings((state) => state.settings.customAgents)
+ const claudeAccounts = useSettings((state) => state.settings.claudeAccounts)
+ const codexAccounts = useSettings((state) => state.settings.codexAccounts)
+ const dispatch = sanitizeBoardDispatch(dispatchRaw)
+ const dispatchConfig = projectId ? dispatch.projects[projectId] : undefined
+ /** 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 setDispatch = (patch: Partial<BoardDispatchProject> | null | undefined, paused?: boolean): void => {
+ const live = new Set(useProjects.getState().projects.map((item) => item.id))
+ const current = pruneBoardDispatch(
+ sanitizeBoardDispatch(useSettings.getState().settings.boardDispatch), live)
+ const projects = { ...current.projects }
+ if (projectId && patch === null) delete projects[projectId]
+ else if (projectId && patch) {
+ const base: BoardDispatchProject = projects[projectId] ?? {
+ columnId: '',
+ agentId: 'claude',
+ maxConcurrent: BOARD_DISPATCH_DEFAULT_CONCURRENT
+ }
+ const next = { ...base, ...patch }
+ if (!next.accountId) delete next.accountId
+ if (next.columnId) projects[projectId] = next
+ }
+ updateSettings({ boardDispatch: { paused: paused ?? current.paused, projects } })
+ }
+ 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 }))
+ ]
+ 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 }))
+ : []
+
/** `GitHubHostController.status(projectId)` MASKS the auth block for a project that is not
* approved on this machine (`ghAuthenticated: false, activeProvider: null, tokenPresent: false`)
* — a deliberate credential boundary, but it means "not approved yet" is indistinguishable from
@@ -649,6 +699,95 @@ export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.
/>
</SearchableRow>
+ <SearchableRow {...ROWS.dispatch}>
+ <div className="space-y-3">
+ <FieldRow
+ label={ROWS.dispatch.title}
+ htmlFor="github-dispatch-column"
+ description={`${ROWS.dispatch.description} Only a move you make in this app on this machine starts one — never a label change on GitHub, a teammate’s move, or a board that arrives by git pull. One run per issue; further runs queue. This setting is for this machine only.`}
+ control={
+ <Select
+ id="github-dispatch-column"
+ value={dispatchConfig && board.columns.some((c) => c.id === dispatchConfig.columnId)
+ ? dispatchConfig.columnId : ''}
+ onChange={(event) => setDispatch(event.target.value ? { columnId: event.target.value } : null)}
+ >
+ <option value="">Off</option>
+ {board.columns
+ .filter((column) => column.id !== githubConfig.completionColumnId)
+ .map((column) => (
+ <option key={column.id} value={column.id}>{column.title}</option>
+ ))}
+ </Select>
+ }
+ />
+ {dispatchConfig && (
+ <>
+ <FieldRow
+ label="Agent"
+ htmlFor="github-dispatch-agent"
+ control={
+ <Select
+ id="github-dispatch-agent"
+ value={dispatchConfig.agentId}
+ onChange={(event) => setDispatch({ agentId: event.target.value, accountId: undefined })}
+ >
+ {dispatchAgentOptions.map((agent) => (
+ <option key={agent.id} value={agent.id}>{agent.label}</option>
+ ))}
+ </Select>
+ }
+ />
+ {dispatchAccountOptions.length > 0 && (
+ <FieldRow
+ label="Account"
+ htmlFor="github-dispatch-account"
+ control={
+ <Select
+ id="github-dispatch-account"
+ value={dispatchConfig.accountId ?? ''}
+ onChange={(event) => setDispatch({ accountId: event.target.value || undefined })}
+ >
+ <option value="">Project default</option>
+ {dispatchAccountOptions.map((account) => (
+ <option key={account.id} value={account.id}>{account.label}</option>
+ ))}
+ </Select>
+ }
+ />
+ )}
+ <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."
+ control={
+ <Select
+ id="github-dispatch-cap"
+ value={String(dispatchConfig.maxConcurrent)}
+ onChange={(event) => setDispatch({ maxConcurrent: Number(event.target.value) })}
+ >
+ {Array.from({ length: BOARD_DISPATCH_MAX_CONCURRENT }, (_, i) => i + 1).map((n) => (
+ <option key={n} value={n}>{n}</option>
+ ))}
+ </Select>
+ }
+ />
+ </>
+ )}
+ <FieldRow
+ label="Pause all dispatch"
+ description="The kill switch, for every project on this machine: nothing new starts and queued dispatches are dropped. Running sessions are not touched."
+ control={
+ <Switch
+ ariaLabel="Pause all dispatch"
+ checked={dispatch.paused}
+ onChange={(checked) => setDispatch(undefined, checked)}
+ />
+ }
+ />
+ </div>
+ </SearchableRow>
+
<SearchableRow {...ROWS.data}>
<div className="space-y-3">
<div className="flex flex-wrap gap-2">
diff --git a/src/renderer/lib/board-dispatch.guard.test.ts b/src/renderer/lib/board-dispatch.guard.test.ts
new file mode 100644
index 000000000..b1969050d
--- /dev/null
+++ b/src/renderer/lib/board-dispatch.guard.test.ts
@@ -0,0 +1,66 @@
+// Board dispatch's security rests on ONE fact: a run starts only from the move a person makes in
+// this app. `decideDispatch` refuses every origin but `'user-move'`, so the remaining question is
+// who may SAY `'user-move'` — and the answer must stay "the board's own move-result path". A
+// refresh that finds a card in the dispatch column (a label someone set on GitHub) or a board that
+// arrives by git pull must have no path into it. This scan pins the whole chain, line by line.
+import { readFileSync, readdirSync, statSync } from 'node:fs'
+import { join } from 'node:path'
+import { describe, expect, it } from 'vitest'
+
+const ROOT = join(__dirname, '..')
+
+function files(dir: string): string[] {
+ return readdirSync(dir).flatMap((name) => {
+ const p = join(dir, name)
+ if (statSync(p).isDirectory()) return files(p)
+ return /\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name) ? [p] : []
+ })
+}
+
+const src = files(ROOT).map((p) => ({ p: p.slice(ROOT.length + 1), text: readFileSync(p, 'utf8').replace(/\r\n/g, '\n') }))
+
+function sitesOf(pattern: RegExp): string[] {
+ return src.flatMap(({ p, text }) =>
+ text.split('\n').flatMap((line) => (pattern.test(line) && !/^\s*(\/\/|\*)/.test(line) ? [p] : []))
+ )
+}
+
+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'])
+ expect(sitesOf(/origin: 'user-move'/)).toEqual(['canvas/Canvas.tsx'])
+ const canvas = src.find((f) => f.p === 'canvas/Canvas.tsx')!.text
+ const body = canvas.slice(canvas.indexOf('const dispatchOnUserMove = useCallback'))
+ expect(body.indexOf("origin: 'user-move'")).toBeLessThan(body.indexOf('const drainDispatchQueue'))
+ })
+
+ it("dispatchOnUserMove is wired ONLY to the board's onIssueMoved", () => {
+ expect(sitesOf(/dispatchOnUserMove\b/)).toEqual(['canvas/Canvas.tsx', 'canvas/Canvas.tsx'])
+ 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))
+ expect(uses.map((l) => l.trim())).toEqual(['onIssueMoved={dispatchOnUserMove}'])
+ })
+
+ it('onIssueMoved fires only after a person-initiated GitHub move (moveIssueByUser)', () => {
+ expect(sitesOf(/onIssueMoved\?\.\(/)).toEqual(['components/kanban/KanbanView.tsx'])
+ const view = src.find((f) => f.p === 'components/kanban/KanbanView.tsx')!.text
+ const fire = view.indexOf('onIssueMoved?.(')
+ expect(view.lastIndexOf('const moveIssueByUser = useCallback', fire)).toBeGreaterThan(-1)
+ // moveIssueByUser is called from exactly the two human paths: requestGitHubMove (drag, Move
+ // control, summary modal) and the close/reopen confirm dialog's onConfirm.
+ const calls = view.split('\n').filter((l) => /moveIssueByUser\(/.test(l) && !/const moveIssueByUser/.test(l))
+ expect(calls.map((l) => l.trim())).toEqual([
+ 'void moveIssueByUser(issue, columnId)',
+ 'void moveIssueByUser(issue, columnId, closeReason)'
+ ])
+ })
+
+ 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
+ expect(text).not.toMatch(/boardDispatch|onIssueMoved|dispatchOnUserMove/)
+ }
+ })
+})
diff --git a/src/renderer/lib/boardDispatch.test.ts b/src/renderer/lib/boardDispatch.test.ts
new file mode 100644
index 000000000..6492af184
--- /dev/null
+++ b/src/renderer/lib/boardDispatch.test.ts
@@ -0,0 +1,166 @@
+import { describe, expect, it } from 'vitest'
+import { sanitizeBoardDispatch } from '@shared/board-dispatch'
+import {
+ DISPATCH_STARTUP_GRACE_MS,
+ decideDispatch,
+ moveWithdrawsDispatch,
+ occupiesSlot,
+ queueToDrop,
+ queueToStart,
+ type DispatchContext,
+ type DispatchQueueEntry,
+ type DispatchTrigger
+} from './boardDispatch'
+
+const dispatch = sanitizeBoardDispatch({
+ projects: { p1: { columnId: 'agent-col', agentId: 'claude', maxConcurrent: 2 } }
+})
+
+function trigger(over: Partial<DispatchTrigger> = {}): DispatchTrigger {
+ return {
+ origin: 'user-move',
+ projectId: 'p1',
+ toColumnId: 'agent-col',
+ moveStatus: 'confirmed',
+ issue: { number: 7, htmlUrl: 'https://github.com/acme/app/issues/7', state: 'open' },
+ ...over
+ }
+}
+
+function ctx(over: Partial<DispatchContext> = {}): DispatchContext {
+ return {
+ dispatch,
+ project: { remote: false, relay: false },
+ completionColumnId: 'done',
+ agentKnown: true,
+ boundRuns: 0,
+ queuedOrStarting: false,
+ occupying: 0,
+ ...over
+ }
+}
+
+describe('decideDispatch — who may trigger a run', () => {
+ it('a confirmed move by this person into the dispatch column starts a run bound to the issue', () => {
+ const d = decideDispatch(trigger(), ctx())
+ expect(d).toEqual({
+ kind: 'start',
+ ref: { owner: 'acme', repo: 'app', number: 7 },
+ key: 'acme/app#7'
+ })
+ })
+
+ it('a card that arrives in the column any other way (refresh after a GitHub label change, a pulled board) starts nothing', () => {
+ expect(decideDispatch(trigger({ origin: 'sync' }), ctx())).toEqual({ kind: 'ignore' })
+ })
+
+ it('a project that is not switched on on THIS machine starts nothing (opt-out)', () => {
+ expect(decideDispatch(trigger({ projectId: 'p2' }), ctx())).toEqual({ kind: 'ignore' })
+ expect(decideDispatch(trigger(), ctx({ dispatch: sanitizeBoardDispatch(undefined) }))).toEqual({ kind: 'ignore' })
+ })
+
+ it('a move into another column, or to Ungrouped, is not a dispatch', () => {
+ expect(decideDispatch(trigger({ toColumnId: 'other' }), ctx())).toEqual({ kind: 'ignore' })
+ expect(decideDispatch(trigger({ toColumnId: null }), ctx())).toEqual({ kind: 'ignore' })
+ })
+
+ it('a move GitHub did not confirm is not a dispatch', () => {
+ for (const moveStatus of ['stale', 'failed', 'read-only', 'invalid-target', 'configuration-changed']) {
+ expect(decideDispatch(trigger({ moveStatus }), ctx())).toEqual({ kind: 'ignore' })
+ }
+ expect(decideDispatch(trigger({ moveStatus: 'refresh-pending' }), ctx()).kind).toBe('start')
+ })
+
+ it('the kill switch refuses, and says so', () => {
+ const paused = sanitizeBoardDispatch({ paused: true, projects: { p1: { columnId: 'agent-col', agentId: 'claude' } } })
+ 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: { 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' })
+ expect(decideDispatch(trigger({ issue: { number: 7, htmlUrl: 'https://evil.example/acme/app/issues/7', state: 'open' } }), ctx()))
+ .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' })
+ })
+
+ it('refuses a dispatch column that is also the completion column', () => {
+ expect(decideDispatch(trigger(), ctx({ completionColumnId: 'agent-col' }))).toMatchObject({ reason: 'completion-column' })
+ })
+
+ it('one run per issue: a second trigger for the same issue starts nothing', () => {
+ expect(decideDispatch(trigger(), ctx({ boundRuns: 1 }))).toMatchObject({ kind: 'refuse', reason: 'already-running' })
+ expect(decideDispatch(trigger(), ctx({ queuedOrStarting: true }))).toMatchObject({ kind: 'refuse', reason: 'already-queued' })
+ })
+
+ it('respects the per-project cap: a full project queues instead of starting', () => {
+ expect(decideDispatch(trigger(), ctx({ occupying: 1 })).kind).toBe('start')
+ expect(decideDispatch(trigger(), ctx({ occupying: 2 })).kind).toBe('queue')
+ expect(decideDispatch(trigger(), ctx({ occupying: 5 })).kind).toBe('queue')
+ })
+})
+
+describe('occupiesSlot', () => {
+ const now = 1_000_000
+ it('working, waiting, blocked and a held launch hold a slot; an idle turn does not', () => {
+ expect(occupiesSlot({ state: 'working', pending: false }, now)).toBe(true)
+ expect(occupiesSlot({ state: 'waiting', pending: false }, now)).toBe(true)
+ expect(occupiesSlot({ state: 'blocked', pending: false }, now)).toBe(true)
+ expect(occupiesSlot({ pending: true }, now)).toBe(true)
+ expect(occupiesSlot({ state: 'done', pending: false, startedAt: now }, now)).toBe(false)
+ })
+ it('an unknown state holds a slot only while it is a run this app just started', () => {
+ expect(occupiesSlot({ pending: false }, now)).toBe(false)
+ expect(occupiesSlot({ pending: false, startedAt: now - 1000 }, now)).toBe(true)
+ expect(occupiesSlot({ pending: false, startedAt: now - DISPATCH_STARTUP_GRACE_MS }, now)).toBe(false)
+ })
+})
+
+describe('queue', () => {
+ const two = sanitizeBoardDispatch({
+ projects: {
+ p1: { columnId: 'c', agentId: 'claude', maxConcurrent: 2 },
+ p2: { columnId: 'c', agentId: 'claude', maxConcurrent: 1 }
+ }
+ })
+ const entry = (key: string, projectId: string, queuedAt: number): DispatchQueueEntry => ({
+ key,
+ projectId,
+ ref: { owner: 'a', repo: 'b', number: queuedAt },
+ number: queuedAt,
+ queuedAt
+ })
+ const queue = [entry('x3', 'p1', 3), entry('x1', 'p1', 1), entry('x2', 'p1', 2), entry('y1', 'p2', 1), entry('y2', 'p2', 2)]
+
+ it('starts oldest first, never past each project\'s free slots', () => {
+ const occ = new Map([['p1', 1], ['p2', 0]])
+ expect(queueToStart(queue, two, (p) => occ.get(p) ?? 0).map((e) => e.key)).toEqual(['x1', 'y1'])
+ expect(queueToStart(queue, two, () => 0).map((e) => e.key)).toEqual(['x1', 'y1', 'x2'])
+ expect(queueToStart(queue, two, () => 9)).toEqual([])
+ })
+
+ 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' } } })
+ expect(queueToStart(queue, onlyP1, () => 0).every((e) => e.projectId === 'p1')).toBe(true)
+ expect(queueToDrop(queue, onlyP1).map((e) => e.key).sort()).toEqual(['y1', 'y2'])
+ })
+})
+
+describe('moveWithdrawsDispatch', () => {
+ it('a landed move out of the dispatch column withdraws a queued dispatch; nothing else does', () => {
+ expect(moveWithdrawsDispatch(trigger({ toColumnId: 'other' }), dispatch)).toBe(true)
+ expect(moveWithdrawsDispatch(trigger({ toColumnId: null }), dispatch)).toBe(true)
+ expect(moveWithdrawsDispatch(trigger(), dispatch)).toBe(false)
+ expect(moveWithdrawsDispatch(trigger({ toColumnId: 'other', moveStatus: 'failed' }), dispatch)).toBe(false)
+ expect(moveWithdrawsDispatch(trigger({ toColumnId: 'other', origin: 'sync' }), dispatch)).toBe(false)
+ expect(moveWithdrawsDispatch(trigger({ toColumnId: 'other', projectId: 'p9' }), dispatch)).toBe(false)
+ })
+})
diff --git a/src/renderer/lib/boardDispatch.ts b/src/renderer/lib/boardDispatch.ts
new file mode 100644
index 000000000..66a8ed8ac
--- /dev/null
+++ b/src/renderer/lib/boardDispatch.ts
@@ -0,0 +1,192 @@
+// Board dispatch decisions (pure). The consent it reads is `@shared/board-dispatch` (machine-local).
+//
+// THE TRIGGER, and why it is this one: a GitHub issue card that THIS PERSON drags (or moves with
+// the card's Move control or the summary modal) into the project's dispatch column, and whose move
+// GitHub CONFIRMED. The call site is the board's own move-result path — the one place a human
+// gesture in this app reaches — so the trigger is provably local:
+// - a label change made on GitHub (by anyone, on a public repository by ANYONE) reaches this app
+// only as a refreshed page, which never calls this module with `origin: 'user-move'`;
+// - a column change arriving by `git pull` changes the shared board file, which no move-result
+// path reads either.
+// The alternative (a GitHub label whose `labeled` actor is on a machine-local allowlist) would work
+// from a phone, but it needs one issue-events read per candidate, the actor's identity compared
+// against a credential that can change under it, and a poll that today runs only while a board is
+// subscribed — i.e. a network-derived fact standing in for consent. v1 takes the gesture.
+//
+// Every refusal has a reason the card shows; `ignore` is for moves that were never a dispatch at all
+// (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 { AgentState } from '@shared/agents/normalize'
+import { issueKey, issueRefFromHtmlUrl, type IssueRef } from '@shared/github-issue-ref'
+
+export type DispatchOrigin = 'user-move' | 'sync'
+
+export interface DispatchTrigger {
+ origin: DispatchOrigin
+ projectId: string
+ toColumnId: string | null
+ /** The GitHub move's outcome (`GitHubIssueMoveResult['status']`). */
+ moveStatus: string
+ issue: { number: number; htmlUrl: string; state: 'open' | 'closed' }
+}
+
+export interface DispatchProjectFacts {
+ /** An SSH project: its runs cannot start headless (v1 is local projects only). */
+ remote: boolean
+ /** A relay tab: the board belongs to another machine. */
+ relay: boolean
+}
+
+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
+ /** Sessions bound to this issue that still exist, in any project. */
+ boundRuns: number
+ /** This issue is already queued or starting. */
+ queuedOrStarting: boolean
+ /** Runs of this project that hold a concurrency slot right now (`occupiesSlot`). */
+ occupying: number
+}
+
+export type DispatchRefusal =
+ | 'paused'
+ | 'remote-project'
+ | 'relay'
+ | 'completion-column'
+ | 'issue-closed'
+ | 'no-reference'
+ | 'agent-unavailable'
+ | 'already-running'
+ | 'already-queued'
+
+export type DispatchDecision =
+ | { kind: 'ignore' }
+ | { kind: 'refuse'; reason: DispatchRefusal }
+ | { kind: 'start'; ref: IssueRef; key: string }
+ | { kind: 'queue'; ref: IssueRef; key: string }
+
+/** The move statuses that mean GitHub now shows the card in the destination column. */
+const LANDED = new Set(['confirmed', 'refresh-pending'])
+
+export function decideDispatch(trigger: DispatchTrigger, ctx: DispatchContext): DispatchDecision {
+ // Only a person's own move in this app. Anything else — a refresh that finds a card in the
+ // column, a pulled board — is never a dispatch.
+ if (trigger.origin !== 'user-move') return { kind: 'ignore' }
+ const config = ctx.dispatch.projects[trigger.projectId]
+ if (!config) return { kind: 'ignore' }
+ 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.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' }
+ }
+ 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' }
+ // 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' }
+ if (ctx.boundRuns > 0) return { kind: 'refuse', reason: 'already-running' }
+ return ctx.occupying >= config.maxConcurrent ? { kind: 'queue', ref, key } : { kind: 'start', ref, key }
+}
+
+/** A person moving a card OUT of the dispatch column withdraws it: a queued dispatch is cancelled
+ * and a refusal line stops describing where the card is. (A run that already started is a session;
+ * moving the card never touches it.) */
+export function moveWithdrawsDispatch(trigger: DispatchTrigger, dispatch: BoardDispatch): boolean {
+ if (trigger.origin !== 'user-move') return false
+ const config = dispatch.projects[trigger.projectId]
+ return !!config && LANDED.has(trigger.moveStatus) && trigger.toColumnId !== config.columnId
+}
+
+export const DISPATCH_REFUSAL_TEXT: Record<DispatchRefusal, string> = {
+ paused: 'Dispatch is paused on this machine.',
+ '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.',
+ 'already-running': 'This issue already has a session. Close it to dispatch again.',
+ 'already-queued': 'This issue is already queued or starting.'
+}
+
+// ── Concurrency slots ──────────────────────────────────────────────────────────────────────────
+
+/** How often the queue is re-checked while something is queued. */
+export const DISPATCH_DRAIN_MS = 5_000
+
+/** A freshly started run holds its slot this long even before its first hook event. */
+export const DISPATCH_STARTUP_GRACE_MS = 120_000
+
+export interface RunSlotFact {
+ state?: AgentState
+ /** The node still holds a launch (queued, starting). */
+ pending: boolean
+ /** When dispatch started it, in this app run. */
+ startedAt?: number
+}
+
+/**
+ * Whether a bound session uses one of its project's slots. A turn in flight (working), a session
+ * waiting on a person (waiting / blocked) and a launch not yet delivered all do; an idle session
+ * (`done`) does not — the cap limits concurrent WORK, and a finished turn is idle whatever the issue
+ * says. An UNKNOWN state (no hook event yet this app run) holds a slot only while it is a run this
+ * app just started: otherwise every session from before a restart would pin the cap forever.
+ */
+export function occupiesSlot(fact: RunSlotFact, now: number): boolean {
+ if (fact.pending) return true
+ if (fact.state === 'working' || fact.state === 'waiting' || fact.state === 'blocked') return true
+ if (fact.state === 'done') return false
+ return fact.startedAt !== undefined && now - fact.startedAt < DISPATCH_STARTUP_GRACE_MS
+}
+
+// ── Queue ──────────────────────────────────────────────────────────────────────────────────────
+
+export interface DispatchQueueEntry {
+ key: string
+ projectId: string
+ ref: IssueRef
+ number: number
+ queuedAt: number
+}
+
+/**
+ * The queued entries to start now, oldest first per project, never more than each project's free
+ * slots. Paused → nothing. A project whose dispatch was switched off → nothing (its entries are
+ * dropped by the caller, which also says why on the card).
+ */
+export function queueToStart(
+ queue: readonly DispatchQueueEntry[],
+ dispatch: BoardDispatch,
+ occupying: (projectId: string) => number
+): 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 (!free.has(entry.projectId)) free.set(entry.projectId, config.maxConcurrent - occupying(entry.projectId))
+ const left = free.get(entry.projectId)!
+ if (left <= 0) continue
+ free.set(entry.projectId, left - 1)
+ out.push(entry)
+ }
+ return out
+}
+
+/** Queue entries whose project no longer dispatches (switched off, or the machine paused it). */
+export function queueToDrop(queue: readonly DispatchQueueEntry[], dispatch: BoardDispatch): DispatchQueueEntry[] {
+ return queue.filter((e) => dispatch.paused || !dispatch.projects[e.projectId])
+}
diff --git a/src/renderer/state/boardDispatch.test.ts b/src/renderer/state/boardDispatch.test.ts
new file mode 100644
index 000000000..871f6593c
--- /dev/null
+++ b/src/renderer/state/boardDispatch.test.ts
@@ -0,0 +1,42 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+import { dispatchChipSig, dispatchEntry, useBoardDispatch } from './boardDispatch'
+
+const base = (key: string, projectId = 'p1') => ({
+ key,
+ projectId,
+ ref: { owner: 'a', repo: 'b', number: 1 },
+ number: 1,
+ columnId: 'c'
+})
+
+describe('board dispatch card state', () => {
+ beforeEach(() => useBoardDispatch.setState({ byKey: {}, startedAt: {} }))
+
+ it('a card never dispatched says nothing', () => {
+ expect(dispatchChipSig(useBoardDispatch.getState(), 'a/b#1')).toBe('')
+ expect(dispatchChipSig(useBoardDispatch.getState(), undefined)).toBe('')
+ })
+
+ it('queued cards carry their place in their own project\'s queue', () => {
+ const s = useBoardDispatch.getState()
+ s.put(dispatchEntry(base('k1'), 'queued', 10))
+ s.put(dispatchEntry(base('k2'), 'queued', 20))
+ s.put(dispatchEntry(base('k3', 'p2'), 'queued', 5))
+ const st = useBoardDispatch.getState()
+ expect(dispatchChipSig(st, 'k1')).toBe('queued||1')
+ expect(dispatchChipSig(st, 'k2')).toBe('queued||2')
+ expect(dispatchChipSig(st, 'k3')).toBe('queued||1')
+ expect(st.queue().map((e) => e.key).sort()).toEqual(['k1', 'k2', 'k3'])
+ })
+
+ it('a refusal carries its reason; starting is not in the queue', () => {
+ const s = useBoardDispatch.getState()
+ s.put(dispatchEntry(base('k1'), 'refused', 1, 'The issue is closed.'))
+ s.put(dispatchEntry(base('k2'), 'starting', 2))
+ const st = useBoardDispatch.getState()
+ expect(dispatchChipSig(st, 'k1')).toBe('refused|The issue is closed.|0')
+ expect(st.queue()).toEqual([])
+ st.remove('k1')
+ expect(dispatchChipSig(useBoardDispatch.getState(), 'k1')).toBe('')
+ })
+})
diff --git a/src/renderer/state/boardDispatch.ts b/src/renderer/state/boardDispatch.ts
new file mode 100644
index 000000000..29ffe9e5d
--- /dev/null
+++ b/src/renderer/state/boardDispatch.ts
@@ -0,0 +1,68 @@
+// Board dispatch's TRANSIENT state: the queue, what is starting, and why a dispatch was refused —
+// what an issue card shows ("Queued for an agent", "Starting…", "Not dispatched: <reason>").
+//
+// In memory only, on purpose: a queue that survived a restart would start agents at boot, while the
+// person who dragged the card may not be there. A restart drops the queue; the cards say nothing
+// afterwards and the drag (or "Start with agent") can be repeated. The consent itself is
+// machine-local settings (`@shared/board-dispatch`).
+
+import { create } from 'zustand'
+import type { IssueRef } from '@shared/github-issue-ref'
+import type { DispatchQueueEntry } from '../lib/boardDispatch'
+
+export type DispatchCardStatus = 'queued' | 'starting' | 'refused'
+
+export interface DispatchCardEntry extends DispatchQueueEntry {
+ status: DispatchCardStatus
+ /** Why nothing started (refused), in the card's words. */
+ reason?: string
+ /** The column the run's session card is filed under (the dispatch column). */
+ columnId: string
+}
+
+interface BoardDispatchState {
+ byKey: Record<string, DispatchCardEntry>
+ /** Node id → when dispatch started it (this app run), for the startup grace of `occupiesSlot`. */
+ startedAt: Record<string, number>
+ put(entry: DispatchCardEntry): void
+ remove(key: string): void
+ markStarted(nodeId: string, at: number): void
+ queue(): DispatchQueueEntry[]
+}
+
+export const useBoardDispatch = create<BoardDispatchState>((set, get) => ({
+ byKey: {},
+ startedAt: {},
+ put: (entry) => set((s) => ({ byKey: { ...s.byKey, [entry.key]: entry } })),
+ remove: (key) =>
+ set((s) => {
+ if (!(key in s.byKey)) return s
+ const { [key]: _gone, ...rest } = s.byKey
+ return { byKey: rest }
+ }),
+ markStarted: (nodeId, at) => set((s) => ({ startedAt: { ...s.startedAt, [nodeId]: at } })),
+ queue: () => Object.values(get().byKey).filter((e) => e.status === 'queued')
+}))
+
+export function dispatchEntry(
+ base: { key: string; projectId: string; ref: IssueRef; number: number; columnId: string },
+ status: DispatchCardStatus,
+ at: number,
+ reason?: string
+): DispatchCardEntry {
+ return { ...base, queuedAt: at, status, ...(reason ? { reason } : {}) }
+}
+
+/** A primitive for one card's chip: `status|reason|position` (position = 1-based place in its
+ * project's queue), so the card re-renders only when its own line changes. */
+export function dispatchChipSig(state: Pick<BoardDispatchState, 'byKey'>, key: string | undefined): string {
+ const e = key ? state.byKey[key] : undefined
+ if (!e) return ''
+ let position = 0
+ if (e.status === 'queued') {
+ for (const other of Object.values(state.byKey)) {
+ if (other.status === 'queued' && other.projectId === e.projectId && other.queuedAt <= e.queuedAt) position++
+ }
+ }
+ return `${e.status}|${e.reason ?? ''}|${position}`
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 1de5cfe60..3be6b4a2a 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -11090,6 +11090,23 @@ button.pull-checks__name {
font-size: 13px;
line-height: 1.6;
}
+/* Board dispatch's line on an issue card (queued / starting / not dispatched). Static text: the
+ run itself shows as a run chip once it exists. */
+.dispatch-chip {
+ margin-top: 6px;
+ font-size: 10px;
+ line-height: 1.4;
+ color: var(--muted);
+}
+.dispatch-chip--starting {
+ color: var(--text);
+}
+.dispatch-chip--refused {
+ color: var(--warn);
+}
+.dispatch-chip__reason {
+ color: var(--muted);
+}
/* GitHub issue ↔ agent session binding. The issue card lists every session started on it as a
live chip (state from the agent-status store — static, no animation: a card can carry several,
and the RUNNING pulse already lives on the session's own card). */
diff --git a/src/shared/board-dispatch.test.ts b/src/shared/board-dispatch.test.ts
new file mode 100644
index 000000000..b16151167
--- /dev/null
+++ b/src/shared/board-dispatch.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest'
+import {
+ BOARD_DISPATCH_MAX_CONCURRENT,
+ clampConcurrent,
+ pruneBoardDispatch,
+ sanitizeBoardDispatch
+} from './board-dispatch'
+
+describe('sanitizeBoardDispatch (settings.json is hand-editable)', () => {
+ it('absent or garbage is off everywhere, not paused', () => {
+ for (const raw of [undefined, null, 5, 'x', [], { projects: [] }, { projects: 'x' }]) {
+ expect(sanitizeBoardDispatch(raw)).toEqual({ paused: false, projects: {} })
+ }
+ })
+
+ it('keeps a well-formed entry', () => {
+ const out = sanitizeBoardDispatch({
+ paused: false,
+ projects: { p1: { columnId: 'col-a', agentId: 'claude', accountId: 'acc1', maxConcurrent: 3 } }
+ })
+ expect(out.projects.p1).toEqual({ columnId: 'col-a', agentId: 'claude', accountId: 'acc1', maxConcurrent: 3 })
+ })
+
+ it('drops an entry with no column or an unsafe agent id — 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' }
+ }
+ })
+ 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 })
+ })
+
+ it('clamps the cap DOWN on anything unreadable, and never above the max', () => {
+ expect(clampConcurrent('9')).toBe(1)
+ expect(clampConcurrent(NaN)).toBe(1)
+ expect(clampConcurrent(0)).toBe(1)
+ expect(clampConcurrent(-3)).toBe(1)
+ expect(clampConcurrent(2.9)).toBe(2)
+ expect(clampConcurrent(999)).toBe(BOARD_DISPATCH_MAX_CONCURRENT)
+ })
+
+ it('the kill switch is on only for a literal true', () => {
+ expect(sanitizeBoardDispatch({ paused: true }).paused).toBe(true)
+ expect(sanitizeBoardDispatch({ paused: 'true' }).paused).toBe(false)
+ expect(sanitizeBoardDispatch({ paused: 1 }).paused).toBe(false)
+ })
+})
+
+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' } }
+ })
+ const out = pruneBoardDispatch(value, new Set(['keep']))
+ expect(out.paused).toBe(true)
+ expect(Object.keys(out.projects)).toEqual(['keep'])
+ })
+})
diff --git a/src/shared/board-dispatch.ts b/src/shared/board-dispatch.ts
new file mode 100644
index 000000000..098592bbc
--- /dev/null
+++ b/src/shared/board-dispatch.ts
@@ -0,0 +1,83 @@
+// Board dispatch: a GitHub issue card that THIS person drags into a chosen column starts its own
+// agent run ("Start with agent", without the click). This module is the machine-local consent — the
+// switch, the column, the agent and the cap — and the one reader of it.
+//
+// MACHINE-LOCAL BY CONSTRUCTION, the same tier as the trigger arm store and
+// `kanbanPullAutoMove`: it lives in settings.json, never in `.nodeterm/project.json`. The project
+// file is written by anyone who can commit to the repository; a dispatch switch there would let a
+// pull request make every clone start agents. The column id it names is a board column (shared
+// content), but WHETHER dropping a card on it runs an agent here is this machine's decision.
+//
+// settings.json is hand-editable, so everything goes through `sanitizeBoardDispatch`. Every
+// failure direction is "fewer runs": an unreadable entry is OFF and an unreadable cap is 1. The
+// kill switch is on only for a literal `true`; an absent or unreadable block already dispatches
+// nothing, because no project is switched on.
+
+export const BOARD_DISPATCH_MAX_CONCURRENT = 8
+export const BOARD_DISPATCH_DEFAULT_CONCURRENT = 2
+
+export interface BoardDispatchProject {
+ /** The column a card must be dragged INTO. A column deleted since then dispatches nothing. */
+ columnId: string
+ /** Which agent a dispatched run opens (a builtin id or `custom:<uuid>`). */
+ agentId: string
+ /** The account the run opens under; absent = the project default (the "New <agent>" funnel). */
+ accountId?: string
+ /** Live runs this project may have at once; further dispatches queue. 1..8. */
+ maxConcurrent: number
+}
+
+export interface BoardDispatch {
+ /** The kill switch: nothing dispatches and the queue is dropped while it is on. */
+ paused: boolean
+ projects: Record<string, BoardDispatchProject>
+}
+
+const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9:_.-]{0,127}$/
+
+function safeId(value: unknown): value is string {
+ return typeof value === 'string' && SAFE_ID.test(value)
+}
+
+function projectKey(value: unknown): value is string {
+ return typeof value === 'string' && value.length > 0 && value.length <= 256
+}
+
+/** Out-of-range or unreadable caps clamp DOWN: a guessed higher cap is more runs than consented. */
+export function clampConcurrent(value: unknown): number {
+ if (typeof value !== 'number' || !Number.isFinite(value)) return 1
+ const n = Math.floor(value)
+ if (n < 1) return 1
+ return Math.min(n, BOARD_DISPATCH_MAX_CONCURRENT)
+}
+
+export function sanitizeBoardDispatch(raw: unknown): BoardDispatch {
+ const value = raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {}
+ const projectsRaw =
+ value.projects && typeof value.projects === 'object' && !Array.isArray(value.projects)
+ ? (value.projects as Record<string, unknown>)
+ : {}
+ const projects: Record<string, BoardDispatchProject> = {}
+ for (const [projectId, entryRaw] of Object.entries(projectsRaw).slice(0, 500)) {
+ const entry = entryRaw && typeof entryRaw === 'object' && !Array.isArray(entryRaw)
+ ? (entryRaw as Record<string, unknown>)
+ : null
+ if (!projectKey(projectId) || !entry) continue
+ if (!projectKey(entry.columnId) || !safeId(entry.agentId)) continue
+ projects[projectId] = {
+ columnId: entry.columnId,
+ agentId: entry.agentId,
+ ...(safeId(entry.accountId) ? { accountId: entry.accountId } : {}),
+ maxConcurrent: clampConcurrent(entry.maxConcurrent)
+ }
+ }
+ return { paused: value.paused === true, projects }
+}
+
+/** Drops projects this machine no longer has (closed ones are kept — closing parks). */
+export function pruneBoardDispatch(value: BoardDispatch, liveProjectIds: ReadonlySet<string>): BoardDispatch {
+ return {
+ paused: value.paused,
+ projects: Object.fromEntries(Object.entries(value.projects).filter(([id]) => liveProjectIds.has(id)))
+ }
+}
diff --git a/src/shared/settings-verb.test.ts b/src/shared/settings-verb.test.ts
index 6328346ae..b3b589834 100644
--- a/src/shared/settings-verb.test.ts
+++ b/src/shared/settings-verb.test.ts
@@ -47,7 +47,8 @@ describe('the allowlist is the gate, and the forbidden set outranks it', () => {
// `customAgents` (it defines what command a custom agent runs), `agentMessagingDefault` — the
// obvious `agent` term would also forbid `agentMessaging`, the key this verb exists to set —
// and `agentIssueReporting`, where none of `report`, `issue` or `github` is a forbidden name
- // class and adding one would be guessing at words rather than at capabilities.
+ // class and adding one would be guessing at words rather than at capabilities. `boardDispatch`
+ // (an agent switching on the dispatcher would grant itself more agents) escapes it too.
// For those two the set is the only fence, so the only change that could make them settable —
// allowlist the key AND drop it from the set, in one edit — must redden a test. This one.
expect([...SETTINGS_VERB_FORBIDDEN].sort()).toEqual([
@@ -55,6 +56,7 @@ describe('the allowlist is the gate, and the forbidden set outranks it', () => {
'agentIssueReporting',
'agentLaunchCommands',
'agentMessagingDefault',
+ 'boardDispatch',
'capabilityAck',
'claudeAccounts',
'claudePermissionMode',
@@ -83,7 +85,7 @@ describe('the allowlist is the gate, and the forbidden set outranks it', () => {
// adding it here is the correct response — it records that the set is that key's only fence.
expect(
[...SETTINGS_VERB_FORBIDDEN].filter((k) => !SETTINGS_VERB_FORBIDDEN_PATTERN.test(k)).sort()
- ).toEqual(['agentIssueReporting', 'agentMessagingDefault', 'customAgents'])
+ ).toEqual(['agentIssueReporting', 'agentMessagingDefault', 'boardDispatch', 'customAgents'])
for (const key of SETTINGS_VERB_KEY_LIST) expect(SETTINGS_VERB_FORBIDDEN_PATTERN.test(key), key).toBe(false)
})
diff --git a/src/shared/settings-verb.ts b/src/shared/settings-verb.ts
index b06cc5c73..d29a53488 100644
--- a/src/shared/settings-verb.ts
+++ b/src/shared/settings-verb.ts
@@ -134,6 +134,10 @@ export const SETTINGS_VERB_FORBIDDEN = new Set<keyof Settings | keyof Project>([
// guessing at words rather than at capabilities), so this entry is the key's ONLY fence — which
// is why it is also named in settings-verb.test.ts's escapees tripwire.
'agentIssueReporting',
+ // Board dispatch — starting agent runs by itself. An agent that could switch it on (or lift its
+ // kill switch, or raise its cap) would grant itself more agents; its consent is the person's own.
+ // The name pattern does not catch it, so this entry is its only fence.
+ 'boardDispatch',
// This machine's consent record for capabilities; writable only by the human's answer.
'capabilityAck',
// Accounts, credentials, model gateway, and anything that decides WHAT COMMAND runs.
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 9eb729bc7..546f61e0e 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -22,6 +22,7 @@ import type { ClientId, DinoSnapshot, PeerDiff, PeerIdentity, PeerState } from '
import type { WhisperModelInfo } from './speech'
import type { ProjectKanbanGitHub } from './github-issues'
import type { KanbanPullAutoMove, KanbanPullLinks } from './kanban-pull-links'
+import type { BoardDispatch } from './board-dispatch'
import type { CodexAccount } from './codex-account'
import type { NotchAlign } from './notch-hud'
import type { ProjectIcon, ProjectIconPickResult } from './project-icon'
@@ -2059,6 +2060,12 @@ export interface Settings {
* and absent from DEFAULT_SETTINGS — means off everywhere. Read through
* `sanitizeKanbanPullAutoMove`: settings.json is hand-editable. */
kanbanPullAutoMove?: KanbanPullAutoMove
+ /** Machine-local board dispatch: which projects start an agent run when this person moves a
+ * GitHub issue card into a chosen column, with which agent and how many at once, plus the kill
+ * switch (@shared/board-dispatch — why this is here and never in the project file). Absent —
+ * and absent from DEFAULT_SETTINGS — means off everywhere. Read through
+ * `sanitizeBoardDispatch`: settings.json is hand-editable. */
+ boardDispatch?: BoardDispatch
}
export const DEFAULT_SETTINGS: Settings = {