Skip to content

fix(mobile): keep paged chat history coherent across reconnect replays (STA-3333) - #12494

Merged
brennanb2025 merged 5 commits into
mainfrom
brennanb2025/sta-3333-reconnect-history
Aug 4, 2026
Merged

brennanb2025 merged 5 commits into
mainfrom
brennanb2025/sta-3333-reconnect-history

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Auto-reconnect no longer truncates native-chat history back to the initial 40 messages.

The mobile transport replays nativeChat.subscribe with its original params after an in-place reconnect, so the replayed snapshot is 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:

  • Overlapping replay — a replay that extends a contiguous retained tail merges in by id, so paged-in history survives the blip.
  • Disjoint replay (long outage, compaction while away) — cannot be stitched without a silent gap, so it falls back to the fresh authoritative window.
  • Authoritative paging metadata — hasMore: false on 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 refreshes hasMore/beforeOffset; a replay whose merge trimmed the window sets hasMore: true, because a trim creates page-able history even if the previous window had none.
  • Stale-cursor avoidance — only a genuinely replaced window resets the grown read limit and cursor (an overlapping replay keeps both). Any snapshot bumps the stream generation so an in-flight older-page request cannot land its result on the new window, and a replaced window that carries no paging metadata clears the stale beforeOffset instead 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 — root oxlint clean, audit:code-quality:native clean, check:max-lines-ratchet OK (no new bypasses, no max-lines disables added), oxlint --config config/oxlint-react-doctor.json clean on the changed source, oxfmt --check clean
  • pnpm typecheck — mobile tsc --noEmit exit 0
  • pnpm 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 rejections
  • pnpm build — not run; no build-affecting changes (CI covers it)
  • Added or updated high-quality tests that would catch regressions

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 after git 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 sawNewMessage guard, the contiguity ordering check, the retained-tail anchor, the hasMore: false authoritative rule, the replayStartIndex === 0 metadata anchor, the !replaceSnapshot base-snapshot gate, the trimmed-replay hasMore: true branch, windowReplaced on the replace path, the >= INITIAL_LIMIT fallback, the snapshotSeenRef write (both deleting it and setting it unconditionally), the snapshot arm of the in-flight-page fence, and both directions of the firstIndex > 0 bound (>= 0 and > 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: false drops 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 reports hasMore: true; a snapshot following a replacement still replaces; a replay with exactly one dropped row ahead of it replaces (the firstIndex > 0 boundary); windowReplaced on 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 clears hasMore; a live appended frame 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-existing can page again after an authoritative snapshot/replacement resets a maxed-out read window test still passes unchanged.

AI Review Report

Reviewed with focus on:

  1. Replay-window semantics. Verified the disjoint-replay fallback preserves the pre-existing "authoritative snapshot resets a maxed-out window" behavior — that test passes unmodified. Checked the contiguity scan (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: false with a non-zero start index is treated as authoritative removal rather than overlap.
  2. Stale-cursor / in-flight paging safety. Every snapshot (merged or replaced) bumps streamGenerationRef, so a resolving nativeChat.readSession from before the replay is dropped by the existing generation guard. Confirmed beforeOffsetRef is cleared (not left stale) when a replaced window omits beforeOffset, which was the latent bug behind a cursor pointing into a window that no longer exists.
  3. Scope containment. The hook's public signature and return type are unchanged, so use-mobile-native-chat-controller.ts and all other consumers are untouched. No refactors, no style cleanup, no dependency changes — mobile/pnpm-lock.yaml was reverted after a local pnpm install so no lockfile churn ships.
  4. Render purity. No new state, effects, or render-time writes were added to the hook; the change is confined to refs and the existing subscription callback. Confirmed against the react-doctor gate.
  5. Cross-platform compatibility (macOS, Linux, Windows). Explicitly checked: this PR touches no keyboard shortcuts or accelerators, no shortcut labels, no file paths or path joining, no shell or process invocation, no Git commands, and no Electron main/renderer or IPC surface. The changed code is React Native transport/state logic that is byte-identical across iOS and Android clients and agnostic of the desktop host OS. It is equally correct over SSH and relay connections — reconnect replay is precisely the SSH/remote case this fixes — and makes no assumption that a workspace is a git worktree rather than a folder workspace.

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.readSession methods 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 as Map keys 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

  • Merge-replays stay bounded by the grown window, so a replay carrying new tail messages trims the same number of oldest rows; the cursor then falls back to the growing-tail read, matching existing live-append trim behavior.
  • A replacement frame 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.
  • The mutants that still survive are equivalent, not uncovered. Dropping the merger.list.length > 0 precondition 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.windowReplaced guards on hasMore/beforeOffset (the windowReplaced branch has already assigned the same value from the same variable) and for the snapshotSeenRef reset in the effect (masked because setList([]) empties the merger before subscribing). These are defense-in-depth; no test can distinguish them.
  • Correction to an earlier revision of this description. The || 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-cut 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 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.
  • An empty replay snapshot still 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.
  • Split from fix(mobile): native chat QA sweep — reconnect history, stale status, prompt-card and paging fixes (STA-3333) #12373; the remaining fixes in that PR (manual-reconnect cached transcript, stale agent status, ask-card dismissal, loadEarlier error surfacing, viewport anchoring, answer-send abort reporting, PTY write lock, streaming bubble, tool-row labels) are out of scope here and stay with fix(mobile): native chat QA sweep — reconnect history, stale status, prompt-card and paging fixes (STA-3333) #12373.

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

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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 windowReplaced. The session hook distinguishes initial snapshots from reconnect snapshots, preserves paged history during merges, invalidates stale pagination requests, and recalculates cursor, offset, and hasMore metadata. Tests cover merging, truncation, ordering, removal, and replacement behavior.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 fix for preserving paged chat history across reconnect replays.
Description check ✅ Passed The description covers the required sections, explains the change, documents testing and limitations, and includes AI review and security audit details.
✨ Finishing Touches
📝 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.

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.

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

56-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Tighten this assertion to toEqual.

This test is the one case where a trimmed replay must drop beforeOffset: 20. toMatchObject ignores extra properties, so it would still pass if the implementation propagated the stale offset. Every neighbouring replay test uses toEqual.

♻️ 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 value

Consider 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 value

Rename the local window fixture.

window shadows the global window binding 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 to baseWindow in each test.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e167ddfb-2cbe-406e-bdc2-f69470040dbd

📥 Commits

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

📒 Files selected for processing (4)
  • mobile/src/session/mobile-native-chat-stream-frame.test.ts
  • mobile/src/session/mobile-native-chat-stream-frame.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

QA evidence — head c502643bc10c11857bbf8670c5ac6c93c560a59e

Electron desktop QA (/electron)

Launched this worktree's dev build on an isolated temp profile (CDP 9336, renderer 5176 — 5173 was held by a sibling worktree and was left untouched), attached over CDP, and confirmed the instance identity before driving anything:

devRepoRoot: /Users/brennanbenson/orca/workspaces/orca/sta-3333-reconnect-history
devBranch:   brennanb2025/sta-3333-reconnect-history

Drove real store actions — repos.add on a disposable fixture repo, then createWorktree — and the sidebar rendered both workspaces. Console: 0 errors (3 warnings, all pre-existing: two Radix tooltip controlled/uncontrolled, one React Grab version notice).

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.

@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

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

350-352: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5274327 and 8f7642e.

📒 Files selected for processing (1)
  • mobile/src/session/use-mobile-native-chat-session.test.ts

Comment on lines +348 to +355
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 })
)

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.

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

Suggested change
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)

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review summary — four independent passes, all resolved

Reviewed at 8f7642e7ed by four fresh same-model subagents, each with its own mutation/property harness. Net result: no source change was needed beyond the original PR; three test-only commits closed real coverage gaps the passes found, and one claim in the PR description turned out to be wrong and has been corrected.

Pass Verdict Outcome
review-perf-1 CLEAN No added renders or allocations. The merge path is O(incoming) against the cached indexById; replayRetainedTailStart is a single bounded scan of the replay window (≤ limit), not of retained history. No new effect, subscription, or dependency.
review-fresh-1 CLEAN 22 mutants + a 4000-seed randomized property harness over replay/retain interleavings. Found one real coverage gap at the firstIndex > 1 boundary.
review-correctness-1 ISSUES → resolved Reviewed a stale checkout (23 tests; head had 28). Both recommended fixes were already implemented; both mutants it claimed survived were re-run at head and died. Its three nits were verified pre-existing against the effective diff.
review-tests-1 ISSUES (2) → 1 fixed, 1 declined Finding #1 accepted and fixed. Finding #2 declined with reasons (below).

What actually changed as a result

Three test-only commits — git diff main..HEAD -- 'mobile/src/session/*.ts' ':!*.test.ts' is unchanged from the original PR.

  1. firstIndex > 1 boundary (review-fresh-1). The authoritative-removal rule was only pinned at firstIndex === 2, so weakening it to firstIndex > 1 survived. A single retained row preceding an authoritative replay is still a dropped row. Now pinned.
  2. Base-snapshot ordering. A live appended frame arriving before the base snapshot must not flip snapshotSeenRef and demote the real base snapshot to a reconnect replay.
  3. The in-flight-page fence (review-tests-1 Linux support #1) — the one I got wrong. I initially rejected this: on a merge without a trim, list[0] doesn't move, so an in-flight page would still splice in correct order. That reasoning is right about ordering and misses the cursor. When replayStillStartsAtOldest holds, the hook adopts the replay's re-cut beforeOffset; the page already in flight was addressed with the old offset and, without the fence, writes its own stale result.beforeOffset back over the fresh one — leaving the next loadEarlier reading from an offset that no longer describes the file. So || frame.type === 'snapshot' is load-bearing, not defensive. Pinned by a test that is the sole failure under that mutation, and the PR description has been corrected.

Declined, with reasons

  • Empty replay snapshot wipes retained history (review-tests-1 Fix Ctrl+Backspace not deleting word in terminal #2). Real, but pre-existing and byte-identical to the merge base — outside this PR's scope. Pinning it would also lock in behavior that is arguably wrong ("an empty replay carries no information" is a defensible alternative reading). Called out in Notes instead so it isn't silently inherited.
  • A 33-page 'older' fixture reshape. Cosmetic; the existing assertion already guards the limitRef arithmetic it was meant to protect.
  • review-tests-1's first framing of the fence issue, which pinned the wart rather than the behavior. It returned a materially reframed version with a re-cut beforeOffset (100 → 250); that one was verified and accepted.

Scope

No 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 8f7642e7ed

tsc exit 0 · full mobile suite 403 files / 3028 passed / 3 skipped · src/session 114 files / 921 passed · max-lines ratchet OK · oxlint + React Doctor + oxfmt clean · CI 42 SUCCESS / 1 SKIPPED.

Electron and device QA evidence follows in a separate comment.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

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: 8f7642e7edf6ff406372cae3a958bef033702282
Control: e9cf106769 (git merge-base HEAD origin/main) — same rig, same replay, same taps.

Rig

No real desktop was involved. The mobile client paired to mobile/scripts/mock-server.ts over a hand-minted v2 pairing offer (full E2EE handshake), with a throwaway scenario patch that serves a 200-row synthetic transcript where the array index doubles as the beforeOffset byte cursor:

  • nativeChat.subscribe emits the newest 40 rows as a snapshot with hasMore / beforeOffset, then re-emits the same subscription's snapshot when a $TMPDIR control file's epoch changes — i.e. exactly the in-place reconnect replay this PR is about.
  • nativeChat.readSession serves [start, before) slices so loadEarlier pages backwards for real.

The scenario patch was reverted before any commit; git status --porcelain is empty at the head above and the branch is unchanged.

Provenance: the dev menu screenshot below shows the bundle came from my Metro on 127.0.0.1:8111 in this worktree, not a sibling agent's 8081.

Result

after paging in 3 older pages (200 rows, top = HISTORY LINE 0) after an identical replay snapshot (extra=2, total 202)
PR head 8f7642e7ed HISTORY LINE 0 at top HISTORY LINE 0 still at top, scroll position unchanged; bottom shows HISTORY LINE 194…199 → RECONNECT TURN 1 → RECONNECT TURN 2 — contiguous merge. PASS
Pre-fix e9cf106769 HISTORY LINE 0 at top collapses to Load earlier messages + HISTORY LINE 162 — all 162 paged-in rows discarded. Bug reproduced

Screenshots

PR #12494 mobile reconnect-history QA (iOS Simulator)

01 — provenance: Metro 127.0.0.1:8111 02 — chat view live on the fixture
01 02
03 — paged in to the oldest row (HISTORY LINE 0) 04 — PR head, top of list, immediately before the replay
03 04
05 — PR head, top of list after the replay (PASS) 06 — PR head, bottom: LINE 199 + both RECONNECT TURN rows
05 06
07 — pre-fix control, top of list before the replay 08 — pre-fix control after the replay (collapsed to LINE 162)
07 08

Reading the evidence honestly

  • 04 and 05 are byte-identical (both md5 a9bfaa9d455809f6f3b17084644cdae6). That identity is the pass criterion — the replay changed nothing at the top of the retained window — but on its own it cannot distinguish "the replay merged cleanly" from "the replay had not landed yet." Two independent facts close that gap: 06, taken after 05, shows RECONNECT TURN 1 and RECONNECT TURN 2 at the bottom, so the replay demonstrably had landed; and the control run (07 → 08, distinct hashes) shows the same tap sequence and the same timing produce a visible collapse on the pre-fix build.
  • The A/B was run on one dedicated simulator (STA-3333 ReconnectHistory QA), booted for this PR and deleted afterwards. No pre-existing device or helper process was touched.
  • Interaction was via serve-sim binary touch frames only — no Computer Use, AppleScript, OS-level automation, or input injection.

Electron desktop QA — not run, deliberately

The effective diff is four files, all under mobile/src/session/, and every importer of the two changed modules is also under mobile/src/session/ (use-mobile-native-chat-controller.ts, mobile-native-chat-render-data.ts, MobileNativeChatView.tsx, plus tests). The Electron app does not bundle mobile/, so a desktop run cannot exercise a single changed line — the screenshots would be decorative. Launching a second Electron dev instance on this machine also risks clobbering the running dev identity and other in-flight sessions. Flagging the gap explicitly rather than substituting evidence that proves nothing; happy to run it if you want it on the record anyway.

@brennanb2025
brennanb2025 merged commit 535b5a5 into main Aug 4, 2026
43 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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