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 "../../appSettings";
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 remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight);
271 return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
272 };
273 return () => {
274 rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = undefined;
275 };
276 }, [rowVirtualizer]);
277 const pendingMeasureFrameRef = useRef<number | null>(null);
278 const onTimelineImageLoad = useCallback(() => {
279 if (pendingMeasureFrameRef.current !== null) return;
280 pendingMeasureFrameRef.current = window.requestAnimationFrame(() => {
281 pendingMeasureFrameRef.current = null;
282 rowVirtualizer.measure();
283 });
284 }, [rowVirtualizer]);
285 useEffect(() => {
286 return () => {
287 const frame = pendingMeasureFrameRef.current;
288 if (frame !== null) {
289 window.cancelAnimationFrame(frame);
290 }
291 };
292 }, []);
293
294 const virtualRows = rowVirtualizer.getVirtualItems();
295 const nonVirtualizedRows = rows.slice(virtualizedRowCount);
296 const [allDirectoriesExpandedByTurnId, setAllDirectoriesExpandedByTurnId] = useState<
297 Record<string, boolean>
298 >({});
299 const onToggleAllDirectories = useCallback((turnId: TurnId) => {
300 setAllDirectoriesExpandedByTurnId((current) => ({
301 ...current,
302 [turnId]: !(current[turnId] ?? true),
303 }));
304 }, []);
305
306 const renderRowContent = (row: TimelineRow) => (
307 <div
308 className="pb-4"
309 data-timeline-row-kind={row.kind}
310 data-message-id={row.kind === "message" ? row.message.id : undefined}
311 data-message-role={row.kind === "message" ? row.message.role : undefined}
312 >
313 {row.kind === "work" &&
314 (() => {
315 const groupId = row.id;
316 const groupedEntries = row.groupedEntries;
317 const isExpanded = expandedWorkGroups[groupId] ?? false;
318 const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
319 const visibleEntries =
320 hasOverflow && !isExpanded
321 ? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
322 : groupedEntries;
323 const hiddenCount = groupedEntries.length - visibleEntries.length;
324 const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
325 const showHeader = hasOverflow || !onlyToolEntries;
326 const groupLabel = onlyToolEntries ? "Tool calls" : "Work log";
327
328 return (
329 <div className="rounded-xl border border-border/45 bg-card/25 px-2 py-1.5">
330 {showHeader && (
331 <div className="mb-1.5 flex items-center justify-between gap-2 px-0.5">
332 <p className="text-[9px] uppercase tracking-[0.16em] text-muted-foreground/55">
333 {groupLabel} ({groupedEntries.length})
334 </p>
335 {hasOverflow && (
336 <button
337 type="button"
338 className="text-[9px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-foreground/75"
339 onClick={() => onToggleWorkGroup(groupId)}
340 >
341 {isExpanded ? "Show less" : `Show ${hiddenCount} more`}
342 </button>
343 )}
344 </div>
345 )}
346 <div className="space-y-0.5">
347 {visibleEntries.map((workEntry) => (
348 <SimpleWorkEntryRow key={`work-row:${workEntry.id}`} workEntry={workEntry} />
349 ))}
350 </div>
351 </div>
352 );
353 })()}
354
355 {row.kind === "message" &&
356 row.message.role === "user" &&
357 (() => {
358 const userImages = row.message.attachments ?? [];
359 const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
360 const terminalContexts = displayedUserMessage.contexts;
361 const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
362 return (
363 <div className="flex justify-end">
364 <div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
365 {userImages.length > 0 && (
366 <div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
367 {userImages.map(
368 (image: NonNullable<TimelineMessage["attachments"]>[number]) => (
369 <div
370 key={image.id}
371 className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
372 >
373 {image.previewUrl ? (
374 <button
375 type="button"
376 className="h-full w-full cursor-zoom-in"
377 aria-label={`Preview ${image.name}`}
378 onClick={() => {
379 const preview = buildExpandedImagePreview(userImages, image.id);
380 if (!preview) return;
381 onImageExpand(preview);
382 }}
383 >
384 <img
385 src={image.previewUrl}
386 alt={image.name}
387 className="h-full max-h-[220px] w-full object-cover"
388 onLoad={onTimelineImageLoad}
389 onError={onTimelineImageLoad}
390 />
391 </button>
392 ) : (
393 <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
394 {image.name}
395 </div>
396 )}
397 </div>
398 ),
399 )}
400 </div>
401 )}
402 {(displayedUserMessage.visibleText.trim().length > 0 ||
403 terminalContexts.length > 0) && (
404 <UserMessageBody
405 text={displayedUserMessage.visibleText}
406 terminalContexts={terminalContexts}
407 />
408 )}
409 <div className="mt-1.5 flex items-center justify-end gap-2">
410 <div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
411 {displayedUserMessage.copyText && (
412 <MessageCopyButton text={displayedUserMessage.copyText} />
413 )}
414 {canRevertAgentWork && (
415 <Button
416 type="button"
417 size="xs"
418 variant="outline"
419 disabled={isRevertingCheckpoint || isWorking}
420 onClick={() => onRevertUserMessage(row.message.id)}
421 title="Revert to this message"
422 >
423 <Undo2Icon className="size-3" />
424 </Button>
425 )}
426 </div>
427 <p className="text-right text-[10px] text-muted-foreground/30">
428 {formatTimestamp(row.message.createdAt, timestampFormat)}
429 </p>
430 </div>
431 </div>
432 </div>
433 );
434 })()}
435
436 {row.kind === "message" &&
437 row.message.role === "assistant" &&
438 (() => {
439 const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
440 return (
441 <>
442 {row.showCompletionDivider && (
443 <div className="my-3 flex items-center gap-3">
444 <span className="h-px flex-1 bg-border" />
445 <span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
446 {completionSummary ? `Response • ${completionSummary}` : "Response"}
447 </span>
448 <span className="h-px flex-1 bg-border" />
449 </div>
450 )}
451 <div className="min-w-0 px-1 py-0.5">
452 <ChatMarkdown
453 text={messageText}
454 cwd={markdownCwd}
455 isStreaming={Boolean(row.message.streaming)}
456 />
457 {(() => {
458 const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
459 if (!turnSummary) return null;
460 const checkpointFiles = turnSummary.files;
461 if (checkpointFiles.length === 0) return null;
462 const summaryStat = summarizeTurnDiffStats(checkpointFiles);
463 const changedFileCountLabel = String(checkpointFiles.length);
464 const allDirectoriesExpanded =
465 allDirectoriesExpandedByTurnId[turnSummary.turnId] ?? true;
466 return (
467 <div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
468 <div className="mb-1.5 flex items-center justify-between gap-2">
469 <p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
470 <span>Changed files ({changedFileCountLabel})</span>
471 {hasNonZeroStat(summaryStat) && (
472 <>
473 <span className="mx-1">•</span>
474 <DiffStatLabel
475 additions={summaryStat.additions}
476 deletions={summaryStat.deletions}
477 />
478 </>
479 )}
480 </p>
481 <div className="flex items-center gap-1.5">
482 <Button
483 type="button"
484 size="xs"
485 variant="outline"
486 onClick={() => onToggleAllDirectories(turnSummary.turnId)}
487 >
488 {allDirectoriesExpanded ? "Collapse all" : "Expand all"}
489 </Button>
490 <Button
491 type="button"
492 size="xs"
493 variant="outline"
494 onClick={() =>
495 onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
496 }
497 >
498 View diff
499 </Button>
500 </div>
501 </div>
502 <ChangedFilesTree
503 key={`changed-files-tree:${turnSummary.turnId}`}
504 turnId={turnSummary.turnId}
505 files={checkpointFiles}
506 allDirectoriesExpanded={allDirectoriesExpanded}
507 resolvedTheme={resolvedTheme}
508 onOpenTurnDiff={onOpenTurnDiff}
509 />
510 </div>
511 );
512 })()}
513 <p className="mt-1.5 text-[10px] text-muted-foreground/30">
514 {formatMessageMeta(
515 row.message.createdAt,
516 row.message.streaming
517 ? formatElapsed(row.durationStart, nowIso)
518 : formatElapsed(row.durationStart, row.message.completedAt),
519 timestampFormat,
520 )}
521 </p>
522 </div>
523 </>
524 );
525 })()}
526
527 {row.kind === "proposed-plan" && (
528 <div className="min-w-0 px-1 py-0.5">
529 <ProposedPlanCard
530 planMarkdown={row.proposedPlan.planMarkdown}
531 cwd={markdownCwd}
532 workspaceRoot={workspaceRoot}
533 />
534 </div>
535 )}
536
537 {row.kind === "working" && (
538 <div className="py-0.5 pl-1.5">
539 <div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70">
540 <span className="inline-flex items-center gap-[3px]">
541 <span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
542 <span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
543 <span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
544 </span>
545 <span>
546 {row.createdAt
547 ? `Working for ${formatWorkingTimer(row.createdAt, nowIso) ?? "0s"}`
548 : "Working..."}
549 </span>
550 </div>
551 </div>
552 )}
553 </div>
554 );
555
556 if (!hasMessages && !isWorking) {
557 return (
558 <div className="flex h-full items-center justify-center">
559 <p className="text-sm text-muted-foreground/30">
560 Send a message to start the conversation.
561 </p>
562 </div>
563 );
564 }
565
566 return (
567 <div
568 ref={timelineRootRef}
569 data-timeline-root="true"
570 className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden"
571 >
572 {virtualizedRowCount > 0 && (
573 <div className="relative" style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
574 {virtualRows.map((virtualRow: VirtualItem) => {
575 const row = rows[virtualRow.index];
576 if (!row) return null;
577
578 return (
579 <div
580 key={`virtual-row:${row.id}`}
581 data-index={virtualRow.index}
582 ref={rowVirtualizer.measureElement}
583 className="absolute left-0 top-0 w-full"
584 style={{ transform: `translateY(${virtualRow.start}px)` }}
585 >
586 {renderRowContent(row)}
587 </div>
588 );
589 })}
590 </div>
591 )}
592
593 {nonVirtualizedRows.map((row) => (
594 <div key={`non-virtual-row:${row.id}`}>{renderRowContent(row)}</div>
595 ))}
596 </div>
597 );
598});
599
600type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
601type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
602type TimelineProposedPlan = Extract<TimelineEntry, { kind: "proposed-plan" }>["proposedPlan"];
603type TimelineWorkEntry = Extract<TimelineEntry, { kind: "work" }>["entry"];
604type TimelineRow =
605 | {
606 kind: "work";
607 id: string;
608 createdAt: string;
609 groupedEntries: TimelineWorkEntry[];
610 }
611 | {
612 kind: "message";
613 id: string;
614 createdAt: string;
615 message: TimelineMessage;
616 durationStart: string;
617 showCompletionDivider: boolean;
618 }
619 | {
620 kind: "proposed-plan";
621 id: string;
622 createdAt: string;
623 proposedPlan: TimelineProposedPlan;
624 }
625 | { kind: "working"; id: string; createdAt: string | null };
626
627function estimateTimelineProposedPlanHeight(proposedPlan: TimelineProposedPlan): number {
628 const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
629 return 120 + Math.min(estimatedLines * 22, 880);
630}
631
632function formatWorkingTimer(startIso: string, endIso: string): string | null {
633 const startedAtMs = Date.parse(startIso);
634 const endedAtMs = Date.parse(endIso);
635 if (!Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs)) {
636 return null;
637 }
638
639 const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
640 if (elapsedSeconds < 60) {
641 return `${elapsedSeconds}s`;
642 }
643
644 const hours = Math.floor(elapsedSeconds / 3600);
645 const minutes = Math.floor((elapsedSeconds % 3600) / 60);
646 const seconds = elapsedSeconds % 60;
647
648 if (hours > 0) {
649 return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
650 }
651
652 return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
653}
654
655function formatMessageMeta(
656 createdAt: string,
657 duration: string | null,
658 timestampFormat: TimestampFormat,
659): string {
660 if (!duration) return formatTimestamp(createdAt, timestampFormat);
661 return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
662}
663
664const UserMessageTerminalContextInlineLabel = memo(
665 function UserMessageTerminalContextInlineLabel(props: { context: ParsedTerminalContextEntry }) {
666 const tooltipText =
667 props.context.body.length > 0
668 ? `${props.context.header}\n${props.context.body}`
669 : props.context.header;
670
671 return <TerminalContextInlineChip label={props.context.header} tooltipText={tooltipText} />;
672 },
673);
674
675const UserMessageBody = memo(function UserMessageBody(props: {
676 text: string;
677 terminalContexts: ParsedTerminalContextEntry[];
678}) {
679 if (props.terminalContexts.length > 0) {
680 const hasEmbeddedInlineLabels = textContainsInlineTerminalContextLabels(
681 props.text,
682 props.terminalContexts,
683 );
684 const inlinePrefix = buildInlineTerminalContextText(props.terminalContexts);
685 const inlineNodes: ReactNode[] = [];
686
687 if (hasEmbeddedInlineLabels) {
688 let cursor = 0;
689
690 for (const context of props.terminalContexts) {
691 const label = formatInlineTerminalContextLabel(context.header);
692 const matchIndex = props.text.indexOf(label, cursor);
693 if (matchIndex === -1) {
694 inlineNodes.length = 0;
695 break;
696 }
697 if (matchIndex > cursor) {
698 inlineNodes.push(
699 <span key={`user-terminal-context-inline-before:${context.header}:${cursor}`}>
700 {props.text.slice(cursor, matchIndex)}
701 </span>,
702 );
703 }
704 inlineNodes.push(
705 <UserMessageTerminalContextInlineLabel
706 key={`user-terminal-context-inline:${context.header}`}
707 context={context}
708 />,
709 );
710 cursor = matchIndex + label.length;
711 }
712
713 if (inlineNodes.length > 0) {
714 if (cursor < props.text.length) {
715 inlineNodes.push(
716 <span key={`user-message-terminal-context-inline-rest:${cursor}`}>
717 {props.text.slice(cursor)}
718 </span>,
719 );
720 }
721
722 return (
723 <div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
724 {inlineNodes}
725 </div>
726 );
727 }
728 }
729
730 for (const context of props.terminalContexts) {
731 inlineNodes.push(
732 <UserMessageTerminalContextInlineLabel
733 key={`user-terminal-context-inline:${context.header}`}
734 context={context}
735 />,
736 );
737 inlineNodes.push(
738 <span key={`user-terminal-context-inline-space:${context.header}`} aria-hidden="true">
739 {" "}
740 </span>,
741 );
742 }
743
744 if (props.text.length > 0) {
745 inlineNodes.push(<span key="user-message-terminal-context-inline-text">{props.text}</span>);
746 } else if (inlinePrefix.length === 0) {
747 return null;
748 }
749
750 return (
751 <div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
752 {inlineNodes}
753 </div>
754 );
755 }
756
757 if (props.text.length === 0) {
758 return null;
759 }
760
761 return (
762 <pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
763 {props.text}
764 </pre>
765 );
766});
767
768function workToneIcon(tone: TimelineWorkEntry["tone"]): {
769 icon: LucideIcon;
770 className: string;
771} {
772 if (tone === "error") {
773 return {
774 icon: CircleAlertIcon,
775 className: "text-foreground/92",
776 };
777 }
778 if (tone === "thinking") {
779 return {
780 icon: BotIcon,
781 className: "text-foreground/92",
782 };
783 }
784 if (tone === "info") {
785 return {
786 icon: CheckIcon,
787 className: "text-foreground/92",
788 };
789 }
790 return {
791 icon: ZapIcon,
792 className: "text-foreground/92",
793 };
794}
795
796function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
797 if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
798 if (tone === "tool") return "text-muted-foreground/70";
799 if (tone === "thinking") return "text-muted-foreground/50";
800 return "text-muted-foreground/40";
801}
802
803function workEntryPreview(
804 workEntry: Pick<TimelineWorkEntry, "detail" | "command" | "changedFiles">,
805) {
806 if (workEntry.command) return workEntry.command;
807 if (workEntry.detail) return workEntry.detail;
808 if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
809 const [firstPath] = workEntry.changedFiles ?? [];
810 if (!firstPath) return null;
811 return workEntry.changedFiles!.length === 1
812 ? firstPath
813 : `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
814}
815
816function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {
817 if (workEntry.requestKind === "command") return TerminalIcon;
818 if (workEntry.requestKind === "file-read") return EyeIcon;
819 if (workEntry.requestKind === "file-change") return SquarePenIcon;
820
821 if (workEntry.itemType === "command_execution" || workEntry.command) {
822 return TerminalIcon;
823 }
824 if (workEntry.itemType === "file_change" || (workEntry.changedFiles?.length ?? 0) > 0) {
825 return SquarePenIcon;
826 }
827 if (workEntry.itemType === "web_search") return GlobeIcon;
828 if (workEntry.itemType === "image_view") return EyeIcon;
829
830 switch (workEntry.itemType) {
831 case "mcp_tool_call":
832 return WrenchIcon;
833 case "dynamic_tool_call":
834 case "collab_agent_tool_call":
835 return HammerIcon;
836 }
837
838 return workToneIcon(workEntry.tone).icon;
839}
840
841function capitalizePhrase(value: string): string {
842 const trimmed = value.trim();
843 if (trimmed.length === 0) {
844 return value;
845 }
846 return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
847}
848
849function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
850 if (!workEntry.toolTitle) {
851 return capitalizePhrase(normalizeCompactToolLabel(workEntry.label));
852 }
853 return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle));
854}
855
856const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
857 workEntry: TimelineWorkEntry;
858}) {
859 const { workEntry } = props;
860 const iconConfig = workToneIcon(workEntry.tone);
861 const EntryIcon = workEntryIcon(workEntry);
862 const heading = toolWorkEntryHeading(workEntry);
863 const preview = workEntryPreview(workEntry);
864 const displayText = preview ? `${heading} - ${preview}` : heading;
865 const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
866 const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail;
867
868 return (
869 <div className="rounded-lg px-1 py-1">
870 <div className="flex items-center gap-2 transition-[opacity,translate] duration-200">
871 <span
872 className={cn("flex size-5 shrink-0 items-center justify-center", iconConfig.className)}
873 >
874 <EntryIcon className="size-3" />
875 </span>
876 <div className="min-w-0 flex-1 overflow-hidden">
877 <p
878 className={cn(
879 "truncate text-[11px] leading-5",
880 workToneClass(workEntry.tone),
881 preview ? "text-muted-foreground/70" : "",
882 )}
883 title={displayText}
884 >
885 <span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
886 {heading}
887 </span>
888 {preview && <span className="text-muted-foreground/55"> - {preview}</span>}
889 </p>
890 </div>
891 </div>
892 {hasChangedFiles && !previewIsChangedFiles && (
893 <div className="mt-1 flex flex-wrap gap-1 pl-6">
894 {workEntry.changedFiles?.slice(0, 4).map((filePath) => (
895 <span
896 key={`${workEntry.id}:${filePath}`}
897 className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
898 title={filePath}
899 >
900 {filePath}
901 </span>
902 ))}
903 {(workEntry.changedFiles?.length ?? 0) > 4 && (
904 <span className="px-1 text-[10px] text-muted-foreground/55">
905 +{(workEntry.changedFiles?.length ?? 0) - 4}
906 </span>
907 )}
908 </div>
909 )}
910 </div>
911 );
912});