Repository navigation
fix(native-chat): every lease latch has a way to die - #22820
Conversation
There was a problem hiding this comment.
Caution
Attaching or holding a chat whose lease is conflicted and names a live owner now throws RangeError: Maximum call stack size exceeded in the main process from a self-recursive refusal-message helper. Reproduced by calling structuredAgentSessionRefusalMessage('agent_session_conflict', record) directly on a conflicted record that has an ownerProcess.
Reviewed changes
- Settlement latch removed —
settlementRetryRequired/settlementRetryIdare deleted; the terminal settlement a dead generation owes is now derived from the journal plus the lease's death evidence at the next acquire or read restore, and the retry module and its phase are gone. - Ownerless reservations released — restart adjudication and failed-acquisition settlement now release a reservation that recorded no process, carrying death evidence only when a spawn-token scan proved nothing spawned.
- Recovery always concludes —
resolveStructuredSessionRecoveryevicts on proof, stops a same-host live owner by identity then evicts, and otherwise releases without sending a signal; aconflictedclaim stays unresolved only while its owner is proven alive. - Codex records its pid at spawn —
onSpawnedcommits the child's identity before the initialize handshake, so a crash mid-start leaves a stoppable owner, and the later identity commit is now an equality check. - Retired fields dropped at load —
processlessAtand the settlement latch fields are stripped by the store transaction queue and removed from the lease type and validator;manual-recoverymaps torecovering.
⚠️ A conflicted owner that cannot be verified is released, against the stated policy
resolveStructuredSessionRecovery returns 'unresolved' for a conflicted claim only inside the isProvenAliveProbe branch (lines 57-60). When the probe is indeterminate, the conflicted claim falls through to releaseUnprovenAgentSessionOwner (lines 64-71), which accepts claimStatus: 'conflicted' and clears the lease with deathEvidence: null. Before this change a conflicted claim was never evicted without proof of its named owner's death. The head comment says a conflicted claim "is waited out and never stopped: it is the user's own agent, and its exit is its way out" — but the indeterminate branch releases it instead. A terminal agent's transport is the user's terminal, which did not die with the crashed Orca runtime, so unlike the native-child case the "nothing can drive it" argument does not apply, and the next attach can resume the same provider thread while the terminal may still be writing. The PR description's table does say this release is intended, so this is likely a deliberate tradeoff against the stuck-chat bug; if so, please make the function's head comment and the shared reasoning say that explicitly, since this is the one branch where it does not hold.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| } | ||
| } | ||
| mutations.push(...runningTurnLifecycleRevisions(items, verdict)) | ||
| if (verdict.state === 'interrupted' && items.some(isInProgressItem)) { |
There was a problem hiding this comment.
This replacement for retryLoadedStructuredAgentSessionSettlement only revises lifecycle rows. The deleted retry also retired unsettled submissions via markPendingSubmissionsUnknown, and it gated the "provider stopped while this response was in progress" row on unfinishedStructuredAgentSessionWorkWasInterrupted(...), which is true when an unsettled submission exists. The read/reveal path never opens through attachJournal — the one remaining caller of markPendingSubmissionsUnknown — so a send left pending by a crashed provider is now neither retired nor given the outcome row.
Technical details
# Stale settlement drops the submission dimension
## Affected sites
- `src/main/native-chat/agent-session-wire/structured-agent-session-dead-generation-settlement.ts:213-253` — writes no submission mutation; the status row at line 234 is gated on `items.some(isInProgressItem)` alone.
- `src/main/native-chat/agent-session-wire/structured-agent-session-restart-restore.ts:84` — the read restore calls this without ever going through `attachJournal`.
- Compare deleted `retryLoadedStructuredAgentSessionSettlement` (diff lines 1798-1928): `settleStructuredAgentSessionDeadGeneration` called `markPendingSubmissionsUnknown` / `rejectPendingSubmissions`, and `showUnexpectedExitOutcome` used `unfinishedStructuredAgentSessionWorkWasInterrupted`.
## Required outcome
- A crashed provider's unanswered send is retired on the read/reveal path too, and an observed exit that interrupted an in-flight send still earns the outcome row.
## Suggested approach (optional)
- Reuse `unfinishedStructuredAgentSessionWorkWasInterrupted(captureUnfinishedStructuredAgentSessionWork(journal), journal, verdict.completedAt)` for the status-row gate, and call `markPendingSubmissionsUnknown` here — or state explicitly that submissions are retired only at attach.
## Open questions for the human (optional)
- Is `attachJournal` the intended single choke point for retiring submissions, making the read/reveal gap acceptable?There was a problem hiding this comment.
ℹ️ Test-only follow-up commits; no new production changes. The blocking finding from the prior review — the self-recursive
ownerDescriptionfor a conflicted owner — is untouched by these commits and still applies.
Reviewed changes (delta since the prior review at ea2de58)
- Mid-turn-at-quit coverage —
structured-agent-session-wedged-profile-migration.test.tsnow pins that a chat mid-turn when the app quit reopens with no running turn and no publishedworkingstatus, for both an observed exit that could not be settled and a probe-proven death. - Attach before the boot sweep — a new case pins that a restart eviction is settled through an attach that arrives before the read-restore sweep.
- Cross-version downgrade test — new
tests/e2e/cross-version-wire/agent-session-unproven-release-downgrade.unit.test.tswrites an unproven release with this build, then opens it with the pinnedv1.4.211record store and proves it loads, reconciles, and can reserve a new owner over it.
The new assertions look like they can fail against the old behavior (the mid-turn cases check the settled turn state and that no working status is published; the downgrade case checks isSessionUnreadable and a successful reserveOwner on the baseline store). Note the PR body still lists the cross-version suites as not run locally, so CI is the first real execution of the downgrade test.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found in the new commits. The prior self-recursion finding is fixed, and the
conflicted-owner recovery path now matches its stated policy.
Reviewed changes (delta since the prior pullfrog review at 78e98b2)
- Self-recursive refusal helper fixed —
ownerDescriptionno longer carries a conflicted-owner branch that interpolated itself; the conflicted sentence lives only inlatchedMessage, so rendering a refusal for a conflicted owner returns a string instead of overflowing the stack.structured-agent-session-legacy-handoff-record.test.tsnow asserts the refusal names the process to quit. - A
conflictedowner recovery cannot verify is now waited out —resolveStructuredSessionRecoveryreturnsunresolvedfor anyconflictedclaim with a recorded owner whose probe is not proven dead, includingindeterminate, rather than releasing it; the head comment and the claim-status docs now say so explicitly.structured-agent-session-wedged-profile-migration.test.tspins the refusal and that a laterpid-absentprobe lets the chat take over. - Cross-version downgrade test wired into CI — the new
agent-session-unproven-release-downgrade.unit.test.tsjoins the cross-version job's file list, andsrc/shared/agent-session-recordjoins the cross-version wire prefixes so record changes trigger that job.
The three changed test files run green (29 passed). One prior thread remains open and is untouched by this delta: the settlement replacement at structured-agent-session-dead-generation-settlement.ts:234 still does not retire pending submissions on the read/reveal path. It is not re-raised here.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found in the new commits.
Reviewed changes (delta since the prior pullfrog review at 8653aa4)
- Retired
manual-recoverystage mapped at decode —normalizeLegacyHandoffLeasenow mapsmanual-recoverytorecoveringthrough a sharedisLegacyHandoffStagehelper,AgentSessionHandoffStageis narrowed to'new-owner-proving' | 'recovering', andleaseCarriesLegacyHandoffValuesmarks such records for write-back. On-disk validation still acceptsmanual-recovery(isPersistedAgentSessionHandoffStage), so an older record still loads and a record this build writes back can no longer carry the retired latch to an older build. - Dead
manual-recoverybranches deleted — the acquisition refusal, the lease-renewer skip,releaseUnprovenAgentSessionOwner's stage check, and thestructuredAgentSessionOwnerStatus"manual recovery is required" answer (with itsphase: 'failed'reply) could only ever see that stage, so they are gone. Every in-memory consumer already treatedrecoveringandmanual-recoveryidentically, so the mapping is behavior-preserving. - Orphan-reaper comment corrected —
adjudicateAgentSessionRestart's comment no longer claims the store-open reaper stops a live token-carrying child on that launch; it now matches the PR's stated behavior that the reaper runs while the lease still claims the token.
The one open prior thread at structured-agent-session-dead-generation-settlement.ts:234 (the read/reveal settlement path does not retire pending submissions) is untouched by these commits and is not re-raised here.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues found in the new commits. The retry-continuation path and the unified terminal-owner refusal are covered by store-level and host-level tests, and the fence/token compare-and-swap still holds.
Reviewed changes (delta since the prior pullfrog review at 371462a)
- A create retried after recovery released its reservation continues —
commitAgentSessionReservationnow derives acontinuedrequest when the lease is released and, under the same operation id, re-reserves at the next fence for both a still-pendingreplay row and an already-expired (pruned) one. A late spawn from the old reservation is refused at its fence and by token, and a further retry while the new reservation stands re-enters it rather than spawning again.pendingAgentSessionOperationRowis factored out ofevaluateAgentSessionOperation, and new store-level plus host-level tests pin both row states. - One refusal message for a terminal-owner claim —
terminalOwnerRefusalMessageis now the single wording for aconflictedclaim, shared by the refusal-message helper, the mutation envelope, and hold/resume, so sending and opening a chat an older build's terminal agent holds both say to quit that process. - Small cleanups —
isResumableStructuredAgentSessionRecorddelegates toagentSessionLeaseIsReleased, and the refusal helper's now-dead settlement-latch branch is removed.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
A failed exit settlement no longer leaves the lease in recovery: the release writes no stage and keeps the exit in its death evidence, and whatever the dead generation left running is settled from that evidence at the next acquire or read restore. The settlement retry flag, its disposition and every branch that read it are gone. A reservation that recorded no process is released at startup and after a failed start, the never-written conflicted status and the processless proof are deleted, recovery resolution always concludes, and Codex records its child's identity at spawn, before the handshake.
…in recovery rather than manual recovery
… build reads an unproven release
…d of recursing Opening a chat whose terminal owner an older build recorded threw a stack overflow instead of the refusal that names the process to quit.
…stead of releasing it A terminal agent an older build recorded keeps its PTY across an Orca restart, so a probe that cannot answer (a start-time read that fails on a loaded host) is not evidence its transport is gone. Releasing it let a native child resume the same conversation beside the live terminal agent. Only proof of its exit now ends the claim.
The sharded unit job excludes tests/e2e/cross-version-wire, and the cross-version job runs an explicit list that did not name the new test, so it never ran in CI. A change to the record validator now also starts the job.
…ering at decode Nothing in this build writes manual-recovery, and restart reconciliation already rewrites it. Mapping it where the other retired handoff stages are mapped removes it from the in-memory lease type and deletes the branches that could only see it: the acquisition refusal, the renewer skip, the unproven-release stage check, and the handoff-status 'manual recovery is required' answer. Older builds accept recovering, so a record written back still loads after a downgrade.
…rvation leaves The reaper runs once at store open, while the unreconciled lease still claims the child's token, so it does not stop that child on this launch. The comment claimed it did.
…ts reservation The client retries a create it never heard back from under the same operation id. Recovery had released that create's reservation, so the retry was refused agent_session_ownership_unknown while its row was pending, and agent_session_operation_expired once the row aged out, and the chat never started. A retry whose lease nothing holds now continues as a fresh reservation at the next fence, which also stops the old reservation's spawn from committing.
…rminal agent holds A chat held by a terminal agent an older build recorded frees only when that agent exits. Sending said to reopen the chat and opening it said two runtimes claimed it; both now say the chat is open in a terminal agent, name its process, and say to quit it. Error codes are unchanged.
6ee8ae9 to
3e65466
Compare
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (1)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review. 📝 WalkthroughWalkthroughThe changes revise structured agent-session ownership and recovery. Codex acquisition records a spawned process identity before the handshake. Recovery releases certain ownerless or unproven leases and removes settlement-retry state from lease records. Stale journal state is settled during acquisition and restoration using available death evidence. Operation admission can continue eligible retries after recovery releases a reservation. Tests cover these flows and add a cross-version downgrade check. Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to An unrelated expired request can start a new agent after a lease is released. Restrict continuation to the operation that held the reservation before merging. Security Architecture ReviewSecurity architecture risk: 🟠 High · up to An interrupted structured chat can become usable again, but recovery may permit a new agent to start while the previous agent process is still present. That could undermine the guarantee that only one agent acts on a conversation. The affected chat mode is described as optional and off by default. Retained concerns
Security review detailsSecurity Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 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 |
… time can tell it from a reused pid
Review status: ready for merge reviewHead What the review did
Fixes pushed during review
Live QA (isolated dev build, macOS)
Before (base), relaunched after a kill mid-start: After (this PR), Retry starts the agent and it replies: After a clean restart, the chat still works: Base-stuck profile upgraded to this build, Retry replies: New Claude chat on this build: The QA re-run tested Validation
Not covered
Known residuals (listed in the PR Notes, none new to users)
|
Ready to mergeChecked at head
|
…ches-die # Conflicts: # src/main/runtime/claude-structured-session-integration.test.ts
…ches-die # Conflicts: # src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts # src/main/native-chat/agent-session-wire/structured-agent-session-host.test.ts
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 756b63e8-40e9-4ddc-84b4-5fcdf3736fbe
📒 Files selected for processing (76)
.github/workflows/pr.ymlconfig/scripts/pr-code-change-scope.mjssrc/main/claude/claude-context-usage-restart.test.tssrc/main/claude/claude-structured-session-state.tssrc/main/codex/codex-app-server-connection-types.tssrc/main/codex/codex-app-server-connection.test.tssrc/main/codex/codex-app-server-connection.tssrc/main/codex/codex-structured-owner-identity.tssrc/main/codex/codex-structured-session-acquire.tssrc/main/codex/codex-structured-session-close.test.tssrc/main/codex/codex-structured-session-close.tssrc/main/native-chat/agent-session-wire/structured-agent-session-acquisition-options.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-acquisition.tssrc/main/native-chat/agent-session-wire/structured-agent-session-adapter.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.tssrc/main/native-chat/agent-session-wire/structured-agent-session-crash-mid-start.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-dead-generation-settlement.tssrc/main/native-chat/agent-session-wire/structured-agent-session-failed-create-owner-verdict.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-hold-resume.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host.tssrc/main/native-chat/agent-session-wire/structured-agent-session-lease-release.tssrc/main/native-chat/agent-session-wire/structured-agent-session-lease-renewer.tssrc/main/native-chat/agent-session-wire/structured-agent-session-legacy-handoff-record.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-owner-status.tssrc/main/native-chat/agent-session-wire/structured-agent-session-processless-reservation.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-readable-restorer.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-readable-restorer.tssrc/main/native-chat/agent-session-wire/structured-agent-session-recovered-turn-clock.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-recovery-exits.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-recovery-resolution.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-recovery-resolution.tssrc/main/native-chat/agent-session-wire/structured-agent-session-refusal-message.tssrc/main/native-chat/agent-session-wire/structured-agent-session-restart-restore.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-restart-restore.tssrc/main/native-chat/agent-session-wire/structured-agent-session-resume-eligibility.tssrc/main/native-chat/agent-session-wire/structured-agent-session-reveal.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-reveal.tssrc/main/native-chat/agent-session-wire/structured-agent-session-send-preparation.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-settled-attach-retry.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.tssrc/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.tssrc/main/native-chat/agent-session-wire/structured-agent-session-surface-lifetime.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.tssrc/main/native-chat/agent-session-wire/structured-agent-session-wedged-profile-migration.test.tssrc/main/observability/agent-session-instrumentation.tssrc/main/observability/instrumentation.test.tssrc/main/runtime/agent-session-acquisition-failure-settlement.tssrc/main/runtime/agent-session-eviction-settlement-latch.test.tssrc/main/runtime/agent-session-lease-transitions.tssrc/main/runtime/agent-session-process-identity-probe.tssrc/main/runtime/agent-session-processless-reservation.tssrc/main/runtime/agent-session-record-store-legacy-handoff-lease.test.tssrc/main/runtime/agent-session-record-store.test.tssrc/main/runtime/agent-session-record-store.tssrc/main/runtime/agent-session-released-reservation-replay.test.tssrc/main/runtime/agent-session-reservation-admission.test.tssrc/main/runtime/agent-session-reservation-admission.tssrc/main/runtime/agent-session-restart-lease-transitions.tssrc/main/runtime/agent-session-store-transaction-queue.tssrc/main/runtime/agent-session-surface-release-transition.tssrc/main/runtime/claude-structured-session-integration.test.tssrc/main/runtime/structured-agent-session-owner-probe.tssrc/main/runtime/structured-agent-session-runtime.test.tssrc/main/runtime/structured-claude-runtime-adapter.tssrc/shared/agent-session-lease-adjudication.test.tssrc/shared/agent-session-lease-adjudication.tssrc/shared/agent-session-legacy-handoff-lease.test.tssrc/shared/agent-session-legacy-handoff-lease.tssrc/shared/agent-session-mutation-envelope.tssrc/shared/agent-session-operation-ledger.tssrc/shared/agent-session-record.tstests/e2e/cross-version-wire/agent-session-unproven-release-downgrade.unit.test.ts
💤 Files with no reviewable changes (10)
- src/main/runtime/agent-session-processless-reservation.ts
- src/main/runtime/structured-claude-runtime-adapter.ts
- src/main/native-chat/agent-session-wire/structured-agent-session-owner-status.ts
- src/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.test.ts
- src/main/runtime/agent-session-eviction-settlement-latch.test.ts
- src/main/claude/claude-structured-session-state.ts
- src/main/runtime/structured-agent-session-runtime.test.ts
- src/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.ts
- src/main/observability/agent-session-instrumentation.ts
- src/main/native-chat/agent-session-wire/structured-agent-session-processless-reservation.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| await (owner && !isProvenDeadProbe(probe) | ||
| ? deps.store.transitionHandoff(sessionId, (latest) => | ||
| releaseUnprovenAgentSessionOwner({ | ||
| record: latest, | ||
| expectedFence: record.lease.runtimeFence, | ||
| now: deps.now() | ||
| }) | ||
| ) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- changed file diff ---'
git diff --unified=80 1c2cf120e32fca765b8313def90647c013c9c113 a407acbc0c0692103a71e173a6628ed145af4467 -- src/main/native-chat/agent-session-wire/structured-agent-session-recovery-resolution.ts
printf '%s\n' '--- target file ---'
cat -n src/main/native-chat/agent-session-wire/structured-agent-session-recovery-resolution.ts
printf '%s\n' '--- recovery symbols ---'
rg -n -C 5 'stopOwnerAndReprobe|releaseUnprovenAgentSessionOwner|isProvenDeadProbe|identity-matched|unresolved' src/main/native-chat src/main | head -n 300
printf '%s\n' '--- provider/process symbols ---'
rg -n -C 5 'stdin|SIGKILL|spawn|Codex|Claude|close|EOF|tool execution|tool_use' src/main/native-chat src/main | head -n 400Repository: stablyai/orca
Length of output: 42136
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 35265
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- relevant files ---'
git ls-files | rg '(^|/)(agent|runtime|native-chat|claude|codex|provider|process|child|lease).*\\.(ts|tsx|js|mjs)$' | head -n 400
printf '%s\n' '--- release transition and lease adjudication ---'
rg -n -C 12 'function releaseUnprovenAgentSessionOwner|releaseUnprovenAgentSessionOwner|type AgentSessionOwnerProbe|isProvenAliveProbe|isProvenDeadProbe|ownerProcess' src/shared src/main/runtime src/main/native-chat
printf '%s\n' '--- provider launch and stdin lifecycle ---'
rg -n -C 10 --glob '*.{ts,tsx,js,mjs}' '(spawn|spawnSync|fork|execFile|stdin\\.end|stdin\\.destroy|\\.stdin|SIGTERM|SIGKILL|on\\(['\"'\"'](close|exit|error)|process\\.kill|kill\\()' src/main src/shared | rg -i 'codex|claude|agent|provider|runtime|child|stdin|spawn|kill|close|exit' | head -n 500
printf '%s\n' '--- direct provider name references ---'
rg -n -C 8 --glob '*.{ts,tsx,js,mjs,json,md}' '\\b(codex|claude)\\b' src/main src/shared | head -n 500Repository: stablyai/orca
Length of output: 45661
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- release transition ---'
rg -n -C 20 'releaseUnprovenAgentSessionOwner' src/main/runtime src/main/native-chat src/shared
printf '%s\n' '--- files containing process creation ---'
rg -l --glob '*.ts' --glob '*.tsx' --glob '*.js' --glob '*.mjs' 'spawn\(|execFile\(|fork\(' src/main src/shared | sort | head -n 150
printf '%s\n' '--- files containing provider launch names ---'
rg -l --glob '*.ts' --glob '*.tsx' --glob '*.js' --glob '*.mjs' -i 'codex|claude' src/main src/shared | sort | head -n 200
printf '%s\n' '--- lifecycle references in native-chat and runtime ---'
rg -n -C 8 --glob '*.ts' '(stdin|stdout|stderr|process\\.kill|\\.kill\\(|\\.on\\("close"|\\.on\\("exit"|\\.on\\('"'"'close'"'"'|\\.on\\('"'"'exit'"'"')' src/main/native-chat src/main/runtime | head -n 500Repository: stablyai/orca
Length of output: 33401
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- structured session files ---'
git ls-files src/main/native-chat/agent-session-wire src/main/native-chat | grep -E 'structured-agent-session|agent-session-wire' | head -n 250
printf '%s\n' '--- structured adapter and transport references ---'
rg -n -C 10 'adapter|dispatch|send|close|stdin|transport|child|process' src/main/native-chat/agent-session-wire src/main/native-chat/structured-agent-session* 2>/dev/null | head -n 700
printf '%s\n' '--- Codex/Claude structured process files ---'
rg -l --glob '*.ts' --glob '*.tsx' 'structured|app-server|query\(|spawn|stdin|close|kill' src/main/codex src/main/claude | sort | head -n 250
printf '%s\n' '--- exact close and stdin calls in provider directories ---'
rg -n -C 8 --glob '*.ts' --glob '*.tsx' 'stdin|stdout|stderr|process\\.kill|kill\\(|\\.close\\(|\\.end\\(|\\.destroy\\(|on\\(' src/main/codex src/main/claude | head -n 700Repository: stablyai/orca
Length of output: 42763
🏁 Script executed:
#!/bin/bash
set -eu
for f in \
src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts \
src/main/claude/claude-structured-session-adapter.ts \
src/main/claude/claude-structured-session-close.ts \
src/main/claude/claude-structured-session-exit-lifecycle.ts \
src/main/claude/claude-agent-sdk-process-spawn.ts \
src/main/codex/codex-app-server-process-teardown.ts \
src/main/codex/codex-app-server-posix-supervisor.ts \
src/main/codex/codex-app-server-connection.ts
do
if [ -f "$f" ]; then
printf '\n--- %s (%s lines) ---\n' "$f" "$(wc -l < "$f")"
cat -n "$f"
fi
done
printf '\n--- targeted provider lifecycle text ---\n'
rg -n -C 8 'stdin|close|destroy|kill|SIGTERM|SIGKILL|turn|tool|exit|terminate' \
src/main/claude/claude-structured-session-adapter.ts \
src/main/claude/claude-structured-session-close.ts \
src/main/claude/claude-structured-session-exit-lifecycle.ts \
src/main/claude/claude-agent-sdk-process-spawn.ts \
src/main/codex/codex-app-server-process-teardown.ts \
src/main/codex/codex-app-server-posix-supervisor.ts \
src/main/codex/codex-app-server-connection.ts \
src/main/native-chat/agent-session-wire/structured-agent-session-adapter.tsRepository: stablyai/orca
Length of output: 43212
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- released lease construction ---'
sed -n '248,275p' src/main/runtime/agent-session-lease-transitions.ts
printf '%s\n' '--- Claude process and close lifecycle ---'
rg -n -C 12 'createClaudeCodeProcessSpawn|stdin|close\\(|kill\\(|SIGTERM|SIGKILL|exit' \
src/main/claude/claude-agent-sdk-process-spawn.ts \
src/main/claude/claude-structured-session-close.ts \
src/main/claude/claude-structured-session-exit-lifecycle.ts \
src/main/claude/claude-structured-session-adapter.ts
printf '%s\n' '--- Codex EOF and forced teardown ---'
rg -n -C 12 'stdin\\.end|stdin end|terminateCodexAppServerProcessTree|SIGKILL|process group|1250|1500|close\\(' \
src/main/codex/codex-app-server-posix-supervisor.ts \
src/main/codex/codex-app-server-process-teardown.ts \
src/main/codex/codex-app-server-connection.tsRepository: stablyai/orca
Length of output: 1141
Keep an identity-matched survivor unresolved.
If stopOwnerAndReprobe still returns a proven-live identity match after SIGKILL, the current branch clears ownerProcess and releases the lease without death evidence. A later attach can then grant a new owner while the old process may still execute its current turn, causing concurrent file edits and token use. Keep this case unresolved, but retain release for an indeterminate probe.
🐛 Suggested fix
if (owner && isProvenAliveProbe(probe)) {
if (owner.hostId !== deps.store.hostId) {
return 'unresolved'
}
probe = await stopOwnerAndReprobe(deps, record, owner.pid)
}
+ if (owner && isProvenAliveProbe(probe)) {
+ return 'unresolved'
+ }
try {Source: Learnings
| if (decision.decision === 'refused') { | ||
| throw new Error(decision.code) | ||
| // An aged-out row proves nothing more: a released reservation runs no effect. | ||
| if (decision.code !== 'agent_session_operation_expired' || !continued) { | ||
| throw new Error(decision.code) | ||
| } | ||
| const row = pendingAgentSessionOperationRow({ ...request.operation, now: request.now }) | ||
| return reserveWithOperationRow(state, continued, row, leaseTtlMs) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
rg -nP -C4 'handoffOperationId' src/main/runtime/agent-session-lease-transitions.ts src/main/runtime/agent-session-restart-lease-transitions.ts src/main/runtime/agent-session-processless-reservation.tsRepository: stablyai/orca
Length of output: 6396
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- changed admission outline ---'
ast-grep outline src/main/runtime/agent-session-reservation-admission.ts
printf '%s\n' '--- admission relevant source ---'
sed -n '200,370p' src/main/runtime/agent-session-reservation-admission.ts
printf '%s\n' '--- lease transition source ---'
sed -n '1,290p' src/main/runtime/agent-session-lease-transitions.ts
printf '%s\n' '--- restart transition source ---'
sed -n '1,100p' src/main/runtime/agent-session-restart-lease-transitions.ts
printf '%s\n' '--- operation and admission references ---'
rg -n -C3 'agent_session_operation_expired|pendingAgentSessionOperationRow|commitAgentSessionReservation|handoffOperationId|operationId' src/main/runtime -g '*.ts'
printf '%s\n' '--- diff from supplied merge base ---'
git diff --unified=30 1c2cf120e32fca765b8313def90647c013c9c113 a407acbc0c0692103a71e173a6628ed145af4467 -- src/main/runtime/agent-session-reservation-admission.ts src/main/runtime/agent-session-lease-transitions.ts src/main/runtime/agent-session-restart-lease-transitions.tsRepository: stablyai/orca
Length of output: 42435
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- lease schema ---'
rg -n -C8 'export type AgentSessionLease|handoffOperationId|claimStatus|deathEvidence' src/main/shared src/main/runtime -g '*.ts'
printf '%s\n' '--- operation ledger ---'
sed -n '1,260p' src/main/shared/agent-session-operation-ledger.ts
printf '%s\n' '--- release and reservation call sites ---'
rg -n -C5 'releaseUnprovenAgentSessionOwner|evictAgentSessionOwner|applyAgentSessionRestartAdjudication|commitAgentSessionReservation' src/main -g '*.ts'
printf '%s\n' '--- focused replay tests ---'
fd -i 'agent-session-released-reservation-replay' src
fd -i 'agent-session.*replay.*test' src
rg -n -C8 'expired|released|handoffOperationId|operationId' src/main/runtime/*released* src/main/runtime/*replay* 2>/dev/null || trueRepository: stablyai/orca
Length of output: 45663
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- locate shared sources ---'
fd -t f -i 'agent-session-(record|operation-ledger|lease-adjudication).*\.ts' .
printf '%s\n' '--- operation ledger definitions ---'
ledger=$(fd -t f -i 'agent-session-operation-ledger\.ts' . | head -n1)
if [ -n "$ledger" ]; then
cat -n "$ledger"
fi
printf '%s\n' '--- handoff operation call sites ---'
rg -n -C5 'handoffOperationId' src -g '*.ts' \
-g '!*.test.ts' \
| head -n 500
printf '%s\n' '--- operation request call sites ---'
rg -n -C4 'operation:\s*\{|operationId:' src/main/runtime -g '*.ts' \
-g '!*.test.ts' | head -n 500Repository: stablyai/orca
Length of output: 41941
Bind expired continuations to the released operation.
The continued check only tests whether the session lease is released. It does not bind the request to the operation that created that reservation. After operation X is pruned, a retry of X can create a new pending row and reserve a session whose later reservation Y was released.
Preserve the released reservation's operation ID in a durable marker. Require that marker to equal request.operation.operationId before accepting an expired continuation. The current handoffOperationId cannot provide this marker after release because the release transitions clear it. Reject the continuation when the marker is absent or does not match.
There was a problem hiding this comment.
ℹ️ No new issues found in the new commits.
Reviewed changes (delta since the prior pullfrog review at 6ee8ae9e34)
- The terminal-owner refusal names a process only when its start time can identify it —
terminalOwnerRefusalMessageappends(process <pid>)only whenownerProcess.processStartTimeMsis recorded, so aconflicted(legacy terminal) refusal never points at a pid that may since belong to an unrelated process. A new unit test pins both wordings, and the existing host test still holds because its lease carries a start time. origin/mainmerged in — two merge commits bring the branch up tomain(1c2cf120e3). They change no author production code; the PR's diff againstmainkeeps its intended removals (owner-statusmanual-recovery branch, settlement-retry module, mutation-envelope wording).
The one previously-flagged open thread (structured-agent-session-dead-generation-settlement.ts:234) is untouched by these commits and remains open, so this review is not an approval.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…ts still-pending attach cannot race the new host
There was a problem hiding this comment.
ℹ️ No new issues found in the new commits. The delta is test-only, and the changed test still passes and still pins the same behavior.
Reviewed changes (delta since the prior pullfrog review at a407acb)
- Crash simulation no longer shares one store between generations —
structured-agent-session-crash-mid-start.test.tsnow gives each host generation its own directory.crash()flushes the dying store's queued writes (renewLeases([])) and copies its directory to the relaunch's root (excluding.tmp/.lock), so the dying host's still-pending in-process attach cannot race or write to the store the relaunched host reads. The spawn case'swaitFornow also requires the durableownerProcess, and the never-settlingattachpromises get a.catch(() => {}). origin/mainmerged in —8081df1206is a base-only merge; the range-diff isolates no author production change.
The one previously-flagged open thread (structured-agent-session-dead-generation-settlement.ts:234) is untouched by these commits, so this review is not an approval.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Brings in main's squash of L (#22820), which replaces the L commits this branch carried.






Scope: which chat this affects
experimentalStructuredNativeChatsetting, which is off by default (src/shared/default-global-settings.ts:137).Builds on #22783, which has merged; this PR now targets
main.ELI5
Orca writes down which process owns each chat, so that it never runs two agents on the same conversation. Some of those notes could get stuck. When that happened, the chat refused every message until you restarted Orca, and sometimes kept refusing after a restart too. This PR makes sure every stuck note has a way to clear itself, and the chat starts again on the next message.
What Changed
What you saw before:
What you see now:
In every one of these cases the chat starts a fresh agent again: on the next message, or, for a chat that was still starting when Orca stopped, on Retry (a message sent before Retry waits in the chat and is answered once the agent starts). The unfinished reply from the dead agent is closed off with the exit reason the agent gave, just as it would have been if the first write had worked. The one exception is a chat still held by a terminal agent from an older version of Orca: it waits for that agent to exit, and sending or opening the chat now says so, names the agent's process, and says to quit it.
Mechanism. These deletions and changes are all in the lease record (the note of who owns a chat) and the code around it:
Settlement retry deleted. Before, a crash whose journal cleanup failed set a "settlement still owed" flag and a
recoveringstage. The start path refused while the flag was set, and nothing but a successful retry cleared it.Reservations with no recorded process are released. A reservation that never recorded a process is released:
Deleted: the never-set "processless" proof field, its store method and probe branch, and the unused conflict marker. Nothing writes
manual-recoveryany more: a record that carries it loads asrecovering, mapped at decode like the removed handoff stages, so the stage and every branch that handled it (including the "manual recovery is required" status answer) are gone. A live terminal owner an older build recorded now waits inrecovering.Recovery always reaches a verdict.
conflictedclaim, and is still waited out, never stopped, including when its identity can't be verified: a terminal keeps its transport across an Orca restart, so only proof that it exited ends that claim. Sending and opening the chat now both say the chat is still open in a terminal agent, name its process, and say to quit it. Before, sending said to reopen the chat and opening it said two runtimes claimed it. Error codes are unchanged.A create retried after recovery released it continues. The client keeps a create it never heard back from and retries it under the same operation id. That create's ledger row stays
pendinguntil it expires about 24 hours later, and the replay path only continued a reservation that still existed. Recovery had just released this one, so every Retry was refusedagent_session_ownership_unknown("Chat connection could not be confirmed"), and after the row expired,agent_session_operation_expired. Now a retry whose lease nothing holds (released, no stage, reconciled) continues as a fresh reservation at the next fence under the same id, whether the row is still pending or has expired. This is derived from the lease, with no new stored field. The fence move is what stops a spawn from the old reservation committing, and a second retry while the new reservation stands re-enters it instead of spawning again. A retry whose reservation is still held (reserved, live, recovering orconflicted) is answered exactly as before.Codex records its process at spawn. The Codex connection reports the child's pid before the initialize handshake. The host writes the identity to the lease right then, so a crash mid-start leaves an owner the next launch can stop by identity. The later identity commit becomes an equality check.
Why
These were latches with no way to die: a durable "work is still owed" fact that nothing re-derived. The fix removes the stored flag and derives the same answer from facts Orca already keeps:
Alternatives considered:
stop-unproven,identity-unverifiable). An older build rejects an unknown kind and marks the whole record unreadable, so a downgrade would lose the chat.unverifiable, neverexited, both to workers and in the owner verdict clients receive.Differences from the plan
Two places where the design this series follows was wrong when checked against the code, corrected here:
stop-unproven,identity-unverifiable, orexit-observed("no process was recorded").exit-observed,pid-absentandidentity-mismatch(isAgentSessionDeathEvidence,src/shared/agent-session-record.ts:280-293onmain). A new kind would put the record in the unreadable set after a downgrade.exit-observedwould also be false for an unproven release. It would makeobserveStructuredWorkeranswerexited(src/main/runtime/structured-worker-authority.ts:117), and turn the stale-turn verdict intointerrupted.deathEvidence: null. Older builds already accept that on any lease:lease.deathEvidence === null || isAgentSessionDeathEvidence(...)atsrc/shared/agent-session-record.ts:334onmain, with no rule tying it toclaimStatus.structured-agent-session-restart-restore.ts:82,retrySettlement). Without a replacement, a chat that was mid-reply when the app quit would show a running turn, and a "working" row, until the next send. The derived settlement therefore also runs at read restore, before the chat is published.The design also said to delete the
conflictedclaim status because no build wrote it. #22783 now writes it when it loads a terminal owner an older build recorded, so it is kept as the claim recovery waits out and never stops. Only the unused conflict marker and theconflictedrestart disposition are deleted.Differences from the common pattern
The comparable desktop agent hosts restart a conversation's provider without proving the old one dead. At startup they settle an orphaned session's state from what they already hold (the "was running, no live runtime" projection), best effort and never blocking, and they finish a bounded kill even when the stop is unproven.
Partial matches (the part that matches, and the part that does not):
Deviations:
Linked Issue
Part of the native-chat "a chat never gets stuck" series.
Visual Proof
Live run in an isolated dev build on macOS. A Codex chat is killed mid-start (Orca's main process killed during the agent's startup handshake), then Orca is relaunched.
A profile the base left stuck, opened with this build: Retry starts the agent and it replies.

Testing
New tests (each written first, then shown to fail two ways: against the base's production code, and with this PR's core line deleted):
recovering)unverifiableand is never refused.ownership_unknown)manual-recoveryfor reservations with no ownerthread/resumeonSpawnedwiringinitializehandshake; failing to record it reaps the child.conflictedwith no process,manual-recoveryreservationmanual-recoveryloads asrecovering; released at startup or in recovery; the chat starts.manual-recoveryfor reservations with no owner; delete the unproven releaseconflictedterminal owner an older build left, still running or not verifiableconflictedowner the probe could not verifyinterruptedat the exit time, orunverifiable), and no published status says working.interruptedcase goes red)unverifiable, neverexited.exitedsucceeded; a further retry replays that answer and starts nothing.agent_session_ownership_unknownpending,agent_session_operation_expiredexpired)conflictedis refused as before.Existing tests. Tests that pinned the latches were rewritten to the new behaviour. The settlement-latch test file and the retry module's tests were deleted along with the code.
Runs:
vitestoversrc/main/native-chat,src/main/runtime,src/shared/agent-session*,src/main/codex,src/main/claudeandsrc/main/observability: 13,874 passed.claude-structured-real-clicases, which need the real CLI (known locally);structured-agent-session-refusal-retry,automation-change-publication,orchestration-all-start-versions-migration), which all pass when re-run alone.pnpm tc:nodeandpnpm tc:webare clean.oxlinton the changed files is clean,check:code-quality:changedpasses, andaudit:anti-slop,audit:code-quality:nativeandaudit:code-quality:type-awareexit 0.Not run locally:
Review
Mixed versions and persisted data:
settlementRetryRequired,settlementRetryIdandprocesslessAtfields are ignored, and dropped when the store loads.conflictedstays a valid value andmanual-recoveryloads asrecovering, so these records still load, and startup re-derives them from the recorded owner. Older builds acceptrecovering, so a record written back after that mapping still loads after a downgrade.Overlaps:
claude-structured-session-state.tsloses one optional event field, which overlaps fix(claude): let the lease release close the adapter's session so an evicted chat resumes #22641. Whichever lands second rebases.Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
indeterminate, so it is now released rather than waited on forever. Its lease no longer reads asexited.unverifiable. The client treats that as "may have started" and keeps retrying the same operation id, which replays the failure, so the chat shows "Chat connection could not be confirmed." until the row expires about 24 hours later; the retry then continues as above. On the base the same chat stayed in manual recovery. Ways out today: close the tab (this also discards the unsent first message), open a new chat (until Orca restarts, New tab may rejoin the stuck launch instead, also on the base), or wait out the ~24 hours. While its row is kept, a failed operation only replays its failure under its old id; only once the row has aged out does a retry of that id, like any expired one, continue when nothing holds the lease. This is removed by the planned split of creating a chat from starting its agent: once a create no longer starts the agent it cannot fail on a start, and a failed start becomes a rejected message with an error row that the next send retries under a new operation.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)Author X handle: @BrennanKB5