Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6739 fix(chat): keep the viewport at the live end while replies stream (#7612)
Tim07bc8bc6bc48
diff --git a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx b/packages/views/chat/components/chat-message-list.autoscroll.test.tsxnew file mode 100644index 0000000000..68cfdcd695--- /dev/null+++ b/packages/views/chat/components/chat-message-list.autoscroll.test.tsx@@ -0,0 +1,634 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, render } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import { chatKeys } from "@multica/core/chat/queries";+import type { TaskMessagePayload } from "@multica/core/types";+import type { ReactElement } from "react";+import enChat from "../../locales/en/chat.json";+import { ChatMessageList } from "./chat-message-list";++// Auto-scroll wiring: the list must keep the live end visible through streaming+// growth and composer resizes, releasing only on real reader input. The latch+// decision table is canonical in transcript-follow.test.ts and the scroll+// geometry in stick-to-bottom.test.ts; this suite drives the real component+// through the DOM signals those decisions are wired to. Reader gestures here+// are wheel INPUT followed by the scroll it causes — position-only moves model+// the browser (clamps), input-led moves model the reader.++// Virtuoso cannot render rows in jsdom's zero-height viewport. The stub keeps+// the row count visible, surfaces `followOutput` verdicts as attributes, and+// captures `totalListHeightChanged` so the harness can report content growth+// the way the real Virtuoso does.+let reportContentHeightChanged: (() => void) | undefined;++vi.mock("react-virtuoso", () => ({+ Virtuoso: ({+ data,+ itemContent,+ computeItemKey,+ followOutput,+ totalListHeightChanged,+ }: {+ data: unknown[];+ itemContent: (i: number, item: unknown) => ReactElement;+ computeItemKey: (i: number, item: unknown) => string;+ followOutput?: (atBottom: boolean) => "smooth" | "auto" | false;+ totalListHeightChanged?: () => void;+ }) => {+ reportContentHeightChanged = totalListHeightChanged;+ return (+ <div+ data-testid="virtuoso-rows"+ data-follow-at-bottom={String(followOutput?.(true))}+ data-follow-away-from-bottom={String(followOutput?.(false))}+ >+ {data.map((item, i) => (+ <div key={computeItemKey(i, item)} data-row-key={computeItemKey(i, item)}>+ {itemContent(i, item)}+ </div>+ ))}+ </div>+ );+ },+}));++const TEST_RESOURCES = { en: { chat: enChat } };+const TASK_ID = "6af44cbe-80ab-4dfe-b07d-bd3cfd588f4d";++const VIEWPORT = 600;++interface FakeObserver {+ targets: Element[];+ fire: () => void;+}++let observers: FakeObserver[] = [];+let animationFrames = new Map<number, FrameRequestCallback>();+let nextAnimationFrameId = 1;++function observedTargets(): Element[] {+ return observers.flatMap((o) => o.targets);+}++function fireResizeObservers() {+ act(() => {+ for (const observer of observers) observer.fire();+ });+}++function renderFrame() {+ const callbacks = [...animationFrames.values()];+ animationFrames.clear();+ now += 16;+ for (const callback of callbacks) callback(now);+}++// Confirmed motion gets a short settle window; tests control that clock.+let now = 0;+function gestureSettles() {+ now += 301;+}++beforeEach(() => {+ observers = [];+ animationFrames = new Map();+ nextAnimationFrameId = 1;+ reportContentHeightChanged = undefined;+ now = 0;+ vi.spyOn(Date, "now").mockImplementation(() => now);+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ const id = nextAnimationFrameId++;+ animationFrames.set(id, callback);+ return id;+ });+ vi.stubGlobal("cancelAnimationFrame", (id: number) => {+ animationFrames.delete(id);+ });+ vi.stubGlobal(+ "ResizeObserver",+ class {+ targets: Element[] = [];+ constructor(private callback: () => void) {+ observers.push(this as unknown as FakeObserver);+ }+ observe(target: Element) {+ this.targets.push(target);+ }+ unobserve(target: Element) {+ this.targets = this.targets.filter((t) => t !== target);+ }+ disconnect() {+ this.targets = [];+ observers = observers.filter((o) => (o as unknown as this) !== this);+ }+ fire() {+ this.callback();+ }+ },+ );+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++interface Scroller {+ el: HTMLElement;+ scrollTop: number;+ distanceFromBottom(): number;+ /** A streamed chunk grew the content; Virtuoso reports the new height. */+ grow(px: number): void;+ /** Content shrank (a fold closing); the browser clamps scrollTop. */+ shrinkContent(px: number): void;+ /** The composer collapsed, giving the list `px` back; scrollTop clamps. */+ growViewport(px: number): void;+ /** The composer grew, taking `px` off the list's height. */+ shrinkViewport(px: number): void;+ /** Reader wheel input scrolling up by `px`, and the scroll it causes. */+ readerScrollsUp(px: number): void;+ /** Starts a one-finger touch gesture at `clientY`. */+ touchStart(clientY: number): void;+ /** Moves that finger and then scrolls the list up by `scrollPx`. */+ touchMove(clientY: number, scrollPx: number): void;+ touchEnd(): void;+ /** Touch momentum scrolls the list after the finger lifts. */+ touchMomentumScrollsUp(px: number): void;+ /** Reader wheel input landing `fromBottom` px above the live end. */+ readerScrollsTo(fromBottom: number): void;+ /**+ * Wheel input the list never consumed: it bubbles from a nested scroller+ * (or hits a list with nothing to scroll), so no scroll event follows.+ */+ wheelWithoutScroll(px: number): void;+ /** PageUp bubbling from a focused control inside a row. */+ pageUpFromRowControl(): void;+ /** Shift+Space (pages UP) bubbling from a focused control inside a row. */+ shiftSpaceFromRowControl(): void;+ /** The browser scrolls the list itself (answering a key), no input seen. */+ browserScrollsListUp(px: number): void;+}++function scroller(el: HTMLElement, initialContent = 2000): Scroller {+ const state = { scrollTop: 0, contentHeight: initialContent, viewportHeight: VIEWPORT };+ // Open at the bottom, matching Virtuoso's `initialTopMostItemIndex: LAST`.+ state.scrollTop = Math.max(0, state.contentHeight - state.viewportHeight);++ Object.defineProperties(el, {+ scrollHeight: { configurable: true, get: () => state.contentHeight },+ clientHeight: { configurable: true, get: () => state.viewportHeight },+ scrollTop: {+ configurable: true,+ get: () => state.scrollTop,+ set: (value: number) => {+ state.scrollTop = value;+ },+ },+ });++ const scrollEvent = () => {+ act(() => {+ el.dispatchEvent(new Event("scroll"));+ });+ };++ const touchEvent = (type: string, clientY?: number) => {+ const event = new Event(type, { bubbles: true }) as TouchEvent;+ const points =+ clientY === undefined+ ? []+ : [{ identifier: 1, clientY } satisfies Pick<Touch, "identifier" | "clientY">];+ Object.defineProperty(event, "touches", {+ value: points,+ });+ Object.defineProperty(event, "changedTouches", { value: points });+ return event;+ };++ // Reader input: the wheel delta the hook judges intent from, then the+ // scroll it produces. Wheel up is a negative deltaY.+ const wheelBy = (px: number) => {+ act(() => {+ el.dispatchEvent(new WheelEvent("wheel", { deltaY: -px }));+ });+ state.scrollTop -= px;+ scrollEvent();+ };++ // Browser clamp after the scrollable extent shrank: scrollTop drops to the+ // new maximum and a scroll event fires, with no input anywhere.+ const clampAfterShrink = () => {+ state.scrollTop = Math.min(+ state.scrollTop,+ Math.max(0, state.contentHeight - state.viewportHeight),+ );+ scrollEvent();+ };++ const contentChanged = () => {+ act(() => {+ reportContentHeightChanged?.();+ });+ };++ return {+ el,+ get scrollTop() {+ return state.scrollTop;+ },+ distanceFromBottom() {+ return Math.max(0, state.contentHeight - state.scrollTop - state.viewportHeight);+ },+ grow(px) {+ state.contentHeight += px;+ contentChanged();+ },+ shrinkContent(px) {+ state.contentHeight -= px;+ clampAfterShrink();+ contentChanged();+ },+ growViewport(px) {+ state.viewportHeight += px;+ clampAfterShrink();+ fireResizeObservers();+ },+ shrinkViewport(px) {+ state.viewportHeight -= px;+ fireResizeObservers();+ },+ readerScrollsUp(px) {+ wheelBy(px);+ },+ touchStart(clientY) {+ act(() => {+ el.dispatchEvent(touchEvent("touchstart", clientY));+ });+ },+ touchMove(clientY, scrollPx) {+ act(() => {+ el.dispatchEvent(touchEvent("touchmove", clientY));+ });+ state.scrollTop -= scrollPx;+ scrollEvent();+ },+ touchEnd() {+ act(() => {+ el.dispatchEvent(touchEvent("touchend"));+ });+ },+ touchMomentumScrollsUp(px) {+ state.scrollTop -= px;+ scrollEvent();+ },+ readerScrollsTo(fromBottom) {+ wheelBy(fromBottom - this.distanceFromBottom());+ },+ wheelWithoutScroll(px) {+ const nested = document.createElement("pre");+ el.appendChild(nested);+ act(() => {+ nested.dispatchEvent(new WheelEvent("wheel", { deltaY: -px, bubbles: true }));+ });+ },+ pageUpFromRowControl() {+ const control = document.createElement("button");+ el.appendChild(control);+ act(() => {+ control.dispatchEvent(new KeyboardEvent("keydown", { key: "PageUp", bubbles: true }));+ });+ },+ shiftSpaceFromRowControl() {+ const control = document.createElement("button");+ el.appendChild(control);+ act(() => {+ control.dispatchEvent(+ new KeyboardEvent("keydown", { key: " ", shiftKey: true, bubbles: true }),+ );+ });+ },+ browserScrollsListUp(px) {+ state.scrollTop -= px;+ scrollEvent();+ },+ };+}++function taskMsg(seq: number, content: string): TaskMessagePayload {+ return { task_id: TASK_ID, seq, type: "text", content } as TaskMessagePayload;+}++function renderStreamingChat({ contentHeight = 2000 } = {}) {+ const qc = new QueryClient();+ qc.setQueryData(chatKeys.taskMessages(TASK_ID), [taskMsg(0, "Looking into it. ")]);++ const view = render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={qc}>+ <ChatMessageList+ messages={[]}+ pendingTask={{ task_id: TASK_ID, status: "running" }}+ availability={undefined}+ />+ </QueryClientProvider>+ </I18nProvider>,+ );++ const el = view.container.querySelector<HTMLElement>("[data-tab-scroll-root]");+ if (!el) throw new Error("chat list did not render a scroll container");++ return {+ qc,+ view,+ scroll: scroller(el, contentHeight),+ rowCount: () => view.container.querySelectorAll("[data-row-key]").length,+ followsAtBottom: () =>+ view.container+ .querySelector("[data-follow-at-bottom]")+ ?.getAttribute("data-follow-at-bottom"),+ streamChunk: (seq: number) => {+ act(() => {+ qc.setQueryData<TaskMessagePayload[]>(+ chatKeys.taskMessages(TASK_ID),+ (old = []) => [...old, taskMsg(seq, `chunk ${seq} `)],+ );+ });+ },+ };+}++describe("ChatMessageList auto-scroll", () => {+ it("follows a streaming reply whose row count never changes", () => {+ const { scroll, streamChunk, rowCount } = renderStreamingChat();++ const rowsBefore = rowCount();+ for (let seq = 1; seq <= 30; seq++) {+ streamChunk(seq);+ scroll.grow(180);+ }++ expect(rowCount()).toBe(rowsBefore);+ expect(scroll.distanceFromBottom()).toBe(0);+ });++ it("keeps the newest content clear of a composer that grew", () => {+ const { scroll } = renderStreamingChat();++ scroll.shrinkViewport(72);++ expect(scroll.distanceFromBottom()).toBe(0);+ });++ it("stays pinned when the composer collapses", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ streamChunk(1);+ scroll.grow(180);+ scroll.growViewport(72);++ for (let seq = 2; seq <= 3; seq++) {+ streamChunk(seq);+ scroll.grow(180);+ }++ expect(scroll.distanceFromBottom()).toBe(0);+ });++ it("stays pinned when content shrinks", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ streamChunk(1);+ scroll.grow(180);+ scroll.shrinkContent(400);++ for (let seq = 2; seq <= 3; seq++) {+ streamChunk(seq);+ scroll.grow(180);+ }++ expect(scroll.distanceFromBottom()).toBe(0);+ });++ // The base behavior `atBottomThreshold` always granted: a trackpad nudge+ // inside the edge zone is not the reader leaving.+ it("keeps following after a small trackpad nudge near the live end", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ scroll.readerScrollsUp(2);+ gestureSettles();++ streamChunk(1);+ scroll.grow(180);++ expect(scroll.distanceFromBottom()).toBe(0);+ });++ it("releases when touch momentum carries a flick past the threshold", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ scroll.touchStart(100);+ scroll.touchMove(180, 80);+ scroll.touchEnd();+ scroll.touchMomentumScrollsUp(80);+ const parked = scroll.scrollTop;++ streamChunk(1);+ scroll.grow(180);++ expect(scroll.scrollTop).toBe(parked);+ });++ it("leaves a fractional touch drag in progress", () => {+ const { scroll, streamChunk, followsAtBottom } = renderStreamingChat();++ scroll.touchStart(100);+ scroll.touchMove(180, 80.5);+ streamChunk(1);++ expect(scroll.distanceFromBottom()).toBe(80.5);+ expect(followsAtBottom()).toBe("auto");+ scroll.touchEnd();+ });++ it("resumes pinning after a sub-threshold touch ends", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ scroll.touchStart(100);+ scroll.touchMove(180, 80);+ scroll.touchEnd();+ gestureSettles();+ streamChunk(1);+ scroll.grow(180);++ expect(scroll.distanceFromBottom()).toBe(0);+ });++ it("releases on incremental upward scrolling during a fast stream", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ streamChunk(1);+ scroll.grow(180);++ // 60px wheel ticks, each under the edge threshold on its own and each+ // answered by a chunk that pins the reader back — but the displacement+ // they actually took accumulates across the pins, so the third tick+ // crosses the threshold and releases.+ for (let seq = 2; seq <= 5; seq++) {+ scroll.readerScrollsUp(60);+ streamChunk(seq);+ scroll.grow(180);+ }+ gestureSettles();+ streamChunk(6);+ scroll.grow(180);++ expect(scroll.distanceFromBottom()).toBe(660);+ });++ // Discrete mouse wheel at reading pace: one notch per event, spaced past+ // the intent window. Release must not require a single fast burst.+ it("releases for wheel notches spaced past the intent window", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ scroll.readerScrollsUp(100);+ gestureSettles();+ scroll.readerScrollsUp(100);+ gestureSettles();+ const parked = scroll.scrollTop;++ streamChunk(1);+ scroll.grow(180);++ expect(scroll.scrollTop).toBe(parked);+ });++ // A reply's final chunk always exists and has a whole intent window to land+ // in after any small nudge; no later event will re-evaluate a declined pin.+ it("pins a chunk that lands inside the reader's intent window", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ scroll.readerScrollsUp(2);+ streamChunk(1);+ scroll.grow(180);++ expect(scroll.distanceFromBottom()).toBe(0);+ });++ it("honors Shift+Space paging from a focused row control", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ scroll.shiftSpaceFromRowControl();+ scroll.browserScrollsListUp(VIEWPORT);+ const parked = scroll.scrollTop;+ gestureSettles();++ streamChunk(1);+ scroll.grow(180);++ expect(scroll.scrollTop).toBe(parked);+ });++ it("leaves the viewport alone once the reader scrolls up to read history", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ scroll.readerScrollsTo(900);+ gestureSettles();+ const parked = scroll.scrollTop;++ streamChunk(1);+ scroll.grow(500);+ scroll.shrinkViewport(72);++ expect(scroll.scrollTop).toBe(parked);+ });++ // Wheel over a capped code block scrolls the block; the event bubbles to+ // the list without moving it. Unconsumed input must not release the follow.+ it("keeps following through wheel input the list never consumed", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ scroll.wheelWithoutScroll(200);+ gestureSettles();++ streamChunk(1);+ scroll.grow(180);++ expect(scroll.distanceFromBottom()).toBe(0);+ });++ it("pins a system shift after nested scrolling left input unconsumed", () => {+ const { scroll } = renderStreamingChat();++ scroll.wheelWithoutScroll(300);+ renderFrame();+ scroll.browserScrollsListUp(200);++ expect(scroll.distanceFromBottom()).toBe(0);+ });++ it("keeps following after a flick on a conversation too short to scroll", () => {+ const { scroll, streamChunk } = renderStreamingChat({ contentHeight: 400 });++ scroll.wheelWithoutScroll(200);+ gestureSettles();++ for (let seq = 1; seq <= 8; seq++) {+ streamChunk(seq);+ scroll.grow(180);+ }++ expect(scroll.distanceFromBottom()).toBe(0);+ });++ // Focus sits on a row control, the reader presses PageUp, and the browser+ // scrolls the list. The scroll confirms the staged key intent: the reader+ // is released, not pinned back over their own keypress.+ it("honors keyboard paging from a focused row control", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ scroll.pageUpFromRowControl();+ scroll.browserScrollsListUp(VIEWPORT);+ const parked = scroll.scrollTop;+ gestureSettles();++ streamChunk(1);+ scroll.grow(180);++ expect(scroll.scrollTop).toBe(parked);+ });++ it("re-engages when the reader scrolls back down to the live end", () => {+ const { scroll, streamChunk } = renderStreamingChat();++ scroll.readerScrollsTo(900);+ scroll.readerScrollsTo(0);+ gestureSettles();++ streamChunk(1);+ scroll.grow(500);++ expect(scroll.distanceFromBottom()).toBe(0);+ });++ // `followOutput` is `atBottom && isFollowing()`: a released follow must turn+ // it off even while Virtuoso still reports the reader at the bottom.+ it("turns followOutput off while released, even when Virtuoso reports atBottom", () => {+ const { scroll, streamChunk, followsAtBottom } = renderStreamingChat();++ expect(followsAtBottom()).toBe("auto");++ scroll.readerScrollsTo(900);+ streamChunk(1);++ expect(followsAtBottom()).toBe("false");+ });++ it("stops measuring once the list unmounts", () => {+ const { view } = renderStreamingChat();++ view.unmount();++ expect(observedTargets()).toHaveLength(0);+ });+});diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex 18e8cb3e62..5fb212f495 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -48,6 +48,8 @@ import { buildTimeline } from "../../common/task-transcript";import { OnboardingStarterCards } from "./onboarding-starter-cards";import { TaskStatusPill } from "./task-status-pill";import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";+import { FOLLOW_EDGE_THRESHOLD } from "../../common/task-transcript/transcript-follow";+import { useStickToBottom } from "./stick-to-bottom";import { formatElapsedMs } from "../lib/format";import { splitTimeline, extractCopyText } from "../lib/copy-text";import { stripChatQuickActionsProtocol } from "../lib/quick-actions";@@ -189,6 +191,7 @@ export function ChatMessageList({scrollRef.current = node;setScrollContainerEl(node);}, []);+ const { isFollowing, onContentHeightChanged } = useStickToBottom(scrollContainerEl);// Soft edge fade hinting more content above/below. Kept small so it barely// grazes full-bleed previews (image / HTML) at the edges.const fadeStyle = useScrollFade(scrollRef, 16);@@ -327,14 +330,20 @@ export function ChatMessageList({// than the viewport, so switching sessions always shows the latest reply.initialTopMostItemIndex={{ index: "LAST", align: "end" }}increaseViewportBy={{ top: 400, bottom: 600 }}- atBottomThreshold={120}+ atBottomThreshold={FOLLOW_EDGE_THRESHOLD}// Follow rapid streamed output only while Virtuoso says the reader is// at the live end. An in-flight smooth animation temporarily reports// "not at bottom" on the next append and permanently drops the follow- // (#6697), so live growth must use an immediate scroll.+ // (#6697), so live growth must use an immediate scroll. `isFollowing`+ // narrows this further: the reader may have scrolled away by input the+ // 120px `atBottom` band forgives (see stick-to-bottom.ts).followOutput={(atBottom) =>- !isFetchingOlderMessages && atBottom ? "auto" : false+ !isFetchingOlderMessages && atBottom && isFollowing() ? "auto" : false}+ // `followOutput` never fires for a single row growing mid-stream, so+ // content resizes route to the bottom-stick through Virtuoso's own+ // height signal instead.+ totalListHeightChanged={onContentHeightChanged}startReached={() => {if (hasOlderMessages && !isFetchingOlderMessages) {onLoadOlderMessages?.();diff --git a/packages/views/chat/components/stick-to-bottom.test.ts b/packages/views/chat/components/stick-to-bottom.test.tsnew file mode 100644index 0000000000..7b9a60e98c--- /dev/null+++ b/packages/views/chat/components/stick-to-bottom.test.ts@@ -0,0 +1,62 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import {+ bottomPinTarget,+ distanceFromBottom,+ isAtLiveEnd,+ type ScrollMetrics,+} from "./stick-to-bottom";+import { FOLLOW_EDGE_THRESHOLD } from "../../common/task-transcript/transcript-follow";++const VIEWPORT = 600;++function at(content: number, fromBottom: number): ScrollMetrics {+ return {+ clientHeight: VIEWPORT,+ scrollHeight: content,+ scrollTop: Math.max(0, content - VIEWPORT - fromBottom),+ };+}++describe("distanceFromBottom", () => {+ it("measures the content left below the fold", () => {+ expect(distanceFromBottom(at(2000, 340))).toBe(340);+ });++ it("floors at zero when the content is shorter than the viewport", () => {+ expect(distanceFromBottom({ clientHeight: 600, scrollHeight: 200, scrollTop: 0 })).toBe(0);+ });+});++describe("isAtLiveEnd", () => {+ it("keeps following inside the edge threshold and releases past it", () => {+ expect(isAtLiveEnd(at(4000, FOLLOW_EDGE_THRESHOLD))).toBe(true);+ expect(isAtLiveEnd(at(4000, FOLLOW_EDGE_THRESHOLD + 1))).toBe(false);+ });+});++describe("bottomPinTarget", () => {+ it("pins a grown row back to the bottom", () => {+ expect(bottomPinTarget({ clientHeight: VIEWPORT, scrollHeight: 920, scrollTop: 200 })).toBe(320);+ });++ it("pins past a reply taller than the viewport in one step", () => {+ expect(bottomPinTarget({ clientHeight: VIEWPORT, scrollHeight: 50_000, scrollTop: 0 })).toBe(+ 50_000 - VIEWPORT,+ );+ });++ it("re-pins when the composer grows and shrinks the viewport", () => {+ const shrunk = { clientHeight: VIEWPORT - 72, scrollHeight: 2000, scrollTop: 2000 - VIEWPORT };+ expect(distanceFromBottom(shrunk)).toBe(72);+ expect(bottomPinTarget(shrunk)).toBe(2000 - (VIEWPORT - 72));+ });++ it("never pins upward when content shrinks under a pinned viewport", () => {+ expect(bottomPinTarget({ clientHeight: VIEWPORT, scrollHeight: 1000, scrollTop: 900 })).toBeNull();+ });++ it("reports no work when the viewport is already at the bottom", () => {+ expect(bottomPinTarget({ clientHeight: VIEWPORT, scrollHeight: 2000, scrollTop: 1400 })).toBeNull();+ });+});diff --git a/packages/views/chat/components/stick-to-bottom.ts b/packages/views/chat/components/stick-to-bottom.tsnew file mode 100644index 0000000000..f9d4c9866e--- /dev/null+++ b/packages/views/chat/components/stick-to-bottom.ts@@ -0,0 +1,212 @@+"use client";++import { useCallback, useEffect, useMemo, useRef } from "react";+import {+ createLiveEndFollow,+ FOLLOW_EDGE_THRESHOLD,+ LINE_SCROLL_PX,+ type LiveEndFollow,+} from "../../common/task-transcript/transcript-follow";++// Bottom-stick for the chat list.+//+// Virtuoso's `followOutput` only fires when the ITEM COUNT changes. A+// streaming assistant reply is ONE row that keeps growing, and a growing+// composer shrinks the list's viewport — neither changes the count, so the+// list has to re-pin itself while the reader is at the live end.+//+// Reader intent comes from the shared live-end latch (transcript-follow.ts):+// scroll position and direction alone cannot separate a reader leaving the+// live end from the browser moving the viewport on its own (a scrollTop clamp+// after the composer collapses, scroll anchoring), so the latch judges intent+// from accumulated input deltas and releases only past FOLLOW_EDGE_THRESHOLD —+// the same forgiveness the list grants Virtuoso via `atBottomThreshold`.+//+// Input is staged, and only the list's own scroll promotes it: rows contain+// nested scrollers (capped `overflow-auto` code blocks) whose wheel/touch+// events bubble here without moving the list, and on a conversation shorter+// than the viewport nothing scrolls at all. Unconsumed input must not release+// the follow. The same rule works in reverse for keys: any scroll key from+// anywhere in the container stages intent, and if the browser answers it by+// scrolling the list (focus on a row control page-scrolls the nearest+// scrollable ancestor), the scroll confirms it — the reader is never pinned+// back over their own keypress.++export interface ScrollMetrics {+ scrollTop: number;+ scrollHeight: number;+ clientHeight: number;+}++export function distanceFromBottom(m: ScrollMetrics): number {+ return Math.max(0, m.scrollHeight - m.scrollTop - m.clientHeight);+}++export function isAtLiveEnd(m: ScrollMetrics): boolean {+ return distanceFromBottom(m) <= FOLLOW_EDGE_THRESHOLD;+}++/** Returns a downward-only scroll target, or `null` when no scrolling is needed. */+export function bottomPinTarget(m: ScrollMetrics): number | null {+ const target = Math.max(0, m.scrollHeight - m.clientHeight);+ return target > m.scrollTop ? target : null;+}++export interface StickToBottom {+ /** For `followOutput`: the reader is still following the live end. */+ isFollowing(): boolean;+ /** Wire to Virtuoso's `totalListHeightChanged`: the content resized. */+ onContentHeightChanged(): void;+}++/**+ * Keeps `scrollEl` pinned to the bottom while the reader follows the live+ * end. Viewport resizes (the composer) are observed here; content resizes+ * (streaming) must be reported through `onContentHeightChanged`, because a+ * ResizeObserver on the container never sees its scroll extent.+ */+export function useStickToBottom(scrollEl: HTMLElement | null): StickToBottom {+ const followRef = useRef<LiveEndFollow | null>(null);+ if (followRef.current === null) {+ followRef.current = createLiveEndFollow();+ // Unlike the transcript, the chat list is always live. Activated at+ // creation, not in an effect: `followOutput` reads the latch on the+ // very first render.+ followRef.current.setActive(true);+ }+ const follow = followRef.current;++ const pin = useCallback(() => {+ if (!scrollEl) return;+ const target = bottomPinTarget(scrollEl);+ if (target !== null) scrollEl.scrollTop = target;+ }, [scrollEl]);++ // Content grew or the viewport resized — displacement with no scroll event,+ // so it can never promote staged reader input.+ const onResize = useCallback(() => {+ if (!scrollEl) return;+ if (follow.onResize(distanceFromBottom(scrollEl))) pin();+ }, [scrollEl, follow, pin]);++ useEffect(() => {+ if (!scrollEl) return;++ // Mirror of the transcript dialog's wiring with the live end at the+ // BOTTOM: away from it is up, so every input sign flips.+ let inputFrame: number | null = null;+ const stageInput = (delta: number) => {+ follow.input(delta);+ if (inputFrame !== null) cancelAnimationFrame(inputFrame);+ inputFrame = requestAnimationFrame(() => {+ inputFrame = null;+ follow.endInputFrame();+ });+ };+ const onWheel = (e: WheelEvent) => {+ const scale =+ e.deltaMode === 1 ? LINE_SCROLL_PX : e.deltaMode === 2 ? scrollEl.clientHeight : 1;+ stageInput(-e.deltaY * scale);+ };+ let touchId: number | null = null;+ let lastTouchY: number | null = null;+ const trackedTouch = (touches: TouchList) =>+ Array.from(touches).find((touch) => touch.identifier === touchId);+ const onTouchStart = (e: TouchEvent) => {+ if (touchId !== null) return;+ const touch = e.changedTouches[0] ?? e.touches[0];+ if (!touch) return;+ touchId = touch.identifier;+ lastTouchY = touch.clientY;+ follow.touchStart();+ };+ const onTouchMove = (e: TouchEvent) => {+ const touch = trackedTouch(e.touches);+ if (!touch) return;+ // Finger moving down scrolls the content up (away from the live end).+ if (lastTouchY !== null) stageInput(touch.clientY - lastTouchY);+ lastTouchY = touch.clientY;+ };+ const onTouchEnd = (e: TouchEvent) => {+ if (touchId === null || trackedTouch(e.touches)) return;+ touchId = null;+ lastTouchY = null;+ follow.touchEnd();+ };+ // No target guard: this container is not focusable, so scroll keys always+ // arrive from a focused row control, and the browser answers them by+ // scrolling the nearest scrollable ancestor — this list. Staging makes+ // that safe in the other direction too: a key a control consumed (Space+ // activating a button, Home in a text field) never scrolls the list, so+ // the staged intent is never promoted.+ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key === "ArrowUp") stageInput(LINE_SCROLL_PX);+ else if (e.key === "ArrowDown") stageInput(-LINE_SCROLL_PX);+ else if (e.key === "PageUp") stageInput(scrollEl.clientHeight);+ else if (e.key === "PageDown") stageInput(-scrollEl.clientHeight);+ // Shift+Space pages UP — away from the live end.+ else if (e.key === " ")+ stageInput(e.shiftKey ? scrollEl.clientHeight : -scrollEl.clientHeight);+ else if (e.key === "Home") stageInput(scrollEl.scrollHeight);+ else if (e.key === "End") stageInput(-scrollEl.scrollHeight);+ };+ const onPointerDown = (e: MouseEvent) => {+ follow.pointerDown(e.target === scrollEl);+ };+ const onPointerUp = () => {+ follow.pointerUp();+ };+ let atEdge = isAtLiveEnd(scrollEl);+ const onScroll = () => {+ const nowAtEdge = isAtLiveEnd(scrollEl);+ if (nowAtEdge !== atEdge) {+ atEdge = nowAtEdge;+ follow.onAtEdgeChange(nowAtEdge);+ }+ // The list itself moved: this is what promotes staged input.+ if (follow.onScroll(distanceFromBottom(scrollEl))) pin();+ };++ // The composer growing (or banners appearing) shrinks the container's box+ // without any scroll event; content growth arrives separately through+ // `onContentHeightChanged`.+ const observer = new ResizeObserver(onResize);+ observer.observe(scrollEl);+ scrollEl.addEventListener("scroll", onScroll, { passive: true });+ scrollEl.addEventListener("wheel", onWheel, { passive: true });+ scrollEl.addEventListener("touchstart", onTouchStart, { passive: true });+ scrollEl.addEventListener("touchmove", onTouchMove, { passive: true });+ scrollEl.addEventListener("touchend", onTouchEnd, { passive: true });+ scrollEl.addEventListener("touchcancel", onTouchEnd, { passive: true });+ scrollEl.addEventListener("keydown", onKeyDown);+ scrollEl.addEventListener("mousedown", onPointerDown);+ window.addEventListener("mouseup", onPointerUp, { capture: true });++ return () => {+ if (inputFrame !== null) cancelAnimationFrame(inputFrame);+ follow.endInputFrame();+ observer.disconnect();+ scrollEl.removeEventListener("scroll", onScroll);+ scrollEl.removeEventListener("wheel", onWheel);+ scrollEl.removeEventListener("touchstart", onTouchStart);+ scrollEl.removeEventListener("touchmove", onTouchMove);+ scrollEl.removeEventListener("touchend", onTouchEnd);+ scrollEl.removeEventListener("touchcancel", onTouchEnd);+ scrollEl.removeEventListener("keydown", onKeyDown);+ scrollEl.removeEventListener("mousedown", onPointerDown);+ window.removeEventListener("mouseup", onPointerUp, { capture: true });+ // The scroller can detach mid-drag; a stuck held-mouse flag would+ // suppress pinning forever.+ follow.pointerUp();+ follow.touchEnd();+ };+ }, [scrollEl, follow, pin, onResize]);++ return useMemo(+ () => ({+ isFollowing: () => follow.isFollowing(),+ onContentHeightChanged: onResize,+ }),+ [follow, onResize],+ );+}diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsxindex 3763e8732e..4b06b8673c 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx@@ -56,7 +56,7 @@ import { runtimeDisplayName, providerDisplayName } from "@multica/core/runtimes"import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";import { redactSecrets } from "./redact";import {- createNewestFirstFollow,+ createLiveEndFollow,FOLLOW_EDGE_THRESHOLD,LINE_SCROLL_PX,} from "./transcript-follow";@@ -333,7 +333,7 @@ export function AgentTranscriptDialog({// controller (see transcript-follow.ts for the model); this component only// wires DOM events to it. A stable instance, never re-rendered by scroll// traffic.- const followCtl = useMemo(() => createNewestFirstFollow(), []);+ const followCtl = useMemo(() => createLiveEndFollow(), []);const detachScrollerRef = useRef<(() => void) | null>(null);const handleScrollerRef = useCallback(@@ -341,30 +341,55 @@ export function AgentTranscriptDialog({detachScrollerRef.current?.();detachScrollerRef.current = null;if (!(el instanceof HTMLElement)) return;+ let inputFrame: number | null = null;+ const stageInput = (delta: number) => {+ followCtl.input(delta);+ if (inputFrame !== null) cancelAnimationFrame(inputFrame);+ inputFrame = requestAnimationFrame(() => {+ inputFrame = null;+ followCtl.endInputFrame();+ });+ };const onWheel = (e: WheelEvent) => {const scale =e.deltaMode === 1 ? LINE_SCROLL_PX : e.deltaMode === 2 ? el.clientHeight : 1;- followCtl.input(e.deltaY * scale);+ stageInput(e.deltaY * scale);};+ let touchId: number | null = null;let lastTouchY: number | null = null;+ const trackedTouch = (touches: TouchList) =>+ Array.from(touches).find((touch) => touch.identifier === touchId);const onTouchStart = (e: TouchEvent) => {- lastTouchY = e.touches[0]?.clientY ?? null;+ if (touchId !== null) return;+ const touch = e.changedTouches[0] ?? e.touches[0];+ if (!touch) return;+ touchId = touch.identifier;+ lastTouchY = touch.clientY;+ followCtl.touchStart();};const onTouchMove = (e: TouchEvent) => {- const y = e.touches[0]?.clientY;- if (y === undefined) return;+ const touch = trackedTouch(e.touches);+ if (!touch) return;// Finger moving up scrolls the content down (away from the live end).- if (lastTouchY !== null) followCtl.input(lastTouchY - y);- lastTouchY = y;+ if (lastTouchY !== null) stageInput(lastTouchY - touch.clientY);+ lastTouchY = touch.clientY;+ };+ const onTouchEnd = (e: TouchEvent) => {+ if (touchId === null || trackedTouch(e.touches)) return;+ touchId = null;+ lastTouchY = null;+ followCtl.touchEnd();};const onKeyDown = (e: KeyboardEvent) => {// Only keys aimed at the scroller itself; Space/arrows bubbling from// row controls are not scroll intent.if (e.target !== el) return;- if (e.key === "ArrowDown") followCtl.input(LINE_SCROLL_PX);- else if (e.key === "ArrowUp") followCtl.input(-LINE_SCROLL_PX);- else if (e.key === "PageDown" || e.key === " ") followCtl.input(el.clientHeight);- else if (e.key === "PageUp") followCtl.input(-el.clientHeight);+ if (e.key === "ArrowDown") stageInput(LINE_SCROLL_PX);+ else if (e.key === "ArrowUp") stageInput(-LINE_SCROLL_PX);+ else if (e.key === "PageDown") stageInput(el.clientHeight);+ // Shift+Space pages up — toward this list's live end.+ else if (e.key === " ") stageInput(e.shiftKey ? -el.clientHeight : el.clientHeight);+ else if (e.key === "PageUp") stageInput(-el.clientHeight);else if (e.key === "End") followCtl.disengage();};// Scrollbar drags hit the scroller element itself; clicks on row@@ -388,14 +413,20 @@ export function AgentTranscriptDialog({el.addEventListener("wheel", onWheel, { passive: true });el.addEventListener("touchstart", onTouchStart, { passive: true });el.addEventListener("touchmove", onTouchMove, { passive: true });+ el.addEventListener("touchend", onTouchEnd, { passive: true });+ el.addEventListener("touchcancel", onTouchEnd, { passive: true });el.addEventListener("keydown", onKeyDown);el.addEventListener("mousedown", onPointerDown);window.addEventListener("mouseup", onPointerUp, { capture: true });el.addEventListener("scroll", onScroll, { passive: true });detachScrollerRef.current = () => {+ if (inputFrame !== null) cancelAnimationFrame(inputFrame);+ followCtl.endInputFrame();el.removeEventListener("wheel", onWheel);el.removeEventListener("touchstart", onTouchStart);el.removeEventListener("touchmove", onTouchMove);+ el.removeEventListener("touchend", onTouchEnd);+ el.removeEventListener("touchcancel", onTouchEnd);el.removeEventListener("keydown", onKeyDown);el.removeEventListener("mousedown", onPointerDown);window.removeEventListener("mouseup", onPointerUp, { capture: true });@@ -403,6 +434,7 @@ export function AgentTranscriptDialog({// The scroller can detach mid-drag (listEpoch remount); a stuck// held-mouse flag would suppress enforcement forever.followCtl.pointerUp();+ followCtl.touchEnd();};},[followCtl],@@ -1204,7 +1236,7 @@ export function AgentTranscriptDialog({}atBottomThreshold={FOLLOW_EDGE_THRESHOLD}atTopThreshold={FOLLOW_EDGE_THRESHOLD}- atTopStateChange={(atTop) => followCtl.onAtTopChange(atTop)}+ atTopStateChange={(atTop) => followCtl.onAtEdgeChange(atTop)}scrollerRef={handleScrollerRef}computeItemKey={(_, row) => row.seq}components={LIST_COMPONENTS}diff --git a/packages/views/common/task-transcript/transcript-follow.test.ts b/packages/views/common/task-transcript/transcript-follow.test.tsindex 1934097ed4..328b74f1d0 100644--- a/packages/views/common/task-transcript/transcript-follow.test.ts+++ b/packages/views/common/task-transcript/transcript-follow.test.ts@@ -1,10 +1,10 @@// @vitest-environment nodeimport { describe, it, expect } from "vitest";-import { createNewestFirstFollow, FOLLOW_EDGE_THRESHOLD } from "./transcript-follow";+import { createLiveEndFollow, FOLLOW_EDGE_THRESHOLD } from "./transcript-follow";function makeFollow(startAt = 0) {let t = startAt;- const follow = createNewestFirstFollow(() => t);+ const follow = createLiveEndFollow(() => t);const tick = (ms: number) => {t += ms;};@@ -12,7 +12,7 @@ function makeFollow(startAt = 0) {return { follow, tick };}-describe("createNewestFirstFollow", () => {+describe("createLiveEndFollow", () => {it("starts following and pins system displacement back to the live end", () => {const { follow, tick } = makeFollow();tick(1000);@@ -21,52 +21,257 @@ describe("createNewestFirstFollow", () => {expect(follow.isFollowing()).toBe(true);});- it("does not disengage when a prepend shift lands inside the input window after an in-zone nudge", () => {+ it("a system shift inside the reader's gesture is pinned, not blamed on them", () => {// Regression: absolute-position heuristics dropped the latch here — the// user nudged 30px (still inside the zone), then a flush pushed the- // viewport past the threshold while their input was still fresh.+ // viewport past the threshold while their input was still fresh. Only+ // 30px of the movement is attributable to the reader; the rest is the+ // system's and is corrected immediately.const { follow, tick } = makeFollow();tick(1000);follow.input(30);tick(200); // inside the intent window- expect(follow.onScroll(500)).toBe(false); // user mid-gesture: no pin either+ expect(follow.onScroll(500)).toBe(true); // pin the system's 470px backexpect(follow.isFollowing()).toBe(true);- tick(400); // gesture over- expect(follow.onScroll(500)).toBe(true); // now pin back+ });++ it("a system shift after a confirmed scroll is pinned, not treated as continued motion", () => {+ // Regression: confirming a small scroll opened a motion window that any+ // same-direction displacement could extend, so a prepend landing inside it+ // was credited to the reader and released the follow — from 30px of real+ // movement, still well inside the edge zone.+ const { follow, tick } = makeFollow();+ tick(1000);+ follow.input(30);+ follow.onScroll(30); // the surface honours it: reader motion, confirmed+ follow.endInputFrame();+ tick(100); // still inside the settle window+ expect(follow.onScroll(230)).toBe(true); // pin the system's 200px back+ expect(follow.isFollowing()).toBe(true);+ });++ it("keeps following a notch whose scroll animates across several frames", () => {+ // The wiring drops the claim after one frame, so a browser-animated wheel+ // scroll spends the rest through the motion it already confirmed. Capping+ // that at the unspent claim is what keeps the case above from counting.+ const { follow, tick } = makeFollow();+ tick(1000);+ follow.input(100);+ tick(16);+ expect(follow.onScroll(40)).toBe(false);+ follow.endInputFrame();+ tick(16);+ expect(follow.onScroll(80)).toBe(false);+ tick(16);+ expect(follow.onScroll(100)).toBe(false);+ expect(follow.isFollowing()).toBe(true); // 100px is inside the zone+ });++ it("keeps following when an animated notch lands on uneven fractional frames", () => {+ // Carry is spent in fractional steps, so its running total drifts from the+ // surface's own arithmetic. An exact comparison rejected the last frame by+ // about one ulp and pinned a perfectly ordinary wheel scroll back.+ const { follow, tick } = makeFollow();+ tick(1000);+ follow.input(100);+ tick(16);+ expect(follow.onScroll(7.29)).toBe(false);+ follow.endInputFrame();+ tick(16);+ expect(follow.onScroll(22.86528)).toBe(false);+ tick(16);+ expect(follow.onScroll(100)).toBe(false);+ });++ it("confirms a second notch that arrives while the first is still animating", () => {+ // The overlapping claim is confirmed by this same-direction scroll; without+ // folding it into the carry, endInputFrame() dropped it and the rest of the+ // reader's own scroll was pinned back.+ const { follow, tick } = makeFollow();+ tick(1000);+ follow.input(100);+ tick(16);+ follow.onScroll(40);+ follow.input(100); // second notch, first is still animating+ tick(16);+ follow.onScroll(80);+ follow.endInputFrame();+ tick(16);+ expect(follow.onScroll(120)).toBe(false);+ tick(16);+ follow.onScroll(160);+ expect(follow.isFollowing()).toBe(false); // 160px of their own scrolling+ });++ it("folds an overlapping notch on the way back to the live end too", () => {+ // The reader must still be FOLLOWING for the pin verdict to mean anything:+ // park the viewport out at 300px under a held pointer, which suppresses the+ // pin without attributing anything, then walk back with two notches.+ const { follow, tick } = makeFollow();+ tick(1000);+ follow.pointerDown(false);+ follow.onScroll(300);+ follow.pointerUp();+ expect(follow.isFollowing()).toBe(true);++ follow.input(-100);+ tick(16);+ expect(follow.onScroll(260)).toBe(false);+ follow.input(-100); // second notch back, first still animating+ tick(16);+ expect(follow.onScroll(220)).toBe(false);+ follow.endInputFrame();+ tick(16);+ // Without the toward fold the second notch is gone and this pins.+ expect(follow.onScroll(180)).toBe(false);+ });++ it("releases when touch momentum carries a confirmed flick past the threshold", () => {+ const { follow } = makeFollow();+ follow.touchStart();+ follow.input(80);+ expect(follow.onScroll(80)).toBe(false);+ follow.touchEnd();++ expect(follow.onScroll(160)).toBe(false);+ expect(follow.isFollowing()).toBe(false);+ });++ it("counts the surface's fractional touch displacement", () => {+ const { follow } = makeFollow();+ follow.touchStart();+ follow.input(80);+ expect(follow.onScroll(80.5)).toBe(false);+ expect(follow.isFollowing()).toBe(true);+ follow.touchEnd();++ expect(follow.onScroll(120.25)).toBe(false);+ expect(follow.isFollowing()).toBe(false);+ });++ it("does not pin unattributed displacement during an active touch", () => {+ const { follow } = makeFollow();+ follow.touchStart();++ expect(follow.onScroll(300)).toBe(false);+ });++ it("releases for wheel notches spaced past the intent window", () => {+ // A discrete mouse wheel at reading pace: one notch per event, far more+ // than the window apart. Attributed displacement accumulates across+ // gestures, so pacing and device units cannot defeat the threshold.+ const { follow, tick } = makeFollow();+ follow.input(100);+ expect(follow.onScroll(100)).toBe(false); // notch 1: 100px taken+ tick(500);+ follow.input(100);+ expect(follow.onScroll(200)).toBe(false); // notch 2: 200px taken, released+ expect(follow.isFollowing()).toBe(false);+ });++ it("accumulates displacement across pins during a fast stream", () => {+ // Sub-threshold notches each answered by a chunk that pins the reader+ // back: the taken displacement survives the pins, so persistence wins+ // instead of losing every round.+ const { follow, tick } = makeFollow();+ follow.input(60);+ expect(follow.onScroll(60)).toBe(false);+ tick(400);+ expect(follow.onResize(240)).toBe(true); // chunk pins back+ follow.input(60);+ expect(follow.onScroll(60)).toBe(false);+ tick(400);+ expect(follow.onResize(240)).toBe(true); // chunk pins back again+ follow.input(60);+ follow.onScroll(60); // 180px taken in total+ expect(follow.isFollowing()).toBe(false);+ });++ it("pins displacement that lands inside the intent window", () => {+ // The final chunk of a reply has a whole window to land in after any+ // small nudge; the pin decision must not hide behind a timer, because+ // no later event exists to re-evaluate it.+ const { follow } = makeFollow();+ follow.input(2);+ expect(follow.onScroll(2)).toBe(false); // 2px nudge, confirmed+ expect(follow.onResize(182)).toBe(true); // still inside the window: pin nowexpect(follow.isFollowing()).toBe(true);});- it("disengages on accumulated user input beyond the threshold", () => {+ it("re-engages a reader who walks themselves back to the live end", () => {+ const { follow } = makeFollow();+ follow.input(200);+ follow.onScroll(200); // released+ expect(follow.isFollowing()).toBe(false);+ follow.input(-200);+ expect(follow.onScroll(0)).toBe(false);+ expect(follow.isFollowing()).toBe(true);+ });++ it("disengages on accumulated user input once the surface's scroll confirms it", () => {const { follow } = makeFollow();follow.input(80);+ follow.input(80); // cumulative 160 > threshold — but only staged so farexpect(follow.isFollowing()).toBe(true);- follow.input(80); // cumulative 160 > threshold+ expect(follow.onScroll(160)).toBe(false); // the surface moved: released, no pinexpect(follow.isFollowing()).toBe(false);expect(follow.onScroll(400)).toBe(false); // no pinning once disengaged});- it("upward input rolls the accumulator back instead of counting as intent", () => {+ it("input the surface never consumed does not release, and never blocks the pin", () => {+ // A wheel over a nested scroller (or a list too short to scroll) bubbles+ // to the container without moving it: no scroll ever attributes it.+ const { follow } = makeFollow();+ follow.input(300);+ expect(follow.isFollowing()).toBe(true);+ expect(follow.onResize(180)).toBe(true); // growth pins straight away+ expect(follow.isFollowing()).toBe(true);+ });++ it("pins a system shift after the surface left input unconsumed", () => {+ const { follow, tick } = makeFollow();+ follow.input(300);+ follow.endInputFrame();+ tick(100);++ expect(follow.onScroll(200)).toBe(true);+ expect(follow.isFollowing()).toBe(true);+ });++ it("a new gesture does not inherit unconsumed intent from an old one", () => {+ const { follow, tick } = makeFollow();+ follow.input(300); // never confirmed by a scroll+ tick(1000);+ follow.input(60); // fresh gesture, sub-threshold on its own+ expect(follow.onScroll(60)).toBe(false);+ expect(follow.isFollowing()).toBe(true);+ });++ it("a mixed-direction gesture counts its net movement, not its pushes", () => {const { follow } = makeFollow();follow.input(100);follow.input(-90);- follow.input(100); // net 110 <= threshold+ follow.input(100);+ // The surface only net-moved 110: attribution is capped by movement.+ expect(follow.onScroll(110)).toBe(false);expect(follow.isFollowing()).toBe(true);});- it("a pin clears sub-threshold residue so old nudges cannot accumulate", () => {+ it("a stale gesture's budget does not attribute a later system shift", () => {const { follow, tick } = makeFollow();- follow.input(100);+ follow.input(100); // never confirmedtick(1000);- expect(follow.onScroll(300)).toBe(true); // pinned; residue cleared+ expect(follow.onScroll(300)).toBe(true); // whole shift is the system's: pinfollow.input(100); // fresh gesture: 100 <= threshold on its ownexpect(follow.isFollowing()).toBe(true);});- it("re-engages when the viewport returns to the top zone", () => {+ it("re-engages when the viewport returns to the live-end zone", () => {const { follow } = makeFollow();follow.input(FOLLOW_EDGE_THRESHOLD + 1);+ follow.onScroll(FOLLOW_EDGE_THRESHOLD + 1);expect(follow.isFollowing()).toBe(false);- follow.onAtTopChange(true);+ follow.onAtEdgeChange(true);expect(follow.isFollowing()).toBe(true);});diff --git a/packages/views/common/task-transcript/transcript-follow.ts b/packages/views/common/task-transcript/transcript-follow.tsindex 3563828116..8696d01f98 100644--- a/packages/views/common/task-transcript/transcript-follow.ts+++ b/packages/views/common/task-transcript/transcript-follow.ts@@ -1,67 +1,123 @@-// Live-follow latch for the newest-first transcript (#5921).+// Live-end follow latch, shared by the newest-first transcript (#5921) and the+// bottom-anchored chat list (chat/components/stick-to-bottom.ts).//-// Newest-first shows live events as PREPENDS, and the list's firstItemIndex-// anchoring holds the viewport across a prepend — which means every flush-// moves the viewport away from the top on its own. "Am I at the top right-// now" therefore cannot distinguish a reader who scrolled away from one the-// anchoring pushed down. This controller keeps that distinction:+// Both surfaces have the same problem: the system moves the viewport on its+// own (prepend anchoring in the transcript; streaming growth, composer+// resizes and the resulting scroll clamps in the chat list), so "am I at the+// live end right now" cannot distinguish a reader who scrolled away from a+// viewport the system displaced. This latch keeps that distinction://-// - Follow disengages only on accumulated USER displacement away from the-// live end (wheel/touch/key deltas, or a scrollbar drag) beyond the edge-// threshold. System displacement never counts, no matter how far it moves-// the viewport.-// - While following, any non-user displacement is pinned straight back to-// the live end (`pin` from onScroll) — but never while the user is-// mid-gesture or holding the mouse down (text selection autoscroll must-// not be fought).-// - Arriving back within the edge zone (atTop) re-engages the follow.+// - Input alone never releases. It opens a claim for the current rendering+// frame, and only the surface's own scroll can confirm reader-driven motion.+// The wiring discards unused claims after that frame, so a later system shift+// cannot inherit input consumed by a nested scroller.+// - Confirmed motion uses the surface's displacement, not raw input magnitude.+// Continued same-direction movement inside the settle window remains reader+// motion, including touch momentum and fractional drag frames.+// - Attributed displacement ACCUMULATES until the reader returns to the live+// end; it does not expire with the gesture and pins do not erase it. A+// trackpad flick and five discrete wheel notches at reading pace both cross+// the same threshold, and repeated sub-threshold attempts against a fast+// stream eventually win instead of being re-pinned forever.+// - While following, displacement not attributed to the reader is pinned+// straight back to the live end (`onScroll` / `onResize` return the+// verdict) — immediately, with no intent-window timer for a final event to+// hide behind — but never during an active touch or while the mouse is held+// down (text selection autoscroll must not be fought).+// - Arriving back within the edge zone re-engages the follow.//-// Pure state machine so the decision table is unit-testable; the dialog owns-// wiring it to DOM events.+// The state machine is direction-agnostic: callers feed it away-positive+// input deltas and the current distance from THEIR live end (`scrollTop` for+// the newest-first transcript, distance-from-bottom for the chat list).+//+// Pure state machine so the decision table is unit-testable; each surface+// owns wiring it to DOM events.-// Forgiving "at the live end" zone, matching the chat list's atBottomThreshold:-// within this distance of the live edge the reader counts as following.+// Forgiving "at the live end" zone: within this distance of the live edge the+// reader counts as following. The chat list also passes this to Virtuoso as+// `atBottomThreshold`, so both judges of "at the bottom" agree.export const FOLLOW_EDGE_THRESHOLD = 120;-// How long after the last wheel/touch/key input the viewport is still treated-// as user-controlled (suppresses pinning mid-gesture, including momentum).-const INPUT_INTENT_WINDOW_MS = 300;+// Maximum gap between an input and its confirming scroll, or between scrolls+// in confirmed motion. DOM wiring normally clears unconfirmed input sooner,+// after the next animation frame.+const MOTION_SETTLE_WINDOW_MS = 300;// WheelEvent.deltaMode 1 (lines) / 2 (pages) conversion.export const LINE_SCROLL_PX = 40;-export interface NewestFirstFollow {- /** `isLive && sortDirection === "newest_first"`; everything is inert otherwise. */+export interface LiveEndFollow {+ /** Whether the surface is live; everything is inert while inactive. */setActive(active: boolean): void;/** New list instance (task/sort/filter change): back to following. */reset(): void;isFollowing(): boolean;- /** Explicit navigation away from the live end (e.g. timeline segment click). */+ /** Explicit navigation away from the live end (e.g. segment click). */disengage(): void;- /** User scroll input in px; positive = away from the live end. */+ /**+ * User scroll input in px; positive = away from the live end. Opens a+ * budget the surface's own scroll can attribute displacement against.+ */input(delta: number): void;+ /** Discards input the surface did not consume during its rendering frame. */+ endInputFrame(): void;+ /** An active touch prevents pinning while drag displacement is confirmed. */+ touchStart(): void;+ /** Ends the held state; confirmed momentum may continue within the settle window. */+ touchEnd(): void;/** Mousedown inside the scroller; `onScroller` = on the element itself (scrollbar). */pointerDown(onScroller: boolean): void;pointerUp(): void;- onAtTopChange(atTop: boolean): void;- /** Every scroll event. Returns whether to pin the viewport back to the top. */- onScroll(scrollTop: number): boolean;+ onAtEdgeChange(atEdge: boolean): void;+ /**+ * The surface itself scrolled. Confirms staged input or continues recent+ * reader motion; returns whether to pin the viewport back to the live end.+ */+ onScroll(distance: number): boolean;+ /**+ * The live end moved without a scroll (content grew, viewport resized).+ * Never attributes displacement to the reader; returns whether to pin back.+ */+ onResize(distance: number): boolean;}-export function createNewestFirstFollow(now: () => number = () => Date.now()): NewestFirstFollow {+export function createLiveEndFollow(now: () => number = () => Date.now()): LiveEndFollow {let active = false;let following = true;- // Accumulated user-caused displacement away from the live end. Compared- // against the edge threshold instead of scrollTop: absolute position mixes- // user and system displacement (a prepend can land inside the intent- // window and push the viewport past any threshold on its own).- let pendingAway = 0;- let lastInputAt = -INPUT_INTENT_WINDOW_MS;+ // Unspent input claims for the current frame, split by direction. A claim+ // becomes reader motion only when the surface confirms matching movement.+ let awayBudget = 0;+ let towardBudget = 0;+ let lastInputAt = -MOTION_SETTLE_WINDOW_MS;+ // Displacement the reader actually took, confirmed scroll by scroll. Does+ // not expire and survives pins: repeated sub-threshold attempts against a+ // fast stream accumulate into a release instead of losing every round.+ let awayTaken = 0;+ let lastDistance = 0;let mouseHeld = false;let scrollbarDrag = false;+ let touchHeld = false;+ let motionDirection: -1 | 0 | 1 = 0;+ let lastMotionAt = -MOTION_SETTLE_WINDOW_MS;+ // What set the current motion running, and how much of the claim behind it+ // the surface has not spent yet. Touch coasts past its claim (momentum is+ // not proportional to finger travel); everything else may only continue+ // for what the reader actually asked for, so a system shift arriving inside+ // the window has nothing to draw on.+ let motionSource: "touch" | "input" | null = null;+ let motionCarry = 0;++ const inputFresh = () => now() - lastInputAt < MOTION_SETTLE_WINDOW_MS;+ const motionFresh = () => now() - lastMotionAt < MOTION_SETTLE_WINDOW_MS;++ // Carry is spent in fractional steps, so its running total drifts from the+ // surface's own arithmetic by a few ulps. Scaled to the amount at hand, a+ // gap this small is rounding — the system moving the viewport is pixels.+ const withinCarry = (amount: number) =>+ amount <= motionCarry + Math.max(1, motionCarry) * 1e-9;- const userControlsViewport = () =>- mouseHeld || scrollbarDrag || now() - lastInputAt < INPUT_INTENT_WINDOW_MS;+ const pinVerdict = (distance: number): boolean =>+ following && !mouseHeld && !scrollbarDrag && !touchHeld && distance > 0;return {setActive(a: boolean) {@@ -69,9 +125,17 @@ export function createNewestFirstFollow(now: () => number = () => Date.now()): N},reset() {following = true;- pendingAway = 0;+ awayBudget = 0;+ towardBudget = 0;+ awayTaken = 0;+ lastDistance = 0;mouseHeld = false;scrollbarDrag = false;+ touchHeld = false;+ motionDirection = 0;+ motionSource = null;+ motionCarry = 0;+ lastMotionAt = -MOTION_SETTLE_WINDOW_MS;},isFollowing: () => active && following,disengage() {@@ -79,9 +143,25 @@ export function createNewestFirstFollow(now: () => number = () => Date.now()): N},input(delta: number) {if (!active) return;+ // A fresh gesture opens fresh budgets: a claim the surface never+ // honored must not linger into a later gesture.+ if (!inputFresh()) {+ awayBudget = 0;+ towardBudget = 0;+ }lastInputAt = now();- pendingAway = Math.max(0, pendingAway + delta);- if (following && pendingAway > FOLLOW_EDGE_THRESHOLD) following = false;+ if (delta > 0) awayBudget += delta;+ else towardBudget -= delta;+ },+ endInputFrame() {+ awayBudget = 0;+ towardBudget = 0;+ },+ touchStart() {+ if (active) touchHeld = true;+ },+ touchEnd() {+ touchHeld = false;},pointerDown(onScroller: boolean) {if (!active) return;@@ -92,25 +172,112 @@ export function createNewestFirstFollow(now: () => number = () => Date.now()): NmouseHeld = false;scrollbarDrag = false;},- onAtTopChange(atTop: boolean) {- if (!active || !atTop) return;+ onAtEdgeChange(atEdge: boolean) {+ if (!active || !atEdge) return;following = true;- pendingAway = 0;+ awayBudget = 0;+ towardBudget = 0;+ awayTaken = 0;+ motionDirection = 0;+ motionSource = null;+ motionCarry = 0;},- onScroll(scrollTop: number): boolean {+ onScroll(distance: number): boolean {if (!active) return false;+ const moved = distance - lastDistance;+ lastDistance = distance;// A scrollbar drag is fully user-controlled: absolute position is the// user's displacement, so the plain threshold applies.- if (scrollbarDrag && scrollTop > FOLLOW_EDGE_THRESHOLD) {- following = false;+ if (scrollbarDrag) {+ if (distance > FOLLOW_EDGE_THRESHOLD) following = false;return false;}- if (following && !userControlsViewport() && scrollTop > 0) {- // System displacement got corrected; drop any sub-threshold residue- // so old nudges don't accumulate into a spurious disengage later.- pendingAway = 0;+ // Motion already confirmed in this direction continues without a new+ // claim. Touch coasts freely — momentum is not proportional to finger+ // travel. Every other source is capped by the claim the surface has not+ // spent yet, so a system shift landing inside the window (a transcript+ // prepend) finds nothing to draw on and falls through to the pin.+ if (moved > 0 && motionDirection === 1 && (touchHeld || motionFresh())) {+ // A notch arriving mid-animation is confirmed by this same-direction+ // scroll, so fold it in: the frame that ends the claim would otherwise+ // discard it and pin the rest of the reader's own scroll back.+ if (inputFresh() && awayBudget > 0) {+ motionCarry += awayBudget;+ awayBudget = 0;+ }+ if (motionSource === "touch" || withinCarry(moved)) {+ if (motionSource !== "touch") motionCarry = Math.max(0, motionCarry - moved);+ awayTaken += moved;+ lastMotionAt = now();+ if (following && awayTaken > FOLLOW_EDGE_THRESHOLD) following = false;+ return false;+ }+ } else if (moved < 0 && motionDirection === -1 && (touchHeld || motionFresh())) {+ if (inputFresh() && towardBudget > 0) {+ motionCarry += towardBudget;+ towardBudget = 0;+ }+ if (motionSource === "touch" || withinCarry(-moved)) {+ if (motionSource !== "touch") motionCarry = Math.max(0, motionCarry + moved);+ awayTaken = Math.max(0, awayTaken + moved);+ lastMotionAt = now();+ if (distance === 0) {+ following = true;+ awayBudget = 0;+ towardBudget = 0;+ awayTaken = 0;+ motionDirection = 0;+ motionSource = null;+ motionCarry = 0;+ }+ return false;+ }+ }+ if (moved > 0 && inputFresh() && awayBudget > 0) {+ const attributed = Math.min(awayBudget, moved);+ awayBudget -= attributed;+ // Touch displacement need not match finger travel pixel-for-pixel.+ if (touchHeld || attributed === moved) {+ awayTaken += moved;+ motionDirection = 1;+ motionSource = touchHeld ? "touch" : "input";+ // One notch can animate across several frames; the wiring drops the+ // claim after the first, so carry its remainder into the motion.+ motionCarry = awayBudget;+ lastMotionAt = now();+ if (following && awayTaken > FOLLOW_EDGE_THRESHOLD) following = false;+ return false;+ }+ } else if (moved < 0 && inputFresh() && towardBudget > 0) {+ const attributed = Math.min(towardBudget, -moved);+ towardBudget -= attributed;+ if (touchHeld || attributed === -moved) {+ awayTaken = Math.max(0, awayTaken + moved);+ motionDirection = -1;+ motionSource = touchHeld ? "touch" : "input";+ motionCarry = towardBudget;+ lastMotionAt = now();+ if (distance === 0) {+ following = true;+ awayBudget = 0;+ towardBudget = 0;+ awayTaken = 0;+ motionDirection = 0;+ }+ return false;+ }+ }+ return pinVerdict(distance);+ },+ onResize(distance: number): boolean {+ if (!active) return false;+ if (pinVerdict(distance)) {+ // The caller pins to the live end; record the destination so the+ // pin's own scroll (or its absence under test) reads as no movement.+ lastDistance = 0;return true;}+ lastDistance = distance;return false;},};