Skip to content

fix(chat): keep reader position when loading earlier messages - #4121

Closed
AKnassa wants to merge 7 commits into
meta:mainfrom
AKnassa:ak-4102-chat-windowing
Closed

AKnassa wants to merge 7 commits into
meta:mainfrom
AKnassa:ak-4102-chat-windowing

Conversation

@AKnassa

@AKnassa AKnassa commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Refs #4102

In one breath

Chat list. You scroll up to read older messages. The app loads more history on top. Before: the page jumped and you lost your place. Now: your spot stays put, a small spinner shows while the page loads, and older pages keep coming until the history runs out. Same API, the existing scrollToTopAction prop now just behaves.

Why

#4102 weighs two paths for long transcripts: load-earlier (Option A) vs a virtualization plugin (Option B). Option A's core affordance already shipped, scrollToTopAction predates the issue; but it teleported the reader on prepend (CSS scroll anchoring is suppressed at scrollTop 0, exactly where the sentinel fires), went dead after one load, could double-fire, and reconnected its observer on every render. This finishes Option A with zero new props. Option B stays open and untouched.

What changed

1-initial-bottom 2-loading-spinner 3-after-prepend-position-held 4-second-page-loaded
  • No jump: the first visible message is anchored when the load starts; after the prepend commits, one measured scrollTop adjustment restores it. Measured means it composes with native scroll anchoring — and backs off entirely if the reader scrolled away mid-load.
  • Both alignments: align="top" has no spacer, so the anchor falls back past the spinner to the sentinel; a load that fires as the previous one resolves still anchors a message, never the spinner.
  • Late stores work: compensation waits for children to actually change, so consumers whose action resolves before their store notifies (React Query style) keep their position too.
  • One load at a time; the action lives in a ref so inline props don't churn the observer; aria-busy while loading so screen readers don't announce old history as new messages.
  • Underfilled lists keep loading until they can scroll (an empty page stops the cycle). Standalone lists (no ChatLayout) compensate against their nearest scrollable ancestor, including legacy overflow-y: overlay scrollers, via utils/getScrollableAncestor, now shared with Outline (internal; Outline keeps its overflow requirement, the list opts out because an underfilled scroller cannot scroll yet).
  • Docs state the contract (JSDoc + doc.mjs en/zh/dense): apply messages before the promise resolves, keep keys stable, pass undefined when history is exhausted.

How to check

  • Storybook: Core/ChatLayout → "Load Earlier History" - 100 messages, pages of 20. Scroll to the top repeatedly; your place holds until history runs out. "Load Earlier History (Top Aligned)" is the same with align="top".
  • 21 new unit tests (33 total in ChatMessageList.test.tsx) plus 7 for getScrollableAncestor, written red-first.
  • Real Chromium (Playwright on both stories): anchor drift 0px across three prepends each (20→40→60→80), 1160px compensated per page, for align="bottom" and align="top"; no snap-back when the reader scrolls away mid-load. Screenshots below.

Notes

Full suite green; the only failures are the 13 pre-existing packages/cli ones reproducible on untouched main.

ChatMessageList's scrollToTopAction fired at scrollTop 0, exactly where
CSS scroll anchoring is suppressed, so prepended history teleported the
reader and the sentinel never re-armed after the first load.

- Anchor-based compensation: capture the first content element and its
  offset in the resolved scroll container at fire time; restore it per
  commit until the prepend lands. Measured, not assumed, so it composes
  with native anchoring and bails when the reader scrolls mid-load.
- Single-flight guard; the action lives in a ref so inline callbacks no
  longer reconnect the IntersectionObserver every render.
- aria-busy while loading so prepended history is not announced as new.
- Underfilled lists keep loading until they overflow.
- Standalone lists compensate the nearest scrollable ancestor, not the
  page.

Adds 15 tests (IntersectionObserver + rect-stub harness), a Storybook
'Load Earlier History' story, and doc.mjs contract notes.

Refs meta#4102
@vercel

vercel Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
astryx Ready Ready Preview Sep 26, 2026 4:28am UTC

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 21, 2026
@github-actions github-actions Bot added community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge labels Jul 21, 2026
@github-actions

github-actions Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR

🧪 Sandbox Preview

View Sandbox for this PR

Modified Components

Outline (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 697 -
Complexity N/A High (28) -

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.9KB 1.2KB

Accessibility Audit

Status: 3 accessibility violation(s) found — 3 serious.

ChatComposer - 1 issue(s)
  • 🟠 serious: Ensure the contrast between foreground and background colors meets WCAG 2 AA minimum contrast ratio thresholds
    • Rule: color-contrast · Affects 1/19 stories · Learn more
    • WCAG: 1.4.3 (Level AA)
ChatComposerInput - 1 issue(s)
  • 🟠 serious: Ensure the contrast between foreground and background colors meets WCAG 2 AA minimum contrast ratio thresholds
    • Rule: color-contrast · Affects 1/16 stories · Learn more
    • WCAG: 1.4.3 (Level AA)
ChatToolCalls - 1 issue(s)
  • 🟠 serious: Ensure the contrast between foreground and background colors meets WCAG 2 AA minimum contrast ratio thresholds
    • Rule: color-contrast · Affects 10/11 stories · Learn more
    • WCAG: 1.4.3 (Level AA)

Visual Regression

Status: No visual change across 420 compared shot(s).


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

- accept the deprecated overflow-y: overlay like Outline's
  getScrollableAncestor, and document why findScrollContainer
  deliberately has no scrollHeight > clientHeight requirement
- pin coalesced IntersectionObserver delivery, the empty-page
  auto-refill bound, and standalone nearest-scroller compensation
- settle the dangling refill action in the underfilled-list test:
  React runs async transition actions on one global chain, and a
  forever-pending load wedges every later transition commit

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

Thanks for this, it's careful work and the tests are the best part.

align="top" landed on main after you opened this, and it omits the spacer. Your anchor is the spacer's next sibling, so a top-aligned list anchors nothing and the reader lands 20 messages from where they were. I measured 1160px of lost position on your own story with align="top"; no test sets it, so the suite stays green either way.

Ideally I'd like the anchor to fall back to the sentinel, which is there whenever scrollToTopAction is:

const anchor = (spacerRef.current ?? sentinelRef.current)?.nextElementSibling;

Same at the prepended check. I tried it on the merge — both alignments hold, all 30 tests still pass.

You need a merge with main anyway; can that come with it?

If you'd rather talk it through with someone, we're in Discord.

[Reviewed by Robohands]

loadEarlierInFlightRef.current = true;

const resolvedContainer = container ?? document.scrollingElement;
const anchor = spacerRef.current?.nextElementSibling;

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.

align="top" on main drops the spacer, so this goes null after the merge.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 75c0ca0. The anchor is now the first message element: after the spacer, else after the spinner while a load is pending, else after the sentinel. Same at the prepended check.

The spinner step is needed: with only the sentinel fallback, a load that fires as the previous one resolves (spinner still mounted) anchors the spinner, which unmounts and disarms the compensation. Three tests cover align="top": position held across a prepend, a late prepend, and that back-to-back case.

* require scrollHeight > clientHeight: an underfilled list's scroller
* cannot scroll *yet*, and the auto-refill cycle must still target it.
*/
function findScrollContainer(el: Element | null): Element | null {

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.

Outline has this at useScrollSpy.ts:60. Might be worth sharing rather than a second copy.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shared in 75c0ca0 as utils/getScrollableAncestor.ts, used by Outline and ChatMessageList. Outline keeps its scrollHeight > clientHeight requirement (the default); ChatMessageList passes requireOverflow: false, since an underfilled list's scroller cannot scroll yet and the auto-refill cycle must still target it.

Kept out of utils/index.ts, which the package entry re-exports. lab's ListInput keeps its own copy for that reason.

@cixzhang

Copy link
Copy Markdown
Contributor

Checking in on chat scroll preservation: top-aligned lists still need a sentinel fallback anchor after merging main. Would you like to continue, have us carry it, or close this for now?

`align="top"` (meta#3933) omits the bottom spacer, so the anchor (the
spacer's next sibling) was null and a top-aligned list lost its
reading position on every prepend.

- Anchor on the first message element: after the spacer, else after
  the spinner while a load is pending, else after the sentinel. Same
  at the prepended check. The spinner step matters when a load fires
  as the previous one resolves: anchoring the spinner disarms as soon
  as it unmounts.
- Share the scrollable-ancestor walk with Outline via
  utils/getScrollableAncestor (internal; utils/index is public API).
  Outline keeps its overflow requirement by default; ChatMessageList
  opts out, since an underfilled list's scroller cannot scroll yet.
- Add a top-aligned variant of the Load Earlier History story.

Adds 3 tests for align="top" and 7 for the helper.

Refs meta#4102
@github-actions
github-actions Bot requested a review from cixzhang August 27, 2026 23:43
@github-actions github-actions Bot added the needs:design-review Affects visuals — Design should review label Aug 27, 2026
@AKnassa

AKnassa commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Continuing. Merged main (align, #3933) and addressed both threads in 75c0ca0:

  • Anchor: falls back past the spacer to the spinner, then the sentinel, at capture and at the prepended check. Three align="top" tests.
  • Scroll container: one getScrollableAncestor helper for Outline and ChatMessageList, with the overflow requirement as an option.

A "Load Earlier History (Top Aligned)" story now sits next to the existing one. Headless Chromium on both stories, three pages each: 0px anchor drift, 1160px compensated per page. ChatMessageList.test.tsx is at 33 tests, the helper has 7, Outline's suite is unchanged and green.

@astracat-bot astracat-bot 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.

Thanks for finishing the load-earlier path — preserving position, single-flight loads, and support for both alignments are well covered.

One fix is needed before approval:

  • After a final page loads nothing and the consumer removes scrollToTopAction (the documented exhaustion flow), the prepend anchor in ChatMessageList is never cleared. Later rerenders keep performing synchronous geometry reads on every commit, and a stale anchor could still adjust scrollTop. Please add a terminal settlement for that no-op case (without breaking late prepends while the action is still present) and extend the empty-page test to remove the action, rerender with the same first message, and verify geometry is no longer read.

Tests and Storybook could not be run in this review environment, so please include the focused test results with the fix.

[Automated review]

Resolved conflicts:
- packages/core/src/Chat/ChatMessageList.tsx: file-header @input line.
  Kept both sides: the PR's useIsomorphicLayoutEffect/getScrollableAncestor
  inputs and upstream's isRenderable empty-state input (ddb63c3).
- packages/core/src/Chat/ChatMessageList.test.tsx: file-header docblock and
  vitest import. Took upstream's docblock and imported
  {describe, it, expect, vi, beforeEach, afterEach}; upstream's two new tests
  ('renders an accepted numeric empty state', 'loads older messages through
  the top sentinel and exposes pending status') are kept and pass.
With the default align="bottom", an empty final page followed by the
consumer passing scrollToTopAction={undefined} left the prepend anchor
armed: the first message never changed, so no disarm condition fired.
Every later commit then forced layout (anchor + container
getBoundingClientRect), and a stale anchor could scroll the list, e.g.
by 40px when a banner was rendered above the first message.
align="top" already disarmed, because removing the sentinel leaves no
first-message element.

astracat F1: the layout effect now also disarms once the load has
settled and the action is gone. The check runs after the delta
compensation, so a final page that prepends and removes the action in
the same commit still holds position, and late prepends while the action
is present work as before.
- 'leaves the scroll untouched when the action loads nothing' now
  removes the action, rerenders with the same first message and asserts
  no further anchor reads, then adds a banner above it and asserts
  scrollTop stays 0. Before the fix: "expected 3 to be +0" (anchor
  reads) and "expected 40 to be +0" (scrollTop). After: passes.
- New guard, 'compensates a final page that also removes the action'
  for align="bottom" and "top": scrollTop 37 -> 437, passing before and
  after the fix.

astracat F2: ChatMessageList.test.tsx 37/37; with getScrollableAncestor,
Outline, ChatLayout and useChatStreamScroll suites 133/133.
The pre-commit hook (lint-staged: eslint --fix, prettier --write) ran on
every staged file of merge 8c1559a and rewrote the formatting of 12
upstream files this PR never touches. Restore them byte-for-byte from the
merge's upstream parent (82fb22c) so the PR diff against main lists only
the PR's own 8 files. Committed with --no-verify because the same hook
would reformat them again.

Restored: apps/storybook/stories/MobileTokenizer.stories.tsx,
internal/vibe-tests/stepper-collapse-naming-test/PLAN.md and
docs/arm-{a-collapsed,b-bare,c-summary,d-enum,recall}.md,
packages/core/src/Carousel/Carousel.test.tsx,
packages/core/src/Chat/__tests__/ChatMessageMetadata.a11y.chromium.spec.ts,
packages/core/src/TextInput/TextInput.test.tsx,
packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx,
packages/lab/src/MobileTokenizer/MobileTokenizer.tsx.
@AKnassa

AKnassa commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Pushed up to aa7f7a1:

  • Merged main (8c1559a). The only conflicts were in the ChatMessageList header/imports and the test file header. Upstream's two new tests are kept and pass. The pre-commit hook reformatted 12 upstream files during the merge, so aa7f7a1 restores them and the diff is back to the PR's own 8 files.
  • Anchor after history runs out (74217e1): with the default align="bottom", if the final page loaded nothing and the consumer then removed scrollToTopAction, the prepend anchor stayed armed. Every later commit did a geometry read, and a stale anchor scrolled the list 40px when a banner was rendered above the first message. align="top" already cleared it. The layout effect now also clears the anchor once the load has settled and the action is gone. The check runs after compensation, so a final page that prepends and removes the action in the same commit still holds position. Late prepends while the action is present work as before.
  • Tests: "leaves the scroll untouched when the action loads nothing" now removes the action, rerenders with the same first message and asserts no more reads. It then adds a banner and asserts scrollTop stays 0. Both assertions failed before the fix. There's also a new guard, "compensates a final page that also removes the action", for both alignments. ChatMessageList.test.tsx passes 37/37. With the getScrollableAncestor, Outline, ChatLayout and useChatStreamScroll suites it's 133/133.

@cixzhang your review still shows changes requested. The sentinel fallback and shared helper went in with 75c0ca0, so could you take another look? Also, the new ChatMessageList.spec.md lists overlap/single-flight as OQ1, and this PR runs one load at a time. Do you want me to update FR6/OQ1 here, or would you rather handle the spec yourself?

@astracat-bot astracat-bot 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.

Thanks for the careful follow-up — the remaining issue from the last review is addressed cleanly.

  • The prepend anchor now disarms once a settled load leaves no scrollToTopAction, so the documented exhaustion flow (empty final page, then passing undefined) no longer leaves geometry reads running on later commits or risks a stale scroll adjustment. Placing the disarm after the delta compensation preserves the late-prepend behaviour, and the new tests cover both sides: the empty-page case now removes the action and asserts no further anchor reads or scroll change, and a both-alignments guard proves a final page that prepends while removing the action still holds position.

No other issues were found: the public API is unchanged, both alignments and standalone scrollers are covered, and the shared scrollable-ancestor helper keeps Outline's existing behaviour. Tests and Storybook could not be run in this review environment (dependencies unavailable offline), so please let the pending checks on this head finish before merging.

[Automated review]

github-actions Bot added a commit that referenced this pull request Sep 26, 2026
@cixzhang

Copy link
Copy Markdown
Contributor

Closing as stale to reduce CI load; feel free to reopen or push a fresh branch if it's still needed. Posted by Cindy's agent on her behalf.

@cixzhang cixzhang closed this Oct 28, 2026
@github-actions
github-actions Bot deleted the ak-4102-chat-windowing branch October 29, 2026 12:17

This branch was successfully deployed

1 active deployment
Preview — aa7f7a17 Deployed Sep 26, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot. community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge needs:design-review Affects visuals — Design should review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants