Repository navigation
fix(native-chat): keep an older page from punching a hole in the transcript - #19845
Conversation
…script Since the retained-item cap (#19841), `items` sits exactly at its limit after any page-back, so every later live batch head-trims one item. If a batch lands while an `agentSession.history { direction: 'before' }` read is in flight, the head moves newer than the cursor that read was anchored on, and merging the response leaves a gap between the page and the retained window -- content that is silently missing and unreachable, because paging again only walks older. Carry the requested cursor on the `older-page` action and drop a page whose anchor the retained head has already passed. Both readers (renderer read owner, mobile state hook) re-anchor and retry a bounded number of times, so a slide costs an extra round trip instead of a hole.
📝 WalkthroughWalkthroughOlder-history loading now uses full cursors instead of epochs. The reducer rejects pages whose retained head moved past the requested sequence. Desktop and mobile readers retry reads when live updates move the oldest cursor, with a maximum of three attempts. Tests cover stale-anchor rejection and successful window expansion. Merge Risk: 🔵 Low · up to On mobile, loading earlier chat history can silently do nothing if a session reset keeps the same oldest sequence. Compare the full cursor before applying the page so the read can re-anchor correctly. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the defect, fix, and verification, but it omits most required template sections, including ELI5, What Changed, Why, Visual Proof or an explicit N/A justification, Testing checkboxes, Review, Notes, the upstream-boundary checkbox, and the Checklist. The linked issue is referenced as Resolution Complete the required template sections. Add ELI5, What Changed, Why, Linked Issue with
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: e1d4683e-ea84-4c57-8aa7-9b9776e0d749
📒 Files selected for processing (5)
mobile/src/session/use-mobile-structured-agent-state.tssrc/renderer/src/components/native-chat/structured-agent-session-read-owner.tssrc/shared/structured-agent-session-item-retention.test.tssrc/shared/structured-agent-session-reducer.test.tssrc/shared/structured-agent-session-reducer.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| if (oldestStructuredAgentSessionCursor(stateRef.current)?.sequence === cursor.sequence) { | ||
| apply({ type: 'older-page', requestedCursor: cursor, page: result.page }) | ||
| return |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Compare the complete cursor before applying the page.
If a reset changes the epoch but retains the same oldest sequence, Line 185 accepts the stale anchor. The reducer rejects requestedCursor because its epoch is old. The function then returns, so the Load-earlier action has no effect.
Compare both cursor fields before applying the page.
Proposed fix
- if (oldestStructuredAgentSessionCursor(stateRef.current)?.sequence === cursor.sequence) {
+ const currentCursor = oldestStructuredAgentSessionCursor(stateRef.current)
+ if (
+ currentCursor?.epoch === cursor.epoch &&
+ currentCursor.sequence === cursor.sequence
+ ) {
apply({ type: 'older-page', requestedCursor: cursor, page: result.page })
return
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (oldestStructuredAgentSessionCursor(stateRef.current)?.sequence === cursor.sequence) { | |
| apply({ type: 'older-page', requestedCursor: cursor, page: result.page }) | |
| return | |
| const currentCursor = oldestStructuredAgentSessionCursor(stateRef.current) | |
| if ( | |
| currentCursor?.epoch === cursor.epoch && | |
| currentCursor.sequence === cursor.sequence | |
| ) { | |
| apply({ type: 'older-page', requestedCursor: cursor, page: result.page }) | |
| return |
There was a problem hiding this comment.
ℹ️ No critical issues — one minor suggestion inline.
Reviewed changes
older-pagecarries the full anchor cursor — the action now takesrequestedCursor: AgentJournalCursorinstead of a bare epoch, giving the reducer the sequence it needs to detect a slid anchor.- Reducer rejects a stale-anchored page — when
state.items[0].sequence > requested.sequence(a live batch head-trimmed past the anchor), the page is dropped rather than merged, so the silent transcript hole from #19841 cannot form. - Re-anchor-and-retry readers — both the renderer read-owner and the mobile hook re-capture the oldest cursor and retry up to 3 times when the head slides mid-read, trading an extra round trip for a dropped page.
- Load-bearing tests — new reducer tests pin the drop-on-slide and accept-on-intact-anchor cases; the drop test fails against the pre-fix reducer.
ℹ️ Nitpicks
- The re-anchor-and-retry loop is only exercised indirectly through the reducer tests; neither reader has a test that simulates a mid-read head slide to assert the retry (and its 3-attempt bound) actually fires.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| return | ||
| } | ||
| // The reducer drops a page whose anchor slid, so only an intact anchor lands. | ||
| if (oldestStructuredAgentSessionCursor(stateRef.current)?.sequence === cursor.sequence) { |
There was a problem hiding this comment.
The re-anchor check reads stateRef.current, which is only synced in useLayoutEffect and can lag the sessionStates map the reducer actually mutates. Unlike the renderer's live snapshot closure, a mid-read head-trim can leave stateRef.current on the pre-trim head, so the check passes, apply runs, and the reducer silently drops the page without the retry firing. No hole results, but on a busy stream mobile's load-earlier can no-op where the renderer would re-anchor and retry.
| return | ||
| } | ||
| // The reducer drops a page whose anchor slid, so only an intact anchor lands. | ||
| if (oldestStructuredAgentSessionCursor(stateRef.current)?.sequence === cursor.sequence) { |
There was a problem hiding this comment.
Technical details
# Mobile re-anchor retry is best-effort
## Affected sites
- mobile/src/session/use-mobile-structured-agent-state.ts:185 — re-checks `oldestStructuredAgentSessionCursor(stateRef.current)` against the captured `cursor`
## Required outcome
- The retry should detect a head slide as reliably as the renderer's `snapshot` closure does, or the divergence should be accepted and documented.
## Why it diverges
- `apply` mutates the `sessionStates` Map via a `setSessionStates` functional updater; the freshest state exists only inside that updater.
- `stateRef.current` is written in `useLayoutEffect`, so between `setSessionStates` and the next commit it still holds the pre-trim head.
- Correctness (no hole) is still guaranteed by the reducer guard, which reads the fresh Map; only the retry's effectiveness is affected.
## Suggested approach (optional)
- Have `apply`'s updater write the reduced `next` back into a ref so `stateRef` tracks the reducer's committed state at the earliest possible point, or accept the occasional silent no-op (user re-taps) and note it in a comment.
Follow-up from the adversarial review of #19841.
The defect
#19841 head-trims
state.itemstoretainedItemLimiton every live batch. Two consequences combine:retainedItemLimit === items.lengthexactly (older-pageraises the floor topaged.length), so every subsequent live item trims one off the head.loadOlder/loadEarliercapture the anchor cursor before awaitingagentSession.history { direction: 'before' }.If a batch lands during that round trip, the head moves newer than the captured cursor. Merging the response then leaves a gap between the page and the retained window — items that are in the journal, absent from the transcript, and unreachable, because the next page walks older still. Only reopening the session recovers them.
Reproduced at the reducer level (proof kept as the new
drops an older page whose anchor a live batch trimmed pasttest — it fails onmain's reducer with the guard removed).Before #19841 there was no trim, so
loadOldercould not produce a gap. Renderer and mobile both have the pattern.The fix
older-pagecarriesrequestedCursor: AgentJournalCursorinstead ofrequestedEpoch: string(same information plus the anchor sequence; no new field).refreshTail's restore loop counts slides separately so a busy stream cannot keep it looping.Verification
pnpm tc,check:code-quality:changedclean.pnpm test src/shared/structured-agent-session-*.test.ts src/renderer/src/components/native-chat— 127 files / 1277 tests pass.