fix(chat): prevent stale timeline scroll and rerenders

- Disable LegendList end-maintenance that could snap after user scrolling
- Cancel stale imperative scrolls and release settled turn anchors
- Stabilize handoff run data to avoid per-event timeline rerenders
This commit is contained in:
Julius Marminge authored and maria-rcks committed 2026-08-03 11:45:13 -04:00
1 parent b76a0919dc
commit f29edafe04
4 files changed
+113 -26

No files matched your search

+49
View File
@@ -309,6 +309,8 @@ import { useAssetUrls } from "../assets/assetUrls";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
// Never part of timeline row data — see cancelTimelineLiveFollowForUserNavigation.
const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});
const EMPTY_PROVIDERS: ServerProvider[] = [];
// During an active turn the thread's updatedAt advances several times per
// second, and every server-side visit is a full command dispatch plus a
@@ -1569,6 +1571,28 @@ function ChatViewContent(props: ChatViewProps) {
setTimelineAnchor({ threadKey: activeThreadKey, messageId: null });
}
const timelineAnchorMessageId = timelineAnchor.messageId;
// Release the turn anchor once its run finishes. LegendList sizes the
// anchored end-space filler for the geometry at anchor time and never
// recomputes it, so a lingering anchor leaves stale filler height behind
// the composer — phantom scroll range on threads whose content fits.
const anchorRunSettled = useMemo(() => {
if (timelineAnchorMessageId === null) return false;
const anchorRun = serverProjection?.runs.find(
(run) => run.userMessageId === timelineAnchorMessageId,
);
if (anchorRun === undefined) return false;
return (
anchorRun.status !== "preparing" &&
anchorRun.status !== "queued" &&
anchorRun.status !== "starting" &&
anchorRun.status !== "running" &&
anchorRun.status !== "waiting"
);
}, [serverProjection, timelineAnchorMessageId]);
useEffect(() => {
if (!anchorRunSettled) return;
setTimelineAnchor({ threadKey: activeThreadKey, messageId: null });
}, [anchorRunSettled, activeThreadKey]);
const activeRightPanelKind = useRightPanelStore((state) =>
selectActiveRightPanel(state.byThreadKey, activeThreadRef),
);
@@ -3479,6 +3503,7 @@ function ChatViewContent(props: ChatViewProps) {
const anchorScrollRestoreFrameRef = useRef<number | null>(null);
const cancelTimelineLiveFollowForUserNavigation = useCallback(() => {
anchorUserScrollGenerationRef.current += 1;
const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling";
timelineScrollModeRef.current = "free-scrolling";
liveFollowUserScrollGenerationRef.current = null;
pendingTimelineAnchorRef.current = null;
@@ -3490,6 +3515,30 @@ function ChatViewContent(props: ChatViewProps) {
cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
anchorScrollRestoreFrameRef.current = null;
}
if (wasProgrammaticScrollMode) {
// While following or anchoring, our scrollToEnd/scrollToOffset calls can
// sit in LegendList's pending-imperative-scroll queue (it defers them
// while layout settles) and fire seconds later with stale targets,
// yanking the view away after the user scrolled. Starting a new
// imperative scroll cancels everything queued; targeting an item that
// is not in the data makes the new request itself resolve without ever
// scrolling, so this is a pure cancel.
void legendListRef.current?.scrollToItem({
item: TIMELINE_SCROLL_CANCEL_SENTINEL,
animated: false,
});
// An already-started animated scroll (behavior: smooth) keeps running in
// the browser regardless of the queue; a same-position instant write is
// the only way to halt it where it is.
const scrollNode = legendListRef.current?.getScrollableNode() as
| { scrollTop?: number }
| null
| undefined;
const currentScrollTop = scrollNode?.scrollTop;
if (scrollNode && typeof currentScrollTop === "number") {
scrollNode.scrollTop = currentScrollTop;
}
}
}, []);
const cancelTimelineLiveFollowForUserNavigationRef = useRef(
cancelTimelineLiveFollowForUserNavigation,
@@ -416,11 +416,10 @@ describe("MessagesTimeline", () => {
);
expect(markup).toContain("Show full message");
expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
expect(markup).toContain('data-maintain-scroll-at-end-animated="false"');
expect(markup).toContain('data-maintain-scroll-at-end-data-change="true"');
expect(markup).toContain('data-maintain-scroll-at-end-item-layout="true"');
expect(markup).toContain('data-maintain-scroll-at-end-layout="true"');
// LegendList's internal maintainScrollAtEnd stays off: it races post-mount
// measurement and snaps the view to stale content ends. End-following is
// owned by ChatView's live-follow, which respects user scroll gestures.
expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
expect(markup).toContain('data-user-message-collapsed="true"');
expect(markup).toContain('data-user-message-fade="true"');
expect(markup).toContain('data-user-message-footer="true"');
@@ -1,7 +1,6 @@
import {
type EnvironmentId,
type MessageId,
type OrchestrationV2Run,
type OrchestrationV2TurnItem,
type RunAttemptId,
type ScopedThreadRef,
@@ -109,7 +108,7 @@ import { type TimestampFormat } from "@t3tools/contracts/settings";
import { formatChatTimestampTooltip, formatShortTimestamp } from "../../timestampFormat";
import { V2ItemInspector } from "./V2ItemInspector";
import { useV2ItemSupport } from "../../state/v2ItemSupport";
import { isV2LifecycleItem, V2LifecycleRow } from "./V2LifecycleRow";
import { isV2LifecycleItem, V2LifecycleRow, type HandoffTimelineRun } from "./V2LifecycleRow";
import { TimelineSystemDivider } from "./TimelineSystemDivider";
import {
@@ -144,7 +143,7 @@ interface TimelineRowSharedState {
/** Provider snapshots for resolving handoff endpoints to icons + model names. */
providerStatuses: ReadonlyArray<ServerProvider>;
/** Projection runs, for recovering handoff models on legacy items. */
runs: ReadonlyArray<OrchestrationV2Run>;
runs: ReadonlyArray<HandoffTimelineRun>;
activeThreadEnvironmentId: EnvironmentId;
onRevertUserMessage: (messageId: MessageId) => void;
onImageExpand: (preview: ExpandedImagePreview) => void;
@@ -176,7 +175,7 @@ const TIMELINE_LIST_FADE_HEADER = <div className="h-10 sm:h-12" />;
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
const EMPTY_TIMELINE_PROVIDERS: ReadonlyArray<ServerProvider> = [];
const EMPTY_TIMELINE_RUNS: ReadonlyArray<OrchestrationV2Run> = [];
const EMPTY_TIMELINE_RUNS: ReadonlyArray<HandoffTimelineRun> = [];
// ---------------------------------------------------------------------------
// Props (public API)
@@ -216,7 +215,7 @@ interface MessagesTimelineProps {
workspaceRoot: string | undefined;
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
providerStatuses?: ReadonlyArray<ServerProvider>;
runs?: ReadonlyArray<OrchestrationV2Run>;
runs?: ReadonlyArray<HandoffTimelineRun>;
anchorMessageId: MessageId | null;
onAnchorReady: (messageId: MessageId, anchorIndex: number) => void;
onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
@@ -256,7 +255,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
workspaceRoot,
skills = EMPTY_TIMELINE_SKILLS,
providerStatuses = EMPTY_TIMELINE_PROVIDERS,
runs = EMPTY_TIMELINE_RUNS,
runs: runsProp = EMPTY_TIMELINE_RUNS,
anchorMessageId,
onAnchorReady,
onAnchorSizeChanged,
@@ -383,6 +382,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
],
);
const rows = useStableRows(rawRows);
// Run status/timestamps churn on every stream event; the shared row context
// must not change with them or every timeline row re-renders per event.
const runs = useStableHandoffRuns(runsProp);
const minimapItems = useMemo(() => deriveTimelineMinimapItems(rows), [rows]);
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
null,
@@ -581,18 +583,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({
initialScrollAtEnd
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={contentInsetEndAdjustment}
maintainScrollAtEnd={
anchoredEndSpace
? false
: {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}
}
// The app owns end-following (ChatView live-follow + scroll-to-end
// pill), which respects the user's scroll gestures. LegendList's
// internal maintainScrollAtEnd races post-mount measurement: it
// caches its at-end flag while a maintain cycle is active, so
// overlapping item-layout reconciliations keep snapping the view
// to stale content ends even after the user scrolled away.
maintainScrollAtEnd={false}
maintainVisibleContentPosition={maintainVisibleContentPosition}
onScroll={handleScroll}
className="messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]"
@@ -2134,6 +2131,38 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
// so LegendList (and React) can skip re-rendering unchanged items.
// ---------------------------------------------------------------------------
/** Content-stable projection of the runs the handoff rows read. The incoming
* array is rebuilt on every projection event (status/timestamp churn), but
* the returned reference only changes when a run's identity-relevant fields
* (id, ordinal, instance, model) do — keeping TimelineRowCtx stable. */
function useStableHandoffRuns(
runs: ReadonlyArray<HandoffTimelineRun>,
): ReadonlyArray<HandoffTimelineRun> {
const prev = useRef<{
signature: string;
value: ReadonlyArray<HandoffTimelineRun>;
}>({ signature: "", value: EMPTY_TIMELINE_RUNS });
return useMemo(() => {
const signature = runs
.map(
(run) =>
`${run.id}\0${run.providerInstanceId}\0${run.ordinal}\0${run.modelSelection.instanceId}\0${run.modelSelection.model}`,
)
.join("\n");
if (signature === prev.current.signature) {
return prev.current.value;
}
const value = runs.map((run) => ({
id: run.id,
ordinal: run.ordinal,
providerInstanceId: run.providerInstanceId,
modelSelection: run.modelSelection,
}));
prev.current = { signature, value };
return value;
}, [runs]);
}
/** Returns a structurally-shared copy of `rows`: for each row whose content
* hasn't changed since last call, the previous object reference is reused. */
function useStableRows(rows: MessagesTimelineRow[]): MessagesTimelineRow[] {
@@ -55,12 +55,22 @@ const TERMINAL_SUBAGENT_STATUSES = new Set<OrchestrationV2TurnItem["status"]>([
"interrupted",
]);
/**
* The subset of a projection run that handoff rows read. Kept minimal so the
* timeline can hold a content-stable snapshot: run status/timestamps churn on
* every stream event, but these fields only change when a run is added.
*/
export type HandoffTimelineRun = Pick<
OrchestrationV2Run,
"id" | "ordinal" | "providerInstanceId" | "modelSelection"
>;
export function V2LifecycleRow(props: {
readonly item: OrchestrationV2TurnItem;
readonly createdAt: string;
readonly timestampFormat: TimestampFormat;
readonly providerStatuses: ReadonlyArray<ServerProvider>;
readonly runs: ReadonlyArray<OrchestrationV2Run>;
readonly runs: ReadonlyArray<HandoffTimelineRun>;
readonly onOpenThread: (threadId: ThreadId) => void;
}) {
const { item } = props;
@@ -301,11 +311,11 @@ function subagentDisplayTitle(title: string): string {
* covered runs are still in the projection.
*/
function latestRunModelBefore(
runs: ReadonlyArray<OrchestrationV2Run>,
runs: ReadonlyArray<HandoffTimelineRun>,
instanceId: ProviderInstanceId,
beforeOrdinal: number | undefined,
): string | undefined {
let latest: OrchestrationV2Run | undefined;
let latest: HandoffTimelineRun | undefined;
for (const run of runs) {
if (run.providerInstanceId !== instanceId) continue;
if (beforeOrdinal !== undefined && run.ordinal >= beforeOrdinal) continue;