Skip to content

fix(orchestration): fence settled worker auto-resume - #17445

Open
Jinwoo-H wants to merge 3 commits into
mainfrom
aug30-sta4577-completed-worker-resume-audit
Open

Jinwoo-H wants to merge 3 commits into
mainfrom
aug30-sta4577-completed-worker-resume-audit

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​792 $\color{#cf222e}{\Huge{\mathbf{−}}}$​11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​781
Prod 16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​227 $\color{#cf222e}{\Huge{\mathbf{−}}}$​57 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​170

Summary

  • Fence automatic provider resume at supervised worker settlement, before release/recovery races can reopen the session.
  • Keep settled-but-unreleased and release_unknown terminal resources in recovery planning, with exact pane/worktree identity checks.
  • Preserve and lift the renderer fence across status recapture, restart persistence, release, retain, and dispatch retirement.
  • Align the completed-worker E2E checkpoint with the actual settled done state.

Validation

  • pnpm tc
  • pnpm run check:code-quality:changed
  • Focused Vitest lifecycle/recovery suites: 18 passed
  • Worker release/recovery suites: 48 passed
  • Renderer/provider-session suites: 27 passed

The focused E2E build progressed past the stale recovery expectation and reached workspace activation, but timed out in the generic waitForActiveTerminalManager helper before the final assertions. No lifecycle assertion failed.

Scope

This is a product fix with accompanying unit/integration/E2E coverage; it is not test-only.

ELI5

When a worker says it is done, its terminal can still be hanging around for a moment. Orca used to see that old sleeping record and start it again during cleanup. The runtime now puts a do-not-auto-resume fence on the exact pane and worktree as soon as settlement is committed, carries it through restart and recovery, and lifts it only after the terminal row is no longer active.

Performance Measurement

No speed-up is claimed or measured; this is a lifecycle-race correctness fix. Recovery remains one SQL query. Added work is bounded to one settled-state check per returned recovery row, one blocked-pane set build, and one pass over each host's sleeping-session map. For S sleeping records and R retired fences, the extra scan is O(S) with O(R) copies/notifier events; R=0 causes no session writes. No wall-clock benchmark was run.

User-Facing Trade-offs

Completed workers intentionally do not auto-resume while their terminal is still owned or unreleased; a user may need explicit release/retain or a manual restart. Other worker launch and recovery behavior is unchanged.

@greptile-apps

greptile-apps Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR prevents settled-but-unreleased orchestration workers from automatically resuming their provider sessions and carries that fence through recovery, persistence, renderer state recapture, and retirement.

  • Extends recovery planning to include settled workers with terminal resources that remain owned or whose release is unresolved.
  • Propagates worktree-qualified fence and unfence events from main through preload to renderer state.
  • Preserves fences while sleeping-session records are recaptured and removes them after release, retention, or dispatch retirement.
  • Adds lifecycle, persistence, renderer, recovery, and end-to-end coverage for the completed-worker race.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
src/main/runtime/orca-runtime.ts Applies settled-worker fences before recovery and retires persisted and renderer fences when dispatch ownership ends.
src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts Keeps settled workers with owned, unreleased terminal resources in the recovery query.
src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.ts Distinguishes settled blocked panes from live terminal-recovery candidates.
src/main/runtime/rpc/methods/orchestration.ts Triggers resume-fence reconciliation immediately after lifecycle messages settle a worker.
src/renderer/src/hooks/ipc-events/agent-status-listeners.ts Applies fence updates only to sleeping records matching both pane and worktree identity.
src/renderer/src/store/slices/agent-status.ts Preserves the automatic-resume fence when the same provider session record is recaptured.
src/renderer/src/components/terminal-pane/pty-connection/agent-idle-working-handlers.ts Clears exact provider-session recovery duplicates when an authoritative agent exit is observed.
tests/e2e/completed-worker-retirement-resume.spec.ts Aligns the checkpoint with the settled done state and waits for terminal startup restoration before activation assertions.

Sequence Diagram

sequenceDiagram
    participant W as Worker
    participant O as Orchestration DB
    participant R as Main Runtime
    participant UI as Renderer Store
    participant P as Provider Session
    W->>O: Report worker_done
    O->>O: Commit settled dispatch
    R->>O: Plan terminal recovery
    O-->>R: Settled, owned terminal row
    R->>UI: fenced(paneKey, worktreeId)
    UI->>UI: Preserve automatic-resume block
    UI--xP: Suppress cold auto-resume
    R->>O: Observe release, retain, or retirement
    O-->>R: Terminal row no longer active
    R->>UI: unfenced(paneKey, worktreeId)
    UI->>UI: Retire automatic-resume block
Loading

Reviews (6): Last reviewed commit: "test(orchestration): port settled-worker..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7eb57a15-ef53-4d31-a8a8-ee7aa1410df5

📥 Commits

Reviewing files that changed from the base of the PR and between a0efa6abc8e3eff720aba810423e342c074b5b16 and 3728d6c.

📒 Files selected for processing (1)
  • src/preload/index.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

The change adds settled-worker terminal recovery rows and tracks whether blocked panes are settled. Runtime lifecycle reconciliation now prepares recovery and emits fenced or unfenced events with typed identities. Preload and window IPC payloads use shared recovery event types. Renderer handlers apply worktree-validated automatic resume blocks and preserve them during sleeping-session re-derivation. Tests cover database selection, lifecycle triggers, event mapping, completed-worker recovery state, and duplicate recovery cleanup on agent exit.

Merge Risk: 🔵 Low · up to 3728d

This change prevents settled workers from automatically resuming and strengthens recovery identity checks, but the fence can be published before its state is durably stored and an early event may be missed during UI hydration. A restart or hydration race could therefore allow an affected settled session to resume unexpectedly; the PR is mergeable with explicit owner awareness and follow-up on durable fence ordering and reconciliation.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.74% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 19 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description clearly explains the change, rationale, scope, trade-offs, performance impact, and validation results. However, it omits the required Linked Issue, Visual Proof or an explicit N/A expl… Add a linked issue after Fixes #. Add before-and-after visual proof for the behavior change, or write N/A with a brief reason if no visual or interaction change exists. Complete the Testing, AI Disclosure, Review, Agent skill upstream b…
✅ Passed checks (3 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: fencing automatic resume for settled workers.
Full details: Description check

Explanation

The description clearly explains the change, rationale, scope, trade-offs, performance impact, and validation results. However, it omits the required Linked Issue, Visual Proof or an explicit N/A explanation, Testing checklist, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections.

Resolution

Add a linked issue after Fixes #. Add before-and-after visual proof for the behavior change, or write N/A with a brief reason if no visual or interaction change exists. Complete the Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections, including the required checklist confirmations or explanations.

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

@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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4cbb5134-5474-49a9-a53e-d5b0240f40ba

📥 Commits

Reviewing files that changed from the base of the PR and between ba5f334 and 2912a5334deda09f5db70e82ebdf5180f1afeb57.

📒 Files selected for processing (18)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts
  • src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts
  • src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.ts
  • src/main/runtime/orchestration/orchestration-settled-worker-resume-fence-db.test.ts
  • src/main/runtime/rpc/methods/orchestration-settlement-resume-fence.test.ts
  • src/main/runtime/rpc/methods/orchestration.ts
  • src/main/runtime/rpc/orchestration-legacy-lifecycle.ts
  • src/main/window/runtime-window-lifecycle.ts
  • src/preload/api/agent-status-api.ts
  • src/preload/index.ts
  • src/renderer/src/hooks/ipc-events/agent-status-listeners.ts
  • src/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.ts
  • src/renderer/src/hooks/legacy-worker-terminal-recovery-event.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/shared/agent-status-types.ts
  • src/shared/worktree/id.ts
  • tests/e2e/completed-worker-retirement-resume.spec.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment thread src/preload/index.ts Resolved

@pullfrog pullfrog 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.

ℹ️ No critical issues — one coverage observation and two nits.

Reviewed changes

  • Settlement-triggered fence — orchestration.send and orchestration.check now call fenceSettledWorkerPanes → prepareLegacyWorkerTerminalRecovery() when a worker_done reconciles to completed/failed, and the legacy lifecycle path does the same on settled.
  • Settled-but-unreleased recovery rows — listLegacyWorkerTerminalRecoveryRows keeps WORKER_SETTLED_STATES dispatches whose terminal resource is still owned and not released/retained, so release_unknown resources stay recoverable.
  • Settled panes fenced, never adopted — planLegacyWorkerTerminalRecovery tags blocked panes with settled and skips settled rows as adoption candidates.
  • Renderer fence lift — new fenced/unfenced resolutions carry a worktreeId; the listener verifies identity before applying set-automatic-resume-block, and sleepingRecordFromEntry now carries the block across re-derivation.
  • E2E checkpoint — completed-worker-retirement-resume.spec.ts expects the settled done state.

ℹ️ Immediate fence does not cover stop/abandon settlement, and is dropped if no sleeping record exists yet

The fence is stamped by prepareLegacyWorkerTerminalRecovery() and only lands on a pane that already has a sleeping record (both the fenced notifier listener and the workspace-session write are gated on an existing record). orchestration.workerStop (settleWorkerStop → stopped) and orchestration.workerAbandon (abandonWorkerDispatch → abandoned) settle into WORKER_SETTLED_STATES but never invoke the fence trigger, so those panes stay unfenced until the next recovery pass (startup, relay-ready, or a later worker_done). This is a bounded window rather than a regression — the backstop recovery pass eventually fences — but it means a stopped worker's pane can still auto-resume during the release window, which is exactly the race this PR otherwise closes. Worth confirming whether stop/abandon are intended to be covered, or documenting that they rely on the backstop.

Technical details
# Settled stop/abandon paths do not fence at settlement

## Affected sites
- src/main/runtime/rpc/methods/orchestration-worker-stop.ts:163 — `settleWorkerStop` settles to `stopped`; no `prepareLegacyWorkerTerminalRecovery()` call.
- src/main/runtime/rpc/methods/orchestration-worker-control.ts:265 — `abandonWorkerDispatch` settles to `abandoned`; no fence trigger.
- src/main/runtime/rpc/methods/orchestration.ts:129 — `fenceSettledWorkerPanes` is only wired into `worker_done` send/check reconciliation.

## Required outcome
- Either fence stopped/abandoned workers at settlement, or confirm the next-recovery-pass backstop is the intended coverage for those states.

## Open questions for the human
- Is a stopped/abandoned worker's pane expected to be non-resumable during the release window? If so, these two settle paths need the same trigger.

ℹ️ Nitpicks

  • worktreeIdsEqual (src/shared/worktree/id.ts:47) is byte-for-byte identical to the existing runtimeWorktreeIdsEqual (src/main/runtime/orca-runtime.ts:43161); the PR migrates only one call site and leaves the duplicate. Consider delegating one to the other.
  • The comment at src/renderer/src/store/terminals/terminal-pane-hibernation.ts:66 still reads "sleepingRecordFromEntry does not copy the flag", which this PR makes inaccurate (it now copies via carryOverAutomaticResumeBlock). The mitigation it justifies is still valid, but the stated premise is stale.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H force-pushed the aug30-sta4577-completed-worker-resume-audit branch 2 times, most recently from 42ba022 to c8bdcd2 Compare August 30, 2026 20:53

@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/renderer/src/components/terminal-pane/pty-connection/agent-idle-working-handlers.ts (1)

39-39: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add a same-session cross-worktree regression test.

clearSleepingRecordProviderDuplicates already requires matching worktreeId. The existing sibling test uses a different provider session, so add a sibling in another worktree with the same provider session and assert that only the exited worktree is cleared.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0b946e29-b2fb-48fc-9553-543eeecd9403

📥 Commits

Reviewing files that changed from the base of the PR and between 2912a5334deda09f5db70e82ebdf5180f1afeb57 and 42ba02244f2c1ea44f32a6bfbde1e685f1c847c3.

📒 Files selected for processing (2)
  • src/renderer/src/components/terminal-pane/pty-connection-main-side-effect-authority.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/agent-idle-working-handlers.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@Jinwoo-H
Jinwoo-H force-pushed the aug30-sta4577-completed-worker-resume-audit branch 2 times, most recently from a0efa6a to 3728d6c Compare August 30, 2026 21:24

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Renderer-side resume retirement on agent exit — agent-idle-working-handlers.ts now clears the pane's sleeping record (and any legacy provider-session duplicate aliases) in onAgentExited before notifying the exit handler, so a settled worker whose shell title confirms exit cannot have its dead session resurrected by a later workspace open.
  • Test parametrization — the new retirement coverage in pty-connection-main-side-effect-authority.test.ts was widened from a single claude case to it.each(['claude', 'codex']), asserting exact-record clearing, sibling isolation, and clear-before-exit-callback ordering for both agents.

The retirement path reuses the existing getSleepingRecordForPane / clearSleepingRecordProviderDuplicates helpers and is gated on a confirmed exit (the main-process agent-exited fact or the idle→shell title transition, which replay/reattach paths already suppress). The focused suite passes (2 tests, claude + codex).

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • E2E restoration-readiness wait — added waitForTerminalStartupRestorationReady and awaited it after reload, so the pre-activation snapshot cannot race terminal startup restoration.
  • Gated-empty reseed consistency — the gateWorktreeAgentActivation empty branch now passes reseedEmptiedWorkspace: opts?.providesInitialSurface !== true, matching the ungated and folder-workspace paths so an explicitly activated empty workspace reseeds a terminal while surface-providing callers stay opted out.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the aug30-sta4577-completed-worker-resume-audit branch from b7ec691 to 844a16c Compare August 31, 2026 06:53
@nwparker

Copy link
Copy Markdown
Contributor

Heads up @Jinwoo-H — a pre-release readiness review found this PR and #17374's sibling #17430 implement the same STA-4577 settled-worker resume fence. We're keeping this one and closing #17430, because your production code is a verified strict superset: across the 18 shared files, agent-status-api.ts and agent-status-listeners.ts are byte-identical and every other shared prod file differs only in comment text, and you additionally carry the orchestration-legacy-lifecycle.ts settlement hook that #17430 lacks.

What I changed here (tests and comments only — no production logic touched):

#17430 had ~370 lines of coverage this branch had none of — git grep unfenced returned only the 3 prod lines, no test hits, and liftRetiredLegacyWorkerResumeFences plus the plan === null fail-closed branch were entirely untested. I ported all of it in 844a16c32c1:

  • 3 tests in orca-runtime.test.ts covering fence push / lift / unreadable-plan
  • new agent-status-settled-worker-resume-fence.test.ts (4 tests) covering the carryOverAutomaticResumeBlock relocation
  • pty-connection-cold-restore-resume-command.test.ts — the only test asserting the user-visible outcome (no transport.connect, no banner, record retained)
  • useIpcEvents-agent-status-ssh-authority.test.ts — 4 assertion blocks covering the worktreeIdsEqual identity guard in the listener
  • the forward-wire-compat case 'ignores a resolution kind it does not understand'
  • stronger assertions in the two shared DB test files, plus 8 rationale comments

Sanity-checked the tests actually bite: inverting if (blocked.settled) turned the runtime test red, and removing the carryOverAutomaticResumeBlock relocation turned 3 of the 4 store-slice tests red. Both restored.

⚠️ I had to force-push. The branch was 93 commits behind main, so the rebase rewrote your two commit SHAs. I used --force-with-lease pinned to b7ec691b308, the rebase had zero conflicts, and your two commits are byte-identical post-rebase (22 files, +576/−63, verified by diffing the ranges). Sorry for touching your branch directly — shout if you'd rather I had opened this as a PR against it.

One latent issue I found, unrelated to the port: useIpcEvents-agent-status-ssh-authority.test.ts times out on a cold Vite cache and passes warm. Bisected to your prod change adding import { worktreeIdsEqual } from '…/shared/worktree/id' to agent-status-listeners.ts — that file previously reached the store only via '../../store', which the test mocks out, so the new direct import pulls an un-mocked subtree into the graph and adds ~12s of transform, pushing the first await import('./useIpcEvents') past the 30s limit. Reverting just that import makes it pass cold. Probably wants a testTimeout bump or a vi.doMock for shared/worktree/id.

Remaining before merge (from the review, all pre-existing on both PRs): fenceSettledWorkerPanes only fires on reconcileLifecycleMessage results of completed/failed, so orchestration.workerStop/workerAbandon and reconcileMissingWorkerTerminal never fence — a stopped or abandoned worker still auto-resumes. WORKER_SETTLED_STATES already covers those states in the SQL, so it's a gap in the trigger sites, not the query.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Ported settle-fence coverage from #17430 — orca-runtime.test.ts gained three tests covering the fenced stamp, the unfenced lift, and the fail-closed unreadable-plan path; a new agent-status-settled-worker-resume-fence.test.ts store suite asserts the fence survives turn completion, periodic capture, and launch-config re-registration while not leaking onto a different provider session.
  • Cold-restore guard test — pty-connection-cold-restore-resume-command.test.ts now asserts a settled worker whose dispatch fenced automatic resume is never cold-restored.
  • Strengthened existing assertions — the DB and settlement tests now pin exact release_state/dispatch state transitions and assert the settled-but-unreleased rows stay recoverable; useIpcEvents-agent-status-ssh-authority.test.ts pins the worktree-identity guard on fenced/unfenced events.
  • Forward-compat coverage — legacy-worker-terminal-recovery-event.test.ts gained a test asserting an unknown resolution kind resolves to ignore rather than detaching a surface.
  • Documentation only on production paths — added Why/JSDoc notes to the fence stamping, lifting, and recovery-query code plus worktreeIdsEqual; no production behavior changed in this delta.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

This branch has not been deployed

No deployments
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.

2 participants