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