Skip to content

fix(native-chat): drop optimistic echoes a replaced conversation can never match - #11509

Open
grboy6770 wants to merge 10 commits into
stablyai:mainfrom
grboy6770:fix/native-chat-stale-pending-echo
Open

grboy6770 wants to merge 10 commits into
stablyai:mainfrom
grboy6770:fix/native-chat-stale-pending-echo

Conversation

@grboy6770

@grboy6770 grboy6770 commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

An optimistic composer echo is cached per paneKey + agent and retires only by matching its real user turn in the transcript. Nothing invalidated it when the pane's conversation was replaced — /clear, an agent restart, or resuming a different session — so a leftover echo could never match the new transcript and stayed pinned at the list tail, rendering an old prompt as the newest message for the rest of the pane's life.

Root cause

  • pendingSendScopeKey keys the echo cache by paneKey + agent only; there is no conversation identity in it.
  • The only retirement path is a normalized-text match against a transcript user turn (prunePendingSends / pendingSendsAsMessages).
  • Once the conversation behind the pane is replaced the text can never match, and no other rule removed the entry.

Change

retainPendingSendsForConversation keeps only the echoes the pane's current conversation can still match:

  1. Queued at or before the latest /clear → drop, matching the transcript boundary applyCommandMarkerBoundaries already applies to real messages.
  2. Current sessionId is null → keep everything; a reconnect can briefly drop provider-session metadata and NativeChatSessionGate (NativeChatSessionGate.tsx:27-40) holds the last identity across it.
  3. entry.sessionId === sessionId → keep.
  4. entry.sessionId == null → adopt the current id. A fresh launch learns its session id only after the first send, so the first id observed claims those echoes instead of dropping them — this is what keeps the first-turn empty-state flash away. This adopts by position, not by identity: if the id the renderer observes first is already the replacement's, the orphan is adopted into it and still pins. See Known limit 1 — that window is out of scope here, not closed by it.
  5. Otherwise (another session's echo) → drop.

Drops release occurrence slots through dropNativeChatPendingOccurrences: repeat sends of identical text carry an explicit matchingOccurrence so a later one cannot reuse a slot an earlier echo already consumed, and a survivor left numbered past a dropped sibling would wait for an identical turn that cannot arrive. The release shifts only the later same-key siblings down by the number of drops that key actually vacated — not a renumber from 1, and not across keys. Renumbering from 1 would erase the slot an echo trimmed at PENDING_SEND_LIMIT still legitimately owns (that send landed, so its transcript turn still arrives); renumbering across keys would pull an unrelated repeated prompt onto a turn a real reply already consumed.

The pending/command-marker state moved into useNativeChatPendingEchoes so NativeChatView stays under its max-lines ceiling — oxlint counted the file at exactly 400/400 before this change, so the extraction is forced rather than cosmetic.

Review rounds on this branch

@brennanb2025 pushed four commits here rather than leaving them inline; all four are in and this description reflects the head, not my original diff.

  • c6acd073b1 — adoption (rule 4) was renumbering even though it drops nothing, erasing the slot a capped-out echo still owns.
  • a132c25ae9 — the drop path renumbered every match key densely from 1, so dropping one prompt's echo pulled an unrelated repeated prompt down a slot. Replaced with the per-key shift-down described above, which subsumes the first fix.
  • 2697c8ff31 — one occurrence-release primitive instead of two, readCommandMarkerCache read inside the retain effect by scope instead of tagging marker state with its scope and skipping a commit, and useEffectEvent for the suppression reset (the indirection I flagged in my own description as droppable).
  • da42f231ef — splitting the cancelled-send fix back out, per the request below.

Split out on review: cancelSend releasing the occurrence a cancelled echo would have taken was in this PR and is now #13513. It is a real strand — a cancelled delayed Enter leaves a later identical echo waiting on a turn that cannot arrive — but it is reachable on main today with no dependency on the stale-echo work here, so it reviews and reverts on its own. cancelSend is back to the plain filter it has on main in this PR; dropNativeChatPendingOccurrences stays because the conversation-retain path is its remaining caller.

Screenshots

No visual change in the fixed state — the change removes a bubble that should never have been on screen, so there is nothing new to show. The defect and each review finding are pinned by tests that fail without their fix.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build — not run; renderer-only change with no main/preload, packaging, or native surface touched. Say the word if you want it anyway.
  • Added or updated high-quality tests that would catch regressions

pnpm lint (including check:max-lines-ratchet with no new bypasses) and all three pnpm typecheck projects exit 0. native-chat is green at 93 files / 837 tests. Full suite: 3758 files passed, 9 failed, 9 skipped (39754 tests passed, 44 failed, 71 skipped) — 0 new failures, each one accounted for:

  • 7 files fail on TypeError: window.localStorage.<removeItem|clear|getItem> is not a function — the happy-dom stub under local Node 25 against the repo's Node 24 requirement. Unrelated to this diff.
  • src/relay/agent-exec-handler.test.ts (2 tests) fails identically on origin/main; I checked out origin/main and reran it to confirm.
  • src/main/native-chat/transcript-watch-liveness.test.ts (1 test) fails only inside the full run and passes 7/7 on this branch when run alone — load-dependent, and a main-process file-watch test that a renderer-only change cannot reach.

Differential evidence — every behavioural claim here has a test that fails without its fix:

Fix Test Result without the fix
Conversation retain (the bug) native-chat-pending-conversation.test.ts, use-native-chat-pending-echoes.test.tsx the replaced conversation's echo survives and stays pinned at the tail
Per-key shift-down on drop native-chat-pending-occurrence.test.ts an unrelated repeated prompt is pulled from occurrence 2 to 1
Adoption must not renumber use-native-chat-pending-echoes.test.tsx expected 1 to be 2 — a capped-out echo's real slot is erased
Stale markers on a leaf move use-native-chat-pending-echoes.test.tsx expected [] to deeply equal [ 'leaf two prompt' ] — a live echo in another pane is dropped permanently

Negative cases are covered too, so the rules cannot over-reach: an echo is dropped only when the session genuinely differs; sentAt exactly equal to the clear boundary resolves as pre-clear; a dropped echo stays dropped across a remount, since native/TUI view switches re-read the pane cache; distinct match keys stay independent; and the release never invents an occurrence or falls below slot 1.

I also exercised this by hand in a dev build — send, /clear immediately after a send, agent restart in place, resuming a different session, Stop right after a send, and two panes with separate sessions — reading each rendered row's message id and source so an optimistic echo could be told apart from a real transcript row. No stranded echo in any of them, and the first send in a fresh pane never blanks the list while the echo hands over to its real turn.

AI Review Report

Two rounds of four-lens review (pure logic / React effects / test quality / repo fit), each finding measured rather than argued, plus the bot review on this PR.

What it checked and what it flagged:

  • Round 1 → round 2 caught my own regressions. A Low-severity cosmetic fix I had added (a pane-scoped /clear boundary, to stop a send queued between /clear and the replacement session id from blanking) turned out to reopen this PR's own failure mode more broadly: the boundary has to outlive the session change to be useful, so it never expires, and every later send in that pane then adopted into whatever session appeared next. Measured: a send 4 hours after one /clear adopted into an unrelated session. I reverted that entirely rather than ship it — this PR is deliberately narrower than my first attempt. See Known limit 2.
  • React mechanics were fuzzed rather than reasoned about: 20,000 randomised prop sequences over the hook, checking effect termination, timer count, and cache-write ordering — 0 violations. The two setPending effects chain safely because both use functional updaters.
  • Bot review (Greptile) raised two P2s. Both were real and both are fixed:
    1. Stale commandMarkers in the retain effect. Correct, and reachable more easily than the bot estimated: the chat surface is one portal per tab with no key, so moving it to another leaf changes paneKey in place. Both scopes change in one commit while the marker state still describes the leaf you came from, and the drop it writes to the module-level pane cache is permanent. /clear in one pane could therefore delete a live, legitimately-pending echo in another. My fix tagged the marker state with its scope and waited a commit when they disagreed; @brennanb2025 replaced it in 2697c8ff31 with a keyed readCommandMarkerCache read inside the effect, which cannot be stale in the first place. My test still pins it either way.
    2. cancelSend skipped occurrence release. Real, fixed, and now split out to fix(native-chat): release the occurrence a cancelled send would have taken #13513 — see above. Not fixed with the suggested dense renumber, which I measured to be incorrect here: a randomised probe over the hook (400 seeds × 50 operations) turned up survivors legitimately holding occurrence 3+ with no pruning involved, because PENDING_SEND_LIMIT trims the oldest echo while its send still landed. The probe was temporary and is not part of the diff.
  • CodeRabbit's docstring-coverage check (27% vs 80%) I took in part (281e4aad4: the hook's return object is a contract and three of its members had non-obvious triggers) and declined for the rest, which is test helpers and inline callbacks that already carry // Why: comments. AGENTS.md asks for concise comments only where non-obvious. Happy to add specific ones you want.
  • Cross-platform: explicitly reviewed and there is nothing platform-dependent in this change. It is renderer-only pure TypeScript — Map caches, array filtering, numeric timestamp comparison. No paths, no shell, no shortcuts or key handling, no labels or new user-visible strings (so no localisation surface — verify:localization-catalog passes at 11546 keys × 5 locales), no process.platform branch, and no Electron main/preload/IPC surface. Nothing here can behave differently on macOS, Linux, or Windows.

Security Audit

No new attack surface. Reviewed against the categories that apply:

  • Input handling: the only external input is transcript-derived message text, already normalised by the existing normalizeNativeChatPendingText (strips the [Image #N] marker, collapses whitespace). It is compared, never parsed, evaluated, or rendered as markup by this change.
  • Command execution / path handling: none. This change writes no PTY input and touches no filesystem path. imagePaths are carried through as opaque strings for content-key equality only.
  • Auth / secrets: none. sessionId is a provider session identifier already present in renderer state; it is used only as an equality key and is not logged, persisted to disk, or sent anywhere.
  • IPC: unchanged — no new channel, handler, or payload shape.
  • Dependencies: none added.
  • Memory/DoS: the caches this touches are bounded (PENDING_SEND_LIMIT = 8, COMMAND_MARKER_LIMIT = 8, LRU of 128 scope keys). The release pass is O(n) over at most 8 entries. Note the reverted work removed an unbounded-lifetime cache entry, so this direction is strictly better than my first attempt.
  • Follow-up: none required for this PR.

Notes

Known limits

Echo retirement still rests on a single text match. These are deliberately left out rather than widened into this PR:

  1. A session id that never resolved before the swap is not covered. Send into a brand-new pane before the agent has reported any session id, then restart or resume a different session: the first id the renderer ever sees is the replacement's, rule 4 adopts the orphan into it, and it still pins. Not a defect introduced here, and strictly better than main — where that echo ghosts forever rather than dying at the next swap — but this PR does not close it. Doing so needs a conversation epoch or restart marker on NativeChatSession, which does not exist yet. Raised by @brennanb2025 in review.
  2. A send queued between /clear and the replacement session id resolving carries the pre-clear id, so rule 5 drops it and the bubble blanks until its real user turn lands. Cosmetic and the opposite direction from the bug above — a brief gap rather than a permanent ghost. I had a fix for this and dropped it for the reason in the AI Review Report. Worth doing properly by recording the session observed at /clear time, which felt like its own change.
  3. A send that never reaches the agent (TUI startup dialog, agent exited, PTY write dropped) has no recovery once useNativeChatSendLifecycle drops the send handle after settleAfterMs. Filed separately as [Bug]: Chat UI leaves a permanent "sent" bubble when a composer send never reaches the agent #11511 — it produces the same symptom by a different cause, and the fix needs a product decision about label semantics that fix(mobile): stop reporting delivered chat messages as "Message not sent" #9792 already settled in one direction on mobile.
  4. Clock-domain mix when the send found no boundary: sentAt is the renderer's clock while message.timestamp is the transcript host's, and use-native-chat-live-session.ts routes reads to a remote host when runtimeEnvironmentId is set — so a host running behind excludes the echo's own real turn. applyCommandMarkerBoundaries mixes the same two clocks. Both predate this PR; filed as [Bug]: Chat UI matches pending echoes across two clock domains — renderer send time vs remote transcript timestamps #11519.
  5. Agent-rewritten prompts (mention expansion, skill prefixes) never match, because normalization only strips the [Image #N] marker and collapses whitespace. This PR narrows that from permanent to until-the-conversation-is-replaced.
  6. COMMAND_MARKER_LIMIT = 8 evicts a /clear after nine later slash commands, after which applyCommandMarkerBoundaries stops hiding the cleared transcript. Pre-existing on main and it cannot strand an echo — rule 1 has already run by then — so it is noted rather than carried here. Raised by @brennanb2025 in review.

Line budget

native-chat-pending-occurrence.ts is close to its max-lines ceiling (the ratchet passes, no new bypass), though 2697c8ff31 brought it back down slightly. #10102 and #10639 both add to native-chat-pending.ts in the same area, so whichever lands last may need a split there — flagging it so it is not a surprise in a rebase.

grboy6770 and others added 2 commits July 29, 2026 14:46
…never match

An optimistic composer echo is cached per pane+agent and retires only by
matching its real user turn in the transcript. Nothing invalidated it when the
pane's conversation was replaced — `/clear`, an agent restart, or resuming a
different session — so a leftover echo could never match the new transcript and
stayed pinned at the list tail, rendering an old prompt as the newest message
for the rest of the pane's life.

Record the provider session an echo was issued into and keep only the echoes the
pane's current conversation can still match. Echoes sent before the session id
resolved (a fresh launch learns it after the first send) adopt the first id
observed instead of being dropped, so the first-turn empty-state flash the
pane+agent scope was protecting against does not come back. Echoes queued before
the latest `/clear` are dropped too, matching the transcript boundary that
`applyCommandMarkerBoundaries` already applies to real messages.

Moves the pending-send and command-marker state into
`useNativeChatPendingEchoes` so `NativeChatView` stays under its max-lines
ceiling; no behavior change in the moved code.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ion drops one

Repeat sends of the same text get an explicit `matchingOccurrence` so a later one
cannot reuse a transcript occurrence an earlier echo already consumed. That is
right for pruning, where a real user turn is what removed the predecessor.

Dropping an echo because its conversation was replaced consumes nothing — no turn
will ever arrive for it — so a survivor left numbered past it waits for a second
identical turn that cannot exist, and stays pinned at the list tail permanently.
Renumber each match key from 1 whenever the retain rule changes the set.
@coderabbitai

coderabbitai Bot commented Jul 30, 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

Native chat pending sends now record an optional provider session, filter echoes across session changes and /clear markers, and renumber surviving occurrences. The new useNativeChatPendingEchoes hook centralizes pending-send and command-marker cache management, transcript pruning, optimistic sends, cancellations, and resets. NativeChatView uses the hook instead of maintaining this state locally, and new tests cover conversation filtering and hook behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% 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 the primary fix for stale optimistic echoes after a conversation replacement.
Description check ✅ Passed The description includes all required sections, detailed testing results, review findings, cross-platform checks, security audit, and known limitations.

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.

@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a ghost-bubble bug where an optimistic composer echo, cached per paneKey + agent, could never be retired after the pane's conversation was replaced (via /clear, agent restart, or session resume) because the retirement path requires a transcript text match that no longer exists.

  • retainPendingSendsForConversation (new pure module) implements five rules to drop echoes that belong to a different provider session or predate a /clear boundary, while safely preserving echoes sent before the session id was known and tolerating the brief null window during reconnect.
  • withoutNativeChatPendingOccurrence / renumberNativeChatPendingOccurrences (new occurrence helpers) correctly distinguish between a conversation swap (renumber from 1, since no dropped echo's turn will arrive) and a cancelSend (shift siblings by 1, since trimmed predecessors still consumed a transcript slot).
  • useNativeChatPendingEchoes (new hook) extracts the ~80-line inline pending/marker block from NativeChatView and adds the retain effect with a markerState.scope !== commandMarkerScope guard to prevent a pane-move from evaluating the new pane's echoes against the previous pane's /clear markers.

Confidence Score: 5/5

Renderer-only change with no IPC, no new dependencies, and no user-visible state beyond removing a bubble that should never have been rendered.

The fix is narrow and well-bounded: it adds a filtering pass over an in-memory array of at most 8 entries, all guarded by the scope-identity check that prevents cross-pane interference. Every behavioral claim in the PR description is pinned by a failing test that passes with the fix, including the subtle asymmetry between conversation replacement (renumber from 1) and cancellation (shift by 1). The withoutNativeChatPendingOccurrence logic correctly handles the capped-out-echo case that would make full renumbering unsound on the cancellation path. No new side effects outside the existing pane-scoped caches.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/renderer/src/components/native-chat/use-native-chat-pending-echoes.ts New hook encapsulating all pending-echo state; fixes stale-markers issue via scope-identity guard; effects chain correctly through functional updaters
src/renderer/src/components/native-chat/native-chat-pending-conversation.ts New pure module implementing the five-rule retain filter; correctly guards the null-sessionId reconnect window and drops pre-/clear entries before the session check
src/renderer/src/components/native-chat/native-chat-pending-occurrence.ts Adds renumberNativeChatPendingOccurrences (renumber from 1 for conversation replacement) and withoutNativeChatPendingOccurrence (shift-by-1 for cancellation); asymmetry is intentional and correct
src/renderer/src/components/native-chat/native-chat-pending.ts Adds optional sessionId field to NativeChatPendingSend and exports latestClearSentAt; additive, backward-compatible change
src/renderer/src/components/native-chat/NativeChatView.tsx Removes ~80 lines of inline pending-echo logic and delegates to useNativeChatPendingEchoes; mechanical extraction, no behavioral change beyond the fix
src/renderer/src/components/native-chat/native-chat-pending-conversation.test.ts Comprehensive tests covering all five retain rules, including renumbering after a drop and independence of distinct match keys
src/renderer/src/components/native-chat/use-native-chat-pending-echoes.test.tsx Hook-level tests covering session swap, null-session bind, /clear interaction, pane-move stale-markers guard, cancelSend renumbering, and PENDING_SEND_LIMIT capped-echo safety

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[paneKey / agent / sessionId changes] --> B{markerState.scope === commandMarkerScope?}
    B -- No: stale markers, pane just moved --> C[bail out, wait one commit]
    B -- Yes: scopes aligned --> D[retainPendingSendsForConversation]
    D --> E{latest /clear sentAt?}
    E -- entry.sentAt <= clearedAt --> F[drop: pre-clear echo]
    E -- No clear or entry.sentAt > clearedAt --> G{current sessionId}
    G -- null: reconnect window --> H[keep all entries]
    G -- entry.sessionId === sessionId --> I[keep entry unchanged]
    G -- entry.sessionId == null, first-send case --> J[adopt: set sessionId]
    G -- entry.sessionId different --> K[drop: foreign session]
    F --> L{any dropped?}
    J --> L
    K --> L
    I --> L
    L -- Yes --> M[renumberNativeChatPendingOccurrences counts from 1 per key]
    L -- No --> N[return same reference]
Loading

Reviews (3): Last reviewed commit: "style(native-chat): cut the pending-echo..." | Re-trigger Greptile

…conversation

The chat surface is one portal per tab, so moving it to another leaf changes
paneKey in place: the pending and command-marker scopes both change in one
commit while the marker state still describes the leaf we came from. The retain
rule then measured the new pane's echoes against the previous pane's `/clear`
and wrote the drop to the module-level pane cache, where the correcting render
cannot restore it — `/clear` in one pane could delete a live, legitimately
pending echo in another. Carry the scope with the markers so the rule can tell
that a value still describes this conversation, and wait the one commit when it
does not.

Cancelling a send also released nothing. A cancelled send consumes no
transcript occurrence, so a later repeat of the same text kept waiting on a turn
that can never arrive. Renumbering from 1 is wrong here: PENDING_SEND_LIMIT
trims the oldest echo while its send still lands, so that turn still arrives and
still consumes an occurrence, and a conversation swap is the only case where
counting genuinely restarts. Shift only the later same-key siblings down by one.

@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)
src/renderer/src/components/native-chat/native-chat-pending-occurrence.ts (1)

252-261: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the new explanatory comments.

Keep the invariants, but reduce these multi-line implementation walkthroughs to brief rationale.

  • src/renderer/src/components/native-chat/native-chat-pending-occurrence.ts#L252-L261: summarize the cancellation-occurrence invariant.
  • src/renderer/src/components/native-chat/use-native-chat-pending-echoes.ts#L101-L105: summarize the stale-marker persistence risk.

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: 57edbffd-5f6e-47ea-960b-f64fa1940030

📥 Commits

Reviewing files that changed from the base of the PR and between 3001394 and e2d0d62.

📒 Files selected for processing (3)
  • src/renderer/src/components/native-chat/native-chat-pending-occurrence.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

`recordSend` carried the only member doc on the returned object; the other three
are equally part of the hook's contract and each has a non-obvious trigger
(a cancelled delayed Enter, a local-only system line, Stop).
@grboy6770

Copy link
Copy Markdown
Contributor Author

@coderabbitai on the docstring-coverage warning (27.27% vs 80%) — I've taken the part of it I think is real and I'm deliberately not taking the rest.

Taken (281e4aa): the object useNativeChatPendingEchoes returns is a contract, and only recordSend carried a member doc. cancelSend, recordSlashCommand and clearPending each have a non-obvious trigger, so they now say what it is — clearPending in particular fires from stopAgent (NativeChatView.tsx:294-301), which is not guessable from the name.

Not taken: the rest of what the metric counts is test helpers (renderEchoProps, renderEchoes) and inline arrow callbacks inside useCallback/useEffect. AGENTS.md asks for concise comments only where the code is non-obvious, and those callbacks already carry // Why: comments on the reasoning that actually needs explaining — the pane-cache write ordering, the scope guard, the occurrence release. Converting those to JSDoc, or adding docs to two-line test helpers, would raise the percentage while making the files harder to read, which is the opposite of what the repo instruction is asking for.

So this one stays as an accepted warning rather than a fix. Happy to add specific docstrings anyone names.

Two follow-ups filed for the limits this PR documents rather than fixes, so they are tracked outside the description: #11511 (a send that never reaches the agent has no recovery path — includes the label-semantics decision, where merged #9792 already settled the same question one way on mobile) and #11519 (the pending matcher compares renderer send time against remote-host transcript timestamps).

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- Repository comment guidance ---'
if [ -f AGENTS.md ]; then
  rg -n -i -C 3 'comment|docstring|documentation|non-obvious|concise' AGENTS.md || true
else
  fd -HI '^AGENTS\.md$' . -x sh -c 'printf "\n--- %s ---\n" "$1"; rg -n -i -C 3 "comment|docstring|documentation|non-obvious|concise" "$1" || true' sh {}
fi

printf '%s\n' '--- Hook outline ---'
ast-grep outline src/renderer/src/components/native-chat/use-native-chat-pending-echoes.ts --items all --view expanded

printf '%s\n' '--- Hook return-contract docs and stop-agent call site ---'
rg -n -C 5 'recordSend|cancelSend|recordSlashCommand|clearPending|stopAgent' \
  src/renderer/src/components/native-chat/use-native-chat-pending-echoes.ts \
  src/renderer/src/components/native-chat/NativeChatView.tsx

printf '%s\n' '--- Targeted commit diff ---'
git show --format=fuller --stat --find-renames 281e4aad4 --
git show --format= --find-renames 281e4aad4 -- \
  src/renderer/src/components/native-chat/use-native-chat-pending-echoes.ts \
  src/renderer/src/components/native-chat/use-native-chat-pending-echoes.test.tsx

Length of output: 15263


@grboy6770 Confirmed. Commit 281e4aad4 documents all non-obvious members of the NativeChatPendingEchoes return contract, including the Stop-driven clearPending path in NativeChatView.tsx.

The remaining metric count concerns trivial test helpers and implementation-local callbacks. Requiring JSDoc there would conflict with AGENTS.md’s concise, “WHY not HOW” comment guidance. The accepted warning is reasonable; I’m withdrawing the broad docstring-coverage finding. Noted the tracked follow-ups in #11511 and #11519.

🐇💭


✏️ Learnings added
Learnt from: grboy6770
URL: https://github.com/stablyai/orca/pull/11509

Timestamp: 2026-07-30T07:29:10.115Z
Learning: For native-chat TypeScript changes, document non-obvious members of exported hook-return contracts, but do not request boilerplate docstrings for trivial test helpers or implementation-local `useCallback`/`useEffect` callbacks merely to satisfy docstring-coverage metrics. Follow `AGENTS.md`: concise comments should explain non-obvious rationale (“WHY”), not obvious mechanics.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

…nale

AGENTS.md asks for the why in one line where possible; these had grown into
walkthroughs of the surrounding code. Same invariants, no mechanics.
@grboy6770

Copy link
Copy Markdown
Contributor Author

@coderabbitai taken in 66522f0 — you were right, and the guideline you cited is the one I'd invoked myself a comment earlier, so it applies to my own prose first. Net −20 lines of comment across the three files, same invariants kept:

  • withoutNativeChatPendingOccurrence: 10 lines → 4. Keeps why not renumber from 1 (only the removed send consumes no turn, so a pruned or capped-out predecessor's elevation must survive); drops the PENDING_SEND_LIMIT walkthrough, which the tests state better than prose can.
  • retain effect: 5 lines → 2. Keeps the risk (a leaf move changes both scopes in one commit; judging by the old pane's /clear writes a permanent drop); drops the description of how the correcting commit arrives.
  • I applied the same pass to two you didn't flag — renumberNativeChatPendingOccurrences (9 → 3, from the earlier commit) and the cancelSend and marker-state comments — plus the two test comments, rather than leave the file inconsistent.

Also removed a dead ids accumulator in the capped-echo test that was pushed to and never read.

pnpm lint and pnpm typecheck still exit 0; native-chat green at 62 files / 607 tests.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@grboy6770 Thanks for applying this consistently. The reduced comments retain the important rationale—especially the occurrence-ownership and cross-pane /clear safeguards—without duplicating what the tests already establish. Removing the unused ids accumulator is a nice cleanup as well.

🐇✨


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

… nothing

Adopting the first observed session id changes no membership, so renumbering
from 1 erased the slot a capped-out predecessor still owns and retired the
survivor against an already-consumed turn.
…actually vacated

Dense renumbering reset every match key, so dropping one echo could pull an
unrelated repeat send down onto a turn a real transcript reply had already
consumed. Count drops per match key and shift only that key's later siblings,
which also subsumes the adoption case.
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for this — stamping each echo with the session id it was sent into is the right shape, and the per-pane vs per-conversation framing made the diff easy to follow.

Heads up that I pushed two small commits to your branch rather than leaving them as inline comments, since both are in the new occurrence bookkeeping and read better as diffs. Each has a regression test that fails on revert.

  • c6acd073b1 — adoption was renumbering even though it drops nothing. When a fresh launch's session id resolved for the first time, rule 4 adopted the id onto pending echoes and renumbered every occurrence from 1. Adoption removes nothing, so that erased the slot an echo trimmed by PENDING_SEND_LIMIT still legitimately owns — the survivor then retired against an already-consumed turn and its bubble disappeared early. Same expected 1 to be 2 signature you already guard for cancelSend, just reached from a path that wasn't covered.
  • a132c25ae9 — a drop on one prompt renumbered an unrelated prompt. renumberNativeChatPendingOccurrences reset every match key densely from 1, so dropping an echo from a replaced session pulled an unrelated repeated prompt from occurrence 2 down to 1, onto a turn a real transcript reply had already consumed. Swapped it for a per-match-key shift-down: count drops per key, subtract only from that key's later siblings. That matches the semantics of your own withoutNativeChatPendingOccurrence, and it subsumes the first fix — the dense helper is now unused, so it's deleted.

Two requests, both asks rather than blockers:

1. Could you move withoutNativeChatPendingOccurrence and the cancelSend rewrite into a follow-up PR? It's a correct fix for a real bug, but it's a different bug: on main today, cancelling a send already strands a later identical echo, with no dependency on the stale-echo work here. Splitting it keeps this PR to its one thing and makes the cancel fix reviewable and revertable on its own. Happy to hear it if you think the two are more entangled than they look from the outside.

2. Could you adjust the PR body so it doesn't imply the never-resolved-session-id window is covered? If you send into a brand-new pane before the agent has reported any session id, then restart or resume a different session, the first id the renderer ever sees is the replacement's — rule 4 adopts the orphan into it and it still pins. That isn't a defect introduced here, and it's strictly better than main (where that echo ghosts forever instead of dying at the next swap), but the description currently reads as though the case is handled. Closing it properly needs a conversation epoch or restart marker on NativeChatSession, which doesn't exist yet.

One pre-existing issue I looked at and deliberately left alone, just so it isn't lost: COMMAND_MARKER_LIMIT = 8 means a /clear gets evicted after nine later slash commands, and applyCommandMarkerBoundaries then stops hiding the cleared transcript. That's already true on main and your echoes are safe from it — a conversation boundary probably shouldn't live in a rolling 8-slot ring, but that's its own change, not yours to carry here.

…markers by scope

Three mechanisms in the pending-echo path were bespoke where a plainer shape
already existed:

- `withoutNativeChatPendingOccurrence` (shift one slot for one removed index)
  and the `droppedByKey` loop in `retainPendingSendsForConversation` (shift N
  slots for a predicate) are the same operation written twice. Collapse both
  into `dropNativeChatPendingOccurrences(pending, shouldDrop)`; `cancelSend`
  loses its `findIndex` + not-found guard because an id predicate that matches
  nothing is already a no-op.
- The `{scope, markers}` state wrapper existed so the retain effect could skip a
  commit when its markers described the leaf it came from. Read the markers from
  the scope-keyed cache the effect is already keyed on instead — no staleness to
  detect, and the drop lands a commit earlier.
- The `useRef` mirror + `useCallback` stabilising `setWorkingInterrupted` is what
  `useEffectEvent` does in one line, as at SourceControl.tsx:1609 and
  mobile/src/session/use-initial-session-terminal-autocreate.ts:51. Event
  handlers call the setter directly, which the rules-of-hooks gate requires.

No behavior change: the pre-existing test files pass verbatim against this, and
reverting the marker read reproduces the original failure
(`expected [] to deeply equal [ 'leaf two prompt' ]`). Adds six direct tests for
the shared primitive, which two callers now depend on and which had none.
@brennanb2025

Copy link
Copy Markdown
Contributor

Audit pass on the head as it stands (author's commits + my earlier review fixes together). The diagnosis and the fix are right and are what ships — this only changes the mechanism in three places where the diff built something bespoke that the repo, or React, already gives us. Pushed as 2697c8ff31.

1. One occurrence-release primitive instead of two. withoutNativeChatPendingOccurrence (shift one slot, for one removed index) and the droppedByKey loop inside retainPendingSendsForConversation (shift N slots, for a predicate) are the same operation written twice — drop entries, then release exactly the same-key slots those drops vacated. The second copy is mine, from free only the occurrence slots a conversation drop actually vacated, so this is me held to the same bar as the rest. Both are now dropNativeChatPendingOccurrences(pending, shouldDrop). retainPendingSendsForConversation goes from 37 lines to 15 — a predicate plus a plain adopt map — and cancelSend loses its findIndex + not-found guard, because an id predicate matching nothing is already a no-op.

2. Read the markers by scope rather than tagging state with the scope. Your {scope, markers} wrapper + skip-a-commit guard fixes a real bug — the leaf move genuinely reaches it. But readCommandMarkerCache is a pure keyed read of a module Map, and the retain effect is already keyed on commandMarkerScope, so reading the cache inside the effect can't be stale at all, instead of detecting when it is. commandMarkers stays in the deps purely as the /clear trigger. That deletes the state wrapper and the guard, and the drop lands one commit earlier instead of deferred. Your test still pins it: reverting to markers: commandMarkers reproduces your exact original failure, expected [] to deeply equal [ 'leaf two prompt' ].

3. useEffectEvent for the suppression reset. You called this one yourself in the description. The useRef mirror + useCallback is what useEffectEvent does in one line, and we already use it at SourceControl.tsx:1609 and mobile/src/session/use-initial-session-terminal-autocreate.ts:51 for the same "caller recreates the callback every render" reason. The two scope effects use it; recordSend calls setWorkingInterrupted directly, which react-hooks/rules-of-hooks requires — Effect Events can only be called from Effects. That gate caught it when I first got it wrong, so it's enforced rather than remembered.

Behaviour unchanged, checked rather than asserted. I checked out your three test files at a132c25ae9 and ran them unmodified against the new source: 21/21 pass. Added six direct tests for the shared primitive, which two callers now depend on and which previously had none — per-key counting, unrelated keys untouched, undefined never invented, never below slot 1, and same-reference-when-nothing-dropped. native-chat is 701/701; oxlint, all three typecheck projects, the max-lines ratchet, and both React Doctor gates are clean.

Two small notes: renderEchoProps passed a fresh vi.fn() per render, which models a caller React doesn't have (the only one passes a useState setter) — it's hoisted now, though with useEffectEvent the setter is no longer in any dep array so it no longer matters either way. And native-chat-pending-occurrence.ts came down slightly net, which helps the ceiling you flagged under Line budget.

@grboy6770

grboy6770 commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor Author

@brennanb2025 Both asks are done, and your four commits are all in — I read them before touching anything and did not revert any of them.

1. Cancelled-send fix split out → #13513. cancelSend is back to the plain filter it has on main (da42f231ef), and its two regression tests moved with it. You are right that the strand has no dependency on the work here.

One constraint worth flagging: I only have read access to this repo, so I cannot push a branch here and target fix/native-chat-stale-pending-echo as the base. GitHub therefore diffs #13513 against main and shows this PR's commits alongside the one that matters. The header says to review the last commit only. Correction to what I wrote there first: this repo squash-merges, so those commits will not fall out of the diff on their own — rebasing #13513 onto the squashed main is a manual step, and I will do it as soon as this lands. If you would rather I hold #13513 until then, say so and I will close it and reopen after.

dropNativeChatPendingOccurrences stays here, since the conversation-retain path is its remaining caller — your unification in 2697c8ff31 made that the clean seam rather than a complication, so the split came out smaller than I expected when you first asked.

2. Description no longer implies the never-resolved-session-id window is covered. Rule 4 now says outright that it adopts by position rather than by identity, and that if the first id the renderer ever observes is already the replacement's, the orphan is adopted into it and still pins. It is Known limit 1, credited to you, with the note that closing it needs a conversation epoch or restart marker on NativeChatSession. Your COMMAND_MARKER_LIMIT = 8 observation is Known limit 6 so it is not lost — noted as pre-existing and not carried here, since rule 1 has already run by the time eviction could matter.

The description also now describes the head rather than my original diff: your three fixes are summarised in a Review rounds on this branch section, the occurrence semantics are stated as the per-key shift-down you landed rather than my renumber-from-1, and the stale-marker entry says your keyed readCommandMarkerCache read replaced my scope-tagged state.

Verification on this branch after the split — pnpm lint (ratchet included, no new bypasses) and all three pnpm typecheck projects exit 0; native-chat 93 files / 837 tests green. Full suite 3758 passed / 9 failed, all accounted for: 7 are the happy-dom localStorage stub under my local Node 25 against the repo's Node 24 floor, src/relay/agent-exec-handler.test.ts fails identically on origin/main (checked out and reran to confirm), and src/main/native-chat/transcript-watch-liveness.test.ts passes 7/7 alone and only fails inside the full run. #13513 is the same picture plus its two tests.

On #13513 I also reverted the source hunk alone against both tests to confirm they fail without it — expected [ 2 ] to deeply equal [ 1 ] and expected 3 to be 2.

…ts own PR

Cancelling a delayed Enter strands a later identical echo on `main` today,
with no dependency on the stale-echo work here — a separate bug that reviews
and reverts on its own. `cancelSend` goes back to the plain filter it had, and
its two regression tests move with it; `dropNativeChatPendingOccurrences`
stays because the conversation-retain path is its remaining caller.
@grboy6770
grboy6770 force-pushed the fix/native-chat-stale-pending-echo branch from 6387598 to da42f23 Compare August 10, 2026 06:29
grboy6770 added a commit to grboy6770/orca that referenced this pull request Aug 10, 2026
…taken

Repeat sends of identical text carry an explicit `matchingOccurrence` so a
later one cannot reuse a slot an earlier echo already consumed. Cancelling the
delayed Enter removes an echo without any transcript turn consuming its slot,
so the survivor is left waiting on a second identical turn that never arrives
and its bubble is stranded for the rest of the pane's life.

`dropNativeChatPendingOccurrences` shifts only the later same-key siblings down
by exactly one — not a renumber from 1, which would erase the slot an echo
trimmed at `PENDING_SEND_LIMIT` still legitimately owns (that send landed, so
its turn still arrives). Both cases are pinned by tests that fail on revert.

Split out of stablyai#11509 on review: the strand is reachable on main today with no
dependency on the stale-echo work there.
@brennanb2025

Copy link
Copy Markdown
Contributor

Native-chat QA (chat driver)

Drove the real native-chat surface on exact SHA 320d5a43893c7cc994a18b2530fbb96cb741802f.

Identity

CDP window.api.app.getIdentity() on the instance I drove:

  • name: Orca: 320d5a4389
  • devLabel: pr-11509-chat-qa @ 320d5a4389
  • devRepoRoot: this worktree
  • Sidebar showed Detached HEAD @ 320d5a4

01-identity-empty-chat.png

Sequence

  1. Opened a native chat with a Grok 4.6 agent and sent QA11509-STALE-ECHO-A. Optimistic echo appeared immediately.

02-echo-after-send.png

  1. After A resolved, sent QA11509-STALE-ECHO-C so a pending echo existed (pendingSendCache held QA11509-STALE-ECHO-C on session 01a002c3-…). C never landed in that session's transcript.

11-after-c-send-attempt.png

  1. Replaced the conversation with a new provider session from the agent's dashboard (Enter: create). TUI showed session 01a002cd-df25-7b20-8c85-dfb01bc3892b.

27-new-session-status.png

  1. When the hook published the new session id, the stale C echo was dropped. Chat showed only the new-session wake turn. No A/B/C bubbles. pendingSendCache for C was empty.

29-chat-after-hook-update.png

  1. Sent QA11509-LIVE-ECHO-D after replacement. Echo appeared, tagged with session 01a002cd-… (not dropped).

32-d-sent-echo.png

  1. D resolved to a real transcript turn (OKAY). C never reappeared.

33-d-resolved.png

Result

Check Result
Stale pending echo dropped after conversation replace Yes — C gone from UI and from pendingSendCache
Post-replacement echo still works Yes — D echoed, then pruned when its real turn landed
Over-drop of live echoes Not observed

Residual gaps

  • Grok has no verified slash catalog, so /clear is not classified as a command here and does not write a /clear marker. Replacement was proven via a new provider session, which is the other path this change covers.
  • The first-id adoption window called out in the PR (Known limit 1) was not exercised.
  • Multi-pane / occurrence-renumber cases were not driven in the live UI (covered by unit tests on the branch).

@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for all the work here, and for splitting out #13513 when I asked — your diagnosis was right and it led somewhere useful.

I've opened #15032 as a replacement rather than merging this one, and I want to be straight about why.

Two things pushed it that way:

  1. Nobody had actually reproduced the defect. This PR closes no issue, and the QA I ran only demonstrated the fixed behaviour. So before writing anything I reproduced it on unmodified main: send under conversation A, replace the conversation, and the orphan echo survives prune, re-persists to the pane cache on every transcript tick, and pins at the list tail across every remount. Your diagnosis was correct — that's now pinned by failing tests on main.

  2. The fix belongs at the layer your own root-cause section named. You wrote that pendingSendScopeKey keys the cache by paneKey + agent with no conversation identity — but the fix kept that key and added a retain pass on top. fix(native-chat): scope optimistic echoes to the conversation they were sent into #15032 puts conversationId in the scope itself, so a replaced conversation's echoes are unreachable by construction. That removes the retain pass, the adoption-by-position rule, and the occurrence-slot shifting entirely — including the residual window you flagged yourself, where an orphan adopted into the replacement still pins.

The one rule that survives is a one-shot bootstrap claim for the window before the agent reports a session id, since that was the genuinely hard part.

To be clear: this isn't a knock on the work. Your root cause was right and I reused your test intent where it still applied. #15032 credits this PR and refs it. #13513 is unaffected and still stands on its own.

I'd rather explain the reasoning than close this quietly — happy to discuss if you see something the new shape gets wrong.

@grboy6770

grboy6770 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor Author

No objection to #15032 replacing this — the call and the reasoning both hold. Leaving the close itself to you rather than doing it myself.

On the two points. (1) Reproduction: fair, and the gap was mine. I never demonstrated the defect on unmodified main, and the QA on this branch only showed the fixed state. (2) Layer: agreed. I named pendingSendScopeKey's missing conversation identity as the root cause and then fixed one layer above it. Putting conversationId in the scope makes the orphan unreachable by construction, which removes the retain pass, adoption-by-position and the occurrence-slot shifting rather than keeping them correct — including Known limit 1, which rule 4 could not close.

One handover item, since it does not travel with this PR. #13513 is stacked on this branch and its merge-order note ("needs #11509 first, then I rebase onto the squashed main") is now void. The strand it fixes survives in #15032 — onOptimisticSendCanceled is a plain filter, so cancelling one of two identical sends still leaves the survivor holding matchingOccurrence: 2 against a transcript that only ever produces one turn. And dropNativeChatPendingOccurrences does not exist on main (I introduced it here) and #15032 does not add it, so that PR needs the helper and its tests carried inside it rather than a rebase. I will rebuild #13513 on top of main once #15032 lands; say the word if you would rather I close it and reopen fresh. I have posted the same note over there so it is not lost.

Thanks for the review time — the four commits you pushed were all in the head that shipped here.

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.

3 participants