Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MessagesTimeline.tsx

1,454 lines52.8 KB

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