Skip to content

fix(native-chat): stop a collapsed run claiming success when a tool call failed - #21151

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/native-chat-failed-tool-tick
Sep 17, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/native-chat-failed-tool-tick

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​144 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​142
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​87 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​81

The bug

A settled activity group drew its completion tick whenever no call in it was running:

{structuredActivityUi && !hasRunningCall ? <Check ... /> : null}

state is 'running' | 'completed' | 'failed', so !running is not success. A run whose tool call
failed had nothing running, took the tick, and asserted success over a failure the reader could
only find by expanding the run. That is what made a real user's failed background command look fine
at a glance.

The mechanism

Success is now stated rather than inferred. nativeChatToolRunOutcome (new
src/shared/native-chat-tool-run-outcome.ts) scans the run once for explicit failed lifecycle
states, error results, and calls still marked running. It uses the larger failure count because
structured producers emit both a failed state and an error result for the same call, while older
transcripts may carry only result errors. Counting those signals directly also prevents an
outputless completed call from taking the next call's error result through FIFO pairing.

The completion mark is granted only when the run is settled, has nothing still running, and has no
failure evidence. A call carrying no lifecycle state is neither a failure nor in flight, so
legacy transcripts still settle as before. The collapsed header additionally reports N failed,
with a spoken Failed tool calls: N. Text only, in the header's own muted mono type: a tool error
is routine work, so no destructive tint and no swapped glyph. Tool calls model no stopped state, so
none is invented here.

Ablation

The base is fbe7b194b8 (origin/main at the time, and this branch's parent).

Arm A — all four source files reverted to origin/main, the new shared module removed from disk,
tests kept at branch HEAD:

Test Files  1 failed (1)
     Tests  2 failed | 41 passed (43)

× refuses the completion mark to a collapsed run whose call failed
    AssertionError: expected SVGSVGElement{…} to be null
    + Received: <svg class="lucide lucide-check size-3 shrink-0 text-muted-foreground" ...>
× counts every failed call in a run, not just the last one
    Expected element to have text content: 2 failed
    Received: 3×shell a shell b shell c

The 41 passing tests include the new says nothing and keeps the mark when every call in the run succeeded — the positive control. It passes on main too, so the two red tests are catching the
defect rather than the suite merely being sensitive to one lever.

Arm B — everything at HEAD: Test Files 3 passed (3) / Tests 70 passed (70).

Before / after

Rendered from the real component with the real token stylesheet — the left panel is
origin/main's component verbatim, the right is this branch's, same blocks, same page.

before-after

Colours verified with getComputedStyle, not by eye:

before after
failed run (1 call) tick drawn no tick, 1 failed
failed run (2 of 3 calls) tick drawn no tick, 2 failed
clean run tick drawn tick drawn, no text

The N failed text computes to rgb(161, 161, 161) at 11px — identical to the
text-muted-foreground probe and deliberately not the text-destructive token, which resolves
to rgb(255, 101, 104) on the same page. Chromium's accessible-name computation reports the
collapsed buttons as … Failed tool calls: 1 / … Failed tool calls: 2, so the failure is
announced and not only seen.

Gates

  • pnpm test (3 explicit files): Test Files 3 passed (3) / Tests 70 passed (70)
  • pnpm test src/renderer/src/components/native-chat …: Test Files 162 passed (162) / Tests 1612 passed (1612)
  • pnpm tc: exit 0
  • pnpm run check:code-quality:changed: 0 new finding(s) across 5 changed file(s) on all seven sub-gates
  • verify:localization-catalog, verify:localization-runtime-catalog, verify:localization-extraction,
    verify:localization-coverage, check:max-lines-ratchet: all exit 0. The two new keys were synced
    with pnpm run sync:localization-runtime-catalog and added to en.json.
  • NativeChatToolRun.tsx measured with a used-symbol probe: clean at +60 appended lines, trips
    max-lines at +80. No ratchet touched, no disable added.
  • git diff origin/main...HEAD --name-only -- pnpm-lock.yaml mobile/pnpm-lock.yaml is empty.

Note

#20519 also modifies NativeChatToolRun.tsx (it adds a backgroundTasks prop and a standaloneRows
list). It does not touch the tick logic, so expect a textual conflict for whichever of the two lands
second; it is not resolved here.

…all failed

A settled activity group drew its completion mark whenever no call in it was
`running`. That is not a success test: a tool call is `running`, `completed` or
`failed`, so a run whose call failed had nothing running, took the mark, and
asserted success over a failure the reader could only find by expanding the run.

Success is now stated rather than inferred. `nativeChatToolRunSucceeded` grants
the mark only to a run that is settled, has nothing still running, and has no
failed call — a call's own `failed` verdict or an error result, the same
composite test the task-list, edit-card and ask-row readers already use. A call
with no lifecycle state is neither, so legacy transcripts still settle.

A collapsed run that did contain failures now says so in the header, as a quiet
`N failed` in the header's own mono type with a spoken `Failed tool calls: N`.
Text only: a tool error is routine work, so no destructive tint and no swapped
glyph. The count is taken over every call in the run, not the latest.
@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview 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: bad7ea4b-3a0a-46e2-b725-a0ef4dca30b7

📥 Commits

Reviewing files that changed from the base of the PR and between fbe7b19 and 650e61d.

📒 Files selected for processing (7)
  • src/renderer/src/components/native-chat/NativeChatToolRun.test.tsx
  • src/renderer/src/components/native-chat/NativeChatToolRun.tsx
  • src/renderer/src/i18n/en-runtime-required.json
  • src/renderer/src/i18n/locales/en.json
  • src/shared/native-chat-tool-activity.ts
  • src/shared/native-chat-tool-run-outcome.test.ts
  • src/shared/native-chat-tool-run-outcome.ts

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


📝 Walkthrough

Walkthrough

The change adds shared outcome evaluation for native chat tool runs. It counts failed calls from lifecycle and result data, avoids double-counting, and reports success only for settled runs without failures. The collapsed header now shows localized failure counts and displays a completion check only for successful runs. English strings and tests cover the new behavior.

Priority: ⬇️ Low

Severity of issue fixed: Low

Merge Risk: ⚪ Minimal · up to 650e6

The collapsed tool-run status change has no established remaining correctness or availability risk and is ready to merge after normal checks.

🚥 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 4 functions across 5 files. (2 skipped: 2… Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the bug, mechanism, user-visible behavior, testing, and visual proof. However, it omits the required linked issue, formal template sections, review checklist, and several requ… Add the required issue reference under “Linked Issue” using “Fixes #...”. Add or map content to the template sections, complete the Testing, Review, Agent skill upstream boundary, Notes, and Checklist sections, and confirm the required chec…
✅ 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 describes the primary change: preventing collapsed native chat runs from showing success when a tool call fails.
Full details: Docstring Coverage

Explanation

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 4 functions across 5 files. (2 skipped: 2 unsupported.)

Full details: Description check

Explanation

The description explains the bug, mechanism, user-visible behavior, testing, and visual proof. However, it omits the required linked issue, formal template sections, review checklist, and several required checklist confirmations.

Resolution

Add the required issue reference under “Linked Issue” using “Fixes #...”. Add or map content to the template sections, complete the Testing, Review, Agent skill upstream boundary, Notes, and Checklist sections, and confirm the required checks or state that CI will cover them.

  • 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.

✅ No new issues found.

Reviewed changes

  • Success is now stated, not inferred — the collapsed run header's !hasRunningCall tick heuristic is replaced by nativeChatToolRunSucceeded, which grants the mark only to a run that is settled, has nothing running, and has no failed call. failed is neither running nor success, which is exactly the defect this closes.
  • Failure detection reuses the existing composite test — countFailedToolCalls pairs blocks with pairToolBlocks and treats call.state === 'failed' || result?.isError === true as a failure, matching the task-list, edit-card, and ask-row readers. State-less legacy calls still settle as before.
  • Header reports N failed — counted over every call, not just the latest, rendered outside the truncating member list so a narrow pane cannot hide it, with a spoken Failed tool calls: N. Deliberately quiet text (no destructive tint, no swapped glyph).
  • New shared module + tests — src/shared/native-chat-tool-run-outcome.ts and its unit tests; the existing failed-run component test was repurposed from asserting the buggy check to refusing it, and a clean-run positive control was added.
  • i18n — components.native-chat.tool.failedCount / failedCallsLabel added to the shared copy fallbacks, the runtime catalog, and en.json.

I ran the new shared unit tests plus the modified component test (55 passing) and the full native-chat renderer suite (161 files / 1600 passing). The PR's ablation shows the two behavioral tests fail on the base, so they pin the defect rather than merely passing at head.

A couple of non-blocking observations:

  • failedCallCount is not gated by structuredActivityUi, unlike the check and category glyph beside it, so NativeChatResolvedView (showTurnStatus={false}) now surfaces N failed. That reads as intentional — failure should surface even where the done-mark is hidden — but no test covers structuredActivityUi={false} in either direction.
  • pairToolBlocks runs twice per render (once inside nativeChatToolRunSucceeded, once for countFailedToolCalls). Negligible for real run sizes, but it is a duplicated O(n) pass if this ever lands in a hot path.
  • Mobile's ToolRun draws no completion tick at all, so the false-success bug does not exist there; no parity follow-up is needed.

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.

Important

The new Math.max failure count is exact for homogeneous runs but undercounts a run that mixes structured (state-bearing) and legacy (state-less) calls — a shape adopted / handed-off sessions can produce. The success verdict is unaffected (a real failure always pushes the count ≥ 1, so the tick is still withheld); only the new N failed badge under-reports.

Reviewed changes

  • Outcome helpers consolidated — countFailedToolCalls and nativeChatToolRunSucceeded are replaced by a single nativeChatToolRunOutcome returning { succeeded, failedCallCount }.
  • FIFO pairing dropped for a single pass — failure counting no longer re-pairs blocks with pairToolBlocks; it tallies state === 'failed' calls and isError results separately and collapses them with Math.max, which fixes the mispairing that double-counted a failed call whose result block is omitted.
  • Tests rewritten against the new function — the two prior suites are merged, and a regression case for the omitted-result mispairing is added.
  • Component and comment references updated to the renamed import and function.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +41 to +42
// Structured lanes carry both signals for one failure; legacy lanes carry only the result.
const failedCallCount = Math.max(failedStateCount, errorResultCount)

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.

Math.max assumes a run is homogeneous — either every call carries lifecycle state (structured lanes) or none do (legacy lanes). That is not true once a session mixes the two: legacyItemBody keeps multi-block legacy messages as state-less calls + isError results, while adopted/handed-off epochs append live structured items into the same journal and foldToolMessages merges them into one run. When a structured failed call has no result block (f0) and a state-less call has an error result (s), max(failedStateCount, errorResultCount) is short by min(f0, s) — e.g. it reports 1 failed for two failures. The tick verdict is safe (a real failure always makes the count ≥ 1), but the new badge can under-report the exact thing this PR added.

Technical details
# `Math.max` undercounts a mixed-lane run

## Affected sites
- `src/shared/native-chat-tool-run-outcome.ts:41-42` — `Math.max(failedStateCount, errorResultCount)` is exact only when `failedStateCount === 0` or `errorResultCount >= failedStateCount`, i.e. when no failed-state call is result-less alongside a state-less error result.

## Why the invariant breaks
- `journal-legacy-import.ts:230-259` — a single-block message becomes a state-bearing `kind:'tool-call'`; a multi-block message stays `kind:'message'` with raw state-less calls and `isError` results.
- `structured-agent-session-projection.ts:54-80` — emits the `tool-result` only inside `body.output ? [...] : []`, so a failed structured call with no output contributes to `failedStateCount` but not `errorResultCount`.
- `f0` producers: `structured-agent-session-dead-generation-settlement.ts:154-157` (running → failed, spreads the body unchanged, running calls have no output), `codex-structured-item-translation.ts:106-108,130,183` (failed command / fileChange / mcp with no output).
- Mixing: `structured-agent-session-adopted-import.ts:86` (`replaceEpochItems('legacy_import', …)`) then live structured items appended to the same epoch; `structured-agent-session-message-projection.ts:18-19` sends every item through `projectStructuredItemsToNativeChat`; `native-chat-tool-fold.ts:98-112` folds tool-only rows into the preceding assistant run.

## Concrete sequence
`[text, tool-call(a, no state), tool-call(b, no state), tool-result(error), tool-result(ok), tool-call(c, state:'failed')]`
source: two blocks fold from the legacy message, one `kind:'tool-call'` failed with no output from the structured lane.
`failedStateCount = 1`, `errorResultCount = 1` → reports `1`, true failures `2` (the state-less call that owns the error result, plus `c`).

## Required outcome
A state-bearing failed call is a failure even without a result; a state-less call's error result is a failure even alongside state-bearing calls. The count must reflect both without collapsing one into the other.

## Considered alternative
Reverting to `pairToolBlocks` per-pair counting restores this mixed case but reintroduces the omitted-result overcount the commit was written to remove (`[call a completed, call b failed, result error]` → 2). Using `callId` where present, or attributing error results only to state-less calls, would avoid both.

## Open question for the human
Is the mixed (legacy-import + live structured) lane expected to render in the same run, or is the two-shape split guaranteed never to fold into one header? If it can, a test built from `projectStructuredItemsToNativeChat` + `foldToolMessages` would pin it.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron QA — collapsed tool-run outcomes (PR head 650e61da9a)

Validated in a hidden Orca Electron instance attached over CDP. window.api.app.getIdentity() matched this worktree/branch (Orca: brennanb2025/native-chat-failed-tool-tick). No production files were edited.

Path: production bridge/resolved native chat (NativeChatResolvedView). Seeded a Claude JSONL transcript, then setAgentStatus + toggleTabViewMode. Store had viewMode=chat and structuredSessionId=null. DOM had [data-native-chat-root="true"] with data-native-chat-working="false" and no [data-native-chat-turn-status], so showTurnStatus={false} → structuredActivityUi={false}.

Failed collapsed run (3 calls, 2 errors)

Header reads 3× Bash false … 2 failed, stays collapsed (aria-expanded=false), and has no success check. Failed label is muted rgb(161, 161, 161) at 11px (not destructive rgb(255, 101, 104)). Playwright getByRole('button', { name: /Failed tool calls: 2/ }) matched; the accessibility snapshot named the button 3× Bash false Bash false Bash echo ok Failed tool calls: 2. Span aria-label is Failed tool calls: 2.

Successful collapsed run

Header reads 1× Bash echo succeeded, collapsed, no N failed label. No success check on this path: the check is gated on structuredActivityUi && runSucceeded, and resolved view hard-codes showTurnStatus={false}.

Structured path not reached

Enabled experimentalStructuredNativeChat and launched Claude from New tab. That created a TUI terminal (launchAgent=claude, structuredSessionId=null), not NativeChatStructuredSession. Did not substitute a component fixture. A settled structured run with the success check is still unverified in this Electron session.

Full app window (one tab):

01-full-app-collapsed-runs.png

Same transcript after a second TUI Claude tab existed:

02-seeded-tab-collapsed-runs.png

Native-chat pane surface:

03-native-chat-pane-collapsed-runs.png

Local artifacts: /tmp/orca-pr21151-qa/ (screenshots, transcript, report).

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready

Reviewed through a fix loop and a clean independent follow-up at 650e61da9a124ba4896adda31a8b414dd8604d1a.

  • The first review found a real double-counting bug when an outputless completed call preceded a failed call. Commit 650e61da9a fixes it by deriving the run outcome directly from lifecycle failures, error results, and running state in one bounded scan.
  • The next independent review returned clean after tracing structured, imported, and legacy producers. The final readiness review found no P0, P1, or P2 issues.
  • The implementation removes the original false-success inference without adding persistence, caches, retries, effects, polling, IPC, or retained state. The added work is O(n) over the blocks in one rendered tool run.
  • Final local validation passed: 57 focused tests, pnpm tc, pnpm run check:code-quality:changed, and git diff --check.
  • GitHub CI is green, including Windows packaging and all eight test shards.
  • Electron QA validated the real production resolved-chat path: a collapsed three-call run with two failures shows 2 failed, has no false success check, and exposes Failed tool calls: 2 to accessibility APIs. Screenshots and exact state are attached in the Electron QA comment.

Remaining QA gap: the Electron lane could not create a real structured SDK session to capture the successful structuredActivityUi=true check. That branch is covered by focused component tests; the production resolved-chat failure path was exercised end to end.

The PR description has been updated to match the final mechanism. The branch is clean, matches the remote PR head, and is ready to merge.

@brennanb2025
brennanb2025 merged commit 68ea3b9 into main Sep 17, 2026
28 checks passed
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…all failed (stablyai#21151)

* fix(native-chat): stop a collapsed run claiming success when a tool call failed

A settled activity group drew its completion mark whenever no call in it was
`running`. That is not a success test: a tool call is `running`, `completed` or
`failed`, so a run whose call failed had nothing running, took the mark, and
asserted success over a failure the reader could only find by expanding the run.

Success is now stated rather than inferred. `nativeChatToolRunSucceeded` grants
the mark only to a run that is settled, has nothing still running, and has no
failed call — a call's own `failed` verdict or an error result, the same
composite test the task-list, edit-card and ask-row readers already use. A call
with no lifecycle state is neither, so legacy transcripts still settle.

A collapsed run that did contain failures now says so in the header, as a quiet
`N failed` in the header's own mono type with a spoken `Failed tool calls: N`.
Text only: a tool error is routine work, so no destructive tint and no swapped
glyph. The count is taken over every call in the run, not the latest.

* fix(native-chat): count failed tool calls without result mispairing
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