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(renderer): exclude background-task nodes from Eco and bulk restart

enes4e758b936e4a
diff --git a/docs/superpowers/plans/2026-08-12-background-task-guard.md b/docs/superpowers/plans/2026-08-12-background-task-guard.md
new file mode 100644
index 000000000..e43e46416
--- /dev/null
+++ b/docs/superpowers/plans/2026-08-12-background-task-guard.md
@@ -0,0 +1,176 @@
+# Background-Task Guard Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A live Claude Code background shell task (`Bash` with `run_in_background: true`) protects its node from Eco hibernation and from the bulk "Restart idle agents" action — closing the one signal-less `/exit`-kills-work gap left by PR #130.
+
+**Architecture:** Approved spec: `docs/superpowers/specs/2026-08-12-background-task-hibernation-guard-design.md` (on disk beside this plan; force-add BOTH files in this PR — `/docs/superpowers/` is gitignored, plans/specs ride feature PRs by convention). Approach A: normalize emits a `background-task` event from Claude's `PreToolUse` (replacing the generic "working" for that one call — harmless, the turn is full of other working events); `agentStatus` stamps transient `backgroundTaskAt`, cleared only at a **turn START** (`done`/`undefined` → `working`; a `blocked`/`waiting` → `working` resumption keeps it — see the spec's §2); `planHibernation` and `planBulkRestart` exclude stamped nodes (bulk counts them in the frozen `skipped.working` bucket). Single-node restart untouched (user decision).
+
+**Tech Stack:** TypeScript, vitest. Two tasks, one PR.
+
+## Global Constraints
+
+- Branch off **origin/main** in a worktree; anchors below were read from origin/main on 2026-08-12 (`git show origin/main:<path>` — the main checkout is stale and belongs to a parallel session; NEVER commit there).
+- Gates per task: `npm run typecheck` + the named vitest files; full `npm test` before the PR.
+- English code/comments, constraint-style; CLAUDE.md rule 7 (closed sets — claude-only signal, no speculative widening) and rule 2 (grep what else a list/type gates before joining it).
+- `agent-restart.test.ts` pre-existing tests must stay green **unmodified** (the Task 8 pin discipline).
+- The bulk summary line is spec-frozen at four parts — background-task skips land in `skipped.working`, never a fifth part.
+
+---
+
+### Task 1: Signal + store (normalize event, agentStatus stamp/clear, Canvas wiring)
+
+**Files:**
+- Modify: `src/shared/agents/normalize.ts` (kind union at `:10`; `ClaudePayload.tool_input` type at `:92`; the claude `PreToolUse` branch — insert BEFORE the `// Any other tool use is just "working".` fallback)
+- Modify: `src/renderer/state/agentStatus.ts` (transient field + action + clear in `setState`'s transition branch)
+- Modify: `src/renderer/canvas/Canvas.tsx` (the `agent:status` listener — add a case beside the `recurring` handling; grep `kind === 'recurring'`)
+- Test: `src/shared/agents/normalize.test.ts` (extend), `src/renderer/state/agentStatus` test files (extend the persistence + setState suites; grep `agentStatus.persist.test.ts` / `agentStatus-session.test.ts` for the house harness)
+
+**Interfaces:**
+- Produces: `NormalizedAgentEvent.kind` gains `'background-task'`; `useAgentStatus` gains `backgroundTaskAt?: number` (transient) and action `markBackgroundTask(id: string): void`.
+- Consumes: nothing new.
+
+- [ ] **Step 1: Write the failing normalize tests**
+
+```ts
+// in normalize.test.ts, beside the existing claude PreToolUse cases (match the file's envelope helper)
+it('claude PreToolUse Bash with run_in_background=true is a background-task event', () => {
+ const e = normalizeClaude({ nodeId: 'n1', agentId: 'claude', payload: {
+ hook_event_name: 'PreToolUse', tool_name: 'Bash',
+ tool_input: { command: 'sleep 999', run_in_background: true }
+ }})
+ expect(e?.kind).toBe('background-task')
+})
+it('foreground Bash, false/absent flag, PostToolUse, and other tools stay generic working', () => {
+ for (const payload of [
+ { hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: 'ls' } },
+ { hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: 'ls', run_in_background: false } },
+ { hook_event_name: 'PostToolUse', tool_name: 'Bash', tool_input: { command: 'ls', run_in_background: true } },
+ { hook_event_name: 'PreToolUse', tool_name: 'Read', tool_input: { run_in_background: true } }
+ ]) {
+ const e = normalizeClaude({ nodeId: 'n1', agentId: 'claude', payload })
+ expect(e?.kind).toBe('state')
+ expect(e?.state).toBe('working')
+ }
+})
+```
+
+(Adapt the call shape to the file's existing helpers — it may wrap payloads. The four negative rows are the mutation guard: a `tool_name` check dropped, an `ev` check dropped, or a truthiness check instead of `=== true` each flips one row.)
+
+- [ ] **Step 2: Run to verify failure** — `npx vitest run src/shared/agents/normalize.test.ts` — the first test fails (`kind` is `'state'`).
+
+- [ ] **Step 3: Implement the normalize branch**
+
+`kind` union (`:10`): add `'background-task'`. `ClaudePayload.tool_input` (`:92`): add `run_in_background?: boolean`. In the claude `PreToolUse|PostToolUse` block, directly before the `// Any other tool use is just "working".` line:
+
+```ts
+ // A background shell task lives INSIDE the CLI process: /exit kills it silently. This event
+ // is the stamp Eco hibernation and the bulk restart exclude on (see hibernation-policy /
+ // planBulkRestart). PreToolUse only, and `=== true` — an absent or false flag is a foreground
+ // command, which the generic "working" below already covers. Claude-only: no other dialect
+ // carries the field (closed set, CLAUDE.md agent rule 7).
+ if (ev === 'PreToolUse' && tool === 'Bash' && p.tool_input?.run_in_background === true) {
+ return { ...base, kind: 'background-task' }
+ }
+```
+
+- [ ] **Step 4: Run** — normalize tests PASS.
+
+- [ ] **Step 5: Write the failing store tests**
+
+In the agentStatus suite (match its store-reset harness):
+
+```ts
+it('markBackgroundTask stamps; only a transition TO working clears it', () => {
+ const s = useAgentStatus.getState()
+ s.setState('n1', 'done', 'claude')
+ s.markBackgroundTask('n1')
+ expect(useAgentStatus.getState().byId['n1']?.backgroundTaskAt).toBeTypeOf('number')
+ s.setState('n1', 'waiting', 'claude') // done -> waiting: NOT cleared
+ expect(useAgentStatus.getState().byId['n1']?.backgroundTaskAt).toBeTypeOf('number')
+ s.setState('n1', 'working', 'claude') // -> working: cleared
+ expect(useAgentStatus.getState().byId['n1']?.backgroundTaskAt).toBeUndefined()
+})
+it('backgroundTaskAt is never persisted', () => {
+ // extend the existing "never written" persistence assertions (lastEventAt/stateAt pattern)
+})
+```
+
+- [ ] **Step 6: Implement the store**
+
+`backgroundTaskAt?: number` on the entry type with a comment (transient — same rationale as `lastEventAt`: after a relaunch Eco is inert until a turn, and any turn's `working` would have cleared it). `markBackgroundTask(id)` in house action style (stamp `Date.now()`, no save — transient). In `setState`'s transition branch, beside the hibernated self-heal: `if (state === 'working') delete entry.backgroundTaskAt` (or set undefined, matching the file's idiom) — comment: a turn start follows the completed task's `<task-notification>`; clearing on `done` would drop the guard while the task still runs.
+
+- [ ] **Step 7: Wire Canvas** — in the `agent:status` listener, beside the `recurring` case: `if (e.kind === 'background-task') { cs.markBackgroundTask(e.nodeId); return }` (match the listener's local naming). No re-render concern: the store write touches one entry and nothing subscribes to `backgroundTaskAt` reactively.
+
+- [ ] **Step 8: Gates + commit**
+
+`npx vitest run src/shared/agents/normalize.test.ts src/renderer/state && npm run typecheck`
+Commit: `feat(agents): background-task hook signal + transient stamp` + Co-Authored-By: Claude Fable 5 <[email protected]>
+
+---
+
+### Task 2: Consumers (hibernation exclusion + bulk-restart skip) + spec/plan force-add
+
+**Files:**
+- Modify: `src/renderer/lib/hibernationCandidates.ts` (`HibernationStatusInput` + candidate assembly), `src/renderer/terminal/hibernation-policy.ts` (required field + exclusion), `src/renderer/terminal/agent-restart.ts` (`BulkRestartCandidate` + `planBulkRestart`), `src/renderer/canvas/Canvas.tsx` (both feeds: the sweep's status narrowing + the bulk action's candidate build — grep `planBulkRestart(`)
+- Test: `src/renderer/lib/hibernationCandidates.test.ts`, `src/renderer/terminal/hibernation-policy.test.ts`, `src/renderer/terminal/agent-restart.test.ts` (ADDITIONS ONLY — zero deletions)
+- Add to git: `docs/superpowers/specs/2026-08-12-background-task-hibernation-guard-design.md` + this plan (`git add -f`, both live on disk in the stale main checkout — copy them into the worktree first)
+
+**Interfaces:**
+- Consumes: Task 1's `backgroundTaskAt`.
+- Produces: `HibernationCandidate.liveBackgroundTask: boolean` (required); `BulkRestartCandidate.backgroundTask: boolean` (required — typecheck forces the call sites, per the `remote`/`liveBackgroundTask` precedent).
+
+- [ ] **Step 1: Failing tests, all three files**
+
+```ts
+// hibernation-policy.test.ts — the oldest-node-surfaces mutation pattern used by every exclusion row
+it('never hibernates a node with a live background task', () => {
+ expect(planHibernation([base('a', { liveBackgroundTask: true, lastEventAt: 0 })], NOW, cfg)).toEqual([])
+})
+// + add liveBackgroundTask: false to base() so every existing fixture still compiles
+
+// hibernationCandidates.test.ts
+it('liveBackgroundTask mirrors backgroundTaskAt presence', () => {
+ // statusById: { a: { ...done..., backgroundTaskAt: 123 }, b: { ...done... } }
+ // expect candidate a.liveBackgroundTask true, b false
+})
+
+// agent-restart.test.ts (append only)
+it('bulk restart files a background-task node under the working skips', () => {
+ const plan = planBulkRestart([
+ { id: 'a', agentId: 'claude', state: 'done', sessionId: 's1', wired: true, backgroundTask: true },
+ { id: 'b', agentId: 'claude', state: 'done', sessionId: 's2', wired: true, backgroundTask: false }
+ ])
+ expect(plan.runnable).toEqual(['b'])
+ expect(plan.skipped.working).toBe(1)
+})
+```
+
+- [ ] **Step 2: Run to verify failures** (type errors on the new required fields count as the red).
+
+- [ ] **Step 3: Implement**
+
+- `HibernationStatusInput` += `backgroundTaskAt?: number` (doc comment: the third safety fact this adapter exists for — see the header's pattern); candidate assembly: `liveBackgroundTask: st?.backgroundTaskAt !== undefined`.
+- `HibernationCandidate` += required `liveBackgroundTask: boolean`; conjunction gains `!c.liveBackgroundTask` with a header sentence (a background shell dies with the CLI; no hook fires while it runs, so the stamp is the only signal).
+- `BulkRestartCandidate` += required `backgroundTask: boolean`; in `planBulkRestart`, AFTER the eligibility gate and BEFORE the wired check: `if (c.backgroundTask) { plan.skipped.working++; continue }` — comment: counted as `working` ("busy, try again in a moment" — exactly what a live background task is), because the summary line is frozen at four parts. A not-resumable background-task node stays uncounted, as today.
+- Canvas: the sweep's `statusById` narrowing passes `backgroundTaskAt` through; the bulk action's candidate build adds `backgroundTask: !!st?.backgroundTaskAt`.
+
+- [ ] **Step 4: Gates**
+
+`npx vitest run src/renderer/lib src/renderer/terminal src/renderer/state src/shared && npm run typecheck` — and verify `git diff --numstat` on `agent-restart.test.ts` shows **0 deletions**.
+
+- [ ] **Step 5: Force-add the docs + commit + PR**
+
+```bash
+git add -f docs/superpowers/specs/2026-08-12-background-task-hibernation-guard-design.md docs/superpowers/plans/2026-08-12-background-task-guard.md
+git add <code files>
+git commit -m "feat(renderer): exclude background-task nodes from Eco and bulk restart" # + Co-Authored-By
+```
+
+PR body must include: the concurrent-tasks accepted edge (first completion's turn clears the stamp; mitigated by the idle-window reset), claude-only rationale, the frozen-four-parts accounting decision, and the new device-checklist item 9 (a node with a running background shell is not hibernated; after the task completes and its turn runs, hibernation happens one idle window later).
+
+---
+
+## Out of scope (spec §Out of scope)
+
+Single-node restart guard; non-Claude agents; completion sniffing (named escalation: approach C); any "why didn't this hibernate" UI.
diff --git a/docs/superpowers/specs/2026-08-12-background-task-hibernation-guard-design.md b/docs/superpowers/specs/2026-08-12-background-task-hibernation-guard-design.md
new file mode 100644
index 000000000..42eed838e
--- /dev/null
+++ b/docs/superpowers/specs/2026-08-12-background-task-hibernation-guard-design.md
@@ -0,0 +1,61 @@
+# Background-Task Guard for Eco Hibernation and Bulk Restart — Design
+
+**Date:** 2026-08-12 · **Status:** approved by enes (scope + approach A) · **Follow-up to:** PR #130 (agent hibernation)
+
+## Problem
+
+Both Eco hibernation (opt-in, PR #130) and the bulk "Restart idle agents" action end an agent CLI by typing its exit command. A Claude Code **background shell task** (`Bash` with `run_in_background: true`) runs inside that CLI process and dies with it — silently lost work. Every other hazard has a guard (subagents, loop/cron, working/blocked); background shells are the one signal-less gap, because they produce no hook events while running and no subagent card. The window is real: a background task that runs >30 minutes with no other activity makes its node look exactly like Eco's target profile (done, offscreen, idle).
+
+## Decision record
+
+- **Scope (user decision):** Eco hibernation + bulk restart are guarded. The single-node "Restart agent (resume)" is deliberately untouched — the user clicks that node knowingly.
+- **Approach (user decision, option A):** hook stamp + clear-on-turn. Alternatives rejected: process-tree inspection at fire time (every claude has MCP-server children — false positive on all nodes, guard would disable Eco), and transcript completion-sniffing (correct model, disproportionate machinery; the fallback if A proves insufficient).
+- **Bulk-restart accounting (controller decision):** background-task skips are counted in the existing `skipped.working` bucket. The summary line is spec-frozen at four parts (see `agent-restart.ts` comments), and `'working'`'s documented meaning — "busy, try again in a moment" — is exactly what a live background task is.
+
+## Design
+
+### 1. Signal — `src/shared/agents/normalize.ts` (Claude only)
+
+In `normalizeClaude`'s `PreToolUse` branch: `tool_name === 'Bash' && tool_input.run_in_background === true` emits a new `NormalizedAgentEvent` kind **`background-task`** (carrying the node id, like the recurring events). The Claude payload type gains `run_in_background?: boolean` under `tool_input`.
+
+Claude-only in v1: the codex/gemini/grok dialects carry no equivalent field, and the house rule (CLAUDE.md "Adding a new agent" #7) is a closed set — no speculative widening. Their behavior stays byte-identical. A background task launched by a Claude *subagent* fires the same hook with the same node id, so protection extends there automatically — the safe direction.
+
+Both shells get this for free: normalize is shared, and the raw listeners forward whole events.
+
+### 2. Store — `src/renderer/state/agentStatus.ts`
+
+Transient `backgroundTaskAt?: number` per node. **Not persisted** — same rationale as `lastEventAt`: after an app relaunch Eco is structurally inert until the node takes a turn, so a persisted stamp would only assert staleness with confidence.
+
+- **Set:** Canvas's `agent:status` listener stamps `Date.now()` on a `background-task` event (a dedicated store action in house style, bail-when-unchanged not needed — re-stamping on every launch is correct).
+- **Clear:** in `setState`'s transition branch, only at a turn **START** (`done`/`undefined` → `working`; `blocked`/`waiting` → `working` is a mid-turn resumption and KEEPS the stamp). Rationale: a background task's completion queues a `<task-notification>` into the parent transcript, which re-invokes the agent — a turn starts — `working` fires. Clearing on `done` would be wrong: a turn can end while the task still runs. And clearing on *every* `working` transition would be wrong too: a background `Bash` whose command needs approval runs UserPromptSubmit(working) → PreToolUse(stamp) → PermissionRequest(blocked) → approve → PostToolUse(working), so the resumption edge would clear the stamp milliseconds after it was set, for exactly the task this guard exists for.
+
+### 3. Consumers
+
+- **Eco:** `buildHibernationCandidates` gains a **required** `liveBackgroundTask: boolean` field (`backgroundTaskAt !== undefined`), and `planHibernation` excludes it. Required-field discipline per the `remote` precedent: typecheck forces every call site, an omission can never read as "no task".
+- **Bulk restart:** `planBulkRestart`'s `BulkRestartCandidate` gains `backgroundTask: boolean`; a true value is counted as `skipped.working` (frozen four-part summary unchanged). Canvas's bulk action feeds it from the store. `restartEligibility` itself is untouched (the single-node menu path must not change).
+
+### 4. Edge cases (accepted, documented)
+
+- **Concurrent background tasks:** the first completion's turn clears the stamp while a second task may still run. Mitigation: that same turn resets `lastEventAt`, so Eco waits another full idle window (30 min default) — the residual exposure is a second task still running >30 min after the first one's completion turn, with no further hook activity. Documented here and in the Eco device checklist; approach C (completion counting) is the named escalation if this bites in practice.
+- **App relaunch:** stamp is gone (transient) — consistent, because Eco cannot act until a turn happens, and any turn's `working` would have cleared the stamp anyway.
+- **A task reporting back while the node sits `waiting`/`blocked`:** the clear needs a turn START, so a `<task-notification>` that lands while the session holds a question open (`waiting`/`blocked` → `working` is a resumption) leaves the stamp in place until the turn after that. Bounded and in the fail-safe direction — and such a node is never a hibernation candidate anyway, since `planHibernation` requires `state === 'done'`.
+- **Manual task kill without a turn:** the stamp stays until the next turn — the node simply isn't hibernated. Fail-safe direction (memory not reclaimed; work never killed).
+
+### 5. Testing
+
+- Normalize: a `PreToolUse` Bash payload with `run_in_background: true` yields the event; without the field (or with `false`, or another tool) yields nothing — mutation-sensitive both ways.
+- Store: stamp set on event; cleared on transition to `working`; NOT cleared on `done`/`waiting`; never persisted (extend the existing persistence tests).
+- Adapter/policy: `liveBackgroundTask` row in `hibernationCandidates` + exclusion row in `planHibernation` (the oldest-node-surfaces mutation pattern already used there).
+- Bulk plan: a background-task candidate lands in `skipped.working` and not in `runnable`.
+- Device checklist (append to PR #130's list as item 9): a node with a running background shell is not hibernated by an enabled Eco sweep; after the task completes and its turn runs, hibernation happens one idle window later.
+
+### 6. Surfaces
+
+Shared normalize + renderer store/policy: Desktop and Server Edition both covered with no shell-specific work. Mobile: N/A (no sweep on the phone).
+
+## Out of scope
+
+- Single-node restart guard (user decision).
+- Non-Claude agents (no signal in their dialects).
+- Completion sniffing / task counting (escalation path, not v1).
+- Any UI surface for "why didn't this node hibernate" (YAGNI).
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 1ab959f0e..7ab99e6cb 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -4343,7 +4343,10 @@ export function Canvas() {
sessionId: byId[n.id]?.sessionId,
// Registration is unconditional for every terminal node, so this says only "mounted and
// wired", never "is an agent" — `agentId` above is what decides that.
- wired: !!agentRestartFn(n.id)
+ wired: !!agentRestartFn(n.id),
+ // A background shell launched by this session is still running (no turn has started since):
+ // the exit line would kill it silently. Presence of the stamp is the whole signal.
+ backgroundTask: !!byId[n.id]?.backgroundTaskAt
}))
)
}, [])
diff --git a/src/renderer/lib/hibernationCandidates.test.ts b/src/renderer/lib/hibernationCandidates.test.ts
index 49647bcea..4767a2ea5 100644
--- a/src/renderer/lib/hibernationCandidates.test.ts
+++ b/src/renderer/lib/hibernationCandidates.test.ts
@@ -31,11 +31,34 @@ describe('buildHibernationCandidates', () => {
remote: false,
recurring: false,
liveSubagents: false,
+ liveBackgroundTask: false,
lastEventAt: IDLE
}
])
})
+ it('liveBackgroundTask mirrors backgroundTaskAt presence', () => {
+ const rows = buildHibernationCandidates(
+ inputs({
+ nodes: [
+ { id: 'a', agentId: 'claude' },
+ { id: 'b', agentId: 'claude' }
+ ],
+ statusById: {
+ a: { state: 'done', sessionId: 'sid-a', lastEventAt: IDLE, backgroundTaskAt: 123 },
+ b: { state: 'done', sessionId: 'sid-b', lastEventAt: IDLE }
+ }
+ })
+ )
+ expect(rows.map((r) => [r.id, r.liveBackgroundTask])).toEqual([
+ ['a', true],
+ ['b', false]
+ ])
+ // …and end to end: a node with a live background shell is refused, however idle it looks.
+ expect(planHibernation([rows[0]], NOW, { enabled: true, idleMinutes: 30 })).toEqual([])
+ expect(planHibernation([rows[1]], NOW, { enabled: true, idleMinutes: 30 })).toEqual(['b'])
+ })
+
it('reads a DISMISSED cron entry as recurring — the card is hidden, the job is not gone', () => {
// The exact hole this adapter exists to close: dismissing a cron card used to CLEAR the entry,
// which dropped the only guard between Eco mode and a silently cancelled job. The entry is now
diff --git a/src/renderer/lib/hibernationCandidates.ts b/src/renderer/lib/hibernationCandidates.ts
index 223d96dd5..83136be00 100644
--- a/src/renderer/lib/hibernationCandidates.ts
+++ b/src/renderer/lib/hibernationCandidates.ts
@@ -3,14 +3,21 @@
* canvas nodes, the agent-status table, the subagent cards, and the node's own wiring/visibility)
* and the pure policy in `terminal/hibernation-policy.ts`.
*
- * It exists as its own tested function rather than as a `.map()` inside the sweep because two of
- * the four facts are SAFETY facts, and an untested inline expression is exactly where they rot:
+ * It exists as its own tested function rather than as a `.map()` inside the sweep because three of
+ * the facts it lifts are SAFETY facts, and an untested inline expression is exactly where they rot:
*
* - **`recurring` is `!!loop`, dismissed or not.** A dismissed cron/schedule card keeps its entry
* precisely so this row stays true (see `agentStatus`'s `loop.dismissed`): the card is hidden,
* the job is not gone, and `/exit` would kill the CLI its wakeup lives in. Reading the render
* filter here — "no card, so nothing recurring" — silently cancels the job Eco mode was never
* allowed to touch. That hole is the reason this file has a test.
+ * - **`liveBackgroundTask` is "a background shell was launched and no turn has started since".**
+ * A Claude `Bash` with `run_in_background` runs INSIDE the CLI process and emits nothing while
+ * it works, so `agentStatus.backgroundTaskAt` is the only evidence it exists; `/exit` kills it
+ * with no output and no error. Note the coupling this depends on: a renderer reload drops
+ * `backgroundTaskAt` AND `lastEventAt` together (both transient), which is safe only because Eco
+ * is inert without an idle clock — that coupling is now load-bearing for two features, so
+ * neither field may be persisted on its own.
* - **`liveSubagents` is "any card for this parent that is NOT done".** Claude launches subagents
* async and their completion is queued into the PARENT's transcript, which a dead parent CLI
* never reads. An unknown/absent state counts as LIVE — the conservative direction, and the
@@ -38,6 +45,9 @@ export interface HibernationStatusInput {
/** Present = this node has a `/loop`, `/schedule` or `/cron` on it. Its `dismissed` flag is
* deliberately NOT consulted — see the header. */
loop?: unknown
+ /** When this node last launched a background shell task, if no turn has started since — the
+ * third safety fact this adapter exists for (see the header). Present at all = live task. */
+ backgroundTaskAt?: number
}
/** One subagent card, narrowed: whose it is, and whether it has finished. */
@@ -81,6 +91,7 @@ export function buildHibernationCandidates(
remote: inputs.isRemote(n.id),
recurring: !!st?.loop,
liveSubagents: liveParents.has(n.id),
+ liveBackgroundTask: st?.backgroundTaskAt !== undefined,
lastEventAt: st?.lastEventAt
}
})
diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.ts
index 519a74ba3..b38bc8610 100644
--- a/src/renderer/terminal/agent-restart.test.ts
+++ b/src/renderer/terminal/agent-restart.test.ts
@@ -757,9 +757,9 @@ describe('restartEligibility — grok', () => {
it('keeps a busy grok node out of the bulk run', () => {
const plan = planBulkRestart([
- { id: 'idle', agentId: 'grok', state: 'done', sessionId: 'sid-1', wired: true },
- { id: 'busy', agentId: 'grok', state: 'working', sessionId: 'sid-2', wired: true },
- { id: 'prompt', agentId: 'grok', state: 'blocked', sessionId: 'sid-3', wired: true }
+ { id: 'idle', agentId: 'grok', state: 'done', sessionId: 'sid-1', wired: true, backgroundTask: false },
+ { id: 'busy', agentId: 'grok', state: 'working', sessionId: 'sid-2', wired: true, backgroundTask: false },
+ { id: 'prompt', agentId: 'grok', state: 'blocked', sessionId: 'sid-3', wired: true, backgroundTask: false }
])
expect(plan.runnable).toEqual(['idle'])
expect(plan.skipped).toEqual({ working: 2, noSession: 0 })
@@ -834,9 +834,9 @@ describe('restartEligibility — gemini', () => {
it('keeps a busy gemini node out of the bulk run', () => {
const plan = planBulkRestart([
- { id: 'idle', agentId: 'gemini', state: 'done', sessionId: 'sid-1', wired: true },
- { id: 'busy', agentId: 'gemini', state: 'working', sessionId: 'sid-2', wired: true },
- { id: 'prompt', agentId: 'gemini', state: 'blocked', sessionId: 'sid-3', wired: true }
+ { id: 'idle', agentId: 'gemini', state: 'done', sessionId: 'sid-1', wired: true, backgroundTask: false },
+ { id: 'busy', agentId: 'gemini', state: 'working', sessionId: 'sid-2', wired: true, backgroundTask: false },
+ { id: 'prompt', agentId: 'gemini', state: 'blocked', sessionId: 'sid-3', wired: true, backgroundTask: false }
])
expect(plan.runnable).toEqual(['idle'])
expect(plan.skipped).toEqual({ working: 2, noSession: 0 })
@@ -1041,6 +1041,7 @@ describe('planBulkRestart', () => {
state: 'waiting',
sessionId: `sid-${over.id}`,
wired: true,
+ backgroundTask: false,
...over
})
@@ -1077,6 +1078,36 @@ describe('planBulkRestart', () => {
const plan = planBulkRestart([cand({ id: 'z' }), cand({ id: 'm' }), cand({ id: 'a' })])
expect(plan.runnable).toEqual(['z', 'm', 'a'])
})
+
+ it('bulk restart files a background-task node under the working skips', () => {
+ // A background shell dies with the CLI the exit line quits, and nothing about it is visible to
+ // the eligibility gate — the node reports `done` for as long as the task runs.
+ const plan = planBulkRestart([
+ cand({ id: 'a', state: 'done', backgroundTask: true }),
+ cand({ id: 'b', state: 'done', backgroundTask: false })
+ ])
+ expect(plan.runnable).toEqual(['b'])
+ expect(plan.skipped.working).toBe(1)
+ expect(plan.skipped.noSession).toBe(0)
+ })
+
+ it('leaves a NOT-RESUMABLE background-task node uncounted, as today', () => {
+ // The eligibility gate runs first, so a node the action never claimed stays out of the counts
+ // whatever else is true of it — the background check may not turn a non-target into a skip.
+ const plan = planBulkRestart([
+ cand({ id: 'shell', agentId: undefined, backgroundTask: true }),
+ cand({ id: 'oc', agentId: 'opencode', backgroundTask: true })
+ ])
+ expect(plan.runnable).toEqual([])
+ expect(plan.skipped).toEqual({ working: 0, noSession: 0 })
+ })
+
+ it('files a background task under working even when the node is unwired', () => {
+ // Ordering guard: the background check sits BEFORE the wired check, so a parked node with a
+ // live task reads as busy rather than as "no session".
+ const plan = planBulkRestart([cand({ id: 'a', wired: false, backgroundTask: true })])
+ expect(plan.skipped).toEqual({ working: 1, noSession: 0 })
+ })
})
describe('settleRestart', () => {
diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.ts
index 0bd74e854..995abd766 100644
--- a/src/renderer/terminal/agent-restart.ts
+++ b/src/renderer/terminal/agent-restart.ts
@@ -462,6 +462,14 @@ export interface BulkRestartCandidate {
* is unconditional for every terminal node, so this answers only "can I reach this pane", never
* "is this an agent" — `agentId` above is the one that decides that. */
wired: boolean
+ /** Is a background shell task running inside this node's CLI (Claude's `Bash` with
+ * `run_in_background`)? It dies with the CLI the exit line quits — silently, with no output and
+ * no error — and the eligibility gate cannot see it: the node reports `done` the whole time.
+ *
+ * Required, not optional: typecheck is what forces every call site to answer the question (the
+ * `remote` / `liveBackgroundTask` precedent), and an omitted field would read as "no task" —
+ * the one wrong direction. Fed from `agentStatus.backgroundTaskAt`. */
+ backgroundTask: boolean
}
export interface BulkRestartPlan {
@@ -491,6 +499,17 @@ export function planBulkRestart(candidates: BulkRestartCandidate[]): BulkRestart
// 'not-resumable' — never a target, see above.
continue
}
+ // AFTER the eligibility gate, so a node that was never a target stays uncounted whatever else
+ // is true of it — and BEFORE the wired check, because a live background task is the sharper
+ // fact: "no session" would send the user looking for a pane that is fine.
+ //
+ // Counted as `working`, not as a fifth part: the summary line is spec-frozen at four, and
+ // `'working'`'s documented meaning — "busy, try again in a moment" — is exactly what a running
+ // background task is.
+ if (c.backgroundTask) {
+ plan.skipped.working++
+ continue
+ }
if (!c.wired) {
plan.skipped.noSession++
continue
diff --git a/src/renderer/terminal/hibernation-policy.test.ts b/src/renderer/terminal/hibernation-policy.test.ts
index 96c60b132..fc7efba9c 100644
--- a/src/renderer/terminal/hibernation-policy.test.ts
+++ b/src/renderer/terminal/hibernation-policy.test.ts
@@ -12,6 +12,7 @@ const base = (id: string, over: object = {}) => ({
remote: false,
recurring: false,
liveSubagents: false,
+ liveBackgroundTask: false,
lastEventAt: 0,
...over
})
@@ -32,7 +33,8 @@ describe('planHibernation', () => {
base('h', { wired: false }),
base('i', { state: 'waiting' }),
base('j', { recurring: true }),
- base('k', { liveSubagents: true })
+ base('k', { liveSubagents: true }),
+ base('l', { liveBackgroundTask: true })
],
NOW,
cfg
@@ -51,6 +53,15 @@ describe('planHibernation', () => {
)
})
+ it('never hibernates a node with a live background task', () => {
+ // A background shell (`Bash` with run_in_background) lives inside the CLI process, so `/exit`
+ // kills it with no output and no error — and while it runs it emits nothing, so this stamp is
+ // the only evidence the node is not idle at all.
+ expect(
+ planHibernation([base('a', { liveBackgroundTask: true, lastEventAt: 0 })], NOW, cfg)
+ ).toEqual([])
+ })
+
it('never hibernates a waiting node — the question would be swallowed', () => {
expect(planHibernation([base('a', { state: 'waiting' })], NOW, cfg)).toEqual([])
expect(planHibernation([base('a', { state: 'blocked' })], NOW, cfg)).toEqual([])
diff --git a/src/renderer/terminal/hibernation-policy.ts b/src/renderer/terminal/hibernation-policy.ts
index 8cef575bd..39f40b00c 100644
--- a/src/renderer/terminal/hibernation-policy.ts
+++ b/src/renderer/terminal/hibernation-policy.ts
@@ -21,6 +21,12 @@
* - **Never a node with live subagents.** Claude launches subagents async: the completion of an
* async-launched subagent is queued into the PARENT's transcript, and a dead parent CLI never
* reads it. Hibernating the parent orphans every subagent still running under it.
+ * - **Never a node with a live BACKGROUND TASK.** A Claude `Bash` launched with
+ * `run_in_background` runs inside the CLI process, so `/exit` kills it silently — no output, no
+ * error, no record. And no hook fires while it runs, so a node whose only activity is a long
+ * background job looks EXACTLY like the target profile (`done`, offscreen, idle for hours): the
+ * stamp the launch left behind (`agentStatus.backgroundTaskAt`, cleared at the next turn start)
+ * is the only signal there is.
* - **Unknown idle is NOT idle.** A candidate with no `lastEventAt` (no hook event has ever been
* seen for it in this run) is never eligible — the same rule as pendingLaunch's "an unknown
* dependency state is not satisfied". Guessing here costs the user a live session.
@@ -73,6 +79,10 @@ export interface HibernationCandidate {
recurring: boolean
/** Any non-done subagent card whose parent is this node (from `state/agentNodes.ts`). */
liveSubagents: boolean
+ /** A background shell task is running inside this node's CLI (from `agentStatus.backgroundTaskAt`
+ * — set on the launch hook, cleared at the next turn start). Required, like `remote`: typecheck
+ * is what forces every call site to answer, and an omitted field would read as "no task". */
+ liveBackgroundTask: boolean
/** When this node's last hook event landed. Absent = never seen ⇒ never eligible. */
lastEventAt?: number
}
@@ -106,6 +116,7 @@ export function planHibernation(
c.state === 'done' &&
!c.recurring &&
!c.liveSubagents &&
+ !c.liveBackgroundTask &&
restartEligibility(c.agentId, c.state, c.sessionId).ok &&
// `?? Infinity`: no event ever seen ⇒ the difference is -Infinity ⇒ never eligible.
nowMs - (c.lastEventAt ?? Infinity) >= idleMs
diff --git a/src/shared/agents/normalize.test.ts b/src/shared/agents/normalize.test.ts
index 3585e122f..d034eb304 100644
--- a/src/shared/agents/normalize.test.ts
+++ b/src/shared/agents/normalize.test.ts
@@ -165,9 +165,9 @@ describe('normalizeClaude — background shell tasks', () => {
})
// The mutation guard: dropping the `tool_name` check, the `ev` check, or matching truthily
- // instead of `=== true` each flips exactly one of these rows. The truthy-but-not-`true` row is
- // what pins the strict compare — the two boolean rows below are both falsy, so on their own they
- // would pass a `!!p.tool_input?.run_in_background` implementation too.
+ // instead of `=== true` each flips a row here — the truthy match flips two. Those two
+ // truthy-but-not-`true` rows are what pin the strict compare: the boolean rows below are both
+ // falsy, so on their own they would pass a `!!p.tool_input?.run_in_background` implementation.
it('foreground Bash, false/absent/truthy-non-true flags, PostToolUse and other tools stay generic working', () => {
for (const payload of [
{ hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: 'ls' } },