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

MessagesTimeline.tsx

1,423 lines51.6 KB

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