Skip to content
TypeScript

perf(web): reuse timeline rows while text streams (#9725)

Theo Browne19c1710a88a2
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 368e43d5e06..d48c5642f62 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -93,16 +93,18 @@ import {
parseStandaloneComposerSlashCommand,
} from "../composer-logic";
import {
+ createMessageAttachmentPreviewProjector,
derivePendingApprovals,
derivePendingUserInputs,
derivePhase,
- deriveTimelineEntries,
+ deriveTimelineEntriesWithState,
deriveActiveWorkStartedAt,
deriveActivePlanState,
findLatestProposedPlan,
deriveWorkLogEntries,
hasActionableProposedPlan,
isLatestTurnSettled,
+ type TimelineEntriesProjection,
} from "../session-logic";
import { type LegendListRef } from "@legendapp/list/react";
import {
@@ -2706,6 +2708,8 @@ export default function ChatView(props: ChatViewProps) {
});
}, []);
const serverMessages = activeThread?.messages;
+ const [projectServerMessagePreviews] = useState(createMessageAttachmentPreviewProjector);
+ const [projectHandoffMessagePreviews] = useState(createMessageAttachmentPreviewProjector);
const downloadFileAttachment = useCallback(
async (attachment: ChatFileAttachment) => {
const connection = readPreparedConnection(environmentId);
@@ -2777,19 +2781,12 @@ export default function ChatView(props: ChatViewProps) {
);
const displayServerMessages = useMemo<ReadonlyArray<ChatMessage>>(() => {
if (!serverMessages) return [];
- return serverMessages.map((message) => {
- if (!message.attachments || message.attachments.length === 0) {
- return message;
- }
- return {
- ...message,
- attachments: message.attachments.map((attachment) => {
- const previewUrl = serverAttachmentUrlById.get(attachment.id);
- return previewUrl ? { ...attachment, previewUrl } : attachment;
- }),
- };
- });
- }, [serverAttachmentUrlById, serverMessages]);
+ return serverMessages.map((message) =>
+ projectServerMessagePreviews(message, (attachment) =>
+ serverAttachmentUrlById.get(attachment.id),
+ ),
+ );
+ }, [projectServerMessagePreviews, serverAttachmentUrlById, serverMessages]);
useEffect(() => {
if (typeof Image === "undefined" || displayServerMessages.length === 0) {
return;
@@ -2879,10 +2876,7 @@ export default function ChatView(props: ChatViewProps) {
const serverMessagesWithPreviewHandoff =
Object.keys(attachmentPreviewHandoffByMessageId).length === 0
? messages
- : // Spread only fires for the few messages that actually changed;
- // unchanged ones early-return their original reference.
- // In-place mutation would break React's immutable state contract.
- messages.map((message) => {
+ : messages.map((message) => {
if (
message.role !== "user" ||
!message.attachments ||
@@ -2895,25 +2889,15 @@ export default function ChatView(props: ChatViewProps) {
return message;
}
- let changed = false;
let imageIndex = 0;
- const attachments = message.attachments.map((attachment) => {
+ return projectHandoffMessagePreviews(message, (attachment) => {
if (!isImageAttachment(attachment)) {
- return attachment;
+ return undefined;
}
const handoffPreviewUrl = handoffPreviewUrls[imageIndex];
imageIndex += 1;
- if (!handoffPreviewUrl || attachment.previewUrl === handoffPreviewUrl) {
- return attachment;
- }
- changed = true;
- return {
- ...attachment,
- previewUrl: handoffPreviewUrl,
- };
+ return handoffPreviewUrl;
});
-
- return changed ? { ...message, attachments } : message;
});
const localMessages = [
@@ -2938,12 +2922,29 @@ export default function ChatView(props: ChatViewProps) {
displayServerMessages,
feedbackSubmissions,
optimisticUserMessages,
+ projectHandoffMessagePreviews,
+ ]);
+ const timelineProjectionRef = useRef<{
+ threadKey: string | null;
+ projection: TimelineEntriesProjection;
+ } | null>(null);
+ const timelineEntries = useMemo(() => {
+ const previous = timelineProjectionRef.current;
+ const projection = deriveTimelineEntriesWithState(
+ timelineMessages,
+ activeThread?.proposedPlans ?? [],
+ workLogEntries,
+ previous?.threadKey === activeThreadKey ? previous.projection : null,
+ );
+ timelineProjectionRef.current = { threadKey: activeThreadKey, projection };
+ return projection.entries;
+ }, [
+ timelineProjectionRef,
+ activeThreadKey,
+ activeThread?.proposedPlans,
+ timelineMessages,
+ workLogEntries,
]);
- const timelineEntries = useMemo(
- () =>
- deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries),
- [activeThread?.proposedPlans, timelineMessages, workLogEntries],
- );
const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);
const draftHeroDockRequested =
activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
index 6e5cf29c291..b0436875c2a 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
@@ -4,6 +4,7 @@ import {
computeStableMessagesTimelineRows,
computeMessageDurationStart,
deriveMessagesTimelineRows,
+ deriveMessagesTimelineRowsWithState,
liveWorkEntryLabel,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
@@ -13,6 +14,346 @@ import {
type MessagesTimelineRow,
workEntryDisplayLabel,
} from "./MessagesTimeline.logic";
+import {
+ createMessageAttachmentPreviewProjector,
+ deriveTimelineEntries,
+ deriveTimelineEntriesWithState,
+ type WorkLogEntry,
+} from "../../session-logic";
+import { isImageAttachment, type ChatMessage, type TurnDiffSummary } from "../../types";
+
+describe("streaming row projection", () => {
+ function fixture(text = "") {
+ const turnId = TurnId.make("live-turn");
+ const historyTurnId = TurnId.make("history-turn");
+ const time = (second: number) => new Date(Date.UTC(2026, 8, 4, 0, 0, second)).toISOString();
+ const messages: ChatMessage[] = [
+ {
+ id: MessageId.make("history-user"),
+ role: "user",
+ text: "Inspect",
+ turnId: null,
+ createdAt: time(0),
+ updatedAt: time(0),
+ streaming: false,
+ },
+ {
+ id: MessageId.make("history-assistant"),
+ role: "assistant",
+ text: "Done",
+ turnId: historyTurnId,
+ createdAt: time(3),
+ updatedAt: time(4),
+ streaming: false,
+ },
+ {
+ id: MessageId.make("live-user"),
+ role: "user",
+ text: "Continue",
+ turnId: null,
+ createdAt: time(5),
+ updatedAt: time(5),
+ streaming: false,
+ },
+ {
+ id: MessageId.make("live-assistant"),
+ role: "assistant",
+ text,
+ turnId,
+ createdAt: time(7),
+ updatedAt: time(7),
+ streaming: true,
+ },
+ ];
+ const work: WorkLogEntry[] = [
+ {
+ id: "history-work",
+ turnId: historyTurnId,
+ createdAt: time(1),
+ label: "Ran command",
+ tone: "tool",
+ command: "vp test",
+ toolCallId: "history-tool",
+ toolLifecycleStatus: "failed",
+ sourceActivityKind: "tool.completed",
+ },
+ {
+ id: "live-work",
+ turnId,
+ createdAt: time(6),
+ label: "Read file",
+ tone: "tool",
+ changedFiles: ["/repo/src/index.ts"],
+ toolCallId: "live-tool",
+ toolLifecycleStatus: "completed",
+ sourceActivityKind: "tool.completed",
+ },
+ ];
+ const timeline = deriveTimelineEntriesWithState(messages, [], work);
+ const input = {
+ timelineEntries: timeline.entries,
+ latestTurn: { turnId, state: "running", startedAt: time(5), completedAt: null },
+ runningTurnId: turnId,
+ isWorking: true,
+ activeTurnStartedAt: time(5),
+ turnDiffSummaryByAssistantMessageId: new Map<MessageId, TurnDiffSummary>(),
+ revertTurnCountByUserMessageId: new Map<MessageId, number>(),
+ } satisfies Parameters<typeof deriveMessagesTimelineRows>[0];
+ return { messages, work, timeline, input, time, turnId, historyTurnId };
+ }
+
+ it.each([
+ ["", "Now visible"],
+ [" \n", "Now visible"],
+ ["Visible", ""],
+ ["", " \t\n"],
+ ["Visible", "★ Insight\nKeep these line breaks"],
+ ])("keeps row parity and history identity when text changes from %j to %j", (before, after) => {
+ const initial = fixture(before);
+ const previous = deriveMessagesTimelineRowsWithState(initial.input);
+ Object.freeze(previous.rows);
+ for (const row of previous.rows) Object.freeze(row);
+ const last = initial.messages.at(-1)!;
+ const messages = [
+ ...initial.messages.slice(0, -1),
+ { ...last, text: after, updatedAt: initial.time(8) },
+ ];
+ const timeline = deriveTimelineEntriesWithState(messages, [], initial.work, initial.timeline);
+ const input = { ...initial.input, timelineEntries: timeline.entries };
+ const next = deriveMessagesTimelineRowsWithState(input, previous);
+
+ expect(next.rows).toEqual(
+ deriveMessagesTimelineRows({
+ ...input,
+ timelineEntries: deriveTimelineEntries(messages, [], initial.work),
+ }),
+ );
+ 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: after } });
+ expect(row.message.text).toBe(before);
+ } else {
+ expect(next.rows[index]).toBe(row);
+ }
+ }
+ });
+
+ it("keeps earlier emitted rows unchanged across two projection branches", () => {
+ const initial = fixture();
+ const previous = deriveMessagesTimelineRowsWithState(initial.input);
+ const last = initial.messages.at(-1)!;
+ const branch = (text: string) => {
+ const messages = [...initial.messages.slice(0, -1), { ...last, text }];
+ const timeline = deriveTimelineEntriesWithState(messages, [], initial.work, initial.timeline);
+ const input = { ...initial.input, timelineEntries: timeline.entries };
+ const projection = deriveMessagesTimelineRowsWithState(input, previous);
+ expect(projection.rows).toEqual(deriveMessagesTimelineRows(input));
+ return projection;
+ };
+ const first = branch("First branch");
+ const savedFirst = structuredClone(first.rows);
+ branch("Second branch");
+ expect(first.rows).toEqual(savedFirst);
+ expect(previous.rows).toEqual(deriveMessagesTimelineRows(initial.input));
+ });
+
+ it.each(["file", "image", "handoff", "streaming-image"] as const)(
+ "preserves stream reuse through the real %s preview materializer",
+ (kind) => {
+ const initial = fixture("Partial");
+ const image = {
+ type: "image" as const,
+ id: "image",
+ name: "image.png",
+ mimeType: "image/png",
+ sizeBytes: 42,
+ };
+ const file = {
+ type: "file" as const,
+ id: "file",
+ name: "file.txt",
+ mimeType: "text/plain",
+ sizeBytes: 8,
+ };
+ const source = initial.messages.map((message, index) =>
+ index === 0 || (kind === "streaming-image" && index === initial.messages.length - 1)
+ ? { ...message, attachments: kind === "file" ? [file] : [image, file] }
+ : message,
+ );
+ const server = createMessageAttachmentPreviewProjector();
+ const handoff = createMessageAttachmentPreviewProjector();
+ const materialize = (messages: ReadonlyArray<ChatMessage>, url: string) => {
+ const urls = new Map(kind === "handoff" ? [] : [[image.id, url]]);
+ return messages.map((message) => {
+ const displayed = server(message, (attachment) => urls.get(attachment.id));
+ return kind === "handoff" && message.role === "user"
+ ? handoff(displayed, (attachment) =>
+ isImageAttachment(attachment) ? "blob:handoff" : undefined,
+ )
+ : displayed;
+ });
+ };
+ const firstMessages = materialize(source, "https://first.test/image");
+ const firstTimeline = deriveTimelineEntriesWithState(firstMessages, [], initial.work);
+ const input = { ...initial.input, timelineEntries: firstTimeline.entries };
+ const previous = deriveMessagesTimelineRowsWithState(input);
+ const saved = structuredClone(previous.rows);
+ const nextSource = [...source.slice(0, -1), { ...source.at(-1)!, text: "Next token" }];
+ const nextMessages = materialize(nextSource, "https://first.test/image");
+ const nextTimeline = deriveTimelineEntriesWithState(
+ nextMessages,
+ [],
+ initial.work,
+ firstTimeline,
+ );
+ const nextInput = { ...input, timelineEntries: nextTimeline.entries };
+ const next = deriveMessagesTimelineRowsWithState(nextInput, previous);
+
+ expect(nextMessages[0]).toBe(firstMessages[0]);
+ expect(next.rows).toEqual(deriveMessagesTimelineRows(nextInput));
+ for (const [index, row] of previous.rows.entries()) {
+ if (
+ (row.kind === "message" || row.kind === "assistant-meta") &&
+ row.message.id === source.at(-1)?.id
+ )
+ continue;
+ expect(next.rows[index]).toBe(row);
+ }
+ expect(previous.rows).toEqual(saved);
+
+ if (kind === "image" || kind === "streaming-image") {
+ const renewed = materialize(nextSource, "https://renewed.test/image");
+ const renewedTimeline = deriveTimelineEntriesWithState(
+ renewed,
+ [],
+ initial.work,
+ nextTimeline,
+ );
+ const renewedInput = { ...input, timelineEntries: renewedTimeline.entries };
+ const renewedRows = deriveMessagesTimelineRowsWithState(renewedInput, next);
+ expect(renewedRows.rows).toEqual(deriveMessagesTimelineRows(renewedInput));
+ expect(renewed[0]?.attachments?.[0]).toMatchObject({
+ previewUrl: "https://renewed.test/image",
+ });
+ expect(firstMessages[0]?.attachments?.[0]).toMatchObject({
+ previewUrl: "https://first.test/image",
+ });
+ }
+ },
+ );
+
+ it.each(["completion", "turn", "role", "ordering"] as const)(
+ "rebuilds row structure for a %s change with otherwise unchanged controls",
+ (change) => {
+ const initial = fixture("Partial");
+ const input = {
+ ...initial.input,
+ latestTurn: {
+ ...initial.input.latestTurn,
+ state: "completed" as const,
+ completedAt: initial.time(9),
+ },
+ runningTurnId: null,
+ isWorking: false,
+ };
+ const previous = deriveMessagesTimelineRowsWithState(input);
+ const last = initial.messages.at(-1)!;
+ const changed: ChatMessage =
+ change === "completion"
+ ? { ...last, streaming: false, updatedAt: initial.time(10) }
+ : change === "turn"
+ ? { ...last, turnId: initial.historyTurnId }
+ : change === "role"
+ ? { ...last, role: "user", turnId: null }
+ : { ...last, createdAt: initial.time(0) };
+ const messages = [...initial.messages.slice(0, -1), changed];
+ const timeline = deriveTimelineEntriesWithState(messages, [], initial.work, initial.timeline);
+ const nextInput = { ...input, timelineEntries: timeline.entries };
+ const next = deriveMessagesTimelineRowsWithState(nextInput, previous);
+ expect(next.rows).toEqual(
+ deriveMessagesTimelineRows({
+ ...nextInput,
+ timelineEntries: deriveTimelineEntries(messages, [], initial.work),
+ }),
+ );
+ expect(previous.rows).toEqual(deriveMessagesTimelineRows(input));
+ },
+ );
+
+ it("keeps full parity through completion, trailing failure, metadata, expansion, and paging", () => {
+ const initial = fixture("Partial");
+ let timeline = initial.timeline;
+ let input: Parameters<typeof deriveMessagesTimelineRows>[0] = initial.input;
+ let projection = deriveMessagesTimelineRowsWithState(input);
+ let messages = initial.messages;
+ let work = initial.work;
+ const check = (changes: Partial<typeof input> = {}) => {
+ const oldRows = structuredClone(projection.rows);
+ const previous = projection;
+ timeline = deriveTimelineEntriesWithState(messages, [], work, timeline);
+ input = { ...input, ...changes, timelineEntries: timeline.entries };
+ projection = deriveMessagesTimelineRowsWithState(input, previous);
+ expect(projection.rows).toEqual(
+ deriveMessagesTimelineRows({
+ ...input,
+ timelineEntries: deriveTimelineEntries(messages, [], work),
+ }),
+ );
+ expect(previous.rows).toEqual(oldRows);
+ };
+
+ messages = [
+ ...messages.slice(0, -1),
+ { ...messages.at(-1)!, streaming: false, text: "Complete", updatedAt: initial.time(9) },
+ ];
+ check({
+ latestTurn: { ...initial.input.latestTurn, state: "completed", completedAt: initial.time(9) },
+ runningTurnId: null,
+ isWorking: false,
+ });
+ work = [
+ ...work,
+ {
+ id: "late-failure",
+ turnId: initial.turnId,
+ createdAt: initial.time(10),
+ label: "Failed command",
+ command: "vp test",
+ tone: "error",
+ toolCallId: "failed-tool",
+ toolLifecycleStatus: "failed",
+ sourceActivityKind: "tool.completed",
+ },
+ ];
+ check();
+ messages = [
+ ...messages.slice(0, -1),
+ { ...messages.at(-1)!, text: "Updated final text", updatedAt: initial.time(11) },
+ ];
+ check();
+ check({
+ latestTurn: {
+ ...initial.input.latestTurn,
+ state: "interrupted",
+ completedAt: initial.time(12),
+ },
+ });
+ check({ expandedTurnIds: new Set([initial.historyTurnId, initial.turnId]) });
+ const group = projection.rows.find((row) => row.kind === "work-toggle");
+ check({ expandedWorkGroupIds: new Set(group ? [group.id] : []) });
+ messages = [
+ { ...messages[0]!, id: MessageId.make("older-user"), createdAt: "2026-09-03T23:59:00.000Z" },
+ ...messages,
+ ];
+ check();
+ messages = messages.map((message) =>
+ message.id === MessageId.make("live-assistant")
+ ? { ...message, role: "user", turnId: null, createdAt: initial.time(0) }
+ : message,
+ );
+ check({ revertTurnCountByUserMessageId: new Map([[MessageId.make("live-user"), 3]]) });
+ });
+});
describe("expanded tool group scrolling", () => {
const entries = [{ id: "first" }, { id: "second" }];
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts
index 6883a5c74c7..7b01caf16d0 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts
@@ -1,4 +1,5 @@
import * as Equal from "effect/Equal";
+import { shallow } from "zustand/vanilla/shallow";
import { renderCodexDirectivesForCopy } from "@t3tools/client-runtime/codex-markdown-directives";
import { commandProgramName } from "@t3tools/client-runtime/work-log/command-label";
import {
@@ -19,6 +20,7 @@ export {
} from "@t3tools/client-runtime/work-log/presentation";
import {
formatDuration,
+ isStreamingMessageTextUpdate,
workEntryDisplayIndicatesToolFailure,
workEntryIndicatesToolSuccess,
workEntryIndicatesToolNeutralStatus,
@@ -1153,6 +1155,59 @@ export function deriveMessagesTimelineRows(input: {
return attachTrailingToolGroupsToAssistant(nextRows);
}
+type MessagesTimelineRowsInput = Parameters<typeof deriveMessagesTimelineRows>[0];
+
+export interface MessagesTimelineRowsProjection {
+ readonly input: MessagesTimelineRowsInput;
+ readonly rows: MessagesTimelineRow[];
+}
+
+function replaceStreamingMessageRows(
+ input: MessagesTimelineRowsInput,
+ previous: MessagesTimelineRowsProjection,
+): MessagesTimelineRow[] | null {
+ const { timelineEntries: previousEntries, ...previousContext } = previous.input;
+ const { timelineEntries, ...context } = input;
+ if (timelineEntries.length !== previousEntries.length || !shallow(previousContext, context)) {
+ return null;
+ }
+ const replacements = new Map<ChatMessage, ChatMessage>();
+ for (const [index, entry] of timelineEntries.entries()) {
+ const previousEntry = previousEntries[index]!;
+ if (entry === previousEntry) continue;
+ if (
+ entry.kind !== "message" ||
+ previousEntry.kind !== "message" ||
+ entry.id !== previousEntry.id ||
+ entry.createdAt !== previousEntry.createdAt
+ ) {
+ return null;
+ }
+ if (entry.message === previousEntry.message) continue;
+ if (!isStreamingMessageTextUpdate(previousEntry.message, entry.message)) return null;
+ replacements.set(previousEntry.message, entry.message);
+ }
+ if (replacements.size === 0) return previous.rows;
+ return previous.rows.map((row) => {
+ if (row.kind !== "message" && row.kind !== "assistant-meta") return row;
+ const message = replacements.get(row.message);
+ return message ? { ...row, message } : row;
+ });
+}
+
+/** Keep one projection per timeline. Reuse rows only when streaming content changes. */
+export function deriveMessagesTimelineRowsWithState(
+ input: MessagesTimelineRowsInput,
+ previous: MessagesTimelineRowsProjection | null = null,
+): MessagesTimelineRowsProjection {
+ return {
+ input,
+ rows:
+ (previous === null ? null : replaceStreamingMessageRows(input, previous)) ??
+ deriveMessagesTimelineRows(input),
+ };
+}
+
export function computeStableMessagesTimelineRows(
rows: MessagesTimelineRow[],
previous: StableMessagesTimelineRowsState,
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 035a3768987..7874daa02c5 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -123,7 +123,8 @@ import {
import { useAssistantCitationTarget, type CitationHistoryPage } from "./useAssistantCitationTarget";
import {
computeStableMessagesTimelineRows,
- deriveMessagesTimelineRows,
+ deriveMessagesTimelineRowsWithState,
+ type MessagesTimelineRowsProjection,
liveWorkEntryLabel,
resolveAssistantMessageCopyState,
resolveTimelineIsAtEnd,
@@ -504,9 +505,15 @@ export const MessagesTimeline = memo(function MessagesTimeline({
});
}, [latestTurn]);
- const rawRows = useMemo(
- () =>
- deriveMessagesTimelineRows({
+ const rowsProjectionRef = useRef<{
+ threadKey: string;
+ workspaceRoot: string | undefined;
+ projection: MessagesTimelineRowsProjection;
+ } | null>(null);
+ const rawRows = useMemo(() => {
+ const previous = rowsProjectionRef.current;
+ const projection = deriveMessagesTimelineRowsWithState(
+ {
timelineEntries,
latestTurn,
runningTurnId,
@@ -516,19 +523,27 @@ export const MessagesTimeline = memo(function MessagesTimeline({
activeTurnStartedAt,
turnDiffSummaryByAssistantMessageId,
revertTurnCountByUserMessageId,
- }),
- [
- timelineEntries,
- latestTurn,
- runningTurnId,
- expandedTurnIds,
- expandedWorkGroupIds,
- isWorking,
- activeTurnStartedAt,
- turnDiffSummaryByAssistantMessageId,
- revertTurnCountByUserMessageId,
- ],
- );
+ },
+ previous?.threadKey === routeThreadKey && previous.workspaceRoot === workspaceRoot
+ ? previous.projection
+ : null,
+ );
+ rowsProjectionRef.current = { threadKey: routeThreadKey, workspaceRoot, projection };
+ return projection.rows;
+ }, [
+ rowsProjectionRef,
+ routeThreadKey,
+ workspaceRoot,
+ timelineEntries,
+ latestTurn,
+ runningTurnId,
+ expandedTurnIds,
+ expandedWorkGroupIds,
+ isWorking,
+ activeTurnStartedAt,
+ turnDiffSummaryByAssistantMessageId,
+ revertTurnCountByUserMessageId,
+ ]);
const rows = useStableRows(rawRows);
const minimapItems = useMemo(() => deriveTimelineMinimapItems(rows), [rows]);
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts
index becd8d91f80..b0d6797bf4d 100644
--- a/apps/web/src/session-logic.test.ts
+++ b/apps/web/src/session-logic.test.ts
@@ -10,11 +10,13 @@ import { describe, expect, it } from "vite-plus/test";
import { resolveWorkEntryToolPresentation } from "@t3tools/client-runtime/work-log/presentation";
import {
+ createMessageAttachmentPreviewProjector,
deriveActiveWorkStartedAt,
deriveActivePlanState,
derivePendingApprovals,
derivePendingUserInputs,
deriveTimelineEntries,
+ deriveTimelineEntriesWithState,
deriveWorkLogEntries,
findLatestProposedPlan,
hasActionableProposedPlan,
@@ -2074,6 +2076,172 @@ describe("deriveWorkLogEntries", () => {
});
describe("deriveTimelineEntries", () => {
+ const streamingMessage = {
+ id: MessageId.make("streaming-message"),
+ role: "assistant" as const,
+ text: "",
+ turnId: TurnId.make("streaming-turn"),
+ createdAt: "2026-02-23T00:00:03.000Z",
+ updatedAt: "2026-02-23T00:00:03.000Z",
+ streaming: true,
+ };
+
+ it("reuses preview objects while preserving URL and attachment metadata changes", () => {
+ const image = {
+ type: "image" as const,
+ id: "image",
+ name: "image.png",
+ mimeType: "image/png",
+ sizeBytes: 42,
+ };
+ const file = {
+ type: "file" as const,
+ id: "file",
+ name: "file.txt",
+ mimeType: "text/plain",
+ sizeBytes: 8,
+ };
+ const message = { ...streamingMessage, attachments: Object.freeze([image, file]) };
+ const project = createMessageAttachmentPreviewProjector();
+ const urls = new Map([[image.id, "https://first.test/image"]]);
+ const first = project(message, (attachment) => urls.get(attachment.id));
+ Object.freeze(first.attachments);
+ expect(project(message, (attachment) => new Map(urls).get(attachment.id))).toBe(first);
+ const streamed = project({ ...message, text: "Next" }, (attachment) => urls.get(attachment.id));
+ expect(streamed.attachments).toBe(first.attachments);
+ expect(streamed.text).toBe("Next");
+ expect(first.text).toBe("");
+ expect(first.attachments?.[1]).toBe(file);
+
+ urls.set(image.id, "https://second.test/image");
+ const renewed = project(message, (attachment) => urls.get(attachment.id));
+ expect(renewed.attachments?.[0]).toMatchObject({ previewUrl: "https://second.test/image" });
+ expect(first.attachments?.[0]).toMatchObject({ previewUrl: "https://first.test/image" });
+ const renamed = project(
+ { ...message, attachments: [{ ...image, name: "renamed.png" }, file] },
+ (attachment) => urls.get(attachment.id),
+ );
+ expect(renamed.attachments?.[0]).toMatchObject({
+ name: "renamed.png",
+ previewUrl: "https://second.test/image",
+ });
+ expect(project(message, () => undefined)).toBe(message);
+ });
+
+ it("keeps pending preview handoffs stable and restores the current server URL", () => {
+ const message = {
+ ...streamingMessage,
+ role: "user" as const,
+ streaming: false,
+ attachments: [
+ {
+ type: "image" as const,
+ id: "image",
+ name: "image.png",
+ mimeType: "image/png",
+ sizeBytes: 42,
+ },
+ ],
+ };
+ const server = createMessageAttachmentPreviewProjector();
+ const handoff = createMessageAttachmentPreviewProjector();
+ const first = handoff(
+ server(message, () => undefined),
+ () => "blob:handoff",
+ );
+ expect(
+ handoff(
+ server(message, () => undefined),
+ () => "blob:handoff",
+ ),
+ ).toBe(first);
+ const ready = server(message, () => "https://server.test/image");
+ expect(handoff(ready, () => "blob:handoff").attachments?.[0]).toMatchObject({
+ previewUrl: "blob:handoff",
+ });
+ expect(handoff(ready, () => undefined)).toBe(ready);
+ expect(ready.attachments?.[0]).toMatchObject({ previewUrl: "https://server.test/image" });
+ expect(first.attachments?.[0]).toMatchObject({ previewUrl: "blob:handoff" });
+ });
+
+ it("reuses ordered history without changing an earlier projection", () => {
+ const history = { ...streamingMessage, id: MessageId.make("history"), streaming: false };
+ const work = [
+ { id: "work", createdAt: history.createdAt, label: "Ran tests", tone: "tool" as const },
+ ];
+ const first = deriveTimelineEntriesWithState([history, streamingMessage], [], work);
+ Object.freeze(first.entries);
+ for (const entry of first.entries) Object.freeze(entry);
+
+ const firstMessage = {
+ ...streamingMessage,
+ text: "First",
+ updatedAt: "2026-02-23T00:00:04.000Z",
+ };
+ const secondMessage = {
+ ...streamingMessage,
+ text: "Second",
+ updatedAt: "2026-02-23T00:00:05.000Z",
+ };
+ const firstBranch = deriveTimelineEntriesWithState([history, firstMessage], [], work, first);
+ const secondBranch = deriveTimelineEntriesWithState([history, secondMessage], [], work, first);
+
+ expect(firstBranch.entries).toEqual(deriveTimelineEntries([history, firstMessage], [], work));
+ expect(secondBranch.entries).toEqual(deriveTimelineEntries([history, secondMessage], [], work));
+ expect(firstBranch.entries[0]).toBe(first.entries[0]);
+ expect(firstBranch.entries[2]).toBe(first.entries[2]);
+ expect(first.entries[1]).toMatchObject({ message: { text: "" } });
+ expect(firstBranch.entries[1]).toMatchObject({ message: { text: "First" } });
+ });
+
+ it("preserves stable source ordering for ties, append, and older pages", () => {
+ const plan = {
+ id: "plan:thread:turn",
+ turnId: streamingMessage.turnId,
+ planMarkdown: "Plan",
+ implementedAt: null,
+ implementationThreadId: null,
+ createdAt: streamingMessage.createdAt,
+ updatedAt: streamingMessage.createdAt,
+ };
+ const firstWork = {
+ id: "work-1",
+ createdAt: streamingMessage.createdAt,
+ label: "Ran tests",
+ tone: "tool" as const,
+ };
+ const first = deriveTimelineEntriesWithState([streamingMessage], [plan], [firstWork]);
+ const appendedMessage = { ...streamingMessage, id: MessageId.make("appended") };
+ const appendedWork = { ...firstWork, id: "work-2" };
+ const messages = [streamingMessage, appendedMessage];
+ const work = [firstWork, appendedWork];
+ const appended = deriveTimelineEntriesWithState(messages, [plan], work, first);
+ expect(appended.entries.map((entry) => entry.id)).toEqual([
+ streamingMessage.id,
+ appendedMessage.id,
+ plan.id,
+ firstWork.id,
+ appendedWork.id,
+ ]);
+ expect(appended.entries[0]).toBe(first.entries[0]);
+
+ const older = {
+ ...streamingMessage,
+ id: MessageId.make("older"),
+ createdAt: "2026-02-22T00:00:00.000Z",
+ };
+ const prepended = deriveTimelineEntriesWithState([older, ...messages], [plan], work, appended);
+ expect(prepended.entries).toEqual(deriveTimelineEntries([older, ...messages], [plan], work));
+ const corrected = {
+ ...streamingMessage,
+ createdAt: "2026-02-24T00:00:00.000Z",
+ streaming: false,
+ };
+ expect(
+ deriveTimelineEntriesWithState([corrected, appendedMessage], [plan], work, appended).entries,
+ ).toEqual(deriveTimelineEntries([corrected, appendedMessage], [plan], work));
+ });
+
it("includes proposed plans alongside messages and work entries in chronological order", () => {
const entries = deriveTimelineEntries(
[
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index b70b2a1ba7f..1fb0391d9eb 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -1,6 +1,7 @@
import * as Option from "effect/Option";
import * as Arr from "effect/Array";
import * as Schema from "effect/Schema";
+import { shallow } from "zustand/vanilla/shallow";
import { isBackgroundTaskActivity } from "@t3tools/client-runtime/state/subagentRuntime";
import {
commandDetailRepeatsCommand,
@@ -24,6 +25,7 @@ import {
} from "@t3tools/contracts";
import type {
+ ChatAttachment,
ChatMessage,
ProposedPlan,
SessionPhase,
@@ -192,6 +194,13 @@ export type TimelineEntry =
entry: WorkLogEntry;
};
+export interface TimelineEntriesProjection {
+ readonly messages: ReadonlyArray<ChatMessage>;
+ readonly proposedPlans: ReadonlyArray<ProposedPlan>;
+ readonly workEntries: ReadonlyArray<WorkLogEntry>;
+ readonly entries: TimelineEntry[];
+}
+
export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") {
return true;
@@ -1774,32 +1783,247 @@ function compareActivityLifecycleRank(kind: string): number {
return 1;
}
-export function deriveTimelineEntries(
- messages: ReadonlyArray<ChatMessage>,
- proposedPlans: ReadonlyArray<ProposedPlan>,
- workEntries: ReadonlyArray<WorkLogEntry>,
-): TimelineEntry[] {
- const messageRows: TimelineEntry[] = messages.map((message) => ({
+function timelineEntryFromMessage(message: ChatMessage): TimelineEntry {
+ return {
id: message.id,
kind: "message",
createdAt: message.createdAt,
message,
- }));
- const proposedPlanRows: TimelineEntry[] = proposedPlans.map((proposedPlan) => ({
+ };
+}
+
+function timelineEntryFromProposedPlan(proposedPlan: ProposedPlan): TimelineEntry {
+ return {
id: proposedPlan.id,
kind: "proposed-plan",
createdAt: proposedPlan.createdAt,
proposedPlan,
- }));
- const workRows: TimelineEntry[] = workEntries.map((entry) => ({
- id: entry.id,
+ };
+}
+
+function timelineEntryFromWork(workEntry: WorkLogEntry): TimelineEntry {
+ return {
+ id: workEntry.id,
kind: "work",
- createdAt: entry.createdAt,
- entry,
- }));
- return [...messageRows, ...proposedPlanRows, ...workRows].toSorted((a, b) =>
- a.createdAt.localeCompare(b.createdAt),
- );
+ createdAt: workEntry.createdAt,
+ entry: workEntry,
+ };
+}
+
+function compareTimelineEntriesByCreatedAt(left: TimelineEntry, right: TimelineEntry): number {
+ return left.createdAt.localeCompare(right.createdAt);
+}
+
+function timelineEntrySourceOrder(entry: TimelineEntry): number {
+ switch (entry.kind) {
+ case "message":
+ return 0;
+ case "proposed-plan":
+ return 1;
+ case "work":
+ return 2;
+ }
+}
+
+function shouldTakePreviousTimelineEntry(previous: TimelineEntry, suffix: TimelineEntry): boolean {
+ const createdAtComparison = compareTimelineEntriesByCreatedAt(previous, suffix);
+ if (createdAtComparison !== 0) return createdAtComparison < 0;
+ // The original full derivation sorts a source-ordered array with a stable
+ // comparator. On a tie, messages precede plans, plans precede work, and an
+ // older item in the same source array precedes a newly appended item.
+ return timelineEntrySourceOrder(previous) <= timelineEntrySourceOrder(suffix);
+}
+
+function hasExactArrayPrefix<T>(previous: ReadonlyArray<T>, next: ReadonlyArray<T>): boolean {
+ if (previous === next) return true;
+ if (next.length < previous.length) return false;
+ for (let index = 0; index < previous.length; index += 1) {
+ if (previous[index] !== next[index]) return false;
+ }
+ return true;
+}
+
+function mergeTimelineEntrySuffix(
+ previous: ReadonlyArray<TimelineEntry>,
+ suffix: ReadonlyArray<TimelineEntry>,
+): TimelineEntry[] {
+ if (suffix.length === 0) return [...previous];
+ const previousLast = previous.at(-1);
+ let suffixIsOrdered = true;
+ for (let index = 1; index < suffix.length; index += 1) {
+ if (compareTimelineEntriesByCreatedAt(suffix[index - 1]!, suffix[index]!) > 0) {
+ suffixIsOrdered = false;
+ break;
+ }
+ }
+ if (
+ suffixIsOrdered &&
+ (previousLast === undefined || shouldTakePreviousTimelineEntry(previousLast, suffix[0]!))
+ ) {
+ return [...previous, ...suffix];
+ }
+
+ const merged: TimelineEntry[] = [];
+ let previousIndex = 0;
+ let suffixIndex = 0;
+ while (previousIndex < previous.length || suffixIndex < suffix.length) {
+ const previousEntry = previous[previousIndex];
+ const suffixEntry = suffix[suffixIndex];
+ if (
+ previousEntry !== undefined &&
+ (suffixEntry === undefined || shouldTakePreviousTimelineEntry(previousEntry, suffixEntry))
+ ) {
+ merged.push(previousEntry);
+ previousIndex += 1;
+ } else if (suffixEntry !== undefined) {
+ merged.push(suffixEntry);
+ suffixIndex += 1;
+ }
+ }
+ return merged;
+}
+
+/** Own one mapper per preview stage. Immutable messages retain unchanged preview objects. */
+export function createMessageAttachmentPreviewProjector() {
+ const attachmentsBySource = new WeakMap<
+ ReadonlyArray<ChatAttachment>,
+ ReadonlyArray<ChatAttachment>
+ >();
+ const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
+ return (
+ message: ChatMessage,
+ previewUrlFor: (attachment: ChatAttachment) => string | undefined,
+ ): ChatMessage => {
+ const source = message.attachments;
+ if (!source || source.length === 0) return message;
+ const previous = attachmentsBySource.get(source) ?? source;
+ let changed: ChatAttachment[] | undefined;
+ let hasOverrides = false;
+ for (const [index, attachment] of source.entries()) {
+ const previewUrl = previewUrlFor(attachment);
+ const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
+ const previousAttachment = previous[index]!;
+ const previousUrl =
+ "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
+ const next =
+ !previewUrl || previewUrl === sourceUrl
+ ? attachment
+ : previewUrl === previousUrl
+ ? previousAttachment
+ : { ...attachment, previewUrl };
+ hasOverrides ||= next !== attachment;
+ if (next !== previousAttachment) {
+ changed ??= previous.slice();
+ changed[index] = next;
+ }
+ }
+ const attachments = hasOverrides ? (changed ?? previous) : source;
+ attachmentsBySource.set(source, attachments);
+ if (attachments === source) {
+ messagesBySource.delete(message);
+ return message;
+ }
+ const previousMessage = messagesBySource.get(message);
+ if (previousMessage?.attachments === attachments) return previousMessage;
+ const result = { ...message, attachments };
+ messagesBySource.set(message, result);
+ return result;
+ };
+}
+
+/** Text and update time do not change a streaming assistant message's timeline structure. */
+export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
+ if (
+ previous.role !== "assistant" ||
+ next.role !== "assistant" ||
+ !previous.streaming ||
+ !next.streaming
+ ) {
+ return false;
+ }
+ const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
+ const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
+ return shallow(previousMetadata, nextMetadata);
+}
+
+function replaceStreamingTimelineMessages(
+ messages: ReadonlyArray<ChatMessage>,
+ previous: TimelineEntriesProjection,
+): TimelineEntry[] | null {
+ if (messages.length !== previous.messages.length) return null;
+ const replacements = new Map<ChatMessage, ChatMessage>();
+ for (const [index, message] of messages.entries()) {
+ const previousMessage = previous.messages[index]!;
+ if (message === previousMessage) continue;
+ if (!isStreamingMessageTextUpdate(previousMessage, message)) return null;
+ replacements.set(previousMessage, message);
+ }
+ if (replacements.size === 0) return previous.entries;
+ return previous.entries.map((entry) => {
+ const replacement = entry.kind === "message" ? replacements.get(entry.message) : undefined;
+ return replacement ? timelineEntryFromMessage(replacement) : entry;
+ });
+}
+
+/** Reuse ordered entries across immutable stream updates. Other changes keep the full sort. */
+export function deriveTimelineEntriesWithState(
+ messages: ReadonlyArray<ChatMessage>,
+ proposedPlans: ReadonlyArray<ProposedPlan>,
+ workEntries: ReadonlyArray<WorkLogEntry>,
+ previous: TimelineEntriesProjection | null = null,
+): TimelineEntriesProjection {
+ if (
+ previous !== null &&
+ previous.proposedPlans.length === proposedPlans.length &&
+ previous.workEntries.length === workEntries.length &&
+ hasExactArrayPrefix(previous.proposedPlans, proposedPlans) &&
+ hasExactArrayPrefix(previous.workEntries, workEntries)
+ ) {
+ const entries = replaceStreamingTimelineMessages(messages, previous);
+ if (entries !== null) return { messages, proposedPlans, workEntries, entries };
+ }
+ const canAppend =
+ previous !== null &&
+ hasExactArrayPrefix(previous.messages, messages) &&
+ hasExactArrayPrefix(previous.proposedPlans, proposedPlans) &&
+ hasExactArrayPrefix(previous.workEntries, workEntries);
+
+ if (canAppend) {
+ const messageRows = messages.slice(previous.messages.length).map(timelineEntryFromMessage);
+ const proposedPlanRows = proposedPlans
+ .slice(previous.proposedPlans.length)
+ .map(timelineEntryFromProposedPlan);
+ const workRows = workEntries.slice(previous.workEntries.length).map(timelineEntryFromWork);
+ const suffix = [...messageRows, ...proposedPlanRows, ...workRows].toSorted(
+ compareTimelineEntriesByCreatedAt,
+ );
+ return {
+ messages,
+ proposedPlans,
+ workEntries,
+ entries: mergeTimelineEntrySuffix(previous.entries, suffix),
+ };
+ }
+
+ const messageRows = messages.map(timelineEntryFromMessage);
+ const proposedPlanRows = proposedPlans.map(timelineEntryFromProposedPlan);
+ const workRows = workEntries.map(timelineEntryFromWork);
+ return {
+ messages,
+ proposedPlans,
+ workEntries,
+ entries: [...messageRows, ...proposedPlanRows, ...workRows].toSorted(
+ compareTimelineEntriesByCreatedAt,
+ ),
+ };
+}
+
+export function deriveTimelineEntries(
+ messages: ReadonlyArray<ChatMessage>,
+ proposedPlans: ReadonlyArray<ProposedPlan>,
+ workEntries: ReadonlyArray<WorkLogEntry>,
+): TimelineEntry[] {
+ return deriveTimelineEntriesWithState(messages, proposedPlans, workEntries).entries;
}
export function inferCheckpointTurnCountByTurnId(