Skip to content

Prevent Agent sleep while orchestration dispatch is active - #11808

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/investigate-orchestration-child-worktree
Jul 31, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/investigate-orchestration-child-worktree

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • preserve runtime-authoritative Dispatch state in renderer Agent status
  • block Agent sleep while an orchestration Dispatch is pending, dispatched, or has unknown settlement
  • publish recent completed, failed, and circuit-broken settlement so stale active state cannot block sleep forever
  • keep Claude awake while shell background tasks, session crons, or a live subagent/teammate roster remain
  • re-evaluate sleep eligibility during the hibernation confirmation window

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:

  1. Keep its orchestration Dispatch at dispatched.
  2. Ask Claude to run sleep 300 in the background. The visible TUI reports 1 shell still running.
  3. Claude naturally reports Agent state: done while the sleep 300 child process is still live.
  4. With the sleep veto temporarily removed, two hibernation confirmation passes remove the PTY and kill Claude; sleep 300 survives orphaned under PID 1.
  5. With this PR loaded, the same passes keep the Claude PTY and child process alive.

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

  • Invariant: a pane is not sleepable while Claude reports non-agent background work, its live roster is nonempty, or its orchestration Dispatch is pending, dispatched, or lacks authoritative settlement.
  • Failure sources covered: lead Stop while shell/cron work remains; idle teammates that remain alive for mail; stale dispatched renderer state after failed or circuit-broken settlement.
  • Oracle: provider hook payload + tracked roster + orchestration DB/runtime graph. The planner re-reads these signals during its existing confirmation pass before teardown.
  • Provider/platform coverage: Claude background-task detection is provider-specific; Dispatch and roster vetoes use existing runtime data. There is no local process-tree assumption, so native, Windows, WSL, SSH, git-worktree, and folder-workspace paths retain the same behavior.
  • Performance budget: event-driven only; one scan of the hook payload's existing background-task array and O(1) planner checks. No polling, process scan, provider fanout, or new IPC round trip.
  • Diagnostics: existing Agent status and Dispatch context remain the inspectable source of truth; no new log or telemetry surface is introduced.
  • Accepted gap: no dedicated Agent-hibernation reliability manifest exists today. The relevant regression and resume tests are run directly rather than expanding this PR into reliability-gate infrastructure. Providers without a structured background-work signal retain their existing behavior; unknown orchestration settlement fails closed.

cmux reference

Compared against manaflow-ai/cmux at 184bd48. 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 shell sleep process.

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

  • existing Electron A/B above with visible Claude TUI plus runtime/store/process inspection
  • focused Vitest suite across runtime, orchestration DB, planner/coordinator, renderer store, Claude listener/roster, and resume reliability: 1,297 passed, 1 skipped
  • pnpm run typecheck
  • targeted oxfmt, default oxlint, native-plugin lint, and type-aware lint checks
  • git diff --check
  • same-model senior review loop: final pass CLEAN
  • PR checks: 41 passed, e2e intentionally skipped; one unrelated Node 26 activity-portal timing failure passed locally and on CI rerun

Screenshots

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.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Runtime task dispatch results now include dispatchStatus. Agent orchestration contexts support pending, dispatched, completed, failed, and circuit-broken states. Runtime lookup uses recent settled dispatches and limits coordinator lookup to unsettled dispatches. Hibernation planning rejects missing or unsettled dispatch status. Claude stop handling remains working while tracked background activity remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the primary change: preventing agent sleep while orchestration dispatch remains active.
Description check ✅ Passed The description explains the change, reproduction, reliability contract, testing, screenshots, security considerations, and platform behavior; some template headings are consolidated or omitted.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR closes a race condition where an orchestrated Claude worker could be hibernated while its dispatch was still live. Provider done hooks fire independently of the runtime orchestration lifecycle, so the PR threads the runtime-authoritative dispatchStatus into the renderer's agent status and vetoes hibernation until the runtime confirms settlement.

  • Adds dispatchStatus to AgentStatusOrchestrationContext (emitted by the runtime, absent from hook-only contexts); mergeCurrentOrchestrationContext naturally preserves the runtime value because hook payloads never carry the field, so the spread { ...existing, ...current } leaves it untouched.
  • Blocks getEligiblePane on hasUnsettledOrUnknownDispatch (allows only completed, failed, circuit_broken) and on any live subagent roster entry; re-evaluates dispatch settlement every confirmation-window pass via the coordinator.
  • Extends the effective-state override in normalizeClaudeEvent to cover non-agent background work (shell tasks, session crons) so a lead that reports done with live shells stays working; adds completed_at to failDispatch so failed/circuit_broken dispatch rows satisfy the recency gate in getRecentSettledDispatchForTerminal.

Confidence Score: 5/5

Safe 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 dispatchStatus is preserved through hook-based merges because hooks never set the field, so the spread never clobbers it) and the decision layer (hasUnsettledOrUnknownDispatch defaults to blocking for absent/unknown values). The failDispatch COALESCE addition correctly anchors completed_at at first failure, and since three retries happen quickly relative to the stale-after window, the frozen timestamp poses no practical staleness problem. The 89 existing tests pass and new coverage hits every new code path.

Files Needing Attention: No files require special attention. All changed files are narrow and well-tested.

Important Files Changed

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
Loading

Reviews (2): Last reviewed commit: "fix(agent-sleep): harden background work..." | Re-trigger Greptile

@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: 1

🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.test.ts (1)

36175-36234: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

New 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 returns dispatchStatus and that getActiveCoordinatorRun is not called for terminal statuses. This matches the PR objective that hibernation eligibility treats failed and circuit_broken as terminal, coordinator-independent states.

Consider adding a companion test for stale failed/circuit_broken dispatches, similar to the existing does not return stale completed orchestration context for renderer-synced terminal leaves test for completed. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2ee4bd2 and 5023deb.

📒 Files selected for processing (11)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration/db.test.ts
  • src/main/runtime/orchestration/db.ts
  • src/renderer/src/lib/agent-hibernation-planner.test.ts
  • src/renderer/src/lib/agent-hibernation-planner.ts
  • src/renderer/src/store/slices/agent-status.test.ts
  • src/shared/agent-hook-listener.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/claude-subagent-roster.test.ts
  • src/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

Comment on lines +153 to +161
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'

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.

🎯 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.

Suggested change
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'
)

@brennanb2025
brennanb2025 merged commit 9bf05b0 into main Jul 31, 2026
81 of 83 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…11808)

* fix(agent-sleep): keep active dispatch workers awake

* fix(agent-sleep): harden background work detection
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.

1 participant