Skip to content

fix(native-chat): release the occurrence a cancelled send would have taken - #13513

Open
grboy6770 wants to merge 10 commits into
stablyai:mainfrom
grboy6770:fix/native-chat-cancelled-send-occurrence
Open

grboy6770 wants to merge 10 commits into
stablyai:mainfrom
grboy6770:fix/native-chat-cancelled-send-occurrence

Conversation

@grboy6770

@grboy6770 grboy6770 commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #11509 — review the last commit only (fix(native-chat): release the occurrence a cancelled send would have taken).

The fix lives in use-native-chat-pending-echoes.ts, a file #11509 creates, so this branch is built on top of it. I only have read access to this repo, so I cannot push the parent branch here and target it as a base — GitHub therefore diffs this against main and shows #11509's commits alongside mine. This repo squash-merges, so they will not fall out of the diff on their own — once #11509 lands I will rebase this branch onto the new main, which leaves exactly the one commit. Ping me and it is done the same day; I will also do it unprompted as soon as I see #11509 merge. Split out at @brennanb2025's request on that PR, since the strand below is reachable on main today with no dependency on the stale-echo work there.

Summary

Repeat sends of identical text carry an explicit matchingOccurrence, so a later echo cannot retire against a transcript turn an earlier one already consumed. Cancelling the delayed Enter (detach, interrupt) removes an echo without any transcript turn consuming its slot — the survivor is left numbered past a sibling that no longer exists, waits for a second identical user turn that can never arrive, and its "queued" bubble is stranded at the list tail for the rest of the pane's life.

Send ping, send ping again, cancel the first: the survivor holds matchingOccurrence: 2 and the transcript only ever produces one ping.

Change

cancelSend releases the slot through dropNativeChatPendingOccurrences, which shifts only the later same-key siblings down by exactly one.

Deliberately not a renumber from 1, which Greptile suggested on #11509 and which I measured to be wrong on this path. PENDING_SEND_LIMIT = 8 trims the oldest echo while its send still landed, so its transcript turn still arrives and still consumes an occurrence — a survivor can legitimately hold slot 3+ with no pruning involved. Renumbering from 1 erases that trimmed echo's real slot and retires the survivor against an already-consumed turn (expected 1 to be 2). A conversation swap replaces the transcript, so renumbering from 1 is right there; a cancellation replaces nothing, so only the one slot it vacated is released.

Screenshots

No visual change in the fixed state — this removes a bubble that should never have stayed on screen. Both behaviours are pinned by tests that fail on revert.

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, no new bypasses) and all three pnpm typecheck projects exit 0. native-chat is green at 93 files / 839 tests. Full suite: 3759 files passed, 8 failed, 9 skipped (39757 tests passed, 43 failed, 71 skipped) — 0 new failures:

  • 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.
  • src/relay/agent-exec-handler.test.ts (2 tests) fails identically on origin/main; I checked it out and reran to confirm.

Nothing in native-chat fails, and the same run on the parent branch differs only by the two tests this PR adds.

Differential evidence — I reverted the source hunk alone, kept both tests, and ran them:

× releases the occurrence a cancelled send would have taken
  AssertionError: expected [ 2 ] to deeply equal [ 1 ]
× keeps the occurrence a capped-out echo still owns when a later send is cancelled
  AssertionError: expected 3 to be 2
Tests  2 failed | 6 passed (8)
Test What it pins
releases the occurrence a cancelled send would have taken the strand itself — survivor drops to slot 1 and retires normally
keeps the occurrence a capped-out echo still owns when a later send is cancelled the over-correction — a trimmed echo's slot survives, so exactly one slot is released, not all of them

dropNativeChatPendingOccurrences already carries six direct tests from #11509 (per-key counting, unrelated keys untouched, never inventing an occurrence, never below slot 1, same-reference when nothing dropped); this change adds the second caller they were written for.

AI Review Report

Reviewed as part of #11509 and carried over intact — the code and both tests are byte-identical to what was reviewed there, only the PR boundary changed.

  • Pure logic: the asymmetry between "conversation replaced" (renumber from 1) and "send cancelled" (shift by one) is the whole point of the change and is the part most worth disagreeing with; the capped-out-echo test is what makes it falsifiable rather than an argument.
  • React effects: cancelSend is a useCallback over pendingScope that reads the pane cache, transforms, and writes back — no new effect, no new dependency, no new render path.
  • Cross-platform: explicitly checked. Renderer-only pure TypeScript — array filtering and integer arithmetic over at most 8 entries. No paths, no shell, no shortcuts or key handling, no user-visible strings or labels (no localisation surface), no process.platform branch, and no Electron main/preload/IPC surface. Nothing here can behave differently on macOS, Linux, or Windows.
  • Bot review on fix(native-chat): drop optimistic echoes a replaced conversation can never match #11509 raised this gap (P2) and proposed the dense renumber; the measurement above is why the fix takes a different shape than suggested.

Security Audit

No new attack surface.

  • Input handling: none added. The predicate compares an internally-minted pending id (nextNativeChatPendingSendId) for equality; no external input is parsed, evaluated, or rendered.
  • Command execution / path handling: none. No PTY write, no filesystem path.
  • Auth / secrets: none touched.
  • IPC: unchanged — no new channel, handler, or payload shape.
  • Dependencies: none added.
  • Memory/DoS: operates on the existing pane cache, bounded at PENDING_SEND_LIMIT = 8; the pass is O(n) over at most 8 entries and allocates no new retained state.
  • Follow-up: none required.

Notes

grboy6770 and others added 8 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.
…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.
`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).
…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.
… 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.
…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.
@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Pending native-chat state now includes optional provider session IDs and conversation-aware retention. A new occurrence helper preserves transcript slots when entries are removed. The useNativeChatPendingEchoes hook manages pending sends, command markers, pruning, cancellation, and clearing. NativeChatView now uses the hook. Tests cover session changes, /clear, pane movement, stale echoes, cancellation, and occurrence handling.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% 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 identifies the native-chat cancellation fix and the occurrence slot it releases.
Description check ✅ Passed The description covers the required summary, screenshots, testing, AI review, security audit, and notes sections with sufficient detail.

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.

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

125-130: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Export and derive the capped-pending test values from PENDING_SEND_LIMIT.

native-chat-pending.ts keeps 8 pending sends, but the tests in use-native-chat-pending-echoes.test.tsx hardcode 9 sends and a length of 8. Export the constant and compute loop/size values from it so changing the cap does not require multiple unrelated magic-number edits.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8c160202-dfab-47f5-b7a2-b73b358667fb

📥 Commits

Reviewing files that changed from the base of the PR and between 016df33 and 328854aa3d17af318bbd3b2b5194ea5f233d0258.

📒 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-occurrence.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

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

grboy6770 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Status update — the merge-order note in the description above is now void.

#11509 is not landing — @brennanb2025 opened #15032 as a replacement and I have said on that PR that I have no objection. This branch was stacked on #11509 because the fix lives in a file that PR creates, so "rebase onto the squashed main once #11509 lands" no longer describes anything that will happen.

The strand is still real on #15032

Its use-native-chat-pending-echoes.ts handles cancellation as a plain filter:

const onOptimisticSendCanceled = useCallback(
  (pendingId: string) => {
    const next = readPendingSendCache(pendingScope).filter((entry) => entry.id !== pendingId)
    setPending(writePendingSendCache(pendingScope, next))
  },
  [pendingScope]
)

No occurrence release. So ping / ping / cancel the first still leaves the survivor holding matchingOccurrence: 2 while the transcript only ever produces one ping, and the bubble strands exactly as described above. Conversation-scoping the cache key does not reach this path — a cancellation replaces no conversation, so the key is unchanged and the survivor is read back with its stale occurrence.

What this PR needs is a rewrite, not a rebase

  1. The entry point renamed: cancelSend → onOptimisticSendCanceled.
  2. dropNativeChatPendingOccurrences does not exist on main — I introduced it in fix(native-chat): drop optimistic echoes a replaced conversation can never match #11509, and fix(native-chat): scope optimistic echoes to the conversation they were sent into #15032 does not add it (it touches native-chat-pending-occurrence.test.ts only, not the module). So this PR has to carry the helper and its six direct tests itself, which changes both its size and its review surface.

The semantics stay what the description argues: shift only the later same-key siblings down by one, never a dense renumber from 1, because PENDING_SEND_LIMIT trims the oldest echo while its send still landed and its transcript turn still arrives.

Plan

I will rebuild this on top of main once #15032 merges, and rewrite the description then — the stacked-branch header and the merge-order note both go away, and the diff becomes the helper plus the cancellation fix plus their tests. Until then this cannot be reviewed meaningfully, so please treat it as blocked on #15032 rather than stale.

Happy to close it and open a fresh PR at that point instead, if you would rather not carry an open one that long — your call, @brennanb2025.

The CodeRabbit nitpick on this branch (derive the capped-pending test values from PENDING_SEND_LIMIT rather than hardcoding 9 and 8) I will fold into the rewrite.

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.

4 participants