Skip to content
TypeScript

perf(web): keep timeline row reuse engaged while text streams (#9909)

Julius Marmingeaefef95ffc34
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index c67ea3f3d5c..a5a8503985b 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -1089,6 +1089,56 @@ describe("buildRevertTurnCountByUserMessageId", () => {
}).size,
).toBe(0);
});
+
+ it.each([true, false])(
+ "returns the previous map when contents are unchanged (rollback supported: %s)",
+ (supportsConversationRollback) => {
+ const input = {
+ supportsConversationRollback,
+ timelineEntries,
+ turnDiffSummaryByAssistantMessageId,
+ inferredCheckpointTurnCountByTurnId: {},
+ };
+ const previous = buildRevertTurnCountByUserMessageId(input);
+ const streamed = timelineEntries.map((entry) =>
+ entry.message.role === "assistant"
+ ? { ...entry, message: { ...entry.message, text: "Updated the file again" } }
+ : entry,
+ );
+
+ expect(
+ buildRevertTurnCountByUserMessageId({ ...input, timelineEntries: streamed }, previous),
+ ).toBe(previous);
+ },
+ );
+
+ it("returns a new map when a revert target changes", () => {
+ const input = {
+ supportsConversationRollback: true,
+ timelineEntries,
+ turnDiffSummaryByAssistantMessageId,
+ inferredCheckpointTurnCountByTurnId: {},
+ };
+ const previous = buildRevertTurnCountByUserMessageId(input);
+ const next = buildRevertTurnCountByUserMessageId(
+ {
+ ...input,
+ turnDiffSummaryByAssistantMessageId: new Map([
+ [
+ assistantMessageId,
+ {
+ ...turnDiffSummaryByAssistantMessageId.get(assistantMessageId)!,
+ checkpointTurnCount: 3,
+ },
+ ],
+ ]),
+ },
+ previous,
+ );
+
+ expect(next).not.toBe(previous);
+ expect(next).toEqual(new Map([[userMessageId, 2]]));
+ });
});
describe("deriveComposerSendState", () => {
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index 10c2fd4710e..bf576a3c763 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -38,6 +38,7 @@ import {
} from "../types";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import * as Schema from "effect/Schema";
+import { shallow } from "zustand/vanilla/shallow";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentThreadDetails } from "../state/threads";
import {
@@ -464,17 +465,24 @@ export function getAntigravitySendBlockReason(
return null;
}
-export function buildRevertTurnCountByUserMessageId(input: {
- supportsConversationRollback: boolean;
- timelineEntries: ReadonlyArray<TimelineEntry>;
- turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
- inferredCheckpointTurnCountByTurnId: Readonly<Record<string, number | undefined>>;
-}) {
+/**
+ * Maps each user message to the checkpoint turn count a revert should target.
+ * Returns `previous` when the result is unchanged: streaming text deltas
+ * rebuild `timelineEntries` per token, and the timeline row projection only
+ * reuses rows while this Map keeps its identity.
+ */
+export function buildRevertTurnCountByUserMessageId(
+ input: {
+ supportsConversationRollback: boolean;
+ timelineEntries: ReadonlyArray<TimelineEntry>;
+ turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
+ inferredCheckpointTurnCountByTurnId: Readonly<Record<string, number | undefined>>;
+ },
+ previous: Map<MessageId, number> | null = null,
+): Map<MessageId, number> {
const byUserMessageId = new Map<MessageId, number>();
- if (!input.supportsConversationRollback) {
- return byUserMessageId;
- }
- for (let index = 0; index < input.timelineEntries.length; index += 1) {
+ const entryCount = input.supportsConversationRollback ? input.timelineEntries.length : 0;
+ for (let index = 0; index < entryCount; index += 1) {
const entry = input.timelineEntries[index];
if (!entry || entry.kind !== "message" || entry.message.role !== "user") {
continue;
@@ -501,7 +509,7 @@ export function buildRevertTurnCountByUserMessageId(input: {
break;
}
}
- return byUserMessageId;
+ return previous !== null && shallow(previous, byUserMessageId) ? previous : byUserMessageId;
}
export function reconcileMountedTerminalThreadIds(input: {
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 4ceba195e98..b27d66c7611 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -2971,21 +2971,25 @@ export default function ChatView(props: ChatViewProps) {
}
return byMessageId;
}, [turnDiffSummaries]);
- const revertTurnCountByUserMessageId = useMemo(
- () =>
- buildRevertTurnCountByUserMessageId({
+ const lastRevertTurnCountRef = useRef<Map<MessageId, number> | null>(null);
+ const revertTurnCountByUserMessageId = useMemo(() => {
+ const next = buildRevertTurnCountByUserMessageId(
+ {
supportsConversationRollback,
timelineEntries,
turnDiffSummaryByAssistantMessageId,
inferredCheckpointTurnCountByTurnId,
- }),
- [
- supportsConversationRollback,
- inferredCheckpointTurnCountByTurnId,
- timelineEntries,
- turnDiffSummaryByAssistantMessageId,
- ],
- );
+ },
+ lastRevertTurnCountRef.current,
+ );
+ lastRevertTurnCountRef.current = next;
+ return next;
+ }, [
+ supportsConversationRollback,
+ inferredCheckpointTurnCountByTurnId,
+ timelineEntries,
+ turnDiffSummaryByAssistantMessageId,
+ ]);
const gitCwd = activeProject
? projectScriptCwd({
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
index 94727086f18..5d310c5fe34 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vite-plus/test";
-import { MessageId, TurnId } from "@t3tools/contracts";
+import { CheckpointRef, MessageId, TurnId } from "@t3tools/contracts";
import {
computeStableMessagesTimelineRows,
computeMessageDurationStart,
@@ -20,6 +20,7 @@ import {
deriveTimelineEntriesWithState,
type WorkLogEntry,
} from "../../session-logic";
+import { buildRevertTurnCountByUserMessageId } from "../ChatView.logic";
import { isImageAttachment, type ChatMessage, type TurnDiffSummary } from "../../types";
describe("streaming row projection", () => {
@@ -242,6 +243,61 @@ describe("streaming row projection", () => {
},
);
+ it("reuses rows when the revert map is rebuilt from the streamed entries", () => {
+ const initial = fixture("Partial");
+ const inferredCheckpointTurnCountByTurnId = { [initial.historyTurnId]: 1 };
+ const turnDiffSummaryByAssistantMessageId = new Map<MessageId, TurnDiffSummary>([
+ [
+ MessageId.make("history-assistant"),
+ {
+ turnId: initial.historyTurnId,
+ checkpointTurnCount: 1,
+ checkpointRef: CheckpointRef.make("refs/t3/checkpoints/history-turn"),
+ status: "ready",
+ files: [],
+ assistantMessageId: MessageId.make("history-assistant"),
+ completedAt: initial.time(4),
+ },
+ ],
+ ]);
+ let revertMap: Map<MessageId, number> | null = null;
+ // Mirrors ChatView: the map is derived from each delta's entries.
+ const build = (timelineEntries: typeof initial.timeline.entries) => {
+ revertMap = buildRevertTurnCountByUserMessageId(
+ {
+ supportsConversationRollback: true,
+ timelineEntries,
+ turnDiffSummaryByAssistantMessageId,
+ inferredCheckpointTurnCountByTurnId,
+ },
+ revertMap,
+ );
+ return {
+ ...initial.input,
+ timelineEntries,
+ turnDiffSummaryByAssistantMessageId,
+ revertTurnCountByUserMessageId: revertMap,
+ };
+ };
+ const previous = deriveMessagesTimelineRowsWithState(build(initial.timeline.entries));
+ expect(previous.rows.some((row) => row.kind === "message" && row.revertTurnCount === 0)).toBe(
+ true,
+ );
+ const last = initial.messages.at(-1)!;
+ const messages = [...initial.messages.slice(0, -1), { ...last, text: "Partial token" }];
+ const timeline = deriveTimelineEntriesWithState(messages, [], initial.work, initial.timeline);
+ const next = deriveMessagesTimelineRowsWithState(build(timeline.entries), previous);
+
+ expect(next.rows).toEqual(deriveMessagesTimelineRows(build(timeline.entries)));
+ for (const [index, row] of previous.rows.entries()) {
+ if ((row.kind === "message" || row.kind === "assistant-meta") && row.message === last) {
+ expect(next.rows[index]).toMatchObject({ message: { text: "Partial token" } });
+ } else {
+ expect(next.rows[index]).toBe(row);
+ }
+ }
+ });
+
it.each(["completion", "turn", "role", "ordering"] as const)(
"rebuilds row structure for a %s change with otherwise unchanged controls",
(change) => {