Repository navigation
Conversation
Greptile SummaryThe PR adds settlement-time automatic-resume fences for supervised worker terminals and retires those fences after release, retention, or dispatch pruning.
Confidence Score: 4/5The abandonment path should be fixed before merging because it can leave a settled worker unfenced long enough for its retained provider session to auto-resume. Message-driven worker completion stamps the new fence immediately, but direct abandonment changes the dispatch to a settled state while retaining possibly-live resources and never invokes the recovery sweep. Files Needing Attention: src/main/runtime/rpc/methods/orchestration.ts, src/main/runtime/rpc/methods/orchestration-worker-control.ts
|
| Filename | Overview |
|---|---|
| src/main/runtime/orca-runtime.ts | Stamps settled-worker fences, persists them by host partition, and removes retired fences while failing closed when recovery planning is unavailable. |
| src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts | Expands recovery rows to settled dispatches that retain owned and not-proven-released terminal resources. |
| src/main/runtime/rpc/methods/orchestration.ts | Triggers fence reconciliation after message-driven completion or failure but omits direct settled-state transitions such as worker abandonment. |
| src/renderer/src/hooks/legacy-worker-terminal-recovery-event.ts | Converts additive fenced and unfenced wire values into worktree-scoped renderer store actions while retaining prior recovery behavior. |
| src/renderer/src/store/slices/agent-status.ts | Carries the fence across record re-derivation only while the pane retains the same provider session. |
| src/shared/agent-status-types.ts | Extends the existing recovery event contract with additive resolution values and an optional worktree identity. |
Sequence Diagram
sequenceDiagram
participant W as Worker lifecycle
participant DB as Orchestration DB
participant RT as Runtime recovery
participant UI as Renderer store
participant P as Terminal pane
W->>DB: Settle worker dispatch
DB-->>RT: Settled + owned terminal recovery row
RT->>UI: fenced(paneKey, worktreeId)
UI->>P: Block automatic provider resume
W->>DB: Release, retain, or prune dispatch
DB-->>RT: Recovery row disappears
RT->>UI: unfenced(paneKey, worktreeId)
UI->>P: Permit fresh spawn
Reviews (1): Last reviewed commit: "fix(orchestration): stamp and lift the s..." | Re-trigger Greptile
| reconciled: readonly LifecycleReconciliationResult[] | ||
| ): void { | ||
| if (reconciled.some((result) => result.action === 'completed' || result.action === 'failed')) { |
There was a problem hiding this comment.
Abandonment skips resume fence
When orchestration.workerAbandon settles a supervised worker while retaining its owned terminal resources, this message-only trigger never runs prepareLegacyWorkerTerminalRecovery, causing the abandoned provider session to auto-resume when the user returns to the workspace.
Knowledge Base Used: Agent workspaces and sessions
📝 WalkthroughWalkthroughThe recovery planner now retains settled workers with unresolved terminal resources and excludes them from adoption candidates. Settlement reconciliation fences affected panes through Merge Risk: 🟡 Moderate · up to The change prevents completed workers from being restarted, but it can also block active workers from normal restart or recovery and can leave fences uncleared when session storage is unavailable. Merge should wait for these lifecycle cases to be corrected or explicitly accepted by the owner. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 20 files. (2 skipped: 2 too large.) Full details: Description checkExplanation The description is detailed and relevant. It explains the problem, implementation, rationale, linked issue, compatibility, testing results, performance impact, and known trade-offs. Some template headings and checklist items are not reproduced, but the required information is mostly present.
✨ 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a08b34ab-8a22-4d2b-9cb7-8fc26aa652ad
📒 Files selected for processing (22)
src/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.tssrc/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.tssrc/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.tssrc/main/runtime/orchestration/orchestration-settled-worker-resume-fence-db.test.tssrc/main/runtime/rpc/methods/orchestration-settlement-resume-fence.test.tssrc/main/runtime/rpc/methods/orchestration.tssrc/main/window/runtime-window-lifecycle.tssrc/preload/api/agent-status-api.tssrc/preload/index.tssrc/renderer/src/components/terminal-pane/pty-connection-cold-restore-resume-command.test.tssrc/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.tssrc/renderer/src/hooks/ipc-events/agent-status-listeners.tssrc/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.tssrc/renderer/src/hooks/legacy-worker-terminal-recovery-event.tssrc/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.tssrc/renderer/src/store/slices/agent-status-settled-worker-resume-fence.test.tssrc/renderer/src/store/slices/agent-status.tssrc/shared/agent-status-types.tssrc/shared/worktree/id.tstests/e2e/completed-worker-retirement-resume.spec.ts
Files not reviewed due to moderation or processing errors (1)
- src/main/runtime/orca-runtime.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| private liftRetiredLegacyWorkerResumeFences( | ||
| plan: LegacyWorkerTerminalRecoveryPlan, | ||
| sessions: Map<ExecutionHostId, { current: WorkspaceSessionState; next: WorkspaceSessionState }>, | ||
| changedHostIds: Set<ExecutionHostId> | ||
| ): void { | ||
| const store = this.store | ||
| if (!store?.getWorkspaceSession) { | ||
| return | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Find OrcaRuntimeService construction sites and check store-null usage
# alongside legacy worker terminal recovery invocation.
set -euo pipefail
echo "== OrcaRuntimeService constructions =="
rg -n -C3 'new OrcaRuntimeService\(' --type=ts
echo "== reconcileLegacyWorkerTerminals invocation sites =="
rg -n -C3 '\breconcileLegacyWorkerTerminals\(' --type=ts -g '!**/orca-runtime.ts'
echo "== store: null usages near runtime construction =="
rg -n -B2 -A2 'store:\s*null' --type=tsRepository: stablyai/orca
Length of output: 190
🏁 Script executed:
set -u
echo "== Scoped repository conventions =="
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print \
| sort \
| while IFS= read -r f; do
echo "--- $f"
head -80 "$f"
done
echo "== Target method and surrounding recovery flow =="
sed -n '4680,4870p' src/main/runtime/orca-runtime.ts
echo "== Constructor and direct recovery references =="
rg -n -C4 'class OrcaRuntimeService|constructor\(|reconcileLegacyWorkerTerminals|getLegacyWorkerTerminalRecoveryPlan|prepareLegacyWorkerTerminalRecovery|liftRetiredLegacyWorkerResumeFences' src/main/runtime/orca-runtime.ts
echo "== Runtime construction sites =="
rg -n -C3 'OrcaRuntimeService' --glob '*.ts' --glob '!src/main/runtime/orca-runtime.ts' . || trueRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
set -u
echo "== Knowledge file names =="
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print | sort
echo "== Relevant knowledge references =="
rg -n -i -C2 'legacy.worker|terminal.recovery|workspace.session|resume.fence|orca.runtime' \
/tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 \
| head -300 || true
echo "== Recovery implementation =="
sed -n '4695,4865p' src/main/runtime/orca-runtime.ts
echo "== Constructor =="
sed -n '3910,3975p' src/main/runtime/orca-runtime.ts
echo "== Exact recovery invocation matches =="
rg -n -C5 'reconcileLegacyWorkerTerminals' --glob '*.ts' . || true
echo "== Exact runtime construction matches =="
rg -n -C3 'new OrcaRuntimeService[[:space:]]*\\(' --glob '*.ts' . || true
echo "== Store-null and no-argument construction matches =="
rg -n -C3 'new OrcaRuntimeService\\(null|store:[[:space:]]*null|new OrcaRuntimeService\\(\\)' --glob '*.ts' . | head -500 || trueRepository: stablyai/orca
Length of output: 44076
🏁 Script executed:
set -u
echo "== Headless/orcad runtime construction and startup =="
sed -n '150,215p' src/main/orcad/orcad-entry.ts
rg -n -C8 'new OrcaRuntimeService' src/main/orcad/orcad-entry.ts src/main/index.ts
echo "== Desktop runtime initialization context =="
sed -n '3365,3440p' src/main/index.ts
echo "== Runtime store assignment and persistence capability =="
rg -n -C4 'this\.store|setStore|RuntimeStore' src/main/runtime/orca-runtime.ts | head -240
echo "== Recovery implementation line numbers =="
nl -ba src/main/runtime/orca-runtime.ts | sed -n '4710,4855p'Repository: stablyai/orca
Length of output: 20040
🏁 Script executed:
set -u
echo "== All concrete runtime constructions, excluding tests =="
rg -n -F --glob '*.ts' 'new OrcaRuntimeService' . \
| rg -v '(\.test\.ts:|\.spec\.ts:)' || true
echo "== Runtime construction sites in tests =="
rg -n -F --glob '*.test.ts' 'new OrcaRuntimeService' src/main | head -120 || true
echo "== Main store initialization and runtime construction =="
rg -n -C10 'let store|const store|new Store|runtimeService = new OrcaRuntimeService|new OrcaRuntimeService' src/main/index.ts | head -260
echo "== Recovery tests for unavailable or partial stores =="
rg -n -i -C8 'persistence unavailable|store.*null|null.*store|without.*store|unfenced|fenced' \
src/main/runtime/orca-runtime.test.ts \
src/main/runtime/orchestration \
| tail -500Repository: stablyai/orca
Length of output: 50369
Decouple fence retirement from workspace-session persistence.
OrcaRuntimeService permits store: null, while setOrchestrationDb does not depend on the store. In that mode, prepareLegacyWorkerTerminalRecovery emits 'fenced' before its persistence guard, then skips liftRetiredLegacyWorkerResumeFences; the lift method has the same guard. A later plan cannot emit 'unfenced', so startFreshSpawn can keep refusing the pane. Track fenced pane keys independently and emit retirement notifications without requiring persistence.
There was a problem hiding this comment.
Important
One settlement path — the one the new SQL explicitly adds — still isn't wired to the settlement-time fence. See the inline comment on fenceSettledWorkerPanes.
Reviewed changes
- Recovery-row SQL broadened —
listLegacyWorkerTerminalRecoveryRowsnow also returns settled workers (succeeded/failed/stopped/abandoned) whose terminal resource is still owned and not yet released/retained. - Plan-level
settledflag —planLegacyWorkerTerminalRecoveryrecords whether a blocked pane is settled, keeps settled rows out of the adoption-candidate set, and demotes a pane back to non-settled when any live dispatch still holds it. - Settlement-time stamp + retirement lift —
prepareLegacyWorkerTerminalRecoverypushesfencedto the renderer for settled panes and addsliftRetiredLegacyWorkerResumeFencesto retire the fence once the pane leaves the plan. - RPC trigger —
orchestration.sendandorchestration.checkcallfenceSettledWorkerPanesafter aworker_donereconciles tocompleted/failed. - Renderer fence action —
fenced/unfencedresolutions map to a worktree-guardedset-automatic-resume-blockstore action via the new sharedworktreeIdsEqual. - Store carry-over —
carryOverAutomaticResumeBlocknow runs on every sleeping-record re-derivation, not just manual worktree sleep.
Note: 1 inline comment(s) dropped because they did not anchor to lines inside the PR diff:
src/main/runtime/orchestration/coordinator.ts:203(RIGHT) — file not in PR diff
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| runtime: OrcaRuntimeService, | ||
| reconciled: readonly LifecycleReconciliationResult[] | ||
| ): void { | ||
| if (reconciled.some((result) => result.action === 'completed' || result.action === 'failed')) { |
There was a problem hiding this comment.
The settlement-time fence is only triggered by the worker_done reconcile results (completed/failed), and fenceSettledWorkerPanes is only called from orchestration.send and orchestration.check. But the new SQL (and WORKER_SETTLED_STATES) deliberately cover stopped and abandoned too — and those settle through orchestration.workerStop/settleWorkerStop, orchestration.workerAbandon/abandonWorkerDispatch, and reconcileMissingWorkerTerminal, none of which call this. There's no periodic sweep either (prepareLegacyWorkerTerminalRecovery runs only at startup, relay-ready, a deferred-candidate retry, or this trigger). So a stopped or abandoned worker whose terminal stays owned-and-unreleased can sit unfenced until the next app start or the next unrelated worker_done, and a workspace return in that window cold-restores it — the exact race this PR closes for succeeded/failed.
|
Closing as a duplicate of #17445, per the pre-release readiness review. #17445 implements the same STA-4577 settled-worker resume fence and its production code is a verified strict superset of this one. Splitting both It is also green, where this PR's required Nothing from this PR is lost. Its entire test contribution — which #17445 had no equivalent of — has been ported to that branch in The STA-4577 traceability, wire-compat analysis and fail-closed rationale from this PR body have been carried into the review notes on #17445. |
|
Superseded by #17651 — same branch ( |

Fixes STA-4577. One of 6 real defects split out of the test-detected-bugs sweep.
ELI5
When a supervised orchestration worker finishes, we're supposed to put a "do not auto-resume" sticker on its pane. We were forgetting the sticker — so the auto-resume logic would cheerfully restart a worker that had already reported done.
This stamps the fence at settlement time, and — equally important — lifts it once the dispatch is released, retained, or gone.
Why the lift matters as much as the stamp
startFreshSpawnrefuses any fenced pane. A fence that outlives its dispatch leaves a terminal that can never spawn again. Release, user retain, user takeover, and dispatch pruning all drop the row from the recovery plan — that is the signal to retire the fence.Fence-lift completeness
Every stamp path and every lift path, enumerated:
orchestration.send/orchestration.checklifecycle reconciliation)liftRetiredLegacyWorkerResumeFencesfencedIPC) with no persisted record behind itliftRendererLegacyWorkerResumeFences(new)orchestration.workerReleaseorchestration.workerRetainorchestration.workerTerminalUserInput(real takeover)changed > 0Two gaps were found and closed in this revision:
Release / retain / takeover ran no sweep. Each drops the worker's row from the recovery plan, but nothing re-read the plan, so the fence stayed stamped until the next app start. All three now run
sweepSettledWorkerResumeFencesin the same call.sweepingRetiredWorkerResumeFenceswraps by method name so every early return in those handlers is covered;orchestration.workerListis a pure read and is deliberately excluded. The takeover path is gated onchanged > 0because every terminal pane reports there on a 30s throttle, and only a real takeover retires the resource.A renderer-only fence had no lift path at all. The
fencedresolution is pushed live, so it can exist with no persisted record behind it (session sync lag, persistence unavailable). The runtime now remembers what it fenced inrendererFencedWorkerPaneWorktreeIdsand lifts before the persistence bail-out, so an unreadable workspace session can no longer strand a fence this runtime pushed.Bound on the worst case: even before these fixes, every fence was swept at the next app start, so the failure mode was "dead pane until restart", not literally never.
maintoday stamps the persisted fence for live dispatches with no lift at all; this PR adds the first one.Paired remote:
agentStatus:legacyWorkerTerminalRecoveryis Electron IPC only and never crosses the remote wire, so a paired client cannot observe a fence it can't lift.Residual (accepted, minor): the lift matches on pane key alone while the stamp also carries
worktreeId. Pane keys aretabId:leafIdUUID pairs, so a cross-worktree collision is not reachable in practice.Failing closed
release_state = 'unknown'keeps the fence — the SQL matchesrelease_state NOT IN ('released','retained'). An unverifiable release refuses a fresh spawn over a possibly-live process.settled: (alreadySettled ?? true) && settleddemotes a reused pane when any dispatch holding it is still live.The red
changed e2e specscheck: a real defect, inmain, not in the fencecompleted-worker-retirement-resume.spec.tswas failing withActive terminal PaneManager did not finish mounting. That is exactly what a wrongly-stamped fence would look like, so it was worth being precise about. It was not the fence.Evidence:
origin/mainproduct +origin/mainspec: fails earlier, at line 275 (state: 'working', received'done'). The spec was already red on main; the branch'sworking→doneedit legitimately fixes that first failure.origin/mainproduct + this branch's spec file only: fails at the identical line 492 with the identical message. Main's product code causes it.activeWorktreeIdis the target,everActivated: true,activeTabId: null,tabCounts: { coordinator: 1, target: 0 }(row present, empty array), andsleepingAgentSessionsByPaneKey: {}. No fence in sight.Root cause: an orchestration-retired worker tab leaves
tabsByWorktree[worktreeId] = []— the closed-last-tab tombstone. On activation,renderableTabCount === 0makesshouldGateAgentActivationtrue, so seeding is deferred intogateWorktreeAgentActivation(...).then(...). That gated branch calledensureWorktreeHasInitialTerminalwithoutreseedEmptiedWorkspace, unlike the ungated branch directly below it and unlike the folder-workspace twin. The tombstone therefore suppressed re-seeding permanently, and no pane could ever mount.Fixed in product code (
worktree-activation.ts) by giving the gated branch the same re-seed authority the ungated one already had. The test was not weakened.Non-vacuity: forcing
reseedEmptiedWorkspace: falsein the new unit test makes it fail- 1 / + 0.Wire compatibility
fenced/unfencedare new values on the existingLegacyWorkerTerminalRecoveryEvent.resolutionfield, plus a new optionalworktreeId(so the renderer can reject a pane-key alias). No new stream opcode, so no capability negotiation is required; old clients ignore resolutions they don't know.Proof
Revert the product files to
2daea491b96:orchestration-settlement-resume-fence.test.tsagent-status-settled-worker-resume-fence.test.tsorca-runtime.test.tsNew in this revision:
orchestration-worker-resume-fence-lift.test.tsworktree-activation-emptied-workspace-reseed.test.ts(+2)providesInitialSurfaceVerification at HEAD:
pnpm tc— clean.pnpm test src/main/runtime/ src/renderer/src/hooks/ src/renderer/src/store/slices/agent-status-settled-worker-resume-fence.test.ts—666 files,6865 passed | 5 skipped. One unrelated failure,terminal-output-frame-chunks-equivalence.test.ts, an 800-trial fuzz that exceeded its 30s wall-clock budget on a loaded machine (load avg 71); it is byte-identical toorigin/main, shares no code with this diff, and passes in 51s with a raised timeout.completed-worker-retirement-resume.spec.ts— 6/6 green across three runs (1×, then 2× repeat-each). Both cases run; theworker-releasecase that CI skipped now executes and passes.oxlint— exit 0, 0 errors.pnpm run check:code-quality:changed—0 new findings across 27 changed files.Known P2, accepted and documented
The fence is persisted to the workspace session. If a user runs this build, settles a worker whose terminal resource is still owned-and-unreleased, then downgrades, the older build has no code path to lift the fence.
What the downgraded user sees: that one pane stays blank and will not spawn a shell. Workaround: close the tab and open a new terminal tab — the fence is keyed per pane key (
tabId:leafId), so a new pane is unaffected. Rolling forward again self-heals on the first sweep.Reduction attempt, evaluated and rejected. The obvious fix is to persist settled fences under a new enum value (e.g.
'settled-orchestration-worker') rather than reusing'legacy-orchestration-worker'. An older build'ssalvagingRecordwould fail to parse that record and drop only it, so the downgraded build would see no fence at all — the P2 disappears. It works, but it touches ~6 strict=== 'legacy-orchestration-worker'comparison sites plus the IPC payload and the stamp/lift transition logic, which is more surface than a CI fix and a de-risk pass should carry. Recorded here so the next change in this area can pick it up.Otherwise accepted because: it is not a regression of this build (rolling forward self-heals via the lift); the previous build already leaks fences it stamps itself, so this enlarges the population of a pre-existing old-build defect rather than introducing one; and reachability is narrow. Removing it would mean not persisting the fence at all — which is precisely the bug.
Note on
src/shared/worktree/id.tsThis PR adds
worktreeIdsEqual(a small helper over the already-existingworktreeIdComparisonKey) because the recovery listener needs it. The STA-5701 PR adds the identical function. The additions are byte-identical, so the two merge cleanly in either order — verified by merging all split branches and diffing against the original combined tree (empty).Performance Measurement
Deterministic settled-worker fixture: the old path allowed 1 fresh-resume attempt after settlement; the fence makes that 0 while the dispatch is settled, then retires the fence when the dispatch is released, retained, or taken over. No extra polling or subprocess work is added. The new sweeps are one recovery-plan read on release/retain/takeover — user-initiated, low-frequency events, and the takeover path is gated on an actual ownership change so ordinary panes never pay for it.
User-Facing Trade-offs
None in the current build. Settled workers no longer restart spuriously; an emptied workspace now re-seeds a terminal on the gated activation path instead of opening blank; and the documented downgrade caveat now carries an explicit user workaround.