Skip to content

Commit 7e4ad44

Browse files
Stabilize chat timeline row reuse
- Extract row stabilization into shared logic - Preserve row identity across unchanged renders - Add tests for unchanged and reordered rows
1 parent ae4c4c7 commit 7e4ad44

3 files changed

Lines changed: 167 additions & 50 deletions

File tree

‎apps/web/src/components/chat/MessagesTimeline.logic.test.ts‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, it } from "vitest";
22
import {
3+
computeStableMessagesTimelineRows,
34
computeMessageDurationStart,
45
deriveMessagesTimelineRows,
56
normalizeCompactToolLabel,
@@ -328,3 +329,107 @@ describe("deriveMessagesTimelineRows", () => {
328329
expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);
329330
});
330331
});
332+
333+
describe("computeStableMessagesTimelineRows", () => {
334+
it("returns the previous result when row order and content are unchanged", () => {
335+
const firstUserMessage = {
336+
id: "user-1" as never,
337+
role: "user" as const,
338+
text: "First",
339+
turnId: null,
340+
createdAt: "2026-01-01T00:00:00Z",
341+
streaming: false,
342+
};
343+
const secondUserMessage = {
344+
id: "user-2" as never,
345+
role: "user" as const,
346+
text: "Second",
347+
turnId: null,
348+
createdAt: "2026-01-01T00:00:10Z",
349+
streaming: false,
350+
};
351+
352+
const rows = deriveMessagesTimelineRows({
353+
timelineEntries: [
354+
{
355+
id: "entry-user-1",
356+
kind: "message",
357+
createdAt: firstUserMessage.createdAt,
358+
message: firstUserMessage,
359+
},
360+
{
361+
id: "entry-user-2",
362+
kind: "message",
363+
createdAt: secondUserMessage.createdAt,
364+
message: secondUserMessage,
365+
},
366+
],
367+
completionDividerBeforeEntryId: null,
368+
isWorking: false,
369+
activeTurnStartedAt: null,
370+
turnDiffSummaryByAssistantMessageId: new Map(),
371+
revertTurnCountByUserMessageId: new Map(),
372+
});
373+
374+
const initial = computeStableMessagesTimelineRows(rows, {
375+
byId: new Map(),
376+
result: [],
377+
});
378+
379+
const repeated = computeStableMessagesTimelineRows(rows, initial);
380+
381+
expect(repeated).toBe(initial);
382+
expect(repeated.result).toBe(initial.result);
383+
});
384+
385+
it("returns a new result when row order changes without content changes", () => {
386+
const firstUserMessage = {
387+
id: "user-1" as never,
388+
role: "user" as const,
389+
text: "First",
390+
turnId: null,
391+
createdAt: "2026-01-01T00:00:00Z",
392+
streaming: false,
393+
};
394+
const secondUserMessage = {
395+
id: "user-2" as never,
396+
role: "user" as const,
397+
text: "Second",
398+
turnId: null,
399+
createdAt: "2026-01-01T00:00:10Z",
400+
streaming: false,
401+
};
402+
403+
const firstRows = deriveMessagesTimelineRows({
404+
timelineEntries: [
405+
{
406+
id: "entry-user-1",
407+
kind: "message",
408+
createdAt: firstUserMessage.createdAt,
409+
message: firstUserMessage,
410+
},
411+
{
412+
id: "entry-user-2",
413+
kind: "message",
414+
createdAt: secondUserMessage.createdAt,
415+
message: secondUserMessage,
416+
},
417+
],
418+
completionDividerBeforeEntryId: null,
419+
isWorking: false,
420+
activeTurnStartedAt: null,
421+
turnDiffSummaryByAssistantMessageId: new Map(),
422+
revertTurnCountByUserMessageId: new Map(),
423+
});
424+
425+
const initial = computeStableMessagesTimelineRows(firstRows, {
426+
byId: new Map(),
427+
result: [],
428+
});
429+
430+
const reordered = computeStableMessagesTimelineRows([firstRows[1]!, firstRows[0]!], initial);
431+
432+
expect(reordered).not.toBe(initial);
433+
expect(reordered.result).toEqual([initial.result[1], initial.result[0]]);
434+
});
435+
});

‎apps/web/src/components/chat/MessagesTimeline.logic.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ export type MessagesTimelineRow =
3737
}
3838
| { kind: "working"; id: string; createdAt: string | null };
3939

40+
export interface StableMessagesTimelineRowsState {
41+
byId: Map<string, MessagesTimelineRow>;
42+
result: MessagesTimelineRow[];
43+
}
44+
4045
export function computeMessageDurationStart(
4146
messages: ReadonlyArray<TimelineDurationMessage>,
4247
): Map<string, string> {
@@ -185,3 +190,51 @@ export function deriveMessagesTimelineRows(input: {
185190

186191
return nextRows;
187192
}
193+
194+
export function computeStableMessagesTimelineRows(
195+
rows: MessagesTimelineRow[],
196+
previous: StableMessagesTimelineRowsState,
197+
): StableMessagesTimelineRowsState {
198+
const next = new Map<string, MessagesTimelineRow>();
199+
let anyChanged = rows.length !== previous.byId.size;
200+
201+
const result = rows.map((row, index) => {
202+
const prevRow = previous.byId.get(row.id);
203+
const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
204+
next.set(row.id, nextRow);
205+
if (!anyChanged && previous.result[index] !== nextRow) {
206+
anyChanged = true;
207+
}
208+
return nextRow;
209+
});
210+
211+
return anyChanged ? { byId: next, result } : previous;
212+
}
213+
214+
/** Shallow field comparison per row variant — avoids deep equality cost. */
215+
function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
216+
if (a.kind !== b.kind || a.id !== b.id) return false;
217+
218+
switch (a.kind) {
219+
case "working":
220+
return a.createdAt === (b as typeof a).createdAt;
221+
222+
case "proposed-plan":
223+
return a.proposedPlan === (b as typeof a).proposedPlan;
224+
225+
case "work":
226+
return a.groupedEntries === (b as typeof a).groupedEntries;
227+
228+
case "message": {
229+
const bm = b as typeof a;
230+
return (
231+
a.message === bm.message &&
232+
a.durationStart === bm.durationStart &&
233+
a.showCompletionDivider === bm.showCompletionDivider &&
234+
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
235+
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
236+
a.revertTurnCount === bm.revertTurnCount
237+
);
238+
}
239+
}
240+
}

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

Lines changed: 9 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,12 @@ import { ChangedFilesTree } from "./ChangedFilesTree";
3636
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
3737
import { MessageCopyButton } from "./MessageCopyButton";
3838
import {
39+
computeStableMessagesTimelineRows,
3940
MAX_VISIBLE_WORK_LOG_ENTRIES,
4041
deriveMessagesTimelineRows,
4142
normalizeCompactToolLabel,
4243
resolveAssistantMessageCopyState,
44+
type StableMessagesTimelineRowsState,
4345
type MessagesTimelineRow,
4446
} from "./MessagesTimeline.logic";
4547
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
@@ -758,61 +760,18 @@ const UserMessageBody = memo(function UserMessageBody(props: {
758760
/** Returns a structurally-shared copy of `rows`: for each row whose content
759761
* hasn't changed since last call, the previous object reference is reused. */
760762
function useStableRows(rows: MessagesTimelineRow[]): MessagesTimelineRow[] {
761-
const prevById = useRef(new Map<string, MessagesTimelineRow>());
762-
const prevResult = useRef<MessagesTimelineRow[]>([]);
763+
const prevState = useRef<StableMessagesTimelineRowsState>({
764+
byId: new Map<string, MessagesTimelineRow>(),
765+
result: [],
766+
});
763767

764768
return useMemo(() => {
765-
const prev = prevById.current;
766-
const next = new Map<string, MessagesTimelineRow>();
767-
let anyChanged = rows.length !== prev.size;
768-
769-
const result = rows.map((row) => {
770-
const prevRow = prev.get(row.id);
771-
if (prevRow && isRowUnchanged(prevRow, row)) {
772-
next.set(row.id, prevRow);
773-
return prevRow;
774-
}
775-
next.set(row.id, row);
776-
anyChanged = true;
777-
return row;
778-
});
779-
780-
prevById.current = next;
781-
782-
if (!anyChanged) return prevResult.current;
783-
prevResult.current = result;
784-
return result;
769+
const nextState = computeStableMessagesTimelineRows(rows, prevState.current);
770+
prevState.current = nextState;
771+
return nextState.result;
785772
}, [rows]);
786773
}
787774

788-
/** Shallow field comparison per row variant — avoids JSON.stringify cost. */
789-
function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
790-
if (a.kind !== b.kind || a.id !== b.id) return false;
791-
792-
switch (a.kind) {
793-
case "working":
794-
return a.createdAt === (b as typeof a).createdAt;
795-
796-
case "proposed-plan":
797-
return a.proposedPlan === (b as typeof a).proposedPlan;
798-
799-
case "work":
800-
return a.groupedEntries === (b as typeof a).groupedEntries;
801-
802-
case "message": {
803-
const bm = b as typeof a;
804-
return (
805-
a.message === bm.message &&
806-
a.durationStart === bm.durationStart &&
807-
a.showCompletionDivider === bm.showCompletionDivider &&
808-
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
809-
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
810-
a.revertTurnCount === bm.revertTurnCount
811-
);
812-
}
813-
}
814-
}
815-
816775
// ---------------------------------------------------------------------------
817776
// Pure helpers
818777
// ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)