Skip to content

feat(chat): add structured session rewind backend - #19235

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/nc-rewind-backend
Sep 7, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/nc-rewind-backend

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1392 $\color{#cf222e}{\Huge{\mathbf{−}}}$​47 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1345
Prod 40 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1428 $\color{#cf222e}{\Huge{\mathbf{−}}}$​94 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1334

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)

Before After
Agent misunderstood 3 messages back Keep arguing, or abandon the session and lose all context Revert to that message, re-ask properly
A bad tool result derailed the run It stays in context forever, colouring every later answer Truncate it away, continue clean
Recovering from a wrong turn Hand-copy what you want into a fresh chat The session itself steps back

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:

  1. "The provider said OK" is not "we have the history." Codex's revert reply deliberately returns an empty list plus a bookmark. Committing on the acknowledgment alone wrote a journal claiming to be the truncated conversation while holding only part of it. Acknowledgment and verified hydration are now distinct.
  2. A half-finished rewind could permanently block sending. That is not a safe failure — it is a broken session that looks recoverable. An interrupted attempt now restores the original cursor and permits sending again.
  3. Some histories are too big to rewind — discoverable only after the destructive step. 600 tiny turns pass the host's 10,000-item gate but blow the 1,024-row hydration budget. It now refuses up front with history-limit and 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.
  4. A just-sent message couldn't be resolved to its provider target, because accepted user messages kept Orca-side ids. Aliases now resolve to provider identities.

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-unknown means 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.rewind using the existing mutation envelope, itemId, and fingerprinted expectedEpoch. 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/main checkout (314506003a) and was left unchanged. Changed-file lint and pre-commit checks passed. Merge 60f9c021ba has two verified parents, and all resolution files match the committed versions. Central typecheck and live Electron/provider QA remain coordinator-owned.

@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 07e89244-7de9-4854-b2b9-d9cdb64ce119

📥 Commits

Reviewing files that changed from the base of the PR and between 90e030c and ef08302.

📒 Files selected for processing (1)
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts

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


📝 Walkthrough

Walkthrough

The 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 ef083

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.92% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 48 functions across 50 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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, … 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 secti…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely identifies the main change: adding the structured session rewind backend.
Full details: Description check

Explanation

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 N/A with a brief reason under Visual Proof because this PR has no UI change.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/revert plus bounded thread/turns/list / thread/items/list pagination through the existing journal translator, refusing legacy-history threads rather than migrating them.
  • Durable recovery — a provider-succeeded record lets a reopen finish epoch replacement (recoverStructuredRewind) without repeating the provider mutation; refused / outcome-unknown gate sends and surface rewindBlockedReason.
  • Wire surface — additive agentSession.rewind method (capability-gated), rewindReason on refusals, and rewind / rewindBlockedReason on 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:

  • recoverStructuredRewind only advances provider-succeeded; reattach ignores prepared (structured-agent-session-attach-orchestration.ts).
  • A rewind retry is refused with outcome-unknown while prepared (structured-agent-session-rewind.ts).
  • send and conversationCommand (clear/compact) are also blocked while prepared (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

  • resumeDropsTurn is only asserted at the internal launch.options level in claude-structured-rewind.test.ts; the repo's SDK drift alarm (claude-agent-sdk-contract-pins.test.ts, which pins --resume / --resume-session-at argv) doesn't pin the new --resume-drops-turn mapping, so a future SDK bump that reshapes the option wouldn't be caught.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: ready for review

Backend only — the user-facing affordance is a separate PR.

Plan review

Reviewed before any code was written. Verdict APPROVE WITH AMENDMENTS; all five applied. Two policy calls were accepted with conditions:

  • Codex legacy-history threads are refused, not migrated. Migrating would silently rewrite a thread's stored history mode as a side effect of a destructive verb. The condition was that refusal be detectable before the user acts, so an unsupported marker is exposed through the session capability surface and the UI can disable rather than fail late.
  • Claude multi-turn rewind uses an explicit cursor resume rather than iterating resumeDropsTurn, which validates only one dropped prompt. Iterating would multiply destructive steps and partial-failure states. What makes it safe is ordering: the journal commits only after the proof observes the leaf equals the requested target.

Code review loop — four real recovery defects found and fixed

This is where the value was. Same-model subagent review plus readiness-checklist at both ends proved four defects, none of which tests or lint would have caught:

  1. Unverified hydration committed as a completed epoch. The provider's revert reply deliberately returns empty turns plus backwards cursors, so an acknowledgment proves acceptance, not possession of the retained history. Committing on that basis writes a journal claiming to be the truncated history while holding whatever subset arrived. Now: acknowledgment and verified hydration are distinguished, and a partial hydration never commits.
  2. Prepared interruptions permanently blocked sends. Not a safe failure — a destroyed session that looks recoverable. Now checkpointed, and an unproven attempt is restored through normal resume proof before unblocking, so the proof is re-earned rather than assumed.
  3. A limit discoverable only after the destructive step. Many small retained turns individually pass the per-item gate but exceed the provider's combined hydration limit — which only surfaced post-revert. Now a bounded preflight refuses up front (history-limit) and the original session stays usable. Worth preserving: this interaction is invisible if you read the caps individually, so please don't fold the preflight back into the item gate as "redundant".
  4. Accepted user messages retained Orca journal IDs, so rewind could not resolve their provider targets and could mismatch a Claude prefix. The host now resolves accepted submission aliases for both targets and retained prefixes, and persists the complete provider prefix before mutation so crash recovery works even when older provider turns were absent locally.

Both readiness runs ended clean for PR scope. 520 tests across 70 suites pass on the merged tree.

Verification

  • Central typecheck run by the coordinator: exit 0, zero errors, post-merge.
  • Main merged with a verified two-parent merge commit (a failing pre-commit hook destroys MERGE_HEAD and silently produces a single-parent commit, so this was checked explicitly).
  • One adoption-replay test fails on the merged tree. This was proven pre-existing on main: the unchanged test fails identically, at the same line and assertion, on a clean detached origin/main checkout. It was reproduced independently by two different lanes. No unrelated test was edited to go green.

Interface contract for the dependent UI PR

Nine refusal reason codes, confirmed stable and final across all four fixes:

unsupported, history-not-paginated, busy, stale-epoch, invalid-target, history-limit, provider-refused, proof-mismatch, outcome-unknown

outcome-unknown must be surfaced as genuine uncertainty — the revert may or may not have completed and sending is blocked until resolved — never as a clean failure.

Scope notes

  • Claude's dropped branch remains in the on-disk transcript by design; reverting files is out of scope.
  • No renderer changes, no forking, no new journal item kind.
  • Durable refusal reasons are open bounded strings so an older build can still parse its own recovery record after a rollback; the closed typed set is applied at the RPC boundary.

Process deviations, stated plainly

  • No Electron validation. This PR has no user-visible surface, so screenshots would show nothing. Visual evidence belongs to the UI PR that consumes this. Producing a screenshot here would be evidence-shaped rather than evidence.
  • Severity counsel unavailable. readiness-checklist's counsel step needs nested agent seats; nested worker depth is 1 in this install. Recorded as unavailable rather than reported as a verdict.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 18db2a1e-2f02-4bcb-a591-21047cbc0bb1

📥 Commits

Reviewing files that changed from the base of the PR and between 3145060 and 60f9c02.

📒 Files selected for processing (44)
  • src/main/claude/claude-structured-launch-resolution.ts
  • src/main/claude/claude-structured-rewind.test.ts
  • src/main/claude/claude-structured-rewind.ts
  • src/main/claude/claude-structured-session-acquisition.ts
  • src/main/claude/claude-structured-session-adapter.ts
  • src/main/claude/claude-structured-session-state.ts
  • src/main/claude/claude-transcript-branch-proof.ts
  • src/main/claude/claude-transcript-rewind-proof.test.ts
  • src/main/codex/codex-structured-rewind.test.ts
  • src/main/codex/codex-structured-rewind.ts
  • src/main/codex/codex-structured-session-acquire.ts
  • src/main/codex/codex-structured-session-adapter.ts
  • src/main/codex/codex-structured-session-state.ts
  • src/main/codex/codex-structured-thread-open.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-adapter-router.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-failure.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-operation-settlement.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-replay-outcome.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-rewind.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-status-feed.ts
  • src/main/native-chat/agent-session-wire/structured-conversation-command-admission.ts
  • src/main/native-chat/agent-session-wire/structured-rewind-claude-owner.ts
  • src/main/native-chat/agent-session-wire/structured-rewind-claude-proof.test.ts
  • src/main/native-chat/agent-session-wire/structured-rewind-claude-proof.ts
  • src/main/native-chat/agent-session-wire/structured-rewind-journal-body.test.ts
  • src/main/native-chat/agent-session-wire/structured-rewind-journal-body.ts
  • src/main/native-chat/agent-session-wire/structured-rewind-recovery.ts
  • src/main/native-chat/agent-session-wire/structured-rewind-refusal.ts
  • src/main/runtime/rpc/methods/structured-agent-session-gate-classification.test-fixture.ts
  • src/main/runtime/rpc/methods/structured-agent-session-rpc.test-fixture.ts
  • src/main/runtime/rpc/methods/structured-agent-session-schemas.ts
  • src/main/runtime/rpc/methods/structured-agent-session.test.ts
  • src/main/runtime/rpc/methods/structured-agent-session.ts
  • src/main/runtime/structured-claude-runtime-adapter.ts
  • src/shared/agent-session-operation-ledger.ts
  • src/shared/agent-session-record.ts
  • src/shared/agent-session-rewind.ts
  • src/shared/agent-session-wire.ts

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

Comment on lines +168 to +170
if (error instanceof AgentSessionRewindRefusal) {
return rewindRefusal(error.rewindReason)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment on lines +10 to +12
if (record.rewind?.phase === 'prepared' || record.rewind?.phase === 'provider-succeeded') {
return 'agent_session_rewind:outcome-unknown'
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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=ts

Repository: 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' src

Repository: 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/renderer

Repository: 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.

Comment on lines +66 to +76
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')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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/claude

Repository: 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 400

Repository: 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-wire

Repository: 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.ts

Repository: 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.ts

Repository: 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.ts

Repository: 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

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-succeeded atomically 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 persists providerApplied right after the revert ack and re-verifies through a read-only recoverCodexRewind.
  • Captured the complete provider prefix before mutation — Codex onPrepared persists the provider-derived retained set ahead of thread/revert, and recoverStructuredRewind now advances prepared as well as provider-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 gained providerItemId/hydrationVerified/providerApplied.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

ELI5 — what this PR actually does

The 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)

Before After
Agent misunderstands 3 messages back Keep arguing with it, or abandon the session and lose all context Revert to that message and re-ask it properly
A bad tool result derails the run It stays in context forever, influencing every later answer Truncate it away and continue clean
Recovering from a wrong turn Copy what you want to keep into a brand-new chat by hand The session itself steps back

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:

  • Both providers keep their own copy of the conversation. Rewinding means changing their history and ours and keeping the two agreeing — including when the app is killed halfway through.
  • One provider's revert reply deliberately hands back an empty list plus a bookmark, so "the provider said OK" is not the same as "we actually have the history". Treating those as the same wrote a journal that claimed to be the truncated conversation while holding only part of it. Fixed.
  • If we half-finish a rewind and get interrupted, the session must not end up permanently unable to send. That is not a safe failure — it is a broken session that looks recoverable. Fixed.
  • Some histories are too big to rewind safely, and that was only discoverable after the destructive step had already happened. Now it refuses up front and leaves your session untouched.
  • Old sessions from an older provider version can't do this at all, so they are refused cleanly and the UI can grey the option out rather than letting you click it and fail.

What it deliberately does not do

  • It does not touch your files. Rewinding the conversation does not revert code on disk. Only the chat history moves.
  • It does not delete the agent's own on-disk transcript; it stops using the part after your chosen point.
  • It does not fork. Forking a session from a point is a separate PR.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

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's acquireOwner extraction without dropping the rewind hook — acquireOwner moved from structured-agent-session-attach-flow.ts into structured-agent-session-acquisition.ts, and the merge correctly preserved claudeRewindAcquisitionProofs in the adapter.acquire call, the rewind field threaded through performAttach, and the AgentSessionRewindRefusal branch in the catch.
  • Adopted main's supportsCreate gate + support helpers — the router and host now expose supportsCreate (backed by adapterSupportsCreate / adapterSupportsCreateIfDeclared / adapterSupportsRecord from structured-agent-session-provider-support.ts), with a re-check after reservation plus a new settleUnsupportedReservation path that avoids double-settling via the unsupportedReservationSettlementAttempted flag.
  • Updated rewind test fixtures — the rewind tests now declare supportsCreate on their adapter mocks; the agentSession.rewind RPC path still bypasses the create gate and calls host.rewind directly.

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.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts (1)

7-7: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Merge the duplicate adapter imports.

import(no-duplicates) reports another import from ./structured-agent-session-adapter in this file. Merge that import with the new AgentSessionRewindRefusal, StructuredAgentSessionAcquireInput, and StructuredAgentSessionAdapter specifiers.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1928367 and 90e030c.

📒 Files selected for processing (6)
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
  • src/renderer/src/runtime/structured-agent-session-client.test.ts
  • src/renderer/src/runtime/structured-agent-session-client.ts
  • src/shared/protocol-version.ts
  • tests/e2e/cross-version-wire/cross-version-agent-session-wire.unit.test.ts
  • tests/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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

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 — callStructuredAgentSession now refuses agentSession.rewind against an environment target that does not advertise agent-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_CAPABILITY to RUNTIME_CAPABILITIES, mirroring the agent-session.status-feed.v1 pattern, 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 structuredHostStub into a parameterized structured-agent-session-host-fixture.ts keyed by session/workspace so the current-tree suite and the release-shaped checkout install an identical rewind-capable host.

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

@brennanb2025
brennanb2025 merged commit ce4a3a4 into main Sep 7, 2026
27 checks passed
brennanb2025 pushed a commit that referenced this pull request Sep 7, 2026
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.
brennanb2025 added a commit that referenced this pull request Sep 9, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant