Open History to see the last commit
1import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
2import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
3import { type MessageId } from "@t3tools/contracts";
4
5export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
6
7export interface TimelineDurationMessage {
8 id: string;
9 role: "user" | "assistant" | "system";
10 createdAt: string;
11 completedAt?: string | undefined;
12}
13
14export type MessagesTimelineRow =
15 | {
16 kind: "work";
17 id: string;
18 createdAt: string;
19 groupedEntries: WorkLogEntry[];
20 }
21 | {
22 kind: "message";
23 id: string;
24 createdAt: string;
25 message: ChatMessage;
26 durationStart: string;
27 showCompletionDivider: boolean;
28 showAssistantCopyButton: boolean;
29 assistantTurnDiffSummary?: TurnDiffSummary | undefined;
30 revertTurnCount?: number | undefined;
31 }
32 | {
33 kind: "proposed-plan";
34 id: string;
35 createdAt: string;
36 proposedPlan: ProposedPlan;
37 }
38 | { kind: "working"; id: string; createdAt: string | null };
39
40export interface StableMessagesTimelineRowsState {
41 byId: Map<string, MessagesTimelineRow>;
42 result: MessagesTimelineRow[];
43}
44
45export function computeMessageDurationStart(
46 messages: ReadonlyArray<TimelineDurationMessage>,
47): Map<string, string> {
48 const result = new Map<string, string>();
49 let lastBoundary: string | null = null;
50
51 for (const message of messages) {
52 if (message.role === "user") {
53 lastBoundary = message.createdAt;
54 }
55 result.set(message.id, lastBoundary ?? message.createdAt);
56 if (message.role === "assistant" && message.completedAt) {
57 lastBoundary = message.completedAt;
58 }
59 }
60
61 return result;
62}
63
64export function normalizeCompactToolLabel(value: string): string {
65 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
66}
67
68export function resolveAssistantMessageCopyState({
69 text,
70 showCopyButton,
71 streaming,
72}: {
73 text: string | null;
74 showCopyButton: boolean;
75 streaming: boolean;
76}) {
77 const hasText = text !== null && text.trim().length > 0;
78 return {
79 text: hasText ? text : null,
80 visible: showCopyButton && hasText && !streaming,
81 };
82}
83
84function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<TimelineEntry>) {
85 const lastAssistantMessageIdByResponseKey = new Map<string, string>();
86 let nullTurnResponseIndex = 0;
87
88 for (const timelineEntry of timelineEntries) {
89 if (timelineEntry.kind !== "message") {
90 continue;
91 }
92 const { message } = timelineEntry;
93 if (message.role === "user") {
94 nullTurnResponseIndex += 1;
95 continue;
96 }
97 if (message.role !== "assistant") {
98 continue;
99 }
100
101 const responseKey = message.turnId
102 ? `turn:${message.turnId}`
103 : `unkeyed:${nullTurnResponseIndex}`;
104 lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
105 }
106
107 return new Set(lastAssistantMessageIdByResponseKey.values());
108}
109
110export function deriveMessagesTimelineRows(input: {
111 timelineEntries: ReadonlyArray<TimelineEntry>;
112 completionDividerBeforeEntryId: string | null;
113 isWorking: boolean;
114 activeTurnStartedAt: string | null;
115 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
116 revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
117}): MessagesTimelineRow[] {
118 const nextRows: MessagesTimelineRow[] = [];
119 const durationStartByMessageId = computeMessageDurationStart(
120 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
121 );
122 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
123
124 for (let index = 0; index < input.timelineEntries.length; index += 1) {
125 const timelineEntry = input.timelineEntries[index];
126 if (!timelineEntry) {
127 continue;
128 }
129
130 if (timelineEntry.kind === "work") {
131 const groupedEntries = [timelineEntry.entry];
132 let cursor = index + 1;
133 while (cursor < input.timelineEntries.length) {
134 const nextEntry = input.timelineEntries[cursor];
135 if (!nextEntry || nextEntry.kind !== "work") break;
136 groupedEntries.push(nextEntry.entry);
137 cursor += 1;
138 }
139 nextRows.push({
140 kind: "work",
141 id: timelineEntry.id,
142 createdAt: timelineEntry.createdAt,
143 groupedEntries,
144 });
145 index = cursor - 1;
146 continue;
147 }
148
149 if (timelineEntry.kind === "proposed-plan") {
150 nextRows.push({
151 kind: "proposed-plan",
152 id: timelineEntry.id,
153 createdAt: timelineEntry.createdAt,
154 proposedPlan: timelineEntry.proposedPlan,
155 });
156 continue;
157 }
158
159 nextRows.push({
160 kind: "message",
161 id: timelineEntry.id,
162 createdAt: timelineEntry.createdAt,
163 message: timelineEntry.message,
164 durationStart:
165 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
166 showCompletionDivider:
167 timelineEntry.message.role === "assistant" &&
168 input.completionDividerBeforeEntryId === timelineEntry.id,
169 showAssistantCopyButton:
170 timelineEntry.message.role === "assistant" &&
171 terminalAssistantMessageIds.has(timelineEntry.message.id),
172 assistantTurnDiffSummary:
173 timelineEntry.message.role === "assistant"
174 ? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
175 : undefined,
176 revertTurnCount:
177 timelineEntry.message.role === "user"
178 ? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
179 : undefined,
180 });
181 }
182
183 if (input.isWorking) {
184 nextRows.push({
185 kind: "working",
186 id: "working-indicator-row",
187 createdAt: input.activeTurnStartedAt,
188 });
189 }
190
191 return nextRows;
192}
193
194export 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. */
215function 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}