Open History to see the last commit
1import { type MessageId, type TurnId } from "@t3tools/contracts";
2import {
3 memo,
4 useCallback,
5 useEffect,
6 useLayoutEffect,
7 useMemo,
8 useRef,
9 useState,
10 type ReactNode,
11} from "react";
12import {
13 measureElement as measureVirtualElement,
14 type VirtualItem,
15 useVirtualizer,
16} from "@tanstack/react-virtual";
17import { deriveTimelineEntries, formatElapsed } from "../../session-logic";
18import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX } from "../../chat-scroll";
19import { type TurnDiffSummary } from "../../types";
20import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
21import ChatMarkdown from "../ChatMarkdown";
22import {
23 BotIcon,
24 CheckIcon,
25 CircleAlertIcon,
26 EyeIcon,
27 GlobeIcon,
28 HammerIcon,
29 type LucideIcon,
30 SquarePenIcon,
31 TerminalIcon,
32 Undo2Icon,
33 WrenchIcon,
34 ZapIcon,
35} from "lucide-react";
36import { Button } from "../ui/button";
37import { clamp } from "effect/Number";
38import { estimateTimelineMessageHeight } from "../timelineHeight";
39import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
40import { ProposedPlanCard } from "./ProposedPlanCard";
41import { ChangedFilesTree } from "./ChangedFilesTree";
42import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
43import { MessageCopyButton } from "./MessageCopyButton";
44import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
45import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
46import {
47 deriveDisplayedUserMessageState,
48 type ParsedTerminalContextEntry,
49} from "~/lib/terminalContext";
50import { cn } from "~/lib/utils";
51import { type TimestampFormat } from "@t3tools/contracts/settings";
52import { formatTimestamp } from "../../timestampFormat";
53import {
54 buildInlineTerminalContextText,
55 formatInlineTerminalContextLabel,
56 textContainsInlineTerminalContextLabels,
57} from "./userMessageTerminalContexts";
58
59const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
60const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
61
62interface MessagesTimelineProps {
63 hasMessages: boolean;
64 isWorking: boolean;
65 activeTurnInProgress: boolean;
66 activeTurnStartedAt: string | null;
67 scrollContainer: HTMLDivElement | null;
68 timelineEntries: ReturnType<typeof deriveTimelineEntries>;
69 completionDividerBeforeEntryId: string | null;
70 completionSummary: string | null;
71 turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
72 nowIso: string;
73 expandedWorkGroups: Record<string, boolean>;
74 onToggleWorkGroup: (groupId: string) => void;
75 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
76 revertTurnCountByUserMessageId: Map<MessageId, number>;
77 onRevertUserMessage: (messageId: MessageId) => void;
78 isRevertingCheckpoint: boolean;
79 onImageExpand: (preview: ExpandedImagePreview) => void;
80 markdownCwd: string | undefined;
81 resolvedTheme: "light" | "dark";
82 timestampFormat: TimestampFormat;
83 workspaceRoot: string | undefined;
84}
85
86export const MessagesTimeline = memo(function MessagesTimeline({
87 hasMessages,
88 isWorking,
89 activeTurnInProgress,
90 activeTurnStartedAt,
91 scrollContainer,
92 timelineEntries,
93 completionDividerBeforeEntryId,
94 completionSummary,
95 turnDiffSummaryByAssistantMessageId,
96 nowIso,
97 expandedWorkGroups,
98 onToggleWorkGroup,
99 onOpenTurnDiff,
100 revertTurnCountByUserMessageId,
101 onRevertUserMessage,
102 isRevertingCheckpoint,
103 onImageExpand,
104 markdownCwd,
105 resolvedTheme,
106 timestampFormat,
107 workspaceRoot,
108}: MessagesTimelineProps) {
109 const timelineRootRef = useRef<HTMLDivElement | null>(null);
110 const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
111
112 useLayoutEffect(() => {
113 const timelineRoot = timelineRootRef.current;
114 if (!timelineRoot) return;
115
116 const updateWidth = (nextWidth: number) => {
117 setTimelineWidthPx((previousWidth) => {
118 if (previousWidth !== null && Math.abs(previousWidth - nextWidth) < 0.5) {
119 return previousWidth;
120 }
121 return nextWidth;
122 });
123 };
124
125 updateWidth(timelineRoot.getBoundingClientRect().width);
126
127 if (typeof ResizeObserver === "undefined") return;
128 const observer = new ResizeObserver(() => {
129 updateWidth(timelineRoot.getBoundingClientRect().width);
130 });
131 observer.observe(timelineRoot);
132 return () => {
133 observer.disconnect();
134 };
135 }, [hasMessages, isWorking]);
136
137 const rows = useMemo<TimelineRow[]>(() => {
138 const nextRows: TimelineRow[] = [];
139 const durationStartByMessageId = computeMessageDurationStart(
140 timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
141 );
142
143 for (let index = 0; index < timelineEntries.length; index += 1) {
144 const timelineEntry = timelineEntries[index];
145 if (!timelineEntry) {
146 continue;
147 }
148
149 if (timelineEntry.kind === "work") {
150 const groupedEntries = [timelineEntry.entry];
151 let cursor = index + 1;
152 while (cursor < timelineEntries.length) {
153 const nextEntry = timelineEntries[cursor];
154 if (!nextEntry || nextEntry.kind !== "work") break;
155 groupedEntries.push(nextEntry.entry);
156 cursor += 1;
157 }
158 nextRows.push({
159 kind: "work",
160 id: timelineEntry.id,
161 createdAt: timelineEntry.createdAt,
162 groupedEntries,
163 });
164 index = cursor - 1;
165 continue;
166 }
167
168 if (timelineEntry.kind === "proposed-plan") {
169 nextRows.push({
170 kind: "proposed-plan",
171 id: timelineEntry.id,
172 createdAt: timelineEntry.createdAt,
173 proposedPlan: timelineEntry.proposedPlan,
174 });
175 continue;
176 }
177
178 nextRows.push({
179 kind: "message",
180 id: timelineEntry.id,
181 createdAt: timelineEntry.createdAt,
182 message: timelineEntry.message,
183 durationStart:
184 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
185 showCompletionDivider:
186 timelineEntry.message.role === "assistant" &&
187 completionDividerBeforeEntryId === timelineEntry.id,
188 });
189 }
190
191 if (isWorking) {
192 nextRows.push({
193 kind: "working",
194 id: "working-indicator-row",
195 createdAt: activeTurnStartedAt,
196 });
197 }
198
199 return nextRows;
200 }, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]);
201
202 const firstUnvirtualizedRowIndex = useMemo(() => {
203 const firstTailRowIndex = Math.max(rows.length - ALWAYS_UNVIRTUALIZED_TAIL_ROWS, 0);
204 if (!activeTurnInProgress) return firstTailRowIndex;
205
206 const turnStartedAtMs =
207 typeof activeTurnStartedAt === "string" ? Date.parse(activeTurnStartedAt) : Number.NaN;
208 let firstCurrentTurnRowIndex = -1;
209 if (!Number.isNaN(turnStartedAtMs)) {
210 firstCurrentTurnRowIndex = rows.findIndex((row) => {
211 if (row.kind === "working") return true;
212 if (!row.createdAt) return false;
213 const rowCreatedAtMs = Date.parse(row.createdAt);
214 return !Number.isNaN(rowCreatedAtMs) && rowCreatedAtMs >= turnStartedAtMs;
215 });
216 }
217
218 if (firstCurrentTurnRowIndex < 0) {
219 firstCurrentTurnRowIndex = rows.findIndex(
220 (row) => row.kind === "message" && row.message.streaming,
221 );
222 }
223
224 if (firstCurrentTurnRowIndex < 0) return firstTailRowIndex;
225
226 for (let index = firstCurrentTurnRowIndex - 1; index >= 0; index -= 1) {
227 const previousRow = rows[index];
228 if (!previousRow || previousRow.kind !== "message") continue;
229 if (previousRow.message.role === "user") {
230 return Math.min(index, firstTailRowIndex);
231 }
232 if (previousRow.message.role === "assistant" && !previousRow.message.streaming) {
233 break;
234 }
235 }
236
237 return Math.min(firstCurrentTurnRowIndex, firstTailRowIndex);
238 }, [activeTurnInProgress, activeTurnStartedAt, rows]);
239
240 const virtualizedRowCount = clamp(firstUnvirtualizedRowIndex, {
241 minimum: 0,
242 maximum: rows.length,
243 });
244
245 const rowVirtualizer = useVirtualizer({
246 count: virtualizedRowCount,
247 getScrollElement: () => scrollContainer,
248 // Use stable row ids so virtual measurements do not leak across thread switches.
249 getItemKey: (index: number) => rows[index]?.id ?? index,
250 estimateSize: (index: number) => {
251 const row = rows[index];
252 if (!row) return 96;
253 if (row.kind === "work") return 112;
254 if (row.kind === "proposed-plan") return estimateTimelineProposedPlanHeight(row.proposedPlan);
255 if (row.kind === "working") return 40;
256 return estimateTimelineMessageHeight(row.message, { timelineWidthPx });
257 },
258 measureElement: measureVirtualElement,
259 useAnimationFrameWithResizeObserver: true,
260 overscan: 8,
261 });
262 useEffect(() => {
263 if (timelineWidthPx === null) return;
264 rowVirtualizer.measure();
265 }, [rowVirtualizer, timelineWidthPx]);
266 useEffect(() => {
267 rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => {
268 const viewportHeight = instance.scrollRect?.height ?? 0;
269 const scrollOffset = instance.scrollOffset ?? 0;
270 const itemIntersectsViewport =
271 item.end > scrollOffset && item.start < scrollOffset + viewportHeight;
272 if (itemIntersectsViewport) {
273 return false;
274 }
275 const remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight);
276 return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
277 };
278 return () => {
279 rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = undefined;
280 };
281 }, [rowVirtualizer]);
282 const pendingMeasureFrameRef = useRef<number | null>(null);
283 const onTimelineImageLoad = useCallback(() => {
284 if (pendingMeasureFrameRef.current !== null) return;
285 pendingMeasureFrameRef.current = window.requestAnimationFrame(() => {
286 pendingMeasureFrameRef.current = null;
287 rowVirtualizer.measure();
288 });
289 }, [rowVirtualizer]);
290 useEffect(() => {
291 return () => {
292 const frame = pendingMeasureFrameRef.current;
293 if (frame !== null) {
294 window.cancelAnimationFrame(frame);
295 }
296 };
297 }, []);
298
299 const virtualRows = rowVirtualizer.getVirtualItems();
300 const nonVirtualizedRows = rows.slice(virtualizedRowCount);
301 const [allDirectoriesExpandedByTurnId, setAllDirectoriesExpandedByTurnId] = useState<
302 Record<string, boolean>
303 >({});
304 const onToggleAllDirectories = useCallback((turnId: TurnId) => {
305 setAllDirectoriesExpandedByTurnId((current) => ({
306 ...current,
307 [turnId]: !(current[turnId] ?? true),
308 }));
309 }, []);
310
311 const renderRowContent = (row: TimelineRow) => (
312 <div
313 className="pb-4"
314 data-timeline-row-kind={row.kind}
315 data-message-id={row.kind === "message" ? row.message.id : undefined}
316 data-message-role={row.kind === "message" ? row.message.role : undefined}
317 >
318 {row.kind === "work" &&
319 (() => {
320 const groupId = row.id;
321 const groupedEntries = row.groupedEntries;
322 const isExpanded = expandedWorkGroups[groupId] ?? false;
323 const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
324 const visibleEntries =
325 hasOverflow && !isExpanded
326 ? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
327 : groupedEntries;
328 const hiddenCount = groupedEntries.length - visibleEntries.length;
329 const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
330 const showHeader = hasOverflow || !onlyToolEntries;
331 const groupLabel = onlyToolEntries ? "Tool calls" : "Work log";
332
333 return (
334 <div className="rounded-xl border border-border/45 bg-card/25 px-2 py-1.5">
335 {showHeader && (
336 <div className="mb-1.5 flex items-center justify-between gap-2 px-0.5">
337 <p className="text-[9px] uppercase tracking-[0.16em] text-muted-foreground/55">
338 {groupLabel} ({groupedEntries.length})
339 </p>
340 {hasOverflow && (
341 <button
342 type="button"
343 className="text-[9px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-foreground/75"
344 onClick={() => onToggleWorkGroup(groupId)}
345 >
346 {isExpanded ? "Show less" : `Show ${hiddenCount} more`}
347 </button>
348 )}
349 </div>
350 )}
351 <div className="space-y-0.5">
352 {visibleEntries.map((workEntry) => (
353 <SimpleWorkEntryRow key={`work-row:${workEntry.id}`} workEntry={workEntry} />
354 ))}
355 </div>
356 </div>
357 );
358 })()}
359
360 {row.kind === "message" &&
361 row.message.role === "user" &&
362 (() => {
363 const userImages = row.message.attachments ?? [];
364 const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
365 const terminalContexts = displayedUserMessage.contexts;
366 const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
367 return (
368 <div className="flex justify-end">
369 <div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
370 {userImages.length > 0 && (
371 <div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
372 {userImages.map(
373 (image: NonNullable<TimelineMessage["attachments"]>[number]) => (
374 <div
375 key={image.id}
376 className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
377 >
378 {image.previewUrl ? (
379 <button
380 type="button"
381 className="h-full w-full cursor-zoom-in"
382 aria-label={`Preview ${image.name}`}
383 onClick={() => {
384 const preview = buildExpandedImagePreview(userImages, image.id);
385 if (!preview) return;
386 onImageExpand(preview);
387 }}
388 >
389 <img
390 src={image.previewUrl}
391 alt={image.name}
392 className="h-full max-h-[220px] w-full object-cover"
393 onLoad={onTimelineImageLoad}
394 onError={onTimelineImageLoad}
395 />
396 </button>
397 ) : (
398 <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
399 {image.name}
400 </div>
401 )}
402 </div>
403 ),
404 )}
405 </div>
406 )}
407 {(displayedUserMessage.visibleText.trim().length > 0 ||
408 terminalContexts.length > 0) && (
409 <UserMessageBody
410 text={displayedUserMessage.visibleText}
411 terminalContexts={terminalContexts}
412 />
413 )}
414 <div className="mt-1.5 flex items-center justify-end gap-2">
415 <div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
416 {displayedUserMessage.copyText && (
417 <MessageCopyButton text={displayedUserMessage.copyText} />
418 )}
419 {canRevertAgentWork && (
420 <Button
421 type="button"
422 size="xs"
423 variant="outline"
424 disabled={isRevertingCheckpoint || isWorking}
425 onClick={() => onRevertUserMessage(row.message.id)}
426 title="Revert to this message"
427 >
428 <Undo2Icon className="size-3" />
429 </Button>
430 )}
431 </div>
432 <p className="text-right text-[10px] text-muted-foreground/30">
433 {formatTimestamp(row.message.createdAt, timestampFormat)}
434 </p>
435 </div>
436 </div>
437 </div>
438 );
439 })()}
440
441 {row.kind === "message" &&
442 row.message.role === "assistant" &&
443 (() => {
444 const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
445 return (
446 <>
447 {row.showCompletionDivider && (
448 <div className="my-3 flex items-center gap-3">
449 <span className="h-px flex-1 bg-border" />
450 <span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
451 {completionSummary ? `Response • ${completionSummary}` : "Response"}
452 </span>
453 <span className="h-px flex-1 bg-border" />
454 </div>
455 )}
456 <div className="min-w-0 px-1 py-0.5">
457 <ChatMarkdown
458 text={messageText}
459 cwd={markdownCwd}
460 isStreaming={Boolean(row.message.streaming)}
461 />
462 {(() => {
463 const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
464 if (!turnSummary) return null;
465 const checkpointFiles = turnSummary.files;
466 if (checkpointFiles.length === 0) return null;
467 const summaryStat = summarizeTurnDiffStats(checkpointFiles);
468 const changedFileCountLabel = String(checkpointFiles.length);
469 const allDirectoriesExpanded =
470 allDirectoriesExpandedByTurnId[turnSummary.turnId] ?? true;
471 return (
472 <div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
473 <div className="mb-1.5 flex items-center justify-between gap-2">
474 <p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
475 <span>Changed files ({changedFileCountLabel})</span>
476 {hasNonZeroStat(summaryStat) && (
477 <>
478 <span className="mx-1">•</span>
479 <DiffStatLabel
480 additions={summaryStat.additions}
481 deletions={summaryStat.deletions}
482 />
483 </>
484 )}
485 </p>
486 <div className="flex items-center gap-1.5">
487 <Button
488 type="button"
489 size="xs"
490 variant="outline"
491 data-scroll-anchor-ignore
492 onClick={() => onToggleAllDirectories(turnSummary.turnId)}
493 >
494 {allDirectoriesExpanded ? "Collapse all" : "Expand all"}
495 </Button>
496 <Button
497 type="button"
498 size="xs"
499 variant="outline"
500 onClick={() =>
501 onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
502 }
503 >
504 View diff
505 </Button>
506 </div>
507 </div>
508 <ChangedFilesTree
509 key={`changed-files-tree:${turnSummary.turnId}`}
510 turnId={turnSummary.turnId}
511 files={checkpointFiles}
512 allDirectoriesExpanded={allDirectoriesExpanded}
513 resolvedTheme={resolvedTheme}
514 onOpenTurnDiff={onOpenTurnDiff}
515 />
516 </div>
517 );
518 })()}
519 <p className="mt-1.5 text-[10px] text-muted-foreground/30">
520 {formatMessageMeta(
521 row.message.createdAt,
522 row.message.streaming
523 ? formatElapsed(row.durationStart, nowIso)
524 : formatElapsed(row.durationStart, row.message.completedAt),
525 timestampFormat,
526 )}
527 </p>
528 </div>
529 </>
530 );
531 })()}
532
533 {row.kind === "proposed-plan" && (
534 <div className="min-w-0 px-1 py-0.5">
535 <ProposedPlanCard
536 planMarkdown={row.proposedPlan.planMarkdown}
537 cwd={markdownCwd}
538 workspaceRoot={workspaceRoot}
539 />
540 </div>
541 )}
542
543 {row.kind === "working" && (
544 <div className="py-0.5 pl-1.5">
545 <div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70">
546 <span className="inline-flex items-center gap-[3px]">
547 <span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
548 <span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
549 <span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
550 </span>
551 <span>
552 {row.createdAt
553 ? `Working for ${formatWorkingTimer(row.createdAt, nowIso) ?? "0s"}`
554 : "Working..."}
555 </span>
556 </div>
557 </div>
558 )}
559 </div>
560 );
561
562 if (!hasMessages && !isWorking) {
563 return (
564 <div className="flex h-full items-center justify-center">
565 <p className="text-sm text-muted-foreground/30">
566 Send a message to start the conversation.
567 </p>
568 </div>
569 );
570 }
571
572 return (
573 <div
574 ref={timelineRootRef}
575 data-timeline-root="true"
576 className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden"
577 >
578 {virtualizedRowCount > 0 && (
579 <div className="relative" style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
580 {virtualRows.map((virtualRow: VirtualItem) => {
581 const row = rows[virtualRow.index];
582 if (!row) return null;
583
584 return (
585 <div
586 key={`virtual-row:${row.id}`}
587 data-index={virtualRow.index}
588 ref={rowVirtualizer.measureElement}
589 className="absolute left-0 top-0 w-full"
590 style={{ transform: `translateY(${virtualRow.start}px)` }}
591 >
592 {renderRowContent(row)}
593 </div>
594 );
595 })}
596 </div>
597 )}
598
599 {nonVirtualizedRows.map((row) => (
600 <div key={`non-virtual-row:${row.id}`}>{renderRowContent(row)}</div>
601 ))}
602 </div>
603 );
604});
605
606type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
607type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
608type TimelineProposedPlan = Extract<TimelineEntry, { kind: "proposed-plan" }>["proposedPlan"];
609type TimelineWorkEntry = Extract<TimelineEntry, { kind: "work" }>["entry"];
610type TimelineRow =
611 | {
612 kind: "work";
613 id: string;
614 createdAt: string;
615 groupedEntries: TimelineWorkEntry[];
616 }
617 | {
618 kind: "message";
619 id: string;
620 createdAt: string;
621 message: TimelineMessage;
622 durationStart: string;
623 showCompletionDivider: boolean;
624 }
625 | {
626 kind: "proposed-plan";
627 id: string;
628 createdAt: string;
629 proposedPlan: TimelineProposedPlan;
630 }
631 | { kind: "working"; id: string; createdAt: string | null };
632
633function estimateTimelineProposedPlanHeight(proposedPlan: TimelineProposedPlan): number {
634 const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
635 return 120 + Math.min(estimatedLines * 22, 880);
636}
637
638function formatWorkingTimer(startIso: string, endIso: string): string | null {
639 const startedAtMs = Date.parse(startIso);
640 const endedAtMs = Date.parse(endIso);
641 if (!Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs)) {
642 return null;
643 }
644
645 const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
646 if (elapsedSeconds < 60) {
647 return `${elapsedSeconds}s`;
648 }
649
650 const hours = Math.floor(elapsedSeconds / 3600);
651 const minutes = Math.floor((elapsedSeconds % 3600) / 60);
652 const seconds = elapsedSeconds % 60;
653
654 if (hours > 0) {
655 return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
656 }
657
658 return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
659}
660
661function formatMessageMeta(
662 createdAt: string,
663 duration: string | null,
664 timestampFormat: TimestampFormat,
665): string {
666 if (!duration) return formatTimestamp(createdAt, timestampFormat);
667 return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
668}
669
670const UserMessageTerminalContextInlineLabel = memo(
671 function UserMessageTerminalContextInlineLabel(props: { context: ParsedTerminalContextEntry }) {
672 const tooltipText =
673 props.context.body.length > 0
674 ? `${props.context.header}\n${props.context.body}`
675 : props.context.header;
676
677 return <TerminalContextInlineChip label={props.context.header} tooltipText={tooltipText} />;
678 },
679);
680
681const UserMessageBody = memo(function UserMessageBody(props: {
682 text: string;
683 terminalContexts: ParsedTerminalContextEntry[];
684}) {
685 if (props.terminalContexts.length > 0) {
686 const hasEmbeddedInlineLabels = textContainsInlineTerminalContextLabels(
687 props.text,
688 props.terminalContexts,
689 );
690 const inlinePrefix = buildInlineTerminalContextText(props.terminalContexts);
691 const inlineNodes: ReactNode[] = [];
692
693 if (hasEmbeddedInlineLabels) {
694 let cursor = 0;
695
696 for (const context of props.terminalContexts) {
697 const label = formatInlineTerminalContextLabel(context.header);
698 const matchIndex = props.text.indexOf(label, cursor);
699 if (matchIndex === -1) {
700 inlineNodes.length = 0;
701 break;
702 }
703 if (matchIndex > cursor) {
704 inlineNodes.push(
705 <span key={`user-terminal-context-inline-before:${context.header}:${cursor}`}>
706 {props.text.slice(cursor, matchIndex)}
707 </span>,
708 );
709 }
710 inlineNodes.push(
711 <UserMessageTerminalContextInlineLabel
712 key={`user-terminal-context-inline:${context.header}`}
713 context={context}
714 />,
715 );
716 cursor = matchIndex + label.length;
717 }
718
719 if (inlineNodes.length > 0) {
720 if (cursor < props.text.length) {
721 inlineNodes.push(
722 <span key={`user-message-terminal-context-inline-rest:${cursor}`}>
723 {props.text.slice(cursor)}
724 </span>,
725 );
726 }
727
728 return (
729 <div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
730 {inlineNodes}
731 </div>
732 );
733 }
734 }
735
736 for (const context of props.terminalContexts) {
737 inlineNodes.push(
738 <UserMessageTerminalContextInlineLabel
739 key={`user-terminal-context-inline:${context.header}`}
740 context={context}
741 />,
742 );
743 inlineNodes.push(
744 <span key={`user-terminal-context-inline-space:${context.header}`} aria-hidden="true">
745 {" "}
746 </span>,
747 );
748 }
749
750 if (props.text.length > 0) {
751 inlineNodes.push(<span key="user-message-terminal-context-inline-text">{props.text}</span>);
752 } else if (inlinePrefix.length === 0) {
753 return null;
754 }
755
756 return (
757 <div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
758 {inlineNodes}
759 </div>
760 );
761 }
762
763 if (props.text.length === 0) {
764 return null;
765 }
766
767 return (
768 <pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
769 {props.text}
770 </pre>
771 );
772});
773
774function workToneIcon(tone: TimelineWorkEntry["tone"]): {
775 icon: LucideIcon;
776 className: string;
777} {
778 if (tone === "error") {
779 return {
780 icon: CircleAlertIcon,
781 className: "text-foreground/92",
782 };
783 }
784 if (tone === "thinking") {
785 return {
786 icon: BotIcon,
787 className: "text-foreground/92",
788 };
789 }
790 if (tone === "info") {
791 return {
792 icon: CheckIcon,
793 className: "text-foreground/92",
794 };
795 }
796 return {
797 icon: ZapIcon,
798 className: "text-foreground/92",
799 };
800}
801
802function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
803 if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
804 if (tone === "tool") return "text-muted-foreground/70";
805 if (tone === "thinking") return "text-muted-foreground/50";
806 return "text-muted-foreground/40";
807}
808
809function workEntryPreview(
810 workEntry: Pick<TimelineWorkEntry, "detail" | "command" | "changedFiles">,
811) {
812 if (workEntry.command) return workEntry.command;
813 if (workEntry.detail) return workEntry.detail;
814 if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
815 const [firstPath] = workEntry.changedFiles ?? [];
816 if (!firstPath) return null;
817 return workEntry.changedFiles!.length === 1
818 ? firstPath
819 : `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
820}
821
822function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {
823 if (workEntry.requestKind === "command") return TerminalIcon;
824 if (workEntry.requestKind === "file-read") return EyeIcon;
825 if (workEntry.requestKind === "file-change") return SquarePenIcon;
826
827 if (workEntry.itemType === "command_execution" || workEntry.command) {
828 return TerminalIcon;
829 }
830 if (workEntry.itemType === "file_change" || (workEntry.changedFiles?.length ?? 0) > 0) {
831 return SquarePenIcon;
832 }
833 if (workEntry.itemType === "web_search") return GlobeIcon;
834 if (workEntry.itemType === "image_view") return EyeIcon;
835
836 switch (workEntry.itemType) {
837 case "mcp_tool_call":
838 return WrenchIcon;
839 case "dynamic_tool_call":
840 case "collab_agent_tool_call":
841 return HammerIcon;
842 }
843
844 return workToneIcon(workEntry.tone).icon;
845}
846
847function capitalizePhrase(value: string): string {
848 const trimmed = value.trim();
849 if (trimmed.length === 0) {
850 return value;
851 }
852 return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
853}
854
855function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
856 if (!workEntry.toolTitle) {
857 return capitalizePhrase(normalizeCompactToolLabel(workEntry.label));
858 }
859 return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle));
860}
861
862const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
863 workEntry: TimelineWorkEntry;
864}) {
865 const { workEntry } = props;
866 const iconConfig = workToneIcon(workEntry.tone);
867 const EntryIcon = workEntryIcon(workEntry);
868 const heading = toolWorkEntryHeading(workEntry);
869 const preview = workEntryPreview(workEntry);
870 const displayText = preview ? `${heading} - ${preview}` : heading;
871 const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
872 const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail;
873
874 return (
875 <div className="rounded-lg px-1 py-1">
876 <div className="flex items-center gap-2 transition-[opacity,translate] duration-200">
877 <span
878 className={cn("flex size-5 shrink-0 items-center justify-center", iconConfig.className)}
879 >
880 <EntryIcon className="size-3" />
881 </span>
882 <div className="min-w-0 flex-1 overflow-hidden">
883 <p
884 className={cn(
885 "truncate text-[11px] leading-5",
886 workToneClass(workEntry.tone),
887 preview ? "text-muted-foreground/70" : "",
888 )}
889 title={displayText}
890 >
891 <span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
892 {heading}
893 </span>
894 {preview && <span className="text-muted-foreground/55"> - {preview}</span>}
895 </p>
896 </div>
897 </div>
898 {hasChangedFiles && !previewIsChangedFiles && (
899 <div className="mt-1 flex flex-wrap gap-1 pl-6">
900 {workEntry.changedFiles?.slice(0, 4).map((filePath) => (
901 <span
902 key={`${workEntry.id}:${filePath}`}
903 className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
904 title={filePath}
905 >
906 {filePath}
907 </span>
908 ))}
909 {(workEntry.changedFiles?.length ?? 0) > 4 && (
910 <span className="px-1 text-[10px] text-muted-foreground/55">
911 +{(workEntry.changedFiles?.length ?? 0) - 4}
912 </span>
913 )}
914 </div>
915 )}
916 </div>
917 );
918});