Repository navigation
fix(mobile): keep paged chat history coherent across reconnect replays (STA-3333) - #12494
Conversation
The transport replays nativeChat.subscribe with its original params after an in-place reconnect, and the session hook treated every snapshot as a fresh base — so a socket blip truncated paged-in history back to the initial 40. A replay snapshot that extends a contiguous retained tail now merges in by id; a disjoint replay (long outage, compaction while away) still replaces, since stitching would leave a silent gap. Only a genuinely replaced window resets the grown read limit and paging cursor, and any snapshot invalidates an in-flight older-page request so a stale cursor result cannot land on the new window. Refs STA-3333.
📝 WalkthroughWalkthroughThe native chat stream merger now validates reconnect snapshot continuity. Compatible replay tails merge with retained messages. Discontinuous or authoritative replays replace the message window and report 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
The scan's three rejection rules were unpinned: deleting the `sawNewMessage` guard, the ordering check, or the retained-tail anchor each left the whole suite green. Cover the interleaved-new-row, reordered-id, and short-of-tail cases, and the replaced-window hasMore fallback. Each new test is mutation-proven to kill exactly one mutant.
Two more branches of the replay logic were unpinned. Adopting a replay's `beforeOffset` when it starts partway into paged-in history would make the next loadEarlier re-fetch on-screen rows and prepend duplicates; treating a post-replacement snapshot as a replay would retain a row the authoritative window dropped. Both mutants now fail exactly one test.
There was a problem hiding this comment.
🧹 Nitpick comments (3)
mobile/src/session/mobile-native-chat-stream-frame.test.ts (1)
56-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTighten this assertion to
toEqual.This test is the one case where a trimmed replay must drop
beforeOffset: 20.toMatchObjectignores extra properties, so it would still pass if the implementation propagated the stale offset. Every neighbouring replay test usestoEqual.♻️ Proposed change
- expect(result).toMatchObject({ + expect(result).toEqual({ kind: 'messages', messages: [message('b'), message('c'), message('d')], cursorInvalidated: true, hasMore: true })mobile/src/session/use-mobile-native-chat-session.ts (1)
157-163: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider extracting the page-request invalidation.
Lines 160-162 and lines 181-183 repeat the same three statements. Both sites cancel an in-flight older-page request. A single local helper documents that one intent and keeps the two triggers from drifting.
♻️ Proposed change
+ const invalidatePageRequest = (): void => { + streamGenerationRef.current += 1 + loadingEarlierRef.current = false + setLoadingEarlier(false) + } if (applied.windowReplaced || frame.type === 'snapshot') { // Why: any authoritative window (and any replay merge) invalidates an // in-flight older-page request; stale results must not land on it. - streamGenerationRef.current += 1 - loadingEarlierRef.current = false - setLoadingEarlier(false) + invalidatePageRequest() }Then at lines 178-185:
if (applied.cursorInvalidated) { // Fall back to a growing-tail read so history trimmed by live appends // cannot leave a gap between the retained window and the old cursor. - streamGenerationRef.current += 1 - loadingEarlierRef.current = false - setLoadingEarlier(false) + invalidatePageRequest() beforeOffsetRef.current = null }mobile/src/session/use-mobile-native-chat-session.test.ts (1)
189-189: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename the local
windowfixture.
windowshadows the globalwindowbinding in three new tests (lines 189, 227, 263). The file also uses "window" for the retained message window, so the identifier reads ambiguously. Rename it tobaseWindowin each test.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e167ddfb-2cbe-406e-bdc2-f69470040dbd
📒 Files selected for processing (4)
mobile/src/session/mobile-native-chat-stream-frame.test.tsmobile/src/session/mobile-native-chat-stream-frame.tsmobile/src/session/use-mobile-native-chat-session.test.tsmobile/src/session/use-mobile-native-chat-session.ts
QA evidence — head
|
| App loaded | Workspaces created | Orca Mobile pane |
|---|---|---|
![]() |
![]() |
![]() |
Automation was CDP-only via playwright-cli. No Computer Use, AppleScript, OS-level automation, or input injection was used. The skill's optional macOS Dock-label check is osascript-based and was therefore skipped; instance identity was proven through window.api.app.getIdentity() over CDP instead, which is the stronger check for "did I attach to the right worktree".
What this does and does not prove. It proves the desktop app is healthy on this branch and that the host side of native chat is intact. It cannot exercise the changed code, which runs only in the React Native client — so it is a regression guard, not a validation of the fix.
Blast radius
The effective diff is 4 files, all under mobile/src/session/. The two changed source modules are imported only from within mobile/ (use-mobile-native-chat-controller.ts, MobileNativeChatView.tsx, mobile-native-chat-render-data.ts); nothing under src/ reaches them. The hook's exported type and signature are unchanged, and its only consumer's tests pass (15/15).
Host-side contract
The PR's "hasMore: false is authoritative" rule depends on the host meaning it literally. transcript-tail-reader.ts:109 computes hasMore as limit > 0 && chronological.length > limit with the read loop bounded at limit + 1, so false genuinely means the whole transcript fits in the window. Host suite green: src/main/native-chat + src/shared/native-chat-merge — 13 files, 113 tests passed.
Gates at this head
| Gate | Result |
|---|---|
tsc --noEmit (mobile) |
0 |
| Full mobile suite | 403 files, 3025 passed, 3 skipped |
src/session |
114 files, 918 passed |
| Host native-chat suite | 13 files, 113 passed |
oxlint |
0 |
oxfmt --check |
0 |
| React Doctor | 0 (no warnings on any of the 4 changed files) |
| max-lines ratchet | OK — no new bypasses, no max-lines disables |
| code-quality native plugins | 0 |
Mobile emulator QA — withheld, not failed
/orca-mobile-emulator-qa has not been run. A standing coordinator rule forbids booting or attaching any simulator without an explicit emulator-owner designation, after concurrent emulators wedged the machine twice. Four simulators are currently booted and at least two are sibling STA-3333 rigs actively driven by other agents; taking one would corrupt their run and produce unreliable evidence here (HID contention makes taps vanish intermittently). Designation has been requested; the freed slot is currently reserved for #12502. This will be run once a slot is granted.
Until then, the reconnect-replay path has no on-device evidence. The confidence above rests on the unit/mutation layer, not on a phone.
…eeping Two branches introduced by this PR survived the suite unpinned: - `firstIndex > 0` was only pinned one-directionally. Weakening it to `firstIndex > 1` kept all 28 tests green, so an off-by-one would silently retain one row the host had already dropped. - `snapshotSeenRef` is set only for snapshot frames. Setting it unconditionally is invisible in normal flows, where the first frame is the snapshot, but demotes the real base snapshot to a replay when a live append lands first. Each new test kills exactly one of those mutants and nothing else. No source change.
…play The snapshot arm of `if (applied.windowReplaced || frame.type === 'snapshot')` was unpinned: deleting it kept the suite green. It is load-bearing. A replay that merges cleanly can still carry a new `beforeOffset`, which the hook adopts via `replayStillStartsAtOldest`. The page already in flight was addressed with the old offset, so without the fence it lands and writes its own stale cursor back over the fresh one, leaving the next `loadEarlier` addressed from a byte offset that no longer describes the file. Row order alone stays correct, which is why the ordering-only reasoning missed this. Sole failure under the mutation. No source change.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
mobile/src/session/use-mobile-native-chat-session.test.ts (1)
350-352: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten the test comment.
Use one line that states the invariant. For example:
// A changed cursor invalidates the older-page request.Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 31fda04d-7897-4052-86d1-34bd22012084
📒 Files selected for processing (1)
mobile/src/session/use-mobile-native-chat-session.test.ts
| act(() => state?.loadEarlier()) | ||
|
|
||
| // The replay merges (same rows, no trim), but the host re-cut the file, so | ||
| // it carries a new cursor. The page already in flight was addressed with the | ||
| // old offset and would write that stale cursor back over the fresh one. | ||
| await act(async () => | ||
| emit({ type: 'snapshot', messages: retained, hasMore: true, beforeOffset: 250 }) | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Prove that the stale request was in flight before the replay.
This test passes if loadEarlier() returns without calling sendRequest. It also passes if the replay leaves loadingEarlier true until resolveEarlier() completes. Assert that the request started and loading is true before the replay. Assert that loading is false immediately after the replay.
Proposed test assertions
await mount({ sendRequest, subscribe } as unknown as RpcClient)
act(() => state?.loadEarlier())
+ expect(sendRequest).toHaveBeenCalledTimes(1)
+ expect(state?.loadingEarlier).toBe(true)
await act(async () =>
emit({ type: 'snapshot', messages: retained, hasMore: true, beforeOffset: 250 })
)
+ expect(state?.loadingEarlier).toBe(false)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| act(() => state?.loadEarlier()) | |
| // The replay merges (same rows, no trim), but the host re-cut the file, so | |
| // it carries a new cursor. The page already in flight was addressed with the | |
| // old offset and would write that stale cursor back over the fresh one. | |
| await act(async () => | |
| emit({ type: 'snapshot', messages: retained, hasMore: true, beforeOffset: 250 }) | |
| ) | |
| act(() => state?.loadEarlier()) | |
| expect(sendRequest).toHaveBeenCalledTimes(1) | |
| expect(state?.loadingEarlier).toBe(true) | |
| // The replay merges (same rows, no trim), but the host re-cut the file, so | |
| // it carries a new cursor. The page already in flight was addressed with the | |
| // old offset and would write that stale cursor back over the fresh one. | |
| await act(async () => | |
| emit({ type: 'snapshot', messages: retained, hasMore: true, beforeOffset: 250 }) | |
| ) | |
| expect(state?.loadingEarlier).toBe(false) |
Review summary — four independent passes, all resolvedReviewed at
What actually changed as a resultThree test-only commits —
Declined, with reasons
ScopeNo scope expansion. This PR remains only reconnect replay/history merging. It does not add manual reconnect cached-transcript behavior or any of the other nine STA-3333 fixes, and #12373 stays open. Gates at
|
Device QA — reconnect replay over paged-in history (iOS Simulator)Follow-up to the review comment above, which promised device QA evidence separately. Head under test: RigNo real desktop was involved. The mobile client paired to
The scenario patch was reverted before any commit; Provenance: the dev menu screenshot below shows the bundle came from my Metro on Result
ScreenshotsPR #12494 mobile reconnect-history QA (iOS Simulator)
Reading the evidence honestly
Electron desktop QA — not run, deliberatelyThe effective diff is four files, all under |
…s (STA-3333) (stablyai#12494) * fix(mobile): keep paged chat history coherent across reconnect replays The transport replays nativeChat.subscribe with its original params after an in-place reconnect, and the session hook treated every snapshot as a fresh base — so a socket blip truncated paged-in history back to the initial 40. A replay snapshot that extends a contiguous retained tail now merges in by id; a disjoint replay (long outage, compaction while away) still replaces, since stitching would leave a silent gap. Only a genuinely replaced window resets the grown read limit and paging cursor, and any snapshot invalidates an in-flight older-page request so a stale cursor result cannot land on the new window. Refs STA-3333. * test(mobile): pin the replay contiguity-scan rejection branches The scan's three rejection rules were unpinned: deleting the `sawNewMessage` guard, the ordering check, or the retained-tail anchor each left the whole suite green. Cover the interleaved-new-row, reordered-id, and short-of-tail cases, and the replaced-window hasMore fallback. Each new test is mutation-proven to kill exactly one mutant. * test(mobile): pin replay paging-metadata and base-snapshot authority Two more branches of the replay logic were unpinned. Adopting a replay's `beforeOffset` when it starts partway into paged-in history would make the next loadEarlier re-fetch on-screen rows and prepend duplicates; treating a post-replacement snapshot as a replay would retain a row the authoritative window dropped. Both mutants now fail exactly one test. * test(mobile): pin the replay removal boundary and base-snapshot bookkeeping Two branches introduced by this PR survived the suite unpinned: - `firstIndex > 0` was only pinned one-directionally. Weakening it to `firstIndex > 1` kept all 28 tests green, so an off-by-one would silently retain one row the host had already dropped. - `snapshotSeenRef` is set only for snapshot frames. Setting it unconditionally is invisible in normal flows, where the first frame is the snapshot, but demotes the real base snapshot to a replay when a live append lands first. Each new test kills exactly one of those mutants and nothing else. No source change. * test(mobile): pin the older-page fence against a cursor-re-cutting replay The snapshot arm of `if (applied.windowReplaced || frame.type === 'snapshot')` was unpinned: deleting it kept the suite green. It is load-bearing. A replay that merges cleanly can still carry a new `beforeOffset`, which the hook adopts via `replayStillStartsAtOldest`. The page already in flight was addressed with the old offset, so without the fence it lands and writes its own stale cursor back over the fresh one, leaving the next `loadEarlier` addressed from a byte offset that no longer describes the file. Row order alone stays correct, which is why the ordering-only reasoning missed this. Sole failure under the mutation. No source change.











Summary
Auto-reconnect no longer truncates native-chat history back to the initial 40 messages.
The mobile transport replays
nativeChat.subscribewith its original params after an in-place reconnect, so the replayedsnapshotis the newest initial window again. The session hook treated every snapshot as a fresh base and replaced the list — so after paging in older history, a socket blip silently threw that history away.The hook now tracks whether the current subscription already delivered its base snapshot; later snapshots on the same subscription are reconnect replays, and the frame applier decides how to fold them in:
hasMore: falseon a replay is authoritative: retained rows older than the replay window really were removed, so they are dropped even when the newest ids still match. A replay that still starts at our oldest retained row refresheshasMore/beforeOffset; a replay whose merge trimmed the window setshasMore: true, because a trim creates page-able history even if the previous window had none.beforeOffsetinstead of reusing it.Split from #12373 (the STA-3333 QA sweep), which bundled ten fixes. This PR is independent of that branch, targets
main, and carries only the reconnect replay/history-merge fix and its regression tests. The other fixes in #12373 — including the manual-reconnect cached-transcript UI behavior — are deliberately not included here. #12373 remains open and untouched.Refs STA-3333.
Screenshots
No visual change— this is transport/state-merge logic. The user-visible effect is the absence of a defect: scrolled-back history stays on screen through a reconnect instead of snapping back to the last 40 messages.Testing
pnpm lint— rootoxlintclean,audit:code-quality:nativeclean,check:max-lines-ratchetOK (no new bypasses, nomax-linesdisables added),oxlint --config config/oxlint-react-doctor.jsonclean on the changed source,oxfmt --checkcleanpnpm typecheck— mobiletsc --noEmitexit 0pnpm test— full mobile suite: 403 files, 3028 passed / 3 skipped;src/session: 114 files, 921 passed; the two directly affected spec files: 31 passed, no unhandled rejectionspnpm build— not run; no build-affecting changes (CI covers it)Tests are verified non-vacuous. With the spec files at this head and the two source files reverted to
main, 15 of the 31 tests in those files fail; all 31 pass with the fix. Reproduce by running the two spec files aftergit checkout $(git merge-base HEAD origin/main) -- mobile/src/session/mobile-native-chat-stream-frame.ts mobile/src/session/use-mobile-native-chat-session.ts.Whole-PR reversion is a deliberately weak probe for part of this change, because the pre-PR code often reached the same result by replacing on every snapshot. Tests that do not discriminate at that granularity are kept as contract locks and pinned by a targeted mutation instead — see below.
Every branch of the new logic is mutation-covered. Fourteen mutations of the changed source each turn the suite red: deleting the
sawNewMessageguard, the contiguity ordering check, the retained-tail anchor, thehasMore: falseauthoritative rule, thereplayStartIndex === 0metadata anchor, the!replaceSnapshotbase-snapshot gate, the trimmed-replayhasMore: truebranch,windowReplacedon the replace path, the>= INITIAL_LIMITfallback, thesnapshotSeenRefwrite (both deleting it and setting it unconditionally), the snapshot arm of the in-flight-page fence, and both directions of thefirstIndex > 0bound (>= 0and> 1). Each rejection branch is killed by exactly one test. The mutations that still survive are equivalent — they cannot change observable behavior — and are enumerated in Notes below.Frame-seam tests (
mobile-native-chat-stream-frame.test.ts): overlapping replay merges; disjoint replay replaces; a partially-overlapping replay that no longer extends the retained tail replaces; a replay repeating retained ids out of order replaces; a replay stopping short of the retained newest row replaces;hasMore: falsedrops retained older rows; a replay still starting at the oldest row refreshes paging metadata, while one starting partway into paged-in history does not adopt it; a trimming replay reportshasMore: true; a snapshot following areplacementstill replaces; a replay with exactly one dropped row ahead of it replaces (thefirstIndex > 0boundary);windowReplacedon first snapshot / replacement.Hook tests (
use-mobile-native-chat-session.test.ts): paged-in history (100 rows) survives a replay and a replay carrying a new message (bounded window trims exactly one oldest row); a trimming replay enables paging on a window that previously had none; an authoritative replay drops paged rows it says were removed; a replacement omitting paging metadata clears the stale cursor; a replaced window shorter than the initial page clearshasMore; a liveappendedframe arriving before the base snapshot does not demote that snapshot to a replay; a merging replay that re-cuts the byte cursor fences the older-page request already in flight. The pre-existingcan page again after an authoritative snapshot/replacement resets a maxed-out read windowtest still passes unchanged.AI Review Report
Reviewed with focus on:
replayRetainedTailStart) rejects every shape it cannot stitch: unknown first id, a gap in the middle, a new message followed by a known one (compaction reorder), and a run that does not reach the end of the retained list.hasMore: falsewith a non-zero start index is treated as authoritative removal rather than overlap.streamGenerationRef, so a resolvingnativeChat.readSessionfrom before the replay is dropped by the existing generation guard. ConfirmedbeforeOffsetRefis cleared (not left stale) when a replaced window omitsbeforeOffset, which was the latent bug behind a cursor pointing into a window that no longer exists.use-mobile-native-chat-controller.tsand all other consumers are untouched. No refactors, no style cleanup, no dependency changes —mobile/pnpm-lock.yamlwas reverted after a localpnpm installso no lockfile churn ships.Security Audit
No new untrusted-input parsing, no command execution, no path handling, no auth or secret handling, no dependency changes, and no new IPC/RPC surface (the fix reuses the existing
nativeChat.subscribe/nativeChat.readSessionmethods with unchanged params). The added logic is pure in-memory list reconciliation over message ids already present in frames the client accepted. Message ids are used only asMapkeys for dedup and ordering — never interpolated into a query, path, or command. The merge is bounded by the existing window cap (MAX_MESSAGES,boundNativeChatWindow), so a hostile or buggy host cannot use replay frames to grow the retained list without limit. No follow-up needed.Notes
replacementframe arriving before any snapshot still counts as a fresh base and does not mark the subscription's base snapshot as seen — matching the validated reference behavior.merger.list.length > 0precondition changes nothing — an empty retained list already fails the first-id lookup and reaches the same replace path. The same holds for the two!applied.windowReplacedguards onhasMore/beforeOffset(thewindowReplacedbranch has already assigned the same value from the same variable) and for thesnapshotSeenRefreset in the effect (masked becausesetList([])empties the merger before subscribing). These are defense-in-depth; no test can distinguish them.|| frame.type === 'snapshot'arm of the in-flight-page fence was previously described here as defensive rather than load-bearing. That was wrong. A replay can merge cleanly and carry a re-cutbeforeOffset, which the hook adopts viareplayStillStartsAtOldest; the page already in flight was addressed with the old offset, so without the fence it lands and writes its own stale cursor back over the fresh one, leaving the nextloadEarlieraddressed from an offset that no longer describes the file. Row order stays correct throughout, which is why ordering-only reasoning missed it. It is now pinned by a test that is the sole failure under that mutation.snapshotstill replaces the whole retained window, discarding paged-in history. This is identical to pre-PR behavior and is left unchanged here rather than pinned, since "an empty replay carries no information" is a defensible alternative reading and settling it belongs in its own change.