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