Open History to see the last commit
1import { ThreadFindTimelineContext } from "./ThreadFindProvider";
2import { MarkdownFindContext } from "./markdownFindContext";
3import { useChatCanvas } from "./ChatCanvasContext";
4import { WorkLogBlock } from "./WorkLog";
5import type { WorktreeSetupSnapshot } from "@t3tools/contracts";
6import { deriveTimelineMinimapItems } from "./timelineMinimapItems";
7import {
8 type AssistantCitation,
9 type EnvironmentId,
10 type MessageId,
11 type OrchestrationV2TurnItem,
12 type RunAttemptId,
13 type ServerProviderSkill,
14 type RunId,
15 ThreadId,
16} from "@t3tools/contracts";
17import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
18import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
19import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
20import { observeResize } from "~/lib/observeResize";
21import { useStableCallback } from "~/hooks/useStableCallback";
22
23const NOOP_USE_ARTIFACT_TEMPLATE = () => {};
24const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
25
26import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
27import { observeVisibleAnimation } from "../../lib/visibleAnimation";
28import {
29 memo,
30 use,
31 useContext,
32 useEffect,
33 useLayoutEffect,
34 useRef,
35 useState,
36 type ReactNode,
37} from "react";
38import {
39 LegendList,
40 type LegendListRef,
41 type MaintainScrollAtEndOptions,
42} from "@legendapp/list/react";
43import { type TimelineEntry } from "../../session-logic";
44import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
45import { type ChatFileAttachment, type TurnDiffSummary } from "../../types";
46import { ArrowRightIcon, BotIcon, Minimize2Icon } from "lucide-react";
47import { ChevronDown, ChevronRight } from "lucide";
48import { MorphIcon } from "~/components/MorphIcon";
49import { ExpandedImagePreview } from "./ExpandedImagePreview";
50import {
51 CHAT_TIMELINE_ANCHOR_OFFSET,
52 readTimelinePosition,
53 type RememberedTimelinePosition,
54 rememberTimelinePosition,
55 timelineContentOverflowsViewport,
56} from "./timelineScrollAnchoring";
57import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";
58import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
59import { type AssistantCitationRequest } from "./AssistantCitationSource";
60import { useAssistantCitationTarget, type CitationHistoryPage } from "./useAssistantCitationTarget";
61import {
62 resolveTimelineIsAtEnd,
63 resolveTimelineMinimapHasPersistentGutter,
64 resolveTimelineMinimapCurrentIndex,
65 isTimelineMinimapRowVisible,
66 resolveTimelineMinimapVisibleRange,
67 resolveTimelineMinimapHitStripWidth,
68 timelineTurnFoldRunIdsByEntryId,
69 worktreeSetupAgentStarted,
70 type MessagesTimelineRow,
71 type TimelineLatestRun,
72} from "./MessagesTimeline.logic";
73import { type ThreadFindMatch } from "./threadFind";
74import { useThreadFindNavigation } from "./useThreadFindNavigation";
75import type { ThreadFindPositionReader } from "./threadFind";
76import { TooltipScrollDismissArea } from "../ui/tooltip";
77import { WorktreeSetupCard } from "./WorktreeSetupCard";
78import { useOpenPrLink } from "~/lib/openPullRequestLink";
79import { useClientSettings } from "~/hooks/useSettings";
80import { useMediaQuery } from "~/hooks/useMediaQuery";
81import { cn } from "~/lib/utils";
82import { type TimestampFormat } from "@t3tools/contracts/settings";
83import { type HandoffTimelineRun } from "./V2LifecycleRow";
84import { TimelineSystemDivider } from "./TimelineSystemDivider";
85
86import { forwardWheelToTimeline } from "./timelineMinimapWheel";
87import { TimelineMinimap } from "./TimelineMinimap";
88import {
89 type TimelineRowSharedState,
90 type TimelineRowActivityState,
91 TimelineRowCtx,
92 TimelineRowActivityCtx,
93 type WorkGroupViewState,
94 type TimelineRow,
95} from "./timelineRowContext";
96import { TimelineRowTimestamp, ActivityShimmerOverlay } from "./TimelineRowParts";
97import {
98 WorkGroupSection,
99 WorkingTimelineRow,
100 ThinkingTimelineRow,
101 LiveWorkEntryTimelineRow,
102 WorkGroupToggleTimelineRow,
103} from "./TimelineWorkGroupRows";
104import { UserMessageRow } from "./TimelineUserMessageRow";
105import {
106 AssistantTimelineRow,
107 AssistantMetaTimelineRow,
108 ProposedPlanTimelineRow,
109 HtmlRenderTimelineRow,
110 McpAppTimelineRow,
111} from "./TimelineAssistantRows";
112import { V2EventTimelineRow } from "./TimelineV2EventRow";
113import { useTimelinePositionRestore } from "./useTimelinePositionRestore";
114import { useThreadFindPositionReader } from "./useThreadFindPositionReader";
115import { useStableHandoffRuns, useIncrementalTimelineRows, useStableRows } from "./useTimelineRows";
116
117function timelineListStateFor(identity: string): {
118 readonly identity: string;
119 readonly rememberedPosition: RememberedTimelinePosition | undefined;
120 readonly workGroupViewState: WorkGroupViewState;
121} {
122 const rememberedPosition = readTimelinePosition(identity);
123 return {
124 identity,
125 rememberedPosition,
126 workGroupViewState: rememberedPosition?.disclosures?.workGroupState ?? {
127 scrollPositions: new Map(),
128 expandedEntries: new Set(),
129 },
130 };
131}
132
133const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
134const TIMELINE_LIST_FADE_HEADER = (
135 <div className="h-[var(--workspace-titlebar-scroll-fade-height)]" />
136);
137function TimelineListFooter({
138 composerInset,
139 children,
140}: {
141 readonly composerInset: number;
142 readonly children?: ReactNode;
143}) {
144 return (
145 <div>
146 {children}
147 <div aria-hidden style={{ height: composerInset }} />
148 <div aria-hidden className="h-3 sm:h-4" />
149 </div>
150 );
151}
152
153const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
154const TIMELINE_MAINTAIN_SCROLL_AT_END = {
155 animated: false,
156 on: {
157 dataChange: true,
158 footerLayout: false,
159 itemLayout: true,
160 layout: true,
161 },
162} as const satisfies MaintainScrollAtEndOptions;
163const EMPTY_RUN_IDS: ReadonlySet<RunId> = new Set();
164const TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH = {
165 ...TIMELINE_MAINTAIN_SCROLL_AT_END,
166 animated: true,
167} as const satisfies MaintainScrollAtEndOptions;
168
169export interface MessagesTimelineHistoryControls {
170 readonly hasMoreHistory: boolean;
171 readonly loading: boolean;
172 readonly error: string | null;
173 readonly onLoadEarlier: (throughEntryId?: string) => void;
174}
175
176interface MessagesTimelineProps {
177 citationRequest?: AssistantCitationRequest | null;
178 citationHistoryLoading?: boolean;
179 onCiteAssistantText?: (
180 citation: AssistantCitation,
181 sourceAnchor: AssistantCitationSourceAnchor,
182 ) => boolean;
183 isWorking: boolean;
184 runlessWorkActive?: boolean;
185 activeTurnInProgress: boolean;
186 activeTurnStartedAt?: string | null;
187 worktreeSetup?: WorktreeSetupSnapshot | null;
188 onCancelWorktreeSetup?: () => void;
189 retryableWorkspacePreparationRunIds?: ReadonlySet<RunId>;
190 onRetryWorkspacePreparation?: (runId: RunId) => void;
191 onWorktreeSetupWorkLocally?: () => void;
192 onOpenWorktreeSetupTerminal?: (terminalId: string) => void;
193 isPreparingWorktree?: boolean;
194 isCompacting?: boolean;
195 awaitingUser?: boolean;
196 footer?: ReactNode;
197
198 listRef: React.RefObject<LegendListRef | null>;
199 timelineEntries: ReadonlyArray<TimelineEntry>;
200 latestRun: TimelineLatestRun | null;
201 runningRunId?: RunId | null;
202 turnDiffSummaries: ReadonlyArray<TurnDiffSummary>;
203 routeThreadKey: string;
204 displayThreadKey?: string;
205 paintOnly?: boolean;
206 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
207 onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
208 parentThreadLink?: {
209 readonly threadId: ThreadId;
210 readonly title: string;
211 } | null;
212 /** Set on a workflow coordinator's thread: its script message renders as this opening. */
213 workflowOpening?: WorkflowOpening | null;
214 onForkFromRun: (input: {
215 readonly sourceThreadId: ThreadId;
216 readonly runId: RunId;
217 }) => Promise<void>;
218 onRollbackCheckpoint: (input: {
219 readonly checkpointId: string;
220 readonly scopeId: string;
221 }) => void;
222 supportsConversationRollback: boolean;
223 threadStartCheckpointReady?: boolean;
224 availableRevertTurnCounts?: ReadonlySet<number> | undefined;
225 onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void;
226 onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
227 onSendAppMessage?: (text: string) => Promise<void>;
228 onRunShellCommand?: (command: string) => void;
229 isRevertingCheckpoint: boolean;
230 onImageExpand: (preview: ExpandedImagePreview) => void;
231 onFileOpen?: (attachment: ChatFileAttachment) => void;
232 onFileDownload?: (attachment: ChatFileAttachment) => void;
233 activeThreadEnvironmentId: EnvironmentId;
234 markdownCwd: string | undefined;
235 resolvedTheme: "light" | "dark";
236 timestampFormat: TimestampFormat;
237 workspaceRoot: string | undefined;
238 skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
239 runs: ReadonlyArray<HandoffTimelineRun>;
240 anchorMessageId: MessageId | null;
241 onAnchorReady: (messageId: MessageId, anchorIndex: number) => void;
242 onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
243 contentInsetEndAdjustment: number;
244 onIsAtEndChange: (isAtEnd: boolean) => void;
245 /**
246 * Off while the user is reading history; LegendList's own maintainScrollAtEnd
247 * would otherwise re-pin regardless of ChatView's scroll-mode refs whenever
248 * the user drifts near the bottom.
249 */
250 liveFollowEnabled: boolean;
251 onContentOverflowChange?: (overflows: boolean) => void;
252 onToolOutputCollapsedAtEnd?: () => void;
253 onManualNavigation: () => void;
254 findOpen?: boolean;
255 cancelPositionRestoreRef?: React.RefObject<(() => void) | null> | undefined;
256 hideEmptyPlaceholder?: boolean;
257 /** Composer space to center the empty state against; held steady through collapse. */
258 emptyPlaceholderInset: number;
259 topFadeEnabled?: boolean;
260 historyControls?: MessagesTimelineHistoryControls | undefined;
261 loadEarlier?: CitationHistoryPage | null;
262 findPositionReaderRef?: React.RefObject<ThreadFindPositionReader | null>;
263 findExpanded?: boolean;
264 findQuery?: string;
265 activeFindMatch?: ThreadFindMatch | null;
266 findNavigationId?: number;
267}
268
269export function MessagesTimeline(props: MessagesTimelineProps) {
270 const find = useContext(ThreadFindTimelineContext);
271 const findOpen = find?.findOpen ?? props.findOpen;
272 const { onManualNavigation } = props;
273 useEffect(() => {
274 if (findOpen) onManualNavigation();
275 }, [findOpen, onManualNavigation]);
276 return (
277 <ConversationTimeline
278 {...props}
279 {...find}
280 liveFollowEnabled={!findOpen && props.liveFollowEnabled}
281 />
282 );
283}
284
285const ConversationTimeline = memo(function ConversationTimeline({
286 citationRequest = null,
287 citationHistoryLoading = false,
288 onCiteAssistantText,
289 isWorking,
290 runlessWorkActive = false,
291 activeTurnInProgress,
292 activeTurnStartedAt = null,
293 worktreeSetup = null,
294 footer = null,
295 onCancelWorktreeSetup,
296 retryableWorkspacePreparationRunIds = EMPTY_RUN_IDS,
297 onRetryWorkspacePreparation,
298 onWorktreeSetupWorkLocally,
299 onOpenWorktreeSetupTerminal,
300 isPreparingWorktree = false,
301 isCompacting = false,
302 awaitingUser = false,
303 listRef,
304 timelineEntries,
305 findExpanded = false,
306 findQuery = "",
307 activeFindMatch = null,
308 findNavigationId = 0,
309 findPositionReaderRef,
310 latestRun,
311 runningRunId = null,
312 turnDiffSummaries,
313 routeThreadKey,
314 displayThreadKey,
315 paintOnly = false,
316 onOpenTurnDiff,
317 onOpenThread,
318 parentThreadLink = null,
319 workflowOpening = null,
320 onForkFromRun,
321 onRollbackCheckpoint,
322 supportsConversationRollback,
323 threadStartCheckpointReady = false,
324 availableRevertTurnCounts,
325 onRevertToTurnCount,
326 onUseArtifactTemplate = NOOP_USE_ARTIFACT_TEMPLATE,
327 onSendAppMessage,
328 onRunShellCommand,
329 isRevertingCheckpoint,
330 onImageExpand,
331 onFileOpen = NOOP_OPEN_ATTACHMENT,
332 onFileDownload = NOOP_OPEN_ATTACHMENT,
333 activeThreadEnvironmentId,
334 markdownCwd,
335 resolvedTheme,
336 timestampFormat,
337 workspaceRoot,
338 skills = EMPTY_TIMELINE_SKILLS,
339 runs: runsProp,
340 anchorMessageId,
341 onAnchorReady,
342 onAnchorSizeChanged,
343 contentInsetEndAdjustment,
344 onIsAtEndChange,
345 onContentOverflowChange,
346 liveFollowEnabled,
347 onToolOutputCollapsedAtEnd,
348 onManualNavigation,
349 cancelPositionRestoreRef,
350 hideEmptyPlaceholder = false,
351 emptyPlaceholderInset,
352 topFadeEnabled = false,
353 historyControls,
354 loadEarlier = null,
355}: MessagesTimelineProps) {
356 const listIdentityKey = displayThreadKey ?? routeThreadKey;
357 // The remembered position is a snapshot taken when the list identity changes;
358 // scrolling keeps rewriting the stored entry, which must not move the restore.
359 const [listState, setListState] = useState(() => timelineListStateFor(listIdentityKey));
360 const [expandedRunIds, setExpandedRunIds] = useState<ReadonlySet<RunId>>(
361 () => listState.rememberedPosition?.disclosures?.runs ?? new Set(),
362 );
363 const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(
364 () => listState.rememberedPosition?.disclosures?.workGroups ?? new Set(),
365 );
366 const [expandedAttemptIds, setExpandedAttemptIds] = useState<ReadonlySet<RunAttemptId>>(
367 () => listState.rememberedPosition?.disclosures?.attempts ?? new Set(),
368 );
369 const [positionedThreadKey, setPositionedThreadKey] = useState<string | null>(() =>
370 listState.rememberedPosition?.atEnd === false ? null : listIdentityKey,
371 );
372 const restoringThreadPosition = positionedThreadKey !== listIdentityKey;
373 const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
374 const [settlingListIdentity, setSettlingListIdentity] = useState<string | null>(listIdentityKey);
375 let paintedExpandedRunIds = expandedRunIds;
376 let paintedExpandedWorkGroupIds = expandedWorkGroupIds;
377 let paintedExpandedAttemptIds = expandedAttemptIds;
378 const identityChanged = listState.identity !== listIdentityKey;
379 const { rememberedPosition, workGroupViewState } = identityChanged
380 ? timelineListStateFor(listIdentityKey)
381 : listState;
382 if (identityChanged) {
383 setListState({ identity: listIdentityKey, rememberedPosition, workGroupViewState });
384 setPositionedThreadKey(null);
385 setSettlingListIdentity(listIdentityKey);
386 paintedExpandedRunIds = rememberedPosition?.disclosures?.runs ?? new Set();
387 paintedExpandedWorkGroupIds = rememberedPosition?.disclosures?.workGroups ?? new Set();
388 paintedExpandedAttemptIds = rememberedPosition?.disclosures?.attempts ?? new Set();
389 setExpandedRunIds(paintedExpandedRunIds);
390 setExpandedWorkGroupIds(paintedExpandedWorkGroupIds);
391 setExpandedAttemptIds(paintedExpandedAttemptIds);
392 }
393 const citationThreadRef = parseScopedThreadKey(routeThreadKey);
394 const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined);
395 const expandCitedRun = (runId: RunId) => {
396 setExpandedRunIds((current) => (current.has(runId) ? current : new Set([...current, runId])));
397 };
398 const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
399 const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
400 const disclosureAnchorKeyRef = useRef<string | null>(null);
401 const disclosureSettleFrameRef = useRef<number | null>(null);
402 const disclosureSettleSecondFrameRef = useRef<number | null>(null);
403 const normalizedFindQuery = findQuery.trim();
404 const findActive = findExpanded;
405
406 useEffect(() => {
407 return () => {
408 if (disclosureSettleFrameRef.current !== null) {
409 cancelAnimationFrame(disclosureSettleFrameRef.current);
410 }
411 if (disclosureSettleSecondFrameRef.current !== null) {
412 cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
413 }
414 };
415 }, []);
416
417 useEffect(() => {
418 if (settlingListIdentity === null) return;
419 let second: number | null = null;
420 const first = requestAnimationFrame(() => {
421 second = requestAnimationFrame(() => {
422 setSettlingListIdentity((current) => (current === settlingListIdentity ? null : current));
423 });
424 });
425 return () => {
426 cancelAnimationFrame(first);
427 if (second !== null) cancelAnimationFrame(second);
428 };
429 }, [settlingListIdentity]);
430
431 const disclosurePinsEndRef = useRef(false);
432 const disclosureCollapsedRef = useRef(false);
433 const pinDisclosureToEnd = () => {
434 if (!disclosurePinsEndRef.current) return;
435 const element = listRef.current?.getScrollableNode();
436 if (element) element.scrollTop = element.scrollHeight;
437 };
438
439 const scheduleDisclosureSettle = () => {
440 if (disclosureSettleFrameRef.current !== null) {
441 cancelAnimationFrame(disclosureSettleFrameRef.current);
442 }
443 if (disclosureSettleSecondFrameRef.current !== null) {
444 cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
445 }
446 disclosureSettleFrameRef.current = requestAnimationFrame(() => {
447 pinDisclosureToEnd();
448 disclosureSettleSecondFrameRef.current = requestAnimationFrame(() => {
449 pinDisclosureToEnd();
450 disclosurePinsEndRef.current = false;
451 disclosureAnchorKeyRef.current = null;
452 setDisclosureToggleSettling(false);
453 disclosureSettleFrameRef.current = null;
454 disclosureSettleSecondFrameRef.current = null;
455 if (
456 disclosureCollapsedRef.current &&
457 resolveTimelineIsAtEnd(listRef.current?.getState()) === true
458 ) {
459 onToolOutputCollapsedAtEnd?.();
460 }
461 });
462 });
463 };
464
465 const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string, collapsed = false) => {
466 disclosureAnchorKeyRef.current = anchorKey;
467 disclosureCollapsedRef.current = collapsed;
468 disclosurePinsEndRef.current = resolveTimelineIsAtEnd(listRef.current?.getState()) === true;
469 setDisclosureToggleSettling(true);
470 scheduleDisclosureSettle();
471 };
472
473 const shouldRestoreVisibleContentPosition = (row: MessagesTimelineRow) => {
474 if (disclosurePinsEndRef.current) return false;
475 const disclosureAnchorKey = disclosureAnchorKeyRef.current;
476 return disclosureAnchorKey === null || row.id === disclosureAnchorKey;
477 };
478
479 const onToggleTurnFold = (runId: RunId) => {
480 suspendEndScrollMaintenanceForDisclosure(`turn-fold:${runId}`);
481 setExpandedRunIds((existing) => {
482 const next = new Set(existing);
483 if (next.has(runId)) {
484 next.delete(runId);
485 } else {
486 next.add(runId);
487 }
488 return next;
489 });
490 };
491 const onToggleWorkGroup = (groupId: string, anchorKey: string) => {
492 suspendEndScrollMaintenanceForDisclosure(anchorKey, expandedWorkGroupIds.has(groupId));
493 setExpandedWorkGroupIds((existing) => {
494 const next = new Set(existing);
495 if (next.has(groupId)) {
496 next.delete(groupId);
497 } else {
498 next.add(groupId);
499 }
500 return next;
501 });
502 };
503 const onToggleAttemptFold = (attemptId: RunAttemptId) => {
504 suspendEndScrollMaintenanceForDisclosure(`attempt-fold:${attemptId}`);
505 setExpandedAttemptIds((existing) => {
506 const next = new Set(existing);
507 if (next.has(attemptId)) {
508 next.delete(attemptId);
509 } else {
510 next.add(attemptId);
511 }
512 return next;
513 });
514 };
515
516 const previousLatestRunRef = useRef({ identity: listIdentityKey, run: latestRun });
517 useEffect(() => {
518 const { identity, run: previous } = previousLatestRunRef.current;
519 previousLatestRunRef.current = { identity: listIdentityKey, run: latestRun };
520 if (identity !== listIdentityKey || !latestRun || previous?.runId === undefined) {
521 return;
522 }
523 if (latestRun.runId === previous.runId) {
524 if (previous.status === "running" && latestRun.status === "interrupted") {
525 setExpandedRunIds((existing) => {
526 const next = new Set(existing);
527 next.add(latestRun.runId);
528 return next;
529 });
530 }
531 return;
532 }
533 setExpandedRunIds((existing) => {
534 if (!existing.has(previous.runId)) {
535 return existing;
536 }
537 const next = new Set(existing);
538 next.delete(previous.runId);
539 return next;
540 });
541 }, [latestRun, listIdentityKey]);
542
543 // Imported turns and post-steer work fold under synthetic keys, not the entries' run ids.
544 const findFoldRunIds = findActive
545 ? timelineTurnFoldRunIdsByEntryId({
546 timelineEntries,
547 latestRun,
548 runningRunId,
549 isWorking,
550 runlessWorkActive,
551 })
552 : null;
553 const activeFindRunId =
554 findActive && activeFindMatch ? findFoldRunIds?.get(activeFindMatch.entryId) : undefined;
555 const [expandedFindRunId, setExpandedFindRunId] = useState<RunId | undefined>();
556 if (expandedFindRunId !== activeFindRunId) {
557 setExpandedFindRunId(activeFindRunId);
558 if (activeFindRunId) {
559 setExpandedRunIds((previous) =>
560 previous.has(activeFindRunId) ? previous : new Set(previous).add(activeFindRunId),
561 );
562 }
563 }
564 const visibleExpandedRunIds =
565 !activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)
566 ? paintedExpandedRunIds
567 : new Set(paintedExpandedRunIds).add(activeFindRunId);
568
569 const activeFindAttemptId = activeFindMatch
570 ? timelineEntries.find((entry) => entry.id === activeFindMatch.entryId)?.attempt?.id
571 : undefined;
572 const [expandedFindAttemptId, setExpandedFindAttemptId] = useState<RunAttemptId | undefined>();
573 if (expandedFindAttemptId !== activeFindAttemptId) {
574 setExpandedFindAttemptId(activeFindAttemptId);
575 if (activeFindAttemptId) {
576 setExpandedAttemptIds((previous) =>
577 previous.has(activeFindAttemptId) ? previous : new Set(previous).add(activeFindAttemptId),
578 );
579 }
580 }
581 const visibleExpandedAttemptIds =
582 activeFindAttemptId && !paintedExpandedAttemptIds.has(activeFindAttemptId)
583 ? new Set(paintedExpandedAttemptIds).add(activeFindAttemptId)
584 : paintedExpandedAttemptIds;
585
586 const rawRows = useIncrementalTimelineRows(`${listIdentityKey}\0${workspaceRoot ?? ""}`, {
587 timelineEntries,
588 latestRun,
589 runningRunId,
590 expandedRunIds: visibleExpandedRunIds,
591 expandedAttemptIds: visibleExpandedAttemptIds,
592 expandedWorkGroupIds,
593 isWorking,
594 runlessWorkActive,
595 activeTurnStartedAt,
596 turnDiffSummaries,
597 supportsConversationRollback,
598 threadStartCheckpointReady,
599 availableRevertTurnCounts,
600 worktreeSetup,
601 });
602 const rows = useStableRows(rawRows, listIdentityKey);
603 // Run status/timestamps churn on every stream event; the shared row context
604 // must not change with them or every timeline row re-renders per event.
605 const runs = useStableHandoffRuns(runsProp);
606 const minimapItems = deriveTimelineMinimapItems(rows);
607 const minimapRowIndices = minimapItems.map((item) => item.rowIndex);
608 const restoreRowIndex =
609 restoringThreadPosition && rememberedPosition?.atEnd === false
610 ? rows.findIndex((row) => row.id === rememberedPosition.rowId)
611 : -1;
612 const restoringAlwaysRender =
613 restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined;
614 useTimelinePositionRestore({
615 listRef,
616 listIdentityKey,
617 restoringThreadPosition,
618 rememberedPosition,
619 rows,
620 citationRequest,
621 cancelPositionRestoreRef,
622 onManualNavigation,
623 onPositioned: setPositionedThreadKey,
624 });
625
626 const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
627 null,
628 );
629 const chatWidth = useClientSettings((settings) => settings.chatWidth);
630 const {
631 target: readyCitationRequest,
632 positioning: citationPositioning,
633 onListLoad: onCitationListLoad,
634 alwaysRender: citationAlwaysRender,
635 } = useAssistantCitationTarget({
636 request: citationRequest,
637 entries: timelineEntries,
638 rows,
639 listRef,
640 viewport: timelineViewportElement,
641 historyLoading: citationHistoryLoading,
642 loadEarlier,
643 getTurnFoldRunId: (entryId) =>
644 (
645 findFoldRunIds ??
646 timelineTurnFoldRunIdsByEntryId({
647 timelineEntries,
648 latestRun,
649 runningRunId,
650 isWorking,
651 runlessWorkActive,
652 })
653 ).get(entryId),
654 onExpandTurn: expandCitedRun,
655 onManualNavigation,
656 });
657 const [findListReady, setFindListReady] = useState(false);
658 const handleListLoad = () => {
659 onCitationListLoad();
660 setFindListReady(true);
661 };
662 const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
663 const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);
664 const onAppFullscreenChange = (rowId: string, fullscreen: boolean) => {
665 setFullscreenAppRowId((current) => (fullscreen ? rowId : current === rowId ? null : current));
666 };
667 const alwaysRenderIndices = restoringAlwaysRender?.indices ?? [];
668 const alwaysRenderKeys = [
669 ...(citationAlwaysRender?.keys ?? []),
670 ...(fullscreenAppRowId === null ? [] : [fullscreenAppRowId]),
671 ];
672 const alwaysRender =
673 alwaysRenderIndices.length === 0 && alwaysRenderKeys.length === 0
674 ? undefined
675 : {
676 ...(alwaysRenderIndices.length === 0 ? {} : { indices: alwaysRenderIndices }),
677 ...(alwaysRenderKeys.length === 0 ? {} : { keys: alwaysRenderKeys }),
678 };
679 const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
680 const [minimapCurrentIndex, setMinimapCurrentIndex] = useState<number | null>(null);
681 const handleAnchorReady = (info: { anchorIndex: number | undefined }) => {
682 if (anchorMessageId !== null && info.anchorIndex !== undefined) {
683 onAnchorReady(anchorMessageId, info.anchorIndex);
684 }
685 };
686 const handleAnchorSizeChanged = (size: number) => {
687 if (anchorMessageId !== null) {
688 onAnchorSizeChanged(anchorMessageId, size);
689 }
690 };
691 const anchoredEndSpaceConfig = resolveChatListAnchoredEndSpace(
692 rows,
693 anchorMessageId,
694 (row) => (row.kind === "message" && row.message.role === "user" ? row.message.id : null),
695 { anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET },
696 );
697 const anchoredEndSpace = anchoredEndSpaceConfig
698 ? {
699 ...anchoredEndSpaceConfig,
700 onReady: handleAnchorReady,
701 onSizeChanged: handleAnchorSizeChanged,
702 }
703 : undefined;
704 const maintainVisibleContentPosition = {
705 data: true,
706 size: true,
707 shouldRestorePosition: shouldRestoreVisibleContentPosition,
708 };
709 const timelineListFooter = (
710 <TimelineListFooter composerInset={anchoredEndSpace ? 0 : contentInsetEndAdjustment}>
711 {footer}
712 </TimelineListFooter>
713 );
714
715 const measureContentOverflow = () =>
716 timelineContentOverflowsViewport(listRef.current?.getState?.(), {
717 composerInset: contentInsetEndAdjustment,
718 anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
719 });
720 // LegendList lays rows out from layout effects, so a read on the next frame
721 // sees the settled positions.
722 const contentOverflowFrameRef = useRef<number | null>(null);
723 const cancelContentOverflowFrame = () => {
724 if (contentOverflowFrameRef.current !== null) {
725 cancelAnimationFrame(contentOverflowFrameRef.current);
726 contentOverflowFrameRef.current = null;
727 }
728 };
729 const reportContentOverflow = () => {
730 if (!onContentOverflowChange || contentOverflowFrameRef.current !== null) return;
731 contentOverflowFrameRef.current = requestAnimationFrame(() => {
732 contentOverflowFrameRef.current = null;
733 onContentOverflowChange(measureContentOverflow());
734 });
735 };
736 useEffect(() => cancelContentOverflowFrame, [cancelContentOverflowFrame]);
737 useLayoutEffect(() => {
738 cancelContentOverflowFrame();
739 onContentOverflowChange?.(measureContentOverflow());
740 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows change the content height.
741 }, [cancelContentOverflowFrame, measureContentOverflow, onContentOverflowChange, rows.length]);
742
743 const refreshMinimap = useStableCallback(() => {
744 const state = listRef.current?.getState?.();
745 if (restoringThreadPosition || state?.data !== rows) return;
746 if (!state || minimapItems.length === 0) {
747 return;
748 }
749
750 const firstBufferedIndex = state.startBuffered;
751 const firstBufferedRow: HTMLElement | undefined =
752 firstBufferedIndex == null ? undefined : state.elementAtIndex(firstBufferedIndex);
753 const firstBufferedTop =
754 firstBufferedIndex == null ? undefined : state.positionAtIndex(firstBufferedIndex);
755 const viewport: HTMLElement | undefined = listRef.current?.getScrollableNode();
756 // Cached row positions exclude the header and pending scroll adjustments.
757 const scroll =
758 firstBufferedRow && viewport && firstBufferedTop !== undefined
759 ? firstBufferedTop +
760 viewport.getBoundingClientRect().top -
761 firstBufferedRow.getBoundingClientRect().top
762 : state.scroll;
763 const visibleRange = resolveTimelineMinimapVisibleRange({ ...state, scroll });
764 for (const item of minimapItems) {
765 const strip = minimapStripMap.get(item.id);
766 const inView = isTimelineMinimapRowVisible(
767 item.rowIndex,
768 visibleRange.start,
769 visibleRange.end,
770 );
771 const next = inView ? "true" : "false";
772 // Avoid dirtying style state on every scroll tick for unchanged strips.
773 if (strip && strip.dataset.inView !== next) {
774 strip.dataset.inView = next;
775 }
776 }
777 const nextCurrentIndex = resolveTimelineMinimapCurrentIndex({
778 visibleStart: visibleRange.start,
779 visibleEnd: visibleRange.end,
780 rowIndices: minimapRowIndices,
781 });
782 setMinimapCurrentIndex((current) =>
783 current === nextCurrentIndex ? current : nextCurrentIndex,
784 );
785 });
786
787 const minimapRefreshFrameRef = useRef<number | null>(null);
788 const scheduleMinimapRefresh = () => {
789 if (minimapRefreshFrameRef.current !== null) return;
790 // LegendList recycles row containers before React commits their positions.
791 minimapRefreshFrameRef.current = requestAnimationFrame(() => {
792 minimapRefreshFrameRef.current = null;
793 refreshMinimap();
794 });
795 };
796
797 const handleScroll = () => {
798 const state = listRef.current?.getState?.();
799 if (restoringThreadPosition || state?.data !== rows) return;
800 const isAtEnd = resolveTimelineIsAtEnd(state);
801 const position = state?.data?.length ? resolveWorkGroupScrollAnchor(state) : undefined;
802 if (position && state && isAtEnd !== undefined && !paintOnly) {
803 const index = state.indexByKey(position.rowId);
804 const row = index === undefined ? undefined : state.elementAtIndex(index);
805 const element = listRef.current?.getScrollableNode();
806 if (row && element) {
807 rememberTimelinePosition(
808 listIdentityKey,
809 {
810 ...position,
811 offsetWithinRow: element.getBoundingClientRect().top - row.getBoundingClientRect().top,
812 scrollOffset: element.scrollTop,
813 atEnd: isAtEnd,
814 disclosures: {
815 runs: paintedExpandedRunIds,
816 workGroups: paintedExpandedWorkGroupIds,
817 attempts: paintedExpandedAttemptIds,
818 workGroupState: workGroupViewState,
819 },
820 },
821 liveFollowEnabled && !anchoredEndSpace,
822 );
823 }
824 }
825 if (isAtEnd !== undefined && !citationPositioning) {
826 onIsAtEndChange(isAtEnd);
827 }
828 reportContentOverflow();
829 scheduleMinimapRefresh();
830 };
831
832 const handleItemSizeChanged = () => {
833 if (disclosurePinsEndRef.current) {
834 queueMicrotask(pinDisclosureToEnd);
835 scheduleDisclosureSettle();
836 }
837 reportContentOverflow();
838 scheduleMinimapRefresh();
839 };
840
841 useEffect(
842 () => () => {
843 if (minimapRefreshFrameRef.current !== null) {
844 cancelAnimationFrame(minimapRefreshFrameRef.current);
845 minimapRefreshFrameRef.current = null;
846 }
847 },
848 [],
849 );
850
851 useEffect(() => {
852 const frame = requestAnimationFrame(handleScroll);
853 return () => cancelAnimationFrame(frame);
854 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows move the scroll position.
855 }, [handleScroll, rows.length]);
856
857 const savedLiveFollowEnabledRef = useRef(liveFollowEnabled);
858 useLayoutEffect(() => {
859 const wasFollowing = savedLiveFollowEnabledRef.current;
860 savedLiveFollowEnabledRef.current = liveFollowEnabled;
861 if (wasFollowing && !liveFollowEnabled) handleScroll();
862 }, [handleScroll, liveFollowEnabled]);
863
864 useEffect(() => {
865 if (!timelineViewportElement) {
866 return;
867 }
868
869 const measure = () => {
870 const viewportWidth = timelineViewportElement.getBoundingClientRect().width;
871 const contentWidth =
872 timelineViewportElement
873 .querySelector<HTMLElement>("[data-timeline-root]")
874 ?.getBoundingClientRect().width ?? viewportWidth;
875 const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(
876 viewportWidth,
877 contentWidth,
878 );
879 setMinimapHasPersistentGutter((current) =>
880 current === nextHasPersistentGutter ? current : nextHasPersistentGutter,
881 );
882 setMinimapHitStripWidth(resolveTimelineMinimapHitStripWidth(viewportWidth, contentWidth));
883 reportContentOverflow();
884 };
885
886 const frame = requestAnimationFrame(measure);
887
888 const stopObserving = observeResize(timelineViewportElement, measure);
889
890 return () => {
891 cancelAnimationFrame(frame);
892 stopObserving();
893 };
894 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Rows and chat width resize the content without resizing the viewport.
895 }, [timelineViewportElement, rows.length, reportContentOverflow, chatWidth]);
896
897 const sharedState: TimelineRowSharedState = {
898 citationRequest: readyCitationRequest,
899 listRef,
900 timestampFormat,
901 routeThreadKey,
902 threadRef: citationThreadRef,
903 markdownCwd,
904 resolvedTheme,
905 workspaceRoot,
906 skills,
907 runs,
908 activeThreadEnvironmentId,
909 onRevertToTurnCount,
910 onRunShellCommand,
911 findActive,
912 onImageExpand,
913 onFileOpen,
914 onUseArtifactTemplate,
915 onSendAppMessage,
916 onAppFullscreenChange,
917 onFileDownload,
918 openPullRequest,
919 onOpenTurnDiff,
920 onOpenThread,
921 workflowOpening,
922 onForkFromRun,
923 onRollbackCheckpoint,
924 onToggleTurnFold,
925 onToggleAttemptFold,
926 onToggleWorkGroup,
927 onToggleWorkEntry: suspendEndScrollMaintenanceForDisclosure,
928 onCancelWorktreeSetup: onCancelWorktreeSetup ?? null,
929 retryableWorkspacePreparationRunIds,
930 onRetryWorkspacePreparation: onRetryWorkspacePreparation ?? null,
931 onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocally ?? null,
932 onOpenWorktreeSetupTerminal: onOpenWorktreeSetupTerminal ?? null,
933 workGroupViewState,
934 };
935 const compactionAwaitingRow =
936 isCompacting && !rows.some((row) => row.kind === "context-compaction" && row.active);
937 const backgroundWorktreeSetup =
938 worktreeSetup !== null &&
939 worktreeSetup.phase === "running" &&
940 worktreeSetupAgentStarted(worktreeSetup) &&
941 latestRun?.startedAt != null
942 ? worktreeSetup
943 : null;
944 const activityState: TimelineRowActivityState = {
945 isWorking,
946 isCompacting: compactionAwaitingRow,
947 isRevertingCheckpoint,
948 backgroundWorktreeSetup,
949 activeTurnInProgress,
950 awaitingUser,
951 isPreparingWorktree,
952 latestRunId: latestRun?.runId ?? null,
953 };
954 const listHeaderLeadingContent =
955 parentThreadLink === null ? (
956 topFadeEnabled ? (
957 TIMELINE_LIST_FADE_HEADER
958 ) : (
959 TIMELINE_LIST_HEADER
960 )
961 ) : (
962 <div className="messages-timeline-row-frame">
963 <div className="chat-content-lane pt-1 sm:pt-2">
964 <TimelineSystemDivider
965 label="Subagent of"
966 detail={parentThreadLink.title}
967 icon={BotIcon}
968 actionLabel="Open parent thread"
969 onAction={() => onOpenThread(parentThreadLink.threadId)}
970 />
971 </div>
972 </div>
973 );
974 const listHeader = (
975 <>
976 {parentThreadLink === null ? listHeaderLeadingContent : null}
977 {historyControls ? <TimelineHistoryControl {...historyControls} /> : null}
978 {parentThreadLink !== null ? listHeaderLeadingContent : null}
979 </>
980 );
981
982 const canvas = useChatCanvas();
983 const registerTimeline = canvas?.registerTimeline;
984 const setTimelineList = (list: LegendListRef | null) => {
985 listRef.current = list;
986 registerTimeline?.(list?.getScrollableNode() ?? null);
987 };
988
989 useThreadFindPositionReader({
990 findPositionReaderRef,
991 timelineViewportElement,
992 findFoldRunIds,
993 timelineEntries,
994 latestRun,
995 runningRunId,
996 isWorking,
997 runlessWorkActive,
998 rows,
999 contentInsetEndAdjustment,
1000 });
1001
1002 useThreadFindNavigation({
1003 listReady: findListReady,
1004 historyControls,
1005 entries: timelineEntries,
1006 container: timelineViewportElement,
1007 query: normalizedFindQuery,
1008 match: activeFindMatch,
1009 navigationId: findNavigationId,
1010 rowIndex: activeFindMatch ? rows.findIndex((row) => row.id === activeFindMatch.entryId) : -1,
1011 listRef,
1012 contentInsetEndAdjustment,
1013 });
1014
1015 // Each row carries its own provider. LegendList moves rows into their
1016 // containers one commit after this component renders, so a provider around
1017 // the list would re-render the outgoing thread's rows with the incoming
1018 // thread's context just before they unmount. extraData hands a changed
1019 // sharedState to the rows that stay.
1020 const renderItem = ({ item }: { item: MessagesTimelineRow }) => (
1021 <TimelineRowCtx value={sharedState}>
1022 <div className="messages-timeline-row-frame">
1023 <div
1024 className="@container/chat-lane chat-content-lane overflow-x-clip"
1025 data-timeline-root="true"
1026 >
1027 <TimelineRowContent row={item} />
1028 </div>
1029 </div>
1030 </TimelineRowCtx>
1031 );
1032 const listExtraData = { identity: listIdentityKey, rowCount: rows.length, sharedState };
1033
1034 const forwardMinimapWheel = (event: WheelEvent) => {
1035 const scrollNode = listRef.current?.getScrollableNode();
1036 if (scrollNode) forwardWheelToTimeline(event, scrollNode);
1037 };
1038
1039 if (
1040 rows.length === 0 &&
1041 !isWorking &&
1042 parentThreadLink === null &&
1043 historyControls === undefined &&
1044 footer === null
1045 ) {
1046 if (hideEmptyPlaceholder) {
1047 return <div className="h-full min-h-0 bg-background" data-timeline-loading="true" />;
1048 }
1049 return (
1050 <div
1051 className="flex h-full items-center justify-center ps-(--chat-lane-inset-start) pe-(--chat-lane-inset-end)"
1052 style={{ paddingBottom: emptyPlaceholderInset }}
1053 >
1054 <p className="text-sm text-muted-foreground/30">
1055 Send a message to start the conversation.
1056 </p>
1057 </div>
1058 );
1059 }
1060
1061 return (
1062 <MarkdownFindContext value={findActive}>
1063 <TimelineRowActivityCtx value={activityState}>
1064 <TooltipScrollDismissArea
1065 ref={setTimelineViewportElement}
1066 className="relative h-full min-h-0"
1067 data-assistant-citation-viewport="true"
1068 >
1069 {onCiteAssistantText && citationThreadRef ? (
1070 <AssistantSelectionToolbar
1071 viewport={timelineViewportElement}
1072 threadRef={citationThreadRef}
1073 onCite={onCiteAssistantText}
1074 />
1075 ) : null}
1076 <LegendList<MessagesTimelineRow>
1077 ref={setTimelineList}
1078 data={rows}
1079 extraData={listExtraData}
1080 keyExtractor={keyExtractor}
1081 getItemType={getItemType}
1082 renderItem={renderItem}
1083 estimatedItemSize={90}
1084 initialScrollAtEnd={
1085 !findActive && citationRequest === null && rememberedPosition?.atEnd !== false
1086 }
1087 // Legend needs a data refresh to mount new pins without a scroll event.
1088 dataVersion={readyCitationRequest?.key ?? listIdentityKey}
1089 {...(alwaysRender ? { alwaysRender } : {})}
1090 onLoad={handleListLoad}
1091 {...(anchoredEndSpace ? { anchoredEndSpace } : {})}
1092 contentInsetEndAdjustment={anchoredEndSpace ? contentInsetEndAdjustment : 0}
1093 maintainScrollAtEnd={
1094 citationPositioning ||
1095 (restoringThreadPosition && rememberedPosition?.atEnd === false) ||
1096 anchoredEndSpace ||
1097 !liveFollowEnabled ||
1098 fullscreenAppRowId !== null ||
1099 disclosureToggleSettling
1100 ? false
1101 : isWorking && !prefersReducedMotion && settlingListIdentity === null
1102 ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH
1103 : TIMELINE_MAINTAIN_SCROLL_AT_END
1104 }
1105 maintainVisibleContentPosition={
1106 findActive ||
1107 citationPositioning ||
1108 (restoringThreadPosition && rememberedPosition?.atEnd === false)
1109 ? false
1110 : maintainVisibleContentPosition
1111 }
1112 maintainScrollAtEndThreshold={1}
1113 onScroll={handleScroll}
1114 onItemSizeChanged={handleItemSizeChanged}
1115 className={cn(
1116 "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",
1117 topFadeEnabled && "topbar-scroll-fade",
1118 )}
1119 ListHeaderComponent={listHeader}
1120 ListFooterComponent={timelineListFooter}
1121 />
1122 <TimelineMinimap
1123 items={minimapItems}
1124 hasPersistentGutter={minimapHasPersistentGutter}
1125 hitStripWidth={minimapHitStripWidth}
1126 currentIndex={minimapCurrentIndex}
1127 stripMap={minimapStripMap}
1128 onWheel={forwardMinimapWheel}
1129 onSelect={(item) => {
1130 onManualNavigation();
1131 void listRef.current?.scrollToIndex({
1132 index: item.rowIndex,
1133 animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
1134 viewOffset: 24,
1135 });
1136 }}
1137 />
1138 </TooltipScrollDismissArea>
1139 </TimelineRowActivityCtx>
1140 </MarkdownFindContext>
1141 );
1142});
1143
1144function TimelineHistoryControl(props: MessagesTimelineHistoryControls) {
1145 if (!props.hasMoreHistory && props.error === null) {
1146 return null;
1147 }
1148 return (
1149 <div className="messages-timeline-row-frame">
1150 <div className="chat-content-lane flex flex-col gap-1.5 pb-2">
1151 {props.hasMoreHistory ? (
1152 <button
1153 type="button"
1154 disabled={props.loading}
1155 aria-label="Load earlier turns"
1156 onClick={() => props.onLoadEarlier()}
1157 className="flex w-full cursor-pointer items-center gap-3 py-1.5 text-muted-foreground text-xs hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring disabled:cursor-default"
1158 >
1159 <span aria-hidden="true" className="h-px flex-1 bg-border/70" />
1160 <span className="shrink-0">
1161 {props.loading ? "Loading earlier turns…" : "Load earlier turns"}
1162 </span>
1163 <span aria-hidden="true" className="h-px flex-1 bg-border/70" />
1164 </button>
1165 ) : null}
1166 {props.error !== null ? (
1167 <p role="status" className="text-center text-muted-foreground text-xs">
1168 {props.error}
1169 </p>
1170 ) : null}
1171 </div>
1172 </div>
1173 );
1174}
1175
1176function keyExtractor(item: MessagesTimelineRow) {
1177 return item.id;
1178}
1179
1180// LegendList estimates unmeasured rows from the running average size of their
1181// type. One type for every assistant reply lets a few very long replies, or
1182// one that is streaming, lift the estimate for short replies to thousands of
1183// pixels. Rows then mount one at a time, each measurement shrinks the list
1184// and mounts the next row in the same commit, and scrolling into unmeasured
1185// history exceeds React's nested update limit. Doubling-length buckets keep
1186// each average within about 2x of the rows it estimates.
1187function getItemType(item: MessagesTimelineRow) {
1188 if (item.kind !== "message") return item.kind;
1189 const lengthBucket = Math.max(0, Math.floor(Math.log2(item.message.text.length / 1000)));
1190 return `message:${item.message.role}:${lengthBucket}`;
1191}
1192
1193const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: TimelineRow }) {
1194 const isExpandedToolGroup = row.kind === "work" && row.isExpandedToolGroup;
1195 const isSubagentGroup = row.kind === "event" && row.projectedItem.item.type === "subagent";
1196 const isWorkLogRow =
1197 row.kind === "work" ||
1198 row.kind === "work-live" ||
1199 row.kind === "work-toggle" ||
1200 row.kind === "thinking";
1201 const isExpandedToolGroupHeader =
1202 (row.kind === "work-toggle" || row.kind === "work-live" || row.kind === "thinking") &&
1203 row.expanded === true;
1204
1205 return (
1206 <div
1207 className={cn(
1208 isWorkLogRow || isSubagentGroup
1209 ? undefined
1210 : row.kind === "turn-fold" || row.kind === "working"
1211 ? "pb-1.5"
1212 : (row.kind === "message" &&
1213 row.message.role === "assistant" &&
1214 !row.showAssistantMeta) ||
1215 row.kind === "worktree-setup" ||
1216 row.kind === "event" ||
1217 row.kind === "attempt-fold" ||
1218 row.kind === "html-render" ||
1219 row.kind === "mcp-app"
1220 ? "pb-2"
1221 : "pb-4",
1222 (row.kind === "message" && row.message.role === "assistant") ||
1223 row.kind === "assistant-meta"
1224 ? "group/assistant"
1225 : null,
1226 )}
1227 data-timeline-row-id={row.id}
1228 data-timeline-row-kind={row.kind}
1229 data-message-id={
1230 row.kind === "message" || row.kind === "assistant-meta" ? row.message.id : undefined
1231 }
1232 data-message-role={row.kind === "message" ? row.message.role : undefined}
1233 >
1234 {isWorkLogRow ? (
1235 <WorkLogBlock
1236 continues={row.continuesWorkLog}
1237 layout={
1238 isExpandedToolGroup
1239 ? "group-content"
1240 : isExpandedToolGroupHeader
1241 ? "group-header"
1242 : "standalone"
1243 }
1244 >
1245 {row.kind === "work" ? (
1246 <WorkGroupSection
1247 anchorKey={row.id}
1248 groupedEntries={row.groupedEntries}
1249 isExpandedToolGroup={row.isExpandedToolGroup}
1250 displayLabel={row.displayLabel}
1251 />
1252 ) : null}
1253 {row.kind === "work-live" ? <LiveWorkEntryTimelineRow row={row} /> : null}
1254 {row.kind === "work-toggle" ? <WorkGroupToggleTimelineRow row={row} /> : null}
1255 {row.kind === "thinking" ? <ThinkingTimelineRow row={row} /> : null}
1256 </WorkLogBlock>
1257 ) : null}
1258 {row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
1259 {row.kind === "attempt-fold" ? <AttemptFoldTimelineRow row={row} /> : null}
1260 {row.kind === "context-compaction" ? <ContextCompactionTimelineRow row={row} /> : null}
1261 {row.kind === "message" && row.message.role === "user" ? <UserMessageRow row={row} /> : null}
1262 {row.kind === "message" && row.message.role === "assistant" ? (
1263 <AssistantTimelineRow row={row} />
1264 ) : null}
1265 {row.kind === "assistant-meta" ? <AssistantMetaTimelineRow row={row} /> : null}
1266 {row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
1267 {row.kind === "html-render" ? <HtmlRenderTimelineRow row={row} /> : null}
1268 {row.kind === "mcp-app" ? <McpAppTimelineRow row={row} /> : null}
1269 {row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
1270 {row.kind === "worktree-setup" ? <WorktreeSetupTimelineRow row={row} /> : null}
1271 {row.kind === "event" ? <V2EventTimelineRow row={row} /> : null}
1272 </div>
1273 );
1274});
1275
1276function WorktreeSetupTimelineRow({
1277 row,
1278}: {
1279 row: Extract<TimelineRow, { kind: "worktree-setup" }>;
1280}) {
1281 const ctx = use(TimelineRowCtx);
1282 const terminalId = row.snapshot.setupScript?.terminalId ?? null;
1283 const openTerminal = ctx.onOpenWorktreeSetupTerminal;
1284 const onOpenTerminal = openTerminal && terminalId ? () => openTerminal(terminalId) : null;
1285 return (
1286 <WorktreeSetupCard
1287 snapshot={row.snapshot}
1288 embedded={row.embedded}
1289 onCancel={row.embedded ? null : ctx.onCancelWorktreeSetup}
1290 onWorkLocally={
1291 !row.embedded && row.snapshot.phase === "running" ? ctx.onWorktreeSetupWorkLocally : null
1292 }
1293 onOpenTerminal={onOpenTerminal}
1294 />
1295 );
1296}
1297
1298function ContextCompactionTimelineRow({
1299 row,
1300}: {
1301 row: Extract<TimelineRow, { kind: "context-compaction" }>;
1302}) {
1303 const content = (
1304 <span className="flex items-center gap-1.5">
1305 <Minimize2Icon aria-hidden="true" className="size-3" />
1306 {row.tokenCounts ? (
1307 <>
1308 Context compacted {row.tokenCounts.before}
1309 <ArrowRightIcon aria-hidden="true" className="size-3" />
1310 {row.tokenCounts.after} tokens
1311 </>
1312 ) : (
1313 row.label
1314 )}
1315 </span>
1316 );
1317 return (
1318 <div
1319 role="separator"
1320 aria-label={row.label}
1321 className="mx-auto flex w-full max-w-(--chat-content-max-width) items-center gap-3 py-1 text-muted-foreground text-xs"
1322 >
1323 <span className="h-px flex-1 bg-border/70" />
1324 <span
1325 ref={row.active ? observeVisibleAnimation : undefined}
1326 className="relative shrink-0 overflow-hidden"
1327 >
1328 {content}
1329 {row.active ? <ActivityShimmerOverlay>{content}</ActivityShimmerOverlay> : null}
1330 </span>
1331 <span className="h-px flex-1 bg-border/70" />
1332 </div>
1333 );
1334}
1335
1336function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-fold" }> }) {
1337 const ctx = use(TimelineRowCtx);
1338
1339 return (
1340 <div className="group/timeline-row relative flex items-center gap-1 border-b border-border/60 pb-2 pe-0.5 pt-1">
1341 <button
1342 type="button"
1343 aria-expanded={row.expanded}
1344 data-scroll-anchor-ignore
1345 onClick={() => ctx.onToggleTurnFold(row.runId)}
1346 className="flex cursor-pointer select-none items-center gap-1 rounded-md px-1 text-sm leading-relaxed text-muted-foreground tabular-nums transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
1347 >
1348 <span>{row.label}</span>
1349 <MorphIcon className="size-3.5" icon={row.expanded ? ChevronDown : ChevronRight} />
1350 </button>
1351 <TimelineRowTimestamp
1352 createdAt={row.createdAt}
1353 timestampFormat={ctx.timestampFormat}
1354 className="ms-auto"
1355 />
1356 </div>
1357 );
1358}
1359
1360function AttemptFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "attempt-fold" }> }) {
1361 const ctx = use(TimelineRowCtx);
1362
1363 return (
1364 <button
1365 type="button"
1366 aria-expanded={row.expanded}
1367 data-scroll-anchor-ignore
1368 data-superseded-attempt-id={row.attemptId}
1369 onClick={() => ctx.onToggleAttemptFold(row.attemptId)}
1370 className="flex w-full cursor-pointer select-none items-center gap-2 rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-left transition-colors hover:bg-muted/35 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
1371 >
1372 <MorphIcon
1373 className="size-3.5 shrink-0 text-muted-foreground"
1374 icon={row.expanded ? ChevronDown : ChevronRight}
1375 />
1376 <span className="text-xs font-medium text-foreground/80">{row.label}</span>
1377 <span className="text-2xs text-muted-foreground">Cut off by a steer</span>
1378 </button>
1379 );
1380}