Repository navigation
fix(native-chat): stop matching pending echoes across clock domains - #13613
brennanb2025 wants to merge 15 commits into
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughNative chat now tracks transcript generation, sequence, and high-water metadata across live-session snapshots, appends, replacements, and pagination. Command markers use dedicated scoped cache and hook modules, record Merge Risk: 🔵 Low · up to The pending-send lifecycle can use the previous chat scope's generation baseline after a scope change, which may remove optimistic bubbles and allow duplicate sends. The risk is localized and mergeable with explicit owner follow-up to reset the baseline when the scope changes. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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 |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 598033b0-07f5-4be6-93a3-e31052642fc5
📒 Files selected for processing (8)
src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsxsrc/renderer/src/components/native-chat/NativeChatView.tsxsrc/renderer/src/components/native-chat/native-chat-command-markers.tssrc/renderer/src/components/native-chat/native-chat-pending-occurrence.test.tssrc/renderer/src/components/native-chat/native-chat-pending-occurrence.tssrc/renderer/src/components/native-chat/native-chat-pending.test.tssrc/renderer/src/components/native-chat/native-chat-pending.tssrc/renderer/src/components/native-chat/use-native-chat-command-markers.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/renderer/src/components/native-chat/use-native-chat-transcript-order.ts (1)
11-39: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider returning a named object instead of a 4-tuple.
appendandsettlehave identical signatures:(messages, retainedCount) => void. The tuple position is the only distinction. A caller that swaps them compiles cleanly and produces wrong sequence semantics. A named object removes that class of mistake.♻️ Proposed refactor
-export function useNativeChatTranscriptOrder(): readonly [ - NativeChatTranscriptOrder, - () => void, - (messages: readonly NativeChatMessage[], retainedCount: number) => void, - (messages: readonly NativeChatMessage[], retainedCount: number) => void -] { +export type NativeChatTranscriptOrderControl = { + order: NativeChatTranscriptOrder + replace: () => void + append: (messages: readonly NativeChatMessage[], retainedCount: number) => void + settle: (messages: readonly NativeChatMessage[], retainedCount: number) => void +} + +export function useNativeChatTranscriptOrder(): NativeChatTranscriptOrderControl {- return [current, replace, append, settle] + return { order: current, replace, append, settle } }Update the destructuring at
src/renderer/src/components/native-chat/use-native-chat-live-session.tslines 69-70 to match.src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts (1)
483-520: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd the non-empty-clear replacement case.
This test covers
/clearon an empty transcript, where treating replacement-settled rows as post-clear is correct. The inverse case is not covered:/clearon a non-empty transcript, then areplacementframe whose payload still contains pre-clear rows and no longer containsclearAfterMessageId.In that case
applyCommandMarkerBoundariescannot resolve the id boundary and falls through to the sequence filter. The replacement settle assigns the pre-clear rows sequences aboveclearTranscriptHighWater, so they would become visible again. This is the same root cause flagged atsrc/renderer/src/components/native-chat/native-chat-transcript-order.tslines 26-57.Do you want me to draft this regression test?
src/renderer/src/components/native-chat/use-native-chat-load-earlier.ts (1)
1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReplace
MutableRefObjectwithRefObjecthere.
package.jsonpins@types/react@^19.2.17for this renderer target, whereMutableRefObjectis deprecated.♻️ Proposed refactor
-import { useCallback, type MutableRefObject } from 'react' +import { useCallback, type RefObject } from 'react'Then update the four ref parameter types:
- limitRef: MutableRefObject<number> - transcriptEpochRef: MutableRefObject<number> - latestSessionId: MutableRefObject<string | null> - latestTransport: MutableRefObject<SessionTransport> + limitRef: RefObject<number> + transcriptEpochRef: RefObject<number> + latestSessionId: RefObject<string | null> + latestTransport: RefObject<SessionTransport>
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c8a93ae6-49cb-45cb-b26f-f8f1c31bc63b
📒 Files selected for processing (17)
src/renderer/src/components/native-chat/NativeChatView.tsxsrc/renderer/src/components/native-chat/native-chat-command-markers.tssrc/renderer/src/components/native-chat/native-chat-incremental-assembler.tssrc/renderer/src/components/native-chat/native-chat-live-session-order.tssrc/renderer/src/components/native-chat/native-chat-live-session-types.tssrc/renderer/src/components/native-chat/native-chat-pending-occurrence.tssrc/renderer/src/components/native-chat/native-chat-pending.test.tssrc/renderer/src/components/native-chat/native-chat-pending.tssrc/renderer/src/components/native-chat/native-chat-transcript-order.test.tssrc/renderer/src/components/native-chat/native-chat-transcript-order.tssrc/renderer/src/components/native-chat/use-native-chat-command-markers.test.tssrc/renderer/src/components/native-chat/use-native-chat-command-markers.tssrc/renderer/src/components/native-chat/use-native-chat-live-session.test.tssrc/renderer/src/components/native-chat/use-native-chat-live-session.tssrc/renderer/src/components/native-chat/use-native-chat-load-earlier.tssrc/renderer/src/components/native-chat/use-native-chat-retained-session.test.tssrc/renderer/src/components/native-chat/use-native-chat-transcript-order.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/renderer/src/components/native-chat/NativeChatView.tsx
- src/renderer/src/components/native-chat/native-chat-pending.test.ts
| if (unsubscribe && typeof (unsubscribe as { then?: unknown }).then === 'function') { | ||
| void (unsubscribe as Promise<unknown>).then((fn) => { | ||
| if (typeof fn === 'function') { | ||
| ;(fn as () => void)() | ||
| } | ||
| }) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Attach a rejection handler to the promise teardown path.
void (unsubscribe as Promise<unknown>).then(...) has no rejection handler. If transport.subscribe resolves to a rejected promise, the renderer raises an unhandledrejection event. Teardown runs on every source rebind and on unmount, so an IPC failure during subscribe reaches this path.
🛡️ Proposed fix
if (unsubscribe && typeof (unsubscribe as { then?: unknown }).then === 'function') {
- void (unsubscribe as Promise<unknown>).then((fn) => {
- if (typeof fn === 'function') {
- ;(fn as () => void)()
- }
- })
+ void (unsubscribe as Promise<unknown>)
+ .then((fn) => {
+ if (typeof fn === 'function') {
+ ;(fn as () => void)()
+ }
+ })
+ // A failed subscribe has nothing to tear down; do not raise unhandledrejection.
+ .catch(() => undefined)
}📝 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.
| if (unsubscribe && typeof (unsubscribe as { then?: unknown }).then === 'function') { | |
| void (unsubscribe as Promise<unknown>).then((fn) => { | |
| if (typeof fn === 'function') { | |
| ;(fn as () => void)() | |
| } | |
| }) | |
| } | |
| if (unsubscribe && typeof (unsubscribe as { then?: unknown }).then === 'function') { | |
| void (unsubscribe as Promise<unknown>) | |
| .then((fn) => { | |
| if (typeof fn === 'function') { | |
| ;(fn as () => void)() | |
| } | |
| }) | |
| // A failed subscribe has nothing to tear down; do not raise unhandledrejection. | |
| .catch(() => undefined) | |
| } |
pending.sentAt is renderer time while transcript message.timestamp is host/provider time on remote runtimes. Never use sentAt as a host-domain bound for echo retirement, and hide /clear rows by the message ids visible at clear time so host-behind and host-ahead no longer strand or leak turns. Closes #11519
Keep transcriptOrder generation across null→sessionId adoption and same-session snapshots so empty-boundary pending can retire against the mandatory initial snapshot. Settle first-seen rows on adoption and replacement frames only (reconnect baselines stay unsequenced), and boundary-filter glue fallbacks so pre-watermark history cannot prune a fresh multi-send pair.
Extract notFound retry scheduling and subscribe outside the effect body, and always return a disposer so effect-needs-cleanup accepts the live-session hook on changed-code quality.
useRef(createNativeChatTranscriptOrder()) re-ran create on every render, allocating and discarding an order object plus Map. Seed with the standard null-guarded lazy-ref pattern and keep updater identity stable across re-renders.
4eb7ab2 to
6be90b2
Compare
|
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. |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e4c18be4-56de-41aa-b710-8c04447c412e
📒 Files selected for processing (26)
src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsxsrc/renderer/src/components/native-chat/NativeChatInteractiveCard.tsxsrc/renderer/src/components/native-chat/NativeChatView.tsxsrc/renderer/src/components/native-chat/native-chat-command-markers.tssrc/renderer/src/components/native-chat/native-chat-incremental-assembler.tssrc/renderer/src/components/native-chat/native-chat-launch-prompt.test.tssrc/renderer/src/components/native-chat/native-chat-launch-prompt.tssrc/renderer/src/components/native-chat/native-chat-live-session-order.tssrc/renderer/src/components/native-chat/native-chat-live-session-types.tssrc/renderer/src/components/native-chat/native-chat-pending-occurrence.test.tssrc/renderer/src/components/native-chat/native-chat-pending-occurrence.tssrc/renderer/src/components/native-chat/native-chat-pending.test.tssrc/renderer/src/components/native-chat/native-chat-pending.tssrc/renderer/src/components/native-chat/native-chat-session-assembler.tssrc/renderer/src/components/native-chat/native-chat-session-transport.tssrc/renderer/src/components/native-chat/native-chat-transcript-order.test.tssrc/renderer/src/components/native-chat/native-chat-transcript-order.tssrc/renderer/src/components/native-chat/use-native-chat-command-markers.test.tssrc/renderer/src/components/native-chat/use-native-chat-command-markers.tssrc/renderer/src/components/native-chat/use-native-chat-launch-prompt.tssrc/renderer/src/components/native-chat/use-native-chat-live-session.test.tssrc/renderer/src/components/native-chat/use-native-chat-live-session.tssrc/renderer/src/components/native-chat/use-native-chat-load-earlier.tssrc/renderer/src/components/native-chat/use-native-chat-retained-session.test.tssrc/renderer/src/components/native-chat/use-native-chat-transcript-order.test.tssrc/renderer/src/components/native-chat/use-native-chat-transcript-order.ts
🚧 Files skipped from review as they are similar to previous changes (22)
- src/renderer/src/components/native-chat/native-chat-session-assembler.ts
- src/renderer/src/components/native-chat/native-chat-session-transport.ts
- src/renderer/src/components/native-chat/use-native-chat-retained-session.test.ts
- src/renderer/src/components/native-chat/use-native-chat-transcript-order.test.ts
- src/renderer/src/components/native-chat/native-chat-pending-occurrence.test.ts
- src/renderer/src/components/native-chat/native-chat-incremental-assembler.ts
- src/renderer/src/components/native-chat/native-chat-live-session-types.ts
- src/renderer/src/components/native-chat/use-native-chat-transcript-order.ts
- src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts
- src/renderer/src/components/native-chat/use-native-chat-launch-prompt.ts
- src/renderer/src/components/native-chat/use-native-chat-command-markers.test.ts
- src/renderer/src/components/native-chat/native-chat-transcript-order.test.ts
- src/renderer/src/components/native-chat/use-native-chat-load-earlier.ts
- src/renderer/src/components/native-chat/native-chat-launch-prompt.test.ts
- src/renderer/src/components/native-chat/use-native-chat-command-markers.ts
- src/renderer/src/components/native-chat/native-chat-transcript-order.ts
- src/renderer/src/components/native-chat/native-chat-pending-occurrence.ts
- src/renderer/src/components/native-chat/native-chat-pending.test.ts
- src/renderer/src/components/native-chat/native-chat-launch-prompt.ts
- src/renderer/src/components/native-chat/native-chat-pending.ts
- src/renderer/src/components/native-chat/use-native-chat-live-session.ts
- src/renderer/src/components/native-chat/native-chat-live-session-order.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 0 remain after this review.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0348c0b5-4e9d-4afe-9b61-a11016fcebe6
📒 Files selected for processing (2)
src/renderer/src/components/native-chat/NativeChatView.tsxsrc/renderer/src/components/native-chat/use-native-chat-pending-sends.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/components/native-chat/NativeChatView.tsx
Included review availability: Your plan includes up to 10 reviews per rolling hour; 0 remain after this review.
| useEffect(() => { | ||
| setPending(readPendingSendCache(scope)) | ||
| }, [scope]) | ||
| useEffect(() => { | ||
| if (pendingGenerationRef.current !== order.generation) { | ||
| // A source rebind invalidates pane-local optimistic sends. | ||
| setPending(writePendingSendCache(scope, [])) | ||
| } | ||
| pendingGenerationRef.current = order.generation | ||
| }, [order.generation, scope]) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Reset the generation baseline when scope changes.
Lines 30-31 load the new scope cache. Lines 33-36 can then erase it because pendingGenerationRef.current still contains the previous scope generation.
When the scope changes, set pendingGenerationRef.current to order.generation before generation invalidation runs. Keep invalidation for generation changes within the same scope only. Otherwise, returning to a scoped chat with pending sends can remove its optimistic bubbles and allow duplicate sends.
|
"## Final review and validation\n\nFinal pushed SHA: fcb85ae.\n\nReview history (predecessor completed four rounds):\n- Round 1 found cross-generation pending matching, snapshot/reconnect retirement gaps, clear fallback blanking, live-status identity risk, launch clock fallback, and a timestamp fallback.\n- Round 2 tightened source/generation isolation and conservative snapshot handling; it identified the opposite risk of promoting an untrusted snapshot baseline.\n- Round 3 fixed source/clear isolation, pending cancellation, and recovery paths; replacement-baseline, snapshot-only, and live-status races remained.\n- Round 4 reconfirmed snapshot-only pending/launch retirement, paged-out clear tails, and live /clear status identity races.\n\nAdjudication:\n- Snapshot-only pending/launch retirement: (b) inherent architecture, known limitation. Ordinary and reconnect snapshots carry no causal host sequence, so sequencing them would incorrectly retire an empty-boundary echo against pre-send history; leaving them unsequenced can strand a first-send/launch bubble when the completed turn arrives only in a reconnect snapshot. This remains reachable for remote/SSH panes until a later append or bounded cache eviction, and is explicitly worse than the old clock-skew tradeoff in that case. Fixing it requires a host-side causal watermark/protocol change, outside this renderer-only issue.\n- Live /clear status identity: (b) inherent architecture, known limitation. Live status has no transcript/source identity, so a lingering pre-clear ask cannot be distinguished from a first post-clear ask solely from status. The conservative clear path suppresses unresolved status and keeps transcript rows visible when a boundary is unavailable; it never auto-clears user data. A source/status identity contract is a follow-up architectural change, not a safe local fix.\n\nThe final mechanical extraction of pending-send state only keeps NativeChatView.tsx under the max-lines ratchet; no behavior was changed in response to those two inherent races.\n\nValidation:\n- Native-chat directory: 77 test files, 796 tests passed.\n- Wider renderer tree: 2,831 test files; 23,751 passed, 10 failed, 4 skipped. The 10 failures are the pre-existing terminal IME xterm suites (terminal-ime-xterm-cancelled-preedit-visibility and terminal-ime-xterm-midline-preedit-tail), outside this PR.\n- npx oxlint src/renderer/src: passed.\n- Changed-code quality gate against pinned 7ae6aed: 27 changed files, 0 code-quality, 0 type-aware, 0 React Doctor findings.\n- ref-oss: not run (coordinator-run).\n\nThe branch is pushed and the worktree contains only the two protected untracked paths: .llm-counsel/ and issue-11519-lazy-ref-report.md." |
|
Closing: superseded by #24207, which orders pending prompts chronologically and tolerates cross-host clock skew. |


Summary
Fixes #11519 / STA-2989: Chat UI pending-echo matching and
/clearfiltering compared renderer-clocksentAtto host/provider transcriptmessage.timestamp. On remote runtimes those are different machines, so host-behind stranded optimistic bubbles forever and blanked post-clear transcripts, while host-ahead retired echoes against older identical prompts and let pre-clear rows survive/clear.Change
nativeChatPendingMatchingAfter/messageIsAfterPendingTimestamponly use host-domain bounds (matchingAfterTimestamp/afterMessageTimestamp). Never fall back to renderersentAt. Without a host bound, identity + occurrence matching sees the full list./clear— record the message ids visible at clear time and hide those ids. No wall-clock comparison across domains.native-chat-command-markers.ts(+ thin hook) so files stay under max-lines.Does not duplicate #11509 (conversation retain on session replace) or #13513 (cancelled-send occurrence release). Those PRs document this clock-domain mix as a known unfixed limit (#11519).
Screenshots
No visual change in the correct state — this removes permanent stale bubbles / blank post-clear lists that should not appear. Behavior is pinned by unit tests (host-behind and host-ahead at both echo retirement and
/clear).Testing
pnpm lint(via pre-commit oxlint on changed files; max-lines clean, no new bypasses)pnpm typecheck:webpnpm typecheck(full three-project; web-only change path exercised)native-chat-pending.test.ts,native-chat-pending-occurrence.test.ts,NativeChatInteractiveCard.test.tsx(68 passed)src/renderer/src/components/native-chat/(69 files / 719 tests passed)pnpm build— not run; renderer-only pure TS with no main/preload/packaging surface/clearSHA:
5bc65d45e8b838bc7edec9735ab78c8defb9c549AI Review Report
Self-reviewed for pure logic, React effects, tests, and repo fit:
/clearis id-set membership (O(n) over page-sized lists). Occurrence inheritance no longer copies renderersentAtinto a field labeled host-domain.commandMarkerScope+messages. No new subscription or render loop.sentAtfilter already failed the same way when the host clock was ahead.Security Audit
No new attack surface.
Notes