Repository navigation
fix(native-chat): scope optimistic echoes to the conversation they were sent into - #15032
brennanb2025 wants to merge 3 commits into
Conversation
…re sent into The pending-echo cache was keyed by paneKey + agent, with no conversation identity, and the only retirement path was a normalized-text match against a transcript user turn. Replacing the pane's conversation (/clear, an agent restart, resuming a different session) left the echo behind: it could never match the new transcript, so an old prompt stayed pinned at the list tail as the newest message for the rest of the pane's life. Put the conversation in the key. A replaced conversation's echoes are then unreachable by construction — they cannot be read, rendered, or written back — so no retain pass, adoption rule, or occurrence-slot shifting is needed. The one case the key cannot express is a send issued before the agent has reported any session id. Those go to a per-pane bootstrap bucket, and the first conversation the pane ever observes claims it exactly once; the bucket is then closed for that pane for good, so no replacement can reach back for a pre-identity echo. A /clear recorded in the same window is direct evidence the conversation moved on, so anything queued at or before it is dropped instead of handed over. The pending/command-marker state moves into useNativeChatPendingEchoes so the wiring is testable without the store and NativeChatView stays under its max-lines ceiling. Refs #11509
Occurrence assignment reads the pending list in order, so appending pre-identity echoes after a conversation's own newer entries would order them backwards. Also notes why LRU-shedding a pane binding is safe.
📝 WalkthroughWalkthroughThe change adds 🚥 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 |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/renderer/src/components/native-chat/use-native-chat-pending-echoes.ts (1)
87-89: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsider skipping the prune write when nothing changed.
prunePendingSendsreturns the same array reference when it removes nothing.writePendingSendCachealways returns a fresh[...next], sosetPendingreceives a new reference on everymessageschange, including when no echo is pending.
messageschanges on every transcript update during streaming. Each change therefore re-renders this hook's consumer and invalidates thepending-keyeduseMemovalues inNativeChatView.tsx(Lines 235-262).♻️ Proposed short-circuit
useEffect(() => { - setPending((prev) => writePendingSendCache(pendingScope, prunePendingSends(prev, messages))) + setPending((prev) => { + const next = prunePendingSends(prev, messages) + // Identity return means nothing was retired, so avoid a fresh array. + return next === prev ? prev : writePendingSendCache(pendingScope, next) + }) }, [messages, pendingScope])Note that this drops the cache write on the no-op path. That write was already redundant, because
prevcame from the cache for this same scope.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f9a512ce-b0c9-4203-933b-8e894e69006b
📒 Files selected for processing (8)
src/renderer/src/components/native-chat/NativeChatView.tsxsrc/renderer/src/components/native-chat/native-chat-pending-conversation.test.tssrc/renderer/src/components/native-chat/native-chat-pending-conversation.tssrc/renderer/src/components/native-chat/native-chat-pending-occurrence.test.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-pending-echoes.test.tsxsrc/renderer/src/components/native-chat/use-native-chat-pending-echoes.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 0 remain after this review.
| function pendingSendScopeKey(scope: NativeChatPendingSendScope): string { | ||
| return `${scope.paneKey}\0${scope.agent}` | ||
| // Why: the pre-identity bucket's sentinel carries a NUL so no provider session | ||
| // id — however malformed, including the empty string — can collide with it. | ||
| return `${scope.paneKey}\0${scope.agent}\0${scope.conversationId ?? '\0bootstrap'}` |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Consider applying the NUL sentinel to commandMarkerScopeKey too.
The comment on Lines 57-58 states that no provider session id, including the empty string, may collide with the pre-identity bucket. pendingSendScopeKey now enforces that. commandMarkerScopeKey on Line 330 still maps sessionId === null to '', so an empty-string session id shares a key with the pre-identity marker bucket.
That matters now because useNativeChatPendingEchoes reads readCommandMarkerCache({ paneKey, agent, sessionId: null }) to filter bootstrap claims. A marker recorded under an empty-string session id would be treated as a pre-identity /clear and could drop a claimable echo.
♻️ Proposed alignment of the two scope keys
function commandMarkerScopeKey(scope: NativeChatCommandMarkerScope): string {
- return `${scope.paneKey}\0${scope.agent}\0${scope.sessionId ?? ''}`
+ // Why: mirrors pendingSendScopeKey — the pre-identity bucket's sentinel carries
+ // a NUL so no session id, including the empty string, can collide with it.
+ return `${scope.paneKey}\0${scope.agent}\0${scope.sessionId ?? '\0bootstrap'}`
}





ELI5
Native chat shows your message instantly as a grey "queued" bubble before the agent's transcript catches up. That bubble was filed under "this pane, this agent" with no note of which conversation it belonged to. So if the conversation underneath got swapped out —
/clear, an agent restart, resuming a different session — the bubble had nowhere to go home to, and just sat at the bottom of the list pretending to be your newest message. Forever.This files the bubble under the conversation too. Swap the conversation and the old bubbles are simply in a drawer nobody opens again.
What Changed
NativeChatPendingSendScopegainsconversationId, and the echo cache key becomespaneKey + agent + conversationId.That is the whole fix for the reported symptom. A replaced conversation reads a different key, so a predecessor's echoes cannot be read, rendered, or written back — no retain pass, no adoption rules, no occurrence-slot shifting.
The one case a conversation-scoped key cannot express is a send issued before the agent has reported any session id (a fresh launch learns it only after the first send). Those echoes go to a per-pane
bootstrapbucket, andclaimBootstrapPendingSendshands them over — see the bootstrap rule below.Supporting change: the pending / command-marker state moved into
useNativeChatPendingEchoes, so the wiring is testable without standing up the store, andNativeChatView.tsxstays under its 400-line ceiling (it had 8 counted lines of headroom before this change; it now has ~60).Why
The bug
Nobody had ever demonstrated this defect, so the first thing I did was prove it on unmodified
origin/main. The repro is short because the mechanism is:paneKey + agentonly (pendingSendScopeKey) — no conversation identity.prunePendingSends/pendingSendsAsMessages).NativeChatView'spendingScopewasuseMemo(..., [paneKey, agent]), and a conversation swap changes neither, so the reset effect keyed on it never fired.prunePendingSendswrites its result straight back to the pane cache on every transcript tick, so an orphan it cannot retire is re-persisted; native/TUI view switches remount the surface and re-seed from that cache.Driven against
origin/main(send under conversation A → replace with conversation B → prune against B's transcript), both assertions fail:So: an old prompt renders as the newest message in a conversation it was never part of, and it survives every remount for the rest of the pane's life.
That repro is now carried by
use-native-chat-pending-echoes.test.tsx→ "leaves a replaced conversation unable to reach its predecessor echo", driven through the real production hook rather than the module functions.Why keying by conversation is the right layer
The defect is that a cache entry outlives the thing it describes. An echo is a claim about one conversation — "this prompt is on its way into this transcript". Once the conversation is gone, the claim is meaningless, and the only honest place to say that is the identity the entry is stored under.
Every alternative is downstream of the key, and therefore has to re-derive an identity the key threw away. #11509 does exactly that: it keeps
paneKey + agentand addsretainPendingSendsForConversation, a 5-rule retain pass that runs on every transcript tick, stamps session ids onto entries, adopts null-session entries by position, and shifts per-key occurrence slots when a drop vacates one. Its own root-cause section names the real defect — "there is no conversation identity in it" — and then does not fix it there. The cost shows up in its own history: four review commits on that branch, three of them fixing the retain/renumber machinery rather than the bug, one reverting a boundary fix that reopened the failure mode more broadly ("a send 4 hours after one/clearadopted into an unrelated session").With the identity in the key, none of that machinery has anything to do. Concretely, this PR deletes the need for: the retain pass, rules 2/3/5 (they are the key's job),
dropNativeChatPendingOccurrencesand per-key slot shifting (nothing is dropped mid-list, so no slot is ever vacated), and the marker-staleness hazard the bot review found in the retain effect (there is no retain effect).The bootstrap rule
One-shot claim by the pane's first conversation, refused on observed replacement.
bootstrapbucket./clearrecorded in the same pre-identity window. A/clearis direct evidence the conversation moved on after the send was queued.Rule 3 is #11509's rule 1, reused verbatim in spirit — it is the one rule in that retain pass that is right regardless of how the cache is keyed, and it matches the transcript boundary
applyCommandMarkerBoundariesalready applies to real messages.The important difference from #11509's rule 4 ("
entry.sessionId == null→ adopt the current id") is scope in time, not in logic. That rule applies to any null-session entry at any point in the pane's life, which is why it is adoption-by-position and why the PR documents a residual window where an orphan is adopted into the replacement and still pins. This one applies once, at the only moment the pane has genuinely never had an identity, and then stops existing.native-chat-pending-conversation.test.ts→ "closes the bucket for good, so a refill cannot be claimed by a replacement" pins that: it refills the bootstrap bucket after the pane is bound and asserts the next conversation gets nothing.Boundary I am not claiming to close, stated plainly: if the agent is replaced before it ever reports any session id at all, the first id the renderer sees is the replacement's, and rule 2 hands it that echo. There is no local evidence that distinguishes that from a normal fresh launch — the "previous conversation" never had an identity for the renderer to compare against. It is bounded to that single conversation and dies with it (the next swap makes it unreachable by construction), and the pane cannot repeat it, because the bucket is closed. Worth noting the shape of the precedent here: chat clients that key optimistic messages by session id avoid this entirely by minting the session id before writing the optimistic entry. Orca cannot — the provider TUI mints it asynchronously, and waiting for it would defeat the point of an instant echo.
Also inherited, not introduced: a send queued between a
/clearand the replacement id resolving is dropped by rule 3, so the bubble blanks until its real user turn lands. Cosmetic, and the opposite direction from the bug being fixed — a brief gap rather than a permanent ghost. Same limit #11509 documents as its Known limit 2.What I reused from #11509
/clearboundary (its rule 1) — the bootstrap claim's refusal condition. It isselectClaimableBootstrapSendshere, tested standalone including the exclusive>boundary (sentAtexactly equal to the clear resolves as pre-clear).useNativeChatPendingEchoesextraction and its filename, andnative-chat-pending-conversation.ts— same decomposition, same reason (NativeChatView.tsxis at itsmax-linesceiling, and the wiring needs to be testable without the store).Not reused: the retain pass, adoption-by-position, and
dropNativeChatPendingOccurrences/ occurrence-slot shifting, all of which exist only to compensate for the missing key.cancelSend's occurrence release stays out of scope here — that is #13513, a separate strand reachable onmaintoday.Linked Issue
Refs #11509— supersedes it. #11509 closes no issue; there is no filed issue for this defect, which is why Part 1 above was to demonstrate it exists.Visual Proof
N/A— the change removes a bubble that should never have been on screen. There is no new UI, no new string, and nothing to show in the fixed state that is not just "the correct conversation". The defect and every rule are pinned by tests that fail without their fix; theorigin/mainrepro output is quoted above.Testing
21 new tests across 2 files, all green;
native-chatis green at 75 files / 787 tests (766 before).terminal-pane(the only other consumer ofNativeChatView) green at 368 files / 3602 tests.Gates, run per-file with real exit codes (piping through
tailmasks them):npx oxlinton all 8 changed filesnpx oxfmton all 8 changed filespnpm audit:code-quality:nativepnpm audit:code-quality:type-awarepnpm check:max-lines-ratchetmax-linesdisable addedlint-react-doctor-changedtsc --noEmit× 3 projectsconfig/*.tsbuildinfo(7.6s / 1.5s / 7.9s — a warm run is a 1.0s no-op and proves nothing)knipThe lint gate is live, not silently dead: planting
const plantedViolation = new Array()innative-chat-pending-conversation.tsproducederror eslint(no-unused-vars), and removing it produced no output.Every new test is revert-proofed — I mutated each guard and confirmed the tests that claim to cover it actually fail:
paneKey + agent(the fix itself)/clearguard removed>→>=The first pass of the re-entrancy mutation was instructive: my original hook-level "claims once" test passed under it, because the bucket is emptied at the claim so there is nothing left to re-claim. The one-shot guard is only observable when the bucket is refilled after binding, which the hook cannot reach. I moved that guarantee to a module test that constructs the state directly, rather than shipping a test that pins nothing.
Platforms: renderer-only pure TypeScript —
Mapcaches, string keys, array filtering. No path handling, no shell, no shortcuts, noprocess.platformbranch, no Electron main/preload/IPC surface. Nothing here can differ across macOS / Linux / Windows.AI Disclosure
Claude Opus 5, via Claude Code.
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
conversationIdis a provider session id already present in renderer state, used only as aMapkey — never logged, persisted, parsed, or rendered. No new IPC channel or payload, no dependencies added, no filesystem or PTY writes.src/renderer/src/components/native-chat/imports these modules (verified by grep acrosssrc/andmobile/src).setBoundedScopeCacheEntry; the newboundPanescorrectness tombstones store one boolean perpaneKey + agentfor the renderer lifetime because evicting a tombstone would reopen a replacement claim. The command-marker cache has been keyed by session id since before this PR, so this brings the echo cache in line with it rather than introducing a new growth shape.sentAt(renderer clock) vsmessage.timestamp(transcript host clock) mix inmessagesAfterPendingBoundaryis [Bug]: Chat UI matches pending echoes across two clock domains — renderer send time vs remote transcript timestamps #11519 and is not affected by this change; the bootstrap rule deliberately uses only renderer-clock comparisons (sentAtvs markersentAt) so it adds no new cross-clock hazard.native-chat-pending.ts. My change there is 3 lines (one type field, one key template, one export), so a conflict should be trivial — butNativeChatView.tsxloses ~50 lines to the hook, so anything else editing that pending block will conflict there instead. Flagging it so it is not a surprise.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred) — lint gates, all three typecheck projects, and the affected suites run locally and listed above.pnpm buildnot run: renderer-only change with no main/preload, packaging, or native surface touched.Author