Skip to content

Commit 1430201

Browse files
committed
fix(web): keep one thread restore running while rows stream in
The restore effect depended on `rows`, so every streamed row restarted it and reset its frame cap. Returning to a streaming thread snapped to the end on each chunk and kept scroll tracking off until the stream paused. The effect now depends on whether rows exist and on the saved row's index. A gesture during a restore to the end now only stops the restore. ChatView's own listeners decide whether it leaves the end, so wheeling down or clicking at the bottom no longer switches following off for good. When the frame cap runs out on a restore to the end, the list jumps to the current end first, so end maintenance (which re-pins only within a viewport of the end) can take over. The thread-switch effect sets the follow flag again, and the render-phase reset starts from the mounted thread instead of an extra render.
1 parent e863233 commit 1430201

3 files changed

Lines changed: 125 additions & 47 deletions

File tree

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5301,11 +5301,13 @@ export default function ChatView(props: ChatViewProps) {
53015301
// State mirror of the follow mode refs. LegendList's maintainScrollAtEnd
53025302
// re-pins on its own (independent of the refs), so the timeline needs a
53035303
// render-visible flag to switch it off once the user scrolls away.
5304-
const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true);
5304+
const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(
5305+
() => readTimelinePosition(routeThreadKey)?.atEnd !== false,
5306+
);
53055307
// Reset during the switching render, not in an effect: the timeline
53065308
// measures the new thread's rows in its first commit, and a flag left over
53075309
// from the previous thread would switch end maintenance off for them.
5308-
const [liveFollowThreadKey, setLiveFollowThreadKey] = useState<string | null>(null);
5310+
const [liveFollowThreadKey, setLiveFollowThreadKey] = useState(routeThreadKey);
53095311
if (liveFollowThreadKey !== routeThreadKey) {
53105312
setLiveFollowThreadKey(routeThreadKey);
53115313
setTimelineLiveFollowEnabled(readTimelinePosition(routeThreadKey)?.atEnd !== false);
@@ -5738,6 +5740,7 @@ export default function ChatView(props: ChatViewProps) {
57385740
liveFollowUserScrollGenerationRef.current = followEnd
57395741
? anchorUserScrollGenerationRef.current
57405742
: null;
5743+
setTimelineLiveFollowEnabled(followEnd);
57415744
pendingTimelineAnchorRef.current = null;
57425745
positionedTimelineAnchorRef.current = null;
57435746
settledTimelineAnchorRef.current = null;

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

Lines changed: 88 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -968,38 +968,48 @@ describe("MessagesTimeline", () => {
968968
frames.clear();
969969
callbacks.forEach((callback) => callback(0));
970970
});
971-
const entries = [
972-
{
973-
id: "entry-restore-work",
974-
kind: "work" as const,
971+
const workEntry = (index: number) => ({
972+
id: `entry-restore-work-${index}`,
973+
kind: "work" as const,
974+
createdAt: MESSAGE_CREATED_AT,
975+
entry: {
976+
id: `work-restore-${index}`,
975977
createdAt: MESSAGE_CREATED_AT,
976-
entry: {
977-
id: "work-restore",
978-
createdAt: MESSAGE_CREATED_AT,
979-
toolCallId: "call-restore",
980-
label: "Run lint",
981-
tone: "tool" as const,
982-
itemType: "command_execution" as const,
983-
command: "pnpm lint",
984-
toolLifecycleStatus: "completed" as const,
985-
},
978+
toolCallId: `call-restore-${index}`,
979+
label: "Run lint",
980+
tone: "tool" as const,
981+
itemType: "command_execution" as const,
982+
command: "pnpm lint",
983+
toolLifecycleStatus: "completed" as const,
986984
},
987-
];
985+
});
986+
let entries = [workEntry(0)];
988987
const noop = () => {};
988+
const listeners = new Map<string, () => void>();
989989
const viewport = {
990990
scrollTop: 0,
991991
scrollHeight: 2000,
992992
clientHeight: 800,
993993
getBoundingClientRect: () => ({ top: 0 }),
994-
addEventListener: noop,
995-
removeEventListener: noop,
994+
addEventListener: (type: string, listener: () => void) => listeners.set(type, listener),
995+
removeEventListener: (type: string) => listeners.delete(type),
996996
ownerDocument: { addEventListener: noop, removeEventListener: noop },
997997
};
998-
const harness = { viewport, rowMounted: true, atEndCalls: [] as boolean[], flushFrame };
998+
const harness = {
999+
viewport,
1000+
listeners,
1001+
rowMounted: true,
1002+
atEndCalls: [] as boolean[],
1003+
manualNavigations: 0,
1004+
flushFrame,
1005+
};
9991006
const props = {
10001007
...buildProps(),
10011008
routeThreadKey: "env-restore:thread-0",
10021009
onIsAtEndChange: (isAtEnd: boolean) => harness.atEndCalls.push(isAtEnd),
1010+
onManualNavigation: () => {
1011+
harness.manualNavigations += 1;
1012+
},
10031013
};
10041014
const scrollTo = (offset: number) => {
10051015
viewport.scrollTop = offset;
@@ -1013,11 +1023,15 @@ describe("MessagesTimeline", () => {
10131023
scrollLength: viewport.clientHeight,
10141024
positionAtIndex: () => 0,
10151025
indexByKey: () => 0,
1026+
// The saved row starts 100px down the content.
10161027
elementAtIndex: () =>
1017-
harness.rowMounted ? { getBoundingClientRect: () => ({ top: 0 }) } : null,
1028+
harness.rowMounted
1029+
? { getBoundingClientRect: () => ({ top: 100 - viewport.scrollTop }) }
1030+
: null,
10181031
}),
10191032
getScrollableNode: () => viewport,
1020-
scrollToEnd: () => scrollTo(viewport.scrollHeight - viewport.clientHeight),
1033+
// Jumps to the end as estimated before rows measure, which lands short.
1034+
scrollToEnd: () => scrollTo(300),
10211035
scrollToIndex: () => Promise.resolve(),
10221036
scrollToOffset: ({ offset }: { offset: number }) => scrollTo(offset),
10231037
} as unknown as LegendListRef;
@@ -1031,19 +1045,27 @@ describe("MessagesTimeline", () => {
10311045
scrollOffset: 0,
10321046
atEnd,
10331047
});
1048+
const renderThread1 = () =>
1049+
act(async () => {
1050+
renderer.update(
1051+
<MessagesTimeline
1052+
{...props}
1053+
routeThreadKey="env-restore:thread-1"
1054+
timelineEntries={entries}
1055+
/>,
1056+
);
1057+
});
10341058
return {
10351059
harness,
10361060
async switchThread() {
1037-
await act(async () => {
1038-
renderer.update(
1039-
<MessagesTimeline
1040-
{...props}
1041-
routeThreadKey="env-restore:thread-1"
1042-
timelineEntries={entries}
1043-
/>,
1044-
);
1045-
});
1061+
await renderThread1();
10461062
harness.atEndCalls.length = 0;
1063+
harness.manualNavigations = 0;
1064+
},
1065+
async streamRow() {
1066+
entries = [...entries, workEntry(entries.length)];
1067+
viewport.scrollHeight += 100;
1068+
await renderThread1();
10471069
},
10481070
cleanup() {
10491071
act(() => renderer.unmount());
@@ -1061,6 +1083,7 @@ describe("MessagesTimeline", () => {
10611083
harness.rowMounted = true;
10621084
for (let frame = 0; frame < 4; frame += 1) await harness.flushFrame();
10631085

1086+
expect(harness.viewport.scrollTop).toBe(100);
10641087
// Restore finished, so scroll reporting (and with it the pill) resumed.
10651088
expect(harness.atEndCalls).toContain(false);
10661089
} finally {
@@ -1072,7 +1095,7 @@ describe("MessagesTimeline", () => {
10721095
const { harness, switchThread, cleanup } = await switchToRememberedThread(true);
10731096
try {
10741097
await switchThread();
1075-
expect(harness.viewport.scrollTop).toBe(1200);
1098+
expect(harness.viewport.scrollTop).toBe(300);
10761099
// Estimated rows measure taller after the first jump to the end.
10771100
harness.viewport.scrollHeight = 5000;
10781101
for (let frame = 0; frame < 6; frame += 1) await harness.flushFrame();
@@ -1084,6 +1107,41 @@ describe("MessagesTimeline", () => {
10841107
}
10851108
});
10861109

1110+
it("hands a thread that streams through its restore to end maintenance at the end", async () => {
1111+
const { harness, switchThread, streamRow, cleanup } = await switchToRememberedThread(true);
1112+
try {
1113+
await switchThread();
1114+
// A row streams in every frame, so the restore never sees two stable frames.
1115+
for (let frame = 0; frame < 40 && harness.atEndCalls.length === 0; frame += 1) {
1116+
await streamRow();
1117+
await harness.flushFrame();
1118+
}
1119+
1120+
// Restore finished, so scroll reporting resumed, after handing over from
1121+
// the end. This double has no end maintenance, so only the one row that
1122+
// streamed after the hand-over jump sits below.
1123+
expect(harness.atEndCalls.length).toBeGreaterThan(0);
1124+
const { scrollTop, scrollHeight, clientHeight } = harness.viewport;
1125+
expect(scrollHeight - clientHeight - scrollTop).toBe(100);
1126+
} finally {
1127+
cleanup();
1128+
}
1129+
});
1130+
1131+
it("keeps following when a gesture interrupts a restore to the end", async () => {
1132+
const { harness, switchThread, cleanup } = await switchToRememberedThread(true);
1133+
try {
1134+
await switchThread();
1135+
act(() => harness.listeners.get("wheel")?.());
1136+
1137+
// ChatView's own listeners decide whether the gesture leaves the end.
1138+
expect(harness.manualNavigations).toBe(0);
1139+
expect(harness.listeners.has("wheel")).toBe(false);
1140+
} finally {
1141+
cleanup();
1142+
}
1143+
});
1144+
10871145
it("snaps to the end while a thread switch settles, even mid-turn", async () => {
10881146
const frames = new Map<number, FrameRequestCallback>();
10891147
let nextFrame = 0;

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

Lines changed: 32 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,10 @@ function TimelineListFooter({ composerInset }: { readonly composerInset: number
370370
);
371371
}
372372
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
373+
// About half a second at 60 Hz. A thread still growing after this many frames
374+
// is handed to end maintenance instead of staying in restore with scroll
375+
// tracking off.
376+
const THREAD_RESTORE_MAX_FRAMES = 30;
373377
const TIMELINE_MAINTAIN_SCROLL_AT_END = {
374378
animated: false,
375379
on: {
@@ -820,8 +824,12 @@ export const MessagesTimeline = memo(function MessagesTimeline({
820824
restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined,
821825
[restoreRowIndex, restoringThreadPosition],
822826
);
827+
// Rows stream in while a thread is restoring. The restore depends on
828+
// whether any exist and where the saved row sits, not on each new row, so a
829+
// streaming thread keeps one restore instead of restarting it every chunk.
830+
const hasRows = rows.length > 0;
823831
useLayoutEffect(() => {
824-
if (!restoringThreadPosition || rows.length === 0) return;
832+
if (!restoringThreadPosition || !hasRows) return;
825833
const list = listRef.current;
826834
if (!list) return;
827835
if (citationRequest !== null) {
@@ -839,9 +847,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({
839847
if (viewport) void list.scrollToOffset({ offset: viewport.scrollTop, animated: false });
840848
setPositionedThreadKey(listIdentityKey);
841849
};
850+
const position = rememberedPosition;
851+
// A restore to the end only stops correcting on a gesture. ChatView's own
852+
// listeners decide whether that gesture leaves the end, so a wheel down
853+
// or a click at the bottom keeps following.
842854
const cancelForNavigation = () => {
843855
cancelRestoration();
844-
onManualNavigation();
856+
if (position?.atEnd === false) onManualNavigation();
845857
};
846858
const onScrollKey = (event: globalThis.KeyboardEvent) => {
847859
if (
@@ -857,15 +869,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({
857869
viewport?.addEventListener("touchmove", cancelForNavigation, { passive: true });
858870
viewport?.addEventListener("pointerdown", cancelForNavigation, { passive: true });
859871
viewport?.ownerDocument.addEventListener("keydown", onScrollKey);
860-
const position = rememberedPosition;
861-
const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;
862872
if (position?.atEnd === false) onManualNavigation();
863873
if (cancelPositionRestoreRef) cancelPositionRestoreRef.current = cancelRestoration;
864874
const scrolling =
865875
position?.atEnd === false
866-
? index >= 0
876+
? restoreRowIndex >= 0
867877
? list.scrollToIndex({
868-
index,
878+
index: restoreRowIndex,
869879
animated: false,
870880
viewPosition: 0,
871881
viewOffset: -position.offsetWithinRow,
@@ -874,28 +884,34 @@ export const MessagesTimeline = memo(function MessagesTimeline({
874884
: list.scrollToEnd({ animated: false });
875885
void Promise.resolve(scrolling).then(() => {
876886
if (cancelled) return;
877-
const savedRow = position?.atEnd === false && index >= 0 ? position : null;
878-
if (position?.atEnd === false && !savedRow) {
887+
if (position?.atEnd === false && restoreRowIndex < 0) {
879888
setPositionedThreadKey(listIdentityKey);
880889
return;
881890
}
891+
const savedRow = position?.atEnd === false ? position : null;
882892
// Scrolling starts from estimated row sizes, so the first jump lands
883-
// short once real rows measure. Keep the target (the saved row, or the
884-
// end) mounted and corrected until it and the DOM agree for two layout
885-
// frames. The frame cap hands a still-growing thread to end
886-
// maintenance instead of leaving it restoring with scroll tracking off.
893+
// short once real rows measure. Keep correcting toward the target (the
894+
// saved row, or the end) until it and the DOM agree for two frames.
887895
let stableFrames = 0;
888896
let frames = 0;
889897
const reconcile = () => {
890898
if (cancelled) return;
891-
if (++frames > 30) {
899+
const element = list.getScrollableNode();
900+
if (++frames > THREAD_RESTORE_MAX_FRAMES) {
901+
// End maintenance only re-pins within a viewport of the end, so
902+
// hand over from the current end rather than wherever this stopped.
903+
if (!savedRow && element) {
904+
void list.scrollToOffset({
905+
offset: Math.max(0, element.scrollHeight - element.clientHeight),
906+
animated: false,
907+
});
908+
}
892909
setPositionedThreadKey(listIdentityKey);
893910
return;
894911
}
895912
const state = list.getState();
896913
const rowIndex = savedRow ? state.indexByKey(savedRow.rowId) : undefined;
897914
const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);
898-
const element = list.getScrollableNode();
899915
// The saved row can mount a frame after the estimated scroll.
900916
if (!element || (savedRow && !row)) {
901917
settleFrame = requestAnimationFrame(reconcile);
@@ -947,9 +963,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
947963
listIdentityKey,
948964
listRef,
949965
onManualNavigation,
966+
hasRows,
950967
rememberedPosition,
968+
restoreRowIndex,
951969
restoringThreadPosition,
952-
rows,
953970
]);
954971

955972
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(

0 commit comments

Comments
 (0)