Skip to content

fix(mobile): native chat QA sweep — reconnect history, stale status, prompt-card and paging fixes (STA-3333) - #12373

Closed
brennanb2025 wants to merge 11 commits into
mainfrom
brennanb2025/sta-3333-chat-qa-sweep-fixes
Closed

brennanb2025 wants to merge 11 commits into
mainfrom
brennanb2025/sta-3333-chat-qa-sweep-fixes

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Fixes the confirmed defect list from the STA-3333 mobile native chat QA sweep (live QA + code-audit findings on the ticket):

  1. Auto-reconnect no longer truncates history to 40. The transport replays nativeChat.subscribe with its original params after an in-place reconnect, and the session hook treated every snapshot as replace-list. The hook now honors the snapshot-vs-replay distinction: a replay snapshot that overlaps retained history merges in by id (paged-in history survives the blip); a disjoint replay (long outage / compaction while away) falls back to replacing with the fresh authoritative window, since stitching would leave a silent gap.
  2. Manual retry keeps the cached transcript on screen. forceReconnect swaps to a new client identity; the hook now holds the last settled list for the same agent/session identity and keeps rendering it while the swapped client's read is in flight, instead of collapsing to a full-screen spinner. transcriptLoading still gates consumers (launch-draft seed) until the fresh read settles.
  3. Stale agent status is muted while disconnected. The working row renders dimmed as "Agent status stale" with the animation stopped, and Stop is disabled (a tap could not reach the PTY anyway). Shares the composer lock's 600 ms debounce so connection blips don't flicker it.
  4. Dismissed Ask cards stay dismissed across chat→terminal→chat toggles. Dismissal state moved from the unmounting view subtree into the controller, scoped per tab, and only resets when the prompt clears while the chat surface can actually observe it. Ask prompts also gained the same waiting/blocked gate the permission path already had, so a sticky prompt payload can't render as a live card while the agent is working/done.
  5. loadEarlier failures surface. RPC failure, error results, and rejected transport requests (previously an unhandled rejection) now set an inline "Couldn’t load earlier messages / Tap to retry" header row instead of silently doing nothing.
  6. No viewport jump on history prepend. The chat FlatList uses maintainVisibleContentPosition so a successful loadEarlier grows the list upward under a stable viewport.
  7. Answer-send abort paths report honestly. A chain aborted mid-answer (session swap, lease loss, supersede) after keystrokes already landed now reports "Answer partly sent — check chat before retrying" instead of leaving the card looking cleanly sent.
  8. PTY writes can no longer interleave. The per-terminal send-in-flight guard moved from the image-attachments hook into a shared module-scope write lock, now also taken by ask answers, permission responses, and question answers. A superseding answer inherits the cancelled chain's hold (refcounted) so changing your mind mid-answer still works; Stop/cancel stay unguarded so interrupts can't deadlock against the send they cancel.
  9. Streaming bubble no longer swallows repeated-prefix replies. A new streaming gate remembers which transcript tail predates the current stream segment: the bubble hides only when the tail moved during the segment and leads with the streamed text (genuine catch-up), never because an older turn happens to share the new reply's prefix. Falls back to the old suppress-on-prefix rule only when mounted mid-stream.
  10. Tool rows label with a clean summary. Expanded tool lines now show the target file path or primary string argument (command/query/pattern/…) instead of raw {"file_path":…} JSON; the expanded detail shows the fully formatted input (desktop parity).

MobileNativeChatView.tsx crossed the 400-line cap with these changes, so the load-earlier header and the streaming-bubble wiring were extracted into MobileNativeChatLoadEarlierHeader.tsx and use-mobile-native-chat-streaming-bubble.ts (no max-lines disables).

Coordination: written to compose with #12364 (STA-3331) and #12366 (STA-3332), which touch MobileNativeChatView.tsx, MobileNativeChatOverlay.tsx, and the controller and are expected to merge first. Their fixes (keyboardShouldPersistTaps, send classification, open-file flow) are not duplicated here. One small textual conflict is possible in the FlatList prop block of MobileNativeChatView.tsx against #12364 (adjacent added props); my side is a single maintainVisibleContentPosition line plus comment.

Refs STA-3333.

Screenshots

No visual change beyond the states described above (muted status row, error/retry header row, tool-row labels); not run on a simulator — see Notes.

Testing

  • pnpm lint (oxlint root + mobile, code-quality native/type-aware audits, max-lines ratchet, react-doctor changed-lines gate — all clean)
  • pnpm typecheck (root three-project tsc + mobile tsc)
  • pnpm test (mobile suite: 391 files, 2913 passed / 3 skipped; affected shared desktop tests pass)
  • pnpm build (not run — no build-affecting changes; CI covers it)
  • Added or updated high-quality tests per fix: replay merge/replace at the stream-frame seam and hook level, cached-transcript-across-swap, loadEarlier failure + retry, ask-dismiss toggle/tab-scope survival, ask blocked-gate, abort misreport, write-lock exclusion + supersede inheritance across all three card paths, streaming-gate scenarios (repeated-prefix, catch-up, part switch, mid-stream mount, idempotency), and describeToolInput labels.

AI Review Report

Self-reviewed with focus on: (1) reconnect-replay window semantics — verified the disjoint-replay fallback preserves the existing "authoritative snapshot resets a maxed-out window" behavior via the pre-existing tests; (2) write-lock deadlock/leak risks — a superseding answer inherits the hold via a per-hook refcount, only the last chain out releases, and Stop/cancel deliberately bypass the lock so interrupts can't deadlock; a hung holder is bounded by the send budget; (3) render purity — the streaming gate advances via the sanctioned render-time state-adjustment pattern (idempotent, settles in one pass) and the transcript cache is captured post-commit in an effect, both verified against the react-doctor changed-lines gate; (4) stale-list safety — the held list is keyed by the full agent/session/transcript identity, so it can never serve another tab's messages (locked by test). Cross-platform: no keyboard shortcuts, path handling, or shell behavior touched; changes are React Native UI/transport logic identical across iOS/Android clients and agnostic of the desktop host OS (native/WSL/SSH); the shared tool-summary change is pure string formatting with Windows-path-safe helpers already in place.

Security Audit

No new input parsing from untrusted sources, no command execution, no auth or secret handling. The write-lock module holds only terminal handles in memory. describeToolInput renders agent-provided strings through the existing bounded-preview truncation (length caps, depth caps, circular-safe) — no new injection surface since output is plain Text. The loadEarlier error string is a fixed literal, not server-echoed content. IPC/RPC surface unchanged (no new methods; the fix reuses existing subscribe/read RPCs).

Notes

  • The optional simulator smoke pass (MOCK_NATIVE_CHAT rig) was skipped — fixes are covered by unit tests at the pure seams; the device re-check of tap handling requested by STA-3331's PR is still outstanding.
  • Merge-replays are bounded by the grown window, so a replay carrying new tail messages trims the same number of oldest rows (cursor falls back to the growing-tail read, as with live-append trims).
  • The blocked gate on ask prompts means hosts that never publish agent status will not surface ask cards — this matches the pre-existing behavior of the permission and question cards.

…prompt-card and paging fixes (STA-3333)

Fixes the confirmed defect list from the STA-3333 QA sweep:
- reconnect replay snapshots merge into paged-in history instead of
  truncating to the initial window; disjoint replays replace it
- manual-retry client swaps keep rendering the cached transcript while
  the fresh read is in flight
- agent-working row mutes and Stop disables while disconnected
- ask-card dismissal lifted to the controller so it survives view
  toggles; ask prompts gated on waiting/blocked like permission
- loadEarlier failures surface an inline tap-to-retry row; FlatList
  anchors the viewport across prepends
- answer-send abort paths report partly-sent instead of ending silent
- per-terminal write lock shared across composer/answer/permission/
  question sends so PTY writes cannot interleave
- streaming bubble no longer swallows a genuine repeated-prefix reply
- tool rows label with the file path / primary arg instead of raw JSON
@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

The mobile native chat now preserves compatible replay history, replaces incompatible windows, and reports retryable earlier-message failures. Streaming bubbles use scoped gating. Ask prompts use agent status and scoped dismissal state. Terminal writes share per-terminal serialization across message, permission, answer, and image sends. The UI marks disconnected status as stale, disables Stop, adds pagination retry states, and improves tool input previews.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 39.47% 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 summarizes the mobile native chat fixes and identifies the QA sweep scope.
Description check ✅ Passed The description covers the required summary, screenshots, testing, AI review, security audit, and notes sections with specific validation 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.

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

🧹 Nitpick comments (1)
src/shared/native-chat-tool-summary.ts (1)

19-21: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten or remove the new explanatory comments.

  • src/shared/native-chat-tool-summary.ts#L19-L21: Replace the implementation summary with one concise non-obvious rationale, or remove it.
  • mobile/src/session/MobileNativeChatMessage.tsx#L92-L98: Remove comments that restate the adjacent preview and diff logic.
  • mobile/src/session/MobileNativeChatMessage.tsx#L137-L138: Remove the comment that restates the conditional render.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3d3ac546-0fa3-4ea9-8fa7-e1107faa47ce

📥 Commits

Reviewing files that changed from the base of the PR and between 637c7e9 and b8c4a89.

📒 Files selected for processing (32)
  • mobile/src/session/MobileAgentWorkingIndicator.tsx
  • mobile/src/session/MobileNativeChatLoadEarlierHeader.tsx
  • mobile/src/session/MobileNativeChatMessage.tsx
  • mobile/src/session/MobileNativeChatOverlay.tsx
  • mobile/src/session/MobileNativeChatView.test.ts
  • mobile/src/session/MobileNativeChatView.tsx
  • mobile/src/session/mobile-native-chat-permission-send.test.ts
  • mobile/src/session/mobile-native-chat-permission-send.ts
  • mobile/src/session/mobile-native-chat-render-data.ts
  • mobile/src/session/mobile-native-chat-stream-frame.test.ts
  • mobile/src/session/mobile-native-chat-stream-frame.ts
  • mobile/src/session/mobile-native-chat-streaming-gate.test.ts
  • mobile/src/session/mobile-native-chat-streaming-gate.ts
  • mobile/src/session/mobile-native-chat-terminal-write-lock.ts
  • mobile/src/session/mobile-native-chat-tool-summary.ts
  • mobile/src/session/mobile-native-chat-view-styles.ts
  • mobile/src/session/use-mobile-native-chat-answer-send.test.ts
  • mobile/src/session/use-mobile-native-chat-answer-send.ts
  • mobile/src/session/use-mobile-native-chat-ask-dismiss.test.ts
  • mobile/src/session/use-mobile-native-chat-ask-dismiss.ts
  • mobile/src/session/use-mobile-native-chat-controller.ts
  • mobile/src/session/use-mobile-native-chat-image-attachments.test.ts
  • mobile/src/session/use-mobile-native-chat-image-attachments.ts
  • mobile/src/session/use-mobile-native-chat-message-send.test.ts
  • mobile/src/session/use-mobile-native-chat-message-send.ts
  • mobile/src/session/use-mobile-native-chat-prompts.test.ts
  • mobile/src/session/use-mobile-native-chat-prompts.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-streaming-bubble.ts
  • src/shared/native-chat-tool-summary.test.ts
  • src/shared/native-chat-tool-summary.ts

Comment on lines +234 to +235
const requestIsCurrent = (): boolean =>
sessionIdRef.current === requestSessionId && streamGenerationRef.current === requestGeneration

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Validate the complete request identity before applying an older page.

requestIsCurrent checks only sessionId and streamGenerationRef. A host, workspace, client, agent, or transcript-path change can retain the same session ID. If the old request resolves before the passive effect increments streamGenerationRef, it can call setList with messages from the previous source.

Capture the request identity and client. Compare them with refs updated during render before mutating session state. Add a deferred-page test that changes sourceIdentity with the same session ID.

Comment thread src/shared/native-chat-tool-summary.ts Outdated
Comment on lines +29 to +32
const primary =
value.command ?? value.cmd ?? value.query ?? value.pattern ?? value.description ?? value.url
if (typeof primary === 'string' && primary.trim()) {
return summarizeToolInput(primary)

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

Select the first non-empty primary field.

An empty command prevents later valid fields from being selected. For example, { command: '', query: 'foo' } falls back to JSON instead of showing foo.

Proposed fix
-    const primary =
-      value.command ?? value.cmd ?? value.query ?? value.pattern ?? value.description ?? value.url
-    if (typeof primary === 'string' && primary.trim()) {
+    const primary = [
+      value.command,
+      value.cmd,
+      value.query,
+      value.pattern,
+      value.description,
+      value.url
+    ].find((candidate): candidate is string => typeof candidate === 'string' && candidate.trim())
+    if (primary) {
       return summarizeToolInput(primary)
     }

Add a regression test with an empty earlier field and a non-empty later field.

📝 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
const primary =
value.command ?? value.cmd ?? value.query ?? value.pattern ?? value.description ?? value.url
if (typeof primary === 'string' && primary.trim()) {
return summarizeToolInput(primary)
const primary = [
value.command,
value.cmd,
value.query,
value.pattern,
value.description,
value.url
].find((candidate): candidate is string => typeof candidate === 'string' && candidate.trim())
if (primary) {
return summarizeToolInput(primary)

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

226-248: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Make the history assertion independent and content-sensitive.

toHaveLength(100) does not verify that the 60 paged-* messages were retained or ordered correctly. The same window array is also passed into the session and reused as the expected value. If the implementation mutates an input array, the final assertion can pass incorrectly. Store the paged fixture separately, pass copies to both snapshots, and assert the exact merged sequence.

Suggested test hardening
+    const pagedMessages = Array.from({ length: 60 }, (_unused, index) => message(`paged-${index}`))
     const sendRequest = vi.fn().mockResolvedValue({
       ok: true,
       result: {
-        messages: Array.from({ length: 60 }, (_unused, index) => message(`paged-${index}`)),
+        messages: [...pagedMessages],
         hasMore: false,
         beforeOffset: 40
       }
     })
...
-      onData({ type: 'snapshot', messages: window, hasMore: true, beforeOffset: 100 })
+      onData({ type: 'snapshot', messages: [...window], hasMore: true, beforeOffset: 100 })
...
-    expect(state?.messages).toHaveLength(100)
+    expect(state?.messages).toEqual([...pagedMessages, ...window])
...
-      emit({ type: 'snapshot', messages: window, hasMore: false, beforeOffset: 0 })
+      emit({ type: 'snapshot', messages: [...window], hasMore: false, beforeOffset: 0 })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9d56bcb7-a309-41f6-97f4-0fbb6b175abb

📥 Commits

Reviewing files that changed from the base of the PR and between b8c4a89 and 4603ede.

📒 Files selected for processing (5)
  • 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-ask-dismiss.test.ts
  • mobile/src/session/use-mobile-native-chat-ask-dismiss.ts
  • mobile/src/session/use-mobile-native-chat-session.test.ts
🚧 Files skipped from review as they are similar to previous changes (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-ask-dismiss.ts
  • mobile/src/session/use-mobile-native-chat-ask-dismiss.test.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.

🧹 Nitpick comments (1)
mobile/src/session/MobileNativeChatView.test.ts (1)

169-192: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Exercise the rendered retry row.

The test calls ListHeaderComponent.props.onLoadEarlier() directly. It does not verify the error branch or the Pressable onPress path in MobileNativeChatLoadEarlierHeader. Assert the rendered error and retry text, invoke the rendered press handler, and then assert onLoadEarlier was called.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 270acf08-d39b-4ab9-b69b-2aba58d88de9

📥 Commits

Reviewing files that changed from the base of the PR and between 4603ede and 9fffa29.

📒 Files selected for processing (2)
  • mobile/src/session/MobileNativeChatView.test.ts
  • mobile/src/session/MobileNativeChatView.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • mobile/src/session/MobileNativeChatView.tsx

@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: 6099bccb-ac76-4edb-b17a-f719f751b5d9

📥 Commits

Reviewing files that changed from the base of the PR and between de958e6 and 693c0b9.

📒 Files selected for processing (8)
  • mobile/src/session/MobileNativeChatView.test.ts
  • mobile/src/session/MobileNativeChatView.tsx
  • mobile/src/session/use-mobile-native-chat-answer-send.test.ts
  • mobile/src/session/use-mobile-native-chat-answer-send.ts
  • mobile/src/session/use-mobile-native-chat-session.test.ts
  • mobile/src/session/use-mobile-native-chat-session.ts
  • src/shared/native-chat-tool-summary.test.ts
  • src/shared/native-chat-tool-summary.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/shared/native-chat-tool-summary.test.ts
  • mobile/src/session/use-mobile-native-chat-session.test.ts
  • mobile/src/session/use-mobile-native-chat-answer-send.test.ts
  • mobile/src/session/MobileNativeChatView.tsx
  • mobile/src/session/use-mobile-native-chat-answer-send.ts
  • mobile/src/session/use-mobile-native-chat-session.ts

Comment thread src/shared/native-chat-tool-summary.ts Resolved
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Final UI QA evidence — a8a4b17177f68926f4322a0bb4c5904627bf1668

  • Electron/CDP: launched this worktree through the repo dev runner on isolated renderer/CDP ports; window.api.app.getIdentity() matched brennanb2025/sta-3333-chat-qa-sweep-fixes and the exact worktree path. The full 1728×1005 Orca window rendered the real Mobile install/pairing flow with 0 console errors.
  • iOS native chat: iPhone 17 Pro simulator, Orca dev client, Metro bundle from this worktree. Completed encrypted pairing to the repo mock native-chat scenario, opened the live Claude tab, and sent STA-3333 mobile QA send accepted through the real composer. The UI rendered the queued user bubble and the mock server logged terminal.send mode=accept.
  • Android: not run; adb is unavailable on this host.

Desktop pairing context

Electron Orca Mobile pairing

Native chat loaded

iOS native chat loaded

Composer send accepted

iOS native chat sent

@brennanb2025

Copy link
Copy Markdown
Contributor Author

This omnibus PR has been split into one independent main-based PR per fix:

Each replacement PR is open and unmerged against main, has a clean independent child worktree, matches its pushed head, has green CI, and includes its review/QA evidence without committing screenshots to the diff. Each also completed the requested fresh Opus review loop through a substantive CLEAN pass; meaningful findings were fixed and re-reviewed.

Closing #12373 as superseded. Please review and merge the focused replacements independently.

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