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