Skip to content

fix(native-chat): scope optimistic echoes to the conversation they were sent into - #15032

Open
brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/native-chat-conversation-scoped-echoes
Open

brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/native-chat-conversation-scoped-echoes

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​472 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​464
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​260 $\color{#cf222e}{\Huge{\mathbf{−}}}$​77 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​183

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

NativeChatPendingSendScope gains conversationId, and the echo cache key becomes paneKey + 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 bootstrap bucket, and claimBootstrapPendingSends hands 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, and NativeChatView.tsx stays 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:

  • The echo cache is keyed by paneKey + agent only (pendingSendScopeKey) — no conversation identity.
  • The only retirement path is a normalized-text match against a transcript user turn (prunePendingSends / pendingSendsAsMessages).
  • NativeChatView's pendingScope was useMemo(..., [paneKey, agent]), and a conversation swap changes neither, so the reset effect keyed on it never fired.
  • prunePendingSends writes 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:

× renders the old conversation prompt as the newest message forever
    AssertionError: expected [ { id: 'send-1', …(4) } ] to have a length of +0 but got 1
× keeps the ghost in the pane cache across a remount
    AssertionError: expected [ { id: 'send-1', …(4) } ] to have a length of +0 but got 1

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 + agent and adds retainPendingSendsForConversation, 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 /clear adopted 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), dropNativeChatPendingOccurrences and 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.

  1. Echoes queued while the pane has no conversation id go to a per-pane bootstrap bucket.
  2. The first conversation id the pane ever observes claims that bucket exactly once. The claim moves the entries into that conversation's bucket and closes the bootstrap bucket for that pane permanently — so every later send is written under a real conversation, and no later conversation can reach back for a pre-identity echo.
  3. The claim is refused for any echo queued at or before a /clear recorded in the same pre-identity window. A /clear is 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 applyCommandMarkerBoundaries already 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 /clear and 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

  • The /clear boundary (its rule 1) — the bootstrap claim's refusal condition. It is selectClaimableBootstrapSends here, tested standalone including the exclusive > boundary (sentAt exactly equal to the clear resolves as pre-clear).
  • The useNativeChatPendingEchoes extraction and its filename, and native-chat-pending-conversation.ts — same decomposition, same reason (NativeChatView.tsx is at its max-lines ceiling, and the wiring needs to be testable without the store).
  • Test scenarios worth keeping, re-expressed against this design: remount persistence (a dropped echo stays dropped, a live echo survives), pane independence, "the session must genuinely differ", the exact-boundary case, and negative cases so the rules cannot over-reach.

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 on main today.

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; the origin/main repro output is quoted above.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

21 new tests across 2 files, all green; native-chat is green at 75 files / 787 tests (766 before). terminal-pane (the only other consumer of NativeChatView) green at 368 files / 3602 tests.

Gates, run per-file with real exit codes (piping through tail masks them):

Gate Result
npx oxlint on all 8 changed files exit 0 each
npx oxfmt on all 8 changed files clean (repo formats with oxfmt, not prettier)
pnpm audit:code-quality:native exit 0
pnpm audit:code-quality:type-aware exit 0
pnpm check:max-lines-ratchet OK — no new bypasses, no max-lines disable added
lint-react-doctor-changed exit 0; warnings on this file drop 3 → 2 (net −1, no new ones)
tsc --noEmit × 3 projects clean, run cold after deleting config/*.tsbuildinfo (7.6s / 1.5s / 7.9s — a warm run is a 1.0s no-op and proves nothing)
knip no findings on the new modules

The lint gate is live, not silently dead: planting const plantedViolation = new Array() in native-chat-pending-conversation.ts produced error 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:

Mutation Tests that fail
Key back to paneKey + agent (the fix itself) 4 — incl. "leaves a replaced conversation unable to reach its predecessor echo"
Bootstrap claim made re-entrant (i.e. #11509's rule 4) 2 — incl. "closes the bucket for good…"
/clear guard removed 3
Claim allowed to run with a null conversation id 4
Clear boundary > → >= 1

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 — Map caches, string keys, array filtering. No path handling, no shell, no shortcuts, no process.platform branch, 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

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security: no new attack surface. conversationId is a provider session id already present in renderer state, used only as a Map key — never logged, persisted, parsed, or rendered. No new IPC channel or payload, no dependencies added, no filesystem or PTY writes.
  • Remote / SSH: unchanged. This touches no wire payload and no host-executed command; a runtime-owned pane routes its transcript reads exactly as before.
  • Mobile: unaffected — nothing outside src/renderer/src/components/native-chat/ imports these modules (verified by grep across src/ and mobile/src).
  • Backwards compatibility: the caches are in-memory and per-renderer-session; nothing is persisted, so there is no stored format to migrate.
  • Memory: the key gains one dimension (conversation), so a pane that churns conversations creates more keys. Pending-send and command-marker payload caches remain LRU-bound to 128 keys via setBoundedScopeCacheEntry; the new boundPanes correctness tombstones store one boolean per paneKey + agent for 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.
  • Pre-existing, untouched: echo retirement still rests on a single normalized-text match, so an agent-rewritten prompt (mention expansion, skill prefixes) still will not match — but this PR narrows that from permanent to until the conversation is replaced. The sentAt (renderer clock) vs message.timestamp (transcript host clock) mix in messagesAfterPendingBoundary is [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 (sentAt vs marker sentAt) so it adds no new cross-clock hazard.
  • Rebase note: fix(native-chat): do not exit Chat UI on false agent-title after send #10102 and fix(native-chat): resolve WSL Codex transcripts for Chat UI toggle #10639 also add to native-chat-pending.ts. My change there is 3 lines (one type field, one key template, one export), so a conflict should be trivial — but NativeChatView.tsx loses ~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

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred) — lint gates, all three typecheck projects, and the affected suites run locally and listed above. pnpm build not run: renderer-only change with no main/preload, packaging, or native surface touched.

Author

  • X / Twitter: @BrennanKB5

…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.
@coderabbitai

coderabbitai Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds useNativeChatPendingEchoes to manage optimistic sends, slash-command markers, pruning, cancellation, and clearing. Pending-send cache scopes now include conversationId. Pre-conversation sends use a bootstrap scope and transfer once to the first observed conversation after /clear filtering. NativeChatView now uses the hook callbacks for submission and stop handling. Tests cover cache scopes, bootstrap claiming, pane isolation, conversation replacement, remounts, cancellation, and command markers.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% 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
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.
Title check ✅ Passed The title clearly and concisely describes scoping native-chat optimistic echoes to their originating conversation.
Description check ✅ Passed The description covers the required sections, explains the bug and fix, links a related issue, documents testing, and addresses UI, platform, and compatibility considerations.
✨ 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: 2

🧹 Nitpick comments (1)
src/renderer/src/components/native-chat/use-native-chat-pending-echoes.ts (1)

87-89: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider skipping the prune write when nothing changed.

prunePendingSends returns the same array reference when it removes nothing. writePendingSendCache always returns a fresh [...next], so setPending receives a new reference on every messages change, including when no echo is pending.

messages changes on every transcript update during streaming. Each change therefore re-renders this hook's consumer and invalidates the pending-keyed useMemo values in NativeChatView.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 prev came 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

📥 Commits

Reviewing files that changed from the base of the PR and between 81d7f9b and 3784cd9.

📒 Files selected for processing (8)
  • src/renderer/src/components/native-chat/NativeChatView.tsx
  • src/renderer/src/components/native-chat/native-chat-pending-conversation.test.ts
  • src/renderer/src/components/native-chat/native-chat-pending-conversation.ts
  • src/renderer/src/components/native-chat/native-chat-pending-occurrence.test.ts
  • src/renderer/src/components/native-chat/native-chat-pending.test.ts
  • src/renderer/src/components/native-chat/native-chat-pending.ts
  • src/renderer/src/components/native-chat/use-native-chat-pending-echoes.test.tsx
  • src/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.

Comment on lines 56 to +59
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'}`

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

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'}`
 }

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Rendered Electron QA — conversation-scoped native-chat echoes

Isolated Orca dev instance at c35d03a1488b904ba48aaf12656f54eb9730ea8c. window.api.app.getIdentity() reported Orca: brennanb2025/gate-pr-15032 / devRepoRoot=/Users/brennanbenson/orca/workspaces/orca/gate-pr-15032. Native chat was exercised through the real Chat UI (new Claude tab, composer send, /clear slash-command picker, Show terminal / Show chat view remount).

Scenario

  1. Launch Claude in native chat and send QA-15032-ECHO-MARKER please reply with only the word pong and do nothing else so the queued user bubble renders.
  2. After Claude replies pong, send a second prompt QA-15032-GHOST-2 do not reply just wait so a new queued bubble is visible.
  3. Replace the conversation via the user-visible /clear command (slash picker + Send).
  4. Remount TUI then native chat and confirm the old prompts stay gone.

Visible evidence

  • Before (queued first send): grey user bubble with the echo-marker prompt; composer empty; Stop visible.
  • Conversation A: same prompt plus Claude's pong.
  • Before replace: QA-15032-GHOST-2 queued on top of conversation A.
  • After /clear: empty native-chat transcript; no echo-marker, GHOST-2, or pong. Tab title became <local-command-caveat>…; sidebar activity Done - Claude.
  • TUI remount: fresh Claude session showing /clear only; old prompts absent.
  • Native remount: empty Chat UI again; old prompts still absent.

Backing state

  • Conversation id changed 95e5bf70-9187-4cde-89fd-c3b728a84498 → 71bd2f44-aea8-4b76-bc0d-da0b357f661d.
  • After /clear and remount: hasEchoMarker=false, hasGhost2=false, agentStatus.prompt="", viewMode=chat.

Screenshots

Queued first send
01-queued-optimistic-bubble.png

Conversation A after reply
01b-conversation-a-with-prompt.png

Queued GHOST-2 before /clear
02-ghost2-queued-bubble.png

After /clear (native chat empty)
04-after-clear-sent.png

TUI remount after /clear
05-tui-after-clear.png

Native remount after /clear (still empty)
06-native-remount-after-clear.png

Gaps

  • First prompt had already reconciled (pong in transcript) before /clear; the stronger leak case is GHOST-2, which was still a queued bubble when /clear was sent.
  • Restart-via-“Continue in New Session…” was not separately exercised; replacement used /clear.
  • Screenshots include the isolated-app status bar usage meters and a Playwright attach chrome remnant; no secrets observed.

This branch has not been deployed

No deployments
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