Skip to content

fix(program-status): keep a Pi row working while a pi-subagents child outlives the parent's done - #33738

Merged
nwparker merged 4 commits into
mainfrom
nwparker/agint-33657
Oct 26, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/agint-33657

Conversation

@nwparker

@nwparker nwparker commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​67 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​66
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​77 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​71

ELI5

When Pi starts a background worker through pi-subagents and then finishes its own reply, Orca marked the whole Pi row Done and put it in the dashboard's IDLE column, even though the worker was still running underneath it. Now the row stays working while a live child is running. It flips to done only when the last child ends. The parent's own "I finished successfully" verdict is still recorded the whole time.

Root cause

The row the reporter captured (programStatus set, mainAgent: {state: done, outcome: success}, child agentType: "pi-subagents") comes from the OSC 7501 program-status lane, not from the Pi hook extension:

  • Pi reports its own root record as done when the parent run settles (pi-mono packages/coding-agent/src/modes/interactive/program-status-reporter.ts:36-69).
  • pi-subagents reports each async run as a separate child record subagents/<run> with app=pi-subagents and state working while it runs ([email protected] src/integrations/program-status.js:3,30,36,87).
  • createProgramStatusProjector copied the root's state straight onto the row (state: projection.state) and listed the live children next to it. Nothing folded child liveness into the row. So the projector emitted done with a working subagent.

The hook path was already correct for this flow: Orca's Pi extension holds agent_end until its roster drains. In the real run below, no agent_end was posted while the child was alive.

What changed

src/shared/program-status/agent-status-projector.ts

  • A finished, non-boundary root done is passed through the existing foldMainAgentWithRowChildWork. Only working and waiting children count. The row stays working while such a child runs, or shows waiting if a child asks the user a question. It returns to done with the lead's success/failure once the last child ends. mainAgent still carries the root's own state, outcome, and clock.
  • Scope is narrow. Rows during a live turn, failed children (blocked in place), idle children, and idle/boundary roots keep exactly the root's state, as on main.
  • The held row and its later all-clear both carry turnCompletedAt set to the root's done time. This matches Claude hook rows: the lead's done is announced once, when it happens (terminal-agent-turn-news.ts, agent-completion-hook-observer.ts). It is not delayed until the children finish, and the all-clear is not announced a second time.

src/main/agent-hooks/server/program-status/hook-precedence.ts

  • A hook row that already settled done is never reopened by a program row that is only held open by its children. Without this, after 2 minutes of hook silence the fallback could flip the row done -> working -> done. In the real run the Pi hook lane sees the same pi-subagents children (via subagent:async-started/async-complete) and holds agent_end until they finish. So normally both lanes agree, and the guard covers cases where they diverge, such as a worker restored after a Pi restart that the hook roster never saw.

Reproduction / verification (real Pi)

Isolated setup: temp HOME and PI_CODING_AGENT_DIR, env -i, a local fake Anthropic server, and a local hook capture server. Nothing posted to a running Orca. Versions: Pi @earendil-works/[email protected] + [email protected] + this branch's Orca Pi status extension. Pi ran in a real PTY (TUI). The parent called subagent({agent: "worker", async: true}) and the fake model held the child's reply for 20s.

Real Pi OSC 7501 output:

]7501;state=working:app=pi
]7501;state=working:id=subagents/dd8bc6d39d80:app=pi-subagents:title=worker:msg=Running
]7501;state=done:app=pi
]7501;state=done:id=subagents/dd8bc6d39d80:app=pi-subagents:title=worker:msg=Finished

That raw PTY stream was replayed through the real main-side createTerminalAgentStatusProcessor:

step main this PR
parent done, child running (~23s) state: done, mainAgent done/success, child working state: working, mainAgent done/success, turnCompletedAt = parent's done time, child working
child finished state: done state: done, mainAgent done/success, same turnCompletedAt (no second announcement)

On main, the first row matches the reporter's orca worktree ps snapshot exactly.

Tests: projector regressions (held row + stamp + all-clear; narrowed scope) and a hook-precedence regression. pnpm test src/shared/program-status/ src/main/agent-hooks/ src/renderer/src/components/terminal-pane/agent-completion* passes (171 files). pnpm tc and check:code-quality:changed are clean. pty-connection-command-finished-late-done.test.ts has 2 timeouts locally, identical on main.

Risk and trade-offs vs main

Low to medium. The change only applies when an OSC 7501 root has finished and a child is still working/waiting. With no such child, output is identical.

  • A Pi parent with a running async child now shows working in the sidebar and dashboard until the child finishes. The "finished" notification still fires when the parent's own reply ends.
  • A waiting child under a finished root now shows the row as waiting, for any OSC 7501 app. During a live turn nothing changes.
  • When the hook lane has already settled done, its verdict wins over the program's child roster. A child the hook roster never saw (for example a worker restored after a Pi restart) still reads done, as on main.
  • Stuck child: children report only changes. In terminal-derived-agent-facts.ts, the lease timer now settles any child-held row that no report has refreshed within AGENT_STATUS_STALE_AFTER_MS minus one renewal interval (between 20 and 30 minutes, before the row would decay). It settles to the lead's own done, drops the unverified children, and keeps turnCompletedAt, so nothing is announced a second time. A later child report reopens the row from real evidence. pi-subagents also reconciles dead runners itself every 5s (async-job-tracker.js:22).
  • A child waiting at the parent's done: the user first gets the needs-input alert, then the turn's done fires once the children clear. This is the same order as other child-waiting rows.
  • Remote relays use the same shared code. Mixed versions keep the old behaviour until both sides update. This composes with fix(pi): keep in-process subagent sessions from taking over the lead pane #33595, which only governs the hook extension's pane ownership.

Fixes #33657

… outlives the parent's done

OSC 7501 projected the root record's done straight onto the row even when
live child records remained, so a Pi parent showed Done/IDLE while an async
pi-subagents worker kept running. Fold child liveness with the existing
foldMainAgentWithRowChildWork; mainAgent keeps the lead's own verdict so the
row settles to done once the last child ends.

Fixes #33657
@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

The projector now folds working or waiting child rows into a completed root’s displayed state while retaining the root state in mainAgent and recording its completion timestamp. A helper lapses child-held payloads after a timeout. The runtime checks and emits lapsed payloads during renewal. Hook precedence remains open when a completed hook state receives a payload held open by child work. Tests cover child activity, completion, lapse timing, and hook precedence.

Issue severity: Medium

Priority: Normal

Severity of issue fixed: Medium

Merge Risk: Moderate · up to 0d13a

A child's request for human input can stay hidden behind a settled hook row. Child activity can also be read as a new root turn by prompt-submission tracking. Both should be fixed before merge.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the main change: keeping the parent row working while a pi-subagents child remains active after the parent reports done.
Description check Passed The description is detailed and covers the user impact, root cause, implementation, rationale, linked issue (#33657), testing, reproduction, risks, and trade-offs. It omits some template headings and …
Linked Issues check Passed Issue #33657 requires the aggregate row to remain working while a child is working, while preserving the root agent's own completion result. agent-status-projector.ts folds working and waiting child…
Out of Scope Changes check Passed The changes stay within issue #33657. Projector changes implement aggregate child liveness and completion handling. Lease handling prevents an unrefreshed child from holding the row indefinitely. Hook…
Full details: Description check

Explanation

The description is detailed and covers the user impact, root cause, implementation, rationale, linked issue (#33657), testing, reproduction, risks, and trade-offs. It omits some template headings and checklist items, but the required change information is substantially complete.

Full details: Linked Issues check

Explanation

Issue #33657 requires the aggregate row to remain working while a child is working, while preserving the root agent's own completion result. agent-status-projector.ts folds working and waiting child rows into a completed root row and retains the root state and outcome in mainAgent. The projector preserves turnCompletedAt and returns the row to done after child completion or hold lapse. The existing fold provides waiting-child priority. Tests cover the held row, completion timestamp, all-clear, lapse, and narrowed-state cases. hook-precedence.ts prevents a settled hook row from reopening. These changes satisfy the linked issue's coding requirements.

Full details: Out of Scope Changes check

Explanation

The changes stay within issue #33657. Projector changes implement aggregate child liveness and completion handling. Lease handling prevents an unrefreshed child from holding the row indefinitely. Hook precedence prevents conflicting status lanes from reopening a settled row. The added tests verify these behaviors. No unrelated product behavior is demonstrated.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments: 1
src/shared/program-status/agent-status-projector.test.ts: 1

123-140: Trivial · Functional Correctness · Quick win

Add the missing waiting-state assertion.

When the root is done and the child changes to a turn-scoped question, assert that the row becomes waiting, while mainAgent.state remains done and the child remains represented. The existing assertions already cover the live-child and final child-completion states.

Suggested fix
     expect(feed(osc('state=done:app=pi'))).toMatchObject([
       {
         state: 'working',
         mainAgent: { state: 'done', outcome: 'success' },
         subagents: [{ id: 'subagents/run1', state: 'working' }]
       }
     ])
+    const [waiting] = feed(
+      osc('state=blocked:kind=question:id=subagents/run1:app=pi-subagents')
+    )
+    expect(waiting).toMatchObject({
+      state: 'waiting',
+      mainAgent: { state: 'done', outcome: 'success' },
+      subagents: [{ id: 'subagents/run1', state: 'waiting' }]
+    })
     const [settled] = feed(osc('state=done:id=subagents/run1:app=pi-subagents'))

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5d81dff5-3bea-4318-b6e0-93a13ac579a6
Commits

Reviewing files that changed from the base of the PR and between bb47718 and 9e54278.

Files selected for processing: 2
  • src/shared/program-status/agent-status-projector.test.ts
  • src/shared/program-status/agent-status-projector.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

nwparker and others added 3 commits October 25, 2026 19:46
…k verdicts authoritative

- Stamp turnCompletedAt on the child-held row and its all-clear so the lead's
  done is announced once, when it happens, as hook rows do.
- Hold only a finished (non-boundary) turn, only for working/waiting children;
  in-turn rows and failed/idle children keep the root's state.
- A settled hook row is never reopened by a program's child-held working row,
  so the 2-minute silence fallback cannot flip done -> working -> done.
Children report only changes, so a pi-subagents that dies or hangs inside a
live Pi would hold the row working until decay. The lease timer now settles a
child-held row no report refreshed within AGENT_STATUS_STALE_AFTER_MS minus one
renewal interval (20-30 min) to the lead's done, keeping turnCompletedAt so it
is not announced again.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d4798e0c-8ad1-496d-b8a8-b2e5ec7088c6
Commits

Reviewing files that changed from the base of the PR and between 9e54278 and 0d13ac5.

Files selected for processing: 5
  • src/main/agent-hooks/server/program-status/hook-precedence.test.ts
  • src/main/agent-hooks/server/program-status/hook-precedence.ts
  • src/main/runtime/terminal/output/terminal-derived-agent-facts.ts
  • src/shared/program-status/agent-status-projector.test.ts
  • src/shared/program-status/agent-status-projector.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

// Why: the hook lane tracks its own children; a program's child roster must not reopen the hook's settled turn.
if (
payload.state === previous.payload.state ||
(previous.payload.state === 'done' && isAgentStatusHeldOpenByChildWork(payload))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

🔎 Supported by static analysis

Script executed:

cat src/main/agent-hooks/server/program-status/hook-precedence.ts
rg -n 'isAgentStatusHeldOpenByChildWork' src
rg -n 'programStatusHookYieldEndsAt' src

Repository: stablyai/orca

Length of output: 8834


Script executed:

sed -n '1,80p' src/shared/agent-lead-status-fold.ts
echo '-----'
sed -n '1,140p' src/main/agent-hooks/server/program-status/hook-precedence.test.ts
echo '-----'
sed -n '190,235p' src/main/agent-hooks/server/server-ingest-terminal.ts
echo '-----'
sed -n '85,105p' src/shared/program-status/agent-status-projector.ts

Repository: stablyai/orca

Length of output: 10485


Let a child's waiting request reach the waiting branch after a done hook.

When the hook state is done, the new child-held condition returns Infinity for a child-held waiting payload. That check runs before the done to waiting branch, which can yield once the program reports work after the hook. The waiting state is therefore excluded from the hook-owned path, and the child's request cannot take precedence over the settled done hook. Limit the new condition to non-waiting child-held states, so child-held waiting uses the same intervening-work rule as an ordinary wait.

🐛 Suggested fix
--- "a/src/main/agent-hooks/server/program-status/hook-precedence.ts"
+++ "b/src/main/agent-hooks/server/program-status/hook-precedence.ts"
@@ -23,7 +23,9 @@
   // Why: the hook lane tracks its own children; a program's child roster must not reopen the hook's settled turn.
   if (
     payload.state === previous.payload.state ||
-    (previous.payload.state === 'done' && isAgentStatusHeldOpenByChildWork(payload))
+    (previous.payload.state === 'done' &&
+      payload.state !== 'waiting' &&
+      isAgentStatusHeldOpenByChildWork(payload))
   ) {
     return Infinity
   }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
(previous.payload.state === 'done' && isAgentStatusHeldOpenByChildWork(payload))
(previous.payload.state === 'done' &&
payload.state !== 'waiting' &&
isAgentStatusHeldOpenByChildWork(payload))

rootDoneHeldOpen ||= projection.state === 'done' && state !== 'done'
const payload: ParsedAgentStatusPayload = {
state: projection.state,
state,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Heavy lift

🔎 Supported by static analysis

Script executed:

#!/bin/bash
# Inspect lifecycle writes, reads, and any root-change correction path.
rg -n -C 5 \
  -e 'recordAgentPromptLifecycleState\s*\(' \
  -e 'mapExplicitAgentStateToRuntimeTerminalStatus\s*\(' \
  -e 'rootChanges' \
  src/main src/shared

Repository: stablyai/orca

Length of output: 17371


Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- projector state construction ---'
nl -ba src/shared/program-status/agent-status-projector.ts | sed -n '1,340p'
printf '%s\n' '--- payload consumer ---'
nl -ba src/main/runtime/terminal/output/terminal-derived-agent-facts.ts | sed -n '120,190p'
printf '%s\n' '--- lifecycle recorder ---'
nl -ba src/main/runtime/terminal/output/terminal-output-generation.ts | sed -n '1,90p'
printf '%s\n' '--- lifecycle reads and wait implementation ---'
rg -n -C 8 -F -e 'agentPromptLifecycleByPtyId' -e 'getTerminalInteractiveWait' -e 'lastAgentStatus' src/main/runtime
printf '%s\n' '--- projector and terminal status tests around child-held behavior ---'
rg -n -C 12 -e 'child' -e 'mainAgent' -e 'prompt lifecycle' -e 'terminal wait' src/shared/program-status src/main/runtime/terminal src/main/runtime/*wait* 2>/dev/null || true

Repository: stablyai/orca

Length of output: 45667


Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- display lifecycle definition ---'
rg -n -C 12 -F 'function getDisplayPromptLifecycle' src/main src/shared
printf '%s\n' '--- interactive wait definition and callers ---'
rg -n -C 20 -F 'getTerminalInteractiveWait' src/main
printf '%s\n' '--- lifecycle sequence consumers ---'
rg -n -C 12 -e 'workingSequence' -e 'getDisplayPromptLifecycle' src/main/runtime src/main | head -n 500
printf '%s\n' '--- focused tests ---'
rg -n -C 15 -e 'workingSequence' -e 'recordAgentPromptLifecycleState' -e 'interactive wait' src/main/runtime --glob '*.test.ts' --glob '*.spec.ts' | head -n 500

Repository: stablyai/orca

Length of output: 42382


Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- prompt activity and lifecycle consumers ---'
rg -n -C 18 -e 'getAgentPromptActivity' -e 'workingSequence' -e 'AgentPromptActivity' src/main/runtime --glob '*.ts' | head -n 700
printf '%s\n' '--- terminal interactive wait implementation ---'
rg -n -C 18 -e 'async getTerminalInteractiveWait' -e 'getTerminalInteractiveWait\(' src/main/runtime --glob '*.ts' | head -n 700
printf '%s\n' '--- payload type ---'
rg -n -C 18 -F 'export type ParsedAgentStatusPayload' src/shared

Repository: stablyai/orca

Length of output: 42540


Record the root state for terminal prompt lifecycle.

When the root is done and a child is active, payload.state is working, but payload.mainAgent.state is done. The lifecycle recorder uses payload.state, so prompt-submission verification can treat child activity as a new root turn. Use the root state for lifecycle tracking and keep the aggregate state for row display.

Suggested fix
       this.recordAgentPromptLifecycleState(
         ptyId,
-        mapExplicitAgentStateToRuntimeTerminalStatus(payload.state)
+        mapExplicitAgentStateToRuntimeTerminalStatus(payload.mainAgent?.state ?? payload.state)
       )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Pi parent shows Done / IDLE while a native async subagent is working (1.4.240)

1 participant