Skip to content

Commit 87be81e

Browse files
committed
fix(web): reliably follow latest thread content
1 parent 83d769f commit 87be81e

5 files changed

Lines changed: 334 additions & 38 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 93 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,14 @@ import {
9292
isLatestTurnSettled,
9393
} from "../session-logic";
9494
import { type LegendListRef } from "@legendapp/list/react";
95-
import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring";
95+
import {
96+
clearTimelineAnchor,
97+
getAnchoredTurnEndRevealOffset,
98+
resolveTimelineLiveFollowEnabled,
99+
resolveTimelineRouteEpoch,
100+
updateTimelineLiveFollowState,
101+
type TimelineScrollMode,
102+
} from "./chat/timelineScrollAnchoring";
96103
import {
97104
buildPendingUserInputAnswers,
98105
derivePendingUserInputProgress,
@@ -3584,12 +3591,33 @@ function ChatViewContent(props: ChatViewProps) {
35843591
const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");
35853592
// State mirror of the follow mode refs. LegendList's maintainScrollAtEnd
35863593
// re-pins on its own (independent of the refs), so the timeline needs a
3587-
// render-visible flag to switch it off once the user scrolls away.
3588-
const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true);
3594+
// render-visible flag to switch it off once the user scrolls away. Scope
3595+
// that flag to the route so a new thread follows on its very first render,
3596+
// before the route reset effect has a chance to commit.
3597+
const timelineRouteEpochRef = useRef({ threadKey: routeThreadKey });
3598+
timelineRouteEpochRef.current = resolveTimelineRouteEpoch(
3599+
timelineRouteEpochRef.current,
3600+
routeThreadKey,
3601+
);
3602+
const timelineRouteEpoch = timelineRouteEpochRef.current;
3603+
const [timelineLiveFollowState, setTimelineLiveFollowState] = useState(() => ({
3604+
threadKey: routeThreadKey,
3605+
enabled: true,
3606+
}));
3607+
const timelineLiveFollowEnabled = resolveTimelineLiveFollowEnabled(
3608+
timelineLiveFollowState,
3609+
routeThreadKey,
3610+
);
3611+
const setTimelineLiveFollowEnabled = useCallback((enabled: boolean) => {
3612+
setTimelineLiveFollowState((current) =>
3613+
updateTimelineLiveFollowState(current, timelineRouteEpochRef.current.threadKey, enabled),
3614+
);
3615+
}, []);
35893616
const pendingTimelineAnchorRef = useRef<MessageId | null>(null);
35903617
const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
35913618
const settledTimelineAnchorRef = useRef<MessageId | null>(null);
35923619
const activeTimelineAnchorIndexRef = useRef<number | null>(null);
3620+
const timelineItemSizeFollowFrameRef = useRef<number | null>(null);
35933621
const anchorUserScrollGenerationRef = useRef(0);
35943622
const liveFollowUserScrollGenerationRef = useRef<number | null>(0);
35953623
// Manual navigation stops live-follow without removing anchored end space.
@@ -3611,7 +3639,7 @@ function ChatViewContent(props: ChatViewProps) {
36113639
cancelTimelineLiveFollowForUserNavigationRef.current =
36123640
cancelTimelineLiveFollowForUserNavigation;
36133641
}, [cancelTimelineLiveFollowForUserNavigation]);
3614-
const getActiveTimelineTurnMetrics = useCallback(
3642+
const getActiveTimelineTurnRevealOffset = useCallback(
36153643
(list?: LegendListRef | null) => {
36163644
const resolvedList = list ?? legendListRef.current;
36173645
const anchorIndex = activeTimelineAnchorIndexRef.current;
@@ -3620,7 +3648,7 @@ function ChatViewContent(props: ChatViewProps) {
36203648
return null;
36213649
}
36223650

3623-
return getAnchoredTurnMetrics({
3651+
return getAnchoredTurnEndRevealOffset({
36243652
state,
36253653
anchorIndex,
36263654
composerOverlayHeight,
@@ -3658,6 +3686,54 @@ function ChatViewContent(props: ChatViewProps) {
36583686
},
36593687
[composerOverlayHeight],
36603688
);
3689+
const revealActiveTimelineTurnEnd = useCallback(() => {
3690+
if (timelineRouteEpochRef.current !== timelineRouteEpoch) {
3691+
return;
3692+
}
3693+
if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {
3694+
return;
3695+
}
3696+
if (timelineScrollModeRef.current !== "anchoring-new-turn") {
3697+
return;
3698+
}
3699+
if (pendingTimelineAnchorRef.current !== null) {
3700+
return;
3701+
}
3702+
if (
3703+
positionedTimelineAnchorRef.current !== null &&
3704+
settledTimelineAnchorRef.current !== positionedTimelineAnchorRef.current
3705+
) {
3706+
return;
3707+
}
3708+
3709+
const list = legendListRef.current;
3710+
if (!list) {
3711+
return;
3712+
}
3713+
const nextOffset = getActiveTimelineTurnRevealOffset(list);
3714+
if (nextOffset === null) {
3715+
return;
3716+
}
3717+
void list.scrollToOffset({ offset: nextOffset, animated: false });
3718+
}, [getActiveTimelineTurnRevealOffset, timelineRouteEpoch]);
3719+
const onTimelineItemSizeChanged = useCallback(() => {
3720+
if (timelineItemSizeFollowFrameRef.current !== null) {
3721+
return;
3722+
}
3723+
timelineItemSizeFollowFrameRef.current = requestAnimationFrame(() => {
3724+
timelineItemSizeFollowFrameRef.current = null;
3725+
revealActiveTimelineTurnEnd();
3726+
});
3727+
}, [revealActiveTimelineTurnEnd]);
3728+
useEffect(
3729+
() => () => {
3730+
if (timelineItemSizeFollowFrameRef.current !== null) {
3731+
cancelAnimationFrame(timelineItemSizeFollowFrameRef.current);
3732+
timelineItemSizeFollowFrameRef.current = null;
3733+
}
3734+
},
3735+
[routeThreadKey],
3736+
);
36613737
// Live-follow stays active after send/thread-open until an actual list scroll
36623738
// gesture opts out.
36633739
const scrollToEnd = useCallback((animated = false) => {
@@ -3669,9 +3745,7 @@ function ChatViewContent(props: ChatViewProps) {
36693745
activeTimelineAnchorIndexRef.current = null;
36703746
showScrollDebouncer.current.cancel();
36713747
setShowScrollToBottom(false);
3672-
setTimelineAnchor((current) =>
3673-
current.messageId === null ? current : { ...current, messageId: null },
3674-
);
3748+
setTimelineAnchor(clearTimelineAnchor);
36753749
requestAnimationFrame(() => {
36763750
void legendListRef.current?.scrollToEnd?.({ animated });
36773751
});
@@ -3783,7 +3857,7 @@ function ChatViewContent(props: ChatViewProps) {
37833857
}
37843858
removeListeners?.();
37853859
};
3786-
}, [activeThread?.id, composerOverlayHeight, timelineRealContentOverflowsViewport]);
3860+
}, [composerOverlayHeight, routeThreadKey, timelineRealContentOverflowsViewport]);
37873861

37883862
const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {
37893863
// Anchored-end space can be remeasured when the turn completes. Once the
@@ -3846,6 +3920,11 @@ function ChatViewContent(props: ChatViewProps) {
38463920
timelineScrollModeRef.current = "following-end";
38473921
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
38483922
setTimelineLiveFollowEnabled(true);
3923+
pendingTimelineAnchorRef.current = null;
3924+
positionedTimelineAnchorRef.current = null;
3925+
settledTimelineAnchorRef.current = null;
3926+
activeTimelineAnchorIndexRef.current = null;
3927+
setTimelineAnchor(clearTimelineAnchor);
38493928
showScrollDebouncer.current.cancel();
38503929
setShowScrollToBottom(false);
38513930
} else {
@@ -3872,30 +3951,7 @@ function ChatViewContent(props: ChatViewProps) {
38723951
let secondFrame: number | null = null;
38733952
const frame = requestAnimationFrame(() => {
38743953
secondFrame = requestAnimationFrame(() => {
3875-
if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {
3876-
return;
3877-
}
3878-
if (pendingTimelineAnchorRef.current !== null) {
3879-
return;
3880-
}
3881-
if (
3882-
positionedTimelineAnchorRef.current !== null &&
3883-
settledTimelineAnchorRef.current !== positionedTimelineAnchorRef.current
3884-
) {
3885-
return;
3886-
}
3887-
const list = legendListRef.current;
3888-
if (!list) {
3889-
return;
3890-
}
3891-
3892-
const metrics = getActiveTimelineTurnMetrics(list);
3893-
if (!metrics || metrics.scrollDeltaToRevealEnd <= 1) {
3894-
return;
3895-
}
3896-
3897-
const nextOffset = list.getState().scroll + metrics.scrollDeltaToRevealEnd;
3898-
void list.scrollToOffset({ offset: nextOffset, animated: false });
3954+
revealActiveTimelineTurnEnd();
38993955
});
39003956
});
39013957

@@ -3905,7 +3961,7 @@ function ChatViewContent(props: ChatViewProps) {
39053961
cancelAnimationFrame(secondFrame);
39063962
}
39073963
};
3908-
}, [activeThread?.id, timelineEntries, getActiveTimelineTurnMetrics]);
3964+
}, [routeThreadKey, timelineEntries, revealActiveTimelineTurnEnd]);
39093965

39103966
useEffect(() => {
39113967
setPullRequestDialogState(null);
@@ -3920,7 +3976,7 @@ function ChatViewContent(props: ChatViewProps) {
39203976
showScrollDebouncer.current.cancel();
39213977
setShowScrollToBottom(false);
39223978
// activeThreadRef resets transitively with the active thread.
3923-
}, [activeThread?.id]);
3979+
}, [routeThreadKey]);
39243980

39253981
useEffect(() => {
39263982
setIsRevertingCheckpoint(false);
@@ -6087,7 +6143,7 @@ function ChatViewContent(props: ChatViewProps) {
60876143
<MessagesTimeline
60886144
agentPanelModel={agentPanelModel}
60896145
onOpenAgents={addAgentsSurface}
6090-
key={activeThread.id}
6146+
key={routeThreadKey}
60916147
isWorking={isWorking}
60926148
workingStepLabel={workingStepLabel}
60936149
activeTurnInProgress={isWorking || !latestTurnSettled}
@@ -6118,6 +6174,7 @@ function ChatViewContent(props: ChatViewProps) {
61186174
contentInsetEndAdjustment={composerOverlayHeight}
61196175
liveFollowEnabled={timelineLiveFollowEnabled}
61206176
onIsAtEndChange={onIsAtEndChange}
6177+
onItemSizeChanged={onTimelineItemSizeChanged}
61216178
onManualNavigation={cancelTimelineLiveFollowForUserNavigation}
61226179
hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}
61236180
topFadeEnabled={!hasTimelineTopBanner}

‎apps/web/src/components/chat/MessagesTimeline.test.tsx‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { createRef, type ReactNode, type Ref } from "react";
33
import { renderToStaticMarkup } from "react-dom/server";
44
import { beforeAll, describe, expect, it, vi } from "vite-plus/test";
55
import type { LegendListRef } from "@legendapp/list/react";
6+
import { resolveTimelineLiveFollowEnabled } from "./timelineScrollAnchoring";
67

78
vi.mock("@legendapp/list/react", async () => {
89
const legendListTestId = "legend-list";
@@ -38,11 +39,28 @@ vi.mock("@legendapp/list/react", async () => {
3839
size?: boolean;
3940
shouldRestorePosition?: (item: { id: string }) => boolean;
4041
};
42+
onItemSizeChanged?: (info: {
43+
index: number;
44+
itemData: { id: string };
45+
itemKey: string;
46+
previous: number;
47+
size: number;
48+
}) => void;
4149
ref?: Ref<LegendListRef>;
4250
}) => {
4351
if (props.anchoredEndSpace) {
4452
props.anchoredEndSpace.onReady?.({ anchorIndex: props.anchoredEndSpace.anchorIndex });
4553
}
54+
const lastItem = props.data.at(-1);
55+
if (lastItem) {
56+
props.onItemSizeChanged?.({
57+
index: props.data.length - 1,
58+
itemData: lastItem,
59+
itemKey: props.keyExtractor(lastItem),
60+
previous: 90,
61+
size: 1_800,
62+
});
63+
}
4664
return (
4765
<div
4866
data-testid={legendListTestId}
@@ -195,6 +213,7 @@ function buildProps() {
195213
workspaceRoot: undefined,
196214
anchorMessageId: null,
197215
onAnchorReady: () => {},
216+
onItemSizeChanged: () => {},
198217
contentInsetEndAdjustment: 0,
199218
liveFollowEnabled: true,
200219
onIsAtEndChange: () => {},
@@ -225,6 +244,23 @@ function buildUserTimelineEntry(text: string) {
225244
};
226245
}
227246

247+
function buildStreamingAssistantTimelineEntry() {
248+
return {
249+
id: "entry-streaming-assistant",
250+
kind: "message" as const,
251+
createdAt: MESSAGE_CREATED_AT,
252+
message: {
253+
id: MessageId.make("message-streaming-assistant"),
254+
role: "assistant" as const,
255+
text: "Streaming response content.",
256+
turnId: TurnId.make("turn-streaming"),
257+
createdAt: MESSAGE_CREATED_AT,
258+
updatedAt: MESSAGE_CREATED_AT,
259+
streaming: true,
260+
},
261+
};
262+
}
263+
228264
describe("MessagesTimeline", () => {
229265
it("uses the larger leading inset only when the top fade is enabled", () => {
230266
const timelineEntries = [buildUserTimelineEntry("Hello")];
@@ -432,6 +468,65 @@ describe("MessagesTimeline", () => {
432468
expect(onAnchorReady).toHaveBeenCalledWith(secondEntry.message.id, 1);
433469
});
434470

471+
it("keeps streamed content following after switching from a thread scrolled into history", () => {
472+
const previousThreadState = {
473+
threadKey: "environment-local:thread-a",
474+
enabled: false,
475+
};
476+
const nextThreadKey = "environment-local:thread-b";
477+
const markup = renderToStaticMarkup(
478+
<MessagesTimeline
479+
{...buildProps()}
480+
routeThreadKey={nextThreadKey}
481+
liveFollowEnabled={resolveTimelineLiveFollowEnabled(previousThreadState, nextThreadKey)}
482+
timelineEntries={[buildStreamingAssistantTimelineEntry()]}
483+
/>,
484+
);
485+
486+
expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
487+
expect(markup).toContain('data-maintain-scroll-at-end-data-change="true"');
488+
expect(markup).toContain('data-maintain-scroll-at-end-item-layout="true"');
489+
expect(markup).toContain('data-maintain-scroll-at-end-layout="true"');
490+
});
491+
492+
it("reports late row measurements so a buffered completion can settle at the live edge", () => {
493+
const onItemSizeChanged = vi.fn();
494+
const userEntry = buildUserTimelineEntry("Generate a response longer than the viewport.");
495+
496+
renderToStaticMarkup(
497+
<MessagesTimeline
498+
{...buildProps()}
499+
anchorMessageId={userEntry.message.id}
500+
onItemSizeChanged={onItemSizeChanged}
501+
timelineEntries={[userEntry, buildStreamingAssistantTimelineEntry()]}
502+
/>,
503+
);
504+
505+
expect(onItemSizeChanged).toHaveBeenCalledWith(
506+
expect.objectContaining({ previous: 90, size: 1_800 }),
507+
);
508+
});
509+
510+
it("disables streamed-content follow while reading history and restores it at the live edge", () => {
511+
const timelineEntries = [buildStreamingAssistantTimelineEntry()];
512+
const readingMarkup = renderToStaticMarkup(
513+
<MessagesTimeline
514+
{...buildProps()}
515+
liveFollowEnabled={false}
516+
timelineEntries={timelineEntries}
517+
/>,
518+
);
519+
const followingMarkup = renderToStaticMarkup(
520+
<MessagesTimeline {...buildProps()} liveFollowEnabled timelineEntries={timelineEntries} />,
521+
);
522+
523+
expect(readingMarkup).not.toContain('data-maintain-scroll-at-end="enabled"');
524+
expect(followingMarkup).toContain('data-maintain-scroll-at-end="enabled"');
525+
expect(followingMarkup).toContain('data-maintain-scroll-at-end-data-change="true"');
526+
expect(followingMarkup).toContain('data-maintain-scroll-at-end-item-layout="true"');
527+
expect(followingMarkup).toContain('data-maintain-scroll-at-end-layout="true"');
528+
});
529+
435530
it("renders collapse controls for long user messages", () => {
436531
const markup = renderToStaticMarkup(
437532
<MessagesTimeline

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,8 @@ interface MessagesTimelineProps {
236236
*/
237237
liveFollowEnabled: boolean;
238238
onIsAtEndChange: (isAtEnd: boolean) => void;
239+
/** Reports authoritative row height changes so anchored follow can settle after late layout. */
240+
onItemSizeChanged: () => void;
239241
onManualNavigation: () => void;
240242
hideEmptyPlaceholder?: boolean;
241243
topFadeEnabled?: boolean;
@@ -276,6 +278,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
276278
contentInsetEndAdjustment,
277279
liveFollowEnabled,
278280
onIsAtEndChange,
281+
onItemSizeChanged,
279282
onManualNavigation,
280283
hideEmptyPlaceholder = false,
281284
topFadeEnabled = false,
@@ -588,6 +591,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
588591
: TIMELINE_MAINTAIN_SCROLL_AT_END
589592
}
590593
maintainVisibleContentPosition={maintainVisibleContentPosition}
594+
onItemSizeChanged={onItemSizeChanged}
591595
onScroll={handleScroll}
592596
className={cn(
593597
"scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5",

0 commit comments

Comments
 (0)