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, CircleAlertIcon, 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 &&
950 !rows.some(
951 (row) =>
952 (row.kind === "context-compaction" && row.active) ||
953 (row.kind === "working" && row.compacting),
954 );
955 const backgroundWorktreeSetup =
956 worktreeSetup !== null &&
957 worktreeSetup.phase === "running" &&
958 worktreeSetupAgentStarted(worktreeSetup) &&
959 latestRun?.startedAt != null
960 ? worktreeSetup
961 : null;
962 const activityState: TimelineRowActivityState = {
963 isWorking,
964 isCompacting: compactionAwaitingRow,
965 isRevertingCheckpoint,
966 backgroundWorktreeSetup,
967 activeTurnInProgress,
968 awaitingUser: awaitingUser !== null,
969 isPreparingWorktree,
970 latestRunId: latestRun?.runId ?? null,
971 };
972 // Mounted in both the empty and filled timeline so a thread's first turn
973 // starts from a baseline instead of a fresh, silent region.
974 const activityAnnouncer = (
975 <ThreadActivityAnnouncer
976 threadKey={paintOnly || !announceTurnStatus ? null : listIdentityKey}
977 status={awaitingUser ?? (isWorking ? "working" : "idle")}
978 requestId={awaitingRequestId}
979 runId={announcedRun?.runId ?? null}
980 runStatus={announcedRun?.status ?? null}
981 detailBehind={detailBehindShell}
982 />
983 );
984 const listHeaderLeadingContent =
985 parentThreadLink === null ? (
986 topFadeEnabled ? (
987 TIMELINE_LIST_FADE_HEADER
988 ) : (
989 TIMELINE_LIST_HEADER
990 )
991 ) : (
992 <div className="messages-timeline-row-frame">
993 <div className="chat-content-lane pt-1 sm:pt-2">
994 <TimelineSystemDivider
995 label="Subagent of"
996 detail={parentThreadLink.title}
997 icon={BotIcon}
998 actionLabel="Open parent thread"
999 onAction={() => onOpenThread(parentThreadLink.threadId)}
1000 />
1001 </div>
1002 </div>
1003 );
1004 const listHeader = (
1005 <>
1006 {parentThreadLink === null ? listHeaderLeadingContent : null}
1007 {historyControls ? <TimelineHistoryControl {...historyControls} /> : null}
1008 {parentThreadLink !== null ? listHeaderLeadingContent : null}
1009 </>
1010 );
1011
1012 const canvas = useChatCanvas();
1013 const registerTimeline = canvas?.registerTimeline;
1014 const setTimelineList = (list: LegendListRef | null) => {
1015 listRef.current = list;
1016 registerTimeline?.(list?.getScrollableNode() ?? null);
1017 };
1018
1019 useThreadFindPositionReader({
1020 findPositionReaderRef,
1021 timelineViewportElement,
1022 findFoldRunIds,
1023 timelineEntries,
1024 latestRun,
1025 runningRunId,
1026 isWorking,
1027 runlessWorkActive,
1028 rows,
1029 contentInsetEndAdjustment,
1030 });
1031
1032 useThreadFindNavigation({
1033 listReady: findListReady,
1034 historyControls,
1035 entries: timelineEntries,
1036 container: timelineViewportElement,
1037 query: normalizedFindQuery,
1038 match: activeFindMatch,
1039 navigationId: findNavigationId,
1040 rowIndex: activeFindMatch ? rows.findIndex((row) => row.id === activeFindMatch.entryId) : -1,
1041 listRef,
1042 contentInsetEndAdjustment,
1043 });
1044
1045 // Each row carries its own provider. LegendList moves rows into their
1046 // containers one commit after this component renders, so a provider around
1047 // the list would re-render the outgoing thread's rows with the incoming
1048 // thread's context just before they unmount. extraData hands a changed
1049 // sharedState to the rows that stay.
1050 const renderItem = ({ item }: { item: MessagesTimelineRow }) => (
1051 <TimelineRowCtx value={sharedState}>
1052 <div className="messages-timeline-row-frame">
1053 <div
1054 className="@container/chat-lane chat-content-lane overflow-x-clip"
1055 data-timeline-root="true"
1056 >
1057 <TimelineRowContent row={item} />
1058 </div>
1059 </div>
1060 </TimelineRowCtx>
1061 );
1062 const listExtraData = { identity: listIdentityKey, rowCount: rows.length, sharedState };
1063
1064 const forwardMinimapWheel = (event: WheelEvent) => {
1065 const scrollNode = listRef.current?.getScrollableNode();
1066 if (scrollNode) forwardWheelToTimeline(event, scrollNode);
1067 };
1068
1069 if (
1070 rows.length === 0 &&
1071 !isWorking &&
1072 parentThreadLink === null &&
1073 historyControls === undefined &&
1074 footer === null
1075 ) {
1076 if (hideEmptyPlaceholder) {
1077 return (
1078 <>
1079 {activityAnnouncer}
1080 <div className="h-full min-h-0 bg-background" data-timeline-loading="true" />
1081 </>
1082 );
1083 }
1084 return (
1085 <>
1086 {activityAnnouncer}
1087 <div
1088 className="flex h-full items-center justify-center ps-(--chat-lane-inset-start) pe-(--chat-lane-inset-end)"
1089 style={{ paddingBottom: emptyPlaceholderInset }}
1090 >
1091 <p className="text-sm text-muted-foreground/30">
1092 Send a message to start the conversation.
1093 </p>
1094 </div>
1095 </>
1096 );
1097 }
1098
1099 return (
1100 <>
1101 {activityAnnouncer}
1102 <MarkdownFindContext value={findActive}>
1103 <TimelineRowActivityCtx value={activityState}>
1104 <TooltipScrollDismissArea
1105 ref={setTimelineViewportElement}
1106 className="relative h-full min-h-0"
1107 data-assistant-citation-viewport="true"
1108 >
1109 {onCiteAssistantText && citationThreadRef ? (
1110 <AssistantSelectionToolbar
1111 viewport={timelineViewportElement}
1112 threadRef={citationThreadRef}
1113 onCite={onCiteAssistantText}
1114 />
1115 ) : null}
1116 <LegendList<MessagesTimelineRow>
1117 ref={setTimelineList}
1118 data={rows}
1119 extraData={listExtraData}
1120 keyExtractor={keyExtractor}
1121 getItemType={getItemType}
1122 renderItem={renderItem}
1123 estimatedItemSize={90}
1124 initialScrollAtEnd={
1125 !findActive && citationRequest === null && rememberedPosition?.atEnd !== false
1126 }
1127 // Legend needs a data refresh to mount new pins without a scroll event.
1128 dataVersion={readyCitationRequest?.key ?? listIdentityKey}
1129 {...(alwaysRender ? { alwaysRender } : {})}
1130 onLoad={handleListLoad}
1131 {...(anchoredEndSpace ? { anchoredEndSpace } : {})}
1132 contentInsetEndAdjustment={anchoredEndSpace ? contentInsetEndAdjustment : 0}
1133 maintainScrollAtEnd={
1134 citationPositioning ||
1135 (restoringThreadPosition && rememberedPosition?.atEnd === false) ||
1136 anchoredEndSpace ||
1137 !liveFollowEnabled ||
1138 fullscreenAppRowId !== null ||
1139 disclosureToggleSettling
1140 ? false
1141 : isWorking && !prefersReducedMotion && settlingListIdentity === null
1142 ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH
1143 : TIMELINE_MAINTAIN_SCROLL_AT_END
1144 }
1145 maintainVisibleContentPosition={
1146 findActive ||
1147 citationPositioning ||
1148 (restoringThreadPosition && rememberedPosition?.atEnd === false)
1149 ? false
1150 : maintainVisibleContentPosition
1151 }
1152 maintainScrollAtEndThreshold={1}
1153 onScroll={handleScroll}
1154 onItemSizeChanged={handleItemSizeChanged}
1155 className={cn(
1156 "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",
1157 topFadeEnabled && "topbar-scroll-fade",
1158 )}
1159 ListHeaderComponent={listHeader}
1160 ListFooterComponent={timelineListFooter}
1161 />
1162 <TimelineMinimap
1163 items={minimapItems}
1164 hasPersistentGutter={minimapHasPersistentGutter}
1165 hitStripWidth={minimapHitStripWidth}
1166 currentIndex={minimapCurrentIndex}
1167 stripMap={minimapStripMap}
1168 onWheel={forwardMinimapWheel}
1169 onSelect={(item) => {
1170 onManualNavigation();
1171 void listRef.current?.scrollToIndex({
1172 index: item.rowIndex,
1173 animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
1174 viewOffset: 24,
1175 });
1176 }}
1177 />
1178 </TooltipScrollDismissArea>
1179 </TimelineRowActivityCtx>
1180 </MarkdownFindContext>
1181 </>
1182 );
1183});
1184
1185function TimelineHistoryControl(props: MessagesTimelineHistoryControls) {
1186 if (!props.hasMoreHistory && props.error === null) {
1187 return null;
1188 }
1189 return (
1190 <div className="messages-timeline-row-frame">
1191 <div className="chat-content-lane flex flex-col gap-1.5 pb-2">
1192 {props.hasMoreHistory ? (
1193 <button
1194 type="button"
1195 disabled={props.loading}
1196 aria-label="Load earlier turns"
1197 onClick={() => props.onLoadEarlier()}
1198 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"
1199 >
1200 <span aria-hidden="true" className="h-px flex-1 bg-border/70" />
1201 <span className="shrink-0">
1202 {props.loading ? "Loading earlier turns…" : "Load earlier turns"}
1203 </span>
1204 <span aria-hidden="true" className="h-px flex-1 bg-border/70" />
1205 </button>
1206 ) : null}
1207 {props.error !== null ? (
1208 <p role="status" className="text-center text-muted-foreground text-xs">
1209 {props.error}
1210 </p>
1211 ) : null}
1212 </div>
1213 </div>
1214 );
1215}
1216
1217function keyExtractor(item: MessagesTimelineRow) {
1218 return item.id;
1219}
1220
1221// LegendList estimates unmeasured rows from the running average size of their
1222// type. One type for every assistant reply lets a few very long replies, or
1223// one that is streaming, lift the estimate for short replies to thousands of
1224// pixels. Rows then mount one at a time, each measurement shrinks the list
1225// and mounts the next row in the same commit, and scrolling into unmeasured
1226// history exceeds React's nested update limit. Doubling-length buckets keep
1227// each average within about 2x of the rows it estimates.
1228function getItemType(item: MessagesTimelineRow) {
1229 if (item.kind !== "message") return item.kind;
1230 const lengthBucket = Math.max(0, Math.floor(Math.log2(item.message.text.length / 1000)));
1231 return `message:${item.message.role}:${lengthBucket}`;
1232}
1233
1234const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: TimelineRow }) {
1235 const isExpandedToolGroup = row.kind === "work" && row.isExpandedToolGroup;
1236 const isSubagentGroup = row.kind === "event" && row.projectedItem.item.type === "subagent";
1237 const isWorkLogRow =
1238 row.kind === "work" ||
1239 row.kind === "work-live" ||
1240 row.kind === "work-toggle" ||
1241 row.kind === "thinking";
1242 const isExpandedToolGroupHeader =
1243 (row.kind === "work-toggle" || row.kind === "work-live" || row.kind === "thinking") &&
1244 row.expanded === true;
1245
1246 return (
1247 <div
1248 className={cn(
1249 isWorkLogRow || isSubagentGroup
1250 ? undefined
1251 : row.kind === "turn-fold" || row.kind === "working"
1252 ? "pb-1.5"
1253 : (row.kind === "message" &&
1254 row.message.role === "assistant" &&
1255 !row.showAssistantMeta) ||
1256 row.kind === "worktree-setup" ||
1257 row.kind === "event" ||
1258 row.kind === "attempt-fold" ||
1259 row.kind === "html-render" ||
1260 row.kind === "mcp-app"
1261 ? "pb-2"
1262 : "pb-4",
1263 (row.kind === "message" && row.message.role === "assistant") ||
1264 row.kind === "assistant-meta"
1265 ? "group/assistant"
1266 : null,
1267 )}
1268 data-timeline-row-id={row.id}
1269 data-timeline-row-kind={row.kind}
1270 data-message-id={
1271 row.kind === "message" || row.kind === "assistant-meta" ? row.message.id : undefined
1272 }
1273 data-message-role={row.kind === "message" ? row.message.role : undefined}
1274 >
1275 {isWorkLogRow ? (
1276 <WorkLogBlock
1277 continues={row.continuesWorkLog}
1278 layout={
1279 isExpandedToolGroup
1280 ? "group-content"
1281 : isExpandedToolGroupHeader
1282 ? "group-header"
1283 : "standalone"
1284 }
1285 >
1286 {row.kind === "work" ? (
1287 <WorkGroupSection
1288 anchorKey={row.id}
1289 groupedEntries={row.groupedEntries}
1290 isExpandedToolGroup={row.isExpandedToolGroup}
1291 displayLabel={row.displayLabel}
1292 />
1293 ) : null}
1294 {row.kind === "work-live" ? <LiveWorkEntryTimelineRow row={row} /> : null}
1295 {row.kind === "work-toggle" ? <WorkGroupToggleTimelineRow row={row} /> : null}
1296 {row.kind === "thinking" ? <ThinkingTimelineRow row={row} /> : null}
1297 </WorkLogBlock>
1298 ) : null}
1299 {row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
1300 {row.kind === "attempt-fold" ? <AttemptFoldTimelineRow row={row} /> : null}
1301 {row.kind === "context-compaction" ? <ContextCompactionTimelineRow row={row} /> : null}
1302 {row.kind === "message" && row.message.role === "user" ? <UserMessageRow row={row} /> : null}
1303 {row.kind === "message" && row.message.role === "assistant" ? (
1304 <AssistantTimelineRow row={row} />
1305 ) : null}
1306 {row.kind === "assistant-meta" ? <AssistantMetaTimelineRow row={row} /> : null}
1307 {row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
1308 {row.kind === "html-render" ? <HtmlRenderTimelineRow row={row} /> : null}
1309 {row.kind === "mcp-app" ? <McpAppTimelineRow row={row} /> : null}
1310 {row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
1311 {row.kind === "worktree-setup" ? <WorktreeSetupTimelineRow row={row} /> : null}
1312 {row.kind === "event" ? <V2EventTimelineRow row={row} /> : null}
1313 </div>
1314 );
1315});
1316
1317function WorktreeSetupTimelineRow({
1318 row,
1319}: {
1320 row: Extract<TimelineRow, { kind: "worktree-setup" }>;
1321}) {
1322 const ctx = use(TimelineRowCtx);
1323 const terminalId = row.snapshot.setupScript?.terminalId ?? null;
1324 const openTerminal = ctx.onOpenWorktreeSetupTerminal;
1325 const onOpenTerminal = openTerminal && terminalId ? () => openTerminal(terminalId) : null;
1326 return (
1327 <WorktreeSetupCard
1328 snapshot={row.snapshot}
1329 embedded={row.embedded}
1330 onCancel={row.embedded ? null : ctx.onCancelWorktreeSetup}
1331 onWorkLocally={
1332 !row.embedded && row.snapshot.phase === "running" ? ctx.onWorktreeSetupWorkLocally : null
1333 }
1334 onOpenTerminal={onOpenTerminal}
1335 />
1336 );
1337}
1338
1339function ContextCompactionTimelineRow({
1340 row,
1341}: {
1342 row: Extract<TimelineRow, { kind: "context-compaction" }>;
1343}) {
1344 const label =
1345 row.title && row.label.startsWith("Context compacted")
1346 ? row.title + row.label.slice("Context compacted".length)
1347 : row.label;
1348 const content = (
1349 <span className="flex min-w-0 items-center gap-1.5">
1350 {row.failed ? (
1351 <CircleAlertIcon aria-hidden="true" className="size-3 shrink-0" />
1352 ) : (
1353 <Minimize2Icon aria-hidden="true" className="size-3" />
1354 )}
1355 {row.tokenCounts ? (
1356 <>
1357 {row.title ?? "Context compacted"} {row.tokenCounts.before}
1358 <ArrowRightIcon aria-hidden="true" className="size-3" />
1359 {row.tokenCounts.after} tokens
1360 </>
1361 ) : (
1362 label
1363 )}
1364 {row.failure ? (
1365 <span className="min-w-0 truncate opacity-80">· {row.failure}</span>
1366 ) : null}
1367 </span>
1368 );
1369 return (
1370 <div
1371 role="separator"
1372 aria-label={row.failure ? `${label}: ${row.failure}` : label}
1373 className={cn(
1374 "mx-auto flex w-full max-w-(--chat-content-max-width) items-center gap-3 py-1 text-xs",
1375 row.failed ? "text-destructive" : "text-muted-foreground",
1376 )}
1377 >
1378 <span className={cn("h-px flex-1", row.failed ? "bg-destructive/30" : "bg-border/70")} />
1379 <span
1380 ref={row.active ? observeVisibleAnimation : undefined}
1381 className="relative min-w-0 overflow-hidden"
1382 >
1383 {content}
1384 {row.active ? <ActivityShimmerOverlay>{content}</ActivityShimmerOverlay> : null}
1385 </span>
1386 <span className={cn("h-px flex-1", row.failed ? "bg-destructive/30" : "bg-border/70")} />
1387 </div>
1388 );
1389}
1390
1391function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-fold" }> }) {
1392 const ctx = use(TimelineRowCtx);
1393
1394 return (
1395 <div className="group/timeline-row relative flex items-center gap-1 border-b border-border/60 pb-2 pe-0.5 pt-1">
1396 <button
1397 type="button"
1398 aria-expanded={row.expanded}
1399 data-scroll-anchor-ignore
1400 onClick={() => ctx.onToggleTurnFold(row.runId)}
1401 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"
1402 >
1403 <span>{row.label}</span>
1404 <MorphIcon className="size-3.5" icon={row.expanded ? ChevronDown : ChevronRight} />
1405 </button>
1406 <TimelineRowTimestamp
1407 createdAt={row.createdAt}
1408 timestampFormat={ctx.timestampFormat}
1409 className="ms-auto"
1410 />
1411 </div>
1412 );
1413}
1414
1415function AttemptFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "attempt-fold" }> }) {
1416 const ctx = use(TimelineRowCtx);
1417
1418 return (
1419 <button
1420 type="button"
1421 aria-expanded={row.expanded}
1422 data-scroll-anchor-ignore
1423 data-superseded-attempt-id={row.attemptId}
1424 onClick={() => ctx.onToggleAttemptFold(row.attemptId)}
1425 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"
1426 >
1427 <MorphIcon
1428 className="size-3.5 shrink-0 text-muted-foreground"
1429 icon={row.expanded ? ChevronDown : ChevronRight}
1430 />
1431 <span className="text-xs font-medium text-foreground/80">{row.label}</span>
1432 <span className="text-2xs text-muted-foreground">Cut off by a steer</span>
1433 </button>
1434 );
1435}