Skip to content

fix(native-chat): record a failed restart in the chat where the restart happens - #22742

Closed
brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/chat-restart-failure-row
Closed

brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/chat-restart-failure-row

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​436 $\color{#cf222e}{\Huge{\mathbf{−}}}$​5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​431
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​237 $\color{#cf222e}{\Huge{\mathbf{−}}}$​116 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​121

ELI5

When a chat's agent could not restart (for example, Claude is not signed in), you only saw why if you had just sent a message. Opening or switching to the chat tried the restart too, but a failure there was silent on desktop, showed a bare error code on the phone, and stopped the phone from loading the chat at all. Now every failed restart is written into the chat as one red error line with the real reason, whoever triggered it, and simply looking at the chat again no longer keeps retrying a start that already failed.

What Changed

Before

  • A restart can be triggered three ways: a chat pane coming into view (a "hold"), a send, or automatic recovery after the agent process exits mid-conversation. Only the send path wrote the reason into the chat. The other two only logged it.
  • The hold request answered with the bare refusal code (for example agent_session_operation_invalid) instead of the reason.
  • Mobile subscribed to the chat only after a successful hold, so a refused hold left the chat empty with a code as the error.
  • Failure rows were plain text with no tone, so they looked like ordinary notices.
  • Every time a pane came back into view (tab switch, window visibility, remount) it restarted a chat whose last start had failed. Each attempt spawned another doomed process and, with a row per attempt, would add another row.

After

  • The row is written by the one resume that all three triggers share, once per attempt, with tone: 'error'. The send-only copy is deleted. The status row a start leaves when its process dies after it was published (the startup-failure row) also gets tone: 'error'.
  • The hold request now answers with the refusal's own message next to the unchanged code.
  • Mobile subscribes whether or not the hold succeeded, so the chat's history, including the failure row, always loads.
  • A chat pane coming into view does not restart a chat whose last start failed. The next send retries, which is the rule automatic exit recovery already follows. An explicit Retry in the restart dialog still restarts it.

Mechanism

  • resumeHeldStructuredAgentSession (the shared resume behind ensureProviderChild) now calls one writer, recordFailedStructuredAgentSessionResume, for any refusal that proves the chat cannot run right now. It makes the journal readable if the failed attach left none and publishes the row to subscribers. Refusals that only mean someone else is still settling the lease write nothing, same as before. The refusal classification moved with it from send preparation into structured-agent-session-resume-refusal.ts.
  • The view rule reads the host's existing fact that the exit rule already reads: a session with no child whose last child phase is starting. A child that dies after it was published leaves exactly that state already. For a child that dies before it was published, the writer sets that phase on the session it made readable. Only the hold RPC (a surface coming into view) opts into the rule, through a new resumeFailedStart: false hold option. Sends, restart-dialog retries and structured workers keep restarting.
  • holds.hold throws a typed StructuredAgentSessionHoldRefusedError. Its message is still the code, which is what the in-process restart ledger reads. The hold RPC handler maps it to { code, message: refusal.message }, and mapRuntimeError passes the agent-session refusal codes through with their message.

Why

  • One writer instead of three. The reason was being lost because only one of three callers wrote it. Writing it where the restart happens fixes all three and deletes the send-only copy, instead of adding a second and third copy.
  • Existing field. tone is an existing optional status field. The schema already admits it, the projection already passes it through, and the desktop renderer already draws error. So this is a new value of a field older clients already handle, not a new row kind. A client that ignores tone still shows the text.
  • Considered and rejected:
    • A "Send again" action on the row. Each path already has its action: the rejected message bubble has Retry, the composer's next send restarts, and a chat that cannot be restarted here says "Start a new chat to continue."
    • A dedupe guard on rows, which would hide real repeated attempts.
    • A new persisted field meaning "last start failed", which would duplicate a fact the host session already carries.
  • Evidence behind the view rule. A test against the real host showed three holds spawning three children and writing three rows. Without the rule, a child that dies after it was published is also restarted on remount, and that already happens on main.

Differences from the common pattern

  • Where the pattern matches: the common pattern records a failed start once, at the single owner that starts turns, as a typed error entry in the conversation with the provider's own reason. This PR matches that in ownership (one writer at the shared resume), delivery (a conversation row published to subscribers) and per-attempt lifecycle (no dedupe).
  • Deviation 1, when a restart can happen: Orca also restarts a chat when a pane comes into view, not only on a user action. The common pattern restarts only on user action. The view rule narrows this for failed starts only.
  • Deviation 2, how the failure is typed: the common pattern types the failure with its own kind or code field. Orca keeps its existing status row and marks it only with the optional tone: 'error'. No field records the failure kind, and there is no separate session-level "last error". The in-memory host session's child phase stands in for that during the process lifetime.
  • Deviation 3, rows without a pending user action: the common pattern writes a system error for a process exit only when a turn was running or waiting to start. Orca also writes one when a view-triggered restart fails with no user action pending, because otherwise nothing in the chat explains why it has no agent.

Linked Issue

No tracking issue. Out of scope, as follow-up context: Linear STA-8084 (provider "retrying" frames).

Visual Proof

N/A. No screenshots were captured for this change. The only visual change is that these rows use the existing error treatment in NativeChatNoticeRow, which its current tests already cover. The behavior is covered by the host and wire tests below.

Testing

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • New structured-agent-session-resume-failure-row.test.ts, against the real host and record store:

    • A hold whose restart dies before it is published delivers exactly one tone: 'error' row with the real reason to a subscriber.
    • A hold, a send and exit recovery each write the same row shape, one per attempt.
    • A remounted pane restarts nothing after a failed start, whether the child died before or after it was published, and the next send retries.
    • An explicit reattach still restarts.
  • structured-agent-session-hold.test.ts (over the RPC dispatcher):

    • A refused hold answers { code, message: <real reason> }.
    • A second hold after a failed start spawns nothing.
  • Updated tests:

    • Startup-failure rows now carry tone: 'error'.
    • The restart-dialog reattach failure now shows the reason row before its existing "didn't reconnect" note.
    • A resend of the same send id after a failed restart now adds its own row, because each attempt is one row.
  • Each new assertion was checked by deleting the core lines and seeing it fail for the stated reason, then restoring.

  • Mobile: new use-mobile-structured-agent-state-hold-refused.test.tsx checks that a refused hold still subscribes and shows the chat. It was not run locally because the mobile suite needs Expo installed. CI covers it.

  • Local runs on macOS: src/main/native-chat, src/main/runtime/rpc, the Claude structured runtime tests, src/shared and the native-chat renderer tests all pass. The one exception is claude-structured-real-cli / claude-tui-resume-real-binary, which already fail locally on main.

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Author X handle: @BrennanKB5

Remote and version compatibility. Clients and hosts update independently, so here is what each mix does.

  • Rows: tone is an existing optional field. A new value reaches older clients, which render the text as before.
  • Hold errors, code: the code is unchanged for every code clients already received as a code.
  • Hold errors, message: the message changes from the code to the reason. Desktop only logs it. Older mobile shows it as its error, which is an improvement over the code.
  • Other refusal codes: refusal codes outside the existing agent-session list (for example structured_agent_session_unsupported) now arrive under their own code instead of runtime_error.
  • Old mobile with a new host: a refused hold still stops the chat from loading. Only the new client subscribes regardless.

SSH and folder workspaces. All of this runs on the execution host that owns the session, so SSH-hosted chats behave the same. Nothing here depends on git.

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)

…rt happens

A restart that failed reached the chat only when a send asked for it. A pane
coming into view (the hold) or provider-exit recovery that met the same
failure only logged it, the hold RPC answered with the bare refusal code, and
mobile never loaded the chat's history after a refused hold.

The failure row is now written by the resume every asker shares, once per
attempt, with tone 'error'; the send-only copy is deleted. The hold RPC carries
the refusal's own message next to its code, mobile subscribes even when the
hold is refused, and startup-failure rows carry the error tone too.

A pane coming into view no longer respawns a chat whose last start failed, the
rule provider-exit recovery already follows: the chat says why, and the next
send retries. Without it every remount spawned a doomed child and wrote a row.
@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

Resume refusals are classified and recorded as error-status rows when applicable. Holds can avoid retrying a failed start, while sends use the shared refusal classification. The hold RPC preserves refusal messages and codes. The mobile hook continues subscription setup after a hold rejection and displays error status from session snapshots.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to de715

Mobile can show a session as ready after a hold fails for an unexpected reason. Surface those failures; this is a bounded issue that does not prevent an explicit restart retry.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 19 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides detailed ELI5, change, rationale, testing, visual proof, compatibility, and checklist information. However, it does not provide the required linked issue; it explicitly states… Add the issue reference in the required Fixes #... format, or obtain an approved issue before merging.
✅ 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 describes the main change: recording failed restarts in the chat where they occur.
Full details: Description check

Explanation

The description provides detailed ELI5, change, rationale, testing, visual proof, compatibility, and checklist information. However, it does not provide the required linked issue; it explicitly states that no tracking issue exists despite the template requiring one.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR

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.

…oes not restart it

The row writer a failed start and a failed restart share also leaves the host
session reading as one whose last child never finished starting, so a pane
coming into view does not start a chat whose create or restart failed, and a
chat this host cannot run says so once rather than once per view.

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 85155f74-4142-418a-bcac-5dfd12f02650

📥 Commits

Reviewing files that changed from the base of the PR and between edbb2a9 and de715cc.

📒 Files selected for processing (19)
  • mobile/src/session/use-mobile-structured-agent-state-hold-refused.test.tsx
  • mobile/src/session/use-mobile-structured-agent-state.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-hold-resume-race.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-hold-resume.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-holds.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-holds.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-lifetime.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-resume-failure-row.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-resume-refusal.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-send-preparation.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-send-preparation.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-start-failure-row.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-startup-failure-exit.test.ts
  • src/main/runtime/rpc/errors.ts
  • src/main/runtime/rpc/methods/structured-agent-session-hold.test.ts
  • src/main/runtime/rpc/methods/structured-agent-session-hold.ts

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

Comment on lines +110 to +115
// A refused hold still leaves the chat readable, and the host writes a real failure into it;
// a send restarts the agent itself.
const readable = held.catch((error: unknown) => {
console.warn('[structured-agent-session] hold failed:', error)
})
void readable

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 | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '50,210p' mobile/src/session/use-mobile-structured-agent-state.ts
sed -n '1,130p' mobile/src/session/use-mobile-structured-agent-state-hold-refused.test.tsx

Repository: stablyai/orca

Length of output: 8538


🏁 Script executed:

set -eu
printf '%s\n' '--- changed hunk ---'
git diff --unified=35 29480cd8cd35a1cf12f36bf056a7e280670c8c52 de715cc78003b6022eb9b537c60a2fd5a5c96c34 -- mobile/src/session/use-mobile-structured-agent-state.ts
printf '%s\n' '--- hook imports and definitions ---'
sed -n '1,125p' mobile/src/session/use-mobile-structured-agent-state.ts
printf '%s\n' '--- bound callAgentSession definitions/usages ---'
rg -n --glob '!node_modules' 'callAgentSession|agentSession\.hold|type .*AgentSession.*Action|reduceStructuredAgentSession' mobile src
printf '%s\n' '--- hook consumers and tests ---'
rg -n --glob '!node_modules' 'useMobileStructuredAgentState|status: .ready|status === .ready|state\.status' mobile/src mobile | head -240

Repository: stablyai/orca

Length of output: 41107


🤖 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: 34460


🏁 Script executed:

set -eu
git diff --unified=35 29480cd8cd35a1cf12f36bf056a7e280670c8c52 de715cc78003b6022eb9b537c60a2fd5a5c96c34 -- mobile/src/session/use-mobile-structured-agent-state.ts
sed -n '1,125p' mobile/src/session/use-mobile-structured-agent-state.ts
rg -n --glob '!node_modules' 'callAgentSession|agentSession\.hold|reduceStructuredAgentSession|useMobileStructuredAgentState' mobile src

Repository: stablyai/orca

Length of output: 22744


🏁 Script executed:

set -eu
printf '%s\n' '--- hook imports and changed area ---'
sed -n '1,145p' mobile/src/session/use-mobile-structured-agent-state.ts
printf '%s\n' '--- exact helper and reducer references ---'
rg -n -C 5 --glob '!node_modules' 'callAgentSession|reduceStructuredAgentSession|agentSession\.hold' .
printf '%s\n' '--- base versus head changed behavior ---'
git diff --unified=20 29480cd8cd35a1cf12f36bf056a7e280670c8c52 de715cc78003b6022eb9b537c60a2fd5a5c96c34 -- mobile/src/session/use-mobile-structured-agent-state.ts

Repository: stablyai/orca

Length of output: 41314


🏁 Script executed:

set -eu
printf '%s\n' '--- mobile RPC helper ---'
sed -n '1,180p' mobile/src/session/mobile-structured-agent-session-rpc.ts
printf '%s\n' '--- reducer definition and transitions ---'
sed -n '1,245p' src/shared/structured-agent-session-reducer.ts
printf '%s\n' '--- mobile session consumer ---'
sed -n '1,330p' mobile/src/session/use-mobile-structured-agent-session.ts
printf '%s\n' '--- relevant mobile hook/session tests ---'
sed -n '270,380p' mobile/src/session/use-mobile-structured-agent-session.test.tsx
sed -n '730,810p' mobile/src/session/use-mobile-structured-agent-session.test.tsx
printf '%s\n' '--- renderer comparable hold implementation/tests ---'
sed -n '1,180p' src/renderer/src/components/native-chat/use-structured-agent-session-hold.ts
sed -n '1,165p' src/renderer/src/components/native-chat/use-structured-agent-session-hold.test.tsx
printf '%s\n' '--- host hold handler ---'
sed -n '30,115p' src/main/runtime/rpc/methods/structured-agent-session-hold.ts

Repository: stablyai/orca

Length of output: 42333


Surface non-refusal hold failures.

callAgentSession rejects for every unsuccessful RPC response, including authorization failures, and transport failures also reject. The new catch treats all of these failures as an intentional refusal, then starts agentSession.subscribe. If the subscription returns a snapshot, replacePage sets the state to ready without an error. The mobile consumer then exposes a ready session even though agentSession.hold failed.

Keep the read-only recovery for the host's hold-refusal code, but rethrow other hold errors so the existing error handler applies.

@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

  • One writer for the failed-restart row. resumeHeldStructuredAgentSession now calls the new recordFailedStructuredAgentSessionResume for any non-transient refusal, so a surface hold, a send and provider-exit recovery all write the same tone: 'error' row; the send-only recordFailedRestart is deleted.
  • Refusal classification extracted. RESUME_REFUSAL_OUTCOME moves from structured-agent-session-send-preparation.ts into structured-agent-session-resume-refusal.ts as structuredAgentSessionResumeRefusalOutcome.
  • View holds stop respawning a failed start. New lastStartFailed dep (hasProviderChild === false && providerChildPhase === 'starting') plus a resumeFailedStart: false hold option suppress the resume for a surface coming into view; agentSession.hold opts in while sends, restart-dialog retries, recovery and workers keep restarting.
  • Typed hold refusal + real message on the wire. StructuredAgentSessionHoldRefusedError carries the refusal; the hold RPC rethrows { code, message: refusal.message }, and AGENT_SESSION_WIRE_REFUSAL_CODES joins STRUCTURED_RUNTIME_PASSTHROUGH_CODES so mapRuntimeError preserves the code.
  • Startup-failure rows get tone: 'error' in the dead-generation settlement.
  • Mobile subscribes after a refused hold, so the chat history with the failure row always loads.
  • Tests: new host-level structured-agent-session-resume-failure-row.test.ts, new mobile use-mobile-structured-agent-state-hold-refused.test.tsx, plus updated expectations for per-attempt rows and the error tone.

I traced every writer of hasProviderChild / providerChildPhase and the row-writer call graph. lastStartFailed is true only for a childless failed start, so a view hold is suppressed exactly where intended and reopened/evicted sessions still resume on view; the two error-row writers are mutually exclusive, so no duplicate rows; and the failure row survives mapRuntimeError's structured branch as asserted. The tests assert exact row bodies and item counts, and the RPC test pins the exact { code, message }, so they would fail if the behavior regressed.

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

@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 — delta since the prior review at e52e990 (commit de715cc):

  • Extracted start-failure writer. The row/publish logic moved out of recordFailedStructuredAgentSessionResume into new recordStructuredAgentSessionStartFailure (structured-agent-session-start-failure-row.ts); recordFailedStructuredAgentSessionResume now delegates to it.
  • Marker broadened. The writer now sets providerChildPhase = 'starting' whenever the session has no provider child, rather than only when ownerVerdict === 'exited'. This closes the earlier gap where a non-transient refusal with an unverifiable verdict would write a row but leave a view hold free to retry on every mount. Row text selection still keys on ownerVerdict === 'exited'.
  • Two new host tests. A chat whose create made the conversation but not its agent is not started by the pane that opens it (the first send starts it, and exactly one error row is delivered); a chat this host cannot run says so once, not once per view.

The broadened condition is sound: recordFailedStructuredAgentSessionResume still returns early for transient refusals and for a missing record, and the resume only runs when ensureProviderChild saw no child, so !hasProviderChild is the state the marker describes. The new tests assert exact row bodies and per-view spawn counts, so they would fail if the marker regressed.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing without merging. It's superseded by the native-chat redesign: the single failure-row writer and the tone: 'error' rows carry forward in #22821, and the 'viewing never starts the agent' part moves to #22835.

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