Open History to see the last commit
1import * as Equal from "effect/Equal";
2import { formatDuration, type TimelineEntry, type WorkLogEntry } from "../../session-logic";
3import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
4import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
5
6export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
7
8function computeElapsedMs(startIso: string, endIso: string): number | null {
9 const start = Date.parse(startIso);
10 const end = Date.parse(endIso);
11 if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
12 return Math.max(0, end - start);
13}
14
15function maxIsoTimestamp(a: string | null, b: string | null): string | null {
16 if (a === null) return b;
17 if (b === null) return a;
18 const aMs = Date.parse(a);
19 const bMs = Date.parse(b);
20 if (!Number.isFinite(aMs)) return b;
21 if (!Number.isFinite(bMs)) return a;
22 return bMs > aMs ? b : a;
23}
24
25export interface TimelineDurationMessage {
26 id: string;
27 role: "user" | "assistant" | "system";
28 createdAt: string;
29 updatedAt: string;
30 streaming: boolean;
31}
32
33export type TimelineLatestTurn = Pick<
34 OrchestrationLatestTurn,
35 "turnId" | "state" | "startedAt" | "completedAt"
36>;
37
38export type MessagesTimelineRow =
39 | {
40 kind: "work";
41 id: string;
42 createdAt: string;
43 groupedEntries: WorkLogEntry[];
44 }
45 | {
46 kind: "turn-fold";
47 id: string;
48 createdAt: string;
49 turnId: TurnId;
50 label: string;
51 expanded: boolean;
52 }
53 | {
54 kind: "message";
55 id: string;
56 createdAt: string;
57 message: ChatMessage;
58 durationStart: string;
59 showAssistantMeta: boolean;
60 showAssistantCopyButton: boolean;
61 assistantCopyStreaming: boolean;
62 assistantTurnDiffSummary?: TurnDiffSummary | undefined;
63 revertTurnCount?: number | undefined;
64 }
65 | {
66 kind: "proposed-plan";
67 id: string;
68 createdAt: string;
69 proposedPlan: ProposedPlan;
70 }
71 | { kind: "working"; id: string; createdAt: string | null };
72
73export interface StableMessagesTimelineRowsState {
74 byId: Map<string, MessagesTimelineRow>;
75 result: MessagesTimelineRow[];
76}
77
78export function computeMessageDurationStart(
79 messages: ReadonlyArray<TimelineDurationMessage>,
80): Map<string, string> {
81 const result = new Map<string, string>();
82 let lastBoundary: string | null = null;
83
84 for (const message of messages) {
85 if (message.role === "user") {
86 lastBoundary = message.createdAt;
87 }
88 result.set(message.id, lastBoundary ?? message.createdAt);
89 if (message.role === "assistant" && !message.streaming) {
90 lastBoundary = message.updatedAt;
91 }
92 }
93
94 return result;
95}
96
97export function normalizeCompactToolLabel(value: string): string {
98 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
99}
100
101export function resolveAssistantMessageCopyState({
102 text,
103 showCopyButton,
104 streaming,
105}: {
106 text: string | null;
107 showCopyButton: boolean;
108 streaming: boolean;
109}) {
110 const hasText = text !== null && text.trim().length > 0;
111 return {
112 text: hasText ? text : null,
113 visible: showCopyButton && hasText && !streaming,
114 };
115}
116
117function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<TimelineEntry>) {
118 const lastAssistantMessageIdByResponseKey = new Map<string, string>();
119 let nullTurnResponseIndex = 0;
120
121 for (const timelineEntry of timelineEntries) {
122 if (timelineEntry.kind !== "message") {
123 continue;
124 }
125 const { message } = timelineEntry;
126 if (message.role === "user") {
127 nullTurnResponseIndex += 1;
128 continue;
129 }
130 if (message.role !== "assistant") {
131 continue;
132 }
133
134 const responseKey = message.turnId
135 ? `turn:${message.turnId}`
136 : `unkeyed:${nullTurnResponseIndex}`;
137 lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
138 }
139
140 return new Set(lastAssistantMessageIdByResponseKey.values());
141}
142
143interface TurnFold {
144 turnId: TurnId;
145 anchorEntryId: string;
146 createdAt: string;
147 hiddenEntryIds: ReadonlySet<string>;
148 label: string;
149}
150
151/**
152 * The session's running turn is authoritative when latestTurn briefly lags or
153 * regresses behind it. Otherwise, the latest turn counts as unsettled while it
154 * is still running (or has not recorded a completion). This is deliberately
155 * keyed on turn lifecycle rather than transient working state: right after the
156 * user sends a message, the previous turn is still the "active" one until the
157 * server creates the new turn, and folding must not flicker through that window.
158 */
159function deriveUnsettledTurnId(
160 latestTurn: TimelineLatestTurn | null,
161 runningTurnId: TurnId | null,
162): TurnId | null {
163 if (runningTurnId !== null) {
164 return runningTurnId;
165 }
166 if (!latestTurn) {
167 return null;
168 }
169 const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running";
170 return isSettled ? null : latestTurn.turnId;
171}
172
173/**
174 * Settled turns fold their commentary and tool activity behind a
175 * "Worked for ..." row anchored at the turn's first foldable entry; the
176 * terminal assistant message stays visible below the fold.
177 */
178function deriveTurnFolds(input: {
179 timelineEntries: ReadonlyArray<TimelineEntry>;
180 terminalAssistantMessageIds: ReadonlySet<string>;
181 latestTurn: TimelineLatestTurn | null;
182 unsettledTurnId: TurnId | null;
183}): ReadonlyMap<string, TurnFold> {
184 interface TurnGroup {
185 entries: Array<TimelineEntry>;
186 terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
187 hasStreamingMessage: boolean;
188 /**
189 * The user message that kicked the turn off. Entry timestamps alone
190 * undercount the duration (the first entry appears only once the
191 * provider starts producing output), and a turn cut short by a steer may
192 * hold a single instantaneous commentary message.
193 */
194 startBoundary: string | null;
195 }
196 const groupsByTurnId = new Map<TurnId, TurnGroup>();
197
198 let pendingUserBoundary: string | null = null;
199 for (const entry of input.timelineEntries) {
200 if (entry.kind === "message" && entry.message.role === "user") {
201 pendingUserBoundary = entry.message.createdAt;
202 continue;
203 }
204 const turnId =
205 entry.kind === "message" && entry.message.role === "assistant"
206 ? (entry.message.turnId ?? null)
207 : entry.kind === "work"
208 ? (entry.entry.turnId ?? null)
209 : null;
210 if (!turnId) {
211 continue;
212 }
213 let group = groupsByTurnId.get(turnId);
214 if (!group) {
215 group = {
216 entries: [],
217 terminalEntry: null,
218 hasStreamingMessage: false,
219 // Each user boundary starts at most one turn; a second turn after the
220 // same user message (e.g. a steer-superseded continuation) falls back
221 // to its own first entry.
222 startBoundary: pendingUserBoundary,
223 };
224 pendingUserBoundary = null;
225 groupsByTurnId.set(turnId, group);
226 }
227 group.entries.push(entry);
228 if (entry.kind === "message") {
229 if (input.terminalAssistantMessageIds.has(entry.message.id)) {
230 group.terminalEntry = entry;
231 }
232 if (entry.message.streaming) {
233 group.hasStreamingMessage = true;
234 }
235 }
236 }
237
238 const foldsByAnchorEntryId = new Map<string, TurnFold>();
239 for (const [turnId, group] of groupsByTurnId) {
240 if (turnId === input.unsettledTurnId) {
241 continue;
242 }
243 if (group.hasStreamingMessage) {
244 continue;
245 }
246 const hiddenEntryIds = new Set<string>();
247 for (const entry of group.entries) {
248 if (entry.id !== group.terminalEntry?.id) {
249 hiddenEntryIds.add(entry.id);
250 }
251 }
252 if (hiddenEntryIds.size === 0) {
253 continue;
254 }
255
256 const firstEntry = group.entries[0];
257 const lastEntry = group.entries.at(-1);
258 if (!firstEntry || !lastEntry) {
259 continue;
260 }
261
262 const isLatestInterruptedTurn =
263 input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
264 // A turn cut short by a steer leaves trailing work entries behind its
265 // terminal message — take whichever ended last.
266 const lastEntryEnd =
267 lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
268 const elapsedMs =
269 input.latestTurn?.turnId === turnId &&
270 input.latestTurn.startedAt &&
271 input.latestTurn.completedAt
272 ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
273 : computeElapsedMs(
274 group.startBoundary ?? firstEntry.createdAt,
275 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
276 lastEntryEnd,
277 );
278 const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
279 const label = isLatestInterruptedTurn
280 ? duration
281 ? `You stopped after ${duration}`
282 : "You stopped this response"
283 : duration
284 ? `Worked for ${duration}`
285 : "Worked";
286
287 foldsByAnchorEntryId.set(firstEntry.id, {
288 turnId,
289 anchorEntryId: firstEntry.id,
290 createdAt: firstEntry.createdAt,
291 hiddenEntryIds,
292 label,
293 });
294 }
295 return foldsByAnchorEntryId;
296}
297
298export function deriveMessagesTimelineRows(input: {
299 timelineEntries: ReadonlyArray<TimelineEntry>;
300 latestTurn?: TimelineLatestTurn | null;
301 runningTurnId?: TurnId | null;
302 expandedTurnIds?: ReadonlySet<TurnId>;
303 isWorking: boolean;
304 activeTurnStartedAt: string | null;
305 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
306 revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
307}): MessagesTimelineRow[] {
308 const nextRows: MessagesTimelineRow[] = [];
309 const durationStartByMessageId = computeMessageDurationStart(
310 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
311 );
312 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
313 const unsettledTurnId = deriveUnsettledTurnId(
314 input.latestTurn ?? null,
315 input.runningTurnId ?? null,
316 );
317 const foldsByAnchorEntryId = deriveTurnFolds({
318 timelineEntries: input.timelineEntries,
319 terminalAssistantMessageIds,
320 latestTurn: input.latestTurn ?? null,
321 unsettledTurnId,
322 });
323 const collapsedEntryIds = new Set<string>();
324 for (const fold of foldsByAnchorEntryId.values()) {
325 if (!input.expandedTurnIds?.has(fold.turnId)) {
326 for (const entryId of fold.hiddenEntryIds) {
327 collapsedEntryIds.add(entryId);
328 }
329 }
330 }
331
332 for (let index = 0; index < input.timelineEntries.length; index += 1) {
333 const timelineEntry = input.timelineEntries[index];
334 if (!timelineEntry) {
335 continue;
336 }
337
338 const turnFold = foldsByAnchorEntryId.get(timelineEntry.id);
339 if (turnFold) {
340 nextRows.push({
341 kind: "turn-fold",
342 id: `turn-fold:${turnFold.turnId}`,
343 createdAt: turnFold.createdAt,
344 turnId: turnFold.turnId,
345 label: turnFold.label,
346 expanded: input.expandedTurnIds?.has(turnFold.turnId) ?? false,
347 });
348 }
349
350 if (collapsedEntryIds.has(timelineEntry.id)) {
351 continue;
352 }
353
354 if (timelineEntry.kind === "work") {
355 const groupedEntries = [timelineEntry.entry];
356 let cursor = index + 1;
357 while (cursor < input.timelineEntries.length) {
358 const nextEntry = input.timelineEntries[cursor];
359 if (
360 !nextEntry ||
361 nextEntry.kind !== "work" ||
362 collapsedEntryIds.has(nextEntry.id) ||
363 foldsByAnchorEntryId.has(nextEntry.id)
364 ) {
365 break;
366 }
367 groupedEntries.push(nextEntry.entry);
368 cursor += 1;
369 }
370 nextRows.push({
371 kind: "work",
372 id: timelineEntry.id,
373 createdAt: timelineEntry.createdAt,
374 groupedEntries,
375 });
376 index = cursor - 1;
377 continue;
378 }
379
380 if (timelineEntry.kind === "proposed-plan") {
381 nextRows.push({
382 kind: "proposed-plan",
383 id: timelineEntry.id,
384 createdAt: timelineEntry.createdAt,
385 proposedPlan: timelineEntry.proposedPlan,
386 });
387 continue;
388 }
389
390 const assistantTurnStillInProgress =
391 timelineEntry.message.role === "assistant" &&
392 unsettledTurnId !== null &&
393 timelineEntry.message.turnId === unsettledTurnId;
394
395 const durationStart =
396 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
397
398 // While the turn is still running, the latest assistant message is only
399 // provisionally terminal — withhold the metadata row until the turn
400 // settles so commentary doesn't flash timestamps mid-work.
401 const showAssistantMeta =
402 timelineEntry.message.role === "assistant" &&
403 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
404 !assistantTurnStillInProgress;
405
406 nextRows.push({
407 kind: "message",
408 id: timelineEntry.id,
409 createdAt: timelineEntry.createdAt,
410 message: timelineEntry.message,
411 durationStart,
412 showAssistantMeta,
413 showAssistantCopyButton: showAssistantMeta,
414 assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
415 assistantTurnDiffSummary:
416 timelineEntry.message.role === "assistant"
417 ? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
418 : undefined,
419 revertTurnCount:
420 timelineEntry.message.role === "user"
421 ? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
422 : undefined,
423 });
424 }
425
426 if (input.isWorking) {
427 nextRows.push({
428 kind: "working",
429 id: "working-indicator-row",
430 createdAt: input.activeTurnStartedAt,
431 });
432 }
433
434 return nextRows;
435}
436
437export function computeStableMessagesTimelineRows(
438 rows: MessagesTimelineRow[],
439 previous: StableMessagesTimelineRowsState,
440): StableMessagesTimelineRowsState {
441 const next = new Map<string, MessagesTimelineRow>();
442 let anyChanged = rows.length !== previous.byId.size;
443
444 const result = rows.map((row, index) => {
445 const prevRow = previous.byId.get(row.id);
446 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
447 next.set(row.id, nextRow);
448 if (!anyChanged && previous.result[index] !== nextRow) {
449 anyChanged = true;
450 }
451 return nextRow;
452 });
453
454 return anyChanged ? { byId: next, result } : previous;
455}
456
457/** Shallow field comparison per row variant — avoids deep equality cost. */
458function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
459 if (a.kind !== b.kind || a.id !== b.id) return false;
460
461 switch (a.kind) {
462 case "working":
463 return a.createdAt === (b as typeof a).createdAt;
464
465 case "turn-fold": {
466 const bf = b as typeof a;
467 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
468 }
469
470 case "proposed-plan":
471 return a.proposedPlan === (b as typeof a).proposedPlan;
472
473 case "work":
474 return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
475
476 case "message": {
477 const bm = b as typeof a;
478 return (
479 a.message === bm.message &&
480 a.durationStart === bm.durationStart &&
481 a.showAssistantMeta === bm.showAssistantMeta &&
482 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
483 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
484 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
485 a.revertTurnCount === bm.revertTurnCount
486 );
487 }
488 }
489}