Skip to content

fix(native-chat): an unfinished tool call too big for one cleanup write no longer breaks a chat for good - #26576

Closed
brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/chat-start-turn-cleanup-best-effort
Closed

brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/chat-start-turn-cleanup-best-effort

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

What you saw: a chat whose agent quit in the middle of a step could become stuck for good. On reopening, it showed "Working for 3m 23s" above "Orca on Local Mac stopped unexpectedly while this response was in progress." and kept counting. Sometimes the old approval card ("Allow the tool?") took the composer's place, so there was nowhere to type. Otherwise, every message failed with "Your message was not sent." and "OMP couldn't restart. Send your message to try again.", and retrying never helped. Restarting Orca didn't help either.

Why: when an agent quits mid-step, Orca later marks what it left unfinished as interrupted. It saves those marks in groups, and a group can hold at most 1.5 MB. If one unfinished item is bigger than that (for example a tool call with a huge input), the marks can never be saved, and the chat stays half-cleaned forever.

Now: a too-big item is saved on its own, the way it was first saved, so the cleanup always finishes. The same chat reopens with the old step shown as "Edited 1 file · 1 interrupted", the approval as "Cancelled", the composer available, and the next message goes straight to the agent.

This is a defensive fix for a rare case. No agent produces an item that size in normal use today: a Claude tool input is limited by its 128k-token output cap to roughly 0.4–0.7 MB. Reaching 1.5 MB would take unusual content or a higher future cap. If it does happen, though, main never recovers, which is why it is worth closing.

What Changed

Before: when an agent stopped mid-turn (Orca restarted, the agent crashed or exited), Orca rewrote what it had left running: the turn, open tool calls, pending approvals and questions. These rewrites go into journal "lifecycle batch" rows, and each row is capped at 1.5 MB. A single leftover item over the cap could not fit any row, so this cleanup failed on every attempt, in each of the three places it runs:

  • Starting or resuming the agent: the start failed, and failed again on every retry.
  • Reopening the chat: the dead turn stayed "working". New messages queued behind it and never sent, and leftover approval cards held the queue.
  • After the agent exited: the exit cleanup gave up.

After: all three cleanups go through one shared writer (appendSettlementMutations in structured-agent-session-dead-generation-settlement.ts). It splits the rewrites into batch rows as before. When one item is too large for any batch row, it is written as an ordinary item row instead, the same kind of row the live agent used to write that item in the first place. So the cleanup stores nothing larger than the journal already holds, and it always lands:

  • the chat starts or reopens,
  • the old turn shows as interrupted,
  • leftover approvals are cancelled,
  • the next message sends right away.

The size check is a small exported predicate in journal-lifecycle-batch-partition.ts. It reuses the partitioner's own size and version accounting, and the partitioning result is unchanged.

A genuine storage failure (disk full, the database locked by another process) still fails the start, as on main. In that case the start's own essential writes would fail too. Failing visibly, so the user can retry, is better than starting with the old turn stuck as "working" behind the new agent.

Why

The 1.5 MB cap exists because a batch row can hold up to 200 changes. Item rows have no such cap, and the oversized body was already written once as an item row while the agent was live. Writing its final state the same way closes the gap instead of adding a second guard.

Alternatives considered:

  • Shrink Claude tool inputs when they are recorded, like the other agents' inputs. Rejected: that would remove the file path and diff from Edit and Write cards over ~16 KB, which is common and visible. It also would not repair journals that already hold such an item.
  • Write a final state that leaves out the body. Rejected: it would add a new kind of saved journal entry for a rare case.
  • Let the start continue when the cleanup fails (an earlier version of this PR). Rejected: it left the dead turn reading "working", so messages queued forever with nothing to clear them. Making the cleanup unable to fail on its own fixes the root problem.

The common pattern also settles a dead session's unfinished work before new work starts, and fails closed when it cannot. This change keeps that ordering and that failure policy.

Linked Issue

Found by review of the native-chat "bookkeeping must never block the user" work (#26554). No separate issue.

Visual Proof

Before (base e3639ef), the chat reopened with an approval left over: stuck "Working", no composer
Q1-1-reopened.png

Before, with no approval left over: every send fails with "OMP couldn't restart"
Q1b-2-after-send.png

After (this PR), the same chat reopened: old step interrupted, approval cancelled, composer back
Q2-1-reopened.png

After: a new message is sent and answered
Q2-2-sent.png

After: still fine after quitting and relaunching Orca, and a third message is answered
Q3-3-third-send.png

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

On macOS, using real temporary SQLite journals with a scripted agent:

  • Start or resume after the agent died, with no new agent activity yet, a running turn, a running tool call over 1.5 MB and a pending approval. The start succeeds, the old turn is interrupted, the approval is cancelled, nothing holds the queue, and a "send now or queue if busy" message is sent rather than queued.
  • Reopening the same chat without starting the agent settles it the same way.
  • The exit cleanup with an oversized call succeeds, and re-running it adds nothing.
  • A storage failure during the cleanup still fails the start and releases the new agent.

The first three fail on main with journal_lifecycle_batch_byte_bound_exceeded (or with the old turn left running) and pass here. The related restart, reopen and exit suites pass too.

Also run: Node typecheck, and orca-ci-checks (lint, code quality, localization, guards).

Manual QA in the Electron app on macOS, using hidden test windows, isolated test profiles and an OpenAI-compatible stand-in model (no credentials). The setup:

  • Each chat got one real answered message.
  • In the profile's chat history I then planted what a dead agent leaves behind: a turn still running, and a running Write tool call with a ~1.6 MB input. Some runs also had a pending approval.

What happened:

  • Base: the chat was stuck as shown above. Every send failed, the agent received nothing, and the log showed journal_lifecycle_batch_byte_bound_exceeded.
  • This PR: the chat settled on reopening. Three messages were sent and answered, including one after a relaunch, and there was no duplicate stop notice.

Not exercised by hand:

  • SSH or remote hosts,
  • Claude or Codex chats (the cleanup is the same for every agent),
  • the start-time and exit-time cleanups on their own (in the app the reopen cleanup ran first; unit tests cover the other two).

AI Disclosure

Review

See the review summary comment.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • SSH, remote and folder workspaces: the journal lives on the host that runs the agent, so the cleanup runs there. Nothing depends on the platform or the workspace kind.
  • Wire compatibility: item rows marked as recovered already exist, so older builds and paired clients read them as before. Clients receive the item's new state exactly as they would from a batch, at no more than the size they already received while it was live.
  • Performance: one extra size check per single-change group, and only during these cleanups.

Follow-ups, not in this PR:

  • a Claude-specific input bound that keeps the Edit and Write diffs (journal size and reconnect cost),
  • optionally moving this fallback into the journal layer so every batch caller gets it by design (no other caller can reach an oversized item today).

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

brennanb2025 and others added 2 commits October 8, 2026 05:51
…esuming a chat's agent

Starting or resuming a chat's agent ran cleanup of turns left over from a
previous run with no error handling, so a failed cleanup write failed the
user's start. The cleanup is now best effort: its failure is logged and
retried on a later start, and the start proceeds.

Co-Authored-By: OpenAI Codex gpt-6.1-sol <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…te no longer stops a chat starting, reopening or settling after exit

When an agent dies mid-turn, Orca rewrites what it left running (its turn, open tool
calls, pending prompts) in batch rows capped at 1.5 MB. A single leftover item larger
than that, such as a tool call whose whole input was journaled, could never fit, so the
cleanup failed on every attempt: the start or resume failed, a reopened chat kept the
dead turn running (sends queued behind it forever), and the exit cleanup gave up.

The settle now writes such an item as an ordinary item revision, the same row kind the
live session wrote it with, so the cleanup always lands. The attach-time cleanup fails
the start again when it cannot be written (as before this branch), instead of leaving
the dead turn running behind a started agent.
@brennanb2025 brennanb2025 changed the title fix(native-chat): a failed turn cleanup no longer fails starting or resuming a chat's agent fix(native-chat): an unfinished tool call too big for one cleanup write no longer breaks a chat for good Oct 8, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review summary

The problem. When a chat's agent stops in the middle of a step, Orca marks whatever it left running as interrupted. That covers the turn, any open tool calls, and pending approvals. These marks are saved in groups capped at 1.5 MB. A single leftover item over that cap can never be saved, so the cleanup failed on every attempt and the chat stayed stuck for good:

  • It showed "Working…" forever.
  • A leftover approval card could take the composer's place.
  • Otherwise, every send failed with "OMP couldn't restart. Send your message to try again."

What changes for the user. That chat now reopens with the old step shown as interrupted and the approval shown as cancelled. The composer is back, and the next message goes straight to the agent. This is rare today, because no agent normally writes an item that large. A Claude tool input tops out around 0.4–0.7 MB under its output cap. But if it ever happens, main never recovers.

How the design changed during review. The first version of this PR let a chat's start continue when the cleanup failed. Review showed that this traded a visible, retryable failure for a silent one. The dead turn stayed "working", so new messages queued behind it forever, and nothing would ever clear it. The PR now fixes why the cleanup fails instead.

  • One shared cleanup writer is used at start, at reopen and after exit.
  • It writes an item too large for a group as an ordinary item row. That is the same kind of row the agent wrote it with while it was running.
  • A genuine storage failure (disk full, the database locked by another process) still fails the start, as on main. The start's own essential writes would fail in that case too.

Fixed in review

  • The dead turn left "working" after a failed cleanup, with sends queuing forever (P1).
  • A leftover approval holding the queue (P1).
  • The cleanup failing deterministically on an oversized item, at start, reopen and exit (P2).
  • A duplicated test case.
  • Code comments, title and description that overstated how common the trigger is.

Deferred (follow-ups, none needed for this fix)

  • Liveness tied to the current agent. Count a turn or prompt as live only when the current agent owns it, so stale rows can never hold the queue whatever their stored state. This would also cover a storage failure during a reopen cleanup, which can still leave a chat stuck on main. It touches about 30 readers and needs a new field the host publishes.
  • Keeping the death proof. The proof of how the previous agent died is cleared before the cleanup is saved, so a later retry can only say "unverifiable".
  • Same pattern elsewhere in starting. Other bookkeeping writes in the start path have the same shape: rewind recovery's trailing writes, and the replaced agent's write barrier. Send settlement is handled separately in fix(native-chat): settling earlier sends after a restart no longer blocks starting a chat #26577.
  • Size limit for Claude tool inputs. A Claude-specific limit that keeps the Edit and Write diffs.
  • Cleanup fallback in the journal layer. Optionally, move the fallback into the journal layer so every caller gets it by design.

Refuted: a suspected 17-byte gap in the group size estimate. The estimate sizes every number at maximum width, which leaves at least 36 bytes spare.

What was verified

  • Two review rounds: an adversarial correctness review, an architecture challenge, reachability and test checks, then two fresh reviews of the new design. A readiness checklist passed, with no P0 or P1 left.

  • Real-SQLite unit tests:

    • start or resume with no new agent activity, an oversized running tool call and a pending approval: the message is sent, not queued;
    • reopen;
    • exit cleanup, including a re-run;
    • storage failure still fails the start.

    The first three fail on main.

  • Electron QA on macOS hidden test windows, before and after, with screenshots in the description:

    • Base: stuck, every send failed, and the log showed journal_lifecycle_batch_byte_bound_exceeded.
    • This PR: settled on reopen, three messages answered, still fine after a relaunch.
  • Node typecheck and orca-ci-checks pass. CI passed on ed98206 with no failures.

Not verified

  • SSH or remote hosts.
  • Claude or Codex chats in the app. QA used one agent; the cleanup is the same for every agent.
  • In the app, the start-time and exit-time cleanups on their own, because the reopen cleanup ran first. Unit tests cover those two.
  • A real model producing an input over 1.5 MB. The QA input was planted directly.

@brennanb2025
brennanb2025 marked this pull request as ready for review October 8, 2026 14:29
@coderabbitai

coderabbitai Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f900306d-fe4a-42a8-898c-d89b8dd8621c
📥 Commits

Reviewing files that changed from the base of the PR and between e3639ef and ed98206.

📒 Files selected for processing (8)
  • config/scripts/vitest-sqlite-runtime-files.mjs
  • src/main/native-chat/agent-session-journal/journal-lifecycle-batch-partition.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-cleanup.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-dead-generation-settlement.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-dead-generation-settlement.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-startup-failure-exit.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-unfinished-work.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.


📝 Walkthrough

Walkthrough

Recovered journal settlement now checks whether a single mutation fits within a recovered lifecycle batch. It writes an oversized single-item mutation with appendItem and other chunks with appendLifecycleBatch. Tests cover oversized interrupted work, cleanup after session restart, and cleanup-write failure during attach. The SQLite runtime test include list now contains the attach-cleanup test.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to ed982

The oversized cleanup case can settle without leaving the chat stuck. No identified issue prevents merging after normal checks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main fix: oversized unfinished tool-call cleanup no longer permanently breaks chats.
Description check ✅ Passed The description is detailed and covers the user impact, cause, implementation, alternatives, testing, visual proof, compatibility, and limitations. It does not link a separate issue, but it identifies…
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing as superseded: a merged PR already covers this change. Merged #26664 (ded0144) says 'Supersedes #26576'. It commits a dead generation's settlement in one transaction, with an oversize item written as an ordinary row with its full body. That is the same failure,

(Stale-PR cleanup 2026-10-20, approved by Brennan. Reopen if something here is still missing on main.)

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