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