Repository navigation
feat(chat): add structured session rewind backend - #19235
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review. 📝 WalkthroughWalkthroughThe change adds structured rewind support for Claude and Codex sessions. It defines shared rewind records, reasons, results, adapter methods, and RPC validation. Claude resumes and proves transcript leaves. Codex validates paginated history and performs native reverts. The session host persists rewind phases, recovers interrupted operations, restores journal items, reports blocked states, and supports replay. Tests cover provider flows, refusal handling, recovery, fencing, limits, and journal integrity. Merge Risk: 🟡 Moderate · up to Claude rewind replay can return a generic refusal instead of the original failure reason after acquisition fails, reducing reliable recovery feedback. The changed file also has a lint warning; both issues should be corrected before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description clearly explains the backend rewind implementation, rationale, scope, and validation. However, it omits several required template sections, including the mandatory Linked Issue entry, Testing checklist, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist. It also does not provide the required exact N/A visual-proof statement. Resolution Add all missing template sections. Include a valid issue reference under Linked Issue, complete the Testing and Checklist items, state AI usage or leave the section blank only when permitted, complete the Agent skill upstream boundary section, add Notes, and write exactly
✨ 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.
Important
A rewind that fails by throwing (provider/store error) — rather than returning an { ok: false } refusal — leaves the durable rewind record stuck at phase: 'prepared' with no recovery path, permanently blocking sends, rewinds, and conversation commands on that session.
Reviewed changes
Backend-only agentSession.rewind for structured sessions, spanning the shared wire/record types, the provider adapters (Claude + Codex), the host mutation/attach/recovery flow, and the RPC method.
- Claude rewind — resumes the same session at the last retained main-chain UUID via
resumeSessionAt+resumeDropsTurn, proves the target is an ancestor of the prior cursor before publication, and consumes the explicit ancestor-proof authorization on its first attempt (ClaudeRewindAttempt). - Codex rewind — uses native
thread/revertplus boundedthread/turns/list/thread/items/listpagination through the existing journal translator, refusing legacy-history threads rather than migrating them. - Durable recovery — a
provider-succeededrecord lets a reopen finish epoch replacement (recoverStructuredRewind) without repeating the provider mutation;refused/outcome-unknowngate sends and surfacerewindBlockedReason. - Wire surface — additive
agentSession.rewindmethod (capability-gated),rewindReasonon refusals, andrewind/rewindBlockedReasonon the options/status summaries, plus a forward-compat body restorer for unknown journal roles/blocks.
⚠️ Interrupted rewind (prepared) has no recovery path
prepared is written durably before the provider mutation, but nothing clears it unless the mutation returns a clean { ok: false } refusal (→ refused) or acknowledges success (→ provider-succeeded). Any rewind that instead throws — a store-write failure, a provider error surfaced as an exception, or a process crash between the prepared write and the provider-succeeded checkpoint — leaves the record at prepared with no way out:
recoverStructuredRewindonly advancesprovider-succeeded; reattach ignoresprepared(structured-agent-session-attach-orchestration.ts).- A rewind retry is refused with
outcome-unknownwhileprepared(structured-agent-session-rewind.ts). sendandconversationCommand(clear/compact) are also blocked whileprepared(structured-agent-session-host-mutations.ts,structured-conversation-command-admission.ts).
The result is a permanently blocked session — no send, no rewind, no clear — and closing/reopening doesn't help because the record persists. The Claude path is the most exposed: replaceClaudeRewindOwner reattaches a full provider process (spawn + init + proof) before the provider-succeeded write, leaving a wide window where a crash lands in this dead-end; the Codex path narrows it via onReverted but still has the pre-revert window. recoverInterruptedCompaction is the in-repo precedent for exactly this crash class (detect a prepared command whose fence has advanced → recover), which rewind does not replicate.
Technical details
# Interrupted rewind (`prepared`) has no recovery path
## Affected sites
- `src/main/native-chat/agent-session-wire/structured-agent-session-rewind.ts` — `persistRewindRecord(prepared)` runs before the provider mutation; a throw from `ctx.adapter.rewind!` / `replaceClaudeRewindOwner` skips the `refused` / `provider-succeeded` flips.
- `src/main/native-chat/agent-session-wire/structured-rewind-recovery.ts` — `recoverStructuredRewind` early-returns unless `phase === 'provider-succeeded'`.
- `src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts` — reattach gates recovery on `phase === 'provider-succeeded'` only.
- `src/main/native-chat/agent-session-wire/structured-rewind-claude-owner.ts` — the reattach (the provider mutation) completes before any `provider-succeeded` write; no `onReverted`-style checkpoint.
## Required outcome
- A rewind record left at `prepared` after a crash/failure must be recoverable: on reattach, an interrupted `prepared` rewind should be settled to a terminal state so sends and a rewind retry unblock — mirroring `recoverInterruptedCompaction`'s fence-advance detection (store the fence in the rewind record, or move the `provider-succeeded` checkpoint into `replaceClaudeRewindOwner` right after its `attach` succeeds).
## Open questions for the human
- Is `prepared` meant to be recovered on reattach, or was the expectation that only a clean refusal/success is durable? If the latter, the `prepared` write should be deferred or made idempotently recoverable rather than leaving a dead-end state.ℹ️ Nitpicks
resumeDropsTurnis only asserted at the internallaunch.optionslevel inclaude-structured-rewind.test.ts; the repo's SDK drift alarm (claude-agent-sdk-contract-pins.test.ts, which pins--resume/--resume-session-atargv) doesn't pin the new--resume-drops-turnmapping, so a future SDK bump that reshapes the option wouldn't be caught.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Status: ready for reviewBackend only — the user-facing affordance is a separate PR. Plan reviewReviewed before any code was written. Verdict APPROVE WITH AMENDMENTS; all five applied. Two policy calls were accepted with conditions:
Code review loop — four real recovery defects found and fixedThis is where the value was. Same-model subagent review plus
Both readiness runs ended clean for PR scope. 520 tests across 70 suites pass on the merged tree. Verification
Interface contract for the dependent UI PRNine refusal reason codes, confirmed stable and final across all four fixes:
Scope notes
Process deviations, stated plainly
|
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 18db2a1e-2f02-4bcb-a591-21047cbc0bb1
📒 Files selected for processing (44)
src/main/claude/claude-structured-launch-resolution.tssrc/main/claude/claude-structured-rewind.test.tssrc/main/claude/claude-structured-rewind.tssrc/main/claude/claude-structured-session-acquisition.tssrc/main/claude/claude-structured-session-adapter.tssrc/main/claude/claude-structured-session-state.tssrc/main/claude/claude-transcript-branch-proof.tssrc/main/claude/claude-transcript-rewind-proof.test.tssrc/main/codex/codex-structured-rewind.test.tssrc/main/codex/codex-structured-rewind.tssrc/main/codex/codex-structured-session-acquire.tssrc/main/codex/codex-structured-session-adapter.tssrc/main/codex/codex-structured-session-state.tssrc/main/codex/codex-structured-thread-open.tssrc/main/native-chat/agent-session-wire/structured-agent-session-adapter-router.tssrc/main/native-chat/agent-session-wire/structured-agent-session-adapter.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-failure.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host.tssrc/main/native-chat/agent-session-wire/structured-agent-session-operation-settlement.tssrc/main/native-chat/agent-session-wire/structured-agent-session-replay-outcome.tssrc/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-rewind.tssrc/main/native-chat/agent-session-wire/structured-agent-session-status-feed.tssrc/main/native-chat/agent-session-wire/structured-conversation-command-admission.tssrc/main/native-chat/agent-session-wire/structured-rewind-claude-owner.tssrc/main/native-chat/agent-session-wire/structured-rewind-claude-proof.test.tssrc/main/native-chat/agent-session-wire/structured-rewind-claude-proof.tssrc/main/native-chat/agent-session-wire/structured-rewind-journal-body.test.tssrc/main/native-chat/agent-session-wire/structured-rewind-journal-body.tssrc/main/native-chat/agent-session-wire/structured-rewind-recovery.tssrc/main/native-chat/agent-session-wire/structured-rewind-refusal.tssrc/main/runtime/rpc/methods/structured-agent-session-gate-classification.test-fixture.tssrc/main/runtime/rpc/methods/structured-agent-session-rpc.test-fixture.tssrc/main/runtime/rpc/methods/structured-agent-session-schemas.tssrc/main/runtime/rpc/methods/structured-agent-session.test.tssrc/main/runtime/rpc/methods/structured-agent-session.tssrc/main/runtime/structured-claude-runtime-adapter.tssrc/shared/agent-session-operation-ledger.tssrc/shared/agent-session-record.tssrc/shared/agent-session-rewind.tssrc/shared/agent-session-wire.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| if (error instanceof AgentSessionRewindRefusal) { | ||
| return rewindRefusal(error.rewindReason) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Persist rewindReason in the failed acquisition outcome.
When adapter.acquire() throws AgentSessionRewindRefusal, the catch block awaits settleFailedAcquisition before returning rewindRefusal(error.rewindReason). The persisted AgentSessionAcquisitionRefusal outcome omits rewindReason, so replay returns a generic refusal. Persist error.rewindReason for this refusal before settling the operation.
| if (record.rewind?.phase === 'prepared' || record.rewind?.phase === 'provider-succeeded') { | ||
| return 'agent_session_rewind:outcome-unknown' | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Find all callers of conversationCommandBlocked and how they use the returned string.
set -euo pipefail
rg -n -C8 'conversationCommandBlocked' --type=ts
# Check whether the returned value reaches a user-facing message field.
rg -n -C4 'agent_session_rewind:outcome-unknown' --type=tsRepository: stablyai/orca
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- target file ---'
cat -n src/main/native-chat/agent-session-wire/structured-conversation-command-admission.ts
printf '%s\n' '--- direct references ---'
rg -n -C8 'conversationCommandBlocked|agent_session_rewind:outcome-unknown' srcRepository: stablyai/orca
Length of output: 13610
🤖 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: 42749
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- conversation command caller ---'
cat -n src/main/native-chat/agent-session-wire/structured-conversation-command.ts | sed -n '70,105p'
printf '%s\n' '--- refusal response contract and consumers ---'
rg -n -C5 'agent_session_operation_invalid|refusal\.message|refusal:.*message|type AgentSessionMutationResult' src/main src/shared src/rendererRepository: stablyai/orca
Length of output: 50369
Return a user-facing sentence for the rewind outcome-unknown branch.
structured-conversation-command.ts assigns the return value directly to refusal.message. The agent_session_rewind:outcome-unknown value can therefore reach the user instead of a sentence.
| if ( | ||
| result.refusal.rewindReason === 'provider-refused' || | ||
| result.refusal.rewindReason === 'proof-mismatch' | ||
| ) { | ||
| const recovered = await attach(undefined, 'resume') | ||
| if (!recovered.ok) { | ||
| return rewindRefusal('outcome-unknown') | ||
| } | ||
| return rewindRefusal(result.refusal.rewindReason) | ||
| } | ||
| return rewindRefusal(result.refusal.rewindReason ?? 'outcome-unknown') |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Check whether a session with hasProviderChild=false re-acquires a provider child on the next send/attach.
set -euo pipefail
fd -t f 'structured-agent-session-.*\.ts' src/main/native-chat/agent-session-wire \
| xargs rg -n -C6 'hasProviderChild'
# Inspect the refusal reasons attach can surface for a rewind intent.
rg -n -C4 'rewindReason' src/main/native-chat/agent-session-wire src/main/claudeRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- rewind owner ---'
sed -n '1,130p' src/main/native-chat/agent-session-wire/structured-rewind-claude-owner.ts
printf '%s\n' '--- attach orchestration ---'
sed -n '1,180p' src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
printf '%s\n' '--- session entry points ---'
rg -n -C5 'resumeStructured|attachStructured|send|hasProviderChild|acquisitionGeneration' \
src/main/native-chat/agent-session-wire/structured-agent-session-*.ts \
-g '!*.test.ts' | head -n 400
printf '%s\n' '--- rewind reason definitions and unsupported path ---'
rg -n -C8 'rewindReason|unsupported|applyLaunch|readTranscriptLeaf' \
src/main/native-chat/agent-session-wire src/main/claude \
-g '!*.test.ts' | head -n 400Repository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- host mutation entry points ---'
rg -l 'send\(' src/main/native-chat/agent-session-wire -g '*.ts' -g '!*.test.ts' |
while read -r f; do
echo "### $f"
rg -n -C12 'send\(|attach\(|perform.*Mutation|mutation' "$f" | head -n 220
done
printf '%s\n' '--- admission and execution flow ---'
sed -n '1,240p' src/main/native-chat/agent-session-wire/structured-agent-session-mutation-plans.ts
fd -t f 'structured-agent-session-.*(mutation|host|attach|flow).*\.ts' src/main/native-chat/agent-session-wireRepository: stablyai/orca
Length of output: 18112
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- conversation command controller ---'
sed -n '1,260p' src/main/native-chat/agent-session-wire/structured-conversation-command-controller.ts
printf '%s\n' '--- mutation admission ---'
sed -n '1,320p' src/main/native-chat/agent-session-wire/structured-agent-session-mutation-admission.ts
printf '%s\n' '--- host mutations ---'
sed -n '1,260p' src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.tsRepository: stablyai/orca
Length of output: 16703
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- attach flow ---'
sed -n '1,300p' src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
printf '%s\n' '--- Claude rewind implementation and refusal types ---'
rg -n -C12 'class ClaudeRewindAttempt|applyLaunch|readTranscriptLeaf|rewindReason|unsupported' \
src/main/native-chat/agent-session-wire src/main/claude \
-g '!*.test.ts' | head -n 500
printf '%s\n' '--- send execution ---'
sed -n '60,180p' src/main/native-chat/agent-session-wire/structured-agent-session-turns.tsRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- post-acquisition failure handling ---'
sed -n '1,220p' src/main/native-chat/agent-session-wire/structured-agent-session-attach-failure.ts
printf '%s\n' '--- send execution and adapter contract ---'
sed -n '1,145p' src/main/native-chat/agent-session-wire/structured-agent-session-turns.ts
sed -n '1,140p' src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts
printf '%s\n' '--- dispatch implementations ---'
rg -n -C10 'dispatch\s*[:=]|async dispatch|dispatch\(' \
src/main/claude src/main/native-chat/agent-session-wire \
-g '!*.test.ts' | head -n 350
printf '%s\n' '--- Claude rewind launch binding ---'
rg -n -C10 'applyLaunch\(' src/main/claude src/main/native-chat/agent-session-wire -g '!*.test.ts'Repository: stablyai/orca
Length of output: 25457
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- Claude adapter session lookup ---'
rg -n -C8 'private session|session\(' src/main/claude/claude-structured-session-adapter.ts | head -n 120
printf '%s\n' '--- acquisition cleanup behavior ---'
rg -n -C18 'rethrowAfterAgentSessionAcquisitionCleanup' \
src/main/native-chat/agent-session-wire/structured-agent-session-adapter.tsRepository: stablyai/orca
Length of output: 6097
Re-acquire the provider child after an unsupported rewind refusal. applyLaunch throws this refusal after the child closes, but this branch skips attach(undefined, 'resume'). The next send does not attach; Claude dispatch finds no live session, records an unknown submission, and does not send the message. Extend recovery to this refusal before returning.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior pullfrog review (51a0df1) closes the interrupted-rewind dead-end that review flagged, plus a Merge origin/main commit.
- Made interrupted rewinds recoverable — Claude now checkpoints
provider-succeededatomically with exact-target proof during acquisition (claudeRewindAcquisitionProofs+ClaudeRewindAttempt.onProved), and restores an interrupted unproven rewind's original cursor via ordinary branch proof (rewindRecovery→proveClaudeRewindRecovery); Codex persistsproviderAppliedright after the revert ack and re-verifies through a read-onlyrecoverCodexRewind. - Captured the complete provider prefix before mutation — Codex
onPreparedpersists the provider-derived retained set ahead ofthread/revert, andrecoverStructuredRewindnow advancespreparedas well asprovider-succeeded, settling a crash-after-journal-commit epoch idempotently. - Resolved accepted user submissions to provider targets — the rewind mutation maps accepted-submission
itemIds to provider identities (providerItemId), and the record schema gainedproviderItemId/hydrationVerified/providerApplied.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
ELI5 — what this PR actually doesThe problem in one sentence. A chat with an agent only moves forward. If it goes down a wrong path three messages ago, there is no way to take that back — you either live with the bad context poisoning everything after it, or you throw the whole session away and start over. What this adds. The machinery to rewind a session back to an earlier message: the agent forgets everything after that point, on both its side and ours, and you can carry on from there as if the detour never happened. Important: this PR ships no button. It is the engine only. The affordance you click is a separate PR that builds on this one. So the honest user-facing before/after today is nothing visible changes. The before/after below is what the pair of PRs delivers once the UI lands. Before → After (once the UI PR lands)
Why the diff is large for "step back a few messages"Because it is a destructive, irreversible operation on durable history, and it has to be safe across two different agent providers that behave differently, plus crashes. Most of this PR is the safety, not the rewind:
What it deliberately does not do
|
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior pullfrog review (60f9c02) is a single Merge origin/main commit (19283675b0) resolving the conflicts between main's new acquisition/support plumbing and the rewind backend.
- Merged
main'sacquireOwnerextraction without dropping the rewind hook —acquireOwnermoved fromstructured-agent-session-attach-flow.tsintostructured-agent-session-acquisition.ts, and the merge correctly preservedclaudeRewindAcquisitionProofsin theadapter.acquirecall, therewindfield threaded throughperformAttach, and theAgentSessionRewindRefusalbranch in the catch. - Adopted
main'ssupportsCreategate + support helpers — the router and host now exposesupportsCreate(backed byadapterSupportsCreate/adapterSupportsCreateIfDeclared/adapterSupportsRecordfromstructured-agent-session-provider-support.ts), with a re-check after reservation plus a newsettleUnsupportedReservationpath that avoids double-settling via theunsupportedReservationSettlementAttemptedflag. - Updated rewind test fixtures — the rewind tests now declare
supportsCreateon their adapter mocks; theagentSession.rewindRPC path still bypasses the create gate and callshost.rewinddirectly.
Verified the merge preserves the provider mutation/attach/recovery flow and ran the rewind suites (structured-agent-session-rewind, structured-rewind-claude-proof, claude-structured-rewind, codex-structured-rewind) — 45 tests pass.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts (1)
7-7: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMerge the duplicate adapter imports.
import(no-duplicates)reports another import from./structured-agent-session-adapterin this file. Merge that import with the newAgentSessionRewindRefusal,StructuredAgentSessionAcquireInput, andStructuredAgentSessionAdapterspecifiers.Static analysis reports
import(no-duplicates)for this import.Source: Linters/SAST tools
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: fdb93d8c-1a0b-4ac6-9999-a8aa81c1b2ae
📒 Files selected for processing (6)
src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.tssrc/renderer/src/runtime/structured-agent-session-client.test.tssrc/renderer/src/runtime/structured-agent-session-client.tssrc/shared/protocol-version.tstests/e2e/cross-version-wire/cross-version-agent-session-wire.unit.test.tstests/e2e/cross-version-wire/structured-agent-session-host-fixture.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior pullfrog review (19283675b0) is a single commit (90e030c8, "negotiate rewind runtime capability") that closes the last wire-compatibility gap for agentSession.rewind.
- Negotiated the rewind capability on the renderer client —
callStructuredAgentSessionnow refusesagentSession.rewindagainst an environment target that does not advertiseagent-session.rewind.v1, throwing a clear "Rewinding requires a newer Orca server" message before any RPC; local builds and every other method dispatch unchanged. - Advertised the capability statically on hosts — added
AGENT_SESSION_REWIND_RUNTIME_CAPABILITYtoRUNTIME_CAPABILITIES, mirroring theagent-session.status-feed.v1pattern, since the RPC is registered unconditionally and per-session support is a separate refusal. - Extended the cross-version wire suite — added rewind to the declared surface manifest and pinned the capability-equivalent-registered-method invariant for both current and baseline builds.
- Extracted a shared host stub — moved
structuredHostStubinto a parameterizedstructured-agent-session-host-fixture.tskeyed by session/workspace so the current-tree suite and the release-shaped checkout install an identical rewind-capable host.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Merging main crossed the 300-line cap on `codex-structured-session-adapter.ts`: the rewind backend (#19235) and this branch's close-time strip clear both landed in it. The four close paths move verbatim into `codex-structured-session-teardown.ts`, where they funnel through one `settled` helper instead of repeating the notification-retry and background-task cleanup at each call site. No ratchet bump. Also normalize a background task's description once at receipt rather than on every projection; the roster is re-projected on each observed frame.
…19346) * feat(native-chat): report Codex background tasks in the chat strip The background-tasks strip works for Claude only; a structured Codex session shows nothing in it. Feed it from the Codex app-server stream. The strip stands for work that OUTLIVED a turn, which is what the monitoring header, Claude's foreground suppression, and the conversation command gate all already assume. Codex has no `is_backgrounded` flag, so that fact is derived from the turn boundary: a `subAgentActivity` child or a primary-thread `commandExecution` becomes visible once the turn it belongs to completes and it is still unsettled. `turn/completed` only reveals a task here, never settles one — measured on `codex app-server` 0.153.4, a spawn_agent child reported `completed` 95.8s after its parent turn ended. Only a child's own activity kind settles it. Codex exposes no honest stop: `turn/interrupt` on a child ends its turn without emitting a terminal activity item and leaves its shell running. So the state carries a new optional `supportsStopAll: false`, the strip hides a control that could not act, and the blocked-command message asks the user to wait rather than to press a button that does not exist. * refactor(codex): move session teardown out of the structured adapter Merging main crossed the 300-line cap on `codex-structured-session-adapter.ts`: the rewind backend (#19235) and this branch's close-time strip clear both landed in it. The four close paths move verbatim into `codex-structured-session-teardown.ts`, where they funnel through one `settled` helper instead of repeating the notification-retry and background-task cleanup at each call site. No ratchet bump. Also normalize a background task's description once at receipt rather than on every projection; the roster is re-projected on each observed frame. * fix(codex): drop the shell row the journal already settles A `commandExecution` still `inProgress` when its turn ends was reported as a `command` task. But `settleCodexJournalTurn` writes exactly those items to the journal as `state: 'failed'` on `turn/completed` and forgets them, so the strip row would have claimed a shell was still running at the same instant Orca recorded that it was not — two surfaces contradicting each other about the same process. A subagent is the opposite case and stays: the roster pointedly does not sweep at a turn boundary, because children measurably outlive it. That leaves the producer making exactly one claim — these spawn_agent children are still live after their turn — which the durable roster row corroborates. * fix(native-chat): track Codex background execution lifetimes * fix(native-chat): keep running tool groups from claiming completion * Fix runtime catalog and capability expectation * fix(codex): keep a child's name on the command row that outlives it A child agent's commands stay hidden behind its agent row while the child works. Once the child's turn settles with a command still running, that command surfaces as its own row labelled from the raw command string, so 'long_probe' became "/bin/zsh -lc 'ping -c 300 127.0.0.1 > /dev/null'" at the moment that row was the only remaining signal for the work. Qualify a child's command row with the child's label. Resolved on read, so a label registered after the command still lands, and bounded by the existing description cap so admission accounting stays valid. Primary- thread commands are left unqualified: they have no child to name. --------- Co-authored-by: Merge Sim <sim@local>

What this does, in plain terms
A chat with an agent only moves forward. If it went down a wrong path three messages ago, you can't take that back — you either keep arguing with a session whose context is already poisoned, or you throw it away and start over.
This adds the ability to rewind a session back to an earlier message: the agent forgets everything after that point, on its side and ours, and you carry on from there as if the detour never happened.
This PR ships no button. It is the engine only; the affordance that calls it is a separate PR. So nothing changes visually yet.
Before → After (once the UI PR lands)
It never touches your files. Rewinding the conversation does not revert code on disk. Only chat history moves.
Why a "step back a few messages" needs 1,300 lines
Because it is a destructive, irreversible operation on durable history, across two providers that behave differently, that must stay correct across crashes. Most of this PR is the safety, not the rewind. The four things that would have gone wrong:
history-limitand leaves the session usable. Please don't later "simplify" this preflight as redundant with the item gate; the interaction is invisible if you read the two caps separately.Old sessions from an older provider version can't do this at all, so they're refused cleanly and the UI can grey the option out rather than let you click it and fail.
Interface contract for the UI PR
Nine refusal reason codes, final:
unsupported,history-not-paginated,busy,stale-epoch,invalid-target,history-limit,provider-refused,proof-mismatch,outcome-unknown.outcome-unknownmeans the revert may or may not have completed and sending is blocked until it resolves. It must never be surfaced as a clean failure.Technical detail
Adds backend-only
agentSession.rewindusing the existing mutation envelope,itemId, and fingerprintedexpectedEpoch. The selected item is the first discarded: Codex discards its whole turn, while Claude resumes the same session at the preceding retained UUID. Accepted user-message aliases resolve to provider identities. Provider session IDs stay unchanged and workspace files are never reverted.Rewind serializes with sends and refuses active, unresolved, concurrent, or stale work. Journal epochs commit only after exact Claude target proof or complete Codex hydration matching the preflight retained item identities. Provider acknowledgment alone cannot commit an epoch. Recovery retries bounded read-only reconciliation without repeating an ambiguous revert, and a crash after journal publication settles the existing epoch.
Codex performs bounded provider preflight before mutation, then verifies both paginated history indexes again afterward. This gate is necessary even with the host item limit: 600 tiny retained turns plus 600 item rows pass the host's 10,000-item gate but exceed the combined 1,024-row hydration budget. Discovering that only after revert would permanently block the session; it now refuses up front with
history-limit. Provider reads are capped at 100 pages per index and 2 MiB combined, and the complete provider-derived prefix is saved before mutation so recovery also covers older turns missing from the local journal. Legacy-history threads remain unsupported.Claude consumes explicit ancestor authorization on its first proof attempt, including failures. Exact proof checkpoints the resumable provider head and success record atomically before later acquisition work. An interrupted unproven attempt restores the original cursor with ordinary exact proof, without reusing ancestor authorization, and permits sending again.
Durable refusal reasons stay open bounded strings; RPC emission retains these nine codes:
unsupported,history-not-paginated,busy,stale-epoch,invalid-target,history-limit,provider-refused,proof-mismatch,outcome-unknown. Unknown roles preserve visible content with a system-role fallback. No renderer, locale, journal-kind, or stream-opcode change.Validation: same-model safety review is clean and opening/ending readiness findings are resolved. On the merged branch, 520 tests passed across 70 suites; one new main adoption-replay test fails identically at line 188 on a clean detached
origin/maincheckout (314506003a) and was left unchanged. Changed-file lint and pre-commit checks passed. Merge60f9c021bahas two verified parents, and all resolution files match the committed versions. Central typecheck and live Electron/provider QA remain coordinator-owned.