diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index 0ca1f46f5d7ea..a68a54e32b0d3 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -35,6 +35,7 @@ import "~/index.css";
import { environmentThreadDetails } from "../../state/threads";
import { act, fakeTimers, render, stubGlobal } from "../../../test/render";
+import { observeResize } from "~/lib/observeResize";
import { ChangedFilesCard } from "./ChangedFilesTree";
import { MessagesTimeline } from "./MessagesTimeline";
import { makeStreamingTimelineFixture } from "../../test-fixtures";
@@ -359,6 +360,90 @@ describe("MessagesTimeline work rows", () => {
await vi.waitFor(() => expect(distanceFromEnd()).toBeLessThan(2));
});
+ it("pins the live end at once when the viewport shrinks during a turn", async () => {
+ const props = { ...baseProps(), isWorking: true };
+ const runId = RunId.make("live-run");
+ const container = document.createElement("div");
+ container.style.cssText = "height: 600px; width: 900px; display: flex; flex-direction: column;";
+ const reply = (id: string) =>
+ message("Streamed reply\n\n".repeat(40), { role: "assistant", runId }, id);
+ const entries = [
+ ...Array.from({ length: 12 }, (_, index) =>
+ message(`Earlier context ${index}`, {}, `context-${index}`),
+ ),
+ reply("progress"),
+ ];
+ // The app shell subscribes to the shared resize observer before any list mounts, so it is
+ // notified before Legend measures the new viewport.
+ const shell = document.body.appendChild(document.createElement("div"));
+ onTestFinished(() => shell.remove());
+ onTestFinished(observeResize(shell, () => {}));
+ await using screen = await render(, {
+ container,
+ });
+ const viewport = props.listRef.current!.getScrollableNode()!;
+ const distanceFromEnd = () =>
+ viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop;
+ await vi.waitFor(() => expect(distanceFromEnd()).toBeLessThan(2));
+ using scrollTo = vi.spyOn(viewport, "scrollTo");
+ const pinnedEnd = (behavior: ScrollBehavior) =>
+ vi.waitFor(() => {
+ expect(scrollTo).toHaveBeenLastCalledWith(expect.objectContaining({ behavior }));
+ expect(distanceFromEnd()).toBeLessThan(2);
+ });
+
+ await screen.rerender(
+ ,
+ );
+ await vi.waitFor(() =>
+ expect(scrollTo).toHaveBeenCalledWith(expect.objectContaining({ behavior: "smooth" })),
+ );
+ // Shrinks by more than the new viewport while that smooth pin runs.
+ container.style.height = "200px";
+ await pinnedEnd("instant");
+
+ await screen.rerender(
+ ,
+ );
+ await pinnedEnd("smooth");
+
+ // Read after Legend's resize delivery and its microtasks, before the frame paints.
+ const distanceAfterResize = (height: string, change: () => void) =>
+ new Promise((resolve) => {
+ const observer = new ResizeObserver(() => {
+ observer.disconnect();
+ resolve(distanceFromEnd());
+ });
+ observer.observe(viewport);
+ change();
+ container.style.height = height;
+ });
+ // The newest row grows in the same resize delivery.
+ const newestParagraph = screen.getByText("Streamed reply").last().element() as HTMLElement;
+ expect(
+ await distanceAfterResize("300px", () => (newestParagraph.style.paddingBottom = "191px")),
+ ).toBeLessThan(2);
+ // The scroll-to-end settle's scrollToOffset clears Legend's follow while it runs.
+ expect(
+ await distanceAfterResize("250px", () => {
+ void props.listRef.current!.scrollToOffset({
+ offset: viewport.scrollHeight - viewport.clientHeight,
+ animated: false,
+ });
+ expect(props.listRef.current!.getState().isFollowingEnd).toBe(false);
+ }),
+ ).toBeLessThan(2);
+
+ viewport.scrollTop = 0;
+ await vi.waitFor(() => expect(props.listRef.current!.getState().isFollowingEnd).toBe(false));
+ scrollTo.mockClear();
+ expect(await distanceAfterResize("500px", () => {})).toBeGreaterThan(500);
+ expect(scrollTo).not.toHaveBeenCalled();
+ });
+
it.each(["delegated", "legacy", "missing"] as const)(
"uses the reported task for %s completion notifications",
async (source) => {
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 3b8db4484132d..9855140c06674 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -22,6 +22,7 @@ import {
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
+import { flushSync } from "react-dom";
import { observeResize } from "~/lib/observeResize";
import { useStableCallback } from "~/hooks/useStableCallback";
@@ -978,6 +979,41 @@ const ConversationTimeline = memo(function ConversationTimeline({
if (viewportElement) measureTimelineGutter(viewportElement);
});
};
+ const maintainScrollAtEnd =
+ citationPositioning ||
+ (restoringThreadPosition && rememberedPosition?.atEnd === false) ||
+ anchoredEndSpace ||
+ !liveFollowEnabled ||
+ fullscreenAppRowId !== null
+ ? false
+ : isWorking && !prefersReducedMotion && settlingListIdentity === null
+ ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH
+ : TIMELINE_MAINTAIN_SCROLL_AT_END;
+ // Legend animates every end pin of an animated list and queues a resize pin behind a running
+ // one, so a viewport resize (terminal drawer) would push the live end out of view for a beat.
+ // Runs from Legend's onLayout, inside the resize batch that flushes item growth after it, so
+ // the pin waits for that flush. scrollToEnd commits through a React update; flushSync paints it.
+ const listViewportHeightRef = useRef(null);
+ const pinEndOnViewportResize = useStableCallback(
+ (event: { nativeEvent: { layout: { height: number } } }) => {
+ const { height } = event.nativeEvent.layout;
+ const previousHeight = listViewportHeightRef.current;
+ listViewportHeightRef.current = height;
+ if (previousHeight === null || previousHeight === height) return;
+ if (maintainScrollAtEnd !== TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH) return;
+ const list = listRef.current;
+ if (!list) return;
+ const state = list.getState();
+ // Any scroll request clears Legend's follow while it runs, so the scroll-to-end settle
+ // reads as leaving the end. A reader who left the end band is still never pulled back.
+ if (
+ !state.isFollowingEnd &&
+ !resolveTimelineIsAtEnd({ ...state, scrollLength: previousHeight })
+ )
+ return;
+ queueMicrotask(() => flushSync(() => void list.scrollToEnd({ animated: false })));
+ },
+ );
const attachTimelineViewportElement = (viewportElement: HTMLDivElement | null) => {
setTimelineViewportElement(viewportElement);
if (!viewportElement) return;
@@ -1322,17 +1358,8 @@ const ConversationTimeline = memo(function ConversationTimeline({
onLoad={handleListLoad}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={anchoredEndSpace ? contentInsetEndAdjustment : 0}
- maintainScrollAtEnd={
- citationPositioning ||
- (restoringThreadPosition && rememberedPosition?.atEnd === false) ||
- anchoredEndSpace ||
- !liveFollowEnabled ||
- fullscreenAppRowId !== null
- ? false
- : isWorking && !prefersReducedMotion && settlingListIdentity === null
- ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH
- : TIMELINE_MAINTAIN_SCROLL_AT_END
- }
+ maintainScrollAtEnd={maintainScrollAtEnd}
+ onLayout={pinEndOnViewportResize}
maintainVisibleContentPosition={
findActive ||
citationPositioning ||