Skip to content

fix(native-chat): surface load-earlier failures and stop retry storms (STA-3333) - #12499

Closed
brennanb2025 wants to merge 10 commits into
mainfrom
brennanb2025/sta-3333-load-earlier-errors
Closed

brennanb2025 wants to merge 10 commits into
mainfrom
brennanb2025/sta-3333-load-earlier-errors

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes native-chat history paging failures on both desktop and mobile without duplicating the behavior between clients.

  • Uses one shared load-earlier controller for request deduplication, stale-result invalidation, explicit retry state, and fixed client-side error copy.
  • Surfaces failed pages as a retryable inline error and suppresses automatic near-top retries until the user retries or an authoritative snapshot replaces the window.
  • Preserves the paging cursor on failure, so retry requests the same history window instead of skipping messages.
  • Anchors desktop prepends to the visible message, so concurrent live tail growth cannot distort the viewport correction; failed/no-growth requests, user scrolling, and transcript or runtime-owner swaps clear stale anchors.
  • Announces desktop auto-pagination failures through a polite live region while keeping the retry button accessible.
  • Owns desktop retry timers and sync/async subscription teardown so unmounts cannot leak resources.

The change remains scoped to load-earlier behavior; reconnect-history merging and broader viewport work are separate concerns.

Screenshots

iOS failure state iOS explicit retry recovery
iOS failure state iOS recovered state

Electron smoke

Verification

  • Shared/desktop focused tests: 56 passed
  • Mobile focused tests: 31 passed
  • Desktop web and mobile TypeScript checks
  • Changed-code quality: native, type-aware, and React Doctor clean
  • Max-lines ratchet
  • Localization catalog, extraction, and coverage
  • Same-model senior review loop completed edit-free CLEAN
  • Electron CDP smoke and iOS failure/recovery QA

Scope and compatibility

No dependencies, RPC methods, Git commands, shell behavior, or provider-specific behavior were added. The shared controller is transport-agnostic; desktop and mobile continue to use their existing local, remote, SSH, and folder-workspace transports.

Refs STA-3333.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Native chat earlier-history loading now uses a shared controller and state model across mobile and renderer sessions. The controller handles concurrency, invalidation, stale results, unsuccessful responses, rejected requests, loading state, and errors. Chat views suppress automatic retries after failure and expose explicit retry controls. Mobile views add accessibility metadata and announcements. Renderer controls add translated loading and retry labels. Tests cover failures, retries, stale requests, transcript replacement, and UI states.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description includes a summary, screenshots, verification details, scope, and compatibility notes, but omits the required AI Review Report and Security Audit sections. Add the required AI Review Report and Security Audit sections, including cross-platform compatibility checks and reviewed security risks.
✅ 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 identifies the native-chat failure handling and retry-storm fix.
✨ 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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA evidence — iOS Simulator + desktop no-regression

Verified at head c7d3bff7ac against a mock host whose nativeChat.readSession failure mode is flipped from a control file, so the same session reproduces failure → explicit retry → recovery without re-pairing.

The bug this fixes: the retry storm

Before, a failed page left the user near the top of the list with no feedback, so every subsequent onScroll frame re-fired the same doomed request.

Measured on the live rig with readSession forced to fail:

readSession calls
7 scroll-to-top gestures 1
8 more gestures after an explicit tap-retry cycle +1

One request per explicit user action. The near-top auto-trigger stays suppressed until the error clears.

1. Failure is now visible, with an explicit retry affordance

failure state

2. Tapping the header retries and recovers (60 older messages prepended, header returns to normal)

recovered

3. The cycle repeats — a second failure does not wedge the surface

second failure

Desktop no-regression smoke check

This PR touches only mobile/, so the desktop has no changed surface. Dev build launched from this worktree (identity confirmed as brennanb2025/sta-3333-load-earlier-errors), attached over CDP: boots and renders normally, 0 console errors.

desktop

SSH / remote behavior

Traced against mobile/src/transport/rpc-client.ts:

  • Brief blip — per-request timeouts deliberately cover offline/reconnect waiting (30s budget), so an in-flight page usually just lands late and succeeds. No error shown.
  • Longer outage — the request rejects; the new catch turns that into the same visible failure + explicit retry instead of an unhandled rejection (which is what it was before).
  • Reconnect — on e2ee_authenticated the client re-sends every live stream subscription, and the resulting snapshot frame clears loadEarlierError. So the sticky error cannot survive a reconnect; paging unblocks on its own.

Gates

913/913 mobile tests · tsc clean · oxlint clean · changed-code quality 0 new findings · React Doctor 0 · max-lines ratchet OK · 38/38 CI checks pass (e2e skipped — no changed specs).

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6c434d01-2218-46e4-abb5-e9e234a81d71

📥 Commits

Reviewing files that changed from the base of the PR and between e9cf106 and 76bba00.

📒 Files selected for processing (6)
  • mobile/src/session/MobileNativeChatOverlay.tsx
  • mobile/src/session/MobileNativeChatView.test.ts
  • mobile/src/session/MobileNativeChatView.tsx
  • mobile/src/session/mobile-native-chat-view-styles.ts
  • mobile/src/session/use-mobile-native-chat-session.test.ts
  • mobile/src/session/use-mobile-native-chat-session.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review — CLEAN at 76bba00d81

Reviewed with fresh same-model subagent passes plus mutation testing, held to the PR's stated scope (surface load-earlier failures; suppress automatic near-top retries until explicit user action). No blockers, no should-fixes on the behavior change.

One meaningful fix applied (76bba00d81, tests only)

The first pass found two coverage gaps, each proven rather than asserted:

  1. An unpinned guard. The requestIsCurrent() guard on the not-ok/{error} page path could be deleted with all 913 tests still green — only the rejection twin was covered. Without it: a page request is in flight → a replacement/snapshot lands and installs a healthy window → the stale request resolves {ok:false} → an error is planted on a window that never failed, gating auto-paging on healthy state. The stale-failure test now runs it.each over both failure shapes.
  2. An assertion that could not fail. not.toContain('Tap to retry') was asserted while rendering with no loadEarlierError, so the retry text was unreachable regardless of implementation. It now renders both props, pinning that an in-flight retry outranks the failure it is retrying.

Mutation testing (the evidence)

Every mutation below now goes RED, each killing exactly the intended test — and the first two were green before this commit:

Mutation Before After
Delete requestIsCurrent() on the not-ok/{error} branch green (gap) RED
Delete requestIsCurrent() in the catch RED RED
Invert the ternary so a stale error beats the spinner green (gap) RED
Remove && !loadEarlierError from the near-top gate RED RED

Hypotheses tested and ruled out

  • Orphaned retry (error set while the header stops rendering) — impossible. hasMore is only written by the effect reset and replacement/snapshot frames (both clear the error in the same batch), the success paths (error already null), and the pageLimit <= 0 cap — which is unreachable with an error set, since limitRef only advances on success.
  • loadingEarlierRef leaking true — every reset site also bumps streamGenerationRef, so a stale request can neither unlock nor write an error.
  • Failure-path coverage — ok:false, {error}, and rejection are the only three; the wire contract confirms a success payload never carries an error key, so 'error' in result is a sound discriminant.
  • SSH/remote — a drop mid-page rejects into the new catch; reconnect re-sends live subscriptions and the resulting snapshot clears the error, so the sticky state cannot survive a reconnect. A drop before the request lands parks in waitForConnected and shows the spinner — identical to pre-fix behavior.
  • The gate blocking a legitimate page — the error is nulled at the top of every loadEarlier() and by every authoritative frame, so a success never leaves it latched.
  • Perf — no new commit is introduced (loadEarlierError always writes alongside setLoadingEarlier); the onScroll dep is a rarely-changing boolean, not per-frame cost.

Known gap, accepted (not fixed here)

VoiceOver does not re-announce a focused element's label change, so a blind user who taps the header and hits a failure hears nothing — the accessibilityLabel swap is the only signal. Impact is degraded-but-recoverable (the same tap is the retry), and this PR still improves a11y over main, which had neither accessibilityRole nor accessibilityLabel on this row. A correct cross-platform fix needs AccessibilityInfo.announceForAccessibility, which is more machinery than this scope warrants — flagging rather than smuggling it in.

Gates at 76bba00d81

403 files / 3021 mobile tests pass · tsc clean · oxlint clean · changed-code quality 0 new findings · React Doctor 0 · max-lines ratchet OK · 42/42 CI checks pass (e2e skipped — no changed specs).

A failed older-history page silently did nothing: the near-top scroll
trigger kept re-firing the same doomed request, and a rejected transport
request escaped as an unhandled rejection.

Failures (RPC not-ok, error results, rejections) now set an inline
"Couldn't load earlier messages / Tap to retry" header row, and the
scroll trigger stands down until the user retries explicitly or an
authoritative window supersedes the failed page.

Refs STA-3333.
…recedence

Review found two coverage gaps, each proven by mutation:

- The `requestIsCurrent()` guard on the not-ok/`{error}` page path could be
  deleted with all 913 tests still green — only the rejection twin was pinned.
  The swapped-out-from-under test now runs over both failure shapes.
- `not.toContain('Tap to retry')` was asserted with no `loadEarlierError` set,
  so it could not fail. It now renders both props, pinning that an in-flight
  retry outranks the failure it is retrying.
Invalidate in-flight pages during full source changes, keep loading accessibility semantics aligned with the spinner, and announce retryable failures to assistive technology.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-3333-load-earlier-errors branch from 76bba00 to 3d5eccf Compare August 4, 2026 22:26
@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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)
mobile/src/session/use-mobile-native-chat-session.test.ts (1)

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

Assert pending and terminal pagination states.

At Line 264, the retry resolves immediately. The test can pass if loadEarlierError clears only after success. Hold the second request pending, then assert that retry clears loadEarlierError while loadingEarlier is true.

At Line 291, also assert that loadingEarlier is false. Otherwise, an error-result branch can leave pagination stuck in loading state.

Suggested test strengthening
+    let resolveRetry: (response: unknown) => void = () => {}
     const sendRequest = vi
       .fn()
       .mockResolvedValueOnce({ ok: false, error: 'offline' })
-      .mockResolvedValueOnce({
-        ok: true,
-        result: { messages: [message('older')], hasMore: false, beforeOffset: 0 }
+      .mockImplementationOnce(
+        () =>
+          new Promise((resolve) => {
+            resolveRetry = resolve
+          })
+      )
+
+    act(() => state?.loadEarlier())
+    expect(state?.loadEarlierError).toBeNull()
+    expect(state?.loadingEarlier).toBe(true)
+
+    await act(async () => {
+      resolveRetry({
+        ok: true,
+        result: { messages: [message('older')], hasMore: false, beforeOffset: 0 }
       })
+      await Promise.resolve()
+    })
 
     expect(state?.messages.map((entry) => entry.id)[0]).toBe('older')
 
     expect(state?.loadEarlierError).toBe('Couldn’t load earlier messages')
+    expect(state?.loadingEarlier).toBe(false)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 866708f6-1480-4cd0-96b0-a8162c931471

📥 Commits

Reviewing files that changed from the base of the PR and between 847c8c8 and 3d5eccf.

📒 Files selected for processing (6)
  • mobile/src/session/MobileNativeChatOverlay.tsx
  • mobile/src/session/MobileNativeChatView.test.ts
  • mobile/src/session/MobileNativeChatView.tsx
  • mobile/src/session/mobile-native-chat-view-styles.ts
  • mobile/src/session/use-mobile-native-chat-session.test.ts
  • mobile/src/session/use-mobile-native-chat-session.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • mobile/src/session/mobile-native-chat-view-styles.ts
  • mobile/src/session/MobileNativeChatOverlay.tsx
  • mobile/src/session/MobileNativeChatView.test.ts
  • mobile/src/session/use-mobile-native-chat-session.ts
  • mobile/src/session/MobileNativeChatView.tsx

…-load-earlier-errors

# Conflicts:
#	mobile/src/session/use-mobile-native-chat-session.test.ts
#	mobile/src/session/use-mobile-native-chat-session.ts

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/e2e/setup-script-prompt-unreadable-orca-yaml.spec.ts (1)

115-125: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Make worktree path matching platform-aware.

normalize only handles one macOS path alias. It does not handle Windows separators or drive-letter casing. The test can fail to find mainWorktree or featureWorktree before it exercises the recovery flow.

Move the comparison out of page.evaluate. Use Node path utilities and a runtime check for Windows. Resolve path aliases when required.

Source: Coding guidelines

🧹 Nitpick comments (2)
mobile/src/session/use-mobile-native-chat-session.test.ts (1)

383-385: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the added test comments.

These comments repeat the setup and expected assertions. Keep only the non-obvious invariant in one concise line.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through how the code works.”

Also applies to: 407-415, 430-430, 490-490, 520-521, 555-557, 580-581

Source: Coding guidelines

tests/e2e/setup-script-prompt-unreadable-orca-yaml.spec.ts (1)

44-72: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Restore the fault-injected handler after every test.

installUnreadableOrcaYamlFault replaces the process-wide hooks:check handler. healOrcaYamlRead only changes the flag. The test has no finally block.

If setup or an assertion fails before healOrcaYamlRead runs at Line [178], later calls can receive the synthetic error. The wrapper also remains installed after a successful test. Return a cleanup function or retain the original handler in main-process test state, then run cleanup in finally. Confirm that electronApp is not shared across tests.

Also applies to: 166-203


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 871cb52e-845b-4546-b2b9-ba391499aa08

📥 Commits

Reviewing files that changed from the base of the PR and between 3d5eccf and f133e3a.

📒 Files selected for processing (6)
  • mobile/src/session/MobileNativeChatOverlay.tsx
  • mobile/src/session/MobileNativeChatView.tsx
  • mobile/src/session/use-mobile-native-chat-session.test.ts
  • mobile/src/session/use-mobile-native-chat-session.ts
  • src/main/runtime/orca-runtime.ts
  • tests/e2e/setup-script-prompt-unreadable-orca-yaml.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • mobile/src/session/MobileNativeChatOverlay.tsx
  • mobile/src/session/use-mobile-native-chat-session.ts
  • mobile/src/session/MobileNativeChatView.tsx

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Fresh review + QA evidence at 308a7b5

Second-pass same-model review returned CLEAN after removing the two unrelated formatting-only files from the PR. The diff now contains exactly the six intended mobile files.

iOS Simulator — STA-3333 QA (iOS 26.5)

Paired to the repo mock host and exercised the real chat control on the loaded native-chat screen.

  • Five scroll-to-top gestures while the page was forced to fail produced exactly one nativeChat.readSession call.
  • The failure remained visible and automatic paging stayed suppressed.
  • One explicit tap on the retry header produced exactly one second call.
  • The retry loaded 60 earlier messages and removed the failure state.
  • Metro bundled the app without a redbox.
Failed page is visible and retryable Explicit retry recovers the earlier page
iOS failure state iOS recovered state

Electron no-regression smoke

Launched this worktree with an isolated user-data profile and attached through CDP. Orca rendered normally and the renderer console was empty.

Electron smoke

Verification

  • Mobile session suite: 118 files / 986 tests passed
  • Focused hook/view suite: 31 tests passed
  • Mobile TypeScript: passed
  • Changed-file oxlint and React Doctor: passed
  • origin/main...HEAD diff check: passed

@brennanb2025 brennanb2025 changed the title fix(mobile): surface load-earlier failures and stop scroll-retry storms (STA-3333) fix(native-chat): surface load-earlier failures and stop retry storms (STA-3333) Aug 5, 2026
@brennanb2025

brennanb2025 commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Final review at 450dc5de97: the same-model senior loop returned CLEAN with no further edits. Desktop and mobile still share one load-earlier controller; desktop prepend anchoring now follows the visible message across concurrent live-tail growth, clears on history-source swaps or user scrolls, and announces automatic paging failures through a polite live region.

Focused shared/desktop tests (56) and mobile tests (31), both typechecks, changed-code quality/React Doctor, max-lines, the full Node 24/26 matrix, static analysis, Git compatibility, and macOS/Windows packaging all pass. Electron CDP and iOS failure/recovery evidence remain embedded in the PR description.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing this old implementation and rebuilding the remaining phone history-loading fix on current main. Failed history loads should offer a retry and should not repeat automatically.

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