Skip to content

fix(native-chat): keep an older page from punching a hole in the transcript - #19845

Merged
nwparker merged 1 commit into
mainfrom
nwparker/structured-session-older-page-anchor
Sep 10, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/structured-session-older-page-anchor

Conversation

@nwparker

@nwparker nwparker commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​44 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​42
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​79 $\color{#cf222e}{\Huge{\mathbf{−}}}$​42 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​37

Follow-up from the adversarial review of #19841.

The defect

#19841 head-trims state.items to retainedItemLimit on every live batch. Two consequences combine:

  1. After any page-back, retainedItemLimit === items.length exactly (older-page raises the floor to paged.length), so every subsequent live item trims one off the head.
  2. loadOlder / loadEarlier capture the anchor cursor before awaiting agentSession.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 past test — it fails on main's reducer with the guard removed).

Before #19841 there was no trim, so loadOlder could not produce a gap. Renderer and mobile both have the pattern.

The fix

  • older-page carries requestedCursor: AgentJournalCursor instead of requestedEpoch: string (same information plus the anchor sequence; no new field).
  • The reducer drops a page whose anchor the retained head has already passed, rather than merging a discontiguous one.
  • Both readers re-anchor on the current head and retry, bounded at 3 attempts, so a slide costs an extra round trip instead of a hole. refreshTail's restore loop counts slides separately so a busy stream cannot keep it looping.

Verification

  • pnpm tc, check:code-quality:changed clean.
  • pnpm test src/shared/structured-agent-session-*.test.ts src/renderer/src/components/native-chat — 127 files / 1277 tests pass.
  • Mutation check: disabling the reducer guard fails the new drop test and nothing else, so the coverage is load-bearing.
  • Mobile typecheck run standalone on the changed file (mobile deps are not installed in this worktree; CI covers the project).

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

coderabbitai Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

Older-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 add9e

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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 chec… Complete the required template sections. Add ELI5, What Changed, Why, Linked Issue with Fixes #19841``, Visual Proof or the exact N/A justification, Testing details and checkboxes, AI Disclosure if applicable, Review, Agent skill upstream b…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the native-chat transcript defect and the fix that prevents older pages from creating a gap.
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.
Full details: Description check

Explanation

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 #19841 but is not declared with the required Fixes format.

Resolution

Complete the required template sections. Add ELI5, What Changed, Why, Linked Issue with Fixes #19841``, Visual Proof or the exact N/A justification, Testing details and checkboxes, AI Disclosure if applicable, Review, Agent skill upstream boundary, Notes, and the Checklist.

  • Fix all pre-merge checks with AI
✨ 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: e1d4683e-ea84-4c57-8aa7-9b9776e0d749

📥 Commits

Reviewing files that changed from the base of the PR and between 34790ce and add9e8c.

📒 Files selected for processing (5)
  • mobile/src/session/use-mobile-structured-agent-state.ts
  • src/renderer/src/components/native-chat/structured-agent-session-read-owner.ts
  • src/shared/structured-agent-session-item-retention.test.ts
  • src/shared/structured-agent-session-reducer.test.ts
  • src/shared/structured-agent-session-reducer.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

Comment on lines +185 to +187
if (oldestStructuredAgentSessionCursor(stateRef.current)?.sequence === cursor.sequence) {
apply({ type: 'older-page', requestedCursor: cursor, page: result.page })
return

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

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.

Suggested change
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

@pullfrog pullfrog 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.

ℹ️ No critical issues — one minor suggestion inline.

Reviewed changes

  • older-page carries the full anchor cursor — the action now takes requestedCursor: AgentJournalCursor instead 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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) {

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.

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) {

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.

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.

@nwparker
nwparker merged commit f2d5711 into main Sep 10, 2026
30 checks passed
@nwparker
nwparker deleted the nwparker/structured-session-older-page-anchor branch September 10, 2026 10:10
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