Repository navigation
fix(mobile): keep repeated-prefix native chat replies streaming (STA-3333) - #12501
Conversation
Text alone can't tell "the transcript caught up with this stream" from "a new reply repeats the previous turn's prefix", so the old suppress-on- prefix rule swallowed genuine repeated replies. A stateful gate remembers which transcript tail predates the current stream segment and hides the bubble only when that tail moved during the segment, scoped to the active host/workspace/tab/session so a swapped chat can't inherit a baseline. Refs STA-3333.
📝 WalkthroughWalkthroughThe mobile native chat now uses a stateful streaming gate to suppress duplicate transcript content. The controller exposes stream liveness and a session scope key. The overlay derives gated streaming state before visibility checks and passes folded messages to the view. The chat view renders pre-folded messages and nullable streaming text. Tests cover repeated replies, hidden views, stream changes, transcript landing, mounting, and streaming row placement. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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 gate lived in MobileNativeChatView, but MobileNativeChatOverlay returns null whenever the user peeks at the terminal — that unmounts the view and throws the baseline away, so the repeated-prefix reply was swallowed again on the way back. Move the gate (and the fold memo it reads) up to the overlay, which stays mounted across those toggles. While hidden the transcript is empty and the throttled stream reports no text, which the gate would have read as "idle" and re-anchored on. Pass the agent's working state so a textless tick inside a live segment holds the baseline instead. The scope key is now keyed off the tab rather than the view-gated chat resolution, so it survives the toggle too; streamIdentity keeps its exact previous value because the delayed-send guards compare against it. Also drops a dead disjunct in the caught-up test: a null baseline is already unequal to every real tail id.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
mobile/src/session/use-mobile-native-chat-controller.test.ts (1)
443-478: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the shared harness and the deprecation-warning suppression.
This suite repeats the
Harnesscomponent and theconsole.errorfilter that the earlier suite in this file already defines. The only difference isactiveSessionTab. Extract one harness factory that accepts the tab plus onesuppressRendererWarninghelper, then reuse both. A third suite would otherwise copy the same block again.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 47fe5a2c-2543-473e-800b-3c35167611bf
📒 Files selected for processing (10)
mobile/src/session/MobileNativeChatOverlay.test.tsmobile/src/session/MobileNativeChatOverlay.tsxmobile/src/session/MobileNativeChatView.test.tsmobile/src/session/MobileNativeChatView.tsxmobile/src/session/mobile-native-chat-render-data.tsmobile/src/session/mobile-native-chat-streaming-gate.test.tsmobile/src/session/mobile-native-chat-streaming-gate.tsmobile/src/session/use-mobile-native-chat-controller.test.tsmobile/src/session/use-mobile-native-chat-controller.tsmobile/src/session/use-mobile-native-chat-streaming-bubble.ts
…ests The overlay regression test replayed the transcript before the stream text on the way back from the terminal view. That ordering is backwards: the session withholds `messages` until a fresh read settles (an RPC round trip) while the throttled stream text returns in ~50ms — and with the transcript already back, a gate that got discarded on the toggle still passes. Replay the real order, which pins the gate's lifetime as intended. Swaps the hidden-gap duplicate case for the in-view one (a tool frame clears the assistant text mid-turn), which is where the hold actually earns its keep; the hidden-gap direction stays covered at the gate level.
A textless status tick was re-anchoring the gate's pre-stream baseline, so two paths still rendered wrong: - The reply's transcript push beats its throttled status text whenever the pane stays `working` past the turn (a live subagent or background task). The tick in between adopted the just-landed reply as history, and the status text that followed rendered it a second time — a duplicate bubble, and a regression against main's suppress-on-prefix rule. - Peeking at the terminal between turns empties the transcript. That empty tail was adopted as the baseline, so the next repeated-prefix reply was swallowed again — the bug this PR exists to fix. Only a tick that carries a real tail and sits outside a live turn anchors now, with an exception for a gate that has never anchored: mounted mid-turn, the first real tail it sees is the best history it will ever get. Also drop `buildMobileNativeChatData`, a test-only builder this PR had wired the new gate into; its green test asserted the exact suppression this PR removes. Its fold/pending/image coverage moves to the builder the view calls.
Mutation testing found the `prevText` reset on an anchoring textless tick unpinned: keeping the previous turn's text there reads the next turn's opener as a new segment, re-anchors onto the reply that just landed, and renders it a second time — the same duplicate-bubble class already fixed twice on this branch.
Follow-ups found during review — deliberately not in this PRFour things surfaced across the review passes. None is a regression from this change and none belongs in this diff, so they're recorded here rather than fixed. 1. A duplicate bubble that this gate cannot fix (OpenCode / any hook that keeps The gate's input is a single string. When an agent starts a new turn and the hook still reports the previous turn's The fix has to be upstream, where the discriminator still exists. The staleness is created by one line in lastAssistantMessage: update.clearLastAssistantMessage
? undefined
: (update.lastAssistantMessage ?? previous.lastAssistantMessage)That
Do not simply set So the discriminator has to be additive: carry the preview's turn id (or a 2. Stale comment in
That was already untrue before this PR. 3. Segment-start detection is prefix-based, and that is a chosen bound.
4. Gate ownership could be narrowed later. The gate currently lives in |
…3333) (stablyai#12501) * fix(mobile): keep repeated-prefix chat replies streaming Text alone can't tell "the transcript caught up with this stream" from "a new reply repeats the previous turn's prefix", so the old suppress-on- prefix rule swallowed genuine repeated replies. A stateful gate remembers which transcript tail predates the current stream segment and hides the bubble only when that tail moved during the segment, scoped to the active host/workspace/tab/session so a swapped chat can't inherit a baseline. Refs STA-3333. * fix(mobile): keep the streaming gate alive across chat/terminal toggles The gate lived in MobileNativeChatView, but MobileNativeChatOverlay returns null whenever the user peeks at the terminal — that unmounts the view and throws the baseline away, so the repeated-prefix reply was swallowed again on the way back. Move the gate (and the fold memo it reads) up to the overlay, which stays mounted across those toggles. While hidden the transcript is empty and the throttled stream reports no text, which the gate would have read as "idle" and re-anchored on. Pass the agent's working state so a textless tick inside a live segment holds the baseline instead. The scope key is now keyed off the tab rather than the view-gated chat resolution, so it survives the toggle too; streamIdentity keeps its exact previous value because the delayed-send guards compare against it. Also drops a dead disjunct in the caught-up test: a null baseline is already unequal to every real tail id. * test(mobile): model the real re-show ordering in the streaming-gate tests The overlay regression test replayed the transcript before the stream text on the way back from the terminal view. That ordering is backwards: the session withholds `messages` until a fresh read settles (an RPC round trip) while the throttled stream text returns in ~50ms — and with the transcript already back, a gate that got discarded on the toggle still passes. Replay the real order, which pins the gate's lifetime as intended. Swaps the hidden-gap duplicate case for the in-view one (a tool frame clears the assistant text mid-turn), which is where the hold actually earns its keep; the hidden-gap direction stays covered at the gate level. * fix(mobile): stop the streaming gate adopting a reply as its own history A textless status tick was re-anchoring the gate's pre-stream baseline, so two paths still rendered wrong: - The reply's transcript push beats its throttled status text whenever the pane stays `working` past the turn (a live subagent or background task). The tick in between adopted the just-landed reply as history, and the status text that followed rendered it a second time — a duplicate bubble, and a regression against main's suppress-on-prefix rule. - Peeking at the terminal between turns empties the transcript. That empty tail was adopted as the baseline, so the next repeated-prefix reply was swallowed again — the bug this PR exists to fix. Only a tick that carries a real tail and sits outside a live turn anchors now, with an exception for a gate that has never anchored: mounted mid-turn, the first real tail it sees is the best history it will ever get. Also drop `buildMobileNativeChatData`, a test-only builder this PR had wired the new gate into; its green test asserted the exact suppression this PR removes. Its fold/pending/image coverage moves to the builder the view calls. * test(mobile): pin the textless anchor's text reset Mutation testing found the `prevText` reset on an anchoring textless tick unpinned: keeping the previous turn's text there reads the next turn's opener as a new segment, re-anchors onto the reply that just landed, and renders it a second time — the same duplicate-bubble class already fixed twice on this branch.





Summary
Native chat could swallow a real assistant reply while it was still streaming. The streaming bubble was gated on text alone: if the newest folded transcript turn started with the streamed text, the bubble was hidden as "the transcript already caught up". That test can't tell catch-up from coincidence — when a new reply happens to repeat the previous turn's prefix ("Done.", "The tests pass.", any stock opener), the older turn matched and the live reply never rendered. The user saw the working indicator spin with no visible text until the whole turn landed.
The gate is now stateful. It records which transcript tail was live when the current stream segment began, and hides the bubble only when the tail moved during that segment and leads with the streamed text — i.e. the real turn actually landed. An older identical turn can no longer suppress anything. A stream that isn't an extension of the previous tick (the next reply part) re-anchors to the tail that predates it.
Two things make that baseline survivable in the real app:
MobileNativeChatOverlay, which returnsnullwhen chat is hidden but is never unmounted — so the baseline outlives the chat list below it. Putting it in the list would reset it on every chat↔terminal toggle, which is exactly when the bug bites.nativeChatStreamScopeKey(host / workspace / tab), which is stable across view toggles. The pre-existingstreamIdentity— which additionally encodes the view so a delayed answer-send or stop can't land in the wrong place — is deliberately not reused here; a view-gated key would drop the baseline on the very toggle this fix is about. Both are asserted against each other inuse-mobile-native-chat-controller.test.ts.streamLive(the pane's working state) distinguishes "no observation this render" from "the stream ended", so a textless tick mid-turn no longer re-anchors the baseline onto a reply that has just landed.Split from #12373 (fix 9 of 10 in that QA sweep), rebased onto
mainas an independent PR. #12373 stays open; none of its other fixes (reconnect history, cached transcript, stale status, prompt cards, paging, write lock, tool summaries) are included here.Refs STA-3333.
Screenshots
A/B on the iOS simulator against a mock desktop, same scenario, two Metro servers: A =
main(e9cf106), B = this branch atfed9ca38— the only commit since is test-only, so the production code in these shots is the code at head. Bundle provenance was verified by grepping each served bundle (A has the oldlastText.startsWithrule and none of the new gate symbols; B hascanAnchor/baselineTailId/nativeChatStreamScopeKeyand zero occurrences of the old rule).A —
main: the reply is swallowed. A prior "Done." turn exists; the agent starts a new reply that also begins "Done.". The pane shows Agent is working + Stop, but only one "Done." is on screen — the live reply never renders, and it is still absent 12 s later.B — this branch: the reply streams, and does not duplicate. Same scenario now renders the second "Done." live (left). When that reply's own turn lands while the pane is still working, the synthetic bubble is withdrawn and the count stays at two — no duplicate (right).
B — the two orderings that previously broke it. Left: the transcript lands the reply before the throttled status text arrives while the pane stays working (a subagent still running) — exactly two bubbles, no third. Right: a chat→terminal→chat peek taken while idle tears the transcript down to empty; the reply that arrives afterwards still streams, and is stable 12 s on.
Testing
pnpm lint— root + mobileoxlint,audit:code-quality:native,check:max-lines-ratchet(352 grandfathered, no new bypasses),oxfmt --check: clean. Nomax-linesdisables and no per-file cap bumps added.pnpm typecheck— root three-projecttscand mobiletsc --noEmit: clean.pnpm test— full mobile suite at1c1afe52: 405 files, 3035 passed / 3 skipped. Root suite does not covermobile/and nosrc/file is touched.check:react-doctor:changed): 0 issues.check:reliability-gates— 65 gates, passed.pnpm build— not run; no build-affecting change (React Native UI logic only). CI covers it.mobile-native-chat-streaming-gate.test.ts(new, 17 tests) drives sequences of(folded, streamingText, streamLive)ticks through one gate and locks the decision table: the repeated-prefix reply stays visible (the actual regression), the bubble hides once the real turn lands, an identical repeated reply is suppressed only by its own turn, hiding persists for the rest of the segment, a new reply part re-anchors, re-anchoring also clears the remembered text so the next turn's opener isn't misread as a new segment, a hidden gap taken mid-turn keeps the baseline, a hidden gap taken between turns does not adopt the empty tail, a reply whose turn lands before its status text is not adopted as history, a gate mounted mid-turn anchors on the first tail it sees, the first-tick fallback, reference-identity idempotency for a repeated tick, scope-swap baseline reset, and empty/whitespace text.MobileNativeChatOverlay.test.ts(new, 6 tests) exercises the same behaviors through the real component — including both chat↔terminal peek orderings and a scope swap — so the ownership/lifetime decision is covered, not just the pure function.MobileNativeChatView.test.tskeeps one placement test for the gated bubble;mobile-native-chat-render-data.test.tsnow asserts only placement of the synthetic row (between transcript and pending), since whether it renders at all is the gate's call.The suite was mutation-checked against the production source (never the tests): 28 mutants, 22 killed. The decisive one reverts the gate to
main's rule by dropping thetailId !== baselineTailIdclause — it fails 14 tests, including the two that name the user-visible bug, which is what proves these tests could not pass againstmain. Others: dropping either conjunct of the anchor condition, inverting or removing segment-start detection, makingadvanceGateallocate a fresh object every render (kills all 6 overlay tests via an infinite render), reusing a gate across a scope change, collapsingstreamScopeKeyback tostreamIdentity, view-gatingstreamLive, and bypassing the gate in the overlay.Of the 6 survivors, 4 are provably equivalent mutants that no test can kill —
text.startsWith('')is always true, so theprevText !== ''conjunct is redundant;showLoadingonfoldedvsmessagescannot differ because a loading session always returns the shared empty array; seeding the gate with a null scope is reset on the first derive; andnativeChatAgentWorkingvsnativeChatStreamLiveonly diverge while chat is hidden, where the tail is null and the gate is inert anyway. The 5th (the assistant-role guard on the tail) is inherited unchanged frommain. The 6th was a real gap in new code and is now closed by the 17th test.AI Review Report
Reviewed across four rounds of independent same-model passes on three dimensions (correctness, tests/scope, render+perf), looping until clean. Two real defects were found and fixed in
fed9ca38before this report:main). A textless status tick re-anchored the baseline onto a reply that had just landed in the transcript, so the next text tick rendered it a second time. Reproduced with a trace harness ([null,null,"Done.","Done."]) and fixed by refusing to anchor on textless ticks taken inside a live turn.[null,null,null,"Done.",null]— flash, then vanish). Fixed by refusing to anchor on a null tail.The combined condition — anchor only on a textless tick that carries a real tail and is either outside a live turn or on a gate that has never anchored — satisfies both plus the mount-mid-turn case. The one case it gives up is a transcript-first landing on the gate's very first tick (a ≤50 ms window), which degrades to
main's existing suppress-on-prefix behavior.The change cannot swallow a reply that
mainrendered.caughtUprequirestailLeadsWithStream, which ismain's entire suppression predicate, plus a second conjunct — so this gate's suppression set is a strict subset ofmain's. A randomized differential run (2.4M ticks over varied text / tail /streamLive/ scope sequences) found zero cases where this branch returnsnullandmainreturns text. That bounds the whole regression surface to one class — a spurious extra bubble — rather than leaving it open-ended.Other findings verified and addressed:
advanceGatereturns the same object when nothing moved, so a repeated(text, tail)pair produces nosetStateand the adjustment settles in one pass; the idempotency test asserts reference equality (toBe), so a future change that allocates a fresh gate per render — which would loop — fails the test. Convergence was proven twice by independent methods: exhaustive enumeration of the gate's state space (46,080 cases, three applications each — 0 non-settling, 0 flipped derived values) and randomized second passes (200,000 — 0 non-settling). Under real React, the worst case observed over 5,000 randomized updates was 2 passes, never 3, with no cross-component-update warnings.react-test-rendereragainstmainas baseline: the extra pass is confined to the overlay's own function body — React discards the children of a render-phase-updated pass — soMobileNativeChatViewrenders exactly once per streaming tick, same asmain, and the folduseMemorecomputes zero times during a turn. Wall clock is +13.8 µs/tick vsmainon a realistic ~6.5 KB reply, i.e. +0.28 ms of CPU per second of streaming, or 0.03% of the 50 ms throttle window. While chat is hidden the gate is fully inert:streamingTextis view-gated toundefinedand the session returns a reference-stable empty transcript, soadvanceGatereturns by reference andsetStatenever fires — 0 view renders and 0 fold calls per tick. While the bubble is suppressed the branch is strictly better thanmain, which kept rebuilding list data as the raw text grew.scopeKeyand self-resets when the caller's identity differs, so a stale baseline from another tab can never license showing a bubble here; locked at both the gate and component level.buildMobileNativeChatDataone-shot helper was deleted rather than left as a second, diverging copy of the rule.Cross-platform: no keyboard shortcuts, shortcut labels, file paths, shell invocation, git commands, or Electron main-process code are touched. This is React Native renderer logic that behaves identically on iOS and Android and is agnostic of the desktop host OS, so it is unaffected by the macOS/Linux/Windows and native/WSL/SSH host distinctions. It reads only already-parsed transcript messages, so local worktrees, SSH worktrees, and folder workspaces are all equivalent here. No git provider (GitHub/GitLab) surface is involved.
Security Audit
No new input parsing from untrusted sources, no command execution, no path handling, no auth or secret handling, no dependency changes, and no IPC/RPC surface change (no new methods; existing subscribe/read paths are untouched). The gate holds two short strings and a message id in renderer memory and derives a boolean; it renders no new content — the streamed text was already rendered through the same
Textpath before this change, so there is no new injection surface. Agent-provided text is only compared withString.prototype.startsWith, never evaluated or interpolated into a command. No follow-up needed.Notes