Repository navigation
Prevent Agent sleep while orchestration dispatch is active - #11808
Conversation
📝 WalkthroughWalkthroughRuntime task dispatch results now include 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
Greptile SummaryThis PR closes a race condition where an orchestrated Claude worker could be hibernated while its dispatch was still live. Provider
Confidence Score: 5/5Safe to merge. The change is conservative in all failure modes: an absent or unrecognised dispatch status blocks hibernation rather than permitting it, so the worst outcome of a regression is that a completed agent stays awake slightly too long. The race is correctly closed at both the data-flow layer (runtime Files Needing Attention: No files require special attention. All changed files are narrow and well-tested.
|
| Filename | Overview |
|---|---|
| src/shared/agent-status-types.ts | Adds optional dispatchStatus field to AgentStatusOrchestrationContext; field is annotated as runtime-authoritative and absent from hook-only contexts. |
| src/main/runtime/orchestration/db.ts | Adds completed_at = COALESCE(completed_at, datetime('now')) to failDispatch so failed and circuit_broken dispatch rows have the timestamp required by getRecentSettledDispatchForTerminal. |
| src/main/runtime/orca-runtime.ts | Renames getRecentCompletedDispatchForTerminal to getRecentSettledDispatchForTerminal to include failed/circuit_broken dispatches; emits dispatchStatus in the returned context; narrows getActiveCoordinatorRun lookup to pending/dispatched only. |
| src/renderer/src/lib/agent-hibernation-planner.ts | Adds hasUnsettledOrUnknownDispatch guard and entry.subagents?.length check to getEligiblePane, blocking hibernation until dispatch is authoritatively settled and the subagent roster is clear. |
| src/renderer/src/store/slices/agent-status.ts | Adds dispatchStatus to orchestrationContextsEqual comparison; the spread-merge order preserves runtime-set dispatchStatus when hook payloads omit the field entirely. |
| src/shared/claude-subagent-roster.ts | Adds hasActiveClaudeNonAgentBackgroundWork to detect live shell tasks and session crons that are not tracked in the agent roster but still prevent the lead from being truly done. |
| src/shared/agent-hook-listener.ts | Extends the effective-state override to include hasActiveNonAgentBackgroundWork (shells/crons on Stop/StopFailure) so a lead that reports done while background work is live stays working. |
| src/renderer/src/lib/agent-hibernation-coordinator.test.ts | Adds a test verifying that dispatch status is re-evaluated within the confirmation window — a completed candidate that changes to dispatched before shutdown is called does not trigger hibernation. |
| src/renderer/src/lib/agent-hibernation-planner.test.ts | Adds parameterised tests for blocking on pending/dispatched/unknown dispatch status and for allowing hibernation on completed/failed/circuit_broken; also covers the subagent roster blocking case. |
| src/renderer/src/store/slices/agent-status.test.ts | Adds tests for dispatchStatus update propagation via setRuntimeAgentOrchestrationByPaneKey for completed, failed, and circuit_broken terminal statuses. |
| src/shared/agent-hook-listener.test.ts | Adds parameterised tests confirming that Stop/StopFailure events with running shell tasks or session crons report state as working without adding a subagent row. |
| src/shared/claude-subagent-roster.test.ts | Adds unit tests for hasActiveClaudeNonAgentBackgroundWork covering shell tasks, session crons, agent-typed tasks (excluded), and empty/absent payloads. |
| src/main/runtime/orchestration/db.test.ts | Adds an assertion that all three failure stages (failed × 2, circuit_broken) produce a row with completed_at set, validating the COALESCE change. |
| src/main/runtime/orca-runtime.test.ts | Extends existing orchestration context tests to assert dispatchStatus is present; adds parameterised tests for failed/circuit_broken dispatch contexts without an active coordinator. |
Sequence Diagram
sequenceDiagram
participant Claude as Claude (Provider Hooks)
participant HL as AgentHookListener
participant Store as Renderer Store
participant RT as OrcaRuntime (main)
participant DB as OrchestrationDb
participant Planner as HibernationPlanner
Claude->>HL: Stop hook (state: done)
HL->>HL: hasActiveNonAgentBackgroundWork?
alt shells / session_crons present
HL->>Store: setAgentStatus(state: working)
else no background work
HL->>Store: "setAgentStatus(state: done, orchestration: {dispatchId, taskId})"
end
RT->>DB: getActiveDispatchForTerminal(handle)
DB-->>RT: "dispatch {status: dispatched}"
RT->>Store: "setRuntimeAgentOrchestrationByPaneKey({dispatchStatus: dispatched})"
Store->>Store: mergeCurrentOrchestrationContext → dispatchStatus: dispatched preserved
Planner->>Store: read agentStatusByPaneKey
Store-->>Planner: "entry {state: done, orchestration: {dispatchStatus: dispatched}}"
Planner->>Planner: hasUnsettledOrUnknownDispatch → true
Planner-->>Planner: candidate blocked (no hibernation)
DB->>DB: completeDispatch / failDispatch (sets completed_at)
RT->>Store: "setRuntimeAgentOrchestrationByPaneKey({dispatchStatus: completed})"
Store->>Store: merge → dispatchStatus: completed
Planner->>Store: read agentStatusByPaneKey (next pass)
Store-->>Planner: "entry {state: done, orchestration: {dispatchStatus: completed}}"
Planner->>Planner: hasUnsettledOrUnknownDispatch → false
Planner-->>Planner: candidate eligible → hibernation allowed
Reviews (2): Last reviewed commit: "fix(agent-sleep): harden background work..." | Re-trigger Greptile
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.test.ts (1)
36175-36234: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueNew parameterized test correctly validates terminal dispatch statuses skip the coordinator lookup.
The
it.each(['failed', 'circuit_broken'])test correctly asserts that a recent settled dispatch returnsdispatchStatusand thatgetActiveCoordinatorRunis not called for terminal statuses. This matches the PR objective that hibernation eligibility treatsfailedandcircuit_brokenas terminal, coordinator-independent states.Consider adding a companion test for stale
failed/circuit_brokendispatches, similar to the existingdoes not return stale completed orchestration context for renderer-synced terminal leavestest forcompleted. Without it, the staleness cutoff behavior for these two new terminal statuses is unverified.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a0cd65a8-b189-4910-b872-4a84a0002005
📒 Files selected for processing (11)
src/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/orchestration/db.test.tssrc/main/runtime/orchestration/db.tssrc/renderer/src/lib/agent-hibernation-planner.test.tssrc/renderer/src/lib/agent-hibernation-planner.tssrc/renderer/src/store/slices/agent-status.test.tssrc/shared/agent-hook-listener.test.tssrc/shared/agent-hook-listener.tssrc/shared/claude-subagent-roster.test.tssrc/shared/claude-subagent-roster.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/renderer/src/lib/agent-hibernation-planner.ts
- src/renderer/src/store/slices/agent-status.test.ts
| const backgroundTasks = hookPayload['background_tasks'] | ||
| return ( | ||
| Array.isArray(backgroundTasks) && | ||
| backgroundTasks.some((item) => { | ||
| if (typeof item !== 'object' || item === null) { | ||
| return false | ||
| } | ||
| const task = item as Record<string, unknown> | ||
| return task.status === 'running' && task.type !== 'subagent' && task.type !== 'teammate' |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Reject background tasks without a valid type.
task.type !== 'subagent' && task.type !== 'teammate' classifies { status: 'running' } and non-string type values as active non-agent work. This can keep the lead state working for malformed payload data. Require type to be a string before classifying the task. Add regression coverage for missing and non-string type values.
The change detail states that malformed values return false.
Proposed fix
}
const task = item as Record<string, unknown>
- return task.status === 'running' && task.type !== 'subagent' && task.type !== 'teammate'
+ return (
+ typeof task.type === 'string' &&
+ task.status === 'running' &&
+ task.type !== 'subagent' &&
+ task.type !== 'teammate'
+ )📝 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.
| const backgroundTasks = hookPayload['background_tasks'] | |
| return ( | |
| Array.isArray(backgroundTasks) && | |
| backgroundTasks.some((item) => { | |
| if (typeof item !== 'object' || item === null) { | |
| return false | |
| } | |
| const task = item as Record<string, unknown> | |
| return task.status === 'running' && task.type !== 'subagent' && task.type !== 'teammate' | |
| const backgroundTasks = hookPayload['background_tasks'] | |
| return ( | |
| Array.isArray(backgroundTasks) && | |
| backgroundTasks.some((item) => { | |
| if (typeof item !== 'object' || item === null) { | |
| return false | |
| } | |
| const task = item as Record<string, unknown> | |
| return ( | |
| typeof task.type === 'string' && | |
| task.status === 'running' && | |
| task.type !== 'subagent' && | |
| task.type !== 'teammate' | |
| ) |
…11808) * fix(agent-sleep): keep active dispatch workers awake * fix(agent-sleep): harden background work detection
Summary
Reproduction
The reported incident involved an orchestrated child Claude worker that never completed; reopening its worktree showed
--- session restored ---, indicating that its original PTY had been interrupted.A controlled Electron A/B reproduced the underlying race with a real Claude session:
dispatched.sleep 300in the background. The visible TUI reports1 shell still running.state: donewhile thesleep 300child process is still live.sleep 300survives orphaned under PID 1.Output activity only changes the confirmation signature. Once output is quiet across two passes, it cannot distinguish a truly idle session from background work after the provider has reported
done. This PR uses the structured Claude background-work payload, live roster, and runtime Dispatch state as conservative sleepability signals.Reliability contract
Stopwhile shell/cron work remains; idle teammates that remain alive for mail; staledispatchedrenderer state after failed or circuit-broken settlement.cmux reference
Compared against
manaflow-ai/cmuxat184bd48. The shared design is conservative aggregation: explicit idle is required, background work vetoes sleep, and teardown eligibility is revalidated. In particular, cmux has a regression test for a background shellsleepprocess.cmux's macOS process-generation, TTY, and process-group validation was not copied because Orca must support native Windows, WSL, SSH, and remote providers. The event-driven signals above provide the portable boundary without new polling or process inspection.
Test plan
pnpm run typecheckgit diff --checkCLEANScreenshots
No visual change. The existing Electron A/B was retained and was not rerun after review because the follow-up changes are state plumbing and regression tests; no new screenshots were produced.
Security
No new command execution, process inspection, network access, permissions, or persisted user data. The change only consumes existing provider/runtime state to make teardown more conservative.