Skip to content

Commit a4f9820

Browse files
fix(web): keep the message list mounted across thread jumps
Remounting MessagesTimeline on every cmd+1/2/3 switch blanked LegendList for a frame, even when the destination was already cached. Remember the last painted timeline per thread and swap list data in place so spam jumps do not flash white. Co-authored-by: Julius Marminge <[email protected]>
1 parent 49a0c15 commit a4f9820

4 files changed

Lines changed: 154 additions & 36 deletions

File tree

‎apps/web/src/components/ChatView.logic.test.ts‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ import {
6060
threadShellHasStarted,
6161
resolveDraftHeroState,
6262
peekHeldThreadTimeline,
63+
peekRememberedThreadTimeline,
6364
rememberReadyThreadTimeline,
6465
resetHeldThreadTimeline,
6566
resolveThreadSwitchTimeline,
@@ -582,7 +583,7 @@ describe("resolveThreadSwitchTimeline", () => {
582583
loading: true,
583584
activeThreadKey: "thread-b",
584585
nextEntries: [],
585-
held,
586+
lastReady: held,
586587
}),
587588
).toEqual({ entries: ["a1", "a2"], displayThreadKey: "thread-a" });
588589
});
@@ -593,7 +594,7 @@ describe("resolveThreadSwitchTimeline", () => {
593594
loading: false,
594595
activeThreadKey: "thread-b",
595596
nextEntries: ["b1"],
596-
held,
597+
lastReady: held,
597598
}),
598599
).toEqual({ entries: ["b1"], displayThreadKey: "thread-b" });
599600
});
@@ -604,7 +605,7 @@ describe("resolveThreadSwitchTimeline", () => {
604605
loading: true,
605606
activeThreadKey: "thread-a",
606607
nextEntries: [],
607-
held: null,
608+
lastReady: null,
608609
}),
609610
).toEqual({ entries: [], displayThreadKey: "thread-a" });
610611
});
@@ -617,10 +618,33 @@ describe("resolveThreadSwitchTimeline", () => {
617618
loading: true,
618619
activeThreadKey: "thread-b",
619620
nextEntries: [],
620-
held: peekHeldThreadTimeline<string[]>(),
621621
}),
622622
).toEqual({ entries: ["a1", "a2"], displayThreadKey: "thread-a" });
623623
});
624+
625+
it("paints a remembered destination instead of the last-viewed thread", () => {
626+
rememberReadyThreadTimeline(held);
627+
rememberReadyThreadTimeline({ threadKey: "thread-b", entries: ["b1", "b2"] });
628+
expect(peekRememberedThreadTimeline<string[]>("thread-a")).toEqual(["a1", "a2"]);
629+
expect(
630+
resolveThreadSwitchTimeline({
631+
loading: true,
632+
activeThreadKey: "thread-a",
633+
nextEntries: [],
634+
}),
635+
).toEqual({ entries: ["a1", "a2"], displayThreadKey: "thread-a" });
636+
});
637+
638+
it("prefers live entries over a remembered snapshot", () => {
639+
rememberReadyThreadTimeline({ threadKey: "thread-b", entries: ["stale-b"] });
640+
expect(
641+
resolveThreadSwitchTimeline({
642+
loading: false,
643+
activeThreadKey: "thread-b",
644+
nextEntries: ["fresh-b"],
645+
}),
646+
).toEqual({ entries: ["fresh-b"], displayThreadKey: "thread-b" });
647+
});
624648
});
625649

626650
describe("shouldReleaseTimelineAnchorForToolActivity", () => {

‎apps/web/src/components/ChatView.logic.ts‎

Lines changed: 68 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -263,51 +263,105 @@ export function resolveDraftHeroState(input: {
263263
}
264264

265265
/**
266-
* Keep the last ready timeline on screen while the next thread's detail is
267-
* still loading. Remounting to an empty list punches a hole through the chat
268-
* pane (white in light mode, blank in dark) for the whole snapshot wait.
266+
* Keep painted timelines on screen across thread jumps. Remounting LegendList
267+
* (or handing it an empty first paint) punches a hole through the chat pane —
268+
* white in light mode — so cmd+1/2/3 spam flashes even when the destination
269+
* is already cached.
269270
*
270271
* Stored at module scope because ChatView remounts when the thread route
271272
* changes (same pattern as the thread-error banner session dismissals).
273+
* Remember more than the last thread so jumping back to cmd+1 does not show
274+
* cmd+3's messages, and so a cached destination can paint on the first frame.
272275
*/
273276
export type HeldThreadTimeline<T extends readonly unknown[]> = {
274277
threadKey: string | null;
275278
entries: T;
276279
};
277280

278-
let heldThreadTimeline: HeldThreadTimeline<readonly unknown[]> | null = null;
281+
const MAX_REMEMBERED_THREAD_TIMELINES = 16;
282+
283+
let rememberedThreadTimelines = new Map<string, readonly unknown[]>();
284+
let rememberedThreadTimelineOrder: string[] = [];
285+
let lastReadyThreadKey: string | null = null;
286+
287+
function rememberThreadTimelineEntries(threadKey: string, entries: readonly unknown[]): void {
288+
rememberedThreadTimelines.set(threadKey, entries);
289+
rememberedThreadTimelineOrder = [
290+
...rememberedThreadTimelineOrder.filter((key) => key !== threadKey),
291+
threadKey,
292+
];
293+
while (rememberedThreadTimelineOrder.length > MAX_REMEMBERED_THREAD_TIMELINES) {
294+
const evicted = rememberedThreadTimelineOrder.shift();
295+
if (evicted !== undefined) {
296+
rememberedThreadTimelines.delete(evicted);
297+
}
298+
}
299+
lastReadyThreadKey = threadKey;
300+
}
279301

280302
export function rememberReadyThreadTimeline<T extends readonly unknown[]>(
281303
held: HeldThreadTimeline<T>,
282304
): void {
283-
heldThreadTimeline = held;
305+
if (held.threadKey === null || held.entries.length === 0) {
306+
return;
307+
}
308+
rememberThreadTimelineEntries(held.threadKey, held.entries);
309+
}
310+
311+
export function peekRememberedThreadTimeline<T extends readonly unknown[]>(
312+
threadKey: string | null,
313+
): T | null {
314+
if (threadKey === null) {
315+
return null;
316+
}
317+
return (rememberedThreadTimelines.get(threadKey) as T | undefined) ?? null;
284318
}
285319

286320
export function peekHeldThreadTimeline<
287321
T extends readonly unknown[],
288322
>(): HeldThreadTimeline<T> | null {
289-
return heldThreadTimeline as HeldThreadTimeline<T> | null;
323+
if (lastReadyThreadKey === null) {
324+
return null;
325+
}
326+
const entries = rememberedThreadTimelines.get(lastReadyThreadKey);
327+
if (entries === undefined || entries.length === 0) {
328+
return null;
329+
}
330+
return { threadKey: lastReadyThreadKey, entries: entries as T };
290331
}
291332

292333
export function resetHeldThreadTimeline(): void {
293-
heldThreadTimeline = null;
334+
rememberedThreadTimelines = new Map();
335+
rememberedThreadTimelineOrder = [];
336+
lastReadyThreadKey = null;
294337
}
295338

296339
export function resolveThreadSwitchTimeline<T extends readonly unknown[]>(input: {
297340
loading: boolean;
298341
activeThreadKey: string | null;
299342
nextEntries: T;
300-
held: HeldThreadTimeline<T> | null;
343+
rememberedForActive?: T | null;
344+
lastReady?: HeldThreadTimeline<T> | null;
301345
}): { entries: T; displayThreadKey: string | null } {
302-
const held = input.held;
346+
if (input.nextEntries.length > 0) {
347+
return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };
348+
}
349+
350+
const rememberedForActive =
351+
input.rememberedForActive ?? peekRememberedThreadTimeline<T>(input.activeThreadKey);
352+
if (rememberedForActive !== null && rememberedForActive.length > 0) {
353+
return { entries: rememberedForActive, displayThreadKey: input.activeThreadKey };
354+
}
355+
356+
const lastReady = input.lastReady ?? peekHeldThreadTimeline<T>();
303357
if (
304358
input.loading &&
305-
held !== null &&
306-
held.threadKey !== null &&
307-
held.threadKey !== input.activeThreadKey &&
308-
held.entries.length > 0
359+
lastReady !== null &&
360+
lastReady.threadKey !== null &&
361+
lastReady.threadKey !== input.activeThreadKey &&
362+
lastReady.entries.length > 0
309363
) {
310-
return { entries: held.entries, displayThreadKey: held.threadKey };
364+
return { entries: lastReady.entries, displayThreadKey: lastReady.threadKey };
311365
}
312366
return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };
313367
}

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

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ import {
415415
resolveComposerInteractionMode,
416416
resolveComposerProviderSelection,
417417
resolveDraftHeroState,
418-
peekHeldThreadTimeline,
418+
peekRememberedThreadTimeline,
419419
rememberReadyThreadTimeline,
420420
resolveThreadSwitchTimeline,
421421
observeProactivePanelUserChoice,
@@ -3249,7 +3249,7 @@ export default function ChatView(props: ChatViewProps) {
32493249
loading: timelineEntries.length === 0 && threadSyncPhase !== null,
32503250
activeThreadKey,
32513251
nextEntries: timelineEntries,
3252-
held: peekHeldThreadTimeline<typeof timelineEntries>(),
3252+
rememberedForActive: peekRememberedThreadTimeline<typeof timelineEntries>(activeThreadKey),
32533253
});
32543254
const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);
32553255
const draftHeroDockRequested =
@@ -4922,6 +4922,21 @@ export default function ChatView(props: ChatViewProps) {
49224922
void legendListRef.current?.scrollToEnd?.({ animated });
49234923
});
49244924
}, []);
4925+
const displayedTimelineKeyRef = useRef(displayedTimeline.displayThreadKey);
4926+
useLayoutEffect(() => {
4927+
const displayKey = displayedTimeline.displayThreadKey;
4928+
if (displayKey === null || displayKey !== activeThreadKey) {
4929+
displayedTimelineKeyRef.current = displayKey;
4930+
return;
4931+
}
4932+
if (displayedTimelineKeyRef.current === displayKey) {
4933+
return;
4934+
}
4935+
displayedTimelineKeyRef.current = displayKey;
4936+
// Keep the list mounted across jumps; pin the newly displayed thread to
4937+
// its end the way a remount used to via initialScrollAtEnd.
4938+
scrollToEnd();
4939+
}, [activeThreadKey, displayedTimeline.displayThreadKey, scrollToEnd]);
49254940
useLayoutEffect(() => {
49264941
if (timelineScrollModeRef.current !== "anchoring-new-turn") {
49274942
return;
@@ -8385,7 +8400,6 @@ export default function ChatView(props: ChatViewProps) {
83858400
onCiteAssistantText={citeAssistantText}
83868401
agentPanelModel={agentPanelModel}
83878402
onOpenAgents={addAgentsSurface}
8388-
key={displayedTimeline.displayThreadKey ?? activeThread.id}
83898403
isWorking={isWorking}
83908404
isPreparingWorktree={isPreparingWorktree}
83918405
isCompacting={isCompacting}
@@ -8397,6 +8411,7 @@ export default function ChatView(props: ChatViewProps) {
83978411
turnDiffSummaries={activeThread.checkpoints}
83988412
activeThreadEnvironmentId={activeThread.environmentId}
83998413
routeThreadKey={routeThreadKey}
8414+
displayThreadKey={displayedTimeline.displayThreadKey ?? routeThreadKey}
84008415
onOpenTurnDiff={onOpenTurnDiff}
84018416
supportsConversationRollback={supportsConversationRollback}
84028417
onRevertToTurnCount={onRevertTimelineTurn}

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

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,12 @@ interface MessagesTimelineProps {
321321
runningTurnId: TurnId | null;
322322
turnDiffSummaries: ReadonlyArray<TurnDiffSummary>;
323323
routeThreadKey: string;
324+
/**
325+
* Thread whose entries are currently painted. Differs from `routeThreadKey`
326+
* while a jump is still holding the previous list. Identity for row
327+
* projection and list extraData — do not remount on this value.
328+
*/
329+
displayThreadKey?: string;
324330
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
325331
supportsConversationRollback: boolean;
326332
onRevertToTurnCount: (targetTurnCount: number) => void;
@@ -379,6 +385,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
379385
runningTurnId,
380386
turnDiffSummaries,
381387
routeThreadKey,
388+
displayThreadKey,
382389
onOpenTurnDiff,
383390
supportsConversationRollback,
384391
onRevertToTurnCount,
@@ -406,17 +413,30 @@ export const MessagesTimeline = memo(function MessagesTimeline({
406413
loadEarlier = null,
407414
}: MessagesTimelineProps) {
408415
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
416+
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
417+
const listIdentityKey = displayThreadKey ?? routeThreadKey;
418+
const listIdentityRef = useRef(listIdentityKey);
419+
const previousLatestTurnRef = useRef(latestTurn);
420+
let paintedExpandedTurnIds = expandedTurnIds;
421+
let paintedExpandedWorkGroupIds = expandedWorkGroupIds;
422+
if (listIdentityRef.current !== listIdentityKey) {
423+
listIdentityRef.current = listIdentityKey;
424+
previousLatestTurnRef.current = latestTurn;
425+
paintedExpandedTurnIds = new Set();
426+
paintedExpandedWorkGroupIds = new Set();
427+
setExpandedTurnIds(paintedExpandedTurnIds);
428+
setExpandedWorkGroupIds(paintedExpandedWorkGroupIds);
429+
}
409430
const citationThreadRef = useMemo(() => parseScopedThreadKey(routeThreadKey), [routeThreadKey]);
410431
const expandCitedTurn = useCallback((turnId: TurnId) => {
411432
setExpandedTurnIds((current) =>
412433
current.has(turnId) ? current : new Set([...current, turnId]),
413434
);
414435
}, []);
415-
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
416436
// Scroll/disclosure state outlives virtualized rows, but never the current thread.
417437
const workGroupViewState = useMemo<WorkGroupViewState>(
418438
() => ({ scrollPositions: new Map(), expandedEntries: new Set() }),
419-
[routeThreadKey],
439+
[listIdentityKey],
420440
);
421441
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
422442
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
@@ -508,7 +528,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
508528

509529
// An in-session interrupt leaves its turn expanded so the user keeps their
510530
// place; the next turn (or a reload, since this is local state) folds it.
511-
const previousLatestTurnRef = useRef(latestTurn);
512531
useEffect(() => {
513532
const previous = previousLatestTurnRef.current;
514533
previousLatestTurnRef.current = latestTurn;
@@ -547,34 +566,34 @@ export const MessagesTimeline = memo(function MessagesTimeline({
547566
timelineEntries,
548567
latestTurn,
549568
runningTurnId,
550-
expandedTurnIds,
551-
expandedWorkGroupIds,
569+
expandedTurnIds: paintedExpandedTurnIds,
570+
expandedWorkGroupIds: paintedExpandedWorkGroupIds,
552571
isWorking,
553572
activeTurnStartedAt,
554573
turnDiffSummaries,
555574
supportsConversationRollback,
556575
},
557-
previous?.threadKey === routeThreadKey && previous.workspaceRoot === workspaceRoot
576+
previous?.threadKey === listIdentityKey && previous.workspaceRoot === workspaceRoot
558577
? previous.projection
559578
: null,
560579
);
561-
rowsProjectionRef.current = { threadKey: routeThreadKey, workspaceRoot, projection };
580+
rowsProjectionRef.current = { threadKey: listIdentityKey, workspaceRoot, projection };
562581
return projection.rows;
563582
}, [
564583
rowsProjectionRef,
565-
routeThreadKey,
584+
listIdentityKey,
566585
workspaceRoot,
567586
timelineEntries,
568587
latestTurn,
569588
runningTurnId,
570-
expandedTurnIds,
571-
expandedWorkGroupIds,
589+
paintedExpandedTurnIds,
590+
paintedExpandedWorkGroupIds,
572591
isWorking,
573592
activeTurnStartedAt,
574593
turnDiffSummaries,
575594
supportsConversationRollback,
576595
]);
577-
const rows = useStableRows(rawRows);
596+
const rows = useStableRows(rawRows, listIdentityKey);
578597
const minimapItems = useMemo(() => deriveTimelineMinimapItems(rows), [rows]);
579598
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
580599
null,
@@ -841,7 +860,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
841860
<LegendList<MessagesTimelineRow>
842861
ref={listRef}
843862
data={rows}
844-
extraData={rows.length}
863+
extraData={`${listIdentityKey}:${rows.length}`}
845864
keyExtractor={keyExtractor}
846865
getItemType={getItemType}
847866
renderItem={renderItem}
@@ -2762,17 +2781,23 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
27622781

27632782
/** Returns a structurally-shared copy of `rows`: for each row whose content
27642783
* hasn't changed since last call, the previous object reference is reused. */
2765-
function useStableRows(rows: MessagesTimelineRow[]): MessagesTimelineRow[] {
2784+
function useStableRows(rows: MessagesTimelineRow[], identity: string): MessagesTimelineRow[] {
27662785
const prevState = useRef<StableMessagesTimelineRowsState>({
27672786
byId: new Map<string, MessagesTimelineRow>(),
27682787
result: [],
27692788
});
2789+
const prevIdentity = useRef(identity);
27702790

27712791
return useMemo(() => {
2772-
const nextState = computeStableMessagesTimelineRows(rows, prevState.current);
2792+
const previous =
2793+
prevIdentity.current === identity
2794+
? prevState.current
2795+
: { byId: new Map<string, MessagesTimelineRow>(), result: [] };
2796+
prevIdentity.current = identity;
2797+
const nextState = computeStableMessagesTimelineRows(rows, previous);
27732798
prevState.current = nextState;
27742799
return nextState.result;
2775-
}, [rows]);
2800+
}, [identity, rows]);
27762801
}
27772802

27782803
// ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)