Skip to content

fix(mobile): keep the chat viewport steady when history pages in (STA-3333) - #12500

Closed
brennanb2025 wants to merge 11 commits into
mainfrom
brennanb2025/sta-3333-prepend-anchor
Closed

brennanb2025 wants to merge 11 commits into
mainfrom
brennanb2025/sta-3333-prepend-anchor

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Paging older native-chat history now preserves the reader's viewport without relying on a timed hold or a render-observed loading transition.

  • loadEarlier returns an explicit Promise<boolean> | null, so tail-follow ownership settles from the actual page result. This cannot wedge when React batches away the intermediate loading render.
  • Transcript replacement and reconnect frames promptly settle invalidated page attempts, so a stale RPC cannot suppress the next retry while generation guards still prevent it from mutating the new window.
  • maintainVisibleContentPosition remains the native prepend anchor, with a module-stable config object.
  • Drag intent remains detached through the drag-to-momentum ownership window, so content growth during that handoff cannot snap the list back to the tail.
  • Desktop and mobile now share the allocation-free scroll geometry predicates in src/shared/native-chat-scroll-geometry.ts. Their DOM and React Native anchoring adapters remain separate because the platform event models are materially different.

The change is intentionally limited to native-chat paging and scroll-follow behavior. It does not alter transcript parsing, transport protocols, or unrelated mobile/desktop UI.

Refs STA-3333.

Screenshots

Existing iOS branch evidence shows the initial tail and the same viewport after older messages prepend:

Before paging After paging — reader held in place
Before paging After paging

Fresh Electron/CDP smoke on the final branch:

Electron desktop smoke

Testing

  • Final CI on 60df189c10: 42 successful, 0 failed, 1 intentionally skipped
  • Mobile Vitest suite: 411 files passed, 3,140 tests passed, 3 skipped
  • Shared geometry tests: 5 passed
  • Mobile TypeScript: clean
  • Desktop/web TypeScript: clean
  • Changed-file lint and formatting: clean
  • Max-lines ratchet: clean; no disable or per-file bump added
  • git diff --check: clean
  • Electron/CDP smoke: final branch rendered successfully; screenshot above
  • iOS branch bundle loaded and completed an encrypted mock-host connection
  • Fresh iOS screenshot rerun: the isolated Orca dev runtime exited twice after emulator attachment, so the existing before/after evidence is retained rather than substituting raw or OS-level automation
  • Android device QA: unavailable because adb is not installed in this environment

Review and performance

The final patch completed an iterative same-model senior review and the repeat pass returned CLEAN.

The scroll hot path remains O(1). The shared geometry API takes positional numbers, avoiding temporary geometry-object allocations on scroll events. No polling, subscription, or unbounded timer was added. Pagination creates one completion promise per user-requested page, and gesture/tail timers remain bounded and cleaned up on identity changes and unmount.

Security

No new input parsing, command execution, path handling, authentication, dependency, IPC, or RPC surface is introduced.

Tapping "Load earlier messages" grew the list from the top while the
viewport stayed at a fixed offset, so the reader was thrown into the
middle of the newly-prepended page.

Anchor the FlatList with maintainVisibleContentPosition so a prepend
grows upward, and hold the two tail-follow paths (the post-commit
autoscroll effect and onContentSizeChange) for the duration of the
page-in. The hold matters on short transcripts, where the reader is
simultaneously at the top and `atBottom` — there the autoscroll would
otherwise immediately undo the anchoring.

Refs STA-3333.
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The mobile chat now uses useMobileNativeChatTailFollow to coordinate tail scrolling, gestures, momentum, pagination, content-size changes, and conversation changes. Earlier-history loading returns completion status. The controller supplies a conversation identity to reset state between conversations. The chat view preserves visible content during prepends and uses shared input-lock handling. Shared scroll geometry utilities now support the native message list. Tests cover pagination, delayed and rejected loads, gesture behavior, latest-message actions, and conversation changes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the mobile chat viewport fix during history pagination.
Description check ✅ Passed The description covers the change, testing, screenshots, performance, and security, but omits the required Notes section and complete AI review details.
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.
✨ 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.

The tail-follow positive control never drove a paging cycle, so a hold that
latched on — chat permanently unable to follow the agent, the worst failure
mode of this design — passed the whole suite. Drive the real
loadingEarlier -> prepend -> settled sequence before the append.

Also record why onContentSizeChange reads the render snapshot instead of the
ref: effects flush before native layout, so the ref is already cleared there.
The hold was a per-render snapshot of `loadingEarlier`, so it survived
exactly one commit. Any render landing between the prepend and its native
content-size event -- a streaming tick at 50ms, a keystroke, an
agentWorking flip -- rebuilt `onContentSizeChange` with the hold already
cleared, and that handler then scrolled to the bottom, undoing the
anchoring maintainVisibleContentPosition had just performed. Reproduced
with a single unrelated re-render inserted before the layout pass.

Re-key it as a latch owned by a small hook: armed when a page is
requested, re-armed when it is delivered, and consumed by the layout pass
the prepend produces. An interleaved render can no longer drop it, and the
effect-ordering dependency the old design relied on is gone.

Arming on request also covers a hole the snapshot never did: swapping the
spinner into the header resizes it, and that layout pass scrolled the
reader to the bottom the moment they tapped "Load earlier".

A page can prepend nothing -- failed, empty, or resolved onto a swapped
session -- and then no layout pass arrives to consume the hold, so it
expires on its own; a latched hold would leave the chat permanently unable
to follow the agent.

Lives in its own hook because the view is at 388/400 effective lines.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: adb4c4f0-62e1-4d4b-aff2-e037fd1d40b5

📥 Commits

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

📒 Files selected for processing (3)
  • mobile/src/session/MobileNativeChatView.test.ts
  • mobile/src/session/MobileNativeChatView.tsx
  • mobile/src/session/use-mobile-native-chat-history-hold.ts

A prepend does not produce exactly one layout pass. onContentSizeChange is a
raw pass-through of the content container's onLayout with no dedup, and
VirtualizedList re-renders as cells measure and its spacer estimates are
revised, so a hold that any single pass could retire let a later pass scroll
the reader to the bottom of the history they had just paged in.

Hold for a bounded window instead, re-armed on delivery so a slow round trip
is covered, and skip arming tail-follow at all while held so an append late in
the window cannot fire once the window lapses.
…-prepend-anchor

# Conflicts:
#	mobile/src/session/MobileNativeChatView.test.ts
#	mobile/src/session/MobileNativeChatView.tsx
#	mobile/src/session/use-mobile-native-chat-controller.ts
@coderabbitai

coderabbitai Bot commented Aug 5, 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8b5e9ceb-a44e-4c3c-819e-97a566b08f49

📥 Commits

Reviewing files that changed from the base of the PR and between dc5c5a8 and cb5ceb7.

📒 Files selected for processing (7)
  • mobile/src/session/MobileNativeChatOverlay.tsx
  • mobile/src/session/MobileNativeChatView.test.ts
  • mobile/src/session/MobileNativeChatView.tsx
  • mobile/src/session/use-mobile-native-chat-controller.ts
  • mobile/src/session/use-mobile-native-chat-session.test.ts
  • mobile/src/session/use-mobile-native-chat-session.ts
  • mobile/src/session/use-mobile-native-chat-tail-follow.ts

@coderabbitai

coderabbitai Bot commented Aug 6, 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/MobileNativeChatView.test.ts (1)

560-576: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Rename this test and add a case for a rejected completion promise.

The callback at Line 563 returns null. In useMobileNativeChatTailFollow, null means the request never started, which is a different branch from a rejection. The current name describes a rejection that the test does not exercise.

requestHistory also installs a rejection handler for the completion promise. No test covers that handler, so a regression there would pass CI.

Rename this test to describe the declined start. Add a second test that resolves the request with a rejected promise and asserts that tail-follow is restored.

💚 Proposed rename and added coverage
-  it('restores tail-follow when a history request is rejected synchronously', async () => {
+  it('restores tail-follow when a history request declines to start', async () => {
     vi.useFakeTimers()
     try {
       const onLoadEarlier = vi.fn(() => null)
       await render({ messages: [message], hasMore: true, onLoadEarlier })
       await act(async () => vi.runAllTimersAsync())
       scrollToEnd.mockClear()
 
       act(() => list().props.ListHeaderComponent.props.onPress())
       await act(async () => vi.runAllTimersAsync())
 
       expect(onLoadEarlier).toHaveBeenCalledOnce()
       expect(scrollToEnd).toHaveBeenCalled()
     } finally {
       vi.useRealTimers()
     }
   })
+
+  it('restores tail-follow when a history request rejects', async () => {
+    vi.useFakeTimers()
+    try {
+      const onLoadEarlier = vi.fn(() => Promise.reject(new Error('page failed')))
+      await render({ messages: [message], hasMore: true, onLoadEarlier })
+      await act(async () => vi.runAllTimersAsync())
+      scrollToEnd.mockClear()
+
+      act(pressLoadEarlier)
+      await act(async () => {
+        await Promise.resolve()
+      })
+      await act(async () => vi.runAllTimersAsync())
+
+      expect(onLoadEarlier).toHaveBeenCalledOnce()
+      expect(scrollToEnd).toHaveBeenCalled()
+    } finally {
+      vi.useRealTimers()
+    }
+  })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c2c960f7-4315-4bfc-8ed9-60ff87599dc6

📥 Commits

Reviewing files that changed from the base of the PR and between b70e337 and 6316315.

📒 Files selected for processing (17)
  • mobile/src/session/MobileNativeChatOverlay.tsx
  • mobile/src/session/MobileNativeChatView.test.ts
  • mobile/src/session/MobileNativeChatView.tsx
  • mobile/src/session/mobile-native-chat-controller-contract.ts
  • mobile/src/session/use-mobile-native-chat-controller.ts
  • mobile/src/session/use-mobile-native-chat-input-lease.ts
  • mobile/src/session/use-mobile-native-chat-input-lock.ts
  • mobile/src/session/use-mobile-native-chat-session.test.ts
  • mobile/src/session/use-mobile-native-chat-session.ts
  • mobile/src/session/use-mobile-native-chat-tail-follow.ts
  • src/main/runtime/rpc/remote-runtime-server-heartbeat-missed-probe-tolerance.test.ts
  • src/renderer/src/components/native-chat/NativeChatMessageList.tsx
  • src/renderer/src/components/native-chat/native-chat-autoscroll.test.ts
  • src/renderer/src/components/native-chat/native-chat-autoscroll.ts
  • src/shared/native-chat-scroll-geometry.test.ts
  • src/shared/native-chat-scroll-geometry.ts
  • src/shared/remote-runtime-shared-control-state.ts
💤 Files with no reviewable changes (3)
  • src/renderer/src/components/native-chat/native-chat-autoscroll.ts
  • src/renderer/src/components/native-chat/native-chat-autoscroll.test.ts
  • src/shared/remote-runtime-shared-control-state.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-controller.ts
  • mobile/src/session/use-mobile-native-chat-session.test.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Close this older scrolling implementation while retaining the work to keep the reader in place when older phone chat messages load. It needs to fit the current chat list.

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