Skip to content

fix(chat): only the reader can release auto-follow (#5662, #5663) - #5678

Merged
cixzhang merged 8 commits into
meta:mainfrom
yyq1025:chat-follow-arbitration
Sep 4, 2026
Merged

cixzhang merged 8 commits into
meta:mainfrom
yyq1025:chat-follow-arbitration

Conversation

@yyq1025

@yyq1025 yyq1025 commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #5662. Fixes #5663.

onWheel and onTouchMove gated on animatingRef — "a rAF loop is live" — as a stand-in for "we are following". #4104 added a prefers-reduced-motion path that follows without ever starting a spring, so for readers with reduced motion the predicate is never true and both handlers are dead (#5662). The remaining release path, onScroll's direction check, returns early whenever the geometry changed on that event — and while content is arriving it changes on nearly every event, which is exactly when a reader wants out. The same conflation is behind #5663: jumpToBottom (#3800) clears animatingRef while lockedRef stays true, so the running loop never reaches its own exit and the next startAnimation opens a second one beside it.

What this does. While following, the hook owns the container's position. It marks the scroll element data-astryx-chat-following while locked, and one injected rule turns scroll anchoring off under that attribute; the element's own inline overflow-anchor is never touched. With anchoring off, the only move the browser makes on its own is the resize clamp onto a new, smaller bottom — and a reader scrolling up never lands on the bottom. So the arbitration is one exact rule: a scroll that lands above the last position the hook set or saw, and not on the bottom, is the reader. The spring records each position it writes, so a reader's move that lands between two frames still reads as below it even when the next frame's write outran it. No gesture is consulted, in either motion mode.

Earlier revisions of this branch inferred whether a scroll was the reader's from the gesture before it — first a touchstart waiver, then a walk from the event target for a nested scroller with room above. Each had a counterexample raised in review: a bubbled touchstart under a resize clamp, a resting finger under an anchoring shift, a nested scroller at its edge 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 the answer is two things, one exact and one switchable.

Unlocked, anchoring is restored: a reader up in the history wants the browser to hold their place when content above them changes (#4102 counts that among ChatLayout's advantages, and #4121's load-earlier compensation falls back to it). Locked, the spring is already the authority on the position, so anchoring has nothing to do — the same reasoning under which ListInput (#4740) and LegendList's maintainVisibleContentPosition switch it off.

Change

useChatStreamScroll.ts only:

  • setLocked(locked) — the one place lockedRef changes; it also toggles data-astryx-chat-following on the scroll element. A single <style data-astryx-chat-following-style> is injected once per document with [data-astryx-chat-following]{overflow-anchor:none !important} — the pattern highlightRanges uses for its dynamic rules. Riding on an attribute rather than the inline style means a consumer's own overflow-anchor, set before or during a lock, is never read, written or restored; it simply applies again once the attribute is gone. !important so an inline auto cannot switch anchoring back on under a following container; an inline !important still wins, deliberately. Toggled directly at each transition, not from an effect, so there is no render between a lock change and the attribute.
  • onScroll — unlocks on scrollTop < lastScrollTop unless the scroll landed on the bottom (scrollHeight - scrollTop - clientHeight < 1; clientHeight rather than the existing dist, since offsetHeight includes borders and a horizontal scrollbar). lastScrollTop is now the last position the hook set or saw: animate() records each write, as jumpToBottom and scrollToMessage already did, so the coalesced scroll event after a wheel that landed between two frames reads below the write and releases — the comparison use-stick-to-bottom makes against ignoreScrollToTop. The scrollHeight/offsetHeight tracking and the synthetic-resize early return are gone; a resize that does not move scrollTop is not an upward scroll, and one that clamps lands on the bottom.
  • The wheel, touchstart, touchmove, touchend, touchcancel listeners are gone.
  • rafRef — the spring's pending frame; jumpToBottom calls cancelAnimationFrame on it. The loop's continuation is always exactly one pending handle, so the cancel is exact, and loops cannot stack ([Bug] jumpToBottom does not cancel the in-flight spring, so animation loops stack #5663). Same shape as useChatDictation and useSpeechRecognition.

About the size of main's (+71/−67). No public API change: no prop, option, return value or export is added or altered.

Verification

  • Unit — useChatStreamScroll.test.tsx: 8 new tests, 5 of which fail on main (scroll-up release while content grows; the same under reduced motion; anchoring owned while locked and handed back when not; a scroll-up the next spring frame outruns still releases; no stacked loops). The other 3 pin what must not regress: content growing alone keeps following; a resize clamp onto the new bottom does not release; the element's own inline overflow-anchor is never touched, whether set before the lock or changed during it (fourth and fifth review rounds). packages/core/src/Chat: 191/191. tsc --noEmit, eslint, prettier, check:changesets clean.
  • Chromium — a probe story with a nested overflow-y: auto; overscroll-behavior: contain block, 80 lines streamed at 16ms, a 100px block above the viewport collapsed mid-stream. The tab was headless, so rAF ran on timers; layout and anchoring are the browser's own.
    • Wheel up over the contained nested block while the spring trailed by 266px, then the collapse: scrollTop 2458 → 2478 (no anchoring shift, just the spring), following throughout, 4px from the bottom at the end. This is the third review's case.
    • Reader scrolls the container up 300px during streaming: released, overflow-anchor back to the element's own inline value ('' in the probe).
    • Then the same collapse while released: scrollTop 2108 → 2008, exactly the collapsed height — the reader's place held by the browser.
    • Counterfactual: anchoring forced back on while following, same collapse: scrollTop 2406 → 2331 and the hook read it as the reader — released. That is why it is off while locked.
    • Inline overflow-anchor: auto set by the caller while following: computed value stays none under the attribute rule.
    • The outrun case (a −100px wheel between spring frames, net position still advancing) is pinned by the unit test that encodes the coalesced event; it was not re-measured headed here.

Follow-ups

  • With an external scrollRef on document.documentElement, overflow-anchor is written on the root element; per CSS Scroll Anchoring, the viewport's scrolling box is generated by the root, so it applies, but the browser runs above used an element scroller.
  • Safari has no scroll anchoring, so the property is a no-op there and the rule holds without it.
  • The injected rule is !important, so a consumer who needs anchoring on under a following container would have to say so with an inline !important; nothing in the library does.

…#5662)

`onWheel` and `onTouchMove` gated on `animatingRef`, which has meant "we
are following" only by coincidence. meta#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 (meta#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` (meta#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 (meta#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]>
@vercel

vercel Bot commented Aug 29, 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 4, 2026 3:58am UTC

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 29, 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 Aug 29, 2026
@github-actions

github-actions Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

Modified Components

Chat (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 5542 -
Complexity N/A Very High (455) -

Bundle Size Summary

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

Accessibility Audit

Status: No accessibility violations detected.

Visual Regression

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


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

github-actions Bot added a commit that referenced this pull request Aug 31, 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.

Readers using nested scroll content can lose auto-follow even though they never moved the chat. touchstart marks every parent scroll as gesture-owned until touchend, so an unrelated content shrink bypasses the resize guard and unlocks the parent; later streamed content then stays behind.

I reproduced this in Chromium on the exact head: after nested touch + parent clamp + growth, main followed to 1077/1079px, while this head stayed at 79/1079px. Please keep parent resize clamps synthetic unless the chat scroller actually consumed the gesture.

[Reviewed by Robohands]

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]>
@github-actions
github-actions Bot requested a review from cixzhang September 3, 2026 21:29
@yyq1025

yyq1025 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Good catch, and the repro is exactly right: the drag waiver was scoped by time, and touchstart bubbles from a nested scroller, so a clamp inside that window was read as the reader.

Fixed in 40e1e19: the guard now keeps a scroll synthetic when the geometry changed and it landed on the bottom, regardless of any gesture in flight. A resize clamp can only ever land on the new maximum, and a reader scrolling up never lands there, so the landing point decides ownership exactly. I went this way rather than walking from e.target for a scrollable ancestor at touchstart: ownership can't see scroll chaining at the nested scroller's edge, where the parent does consume the drag, and the same rule also closes the two-frame window on the wheel side.

Added a test that mirrors your sequence (nested touchstart → parent shrink clamp → still locked); it failed on the previous head and passes now, packages/core/src/Chat 191/191. In Chromium with the same setup, streaming ended 853px from the bottom before and 11px after. PR body updated to match.

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]>

@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 fixing the full-clamp case, but the parent still treats a bubbled gesture as ownership of any non-bottom geometry change. In Chromium on this exact head, while follow trailed streaming by 576px, a nested touch plus a 100px collapse above preserved that distance (1344/2320 → 1244/2220), yet landedAtBottom was false, so the resize guard was bypassed and the parent unlocked. The no-gesture control stayed locked; touch and wheel reproduced in three runs. Please make the parent waive the synthetic guard only when its own scroll was caused by that input, rather than adding another geometry heuristic.

[Reviewed by Robohands]

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]>
@github-actions
github-actions Bot requested a review from cixzhang September 3, 2026 23:13
@yyq1025

yyq1025 commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Agreed — the landing-point rule only covered the clamp, and a bubbled gesture was still standing in for ownership. 063d25a makes ownership come from the gesture itself.

scrollUpConsumedBelow(target, el) walks from the event target up to the scroller; a vertically scrollable element in between that still has room above takes the gesture, since scroll chaining only hands one outward from a scroller at its edge. A wheel up that is not consumed below vouches for its two frames as before. A drag records its target and finger position on touchstart and vouches from the first touchmove that moves the finger down and is not consumed below, until the finger lifts; a finger that rests without moving is not a gesture, so in your sequence nothing is waived and the anchoring shift stays synthetic. landedAtBottom remains for the one clamp a consumed gesture can still coincide with (a drag at the bottom that moves nothing while a block above collapses).

Tests mirror your sequence (1344/2320 → 1244/2220 under a resting nested touchstart, still locked), plus a drag and a wheel a nested scroller consumes, and a nested scroller at its top handing the drag to us — the first three failed on the previous head. In Chromium with real TouchEvents on a probe story: resting finger on the nested block plus a mid-stream collapse stays following; a drag on the nested block with room above stays following; a drag on the container itself, and one on the nested block at its top, both release. 195/195 in packages/core/src/Chat.

The red CI is packages/cli/api/search/search.mjs failing tsc --project tsconfig.api-dts.json on the merge with current main — not touched here; it came in with #5289 and #5994 is the fix.

@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 tightening the nested-scroll cases. Readers can still lose auto-follow because the parent predicts ownership from a descendant’s scrollTop, rather than observing whether the chat scroller moved. In Chromium, a nested scroller at its top with overscroll-behavior: contain kept both scrollers stationary; after 100px above collapsed, the parent flipped from locked to unlocked. The identical no-wheel control stayed locked, and a focused regression test fails 1/22. This is the same ownership gap as the prior review: an edge is not proof that chaining reached the parent. Please make the resize waiver depend on the chat scroller actually consuming the input, rather than adding another descendant exception. If you'd rather talk it through with someone, we're in Discord.

[Reviewed by Robohands]

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 (meta#4740) and LegendList's
maintainVisibleContentPosition, for the same reason.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@github-actions
github-actions Bot requested a review from cixzhang September 4, 2026 00:07
@yyq1025 yyq1025 changed the title fix(chat): gestures vouch for their scroll instead of unlocking (#5662, #5663) fix(chat): only the reader can release auto-follow (#5662, #5663) Sep 4, 2026
@yyq1025

yyq1025 commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

You're right, and the contain case settles it: any rule that predicts ownership from a descendant is inference, and each round found the next counterexample. 3879ba8 stops inferring.

The question I should have asked is what can move a following container up other than the reader. There are two things: the resize clamp onto a new bottom, and CSS scroll anchoring. The clamp lands exactly on the bottom, which a reader scrolling up never does. Anchoring is now switched off on the scroll element while locked (overflow-anchor: none, restored to '' on unlock), the same shape as ListInput and LegendList's maintainVisibleContentPosition — while following, the spring is the only writer of the position, so anchoring has nothing to do; unlocked, a reader up in the history keeps it. With that, the arbitration is one rule: an upward scroll that does not land on the bottom is the reader. The wheel and touch listeners, the waiver, and the geometry tracking are gone; the hook is 20 lines shorter than main.

Your sequence in Chromium on this head: nested block at its top with overscroll-behavior: contain, wheel up over it while the spring trailed by 266px, then a 100px collapse above the viewport — scrollTop 2458 → 2478 (the spring, no anchoring shift), following throughout, 4px from the bottom at the end. Released state: the same collapse moved scrollTop 2108 → 2008, the reader's place held. Counterfactual with anchoring forced back on while following: 2406 → 2331, read as the reader, released — which is the shift every earlier revision was trying to explain away. 6 new unit tests, 4 red on main; packages/core/src/Chat 189/189. PR body rewritten to match; the "restores #1249" framing is gone since this is a different position, not the old one.

@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, this now fixes the gesture/resize ownership gap in Chromium, including touch and reduced motion. One external-scroller path still changes caller behavior: on unlock, setLocked(false) clears an existing inline overflow-anchor: none, so later content changes can move a reader who explicitly disabled anchoring. In the same probe, main preserved none; this head changed it to auto. Could we save and restore the scroll element’s prior inline value on unlock and cleanup?

[Reviewed by Robohands]

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]>
@yyq1025

yyq1025 commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Done in 9788887: the listener effect captures the element's inline overflow-anchor when the hook takes the element over, and both setLocked(false) and the effect cleanup write that value back instead of ''. A consumer's own none now survives unlock and unmount; a test pins it (mounted disabled with none set, enabled, unlocked by a scroll-up, unmounted — none at every step), red on the previous head. packages/core/src/Chat 190/190.

@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, the static overflow-anchor: none case is fixed, but two ownership paths still lose reader/caller intent on this head.

In headed Chromium during active streaming, a real −100px wheel event landed between spring frames: scrollTop still advanced 25.5px and follow stayed locked. Because the hook now observes only net position, a reader's smaller upward gesture can be erased by the spring and they remain pinned to the tail.

Also, an external scroller changing inline overflow-anchor from auto to none while locked is restored to the captured auto on unlock. React has already committed none, so it leaves the DOM at auto, changing the caller's current policy. Please preserve the latest caller-owned value, not only the mount-time value.

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

[Reviewed by Robohands]

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]>
@github-actions
github-actions Bot requested a review from cixzhang September 4, 2026 01:38
@yyq1025

yyq1025 commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Both in 9b19b03.

The outrun: the hook compared each scroll event against the last position it had seen, and a wheel landing between two spring frames coalesces into one event carrying the net after the next write. animate() now records the position it writes, as jumpToBottom and scrollToMessage already did, so that event reads below the hook's own last write and releases — the same comparison use-stick-to-bottom makes against ignoreScrollToTop. A test encodes your sequence (spring writes +120, event arrives at write − 100, released), red on the previous head.

The caller's value: the switch no longer goes through inline style at all. Locked, the element carries data-astryx-chat-following; one injected rule ([data-astryx-chat-following]{overflow-anchor:none !important}, the highlightRanges pattern) turns anchoring off under it. The element's own overflow-anchor is never read, written or restored — whatever the caller set before or during the lock is what applies once the attribute is gone. Test: inline auto at mount, caller changes it to none while locked, unlock — none, and the hook never wrote the property. In Chromium an inline auto under the attribute computes to none. 191/191 in packages/core/src/Chat.

@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, both prior ownership gaps are fixed on this head. Headed Chromium released auto-follow for all 18 wheel trials, and caller-owned overflow-anchor: none survived unlock.

[Reviewed by Robohands]

@github-actions github-actions Bot removed the needs:code-review High-risk change (new package/component/API) — needs human code review before merge label Sep 4, 2026
github-actions Bot added a commit that referenced this pull request Sep 4, 2026
yyq1025 added a commit to yyq1025/astryx that referenced this pull request Sep 4, 2026
…oller

Four carry-overs from the review of meta#5678, where the same ownership
questions were settled for useChatStreamScroll:

- A wheel no longer disengages follow by itself. One this scroller never
  consumes — over a nested scroller with room above, over one with
  `overscroll-behavior: contain`, an overscroll at the bottom — moves
  nothing here, and unpinning on it stranded the reader off the tail.
- The reader's displacement is measured from the position the list last
  WROTE, not from the last scroll event seen. A wheel between two writes
  coalesces with the next write into one event carrying the net, and
  against the previous event that net could read as "moved down".
- A non-echo scroll that lands exactly on the bottom is not displacement:
  with native anchoring off, that is the browser clamping onto a smaller
  bottom after a shrink no commit announced.
- Native anchoring is switched off through `data-astryx-chat-virtualized`
  and one injected rule (the highlightRanges pattern), never the inline
  style: in attach mode the scroller is the caller's, and their own
  `overflow-anchor` is neither read, written nor restored.

The story now runs the virtualizer in own-container mode inside a shell
of its own — ChatMessageList for the log semantics, the composer in a
dock — instead of attaching to ChatLayout's scroller. ChatLayout runs its
own follow on that scroller with no way to hand it off, and a position
with two writers is a position nobody owns. Attach mode stays for hosts
whose scroller has no follow of its own; the baseline story keeps
ChatLayout as the control.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@cixzhang
cixzhang merged commit c3b79f6 into meta:main Sep 4, 2026
25 checks passed
@github-actions
github-actions Bot deleted the chat-follow-arbitration branch September 5, 2026 10:24
cixzhang added a commit that referenced this pull request Nov 9, 2026
* feat(lab): experimental ChatVirtualizer with a virtualized transcript story

Adds a windowing participant for ChatMessageList children: ChatLayout
keeps the scroller, ChatMessageList keeps its shell semantics, and the
lab ChatVirtualizer renders only the rows near the viewport between two
document-flow spacers. It owns follow-at-end (displacement-based
disengage, position-based re-engage, declarative jumps) and
read-position stability (identity anchoring while scrolled up), with
per-type running size estimates behind hysteresis.

The story pairs a virtualized and an unvirtualized arm over the same
corpus and controls: streaming a reply with 3000 messages mounted
measures ~8fps unvirtualized vs the machine's full frame rate
virtualized with ~17 rows in the DOM (the status pill shows both live).

Related: #4102, #2282, #3942.

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

* feat(lab): expose endThreshold as a story control

The re-engage threshold maps directly to the follow-semantics
discussion in the PR: at 1px (TanStack Virtual's default) stopping
visually at the bottom often leaves follow silently disengaged while a
stream grows below; the control makes that reproducible in 30 seconds.

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

* feat(lab): streamSpeed story control (relaxed/default/fast)

Fast chunk cadence is the stress case for follow ownership —
disengage mid-stream, scroll back, re-engage — so make it a control
instead of a fixed 25ms.

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

* fix(lab): static source for the ChatVirtualization docs panel

'Show code' defaults to the dynamic snippet, which serializes the
rendered element tree — at messageCount=3000 that walk freezes the
docs panel. docs.source.type='code' renders the story source instead
(4KB, instant).

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

* storybook: split the two arms into two stories, add startAtTop

The virtualized/unvirtualized comparison becomes a story switch instead of
a control that turns the subject off: "Thousands of Messages" keeps the
virtualizer controls, "Unvirtualized Baseline" carries only the shared
corpus/stream controls. startAtTop demos the anchorToKey half of the
imperative API (log-reading mode: open at the first row, stream grows
below without moving the viewport).

* ci: retrigger preview deploy after the gh-pages reset

* feat(lab): hold scrollTop during touch gestures, absorb corrections in the spacer

The follow and anchoring machinery was measured against wheel gestures and
programmatic scrolls. Touch produces scroll events with no wheel event
anywhere, and that input class had three defects living in it, found by
hand-testing the preview on a phone.

Slow drags off the bottom deadlocked: re-engage is a position test, disengage
a displacement test, and per-event restores erased the displacement faster
than a slow drag could accumulate it — 599 of 600 frames reverted, 8px of
4800 travelled, identical in Blink and WebKit. Where momentum belongs to the
scroll view (iOS WebKit, Android) a programmatic write also cancels the
fling, so a flick stopped after about two messages. And with writes withheld,
rows mounting above the viewport landed their (real − estimate) delta in the
geometry and the content crawled under the finger.

So while a touch gesture owns the viewport — finger down, plus the settle
window after lift-off — the machinery writes no scrollTop at all. The
correction it would have written goes into the top spacer instead, and
paintOrigin() converts between painted space and model space so the two can
never be mixed. Rows in normal document flow are what make that possible: the
spacer is a second knob, where a transform-positioned virtualizer has only
scrollTop, which is exactly the thing a gesture forbids. Nothing is deferred
into a ledger, so nothing stale can replay — the flush is one ordinary sync
from the re-stated mode.

That restatement is unconditional, because it also hands the adjustment back:
anchorAt reads through paintOrigin, so the carried adjustment folds into the
stored viewportOffset and zeroing it leaves a single balancing write in the
same task. Whether the gesture moved decides only the semantics — a real
scroll re-judges follow against the bottom edge, a plain tap keeps the mode it
had, and "moved" counts only non-echo scrolls so a browser clamp cannot
masquerade as intent.

No platform sniffing: where momentum survives a write there are touch events
to gate on, and where it does not (a macOS trackpad, whose momentum arrives as
wheel events) this path never runs. Settling is scroll silence plus an
elastic-overscroll guard, polled; only the last finger off the glass starts
it.

Measured on this story, 40000px of touch travel: 0 pushbacks, 0 drift events,
1px flush shift, 0px on a tap. Four tests pin the state machine (both the gate
and the multi-touch guard fail the suite when reverted). The story's wrapper
moves to dvh, which mobile Safari needs to stop the page rubber-banding under
the list.

* fix(lab): read the gesture reference frame from paint, and converge on a head change

Two defects found by hand-testing the preview on a phone.

Releasing the finger moved the page. paintOrigin() — and so anchorAt, targetFor
and computeWindow — assume painted == model + gestureAdj. At the very top there
is nothing above to absorb a negative adjustment into, so the spacer stops at 0
while gestureAdj keeps its full value, and the flush then restates the frame
from a map the screen no longer shares. anchorFromPaint reads viewportOffset off
a rendered row's rect instead; anchorAt already computes that same quantity
(offsets[idx] - y IS the painted top), so this only stops assuming the map holds.
A drag ending at the top moved 182px on release before and 0px after, while
mid-history the scroll still travels (435px, 1218px) with the picture at 0-1px.

Loading older history hijacked the anchor. The live-anchor refresh fired in the
middle of an unfinished correction and froze the intermediate position, after
which the list held the wrong row faithfully — 7 runs in 12, permanently. A page
of history is a correction the size of the page, paid over several passes as
those rows measure in; converging is already the state for "a correction is in
flight, do not re-derive", it was simply never set for a data change. 7/12 -> 0/12,
and every gesture path already clears converging so it cannot wedge.

Adds the contract halves jsdom can hold: a prepend re-indexes rows without
renumbering their keys, and a gesture that ends with nothing rendered falls back
rather than throwing.

* feat(lab): load-older-history control in the story, and an estimate contract

The story could demo streaming and follow but had no way to prepend, so the one
question a reviewer is most likely to ask — what happens to my reading position
when older messages load — could not be answered by pressing anything. Adds a
'Load 300 older' button that inserts a page with ids of its own, never a
renumbering of the messages already on screen.

Measured through it, at scrollTop 0 with the page inserted above: the anchored
row holds to within 40-60px, reproducibly. That is a real residual and smaller
than a row, not the row-sized slip this used to be; it is larger than the 0px
the same case measures on a lighter corpus, because these rows measure in later
than the compensation pass that reads them.

Also documents the estimatedItemSize bias, which is the one setting that can
make a drag look broken: too small and content grows as it measures, extending
the scroll range below you and leaving your position valid; too large and it
shrinks, and the browser clamps scrollTop into a range that just got smaller,
which nothing can undo.

* fix(lab): take the repricing decision once per pass, not per row

The size-average repricing decision lived inside effectiveAvg, which runs once
per row inside recompute's O(N) loop, and one of its gates is a clock reading.
A loop long enough to straddle the instant that gate opens repriced the tail of
the list and not the head: the pass published a geometry that was internally
inconsistent, restored scrollTop against it, and consumed geoChanged — so the
next pass, the one holding the consistent geometry and the correct target, found
the flag clear and never wrote. The landing was left short, permanently.

The odds scale with loop length and the gate re-crosses its threshold after
every gesture, so this is a size-amplified race rather than a large-list-only
bug. Measured upstream of this port on the same engine at 100k rows: a declared
jump landed up to 698,000px short in 25-50% of runs, 5/20 -> 0/17 after the fix,
with the smaller corpora unchanged at 0px on every axis.

repriceBuckets now takes the decision before the rebuild, from a single clock
reading, and effectiveAvg becomes a pure read — a pass always prices every row
from one set of numbers. priceFreeze additionally holds prices still while a
declared target is in flight and gives the release a frame of its own, so the
correction the averages owe is derived from a settled geometry instead of being
appended to the pass that just landed.

* fix(lab): the RO fallback measured a different box than the sync path

Both writers feed one size cache, and in 'ro' mode both actually run: a
row's first measurement comes from the sync pass's offsetHeight backstop,
every later one from the observer. contentRect is the CONTENT box, so on
a browser without borderBoxSize a padded row was cached short by its
padding and border, for as long as the fallback stayed the writer.

Fall back to offsetHeight on the observed element instead — the same box,
read off the same node as the sync path, so the two agree by construction
rather than by browser support.

* docs(lab): document ChatVirtualizer

The only component in the Chat directory without a doc, so the props that
carry a real contract — bias the estimate low, spacing lives inside the
row, pass the scroll container as an element — were readable only from the
source.

The scrollElement entry states why it takes an element rather than a ref:
a parent's ref attaches after its children's layout effects, so a ref
still reads null on the commit that first needs the scroller, and a ref
write is invisible to React, while an element held in state makes the
container's arrival a render and a real dependency.

No keywords field: family fields are inherited from the parent Chat doc,
and setting keywords here would replace that list rather than extend it.

* fix(lab): a head-change convergence let go of the anchor too early

Reaching the restore target does not end a head-change convergence. The
rows that arrived above are still measuring in, so the prices and the
offsets keep moving for several more passes — which is why the prices were
already held one pass longer, on a release of their own. The anchor half
was dropped on the spot instead, and in that gap the live-anchor refresh
re-derives from a scrollTop still mid-settle and freezes the intermediate
position as the new reference frame. Permanently: nothing later disagrees
with a stored anchor.

Both halves now lift on the same later pass, the one that sees the settled
numbers.

Measured on the virtualized story, reading at the top and pressing "Load
300 older": every visible row moved together by 33-53px and stayed there,
across every run. After: 0.1px, over five runs at the top and two in
mid-history, with follow-at-end and post-prepend scrolling unaffected.

No unit test: the defect lives in the window where the DOM has laid out
new rows at their real heights while the geometry still carries their
estimates, and jsdom has no layout to disagree with. The story is the
reproduction.

* Merge remote-tracking branch 'upstream/main' into chat-virtualizer-story

* fix(lab): ChatVirtualizer judges the reader by position, owns its scroller

Four carry-overs from the review of #5678, where the same ownership
questions were settled for useChatStreamScroll:

- A wheel no longer disengages follow by itself. One this scroller never
  consumes — over a nested scroller with room above, over one with
  `overscroll-behavior: contain`, an overscroll at the bottom — moves
  nothing here, and unpinning on it stranded the reader off the tail.
- The reader's displacement is measured from the position the list last
  WROTE, not from the last scroll event seen. A wheel between two writes
  coalesces with the next write into one event carrying the net, and
  against the previous event that net could read as "moved down".
- A non-echo scroll that lands exactly on the bottom is not displacement:
  with native anchoring off, that is the browser clamping onto a smaller
  bottom after a shrink no commit announced.
- Native anchoring is switched off through `data-astryx-chat-virtualized`
  and one injected rule (the highlightRanges pattern), never the inline
  style: in attach mode the scroller is the caller's, and their own
  `overflow-anchor` is neither read, written nor restored.

The story now runs the virtualizer in own-container mode inside a shell
of its own — ChatMessageList for the log semantics, the composer in a
dock — instead of attaching to ChatLayout's scroller. ChatLayout runs its
own follow on that scroller with no way to hand it off, and a position
with two writers is a position nobody owns. Attach mode stays for hosts
whose scroller has no follow of its own; the baseline story keeps
ChatLayout as the control.

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

* fix(lab): ChatVirtualizer floors its extent, resets geometry on detach

React commits a window shift children-first: rows are removed before
any spacer or parent style changes, and useInsertionEffect runs only
after the whole subtree has mutated. A row whose unmount reads layout
saw the extent without the removed rows, the browser clamped scrollTop
and the live-anchor refresh adopted it (2381-2617px short, Chromium
and Firefox). Spacers and rows now sit in one content block whose
min-height is the modelled extent, written only by the correction
pass, so the previous extent holds through the commit. The insertion
effect is gone. Attach mode renders that block instead of a fragment.

Own-container mode now resets the attach-mode origin/below geometry;
switching back from scrollElement kept the host's offsets and aimed
every follow target past the end of the list.

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

* Merge remote-tracking branch 'upstream/main' into chat-virtualizer-story

* chore(registry): lock the ChatVirtualizer shadcn route

The route lock landed on main after this branch last synced, so the
new lab component was missing from it. Regenerated with
UPDATE_SHADCN_ROUTE_LOCK=1; the only change is the new entry.

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

* fix(lab): file ChatVirtualizer under Chat, title its story by name

The docsite now requires every lab Chat* doc to carry group and
category 'Chat', and the PR accessibility scope maps stories to
components by title, which 'Lab/ChatVirtualization' did not match.

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

* docs(lab): ChatVirtualizer attach mode names a follow-free host

The scrollElement JSDoc pointed callers at ChatLayout's scroller, the
one host that cannot work today: ChatLayout runs its own follow on
that element with no way to turn it off, so attaching there puts two
writers on one position. The example is now a scroller with no follow
of its own, and the doc says ChatLayout cannot host attach mode until
it exposes a seam to disable that follow. Comments that named
ChatLayout as the host follow suit.

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

* Merge main into chat-virtualizer-story

Resolves the generated route lists (the union of both sides' entries, in generator format) and refreshes any generated goldens; no other change.

* fix(lab): ChatVirtualizer review round — keyboard access, history kept off the log, Core's shared touch and anchoring

- Keyboard users reach and scroll the list's own scroller, a `group` named
  by its new `label` prop (default "Messages"), through Core's
  useScrollableArea; a row holding focus stays mounted while the window
  moves away from it.
- Rows the window mounts over history, or history loaded above, mark the
  content block `aria-busy` for that commit and the next frame, so the
  transcript's log does not read them out as new; tail appends stay news.
- The touch write-gate follows Core's useFingerScroll (and its onEnd) in
  place of the list's own touch listeners and settle clock.
- Scroll anchoring goes off through Core's scroll-anchoring writer instead
  of a copied rule and a hand-written private attribute.
- `apiRef` is `handleRef`, as in Core components; static styles move to
  StyleX; the docs limit the spacer-height wording to touch gestures.
- A draft component record holds the ownership lines and the verification
  map, with the screen-reader evidence gap for aria-busy.

Depends on the Core changes in #10172 and #10173.

* chore(storybook): the ChatVirtualizer comparison story moves to its own pull request

The Storybook comparison of virtualized and unvirtualized transcripts
lands in a follow-up pull request, so this one stays under the 2,000-line
review limit.

* fix(lab): ChatVirtualizer keeps a focused row pinned through a blur with no next target; keyExtractor is getRowKey

A blur with no next target can come while the row still holds focus, so
the pin drops only once focus has really left the list. The row identity
prop is `getRowKey`, as in Core's table row hooks.

* fix(lab): ChatVirtualizer observes sizes through Core's shared resize observer

Rows and the scroller register with observeResize from
@astryxdesign/core/utils instead of a ResizeObserver of their own; one
sync still runs per batch, after the last entry, and the registration's
own boxless call is skipped so it forces no layout.

* Merge branch 'main' into chat-virtualizer-story

* chore(cli): list ChatVirtualizer among the official Lab components

Regenerated with `pnpm bundle:cli-official-packages`.

* fix(ChatVirtualizer): measureMode is not a public prop

The measurement pipeline is an implementation detail (AST-002 DEC-1), so
the prop and ChatVirtualizerMeasureMode are gone; the list always uses
the ResizeObserver pipeline it shipped as the default. It never shipped,
so nothing migrates.

* fix(ChatVirtualizer): a message that arrives while the reader is in history mounts, unmarked

Away from the tail, the window never reaches a new message, so it did not
mount and the log had nothing to deliver; when the reader returned it
mounted inside an aria-busy block. Now such a row mounts on arrival after
a gap spacer below the window, as the focused-row pin does, and stays
mounted (streamed updates included) until the window reaches it (AR2).

* perf(ChatVirtualizer): read layout once per scroll event and twice per pass

The scroll handler reads the scroller's position and size in one batch
and writes nothing, so it forces no layout. Each correction pass writes
its spacers, reads in one batch, writes its spacers and scrollTop, and
reads scrollTop back once to claim any browser move, so it forces at most
two layouts; the size it needs after its writes comes from the batch. The
record gains FR4, the clause react-component-runtime INV18 asks for, and
a layout-trace test checks the bound.

* fix(ChatVirtualizer): arrivals in state; a replaced thread adds none; no pass for an idle commit

Tail arrivals are now state, updated during render when the data or the
window changes, not a ref mutated in render (react-component-runtime
INV4). Only a tail append adds to them: a replaced array (another thread)
shares no row with the previous data, so switching threads while the
reader is in history no longer mounts the whole thread for a commit.
Arrivals leave once the window reaches them. The correction pass now
skips a commit that changes nothing it reads (a parent re-render with the
same rows); FR4 lists every trigger the pass has. Tests cover the thread
switch and the skipped pass.

* fix(ChatVirtualizer): an appended batch mounts at most a window of rows

Arrivals are added only while the window does not reach the previous
last row, so a batch appended while following is left to the window, and
at most one window of the newest rows mounts as arrivals while the reader
is in history (this also covers a thread switch that shares a row key).
The correction pass also runs when a sizing prop changes, and FR4 names
that trigger. Tests append 2,000 rows while following and while in
history. The file header says which commits run the pass.

* fix(ChatVirtualizer): arrivals stay one window across batches in history

The cap on mounted arrivals now applies to the whole set after every
change, not only to the newest batch, so a second batch or a run of single
arrivals while the reader stays in history keeps one window of the newest
rows mounted. The test appends a second 2,000-row batch and three single
rows in history.

* fix(ChatVirtualizer): a loaded or replacing thread is history for the log

Rows count as news only for a tail append, when the walk stops at a row
the previous data held. A thread loaded into an empty list, or one that
replaces the rows, mounts as history, so the block is busy for that commit
and the log does not read old messages out as new. Test and the AR2
verification row cover both.

* fix(ChatVirtualizer): the first message of an empty transcript is news

One row arriving into an empty list counts as news, so the opening message
of a new conversation mounts unmarked and the log delivers it; a larger load
into an empty list stays history. Adds a test and the AR2 verification
state, a CLI Changeset for the discover package list, stable-function
notes on estimatedItemSize and getItemType, and trims the file header and
a history comment.

Co-authored-by: Cindy Zhang <[email protected]>

This branch was successfully deployed

1 active deployment
Preview — 1c49290f Deployed Sep 4, 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

2 participants