Skip to content

fix(chat): position the first fill instantly + scrollToBottom({behavior: 'instant'}) (#3795) - #3800

Merged
cixzhang merged 4 commits into
meta:mainfrom
yyq1025:chat-initial-scroll
Jul 19, 2026
Merged

cixzhang merged 4 commits into
meta:mainfrom
yyq1025:chat-initial-scroll

Conversation

@yyq1025

@yyq1025 yyq1025 commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #3795.

Opening a chat that already has content (history, replay, session switching) spring-flies from scrollTop: 0 across the whole transcript. Root cause confirmed on #3795: the layout's ResizeObserver fires its callback synchronously on registration, so the follow spring starts before the hook's rAF-deferred initial jump runs — async fills fall into the streaming path. Per the arbitration there, this is now a pure behavior fix with no new component surface:

  • The first fill positions instantly by default, whether the content is present at mount or arrives asynchronously. A pending flag is consumed by the first scrollIfLocked that sees scrollable content, mirroring use-stick-to-bottom's previousHeight ? resize : initial. Subsequent growth (streaming) springs exactly as today.
  • scrollToBottom({behavior?: 'instant' | 'spring'}) — one-frame programmatic jump that cancels any in-flight spring and zeroes velocity, so a stale animation tick can't fight the assignment. Shape matches scrollToMessage's behavior: 'instant' in the same file and the DOM's scrollTo/scrollIntoView. Default 'spring' is byte-identical to today.

The earlier initial prop ('spring' | 'instant' | false) is dropped per review: instant first-fill is unconditionally correct and needs no opt-in, and the false/start-at-top value is the scroll side of #2572's align/anchor axis — deferred to that arbitration. ChatLayout.tsx and ChatLayout.doc.mjs are untouched relative to main.

Change

  • useChatStreamScroll.ts: unconditional first-fill guard (pending flag consumed by the mount jump or the first scrollable scrollIfLocked), jumpToBottom internal (cancels in-flight spring, zeroes velocity), behavior option on scrollToBottom. Exports ChatScrollToBottomOptions.
  • Chat/index.ts: type export.
  • Changeset: @astryxdesign/core patch ([fix]).

No public API is removed or changed; scrollToBottom() with no arguments behaves exactly as before. The only behavior change is the first fill no longer spring-scrolling from the top.

Verification

  • 9 tests: 7 in useChatStreamScroll.test.tsx (first coverage for this hook), 2 in ChatLayout.test.tsx exercising the full ResizeObserver → scrollIfLocked path with the FakeResizeObserver pattern from useChatNewMessages.test.tsx — first fill positions synchronously, later growth stays on the spring. jsdom has no layout, so tests cover the synchronous paths only; the spring physics stays under manual/Storybook verification (rationale in the test file header).
  • pnpm -F @astryxdesign/core test Chat/useChatStreamScroll Chat/ChatLayout: 17/17 pass. Typecheck and eslint on touched files: clean.
  • Manual verification: consumed from a WKWebView-based Claude Code session GUI — transcript replay lands at the latest message with no animation on open and on session switch, with no props passed; streaming follow unchanged.

Follow-ups

🤖 Generated with Claude Code

@vercel

vercel Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
astryx Ready Ready Preview, Comment Jul 19, 2026 3:54pm

Request Review

@meta-cla

meta-cla Bot commented Jul 11, 2026

Copy link
Copy Markdown

Hi @yyq1025!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 11, 2026
@meta-cla

meta-cla Bot commented Jul 11, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@cixzhang cixzhang added area:core needs:code-review High-risk change (new package/component/API) — needs human code review before merge and removed area:core labels Jul 11, 2026
@github-actions github-actions Bot added the community Authored by a community contributor (not on the eng/design team) label Jul 12, 2026

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

Reviewed against the mechanism — the core fix is right and the first-fill guard is exactly the correct shape (mount snapshot + a pending flag consumed by the first scrollIfLocked that sees scrollable content, mirroring use-stick-to-bottom's previousHeight ? resize : initial). jumpToBottom cancelling the in-flight spring and zeroing velocity before the assignment is the right call — that's the race that caused the original bug.

Two things to settle (see the arbitration on #3795):

1. Scope — the initial prop is broader than the bug. The behavior fix (instant first fill + instant imperative) fully resolves this issue on its own with no new public surface on ChatLayout. The initial prop mixes in an initial-position concern — specifically false/start-at-top, which is the scroll side of #2572's align/anchor axis. I'd suggest landing the behavior fix here and arbitrating the position knob on #2572 so we don't ship two overlapping surfaces (ChatLayout initial={false} vs ChatMessageList align="top") that later have to be reconciled. If you'd rather keep initial in one PR, at minimum let's get #2572 sign-off first so the naming unifies.

2. Imperative shape — behavior over instant. scrollToMessage in this same file already uses behavior: 'instant', and the DOM's scrollTo/scrollIntoView use behavior: 'instant' | 'smooth'. scrollToBottom({behavior?: 'instant' | 'spring'}) stays consistent with both the sibling API and the platform; a bare {instant: boolean} is a third convention. Mechanical rename either way.

Tests read well — the FakeResizeObserver + rAF-queue harness exercises the real scrollIfLocked path, and documenting the jsdom-no-layout limitation (sync paths only) is the honest framing. Nice to see the hook get its first coverage.

Not blocking on my end — mainly want the scope/naming settled against #3795 + #2572 before this leaves draft.

@github-actions
github-actions Bot requested review from cixzhang and ejhammond July 13, 2026 10:36
@yyq1025 yyq1025 changed the title feat(chat): initial first-fill scroll positioning + scrollToBottom({instant}) (proposal for #3795) fix(chat): position the first fill instantly + scrollToBottom({behavior: 'instant'}) (#3795) Jul 13, 2026
@yyq1025

yyq1025 commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Both points landed as suggested — thanks for digging into the mechanism on #3795, the observeResize sync-fire vs rAF-deferred-jump framing made the scope call easy.

  • The initial prop is gone. Instant first-fill is now the unconditional default: a pending flag consumed by the mount jump or the first scrollIfLocked that sees scrollable content. ChatLayout.tsx and ChatLayout.doc.mjs are untouched relative to main, and the changeset is reframed as [fix].
  • The imperative is now scrollToBottom({behavior: 'instant' | 'spring'}), default 'spring' — matching scrollToMessage and the DOM.

I'll file the prefers-reduced-motion gap as a separate issue, with jumpToBottom as the natural fallback. Marking ready for review.

@yyq1025
yyq1025 marked this pull request as ready for review July 13, 2026 10:52

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

Thank you for adding this, this looks good! Our next release will need on Thursday.

@cixzhang
cixzhang enabled auto-merge (squash) July 14, 2026 04:20
@github-actions github-actions Bot removed the needs:code-review High-risk change (new package/component/API) — needs human code review before merge label Jul 14, 2026
@github-actions

github-actions Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

No new or modified components detected.

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.7KB 0B

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | View full report

yyq1025 and others added 4 commits July 19, 2026 15:51
…ant})

The hook already positions instantly when content is present at mount
(the 'Initial scroll to bottom' rAF), but content that arrives after
mount (async-loaded conversations) misses it and gets the streaming
spring instead. The new 'initial' option extends the existing intent:

- 'spring' (default): today's behavior, byte-identical paths
- 'instant': the first fill positions in one synchronous step whether
  content is present at mount or arrives later; later growth springs
- false: skip initial positioning entirely and start unlocked — the
  scroll half of top-anchored reading surfaces (meta#2572)

scrollToBottom(options) gains {instant: true} for one-frame
programmatic jumps (cancels any in-flight spring). Exports
ChatScrollInitial and ChatScrollToBottomOptions.

Tests cover the synchronous paths only — jsdom has no layout, so the
spring physics stays under manual/Storybook verification (rationale in
the test file header).
Forwards the new useChatStreamScroll 'initial' option as a ChatLayout
prop, so opening an existing conversation can land on the latest
message with no animation (initial='instant'), or start at the top
with follow disengaged (initial={false}). Default stays 'spring'.

Docs: en/zh/dense prop entries in ChatLayout.doc.mjs. Tests exercise
the full ResizeObserver -> scrollIfLocked path at the layout level
(FakeResizeObserver, same pattern as useChatNewMessages.test).
Address review on the PR (arbitration on meta#3795):

- First-fill instant positioning becomes the default behavior with no
  new public surface. The initial prop ('spring' | 'instant' | false)
  is removed from ChatLayout and useChatStreamScroll; the false /
  start-at-top axis is deferred to meta#2572's align/anchor arbitration.
- scrollToBottom({instant: boolean}) becomes scrollToBottom({behavior:
  'instant' | 'spring'}), consistent with scrollToMessage in this file
  and the DOM's scrollTo/scrollIntoView.

Co-Authored-By: Claude Fable 5 <[email protected]>
CI never ran on this head, leaving required status checks (build/lint/test/
docsite-test) missing and the PR unmergeable. Empty commit to kick off a fresh
run.
@cixzhang
cixzhang force-pushed the chat-initial-scroll branch from 4391d25 to d7ac544 Compare July 19, 2026 15:52
@cixzhang
cixzhang merged commit 4812e5b into meta:main Jul 19, 2026
17 checks passed
@github-actions
github-actions Bot deleted the chat-initial-scroll branch July 20, 2026 09:29
humbertovirtudes pushed a commit that referenced this pull request Jul 24, 2026
…on (#4104)

Follow-up promised in #3800: the rAF spring in useChatStreamScroll
ignored prefers-reduced-motion. All spring entry points funnel through
startAnimation, which now falls back to the existing jumpToBottom under
the preference — locked following, scrollToBottom(), and lock() still
track the bottom, just without animated travel.

Co-authored-by: Claude Fable 5 <[email protected]>
cixzhang pushed a commit that referenced this pull request Sep 4, 2026
)

* fix(chat): gestures vouch for their scroll instead of unlocking (#5662)

`onWheel` and `onTouchMove` gated on `animatingRef`, which has meant "we
are following" only by coincidence. #4104 added a reduced-motion path
that follows without ever starting a spring, so both handlers became
permanent no-ops for readers with reduced motion, and the remaining
release path — `onScroll`'s direction check — is blind exactly when it
matters, since arriving content changes the geometry on nearly every
event.

Restores the arbitration this hook was extracted from (#1249): the
gesture does not unlock, it clears the suppression so the scroll it
produces is read as intent. Here that means waiving the synthetic-resize
guard for the frames the gesture covers and letting the direction check
decide. A gesture this scroller never consumed — a wheel over a nested
scrollable child, an overscroll at the bottom — produces no scroll event
and now leaves following alone, where before it released the tail
whenever the spring was live. `touchstart` replaces `touchmove` for the
reason it was the original listener: it fires once, before any movement,
and needs no per-drag bookkeeping.

`jumpToBottom` (#3800) also cleared `animatingRef` while `lockedRef`
stayed true, which no other caller did, so a running loop survived its
own cancellation and the next `startAnimation` stacked a second one on
top (#5663). A generation token makes the documented cancel real; with
the gesture handlers off `animatingRef`, it is loop bookkeeping again.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(chat): a resize clamp landing on the bottom is never a release

A finger resting on a nested scrollable child bubbles `touchstart` to
the chat scroller, so the gesture waiver was live for a drag this
scroller never consumed. If an earlier block collapsed while the finger
was down, the browser clamped `scrollTop` up to the new bottom and the
waived guard read that clamp as the reader scrolling: following
released, and the lines streamed next stayed below the fold. The wheel
waiver had the same hole, two frames wide.

A clamp can only ever land on the new maximum, and a reader scrolling
up never lands there. So a scroll that arrives with changed geometry
and ends at the bottom is the clamp regardless of any gesture, and the
guard now keeps it synthetic. The waiver still lets a real scroll-up
through while content is arriving, which is what it was for.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* refactor(chat): cancel the spring's frame instead of tagging generations

The loop's continuation is always one pending rAF handle, and
`jumpToBottom` only ever runs from an event or another frame callback,
so `cancelAnimationFrame` on that handle is an exact cancel — the same
`rafRef` shape `useChatDictation` and `useSpeechRecognition` use.
`animate` goes back to taking no argument, and the generation counter,
its per-frame closure, and the check at the top of the tick are gone.

The test double now hands out real ids and honours cancellation, so the
stacked-loop test keeps proving the same thing. Comments around the
synthetic-resize guard and the wheel waiver are folded down to what the
code no longer says on its own.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(chat): only a gesture this scroller consumes waives the guard

A bubbled gesture was treated as ownership of every scroll that
followed. With the spring trailing a fast stream, a finger resting on a
nested scroller plus a collapse above the viewport moved scrollTop up
by scroll anchoring — not a clamp, so it did not land on the bottom —
and the waived guard read the shift as the reader. Following released.

Ownership now comes from the gesture itself. A wheel up vouches only
when no vertically scrollable element between its target and this
scroller still has room above; scroll chaining hands a gesture outward
only from a scroller at its edge. A drag records its target and finger
position on touchstart and vouches from the first touchmove that pushes
this scroller up, under the same nested check, until the finger lifts.
A resting finger is not a gesture. The bottom-landing rule stays for the
one clamp a consumed gesture can still coincide with: an overscroll at
the bottom while a block above collapses.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(chat): own the position while following instead of judging gestures

Every revision so far inferred whether a scroll was the reader's from
the gesture that preceded it, and every inference has a counterexample:
a bubbled touchstart, a nested scroller at its edge, then one with
`overscroll-behavior: contain`. The question was never who owns the
gesture. It is what can move a following container up other than the
reader, and there are two answers: the resize clamp onto the bottom,
and CSS scroll anchoring.

The clamp lands exactly on the bottom, which the guard already checks.
Anchoring is switched off on the scroll element while following and
restored when not — the hook is the only writer of the position while
locked, so anchoring has nothing to do there, and a reader up in the
history keeps it. With that, any upward scroll that does not land on
the bottom is the reader, and the wheel and touch listeners, the
gesture waiver, the two-frame expiry, and the synthetic-resize tracking
all go. Same shape as ListInput (#4740) and LegendList's
maintainVisibleContentPosition, for the same reason.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(chat): hand back the scroll element's own overflow-anchor

Unlocking wrote '' over whatever inline overflow-anchor the consumer had
set, so a scroller that had disabled anchoring itself got it back once
the reader scrolled up. Capture the element's inline value when the
hook takes it over and restore that value on unlock and on cleanup.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(chat): judge a scroll against the hook's own last write

Two ownership gaps from review. A reader's wheel that lands between two
spring frames was compared against the last observed position, and the
next frame's write outran it — net position still advanced, so the
reader stayed pinned. The spring now records the position it wrote, so
the coalesced scroll event that follows reads below it and releases;
the same comparison use-stick-to-bottom makes against the position it
set (`ignoreScrollToTop`).

And the anchoring switch no longer goes through the element's inline
style at all. It is an attribute, `data-astryx-chat-following`, and one
injected rule with `!important`, the pattern `highlightRanges` uses for
its dynamic stylesheet. A consumer's own `overflow-anchor` is never read,
written or restored — whatever they set, before or during a lock, is
what applies once the attribute is gone.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>

This branch was successfully deployed

1 active deployment
Preview — d7ac5445 Deployed Jul 19, 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)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Chat: no instant scroll path — opening an existing conversation spring-scrolls from the top

2 participants