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

MessagesTimeline.tsx

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