An open source design system that's fully customizable and agent ready
TypeScript
fix(chat): only the reader can release auto-follow (#5662, #5663) (#5678)
Yueqian Yangc3b79f6d0482
diff --git a/.changeset/chat-follow-arbitration.md b/.changeset/chat-follow-arbitration.mdnew file mode 100644index 0000000000..9897e3da16--- /dev/null+++ b/.changeset/chat-follow-arbitration.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Chat/useChatStreamScroll: an upward scroll releases auto-follow in both motion modes, and only the reader can release it. While following, the hook owns the container's position: it disables CSS scroll anchoring on the scroll element, so the only move the browser makes on its own is the resize clamp onto the bottom, and any other upward move is read as the reader. A wheel or drag a nested scroller consumes, or a block collapsing above the viewport, no longer touches the lock either way; unlocked, anchoring is restored. The wheel and touch listeners are gone. `jumpToBottom` also cancels the spring's pending frame, so animation loops cannot stack. (#5662, #5663)+@yyq1025diff --git a/packages/core/src/Chat/useChatStreamScroll.test.tsx b/packages/core/src/Chat/useChatStreamScroll.test.tsxindex dfea626714..b8b7bb47af 100644--- a/packages/core/src/Chat/useChatStreamScroll.test.tsx+++ b/packages/core/src/Chat/useChatStreamScroll.test.tsx@@ -19,14 +19,15 @@ import {// manually via Storybook — mocking it here would only test the mock.// ----------------------------------------------------------------------------let rafQueue: FrameRequestCallback[] = [];+let rafQueue: {id: number; cb: FrameRequestCallback}[] = [];+let nextRafId = 1;function flushRaf() {// One flush = one frame: callbacks scheduled during a flush run next flush.const frame = rafQueue;rafQueue = [];act(() => {- for (const cb of frame) {+ for (const {cb} of frame) {cb(performance.now());}});@@ -34,11 +35,15 @@ function flushRaf() {beforeEach(() => {rafQueue = [];+ nextRafId = 1;vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {- rafQueue.push(cb);- return rafQueue.length;+ const id = nextRafId++;+ rafQueue.push({id, cb});+ return id;+ });+ vi.stubGlobal('cancelAnimationFrame', (id: number) => {+ rafQueue = rafQueue.filter(frame => frame.id !== id);});- vi.stubGlobal('cancelAnimationFrame', () => {});});afterEach(() => {@@ -215,3 +220,161 @@ describe('useChatStreamScroll — prefers-reduced-motion', () => {expect(api.current!.isLocked).toBe(true);});});++describe('useChatStreamScroll — reader intent while content arrives', () => {+ // Mount with content present: the initial jump lands at the bottom, and one+ // scroll event syncs the tracked position so later events are judged+ // against it rather than against the empty container.+ function settleAtBottom(el: HTMLElement) {+ setGeometry(el, {scrollHeight: 1000, clientHeight: 400});+ flushRaf();+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });+ }++ // The reader's scroll arrives in the same event that carries new content —+ // the shape every scroll event has while a turn is streaming.+ function scrollUpDuringGrowth(el: HTMLElement) {+ setGeometry(el, {scrollHeight: 1400, clientHeight: 400});+ el.scrollTop = 300;+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });+ }++ it('releases follow when the reader scrolls up while content grows', () => {+ const {api, el} = renderHook();+ settleAtBottom(el);++ scrollUpDuringGrowth(el);++ expect(api.current!.isLocked).toBe(false);+ });++ it('releases follow under prefers-reduced-motion too', () => {+ stubReducedMotion();+ const {api, el} = renderHook();+ settleAtBottom(el);++ scrollUpDuringGrowth(el);++ expect(api.current!.isLocked).toBe(false);+ });++ it('keeps following when only the content grew', () => {+ const {api, el} = renderHook();+ settleAtBottom(el);++ setGeometry(el, {scrollHeight: 1400, clientHeight: 400});+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });++ expect(api.current!.isLocked).toBe(true);+ });++ it('a resize clamp onto the new bottom does not release', () => {+ // A block above collapses; the browser pins the position to the new+ // maximum. That is the one upward move that is not the reader.+ const {api, el} = renderHook();+ settleAtBottom(el);++ setGeometry(el, {scrollHeight: 800, clientHeight: 400});+ el.scrollTop = 400;+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });++ expect(api.current!.isLocked).toBe(true);+ });++ it('owns scroll anchoring while following and hands it back when not', () => {+ // Anchoring is the browser's other way of moving a container up on a+ // content change; while following, the hook is the only writer. The+ // switch is an attribute plus one injected rule, never the element's own+ // inline style.+ const {api, el, unmount} = renderHook();+ settleAtBottom(el);+ expect(el.hasAttribute('data-astryx-chat-following')).toBe(true);+ const rule = document.head.querySelector(+ '[data-astryx-chat-following-style]',+ );+ expect(rule?.textContent).toContain('overflow-anchor:none !important');+ expect(el.style.overflowAnchor).toBe('');++ scrollUpDuringGrowth(el);+ expect(api.current!.isLocked).toBe(false);+ expect(el.hasAttribute('data-astryx-chat-following')).toBe(false);++ act(() => api.current!.scrollToBottom({behavior: 'instant'}));+ expect(el.hasAttribute('data-astryx-chat-following')).toBe(true);++ unmount();+ expect(el.hasAttribute('data-astryx-chat-following')).toBe(false);+ });++ it("never touches the element's own overflow-anchor, whatever it becomes", () => {+ // The consumer set an inline value before the hook took over, then+ // changed it while the hook was following. Both are theirs: the hook+ // must not have written over either, and the latest one is what applies+ // once the hook lets go.+ const {api, el, unmount} = renderHook();+ el.style.overflowAnchor = 'auto';+ settleAtBottom(el);+ expect(el.style.overflowAnchor).toBe('auto');++ el.style.overflowAnchor = 'none';+ scrollUpDuringGrowth(el);+ expect(api.current!.isLocked).toBe(false);+ expect(el.style.overflowAnchor).toBe('none');++ unmount();+ expect(el.style.overflowAnchor).toBe('none');+ });++ it('a scroll-up the next spring frame outruns still releases', () => {+ // Between two frames the reader wheels up 100px; the spring's next write+ // then adds more than that, so the net position still advanced. Judged+ // against the position the hook itself wrote, the reader's move shows.+ const {api, el} = renderHook();+ settleAtBottom(el);++ setGeometry(el, {scrollHeight: 4000, clientHeight: 400});+ act(() => api.current!.scrollIfLocked());+ flushRaf();+ const written = el.scrollTop;+ expect(written).toBeGreaterThan(700);++ el.scrollTop = written - 100;+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });++ expect(api.current!.isLocked).toBe(false);+ });+});++describe('useChatStreamScroll — spring cancellation', () => {+ it('an instant jump leaves at most one live animation loop', () => {+ const {api, el} = renderHook();+ setGeometry(el, {scrollHeight: 1000, clientHeight: 400});+ flushRaf();++ // Streaming growth starts a spring.+ setGeometry(el, {scrollHeight: 1400, clientHeight: 400});+ act(() => api.current!.scrollIfLocked());+ flushRaf();+ expect(rafQueue).toHaveLength(1);++ // A programmatic jump lands mid-spring, and content grows again before+ // the superseded loop's next tick — so startAnimation opens a second one.+ act(() => api.current!.scrollToBottom({behavior: 'instant'}));+ setGeometry(el, {scrollHeight: 1800, clientHeight: 400});+ act(() => api.current!.scrollIfLocked());+ flushRaf();++ // Only the live loop rescheduled itself.+ expect(rafQueue).toHaveLength(1);+ });+});diff --git a/packages/core/src/Chat/useChatStreamScroll.ts b/packages/core/src/Chat/useChatStreamScroll.tsindex cc9a9f649c..97fc3c7f65 100644--- a/packages/core/src/Chat/useChatStreamScroll.ts+++ b/packages/core/src/Chat/useChatStreamScroll.ts@@ -18,10 +18,12 @@* - Under `prefers-reduced-motion`, every spring path falls back to the* same instant jump — following still works, it just doesn't animate*- * Uses scroll direction (lastScrollTop comparison) to detect user- * intent — works for wheel, touch, scrollbar drag, keyboard, everything.- * Tracks scrollHeight/offsetHeight changes to ignore Chrome synthetic- * scroll events caused by content resize.+ * Reads user intent from position: a scroll that lands above the last+ * position this hook set or saw is the reader — wheel, touch, scrollbar+ * drag, keyboard, everything, including a move the spring's next frame+ * would otherwise outrun. While following, the hook owns the position:+ * it disables scroll anchoring on the container, so the only move the+ * browser makes on its own is a resize clamp onto the bottom.** SYNC: When modified, update:* - /packages/core/src/Chat/index.ts (exports)@@ -124,6 +126,28 @@ export interface UseChatStreamScrollReturn {const SIXTY_FPS_MS = 1000 / 60;+// While following, the hook owns the container's position, so the browser's+// scroll anchoring must not move it. The rule rides on an attribute rather+// than the element's inline style: a consumer's own `overflow-anchor` 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.+const FOLLOWING_ATTR = 'data-astryx-chat-following';+const FOLLOWING_STYLE_ATTR = 'data-astryx-chat-following-style';++function ensureFollowingStyle(): void {+ if (+ typeof document === 'undefined' ||+ document.head.querySelector(`[${FOLLOWING_STYLE_ATTR}]`)+ ) {+ return;+ }+ const style = document.createElement('style');+ style.setAttribute(FOLLOWING_STYLE_ATTR, '');+ style.textContent = `[${FOLLOWING_ATTR}]{overflow-anchor:none !important}`;+ document.head.appendChild(style);+}+export function useChatStreamScroll({scrollRef,enabled = true,@@ -143,12 +167,27 @@ export function useChatStreamScroll({const velocityRef = useRef(0);const animatingRef = useRef(false);const lastTickRef = useRef<number | undefined>(undefined);-- // For scroll direction detection+ // The spring's pending frame, so a jump can cancel it for real.+ const rafRef = useRef<number>(0);+ // The last position this hook set or saw. Updated by every write of ours+ // (spring frame, jump, scrollToMessage) as well as by every scroll event,+ // so a reader's move that lands between two spring frames still shows as+ // "above where we put it" even when the next frame's write outran it.const lastScrollTopRef = useRef(0);- // For synthetic scroll detection- const lastScrollHeightRef = useRef(0);- const lastOffsetHeightRef = useRef(0);++ // While following, this hook is the only thing that should move the+ // container: scroll anchoring is off, so the browser's one remaining move+ // is the resize clamp onto the bottom, and every other upward move is the+ // reader. Unlocked, the element's own anchoring applies again — a reader up+ // in the history wants it when content above them changes.+ const setLocked = useCallback(+ (locked: boolean) => {+ lockedRef.current = locked;+ setIsLocked(locked);+ scrollRef.current?.toggleAttribute(FOLLOWING_ATTR, locked);+ },+ [scrollRef],+ );// --- Spring animation ---@@ -189,8 +228,9 @@ export function useChatStreamScroll({velocityRef.current =(damping * velocityRef.current + stiffness * diff) / mass;el.scrollTop += velocityRef.current * tickDelta;+ lastScrollTopRef.current = el.scrollTop;- requestAnimationFrame(animate);+ rafRef.current = requestAnimationFrame(animate);}, [scrollRef, damping, stiffness, mass]);// Jump to the bottom in a single frame — cancels any in-flight spring so@@ -200,6 +240,7 @@ export function useChatStreamScroll({if (!el) {return;}+ cancelAnimationFrame(rafRef.current);animatingRef.current = false;velocityRef.current = 0;lastTickRef.current = undefined;@@ -224,7 +265,7 @@ export function useChatStreamScroll({if (!animatingRef.current) {animatingRef.current = true;lastTickRef.current = undefined;- requestAnimationFrame(animate);+ rafRef.current = requestAnimationFrame(animate);}}, [animate, jumpToBottom, prefersReducedMotion]);@@ -232,8 +273,7 @@ export function useChatStreamScroll({const scrollToBottom = useCallback((options?: ChatScrollToBottomOptions) => {- lockedRef.current = true;- setIsLocked(true);+ setLocked(true);setIsScrolledUp(false);initialFillPendingRef.current = false;if (options?.behavior === 'instant') {@@ -242,7 +282,7 @@ export function useChatStreamScroll({}startAnimation();},- [startAnimation, jumpToBottom],+ [setLocked, startAnimation, jumpToBottom],);const scrollToMessage = useCallback(@@ -273,17 +313,15 @@ export function useChatStreamScroll({}, [scrollRef, scrollToMessage]);const lock = useCallback(() => {- lockedRef.current = true;- setIsLocked(true);+ setLocked(true);setIsScrolledUp(false);startAnimation();- }, [startAnimation]);+ }, [setLocked, startAnimation]);const unlock = useCallback(() => {- lockedRef.current = false;+ setLocked(false);animatingRef.current = false;- setIsLocked(false);- }, []);+ }, [setLocked]);const scrollIfLocked = useCallback(() => {if (!enabled) {@@ -317,10 +355,9 @@ export function useChatStreamScroll({return;}- // Initialize tracking valueslastScrollTopRef.current = el.scrollTop;- lastScrollHeightRef.current = el.scrollHeight;- lastOffsetHeightRef.current = el.offsetHeight;+ ensureFollowingStyle();+ el.toggleAttribute(FOLLOWING_ATTR, lockedRef.current);const onScroll = () => {const {scrollTop, scrollHeight, offsetHeight} = el;@@ -329,62 +366,30 @@ export function useChatStreamScroll({// Button visibilitysetIsScrolledUp(dist > buttonThreshold);- // Detect synthetic scroll — Chrome fires scroll events when- // scrollHeight or offsetHeight changes (content resize, keyboard).- const scrollHeightChanged = scrollHeight !== lastScrollHeightRef.current;- const offsetHeightChanged = offsetHeight !== lastOffsetHeightRef.current;- lastScrollHeightRef.current = scrollHeight;- lastOffsetHeightRef.current = offsetHeight;-- if (scrollHeightChanged || offsetHeightChanged) {- // Synthetic scroll from resize — don't change lock state- lastScrollTopRef.current = scrollTop;- return;- }-- // Scroll direction — unlock on scroll upconst isScrollingUp = scrollTop < lastScrollTopRef.current;lastScrollTopRef.current = scrollTop;- if (isScrollingUp && lockedRef.current) {- lockedRef.current = false;+ // With anchoring off, the browser only ever moves a following+ // container up to clamp it onto a new, smaller bottom, and a reader+ // scrolling up never lands there. (clientHeight, not dist: offsetHeight+ // includes borders and a horizontal scrollbar.)+ const landedAtBottom = scrollHeight - scrollTop - el.clientHeight < 1;++ if (isScrollingUp && !landedAtBottom && lockedRef.current) {+ setLocked(false);animatingRef.current = false;- setIsLocked(false);}};const onScrollEnd = () => {const dist = el.scrollHeight - el.scrollTop - el.offsetHeight;if (dist <= lockThreshold) {- lockedRef.current = true;- setIsLocked(true);- }- };-- // Wheel up while animating — interrupt immediately.- // onScroll direction detection covers most cases, but wheel fires- // before the scroll position updates so we can react faster.- const onWheel = (e: WheelEvent) => {- if (e.deltaY < 0 && animatingRef.current) {- lockedRef.current = false;- animatingRef.current = false;- setIsLocked(false);- }- };-- // Touch move — user is dragging, take control- const onTouchMove = () => {- if (animatingRef.current) {- lockedRef.current = false;- animatingRef.current = false;- setIsLocked(false);+ setLocked(true);}};el.addEventListener('scroll', onScroll, {passive: true});el.addEventListener('scrollend', onScrollEnd);- el.addEventListener('wheel', onWheel, {passive: true});- el.addEventListener('touchmove', onTouchMove, {passive: true});// Initial scroll to bottom — content already present at mount.requestAnimationFrame(() => {@@ -398,10 +403,9 @@ export function useChatStreamScroll({return () => {el.removeEventListener('scroll', onScroll);el.removeEventListener('scrollend', onScrollEnd);- el.removeEventListener('wheel', onWheel);- el.removeEventListener('touchmove', onTouchMove);+ el.removeAttribute(FOLLOWING_ATTR);};- }, [scrollRef, enabled, lockThreshold, buttonThreshold]);+ }, [scrollRef, enabled, lockThreshold, buttonThreshold, setLocked]);return {isScrolledUp,