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(control): a turn that ends with background tasks running does not release --after

reviewe20bb9785468
diff --git a/CLAUDE.md b/CLAUDE.md
index 1d84e48d2..b64dcbd2a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3852,6 +3852,20 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
`--after` would hold. The Server Edition's factory asks `handedOver` in `refreshArmed` AND in the
creation shortcut (`mustWait`): "already satisfied at creation" must mean satisfied under this
rule, or the node is launched immediately by the shortcut.
+ - **Background tasks hold the same way** (same module, same list; `background: true` on the
+ record). MEASURED live 2026-09-30: an agent's turn ended while its full test suite still ran in
+ a background shell, and the node armed `--after` it fired before anything was pushed — the same
+ bug class, from background work instead of a hand-over. Claude's `Stop` carries
+ `background_tasks` (see **Claude's native subagent hooks**, fact 6), normalized to
+ `backgroundTaskIds`. A `done` whose inventory lists a live task holds the station; only a later
+ `done` whose inventory is PRESENT and EMPTY releases it, or `SessionEnd` (the CLI took its tasks
+ with it and will never report them). An ABSENT inventory is unknown and changes NOTHING: a CLI
+ too old to send the field keeps today's behaviour exactly (it never sets the hold — holding on
+ "unknown" would strand every such station forever), and a `done` without one (the idle-prompt
+ rescue, `StopFailure`, other agents) neither sets nor clears it. A turn STARTING does not clear
+ it (the task may outlive that turn). A task that finishes without waking the station for another
+ turn leaves the hold until the station's next turn end — holding, with ▶ / `run` as the way out.
+ The agent bodies tell a station not to end its turn with background work a dependent needs.
- **Eviction never drops a held station** (the bound is 2000 tracked stations; the oldest with
nothing handed over goes first) — dropping one would release its dependents.
- Surfaces: `list` says `waiting for <station> to finish the work handed to it`; the QUEUED tooltip
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 9adbb2a3b..d098227b6 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -270,7 +270,13 @@ function afterHandoverDocLines(): string[] {
'- So to reuse a station, hand it the next task FIRST, then open the dependent `--after` it — opened',
' first, the dependent would start at once on the previous task\'s output. `list` marks such a',
' dependent "waiting for <station> to finish the work handed to it". A person typing in the',
- " station's pane is not a hand-over. `run` (or the user's ▶) always starts a held node anyway."
+ " station's pane is not a hand-over. `run` (or the user's ▶) always starts a held node anyway.",
+ '- A turn that ENDS with background tasks still running (a background shell, an async subagent —',
+ ' Claude reports them when its turn ends) has not finished either: `--after` on that station waits',
+ ' for a later turn end that reports none (`list`: "waiting for <station> to finish the tasks still',
+ ' running in its background"). If YOU are the station, do not end your turn with background work',
+ ' whose result a dependent needs; wait for it, then finish. Agents that do not report background',
+ ' tasks release on their turn end as before.'
]
}
diff --git a/src/core/station-handover.test.ts b/src/core/station-handover.test.ts
index f2f1feadc..f3e4ba934 100644
--- a/src/core/station-handover.test.ts
+++ b/src/core/station-handover.test.ts
@@ -136,6 +136,55 @@ describe('StationHandoverTracker — when a station counts as finished for plain
expect(h.t.list().map((r) => r.nodeId)).toEqual(['st'])
})
+ describe('background tasks left running at a turn end (Claude `Stop.background_tasks`)', () => {
+ const stop = (t: StationHandoverTracker, ids?: string[]) =>
+ t.onAgentEvent({ nodeId: 'st', state: 'done', ...(ids ? { backgroundTaskIds: ids } : {}) })
+
+ it('a done that still lists a running task holds; a later done with an EMPTY inventory releases', () => {
+ const h = tracker()
+ h.ev('working', 100)
+ stop(h.t, ['bash_1'])
+ expect(h.t.isHandedOver('st')).toBe(true)
+ expect(h.t.list()).toEqual([{ nodeId: 'st', background: true }])
+ // A turn starting does not end it: the task may outlive that turn.
+ h.ev('working', 200)
+ expect(h.t.isHandedOver('st')).toBe(true)
+ stop(h.t, [])
+ expect(h.t.isHandedOver('st')).toBe(false)
+ })
+
+ it('an ABSENT inventory is unknown: it neither sets the hold (older CLI) nor clears it', () => {
+ const h = tracker()
+ h.ev('working', 100)
+ stop(h.t) // a CLI too old to send the field: today's behaviour
+ expect(h.t.isHandedOver('st')).toBe(false)
+ stop(h.t, ['agent_1'])
+ h.ev('done', 300) // the idle-prompt rescue / StopFailure carry no inventory
+ expect(h.t.isHandedOver('st')).toBe(true)
+ })
+
+ it('SessionEnd ends it: the CLI took its tasks with it and will never report them', () => {
+ const h = tracker()
+ h.ev('working', 100)
+ stop(h.t, ['bash_1'])
+ h.t.onAgentEvent({ nodeId: 'st', state: undefined, sessionPhase: 'end' })
+ expect(h.t.isHandedOver('st')).toBe(false)
+ })
+
+ it('background work and a hand-over hold independently', () => {
+ const h = tracker()
+ h.ev('working', 100)
+ stop(h.t, ['bash_1'])
+ h.t.noteControlAnswer('write', { node: 'st' }, { ok: true }, 'orch', h.at(150))
+ h.ev('working', 160)
+ stop(h.t, ['bash_1']) // the new work's turn ended, the background task still runs
+ expect(h.t.list()).toEqual([{ nodeId: 'st', background: true }])
+ h.ev('working', 200)
+ stop(h.t, [])
+ expect(h.t.isHandedOver('st')).toBe(false)
+ })
+ })
+
it('ignores unsafe ids and stateless events', () => {
const h = tracker()
h.t.markHandedOver('../x', 5)
diff --git a/src/core/station-handover.ts b/src/core/station-handover.ts
index dd0efc715..ae4062c98 100644
--- a/src/core/station-handover.ts
+++ b/src/core/station-handover.ts
@@ -28,6 +28,23 @@
* current turn instead, the hold lasts until the next turn — the holding direction, with ▶ and
* `run` as the way out).
*
+ * BACKGROUND WORK is the second kind of unfinished work, and it holds the same way. Claude's `Stop`
+ * carries `background_tasks` — every background task of the session still running at that turn end
+ * (background shells, async subagents; `NormalizedAgentEvent.backgroundTaskIds`). A turn that ends
+ * with such a task running has not finished the station's work: the output the dependent is armed
+ * to read is still being produced (measured live, 2026-09-30: an agent's turn ended while its test
+ * suite ran in a background shell, and the node armed `--after` it fired before anything was
+ * pushed). So a `done` whose inventory lists a live task holds the station, and only a later
+ * `done` whose inventory is PRESENT and EMPTY releases it. Three decisions:
+ * - an ABSENT inventory is "unknown", never "none" — and it changes nothing: a CLI too old to send
+ * the field never sets the hold (today's behaviour, exactly), and a `done` without one (the
+ * idle-prompt rescue, a `StopFailure`, another agent) neither sets nor clears it;
+ * - the hold is not cleared by a turn STARTING (the tasks may well outlive it) — only by a turn
+ * end that says they are gone, or by `SessionEnd` (the CLI exited, taking its tasks with it;
+ * waiting on a session that will never report again would strand the dependent);
+ * - a background task that finishes WITHOUT waking the station for another turn leaves the hold
+ * up until the station's next turn end. That is the holding direction, and ▶ / `run` end it.
+ *
* NOT a hand-over: a board comment (a person steering), a station notice (the app telling an
* orchestrator something), a person typing in the pane. Deliberately the same set #1042 counts.
*
@@ -61,6 +78,12 @@ interface StationTrack {
queued: number
/** The newest hand-over that no finished turn has answered yet. */
handedAt?: number
+ /** The last turn end listed background tasks still running (see the header). */
+ background?: boolean
+}
+
+function holds(t: StationTrack): boolean {
+ return t.queued > 0 || t.handedAt !== undefined || t.background === true
}
export class StationHandoverTracker {
@@ -82,7 +105,7 @@ export class StationHandoverTracker {
while (this.byId.size > STATION_HANDOVER_MAX_TRACKED) {
let victim: string | undefined
for (const [id, t] of this.byId) {
- if (id !== nodeId && t.queued <= 0 && t.handedAt === undefined) {
+ if (id !== nodeId && !holds(t)) {
victim = id
break
}
@@ -107,7 +130,9 @@ export class StationHandoverTracker {
private changed(): void {
const list = this.list()
- const sig = list.map((r) => `${r.nodeId}:${r.since ?? ''}:${r.queued ? 1 : 0}`).join('|')
+ const sig = list
+ .map((r) => `${r.nodeId}:${r.since ?? ''}:${r.queued ? 1 : 0}:${r.background ? 1 : 0}`)
+ .join('|')
if (sig === this.lastSig) return
this.lastSig = sig
this.publish(list)
@@ -115,9 +140,22 @@ export class StationHandoverTracker {
/** Every agent event of every node, fed BEFORE anything that acts on it (the Server Edition's
* `refreshArmed`, the messaging queue's flush on `done`). Events without a state are ignored. */
- onAgentEvent(event: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>): void {
- const state = event?.state
- if (!event?.nodeId || !isSafeNodeId(event.nodeId) || typeof state !== 'string') return
+ onAgentEvent(
+ event: Pick<NormalizedAgentEvent, 'nodeId' | 'state'> &
+ Partial<Pick<NormalizedAgentEvent, 'backgroundTaskIds' | 'sessionPhase'>>
+ ): void {
+ if (!event?.nodeId || !isSafeNodeId(event.nodeId)) return
+ // The CLI exited: its background tasks died with it, and it will never report them finished.
+ if (event.sessionPhase === 'end') {
+ const t = this.byId.get(event.nodeId)
+ if (t?.background) {
+ t.background = false
+ this.changed()
+ }
+ return
+ }
+ const state = event.state
+ if (typeof state !== 'string') return
const t = this.touch(event.nodeId)
if (ACTIVE.has(state)) {
if (!t.state || !ACTIVE.has(t.state)) t.turnStartedAt = this.now()
@@ -126,6 +164,8 @@ export class StationHandoverTracker {
}
t.state = state
if (state === 'done') {
+ // Only a PRESENT inventory speaks about background work; an absent one is unknown.
+ if (Array.isArray(event.backgroundTaskIds)) t.background = event.backgroundTaskIds.length > 0
this.settle(t)
this.changed()
}
@@ -179,21 +219,23 @@ export class StationHandoverTracker {
}
}
- /** Is `--after` on this station held by unfinished handed-over work? */
+ /** Is `--after` on this station held by unfinished work — handed over, or still running in the
+ * background of its last turn? */
isHandedOver(nodeId: string): boolean {
const t = this.byId.get(nodeId)
- return !!t && (t.queued > 0 || t.handedAt !== undefined)
+ return !!t && holds(t)
}
/** Every station with unfinished handed-over work, newest first. */
list(): StationHandoverRecord[] {
const out: StationHandoverRecord[] = []
for (const [nodeId, t] of [...this.byId.entries()].reverse()) {
- if (t.queued <= 0 && t.handedAt === undefined) continue
+ if (!holds(t)) continue
out.push({
nodeId,
...(t.handedAt !== undefined ? { since: t.handedAt } : {}),
- ...(t.queued > 0 ? { queued: true as const } : {})
+ ...(t.queued > 0 ? { queued: true as const } : {}),
+ ...(t.background ? { background: true as const } : {})
})
}
return out
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index e00289168..97c6a8319 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -1532,6 +1532,9 @@ describe('--after-success + report-outcome: a dependent that waits for a reporte
expect(flat).toContain('hand it the next task FIRST, then open the dependent `--after` it')
expect(flat).toContain('"waiting for <station> to finish the work handed to it"')
expect(flat).toContain("A person typing in the station's pane is not a hand-over")
+ expect(flat).toContain('A turn that ENDS with background tasks still running')
+ expect(flat).toContain('waits for a later turn end that reports none')
+ expect(flat).toContain('"waiting for <station> to finish the tasks still running in its background"')
})
it.each(bodies)('%s teaches stations to report, honestly, about themselves only', (_name, body) => {
diff --git a/src/renderer/canvas/control-after-pr.source.test.ts b/src/renderer/canvas/control-after-pr.source.test.ts
index 7728e8e37..c2aa242f8 100644
--- a/src/renderer/canvas/control-after-pr.source.test.ts
+++ b/src/renderer/canvas/control-after-pr.source.test.ts
@@ -105,7 +105,7 @@ describe('the launch loop judges the wait on the ACTIVE project’s pull request
})
it('re-runs when a waited-on pull request changes, off a PRIMITIVE signature', () => {
- expect(src).toMatch(/\}, \[nodes, armedDepSig, armedSetupSig, armedPrSig, armedSuccessSig, launchNudge\]\)/)
+ expect(src).toMatch(/\}, \[nodes, armedDepSig, armedHandoverSig, armedSetupSig, armedPrSig, armedSuccessSig, launchNudge\]\)/)
const sig = slice('const armedPrSig = useGitHubIssues((s) => {', '})')
expect(sig).toContain('prHoldReports(')
expect(sig).toContain("sig +=")
@@ -134,6 +134,6 @@ describe('the node badge', () => {
it('reads EXPIRED and hands the PR wait to the tooltip', () => {
expect(node).toMatch(/prExpired \|\| successExpired\s*\?\s*'⚠ EXPIRED'/)
- expect(node).toMatch(/launchTooltip\([^)]*prTooltip, successTooltip\)/)
+ expect(node).toMatch(/launchTooltip\([^)]*prTooltip, successTooltip, pendingHandedOverOn\)/)
})
})
diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.ts
index 50d31e912..a0c91e186 100644
--- a/src/renderer/lib/controlRouting.test.ts
+++ b/src/renderer/lib/controlRouting.test.ts
@@ -369,6 +369,13 @@ describe('storedNodeListing — a dependent held by work handed to its station (
expect(controlListingText(rows).split('\n')[1]).toBe(
'd [terminal] Reviewer — QUEUED — waiting for st "Builder" to finish the work handed to it'
)
+ // Only background tasks left running: named as such.
+ const bg = storedNodeListing(nodes, statuses, {}, 0, {}, { st: { nodeId: 'st', background: true } })
+ expect(bg[1]).toMatchObject({ backgroundWait: 'st "Builder"' })
+ expect(bg[1]).not.toHaveProperty('handoverWait')
+ expect(controlListingText(bg).split('\n')[1]).toBe(
+ 'd [terminal] Reviewer — QUEUED — waiting for st "Builder" to finish the tasks still running in its background'
+ )
// Nothing handed over: the row is what it always was.
expect(storedNodeListing(nodes, statuses, {}, 0, {}, {})[1]).not.toHaveProperty('handoverWait')
})
diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.ts
index dcc1d1c0d..4ecbaaf49 100644
--- a/src/renderer/lib/controlRouting.ts
+++ b/src/renderer/lib/controlRouting.ts
@@ -27,6 +27,7 @@ import { prHoldExpired } from './prWait'
import {
controlLaunchState,
handedOverDeps,
+ holdReason,
successDepFacts,
type HandoverById,
type LaunchDelivery,
@@ -256,7 +257,12 @@ export function storedNodeListing(
...(launchState ? { launchState } : {}),
...(launchState === 'queued' && prHold && !prHold.invalid ? { prWait: formatPrWaits(prHold) } : {}),
...(successWait ? { successWait } : {}),
- ...(handedOver.length ? { handoverWait: handedOver.map(titleOf).join(', ') } : {}),
+ ...(handedOver.some((d) => holdReason(handovers[d]) === 'work')
+ ? { handoverWait: handedOver.filter((d) => holdReason(handovers[d]) === 'work').map(titleOf).join(', ') }
+ : {}),
+ ...(handedOver.some((d) => holdReason(handovers[d]) === 'background')
+ ? { backgroundWait: handedOver.filter((d) => holdReason(handovers[d]) === 'background').map(titleOf).join(', ') }
+ : {}),
...(reported
? {
outcome: reported.outcome,
@@ -290,6 +296,7 @@ export function controlListingText(rows: ReturnType<typeof storedNodeListing>):
(n.prWait ? ` — waits on ${n.prWait}` : '') +
(n.successWait ? ` — needs success from: ${n.successWait}` : '') +
(n.handoverWait ? ` — waiting for ${n.handoverWait} to finish the work handed to it` : '') +
+ (n.backgroundWait ? ` — waiting for ${n.backgroundWait} to finish the tasks still running in its background` : '') +
(n.outcome ? ` — REPORTED ${n.outcome === 'succeeded' ? 'SUCCESS' : 'FAILURE'}${n.outcomeNote ? ` ("${n.outcomeNote}")` : ''}` : '') +
(n.outcomeSuperseded ? ' (before new work queued for it; not counted until it reports again)' : '') +
(n.lastTurnErrored ? ' — LAST TURN ERRORED' : '')
diff --git a/src/renderer/lib/pendingLaunch.test.ts b/src/renderer/lib/pendingLaunch.test.ts
index 896ba4b9b..db2360281 100644
--- a/src/renderer/lib/pendingLaunch.test.ts
+++ b/src/renderer/lib/pendingLaunch.test.ts
@@ -593,7 +593,7 @@ describe('plain --after on a station handed new work (core/station-handover.ts)'
it('the tooltip says what the wait is for, not "waiting for X to finish" about an idle X', () => {
const text = launchTooltip(undefined, 'Builder, Tester', 'claude go', undefined, false, undefined, undefined, 'Builder')
expect(text).toBe(
- 'Waiting for Builder to finish the work just handed to it — its earlier turn does not count ' +
+ 'Waiting for Builder to finish — a turn that ended before that work was done does not count ' +
'(all waits: Builder, Tester), then runs:\nclaude go'
)
// An errored upstream is still named first: it will not end on its own.
diff --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.ts
index a5801f1e8..97b53ff08 100644
--- a/src/renderer/lib/pendingLaunch.ts
+++ b/src/renderer/lib/pendingLaunch.ts
@@ -247,6 +247,12 @@ function depSatisfied(
/** Of the deps this node is still waiting on, which are held because they were handed new work
* they have not finished — what the QUEUED tooltip and `list` name. */
+/** Why a dep is held (see `handedOverDeps`): new work handed to it, or ONLY tasks its last turn left
+ * running in the background. Named differently in the tooltip and in `list`. */
+export function holdReason(record: StationHandoverRecord | undefined): 'work' | 'background' {
+ return record?.background && !record.queued && record.since === undefined ? 'background' : 'work'
+}
+
export function handedOverDeps(
node: ArmedNode,
live: ReadonlySet<string>,
@@ -467,7 +473,7 @@ export function launchTooltip(
// X to finish" alone would read as a wait that should already be over.
if (handedOverOn)
return (
- `Waiting for ${handedOverOn} to finish the work just handed to it — its earlier turn does not ` +
+ `Waiting for ${handedOverOn} to finish — a turn that ended before that work was done does not ` +
`count${waitingOn ? ` (all waits: ${waitingOn})` : ''}, then runs:\n${command}`
)
if (success?.status === 'waiting') {
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 9f9364f0f..ee3e673da 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -234,7 +234,7 @@ import { useCodexIdentity, codexSharedIdentity, codexFallbackText } from '../sta
import { codexApprovalCaps } from '../state/codexCli'
import { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'
import { useLaunchDelivery } from '../state/launchDelivery'
-import { erroredDeps, handedOverDeps, launchTooltip } from '../lib/pendingLaunch'
+import { erroredDeps, handedOverDeps, holdReason, launchTooltip } from '../lib/pendingLaunch'
import { useStationHandovers } from '../state/stationHandovers'
import { useSuccessWait } from '../lib/useSuccessWait'
import { StationFailedChip } from '../components/StationFailedChip'
@@ -2129,12 +2129,20 @@ export function TerminalNode({
const after = pendingLaunch?.after ?? []
if (!after.length) return ''
const live = new Set(after.filter((d) => !!getNode(d)))
- return handedOverDeps({ id, data: { pendingLaunch } }, live, s.byId).join(',')
+ return handedOverDeps({ id, data: { pendingLaunch } }, live, s.byId)
+ .map((d) => `${d}:${holdReason(s.byId[d])}`)
+ .join(',')
})
const pendingHandedOverOn = handedOverDepIds
? handedOverDepIds
.split(',')
- .map((depId) => ((getNode(depId) as CanvasNode | undefined)?.data.title as string) || depId)
+ .map((entry) => {
+ const [depId, reason] = entry.split(':')
+ const title = ((getNode(depId) as CanvasNode | undefined)?.data.title as string) || depId
+ return reason === 'background'
+ ? `${title} (tasks still running in its background)`
+ : `${title} (the work just handed to it)`
+ })
.join(', ')
: undefined
const pendingErroredOn = erroredDepIds
diff --git a/src/renderer/nodes/session-ready-signal.test.ts b/src/renderer/nodes/session-ready-signal.test.ts
index 05e2e8eeb..ad85ad8b3 100644
--- a/src/renderer/nodes/session-ready-signal.test.ts
+++ b/src/renderer/nodes/session-ready-signal.test.ts
@@ -102,7 +102,7 @@ describe('the QUEUED badge carries the delivery state (source pins)', () => {
// arguments name an `--after-pr` wait and an `--after-success` wait (with their deadlines)
// beside the stations.
expect(src).toContain(
- "launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay', prTooltip, successTooltip)"
+ "launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay', prTooltip, successTooltip, pendingHandedOverOn)"
)
})
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index 2a9f3a446..64b06dd1c 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -1,4 +1,5 @@
import fs from 'node:fs'
+import { StationHandoverTracker } from '../core/station-handover'
import os from 'node:os'
import path from 'node:path'
@@ -1262,6 +1263,32 @@ describe('HeadlessNodeFactory', () => {
expect(pty.sends).toEqual([{ nodeId: id, text: "claude 'consume result'" }])
})
+ it('with a REAL tracker, a done still listing background tasks holds; an empty one releases', async () => {
+ // Wired as canvas-control.ts wires it: the tracker is fed every event BEFORE the factory.
+ const tracker = new StationHandoverTracker()
+ handedOver = { has: (id: string) => tracker.isHandedOver(id) } as unknown as Set<string>
+ const feed = (ev: { nodeId: string; state: 'working' | 'done'; backgroundTaskIds?: string[] }) => {
+ states[ev.nodeId] = ev.state
+ tracker.onAgentEvent(ev)
+ factory.onAgentEvent(ev)
+ }
+ feed({ nodeId: 'term-upstream', state: 'working' })
+ const reply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'consume result', after: 'term-upstream' },
+ true
+ )
+ const id = (reply.result as { id: string }).id
+ feed({ nodeId: 'term-upstream', state: 'done', backgroundTaskIds: ['bash_suite'] })
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([])
+ feed({ nodeId: 'term-upstream', state: 'working' })
+ feed({ nodeId: 'term-upstream', state: 'done', backgroundTaskIds: [] })
+ await factory.refreshArmed()
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([{ nodeId: id, text: "claude 'consume result'" }])
+ })
+
it('a success wait holds too: its turn is not over while handed-over work is unfinished', async () => {
states['term-upstream'] = 'done'
outcomes['term-upstream'] = { nodeId: 'term-upstream', outcome: 'succeeded', at: Date.now() }
diff --git a/src/shared/station-handover.ts b/src/shared/station-handover.ts
index 0d43b4aa0..59b37df5a 100644
--- a/src/shared/station-handover.ts
+++ b/src/shared/station-handover.ts
@@ -9,6 +9,9 @@
// `--after-success` (a report stops counting once new work is handed over); this is the plain-turn
// half.
//
+// The same hold covers BACKGROUND work: a turn that ended with background tasks still running
+// (Claude's `background_tasks` on `Stop`) has not finished what a dependent is armed to read.
+//
// THE RULE (decided in core, `core/station-handover.ts`; this module is only the wire shape): a
// station is "handed over" from the moment new work is queued for it, or lands in its pane, until a
// turn that STARTED at or after that hand-over has ENDED. While it is, `--after` on it is not
@@ -29,6 +32,9 @@ export interface StationHandoverRecord {
since?: number
/** A `send` / `reply` is still waiting in the station's queue. */
queued?: true
+ /** The station's last turn ended with background tasks still running (Claude's
+ * `background_tasks`): its output is still being produced. */
+ background?: true
}
/** Parse a pushed / pulled list defensively: it crosses a process boundary (and, in the Server
@@ -44,7 +50,8 @@ export function sanitizeHandoverRecords(raw: unknown): StationHandoverRecord[] {
out.push({
nodeId: r.nodeId,
...(since !== undefined ? { since } : {}),
- ...(r.queued === true ? { queued: true as const } : {})
+ ...(r.queued === true ? { queued: true as const } : {}),
+ ...(r.background === true ? { background: true as const } : {})
})
}
return out
diff --git a/test/acceptance/after-handover.test.ts b/test/acceptance/after-handover.test.ts
index b3c67b86d..530895fd0 100644
--- a/test/acceptance/after-handover.test.ts
+++ b/test/acceptance/after-handover.test.ts
@@ -217,6 +217,35 @@ describe('plain --after after a write / run', () => {
})
})
+describe('plain --after on a station whose turn ended with BACKGROUND tasks still running', () => {
+ // Measured live (2026-09-30): an agent's turn ended while its test suite still ran in a
+ // background shell, and the node armed `--after` it fired before anything had been pushed.
+ const stop = (h: Harness, ids: string[] | undefined) => {
+ h.tick(10)
+ h.state.st = 'done'
+ h.tracker.onAgentEvent({ nodeId: 'st', state: 'done', ...(ids ? { backgroundTaskIds: ids } : {}) })
+ }
+
+ it('a done listing a running task does not release D; a later done with an empty inventory does', () => {
+ const h = harness()
+ h.event('working')
+ stop(h, ['bash_suite'])
+ expect(dFires(h)).toBe(false)
+ // The suite finishes and wakes the station (or the next prompt does); that turn's end is empty.
+ h.event('working')
+ expect(dFires(h)).toBe(false)
+ stop(h, [])
+ expect(dFires(h)).toBe(true)
+ })
+
+ it('a CLI that sends no inventory keeps today\'s behaviour: its done releases D', () => {
+ const h = harness()
+ h.event('working')
+ stop(h, undefined)
+ expect(dFires(h)).toBe(true)
+ })
+})
+
describe('the ordinary case is unchanged', () => {
it('a station nobody handed anything fires D on its done, as before', () => {
const h = harness()