Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MessagesTimeline.tsx

1,021 lines36.1 KB

1import { type EnvironmentId, type MessageId, type TurnId } from "@t3tools/contracts";
2import {
3 createContext,
4 memo,
5 use,
6 useCallback,
7 useEffect,
8 useMemo,
9 useRef,
10 useState,
11 type ReactNode,
12} from "react";
13import { LegendList, type LegendListRef } from "@legendapp/list/react";
14import { deriveTimelineEntries, formatElapsed } from "../../session-logic";
15import { type TurnDiffSummary } from "../../types";
16import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
17import ChatMarkdown from "../ChatMarkdown";
18import {
19 BotIcon,
20 CheckIcon,
21 CircleAlertIcon,
22 EyeIcon,
23 GlobeIcon,
24 HammerIcon,
25 type LucideIcon,
26 SquarePenIcon,
27 TerminalIcon,
28 Undo2Icon,
29 WrenchIcon,
30 ZapIcon,
31} from "lucide-react";
32import { Button } from "../ui/button";
33import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
34import { ProposedPlanCard } from "./ProposedPlanCard";
35import { ChangedFilesTree } from "./ChangedFilesTree";
36import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
37import { MessageCopyButton } from "./MessageCopyButton";
38import {
39 computeStableMessagesTimelineRows,
40 MAX_VISIBLE_WORK_LOG_ENTRIES,
41 deriveMessagesTimelineRows,
42 normalizeCompactToolLabel,
43 resolveAssistantMessageCopyState,
44 type StableMessagesTimelineRowsState,
45 type MessagesTimelineRow,
46} from "./MessagesTimeline.logic";
47import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
48import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
49import {
50 deriveDisplayedUserMessageState,
51 type ParsedTerminalContextEntry,
52} from "~/lib/terminalContext";
53import { cn } from "~/lib/utils";
54import { useUiStateStore } from "~/uiStateStore";
55import { type TimestampFormat } from "@t3tools/contracts/settings";
56import { formatTimestamp } from "../../timestampFormat";
57​
58import {
59 buildInlineTerminalContextText,
60 formatInlineTerminalContextLabel,
61 textContainsInlineTerminalContextLabels,
62} from "./userMessageTerminalContexts";
63import { formatWorkspaceRelativePath } from "../../filePathDisplay";
64​
65// ---------------------------------------------------------------------------
66// Context — shared state consumed by every row component via useContext.
67// Propagates through LegendList's memo boundaries for shared callbacks and
68// non-row-scoped state. `nowIso` is intentionally excluded — self-ticking
69// components (WorkingTimer, LiveElapsed) handle it.
70// ---------------------------------------------------------------------------
71​
72interface TimelineRowSharedState {
73 activeTurnInProgress: boolean;
74 activeTurnId: TurnId | null | undefined;
75 isWorking: boolean;
76 isRevertingCheckpoint: boolean;
77 completionSummary: string | null;
78 timestampFormat: TimestampFormat;
79 routeThreadKey: string;
80 markdownCwd: string | undefined;
81 resolvedTheme: "light" | "dark";
82 workspaceRoot: string | undefined;
83 activeThreadEnvironmentId: EnvironmentId;
84 onRevertUserMessage: (messageId: MessageId) => void;
85 onImageExpand: (preview: ExpandedImagePreview) => void;
86 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
88​
89const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
90​
91// ---------------------------------------------------------------------------
92// Props (public API)
93// ---------------------------------------------------------------------------
94​
95interface MessagesTimelineProps {
96 isWorking: boolean;
97 activeTurnInProgress: boolean;
98 activeTurnId?: TurnId | null;
99 activeTurnStartedAt: string | null;
100 listRef: React.RefObject<LegendListRef | null>;
101 timelineEntries: ReturnType<typeof deriveTimelineEntries>;
102 completionDividerBeforeEntryId: string | null;
103 completionSummary: string | null;
104 turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
105 routeThreadKey: string;
106 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
107 revertTurnCountByUserMessageId: Map<MessageId, number>;
108 onRevertUserMessage: (messageId: MessageId) => void;
109 isRevertingCheckpoint: boolean;
110 onImageExpand: (preview: ExpandedImagePreview) => void;
111 activeThreadEnvironmentId: EnvironmentId;
112 markdownCwd: string | undefined;
113 resolvedTheme: "light" | "dark";
114 timestampFormat: TimestampFormat;
115 workspaceRoot: string | undefined;
116 onIsAtEndChange: (isAtEnd: boolean) => void;
118​
119// ---------------------------------------------------------------------------
120// MessagesTimeline — list owner
121// ---------------------------------------------------------------------------
122​
123export const MessagesTimeline = memo(function MessagesTimeline({
124 isWorking,
125 activeTurnInProgress,
126 activeTurnId,
127 activeTurnStartedAt,
128 listRef,
129 timelineEntries,
130 completionDividerBeforeEntryId,
131 completionSummary,
132 turnDiffSummaryByAssistantMessageId,
133 routeThreadKey,
134 onOpenTurnDiff,
135 revertTurnCountByUserMessageId,
136 onRevertUserMessage,
137 isRevertingCheckpoint,
138 onImageExpand,
139 activeThreadEnvironmentId,
140 markdownCwd,
141 resolvedTheme,
142 timestampFormat,
143 workspaceRoot,
144 onIsAtEndChange,
145}: MessagesTimelineProps) {
146 const rawRows = useMemo(
147 () =>
148 deriveMessagesTimelineRows({
149 timelineEntries,
150 completionDividerBeforeEntryId,
151 isWorking,
152 activeTurnStartedAt,
153 turnDiffSummaryByAssistantMessageId,
154 revertTurnCountByUserMessageId,
155 }),
156 [
157 timelineEntries,
158 completionDividerBeforeEntryId,
159 isWorking,
160 activeTurnStartedAt,
161 turnDiffSummaryByAssistantMessageId,
162 revertTurnCountByUserMessageId,
163 ],
164 );
165 const rows = useStableRows(rawRows);
166​
167 const handleScroll = useCallback(() => {
168 const state = listRef.current?.getState?.();
169 if (state) {
170 onIsAtEndChange(state.isAtEnd);
171 }
172 }, [listRef, onIsAtEndChange]);
173​
174 const previousRowCountRef = useRef(rows.length);
175 useEffect(() => {
176 const previousRowCount = previousRowCountRef.current;
177 previousRowCountRef.current = rows.length;
178​
179 if (previousRowCount > 0 || rows.length === 0) {
180 return;
181 }
182​
183 onIsAtEndChange(true);
184 const frameId = window.requestAnimationFrame(() => {
185 void listRef.current?.scrollToEnd?.({ animated: false });
186 });
187 return () => {
188 window.cancelAnimationFrame(frameId);
189 };
190 }, [listRef, onIsAtEndChange, rows.length]);
191​
192 // Memoised context value — only changes on state transitions, NOT on
193 // every streaming chunk. Callbacks from ChatView are useCallback-stable.
194 const sharedState = useMemo<TimelineRowSharedState>(
195 () => ({
196 activeTurnInProgress,
197 activeTurnId: activeTurnId ?? null,
198 isWorking,
199 isRevertingCheckpoint,
200 completionSummary,
201 timestampFormat,
202 routeThreadKey,
203 markdownCwd,
204 resolvedTheme,
205 workspaceRoot,
206 activeThreadEnvironmentId,
207 onRevertUserMessage,
208 onImageExpand,
209 onOpenTurnDiff,
210 }),
211 [
212 activeTurnInProgress,
213 activeTurnId,
214 isWorking,
215 isRevertingCheckpoint,
216 completionSummary,
217 timestampFormat,
218 routeThreadKey,
219 markdownCwd,
220 resolvedTheme,
221 workspaceRoot,
222 activeThreadEnvironmentId,
223 onRevertUserMessage,
224 onImageExpand,
225 onOpenTurnDiff,
226 ],
227 );
228​
229 // Stable renderItem — no closure deps. Row components read shared state
230 // from TimelineRowCtx, which propagates through LegendList's memo.
231 const renderItem = useCallback(
232 ({ item }: { item: MessagesTimelineRow }) => (
233 <div className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden" data-timeline-root="true">
234 <TimelineRowContent row={item} />
235 </div>
236 ),
237 [],
238 );
239​
240 if (rows.length === 0 && !isWorking) {
241 return (
242 <div className="flex h-full items-center justify-center">
243 <p className="text-sm text-muted-foreground/30">
244 Send a message to start the conversation.
245 </p>
246 </div>
247 );
248 }
249​
250 return (
251 <TimelineRowCtx.Provider value={sharedState}>
252 <LegendList<MessagesTimelineRow>
253 ref={listRef}
254 data={rows}
255 keyExtractor={keyExtractor}
256 renderItem={renderItem}
257 estimatedItemSize={90}
258 initialScrollAtEnd
259 maintainScrollAtEnd
260 maintainScrollAtEndThreshold={0.1}
261 maintainVisibleContentPosition
262 onScroll={handleScroll}
263 className="h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
264 ListHeaderComponent={<div className="h-3 sm:h-4" />}
265 ListFooterComponent={<div className="h-3 sm:h-4" />}
266 />
267 </TimelineRowCtx.Provider>
268 );
269});
270​
271function keyExtractor(item: MessagesTimelineRow) {
272 return item.id;
274​
275// ---------------------------------------------------------------------------
276// TimelineRowContent — the actual row component
277// ---------------------------------------------------------------------------
278​
279type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
280type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
281type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
282type TimelineRow = MessagesTimelineRow;
283​
284function TimelineRowContent({ row }: { row: TimelineRow }) {
285 const ctx = use(TimelineRowCtx);
286​
287 return (
288 <div
289 className={cn(
290 "pb-4",
291 row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null,
292 )}
293 data-timeline-row-id={row.id}
294 data-timeline-row-kind={row.kind}
295 data-message-id={row.kind === "message" ? row.message.id : undefined}
296 data-message-role={row.kind === "message" ? row.message.role : undefined}
297 >
298 {row.kind === "work" && <WorkGroupSection groupedEntries={row.groupedEntries} />}
299​
300 {row.kind === "message" &&
301 row.message.role === "user" &&
302 (() => {
303 const userImages = row.message.attachments ?? [];
304 const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
305 const terminalContexts = displayedUserMessage.contexts;
306 const canRevertAgentWork = typeof row.revertTurnCount === "number";
307 return (
308 <div className="flex justify-end">
309 <div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
310 {userImages.length > 0 && (
311 <div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
312 {userImages.map(
313 (image: NonNullable<TimelineMessage["attachments"]>[number]) => (
314 <div
315 key={image.id}
316 className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
317 >
318 {image.previewUrl ? (
319 <button
320 type="button"
321 className="h-full w-full cursor-zoom-in"
322 aria-label={`Preview ${image.name}`}
323 onClick={() => {
324 const preview = buildExpandedImagePreview(userImages, image.id);
325 if (!preview) return;
326 ctx.onImageExpand(preview);
327 }}
328 >
329 <img
330 src={image.previewUrl}
331 alt={image.name}
332 className="block h-auto max-h-[220px] w-full object-cover"
333 />
334 </button>
335 ) : (
336 <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
337 {image.name}
338 </div>
339 )}
340 </div>
341 ),
342 )}
343 </div>
344 )}
345 {(displayedUserMessage.visibleText.trim().length > 0 ||
346 terminalContexts.length > 0) && (
347 <UserMessageBody
348 text={displayedUserMessage.visibleText}
349 terminalContexts={terminalContexts}
350 />
351 )}
352 <div className="mt-1.5 flex items-center justify-end gap-2">
353 <div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
354 {displayedUserMessage.copyText && (
355 <MessageCopyButton text={displayedUserMessage.copyText} />
356 )}
357 {canRevertAgentWork && (
358 <Button
359 type="button"
360 size="xs"
361 variant="outline"
362 disabled={ctx.isRevertingCheckpoint || ctx.isWorking}
363 onClick={() => ctx.onRevertUserMessage(row.message.id)}
364 title="Revert to this message"
365 >
366 <Undo2Icon className="size-3" />
367 </Button>
368 )}
369 </div>
370 <p className="text-right text-xs text-muted-foreground/50">
371 {formatTimestamp(row.message.createdAt, ctx.timestampFormat)}
372 </p>
373 </div>
374 </div>
375 </div>
376 );
377 })()}
378​
379 {row.kind === "message" &&
380 row.message.role === "assistant" &&
381 (() => {
382 const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
383 const assistantTurnStillInProgress =
384 ctx.activeTurnInProgress &&
385 ctx.activeTurnId !== null &&
386 ctx.activeTurnId !== undefined &&
387 row.message.turnId === ctx.activeTurnId;
388 const assistantCopyState = resolveAssistantMessageCopyState({
389 text: row.message.text ?? null,
390 showCopyButton: row.showAssistantCopyButton,
391 streaming: row.message.streaming || assistantTurnStillInProgress,
392 });
393 return (
394 <>
395 {row.showCompletionDivider && (
396 <div className="my-3 flex items-center gap-3">
397 <span className="h-px flex-1 bg-border" />
398 <span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
399 {ctx.completionSummary ? `Response • ${ctx.completionSummary}` : "Response"}
400 </span>
401 <span className="h-px flex-1 bg-border" />
402 </div>
403 )}
404 <div className="min-w-0 px-1 py-0.5">
405 <ChatMarkdown
406 text={messageText}
407 cwd={ctx.markdownCwd}
408 isStreaming={Boolean(row.message.streaming)}
409 />
410 <AssistantChangedFilesSection
411 turnSummary={row.assistantTurnDiffSummary}
412 routeThreadKey={ctx.routeThreadKey}
413 resolvedTheme={ctx.resolvedTheme}
414 onOpenTurnDiff={ctx.onOpenTurnDiff}
415 />
416 <div className="mt-1.5 flex items-center gap-2">
417 <p className="text-[10px] text-muted-foreground/30">
418 {row.message.streaming ? (
419 <LiveMessageMeta
420 createdAt={row.message.createdAt}
421 durationStart={row.durationStart}
422 timestampFormat={ctx.timestampFormat}
423 />
424 ) : (
425 formatMessageMeta(
426 row.message.createdAt,
427 formatElapsed(row.durationStart, row.message.completedAt),
428 ctx.timestampFormat,
429 )
430 )}
431 </p>
432 {assistantCopyState.visible ? (
433 <div className="flex items-center opacity-0 transition-opacity duration-200 group-hover/assistant:opacity-100">
434 <MessageCopyButton
435 text={assistantCopyState.text ?? ""}
436 size="icon-xs"
437 variant="outline"
438 className="border-border/50 bg-background/35 text-muted-foreground/45 shadow-none hover:border-border/70 hover:bg-background/55 hover:text-muted-foreground/70"
439 />
440 </div>
441 ) : null}
442 </div>
443 </div>
444 </>
445 );
446 })()}
447​
448 {row.kind === "proposed-plan" && (
449 <div className="min-w-0 px-1 py-0.5">
450 <ProposedPlanCard
451 planMarkdown={row.proposedPlan.planMarkdown}
452 environmentId={ctx.activeThreadEnvironmentId}
453 cwd={ctx.markdownCwd}
454 workspaceRoot={ctx.workspaceRoot}
455 />
456 </div>
457 )}
458​
459 {row.kind === "working" && (
460 <div className="py-0.5 pl-1.5">
461 <div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70">
462 <span className="inline-flex items-center gap-[3px]">
463 <span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
464 <span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
465 <span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
466 </span>
467 <span>
468 {row.createdAt ? (
469 <>
470 Working for <WorkingTimer createdAt={row.createdAt} />
471 </>
472 ) : (
473 "Working..."
474 )}
475 </span>
476 </div>
477 </div>
478 )}
479 </div>
480 );
482​
483// ---------------------------------------------------------------------------
484// Self-ticking components — bypass LegendList memoisation entirely.
485// Each owns a `nowMs` state value consumed in the render output so the
486// React Compiler cannot elide the re-render as a no-op.
487// ---------------------------------------------------------------------------
488​
489/** Live "Working for Xs" label. */
490function WorkingTimer({ createdAt }: { createdAt: string }) {
491 const [nowMs, setNowMs] = useState(() => Date.now());
492 useEffect(() => {
493 const id = setInterval(() => setNowMs(Date.now()), 1000);
494 return () => clearInterval(id);
495 }, [createdAt]);
496 return <>{formatWorkingTimer(createdAt, new Date(nowMs).toISOString()) ?? "0s"}</>;
498​
499/** Live timestamp + elapsed duration for a streaming assistant message. */
500function LiveMessageMeta({
501 createdAt,
502 durationStart,
503 timestampFormat,
504}: {
505 createdAt: string;
506 durationStart: string | null | undefined;
507 timestampFormat: TimestampFormat;
508}) {
509 const [nowMs, setNowMs] = useState(() => Date.now());
510 useEffect(() => {
511 const id = setInterval(() => setNowMs(Date.now()), 1000);
512 return () => clearInterval(id);
513 }, [durationStart]);
514 const elapsed = durationStart
515 ? formatElapsed(durationStart, new Date(nowMs).toISOString())
516 : null;
517 return <>{formatMessageMeta(createdAt, elapsed, timestampFormat)}</>;
519​
520// ---------------------------------------------------------------------------
521// Extracted row sections — own their state / store subscriptions so changes
522// re-render only the affected row, not the entire list.
523// ---------------------------------------------------------------------------
524​
525/** Owns its own expand/collapse state so toggling re-renders only this row.
526 * State resets on unmount which is fine — work groups start collapsed. */
527const WorkGroupSection = memo(function WorkGroupSection({
528 groupedEntries,
529}: {
530 groupedEntries: Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"];
531}) {
532 const { workspaceRoot } = use(TimelineRowCtx);
533 const [isExpanded, setIsExpanded] = useState(false);
534 const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
535 const visibleEntries =
536 hasOverflow && !isExpanded
537 ? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
538 : groupedEntries;
539 const hiddenCount = groupedEntries.length - visibleEntries.length;
540 const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
541 const showHeader = hasOverflow || !onlyToolEntries;
542 const groupLabel = onlyToolEntries ? "Tool calls" : "Work log";
543​
544 return (
545 <div className="rounded-xl border border-border/45 bg-card/25 px-2 py-1.5">
546 {showHeader && (
547 <div className="mb-1.5 flex items-center justify-between gap-2 px-0.5">
548 <p className="text-[9px] uppercase tracking-[0.16em] text-muted-foreground/55">
549 {groupLabel} ({groupedEntries.length})
550 </p>
551 {hasOverflow && (
552 <button
553 type="button"
554 className="text-[9px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-foreground/75"
555 onClick={() => setIsExpanded((v) => !v)}
556 >
557 {isExpanded ? "Show less" : `Show ${hiddenCount} more`}
558 </button>
559 )}
560 </div>
561 )}
562 <div className="space-y-0.5">
563 {visibleEntries.map((workEntry) => (
564 <SimpleWorkEntryRow
565 key={`work-row:${workEntry.id}`}
566 workEntry={workEntry}
567 workspaceRoot={workspaceRoot}
568 />
569 ))}
570 </div>
571 </div>
572 );
573});
574​
575/** Subscribes directly to the UI state store for expand/collapse state,
576 * so toggling re-renders only this component — not the entire list. */
577const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection({
578 turnSummary,
579 routeThreadKey,
580 resolvedTheme,
581 onOpenTurnDiff,
582}: {
583 turnSummary: TurnDiffSummary | undefined;
584 routeThreadKey: string;
585 resolvedTheme: "light" | "dark";
586 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
587}) {
588 if (!turnSummary) return null;
589 const checkpointFiles = turnSummary.files;
590 if (checkpointFiles.length === 0) return null;
591​
592 return (
593 <AssistantChangedFilesSectionInner
594 turnSummary={turnSummary}
595 checkpointFiles={checkpointFiles}
596 routeThreadKey={routeThreadKey}
597 resolvedTheme={resolvedTheme}
598 onOpenTurnDiff={onOpenTurnDiff}
599 />
600 );
601});
602​
603/** Inner component that only mounts when there are actual changed files,
604 * so the store subscription is unconditional (no hooks after early return). */
605function AssistantChangedFilesSectionInner({
606 turnSummary,
607 checkpointFiles,
608 routeThreadKey,
609 resolvedTheme,
610 onOpenTurnDiff,
611}: {
612 turnSummary: TurnDiffSummary;
613 checkpointFiles: TurnDiffSummary["files"];
614 routeThreadKey: string;
615 resolvedTheme: "light" | "dark";
616 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
617}) {
618 const allDirectoriesExpanded = useUiStateStore(
619 (store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
620 );
621 const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
622 const summaryStat = summarizeTurnDiffStats(checkpointFiles);
623 const changedFileCountLabel = String(checkpointFiles.length);
624​
625 return (
626 <div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
627 <div className="mb-1.5 flex items-center justify-between gap-2">
628 <p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
629 <span>Changed files ({changedFileCountLabel})</span>
630 {hasNonZeroStat(summaryStat) && (
631 <>
632 <span className="mx-1">•</span>
633 <DiffStatLabel additions={summaryStat.additions} deletions={summaryStat.deletions} />
634 </>
635 )}
636 </p>
637 <div className="flex items-center gap-1.5">
638 <Button
639 type="button"
640 size="xs"
641 variant="outline"
642 data-scroll-anchor-ignore
643 onClick={() => setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)}
644 >
645 {allDirectoriesExpanded ? "Collapse all" : "Expand all"}
646 </Button>
647 <Button
648 type="button"
649 size="xs"
650 variant="outline"
651 onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
652 >
653 View diff
654 </Button>
655 </div>
656 </div>
657 <ChangedFilesTree
658 key={`changed-files-tree:${turnSummary.turnId}`}
659 turnId={turnSummary.turnId}
660 files={checkpointFiles}
661 allDirectoriesExpanded={allDirectoriesExpanded}
662 resolvedTheme={resolvedTheme}
663 onOpenTurnDiff={onOpenTurnDiff}
664 />
665 </div>
666 );
668​
669// ---------------------------------------------------------------------------
670// Leaf components
671// ---------------------------------------------------------------------------
672​
673const UserMessageTerminalContextInlineLabel = memo(
674 function UserMessageTerminalContextInlineLabel(props: { context: ParsedTerminalContextEntry }) {
675 const tooltipText =
676 props.context.body.length > 0
677 ? `${props.context.header}\n${props.context.body}`
678 : props.context.header;
679​
680 return <TerminalContextInlineChip label={props.context.header} tooltipText={tooltipText} />;
681 },
682);
683​
684const UserMessageBody = memo(function UserMessageBody(props: {
685 text: string;
686 terminalContexts: ParsedTerminalContextEntry[];
687}) {
688 if (props.terminalContexts.length > 0) {
689 const hasEmbeddedInlineLabels = textContainsInlineTerminalContextLabels(
690 props.text,
691 props.terminalContexts,
692 );
693 const inlinePrefix = buildInlineTerminalContextText(props.terminalContexts);
694 const inlineNodes: ReactNode[] = [];
695​
696 if (hasEmbeddedInlineLabels) {
697 let cursor = 0;
698​
699 for (const context of props.terminalContexts) {
700 const label = formatInlineTerminalContextLabel(context.header);
701 const matchIndex = props.text.indexOf(label, cursor);
702 if (matchIndex === -1) {
703 inlineNodes.length = 0;
704 break;
705 }
706 if (matchIndex > cursor) {
707 inlineNodes.push(
708 <span key={`user-terminal-context-inline-before:${context.header}:${cursor}`}>
709 {props.text.slice(cursor, matchIndex)}
710 </span>,
711 );
712 }
713 inlineNodes.push(
714 <UserMessageTerminalContextInlineLabel
715 key={`user-terminal-context-inline:${context.header}`}
716 context={context}
717 />,
718 );
719 cursor = matchIndex + label.length;
720 }
721​
722 if (inlineNodes.length > 0) {
723 if (cursor < props.text.length) {
724 inlineNodes.push(
725 <span key={`user-message-terminal-context-inline-rest:${cursor}`}>
726 {props.text.slice(cursor)}
727 </span>,
728 );
729 }
730​
731 return (
732 <div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
733 {inlineNodes}
734 </div>
735 );
736 }
737 }
738​
739 for (const context of props.terminalContexts) {
740 inlineNodes.push(
741 <UserMessageTerminalContextInlineLabel
742 key={`user-terminal-context-inline:${context.header}`}
743 context={context}
744 />,
745 );
746 inlineNodes.push(
747 <span key={`user-terminal-context-inline-space:${context.header}`} aria-hidden="true">
748 {" "}
749 </span>,
750 );
751 }
752​
753 if (props.text.length > 0) {
754 inlineNodes.push(<span key="user-message-terminal-context-inline-text">{props.text}</span>);
755 } else if (inlinePrefix.length === 0) {
756 return null;
757 }
758​
759 return (
760 <div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
761 {inlineNodes}
762 </div>
763 );
764 }
765​
766 if (props.text.length === 0) {
767 return null;
768 }
769​
770 return (
771 <div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
772 {props.text}
773 </div>
774 );
775});
776​
777// ---------------------------------------------------------------------------
778// Structural sharing — reuse old row references when data hasn't changed
779// so LegendList (and React) can skip re-rendering unchanged items.
780// ---------------------------------------------------------------------------
781​
782/** Returns a structurally-shared copy of `rows`: for each row whose content
783 * hasn't changed since last call, the previous object reference is reused. */
784function useStableRows(rows: MessagesTimelineRow[]): MessagesTimelineRow[] {
785 const prevState = useRef<StableMessagesTimelineRowsState>({
786 byId: new Map<string, MessagesTimelineRow>(),
787 result: [],
788 });
789​
790 return useMemo(() => {
791 const nextState = computeStableMessagesTimelineRows(rows, prevState.current);
792 prevState.current = nextState;
793 return nextState.result;
794 }, [rows]);
796​
797// ---------------------------------------------------------------------------
798// Pure helpers
799// ---------------------------------------------------------------------------
800​
801function formatWorkingTimer(startIso: string, endIso: string): string | null {
802 const startedAtMs = Date.parse(startIso);
803 const endedAtMs = Date.parse(endIso);
804 if (!Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs)) {
805 return null;
806 }
807​
808 const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
809 if (elapsedSeconds < 60) {
810 return `${elapsedSeconds}s`;
811 }
812​
813 const hours = Math.floor(elapsedSeconds / 3600);
814 const minutes = Math.floor((elapsedSeconds % 3600) / 60);
815 const seconds = elapsedSeconds % 60;
816​
817 if (hours > 0) {
818 return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
819 }
820​
821 return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
823​
824function formatMessageMeta(
825 createdAt: string,
826 duration: string | null,
827 timestampFormat: TimestampFormat,
828): string {
829 if (!duration) return formatTimestamp(createdAt, timestampFormat);
830 return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
832​
833function workToneIcon(tone: TimelineWorkEntry["tone"]): {
834 icon: LucideIcon;
835 className: string;
836} {
837 if (tone === "error") {
838 return {
839 icon: CircleAlertIcon,
840 className: "text-foreground/92",
841 };
842 }
843 if (tone === "thinking") {
844 return {
845 icon: BotIcon,
846 className: "text-foreground/92",
847 };
848 }
849 if (tone === "info") {
850 return {
851 icon: CheckIcon,
852 className: "text-foreground/92",
853 };
854 }
855 return {
856 icon: ZapIcon,
857 className: "text-foreground/92",
858 };
860​
861function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
862 if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
863 if (tone === "tool") return "text-muted-foreground/70";
864 if (tone === "thinking") return "text-muted-foreground/50";
865 return "text-muted-foreground/40";
867​
868function workEntryPreview(
869 workEntry: Pick<TimelineWorkEntry, "detail" | "command" | "changedFiles">,
870 workspaceRoot: string | undefined,
871) {
872 if (workEntry.command) return workEntry.command;
873 if (workEntry.detail) return workEntry.detail;
874 if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
875 const [firstPath] = workEntry.changedFiles ?? [];
876 if (!firstPath) return null;
877 const displayPath = formatWorkspaceRelativePath(firstPath, workspaceRoot);
878 return workEntry.changedFiles!.length === 1
879 ? displayPath
880 : `${displayPath} +${workEntry.changedFiles!.length - 1} more`;
882​
883function workEntryRawCommand(
884 workEntry: Pick<TimelineWorkEntry, "command" | "rawCommand">,
885): string | null {
886 const rawCommand = workEntry.rawCommand?.trim();
887 if (!rawCommand || !workEntry.command) {
888 return null;
889 }
890 return rawCommand === workEntry.command.trim() ? null : rawCommand;
892​
893function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {
894 if (workEntry.requestKind === "command") return TerminalIcon;
895 if (workEntry.requestKind === "file-read") return EyeIcon;
896 if (workEntry.requestKind === "file-change") return SquarePenIcon;
897​
898 if (workEntry.itemType === "command_execution" || workEntry.command) {
899 return TerminalIcon;
900 }
901 if (workEntry.itemType === "file_change" || (workEntry.changedFiles?.length ?? 0) > 0) {
902 return SquarePenIcon;
903 }
904 if (workEntry.itemType === "web_search") return GlobeIcon;
905 if (workEntry.itemType === "image_view") return EyeIcon;
906​
907 switch (workEntry.itemType) {
908 case "mcp_tool_call":
909 return WrenchIcon;
910 case "dynamic_tool_call":
911 case "collab_agent_tool_call":
912 return HammerIcon;
913 }
914​
915 return workToneIcon(workEntry.tone).icon;
917​
918function capitalizePhrase(value: string): string {
919 const trimmed = value.trim();
920 if (trimmed.length === 0) {
921 return value;
922 }
923 return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
925​
926function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
927 if (!workEntry.toolTitle) {
928 return capitalizePhrase(normalizeCompactToolLabel(workEntry.label));
929 }
930 return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle));
932​
933const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
934 workEntry: TimelineWorkEntry;
935 workspaceRoot: string | undefined;
936}) {
937 const { workEntry, workspaceRoot } = props;
938 const iconConfig = workToneIcon(workEntry.tone);
939 const EntryIcon = workEntryIcon(workEntry);
940 const heading = toolWorkEntryHeading(workEntry);
941 const preview = workEntryPreview(workEntry, workspaceRoot);
942 const rawCommand = workEntryRawCommand(workEntry);
943 const displayText = preview ? `${heading} - ${preview}` : heading;
944 const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
945 const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail;
946​
947 return (
948 <div className="rounded-lg px-1 py-1">
949 <div className="flex items-center gap-2 transition-[opacity,translate] duration-200">
950 <span
951 className={cn("flex size-5 shrink-0 items-center justify-center", iconConfig.className)}
952 >
953 <EntryIcon className="size-3" />
954 </span>
955 <div className="min-w-0 flex-1 overflow-hidden">
956 <div className="max-w-full">
957 <p
958 className={cn(
959 "truncate text-xs leading-5",
960 workToneClass(workEntry.tone),
961 preview ? "text-muted-foreground/70" : "",
962 )}
963 title={rawCommand ? undefined : displayText}
964 >
965 <span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
966 {heading}
967 </span>
968 {preview &&
969 (rawCommand ? (
970 <Tooltip>
971 <TooltipTrigger
972 closeDelay={0}
973 delay={75}
974 render={
975 <span className="max-w-full cursor-default text-muted-foreground/55 transition-colors hover:text-muted-foreground/75 focus-visible:text-muted-foreground/75">
976 {" "}
977 - {preview}
978 </span>
979 }
980 />
981 <TooltipPopup
982 align="start"
983 className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
984 side="top"
985 >
986 <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">
987 {rawCommand}
988 </div>
989 </TooltipPopup>
990 </Tooltip>
991 ) : (
992 <span className="text-muted-foreground/55"> - {preview}</span>
993 ))}
994 </p>
995 </div>
996 </div>
997 </div>
998 {hasChangedFiles && !previewIsChangedFiles && (
999 <div className="mt-1 flex flex-wrap gap-1 pl-6">
1000 {workEntry.changedFiles?.slice(0, 4).map((filePath) => {
1001 const displayPath = formatWorkspaceRelativePath(filePath, workspaceRoot);
1002 return (
1003 <span
1004 key={`${workEntry.id}:${filePath}`}
1005 className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
1006 title={displayPath}
1008 {displayPath}
1009 </span>
1010 );
1011 })}
1012 {(workEntry.changedFiles?.length ?? 0) > 4 && (
1013 <span className="px-1 text-[10px] text-muted-foreground/55">
1014 +{(workEntry.changedFiles?.length ?? 0) - 4}
1015 </span>
1016 )}
1017 </div>
1018 )}
1019 </div>
1020 );
1021});