@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 1,933 lines 73.6 KB
Raw
1 import { T, useGT, useMessages, Var } from "gt-react";
2 import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread";
3 import { threadErrorText } from "@t3tools/client-runtime/state/threads";
4 import { threadEnvironment } from "../../state/threads";
5 import { useAtomCommand } from "../../state/use-atom-command";
6 import type { ToolCallDiffTarget } from "../../diffPanelStore";
7 import { AudioPreviewUnmountContext } from "../files/AudioPreview";
8 import { ThreadFindTimelineContext } from "./ThreadFindProvider";
9 import { MarkdownFindContext } from "./markdownFindContext";
10 import { useChatCanvas } from "./ChatCanvasContext";
11 import { WorkLogBlock } from "./WorkLog";
12 import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow";
13 import type { WorktreeSetupSnapshot } from "@t3tools/contracts";
14 import { deriveTimelineMinimapItems } from "./timelineMinimapItems";
15 import {
16 type AssistantCitation,
17 type EnvironmentId,
18 type MessageId,
19 type OrchestrationV2TurnItem,
20 type RunAttemptId,
21 type ServerProviderSkill,
22 type RunId,
23 ThreadId,
24 } from "@t3tools/contracts";
25 import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
26 import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
27 import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
28 import { observeResize } from "~/lib/observeResize";
29 import { useStableCallback } from "~/hooks/useStableCallback";
30
31 const NOOP_USE_ARTIFACT_TEMPLATE = () => {};
32 const EMPTY_PENDING_APPROVALS: ReadonlyArray<PendingApproval> = [];
33 const EMPTY_RESPONDING_REQUEST_IDS: TimelineRowSharedState["respondingRequestIds"] = [];
34
35 const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
36
37 import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
38 import { observeVisibleAnimation } from "../../lib/visibleAnimation";
39 import {
40 memo,
41 use,
42 useContext,
43 useLayoutEffect,
44 useEffect,
45 useEffectEvent,
46 useRef,
47 useState,
48 type ReactNode,
49 type SyntheticEvent,
50 } from "react";
51 import {
52 LegendList,
53 type LegendListRef,
54 type MaintainScrollAtEndOptions,
55 } from "@legendapp/list/react";
56 import { type PendingApproval, type TimelineEntry } from "../../session-logic";
57 import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
58 import { type ChatFileAttachment, type TurnDiffSummary } from "../../types";
59 import {
60 ArrowRightIcon,
61 BotIcon,
62 CircleAlertIcon,
63 MessagesSquareIcon,
64 Minimize2Icon,
65 ChevronDownIcon,
66 ChevronRightIcon,
67 } from "lucide-react";
68 import { Skeleton } from "../ui/skeleton";
69 import { ExpandedImagePreview } from "./ExpandedImagePreview";
70 import {
71 CHAT_TIMELINE_ANCHOR_OFFSET,
72 readTimelinePosition,
73 type RememberedTimelinePosition,
74 rememberTimelinePosition,
75 resolveDisclosureRevealScrollDelta,
76 } from "./timelineScrollAnchoring";
77 import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";
78 import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
79 import { type AssistantCitationRequest } from "./AssistantCitationSource";
80 import { useAssistantCitationTarget } from "./useAssistantCitationTarget";
81 import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
82 import { resolveCitationPhase, type CitedHistory } from "./citationProcedure";
83 import {
84 resolveTimelineIsAtEnd,
85 resolveTimelineMinimapHasPersistentGutter,
86 resolveTimelineMinimapCurrentIndex,
87 isTimelineMinimapTurnVisible,
88 resolveTimelineMinimapVisibleRange,
89 resolveTimelineMinimapHitStripWidth,
90 TIMELINE_MINIMAP_TARGET_OFFSET,
91 timelineTurnFoldRunIdsByEntryId,
92 liveAnswerPreview,
93 type MessagesTimelineRow,
94 type TimelineLatestRun,
95 } from "./MessagesTimeline.logic";
96 import { type ThreadFindMatch } from "./threadFind";
97 import { useThreadFindNavigation } from "./useThreadFindNavigation";
98 import { TooltipScrollDismissArea } from "../ui/tooltip";
99 import { WorktreeSetupCard } from "./WorktreeSetupCard";
100 import { useOpenPrLink } from "~/lib/openPullRequestLink";
101 import { useMediaQuery } from "~/hooks/useMediaQuery";
102 import { cn } from "~/lib/utils";
103 import { type TimestampFormat } from "@t3tools/contracts/settings";
104 import { type HandoffTimelineRun } from "./V2LifecycleRow";
105 import { TimelineSystemDivider } from "./TimelineSystemDivider";
106
107 import { forwardWheelToTimeline } from "./timelineMinimapWheel";
108 import { TimelineMinimap } from "./TimelineMinimap";
109 import {
110 type TimelineRowSharedState,
111 type TimelineRowActivityState,
112 TimelineRowCtx,
113 TimelineRowActivityCtx,
114 type WorkGroupViewState,
115 type TimelineRow,
116 } from "./timelineRowContext";
117 import { TimelineRowTimestamp, ActivityShimmerOverlay } from "./TimelineRowParts";
118 import {
119 WorkGroupSection,
120 WorkingTimelineRow,
121 ThinkingTimelineRow,
122 LiveWorkEntryTimelineRow,
123 WorkGroupToggleTimelineRow,
124 } from "./TimelineWorkGroupRows";
125 import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow";
126 import { UserMessageRow } from "./TimelineUserMessageRow";
127 import {
128 AssistantTimelineRow,
129 AssistantMetaTimelineRow,
130 ProposedPlanTimelineRow,
131 HtmlRenderTimelineRow,
132 SentMessageTimelineRow,
133 McpAppTimelineRow,
134 } from "./TimelineAssistantRows";
135 import { V2EventTimelineRow } from "./TimelineV2EventRow";
136 import { startTimelinePositionRestore } from "./useTimelinePositionRestore";
137 import {
138 attachTimelineViewport,
139 nextListOpening,
140 type TimelineListOpening,
141 type TimelineViewport,
142 } from "./timelineViewport";
143 import { useThreadFindPositionReader } from "./useThreadFindPositionReader";
144 import { ThreadActivityAnnouncer } from "./ThreadActivityAnnouncer";
145 import { useStableHandoffRuns, useIncrementalTimelineRows, useStableRows } from "./useTimelineRows";
146 import { useClientSettings } from "../../hooks/useSettings";
147
148 function timelineListStateFor(identity: string): {
149 readonly identity: string;
150 readonly rememberedPosition: RememberedTimelinePosition | undefined;
151 readonly workGroupViewState: WorkGroupViewState;
152 } {
153 const rememberedPosition = readTimelinePosition(identity);
154 return {
155 identity,
156 rememberedPosition,
157 workGroupViewState: rememberedPosition?.disclosures?.workGroupState ?? {
158 scrollPositions: new Map(),
159 expandedEntries: new Set(),
160 },
161 };
162 }
163
164 const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
165 const TIMELINE_LIST_FADE_HEADER = (
166 <div className="h-[var(--workspace-titlebar-scroll-fade-height)]" />
167 );
168 function TimelineListFooter({
169 composerInset,
170 onGrow,
171 children,
172 }: {
173 readonly composerInset: number;
174 readonly onGrow: (() => void) | undefined;
175 readonly children?: ReactNode;
176 }) {
177 const contentRef = useRef<HTMLDivElement>(null);
178 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports growth of the footer's content, which the list does not follow
179 useLayoutEffect(() => {
180 const content = contentRef.current;
181 if (!content || !onGrow) return;
182 let height = content.offsetHeight;
183 return observeResize(content, () => {
184 const next = content.offsetHeight;
185 if (next > height) onGrow();
186 height = next;
187 });
188 }, [onGrow]);
189 return (
190 <div>
191 <div ref={contentRef}>{children}</div>
192 <div aria-hidden style={{ height: composerInset }} />
193 <div aria-hidden className="h-3 sm:h-4" />
194 </div>
195 );
196 }
197
198 const EMPTY_TIMELINE_SKILLS: ReadonlyArray<ServerProviderSkill> = [];
199 const TIMELINE_MAINTAIN_SCROLL_AT_END = {
200 animated: false,
201 on: {
202 dataChange: true,
203 footerLayout: false,
204 itemLayout: true,
205 layout: true,
206 },
207 } as const satisfies MaintainScrollAtEndOptions;
208 const EMPTY_RUN_IDS: ReadonlySet<RunId> = new Set();
209 const EMPTY_TIMELINE_ENTRIES: ReadonlyArray<TimelineEntry> = [];
210 const TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH = {
211 ...TIMELINE_MAINTAIN_SCROLL_AT_END,
212 animated: true,
213 } as const satisfies MaintainScrollAtEndOptions;
214
215 const CITED_HISTORY_LOADING: CitedHistory = { _tag: "loading" };
216
217 export interface MessagesTimelineHistoryControls {
218 readonly hasMoreHistory: boolean;
219 readonly loading: boolean;
220 readonly error: string | null;
221 readonly onLoadEarlier: (throughEntryId?: string) => void;
222 }
223
224 interface MessagesTimelineProps {
225 pendingApprovals?: ReadonlyArray<PendingApproval>;
226 heldApprovalRequestIds?: ReadonlySet<string> | undefined;
227 respondingRequestIds?: TimelineRowSharedState["respondingRequestIds"];
228 canOperateThread?: boolean;
229 onRespondToApproval?: TimelineRowSharedState["onRespondToApproval"];
230 citationRequest?: AssistantCitationRequest | null;
231 citationHistory?: CitedHistory;
232 onCiteAssistantText?: (
233 citation: AssistantCitation,
234 sourceAnchor: AssistantCitationSourceAnchor,
235 ) => boolean;
236 onReplyToResponse?: TimelineRowSharedState["onReplyToResponse"];
237 isWorking: boolean;
238 /** The thread is catching up from a cached copy, whose working state may be stale. */
239 syncing?: boolean;
240 runlessWorkActive?: boolean;
241 activeTurnStartedAt?: string | null;
242 /** Replaces "Thinking" while the active run's provider has not started a turn. */
243 providerStartingLabel?: string | null;
244 worktreeSetup?: WorktreeSetupSnapshot | null;
245 onCancelWorktreeSetup?: () => void;
246 retryableWorkspacePreparationRunIds?: ReadonlySet<RunId>;
247 onRetryWorkspacePreparation?: (runId: RunId) => void;
248 onWorktreeSetupWorkLocally?: () => void;
249 onOpenWorktreeSetupTerminal?: (terminalId: string) => void;
250 isPreparingWorktree?: boolean;
251 isCompacting?: boolean;
252 awaitingUser?: "approval" | "input" | null;
253 /** Which request is waiting, so a second one of the same kind is announced too. */
254 awaitingRequestId?: string | null;
255 footer?: ReactNode;
256
257 listRef: React.RefObject<LegendListRef | null>;
258 timelineEntries: ReadonlyArray<TimelineEntry>;
259 latestRun: TimelineLatestRun | null;
260 /** The run the screen reader announcer follows; see announcedRun. */
261 announcedRun?: { readonly runId: RunId; readonly status: TimelineLatestRun["status"] } | null;
262 /** See isDetailBehindShell. */
263 detailBehindShell?: boolean;
264 runningRunId?: RunId | null;
265 turnDiffSummaries: ReadonlyArray<TurnDiffSummary>;
266 routeThreadKey: string;
267 displayThreadKey?: string;
268 /** Off where another region already speaks the thread's status, like a subagent's bar. */
269 announceTurnStatus?: boolean;
270 onOpenToolDiff?: (target: ToolCallDiffTarget) => void;
271 onOpenTurnDiff?: (runId: RunId, filePath?: string) => void;
272 onOpenThread: (
273 threadId: OrchestrationV2TurnItem["threadId"],
274 environmentId?: EnvironmentId,
275 /** How the click asked to open a subagent or side chat; a plain click when absent. */
276 intent?: SideThreadOpenIntent,
277 ) => void;
278 renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"];
279 turnItemSource?: TimelineRowSharedState["turnItemSource"];
280 /**
281 * The thread this one is a subagent or side chat of; `open` is absent when it cannot be
282 * opened from here.
283 */
284 parentThreadLink?: {
285 readonly title: string;
286 /** A side chat's inherited rows collapse into this link. */
287 readonly sideChat?: boolean;
288 /** Where it runs, when that is another environment. */
289 readonly environmentLabel?: string;
290 readonly open?: () => void;
291 } | null;
292 workflowOpening?: WorkflowOpening | null;
293 onForkFromRun?: (input: {
294 readonly sourceThreadId: ThreadId;
295 readonly runId: RunId;
296 }) => Promise<void>;
297 supportsConversationRollback: boolean;
298 threadStartCheckpointAvailable?: boolean;
299 availableRevertTurnCounts?: ReadonlySet<number> | undefined;
300 onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void;
301 onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
302 onSendAppMessage?: (text: string) => Promise<void>;
303 onRunShellCommand?: (command: string) => void;
304 isRevertingCheckpoint: boolean;
305 onImageExpand: (preview: ExpandedImagePreview) => void;
306 onFileOpen?: (attachment: ChatFileAttachment) => void;
307 onFileDownload?: (attachment: ChatFileAttachment) => void;
308 activeThreadEnvironmentId: EnvironmentId;
309 markdownCwd: string | undefined;
310 resolvedTheme: "light" | "dark";
311 timestampFormat: TimestampFormat;
312 workspaceRoot: string | undefined;
313 skills?: ReadonlyArray<ServerProviderSkill>;
314 runs: ReadonlyArray<HandoffTimelineRun>;
315 anchorMessageId: MessageId | null;
316 onAnchorReady: (messageId: MessageId, anchorIndex: number) => void;
317 onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
318 contentInsetEndAdjustment: number;
319 onIsAtEndChange: (isAtEnd: boolean) => void;
320 /** Disable while reading history to prevent LegendList re-pinning near the bottom. */
321 liveFollowEnabled: boolean;
322 /** Receives the list's viewport when it mounts; the returned cleanup runs when it goes away. */
323 onViewportAttach?: (viewport: TimelineViewport) => () => void;
324 /** The footer's content grew, such as a new queued turn or status line. */
325 onFooterGrow?: () => void;
326 findOpen?: boolean;
327 hideEmptyPlaceholder?: boolean;
328 /** Composer space to center the empty state against; held steady through collapse. */
329 emptyPlaceholderInset: number;
330 topFadeEnabled?: boolean;
331 historyControls?: MessagesTimelineHistoryControls | undefined;
332 findExpanded?: boolean;
333 findQuery?: string;
334 activeFindMatch?: ThreadFindMatch | null;
335 findNavigationId?: number;
336 }
337
338 export function MessagesTimeline(props: MessagesTimelineProps) {
339 const find = useContext(ThreadFindTimelineContext);
340 const findOpen = find?.findOpen ?? props.findOpen;
341 return (
342 <ConversationTimeline
343 {...props}
344 {...find}
345 liveFollowEnabled={!findOpen && props.liveFollowEnabled}
346 />
347 );
348 }
349
350 const ConversationTimeline = memo(function ConversationTimeline({
351 pendingApprovals = EMPTY_PENDING_APPROVALS,
352 heldApprovalRequestIds,
353 respondingRequestIds = EMPTY_RESPONDING_REQUEST_IDS,
354 canOperateThread = false,
355 onRespondToApproval,
356 citationRequest = null,
357 citationHistory = CITED_HISTORY_LOADING,
358 onCiteAssistantText,
359 onReplyToResponse,
360 isWorking,
361 syncing = false,
362 runlessWorkActive = false,
363 activeTurnStartedAt = null,
364 providerStartingLabel = null,
365 worktreeSetup = null,
366 footer = null,
367 onCancelWorktreeSetup,
368 retryableWorkspacePreparationRunIds = EMPTY_RUN_IDS,
369 onRetryWorkspacePreparation,
370 onWorktreeSetupWorkLocally,
371 onOpenWorktreeSetupTerminal,
372 isPreparingWorktree = false,
373 isCompacting = false,
374 awaitingUser = null,
375 awaitingRequestId = null,
376 listRef,
377 timelineEntries,
378 findOpen = false,
379 findExpanded = false,
380 findQuery = "",
381 activeFindMatch = null,
382 findNavigationId = 0,
383 latestRun,
384 announcedRun = null,
385 detailBehindShell = false,
386 runningRunId = null,
387 turnDiffSummaries,
388 routeThreadKey,
389 displayThreadKey,
390 announceTurnStatus = true,
391 onOpenToolDiff,
392 onOpenTurnDiff,
393 onOpenThread,
394 renderHtmlRender,
395 turnItemSource,
396 parentThreadLink = null,
397 workflowOpening = null,
398 onForkFromRun,
399 supportsConversationRollback,
400 threadStartCheckpointAvailable = false,
401 availableRevertTurnCounts,
402 onRevertToTurnCount,
403 onUseArtifactTemplate = NOOP_USE_ARTIFACT_TEMPLATE,
404 onSendAppMessage,
405 onRunShellCommand,
406 isRevertingCheckpoint,
407 onImageExpand,
408 onFileOpen = NOOP_OPEN_ATTACHMENT,
409 onFileDownload = NOOP_OPEN_ATTACHMENT,
410 activeThreadEnvironmentId,
411 markdownCwd,
412 resolvedTheme,
413 timestampFormat,
414 workspaceRoot,
415 skills = EMPTY_TIMELINE_SKILLS,
416 runs: runsProp,
417 anchorMessageId,
418 onAnchorReady,
419 onAnchorSizeChanged,
420 contentInsetEndAdjustment,
421 onIsAtEndChange,
422 liveFollowEnabled,
423 onViewportAttach,
424 onFooterGrow,
425 hideEmptyPlaceholder = false,
426 emptyPlaceholderInset,
427 topFadeEnabled = false,
428 historyControls,
429 }: MessagesTimelineProps) {
430 const gt = useGT();
431 const listIdentityKey = displayThreadKey ?? routeThreadKey;
432 // Snapshot restore positions on identity changes; ongoing scroll writes must not move them.
433 // Find open at the opening is part of the snapshot: opening find later
434 // announces its own navigation (threadFindStore's announceOpening).
435 const [listState, setListState] = useState(() => ({
436 ...timelineListStateFor(listIdentityKey),
437 findOpenAtOpening: findOpen,
438 }));
439 const [expandedRunIds, setExpandedRunIds] = useState<ReadonlySet<RunId>>(
440 () => listState.rememberedPosition?.disclosures?.runs ?? new Set(),
441 );
442 const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(
443 () => listState.rememberedPosition?.disclosures?.workGroups ?? new Set(),
444 );
445 const [expandedAttemptIds, setExpandedAttemptIds] = useState<ReadonlySet<RunAttemptId>>(
446 () => listState.rememberedPosition?.disclosures?.attempts ?? new Set(),
447 );
448 // A list that opens on a thread with find open takes the opening step below,
449 // so the restore runs and releases follow once for find.
450 const [positionedThreadKey, setPositionedThreadKey] = useState<string | null>(() =>
451 listState.rememberedPosition?.atEnd === false || findOpen ? null : listIdentityKey,
452 );
453 const restoringThreadPosition = positionedThreadKey !== listIdentityKey;
454 const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
455 const [settlingListIdentity, setSettlingListIdentity] = useState<string | null>(listIdentityKey);
456 const [playingAudioRows, setPlayingAudioRows] = useState<ReadonlyMap<HTMLAudioElement, string>>(
457 () => new Map(),
458 );
459 const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);
460 let paintedExpandedRunIds = expandedRunIds;
461 let paintedExpandedWorkGroupIds = expandedWorkGroupIds;
462 let paintedExpandedAttemptIds = expandedAttemptIds;
463 const identityChanged = listState.identity !== listIdentityKey;
464 const { rememberedPosition, workGroupViewState } = identityChanged
465 ? timelineListStateFor(listIdentityKey)
466 : listState;
467 if (identityChanged) {
468 setPlayingAudioRows(new Map());
469 setListState({
470 identity: listIdentityKey,
471 rememberedPosition,
472 workGroupViewState,
473 findOpenAtOpening: findOpen,
474 });
475 setPositionedThreadKey(null);
476 setSettlingListIdentity(listIdentityKey);
477 // A viewer pinned in another thread must not keep live follow off here,
478 // nor when that thread comes back.
479 setFullscreenAppRowId(null);
480 paintedExpandedRunIds = rememberedPosition?.disclosures?.runs ?? new Set();
481 paintedExpandedWorkGroupIds = rememberedPosition?.disclosures?.workGroups ?? new Set();
482 paintedExpandedAttemptIds = rememberedPosition?.disclosures?.attempts ?? new Set();
483 setExpandedRunIds(paintedExpandedRunIds);
484 setExpandedWorkGroupIds(paintedExpandedWorkGroupIds);
485 setExpandedAttemptIds(paintedExpandedAttemptIds);
486 }
487 const citationThreadRef = parseScopedThreadKey(routeThreadKey);
488 const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined);
489 const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
490 const normalizedFindQuery = findQuery.trim();
491 const findActive = findExpanded;
492
493 const disclosureRevealRef = useRef<{
494 key: string;
495 identity: string;
496 entryId: string | undefined;
497 contentKey: string | undefined;
498 ready: boolean;
499 } | null>(null);
500 const disclosureRevealFrameRef = useRef<number | null>(null);
501
502 // Anchoring keeps the toggled row still, so content that expands below it
503 // near the bottom would otherwise land under the composer.
504 const revealExpandedDisclosure = useStableCallback(() => {
505 const pending = disclosureRevealRef.current;
506 if (!pending || pending.identity !== listIdentityKey) return;
507 const state = listRef.current?.getState();
508 const element = listRef.current?.getScrollableNode();
509 const index = state?.indexByKey(pending.key);
510 const row = index === undefined ? undefined : state?.elementAtIndex(index);
511 if (!element || !(row instanceof HTMLElement)) return;
512 const viewport = element.getBoundingClientRect();
513 const entry = pending.entryId
514 ? row.querySelector<HTMLElement>(`[data-work-entry-id="${CSS.escape(pending.entryId)}"]`)
515 : null;
516 const contentIndex = pending.contentKey ? state?.indexByKey(pending.contentKey) : undefined;
517 const content = contentIndex === undefined ? null : state?.elementAtIndex(contentIndex);
518 const bounds = (entry ?? row).getBoundingClientRect();
519 const delta = resolveDisclosureRevealScrollDelta({
520 rowTop: bounds.top,
521 rowBottom: content?.getBoundingClientRect().bottom ?? bounds.bottom,
522 viewportTop: viewport.top,
523 viewportBottom: viewport.bottom,
524 composerOverlayHeight: contentInsetEndAdjustment,
525 anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
526 });
527 // Nested lists can finish measuring before their height reaches the outer scroller.
528 if (pending.ready && element.scrollTop + delta <= element.scrollHeight - element.clientHeight) {
529 disclosureRevealRef.current = null;
530 }
531 if (delta > 0) {
532 element.scrollBy({ top: delta, behavior: prefersReducedMotion ? "auto" : "smooth" });
533 }
534 });
535 const scheduleDisclosureReveal = () => {
536 if (disclosureRevealFrameRef.current !== null) {
537 cancelAnimationFrame(disclosureRevealFrameRef.current);
538 }
539 disclosureRevealFrameRef.current = requestAnimationFrame(() => {
540 disclosureRevealFrameRef.current = null;
541 revealExpandedDisclosure();
542 });
543 };
544
545 const preserveDisclosurePosition = (
546 anchorKey: string,
547 reveal?: { readonly entryId?: string | undefined; readonly contentKey?: string | undefined },
548 ) => {
549 const list = listRef.current;
550 disclosureRevealRef.current = null;
551 // An anchor ends end-follow until the reader scrolls, so a streaming turn keeps the live end.
552 if (!list || (isWorking && list.getState().isFollowingEnd)) return;
553 if (reveal) {
554 disclosureRevealRef.current = {
555 key: anchorKey,
556 identity: listIdentityKey,
557 entryId: reveal.entryId,
558 contentKey: reveal.contentKey,
559 ready: false,
560 };
561 }
562 list.cancelScroll();
563 list.anchorVisibleContent({ key: anchorKey });
564 };
565
566 // Turn and attempt folds reveal later rows rather than growing their own row.
567 const onToggleTurnFold = (runId: RunId) => {
568 preserveDisclosurePosition(`turn-fold:${runId}`);
569 setExpandedRunIds((existing) => {
570 const next = new Set(existing);
571 if (next.has(runId)) {
572 next.delete(runId);
573 } else {
574 next.add(runId);
575 }
576 return next;
577 });
578 };
579 const onToggleWorkGroup = (groupId: string, anchorKey: string) => {
580 preserveDisclosurePosition(
581 anchorKey,
582 expandedWorkGroupIds.has(groupId) ? undefined : { contentKey: `${groupId}:details` },
583 );
584 setExpandedWorkGroupIds((existing) => {
585 const next = new Set(existing);
586 if (next.has(groupId)) {
587 next.delete(groupId);
588 } else {
589 next.add(groupId);
590 }
591 return next;
592 });
593 };
594 const onToggleAttemptFold = (attemptId: RunAttemptId) => {
595 preserveDisclosurePosition(`attempt-fold:${attemptId}`);
596 setExpandedAttemptIds((existing) => {
597 const next = new Set(existing);
598 if (next.has(attemptId)) {
599 next.delete(attemptId);
600 } else {
601 next.add(attemptId);
602 }
603 return next;
604 });
605 };
606
607 // An interrupted run opens its fold; a newer run closes the previous run's.
608 const [observedLatestRun, setObservedLatestRun] = useState({
609 identity: listIdentityKey,
610 runId: latestRun?.runId,
611 status: latestRun?.status,
612 });
613 if (
614 observedLatestRun.identity !== listIdentityKey ||
615 observedLatestRun.runId !== latestRun?.runId ||
616 observedLatestRun.status !== latestRun?.status
617 ) {
618 setObservedLatestRun({
619 identity: listIdentityKey,
620 runId: latestRun?.runId,
621 status: latestRun?.status,
622 });
623 const previousRunId = observedLatestRun.runId;
624 if (
625 observedLatestRun.identity === listIdentityKey &&
626 latestRun &&
627 previousRunId !== undefined
628 ) {
629 if (latestRun.runId === previousRunId) {
630 if (observedLatestRun.status === "running" && latestRun.status === "interrupted") {
631 setExpandedRunIds((existing) => new Set(existing).add(latestRun.runId));
632 }
633 } else {
634 setExpandedRunIds((existing) => {
635 if (!existing.has(previousRunId)) return existing;
636 const next = new Set(existing);
637 next.delete(previousRunId);
638 return next;
639 });
640 }
641 }
642 }
643
644 const preferredToolCallVisibility = useClientSettings((settings) => settings.toolCallVisibility);
645 const screenReaderAnnouncements = useClientSettings(
646 (settings) => settings.screenReaderAnnouncements,
647 );
648 const toolCallVisibility =
649 findActive && preferredToolCallVisibility === "zen" ? "hideAll" : preferredToolCallVisibility;
650 const revealedMessageId = citationRequest?.citation.messageId ?? null;
651 // Imported turns and post-steer work fold under synthetic keys, not the entries' run ids.
652 const findFoldRunIds = findActive
653 ? timelineTurnFoldRunIdsByEntryId({
654 timelineEntries,
655 latestRun,
656 runningRunId,
657 isWorking,
658 runlessWorkActive,
659 toolCallVisibility,
660 revealedMessageId,
661 })
662 : null;
663 const activeFindRunId =
664 findActive && activeFindMatch ? findFoldRunIds?.get(activeFindMatch.entryId) : undefined;
665 const [expandedFindRunId, setExpandedFindRunId] = useState<RunId | undefined>();
666 if (expandedFindRunId !== activeFindRunId) {
667 setExpandedFindRunId(activeFindRunId);
668 if (activeFindRunId) {
669 setExpandedRunIds((previous) =>
670 previous.has(activeFindRunId) ? previous : new Set(previous).add(activeFindRunId),
671 );
672 }
673 }
674 // A cited response folded inside a turn opens its fold once per activation;
675 // the user can fold it again. Only a citation that can still land opens one.
676 // The marker stops the O(entries) fold lookup once the entry is found, since
677 // the href stays in the URL after the citation settles.
678 const [citationExpandedFor, setCitationExpandedFor] = useState<string | null>(null);
679 // Back/Forward can restore an earlier activation key, so the marker clears
680 // between activations and a revisit opens the fold again.
681 if (!citationRequest && citationExpandedFor !== null) setCitationExpandedFor(null);
682 const citedEntry =
683 citationRequest &&
684 citationExpandedFor !== citationRequest.key &&
685 citationHistory._tag !== "failed"
686 ? timelineEntries.find(
687 (entry) =>
688 (entry.kind === "message" &&
689 entry.message.role === "assistant" &&
690 entry.message.id === citationRequest.citation.messageId) ||
691 (entry.kind === "sent-message" && entry.id === citationRequest.citation.messageId),
692 )
693 : undefined;
694 if (citationRequest && citedEntry) {
695 const citedRunId = (
696 findFoldRunIds ??
697 timelineTurnFoldRunIdsByEntryId({
698 timelineEntries,
699 latestRun,
700 runningRunId,
701 isWorking,
702 runlessWorkActive,
703 toolCallVisibility,
704 revealedMessageId,
705 })
706 ).get(citedEntry.id);
707 setCitationExpandedFor(citationRequest.key);
708 if (citedRunId) {
709 setExpandedRunIds((previous) =>
710 previous.has(citedRunId) ? previous : new Set(previous).add(citedRunId),
711 );
712 }
713 const citedAttempt = citedEntry.attempt;
714 if (citedAttempt?.status === "superseded") {
715 setExpandedAttemptIds((previous) =>
716 previous.has(citedAttempt.id) ? previous : new Set(previous).add(citedAttempt.id),
717 );
718 }
719 }
720 const visibleExpandedRunIds =
721 !activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)
722 ? paintedExpandedRunIds
723 : new Set(paintedExpandedRunIds).add(activeFindRunId);
724
725 const activeFindAttemptId = activeFindMatch
726 ? timelineEntries.find((entry) => entry.id === activeFindMatch.entryId)?.attempt?.id
727 : undefined;
728 const [expandedFindAttemptId, setExpandedFindAttemptId] = useState<RunAttemptId | undefined>();
729 if (expandedFindAttemptId !== activeFindAttemptId) {
730 setExpandedFindAttemptId(activeFindAttemptId);
731 if (activeFindAttemptId) {
732 setExpandedAttemptIds((previous) =>
733 previous.has(activeFindAttemptId) ? previous : new Set(previous).add(activeFindAttemptId),
734 );
735 }
736 }
737 const visibleExpandedAttemptIds =
738 activeFindAttemptId && !paintedExpandedAttemptIds.has(activeFindAttemptId)
739 ? new Set(paintedExpandedAttemptIds).add(activeFindAttemptId)
740 : paintedExpandedAttemptIds;
741
742 const isVisiblePendingApproval = (approval: PendingApproval) =>
743 !heldApprovalRequestIds?.has(approval.requestId);
744 const pendingApprovalRequestIds = new Set(
745 pendingApprovals.filter(isVisiblePendingApproval).map((approval) => approval.requestId),
746 );
747 const rawRows = useIncrementalTimelineRows(`${listIdentityKey}\0${workspaceRoot ?? ""}`, {
748 timelineEntries,
749 pendingApprovalRequestIds,
750 latestRun,
751 runningRunId,
752 expandedRunIds: visibleExpandedRunIds,
753 expandedAttemptIds: visibleExpandedAttemptIds,
754 expandedWorkGroupIds,
755 isWorking,
756 runlessWorkActive,
757 activeTurnStartedAt,
758 turnDiffSummaries,
759 supportsConversationRollback,
760 threadStartCheckpointAvailable,
761 availableRevertTurnCounts,
762 worktreeSetup,
763 toolCallVisibility,
764 revealedMessageId,
765 });
766 const rows = useStableRows(rawRows, listIdentityKey);
767 const matchedApprovalRequestIds = new Set<string>();
768 for (const row of pendingApprovalRequestIds.size > 0 ? rows : []) {
769 const entries =
770 row.kind === "work" ? row.groupedEntries : row.kind === "work-live" ? [row.entry] : [];
771 for (const entry of entries) {
772 const item = entry.projectedItem?.item;
773 if (item?.type === "approval_request") matchedApprovalRequestIds.add(item.requestId);
774 }
775 }
776 const unmatchedPendingApprovals = pendingApprovals.filter(
777 (approval) =>
778 isVisiblePendingApproval(approval) && !matchedApprovalRequestIds.has(approval.requestId),
779 );
780 // Run status/timestamps change per stream event; keep them out of shared row context.
781 const runs = useStableHandoffRuns(runsProp);
782 const minimapItems = deriveTimelineMinimapItems(rows);
783 const minimapRowIndices = minimapItems.map((item) => item.rowIndex);
784 const restoreRowIndex =
785 restoringThreadPosition && rememberedPosition?.atEnd === false
786 ? rows.findIndex((row) => row.id === rememberedPosition.rowId)
787 : -1;
788 const restoringAlwaysRender =
789 restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined;
790 const showsEmptyState =
791 rows.length === 0 &&
792 unmatchedPendingApprovals.length === 0 &&
793 !isWorking &&
794 parentThreadLink === null &&
795 historyControls === undefined &&
796 footer === null;
797 const [listOpening, setListOpening] = useState<TimelineListOpening>(() =>
798 nextListOpening({ mounted: false }, !showsEmptyState, listIdentityKey),
799 );
800 const nextOpening = nextListOpening(listOpening, !showsEmptyState, listIdentityKey);
801 if (nextOpening !== listOpening) setListOpening(nextOpening);
802 const listOpenedOn = nextOpening.mounted ? nextOpening.identity : null;
803 const viewportRef = useRef<TimelineViewport | null>(null);
804 const navigateTimeline = () => viewportRef.current?.navigate({ releasesFollow: true });
805 const restoreReady = restoringThreadPosition && rows.length > 0;
806 // Z: syncs LegendList's scroll position with which thread it shows. The list
807 // is not keyed per thread and reports no "new data" event, and the restore
808 // must land before paint, after LegendList's own layout effects applied the
809 // new data. A citation request that arrives mid-restore takes over.
810 const { findOpenAtOpening } = identityChanged ? { findOpenAtOpening: findOpen } : listState;
811 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores LegendList's scroll position for the shown thread before paint, after the list's own layout
812 useLayoutEffect(() => {
813 const list = listRef.current;
814 const viewport = viewportRef.current;
815 if (!restoreReady || !list || !viewport) return;
816 return startTimelinePositionRestore({
817 list,
818 viewport,
819 listIdentityKey,
820 listOpenedOn,
821 rememberedPosition,
822 citationPending: citationRequest !== null,
823 releaseForFind: findOpenAtOpening,
824 onPositioned: setPositionedThreadKey,
825 });
826 }, [
827 citationRequest,
828 findOpenAtOpening,
829 listIdentityKey,
830 listOpenedOn,
831 listRef,
832 rememberedPosition,
833 restoreReady,
834 viewportRef,
835 ]);
836
837 const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
838 null,
839 );
840 const {
841 target: readyCitationRequest,
842 positioning: citationPositioning,
843 onListLoad: onCitationListLoad,
844 alwaysRender: citationAlwaysRender,
845 } = useAssistantCitationTarget({
846 request: citationRequest,
847 phase: citationRequest
848 ? resolveCitationPhase({
849 history: citationHistory,
850 messageId: citationRequest.citation.messageId,
851 entries: timelineEntries,
852 rows,
853 })
854 : null,
855 viewport: timelineViewportElement,
856 onManualNavigation: navigateTimeline,
857 });
858 const [findListReady, setFindListReady] = useState(false);
859 const handleListLoad = () => {
860 onCitationListLoad();
861 setFindListReady(true);
862 };
863 const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
864 // Every full-screen viewer reports false when it unmounts, so a row that leaves the list
865 // while full screen releases its pin too.
866 const onAppFullscreenChange = (rowId: string, fullscreen: boolean) => {
867 setFullscreenAppRowId((current) => (fullscreen ? rowId : current === rowId ? null : current));
868 };
869 const selectedRowIds = useSelectedTimelineRowIds(timelineViewportElement);
870 const alwaysRenderIndices = [
871 ...(restoringAlwaysRender?.indices ?? []),
872 ...timelineRowSpanIndices(rows, selectedRowIds),
873 ];
874 // Screen readers can only reach headings in the DOM. Keeping the first and
875 // last messages mounted lets heading navigation wrap to either end.
876 const firstMessageRow = rows.find(isMessageRow);
877 const lastMessageRow = rows.findLast(isMessageRow);
878 const alwaysRenderKeys = [
879 ...(firstMessageRow ? [firstMessageRow.id] : []),
880 ...(lastMessageRow && lastMessageRow !== firstMessageRow ? [lastMessageRow.id] : []),
881 ...(citationAlwaysRender?.keys ?? []),
882 ...(fullscreenAppRowId === null ? [] : [fullscreenAppRowId]),
883 ...new Set(
884 [...playingAudioRows].filter(([audio]) => audio.isConnected).map(([, rowId]) => rowId),
885 ),
886 ];
887 const alwaysRender =
888 alwaysRenderIndices.length === 0 && alwaysRenderKeys.length === 0
889 ? undefined
890 : {
891 ...(alwaysRenderIndices.length === 0 ? {} : { indices: alwaysRenderIndices }),
892 ...(alwaysRenderKeys.length === 0 ? {} : { keys: alwaysRenderKeys }),
893 };
894 const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
895 const [minimapCurrentIndex, setMinimapCurrentIndex] = useState<number | null>(null);
896 const [minimapAtEnd, setMinimapAtEnd] = useState(false);
897 const handleAnchorReady = (info: { anchorIndex: number | undefined }) => {
898 if (anchorMessageId !== null && info.anchorIndex !== undefined) {
899 onAnchorReady(anchorMessageId, info.anchorIndex);
900 }
901 };
902 const handleAnchorSizeChanged = (size: number) => {
903 if (anchorMessageId !== null) {
904 onAnchorSizeChanged(anchorMessageId, size);
905 }
906 };
907 const anchoredEndSpaceConfig = resolveChatListAnchoredEndSpace(
908 rows,
909 anchorMessageId,
910 (row) => (row.kind === "message" && row.message.role === "user" ? row.message.id : null),
911 { anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET },
912 );
913 const anchoredEndSpace = anchoredEndSpaceConfig
914 ? {
915 ...anchoredEndSpaceConfig,
916 onReady: handleAnchorReady,
917 onSizeChanged: handleAnchorSizeChanged,
918 }
919 : undefined;
920 const maintainVisibleContentPosition = {
921 data: true,
922 size: true,
923 };
924
925 const refreshMinimap = useStableCallback(() => {
926 const state = listRef.current?.getState?.();
927 if (restoringThreadPosition || state?.data !== rows) return;
928 if (!state || minimapItems.length === 0) {
929 return;
930 }
931
932 const firstBufferedIndex = state.startBuffered;
933 const firstBufferedRow: HTMLElement | undefined =
934 firstBufferedIndex == null ? undefined : state.elementAtIndex(firstBufferedIndex);
935 const firstBufferedTop =
936 firstBufferedIndex == null ? undefined : state.positionAtIndex(firstBufferedIndex);
937 const viewport = listRef.current?.getScrollableNode() ?? undefined;
938 // Cached row positions exclude the header and pending scroll adjustments.
939 const scroll =
940 firstBufferedRow && viewport && firstBufferedTop !== undefined
941 ? firstBufferedTop +
942 viewport.getBoundingClientRect().top -
943 firstBufferedRow.getBoundingClientRect().top
944 : state.scroll;
945 const visibleRange = resolveTimelineMinimapVisibleRange({ ...state, scroll });
946 for (const [index, item] of minimapItems.entries()) {
947 const strip = minimapStripMap.get(item.id);
948 const inView = isTimelineMinimapTurnVisible(
949 item.rowIndex,
950 minimapItems[index + 1]?.rowIndex,
951 visibleRange.start,
952 visibleRange.end,
953 );
954 const next = inView ? "true" : "false";
955 // Avoid dirtying style state on every scroll tick for unchanged strips.
956 if (strip && strip.dataset.inView !== next) {
957 strip.dataset.inView = next;
958 }
959 }
960 // Ignore rows ending within the offset minimap navigation leaves above its target, or
961 // Next turn keeps retargeting the same row. 1px absorbs device-pixel scroll rounding.
962 const currentInset = TIMELINE_MINIMAP_TARGET_OFFSET + 1;
963 const currentRange = resolveTimelineMinimapVisibleRange({
964 ...state,
965 scroll: scroll + currentInset,
966 scrollLength: state.scrollLength - currentInset,
967 });
968 const nextCurrentIndex = resolveTimelineMinimapCurrentIndex({
969 visibleStart: currentRange.start,
970 visibleEnd: currentRange.end,
971 rowIndices: minimapRowIndices,
972 });
973 setMinimapCurrentIndex((current) =>
974 current === nextCurrentIndex ? current : nextCurrentIndex,
975 );
976 // The exact bottom, not the follow re-arm zone: Next can still scroll inside that zone.
977 setMinimapAtEnd(
978 viewport !== undefined &&
979 viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight <= 1,
980 );
981 });
982
983 const minimapRefreshFrameRef = useRef<number | null>(null);
984 const scheduleMinimapRefresh = useStableCallback(() => {
985 if (minimapRefreshFrameRef.current !== null) return;
986 // LegendList recycles row containers before React commits their positions.
987 minimapRefreshFrameRef.current = requestAnimationFrame(() => {
988 minimapRefreshFrameRef.current = null;
989 refreshMinimap();
990 });
991 });
992
993 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the minimap skips refreshes until the restore commits, and the restore can land without a scroll event
994 useLayoutEffect(() => {
995 if (!restoringThreadPosition) scheduleMinimapRefresh();
996 }, [restoringThreadPosition, scheduleMinimapRefresh]);
997
998 // The measurement the last remember wrote, so a follow release can rewrite
999 // it without reading render state from a listener.
1000 const lastRememberedRef = useRef<{
1001 readonly data: unknown;
1002 readonly threadKey: string;
1003 readonly position: Parameters<typeof rememberTimelinePosition>[1];
1004 } | null>(null);
1005 const rememberPosition = (followingEnd: boolean) => {
1006 const state = listRef.current?.getState?.();
1007 if (restoringThreadPosition || state?.data !== rows) return;
1008 const isAtEnd = resolveTimelineIsAtEnd(state);
1009 const position = state.data.length ? resolveWorkGroupScrollAnchor(state) : undefined;
1010 if (position && isAtEnd !== undefined) {
1011 const index = state.indexByKey(position.rowId);
1012 const row = index === undefined ? undefined : state.elementAtIndex(index);
1013 const element = listRef.current?.getScrollableNode();
1014 if (row && element) {
1015 const measured = {
1016 ...position,
1017 offsetWithinRow: element.getBoundingClientRect().top - row.getBoundingClientRect().top,
1018 scrollOffset: element.scrollTop,
1019 atEnd: isAtEnd,
1020 disclosures: {
1021 runs: paintedExpandedRunIds,
1022 workGroups: paintedExpandedWorkGroupIds,
1023 attempts: paintedExpandedAttemptIds,
1024 workGroupState: workGroupViewState,
1025 },
1026 };
1027 lastRememberedRef.current = { data: rows, threadKey: listIdentityKey, position: measured };
1028 rememberTimelinePosition(listIdentityKey, measured, followingEnd);
1029 }
1030 }
1031 return isAtEnd;
1032 };
1033 // A follow release without a scroll after it would leave the position
1034 // remembered as following.
1035 const rememberReleasedPosition = () => {
1036 const last = lastRememberedRef.current;
1037 if (last && listRef.current?.getState().data === last.data) {
1038 rememberTimelinePosition(last.threadKey, last.position, false);
1039 }
1040 };
1041
1042 const handleScroll = () => {
1043 if (restoringThreadPosition || listRef.current?.getState?.().data !== rows) return;
1044 const isAtEnd = rememberPosition(liveFollowEnabled && !anchoredEndSpace);
1045 if (isAtEnd !== undefined && !citationPositioning) {
1046 onIsAtEndChange(isAtEnd);
1047 }
1048 scheduleMinimapRefresh();
1049 };
1050
1051 const measureTimelineGutter = (viewportElement: HTMLElement) => {
1052 const viewportWidth = viewportElement.getBoundingClientRect().width;
1053 const contentWidth =
1054 viewportElement.querySelector<HTMLElement>("[data-timeline-root]")?.getBoundingClientRect()
1055 .width ?? viewportWidth;
1056 const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(
1057 viewportWidth,
1058 contentWidth,
1059 );
1060 setMinimapHasPersistentGutter((current) =>
1061 current === nextHasPersistentGutter ? current : nextHasPersistentGutter,
1062 );
1063 setMinimapHitStripWidth(resolveTimelineMinimapHitStripWidth(viewportWidth, contentWidth));
1064 };
1065 // Rows added, removed or rewrapped (chat width) change the content size,
1066 // which moves the scroll position, the overflow, and the content lane width.
1067 const handleContentSizeChanged = useStableCallback((laidOutData: unknown) => {
1068 // The first laid-out content of a newly shown thread ends its settling; a
1069 // frame the previous thread scheduled laid out the previous thread's rows.
1070 if (laidOutData === rows) {
1071 setSettlingListIdentity((current) => (current === listIdentityKey ? null : current));
1072 }
1073 handleScroll();
1074 });
1075 // The content lane only changes width with the viewport or the chat width
1076 // setting, never with streamed content; measuring per content frame would
1077 // force a layout on every chunk.
1078 const measuredLaneWidthRef = useRef<number | null>(null);
1079 const observeLaneWidth = (lane: HTMLDivElement | null) => {
1080 if (!lane) return;
1081 return observeResize(lane, (entries) => {
1082 const width = entries.at(-1)?.contentRect.width;
1083 if (width === undefined || width === measuredLaneWidthRef.current) return;
1084 measuredLaneWidthRef.current = width;
1085 const viewportElement = lane.closest<HTMLElement>("[data-assistant-citation-viewport]");
1086 if (viewportElement) measureTimelineGutter(viewportElement);
1087 });
1088 };
1089 const attachTimelineViewportElement = (viewportElement: HTMLDivElement | null) => {
1090 setTimelineViewportElement(viewportElement);
1091 if (!viewportElement) return;
1092 const stopObserving = observeResize(viewportElement, () => {
1093 measureTimelineGutter(viewportElement);
1094 scheduleMinimapRefresh();
1095 });
1096 return () => {
1097 stopObserving();
1098 setTimelineViewportElement(null);
1099 };
1100 };
1101
1102 // Built from props after the last hook so the compiler can memoize the row context; a map
1103 // made before a hook would rebuild it, and re-render every row, on each streamed update.
1104 const pendingApprovalsByRequestId = new Map(
1105 pendingApprovals
1106 .filter(isVisiblePendingApproval)
1107 .map((approval) => [approval.requestId, approval]),
1108 );
1109 const sharedState: TimelineRowSharedState = {
1110 pendingApprovals: pendingApprovalsByRequestId,
1111 respondingRequestIds,
1112 canOperateThread,
1113 onRespondToApproval,
1114 citationRequest: readyCitationRequest,
1115 onReplyToResponse,
1116 listRef,
1117 timestampFormat,
1118 routeThreadKey,
1119 threadRef: citationThreadRef,
1120 markdownCwd,
1121 resolvedTheme,
1122 workspaceRoot,
1123 skills,
1124 runs,
1125 activeThreadEnvironmentId,
1126 onRevertToTurnCount,
1127 onRunShellCommand,
1128 findActive,
1129 onImageExpand,
1130 onFileOpen,
1131 onUseArtifactTemplate,
1132 onSendAppMessage,
1133 onAppFullscreenChange,
1134 onFileDownload,
1135 openPullRequest,
1136 onOpenToolDiff,
1137 onOpenTurnDiff,
1138 onOpenThread,
1139 renderHtmlRender,
1140 turnItemSource,
1141 workflowOpening,
1142 onForkFromRun,
1143 onToggleTurnFold,
1144 onToggleAttemptFold,
1145 onToggleWorkGroup,
1146 onToggleWorkEntry: (anchorKey, collapsed, entryId) =>
1147 preserveDisclosurePosition(anchorKey, collapsed ? undefined : { entryId }),
1148 onWorkEntryContentReady: (anchorKey, entryId) => {
1149 const pending = disclosureRevealRef.current;
1150 if (
1151 !pending ||
1152 pending.identity !== listIdentityKey ||
1153 (pending.contentKey === undefined
1154 ? pending.key !== anchorKey || pending.entryId !== entryId
1155 : pending.contentKey !== anchorKey)
1156 )
1157 return;
1158 pending.ready = pending.contentKey === undefined;
1159 scheduleDisclosureReveal();
1160 },
1161 onCancelWorktreeSetup: onCancelWorktreeSetup ?? null,
1162 retryableWorkspacePreparationRunIds,
1163 onRetryWorkspacePreparation: onRetryWorkspacePreparation ?? null,
1164 onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocally ?? null,
1165 onOpenWorktreeSetupTerminal: onOpenWorktreeSetupTerminal ?? null,
1166 workGroupViewState,
1167 };
1168 const compactionAwaitingRow =
1169 isCompacting &&
1170 !rows.some(
1171 (row) =>
1172 (row.kind === "context-compaction" && row.active) ||
1173 (row.kind === "working" && row.compacting),
1174 );
1175 const backgroundWorktreeSetup =
1176 worktreeSetup !== null &&
1177 worktreeSetup.phase === "running" &&
1178 worktreeSetupAgentStarted(worktreeSetup) &&
1179 latestRun?.startedAt != null
1180 ? worktreeSetup
1181 : null;
1182 const activityState: TimelineRowActivityState = {
1183 isWorking,
1184 isCompacting: compactionAwaitingRow,
1185 isRevertingCheckpoint,
1186 backgroundWorktreeSetup,
1187 awaitingUser: awaitingUser !== null,
1188 isPreparingWorktree,
1189 providerStartingLabel,
1190 latestRunId: latestRun?.runId ?? null,
1191 liveAnswerPreview:
1192 isWorking && toolCallVisibility === "zen" ? liveAnswerPreview(timelineEntries) : null,
1193 };
1194 // Mounted in both the empty and filled timeline so a thread's first turn
1195 // starts from a baseline instead of a fresh, silent region.
1196 const activityAnnouncer = (
1197 <ThreadActivityAnnouncer
1198 threadKey={announceTurnStatus ? listIdentityKey : null}
1199 status={awaitingUser ?? (isWorking ? "working" : "idle")}
1200 requestId={awaitingRequestId}
1201 runId={announcedRun?.runId ?? null}
1202 runStatus={announcedRun?.status ?? null}
1203 detailBehind={detailBehindShell}
1204 level={screenReaderAnnouncements}
1205 entries={screenReaderAnnouncements === "status" ? EMPTY_TIMELINE_ENTRIES : timelineEntries}
1206 workspaceRoot={workspaceRoot}
1207 />
1208 );
1209 const listHeaderLeadingContent =
1210 parentThreadLink === null ? (
1211 topFadeEnabled ? (
1212 TIMELINE_LIST_FADE_HEADER
1213 ) : (
1214 TIMELINE_LIST_HEADER
1215 )
1216 ) : (
1217 <div className="messages-timeline-row-frame">
1218 <div className="chat-content-lane pt-1 sm:pt-2">
1219 <TimelineSystemDivider
1220 label={
1221 parentThreadLink.sideChat
1222 ? gt("Context from", {
1223 $context: "divider label; the parent thread title follows as a link",
1224 })
1225 : gt("Subagent of", {
1226 $context: "divider label; the parent thread title follows as a link",
1227 })
1228 }
1229 detail={
1230 parentThreadLink.environmentLabel === undefined
1231 ? parentThreadLink.title
1232 : gt("{title} on {environment}", {
1233 title: parentThreadLink.title,
1234 environment: parentThreadLink.environmentLabel,
1235 })
1236 }
1237 icon={parentThreadLink.sideChat ? MessagesSquareIcon : BotIcon}
1238 {...(parentThreadLink.open === undefined
1239 ? {}
1240 : { actionLabel: gt("Open parent thread"), onAction: parentThreadLink.open })}
1241 />
1242 </div>
1243 </div>
1244 );
1245 const listHeader = (
1246 <>
1247 {parentThreadLink === null ? listHeaderLeadingContent : null}
1248 {historyControls ? <TimelineHistoryControl {...historyControls} /> : null}
1249 {parentThreadLink !== null ? listHeaderLeadingContent : null}
1250 </>
1251 );
1252
1253 const canvas = useChatCanvas();
1254 const registerTimeline = canvas?.registerTimeline;
1255 // Stable so the list attaches once per mount, not on every render.
1256 const setTimelineList = useStableCallback((list: LegendListRef | null) => {
1257 listRef.current = list;
1258 const scrollNode: HTMLElement | null = list?.getScrollableNode() ?? null;
1259 registerTimeline?.(scrollNode);
1260 const viewport = scrollNode
1261 ? attachTimelineViewport(scrollNode, (frame) => {
1262 const rowId = frame.closest<HTMLElement>("[data-timeline-row-id]")?.dataset.timelineRowId;
1263 if (rowId && list) {
1264 list.cancelScroll();
1265 list.anchorVisibleContent({ key: rowId });
1266 }
1267 })
1268 : null;
1269 viewportRef.current = viewport;
1270 const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined;
1271 const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition);
1272 const stopDisclosureReveal = viewport?.subscribe(() => {
1273 disclosureRevealRef.current = null;
1274 });
1275 let contentSizeFrame: number | null = null;
1276 // LegendList lays rows out from layout effects; the next frame sees them settled.
1277 let scheduledData: unknown = null;
1278 const scheduleContentSizeChanged = () => {
1279 if (!list) return;
1280 const laidOutData = list.getState().data;
1281 if (contentSizeFrame !== null) {
1282 if (scheduledData === laidOutData) return;
1283 cancelAnimationFrame(contentSizeFrame);
1284 }
1285 scheduledData = laidOutData;
1286 contentSizeFrame = requestAnimationFrame(() => {
1287 contentSizeFrame = null;
1288 handleContentSizeChanged(laidOutData);
1289 revealExpandedDisclosure();
1290 });
1291 };
1292 const stopListeningToContentSize = list
1293 ?.getState()
1294 .listen("totalSize", () => scheduleContentSizeChanged());
1295 scheduleContentSizeChanged();
1296 return () => {
1297 stopListeningToContentSize?.();
1298 stopRememberingRelease?.();
1299 stopDisclosureReveal?.();
1300 if (contentSizeFrame !== null) cancelAnimationFrame(contentSizeFrame);
1301 if (disclosureRevealFrameRef.current !== null) {
1302 cancelAnimationFrame(disclosureRevealFrameRef.current);
1303 disclosureRevealFrameRef.current = null;
1304 }
1305 detachViewport?.();
1306 viewport?.dispose();
1307 if (viewportRef.current === viewport) viewportRef.current = null;
1308 if (minimapRefreshFrameRef.current !== null) {
1309 cancelAnimationFrame(minimapRefreshFrameRef.current);
1310 minimapRefreshFrameRef.current = null;
1311 }
1312 listRef.current = null;
1313 registerTimeline?.(null);
1314 };
1315 });
1316
1317 useThreadFindPositionReader({
1318 threadKey: listIdentityKey,
1319 navigate: navigateTimeline,
1320 timelineViewportElement,
1321 findFoldRunIds,
1322 timelineEntries,
1323 latestRun,
1324 runningRunId,
1325 isWorking,
1326 runlessWorkActive,
1327 toolCallVisibility,
1328 rows,
1329 contentInsetEndAdjustment,
1330 });
1331
1332 useThreadFindNavigation({
1333 // Find reveals its match only after the opening restore settles; both
1334 // scroll the list directly, so the restore would otherwise pull it back.
1335 listReady: findListReady && !restoringThreadPosition,
1336 historyControls,
1337 entries: timelineEntries,
1338 container: timelineViewportElement,
1339 query: normalizedFindQuery,
1340 match: activeFindMatch,
1341 navigationId: findNavigationId,
1342 rowIndex: activeFindMatch ? rows.findIndex((row) => row.id === activeFindMatch.entryId) : -1,
1343 listRef,
1344 contentInsetEndAdjustment,
1345 });
1346
1347 // LegendList moves rows one commit late; per-row providers prevent thread context leaks.
1348 const onAudioPlaybackChange = (rowId: string, event: SyntheticEvent) => {
1349 const audio = event.target;
1350 if (!(audio instanceof HTMLAudioElement)) return;
1351 setPlayingAudioRows((current) => {
1352 const playing = !audio.paused && !audio.ended;
1353 if (playing === current.has(audio)) return current;
1354 const next = new Map(current);
1355 if (playing) next.set(audio, rowId);
1356 else next.delete(audio);
1357 return next;
1358 });
1359 };
1360 const onAudioUnmount = useStableCallback((audio: HTMLAudioElement) => {
1361 setPlayingAudioRows((current) => {
1362 if (!current.has(audio)) return current;
1363 const next = new Map(current);
1364 next.delete(audio);
1365 return next;
1366 });
1367 });
1368 const renderItem = ({ item }: { item: MessagesTimelineRow }) => (
1369 <TimelineRowCtx value={sharedState}>
1370 <div
1371 className="messages-timeline-row-frame"
1372 onPlayCapture={(event) => onAudioPlaybackChange(item.id, event)}
1373 onPauseCapture={(event) => onAudioPlaybackChange(item.id, event)}
1374 onEndedCapture={(event) => onAudioPlaybackChange(item.id, event)}
1375 >
1376 <div
1377 ref={observeLaneWidth}
1378 className="chat-content-lane overflow-x-clip"
1379 data-timeline-root="true"
1380 >
1381 <AudioPreviewUnmountContext value={onAudioUnmount}>
1382 <TimelineRowContent row={item} />
1383 </AudioPreviewUnmountContext>
1384 </div>
1385 </div>
1386 </TimelineRowCtx>
1387 );
1388 const listExtraData = { identity: listIdentityKey, rowCount: rows.length, sharedState };
1389 const timelineListFooter = (
1390 <TimelineListFooter
1391 composerInset={anchoredEndSpace ? 0 : contentInsetEndAdjustment}
1392 onGrow={onFooterGrow}
1393 >
1394 {footer}
1395 {unmatchedPendingApprovals.length > 0 ? (
1396 <TimelineRowCtx value={sharedState}>
1397 <div className="messages-timeline-row-frame">
1398 <div className="chat-content-lane overflow-x-clip" data-timeline-root="true">
1399 <WorkLogBlock>
1400 {unmatchedPendingApprovals.map((approval) => (
1401 <TimelinePendingApprovalRow key={approval.requestId} approval={approval} />
1402 ))}
1403 </WorkLogBlock>
1404 </div>
1405 </div>
1406 </TimelineRowCtx>
1407 ) : null}
1408 </TimelineListFooter>
1409 );
1410
1411 const forwardMinimapWheel = (event: WheelEvent) => {
1412 const scrollNode = listRef.current?.getScrollableNode();
1413 if (scrollNode) forwardWheelToTimeline(event, scrollNode);
1414 };
1415
1416 if (showsEmptyState) {
1417 if (hideEmptyPlaceholder) {
1418 return (
1419 <>
1420 {activityAnnouncer}
1421 <div className="h-full min-h-0 bg-background" data-timeline-loading="true" />
1422 </>
1423 );
1424 }
1425 return (
1426 <>
1427 {activityAnnouncer}
1428 <div
1429 className="flex h-full items-center justify-center ps-(--chat-lane-inset-start) pe-(--chat-lane-inset-end)"
1430 style={{ paddingBottom: emptyPlaceholderInset }}
1431 >
1432 <p className="text-sm text-muted-foreground">
1433 <T>Send a message to start the conversation.</T>
1434 </p>
1435 </div>
1436 </>
1437 );
1438 }
1439
1440 return (
1441 <>
1442 {activityAnnouncer}
1443 <MarkdownFindContext value={findActive}>
1444 <TimelineRowActivityCtx value={activityState}>
1445 <TooltipScrollDismissArea
1446 ref={attachTimelineViewportElement}
1447 className="relative h-full min-h-0"
1448 data-assistant-citation-viewport="true"
1449 >
1450 {onCiteAssistantText && citationThreadRef ? (
1451 <AssistantSelectionToolbar
1452 viewport={timelineViewportElement}
1453 threadRef={citationThreadRef}
1454 onCite={onCiteAssistantText}
1455 />
1456 ) : null}
1457 <LegendList<MessagesTimelineRow>
1458 ref={setTimelineList}
1459 data={rows}
1460 extraData={listExtraData}
1461 keyExtractor={keyExtractor}
1462 getItemType={getItemType}
1463 renderItem={renderItem}
1464 estimatedItemSize={90}
1465 initialScrollAtEnd={
1466 !findActive && citationRequest === null && rememberedPosition?.atEnd !== false
1467 }
1468 // Legend needs a data refresh to mount new pins without a scroll event.
1469 dataVersion={`${readyCitationRequest?.key ?? listIdentityKey}:${alwaysRenderKeys.join(",")}`}
1470 {...(alwaysRender ? { alwaysRender } : {})}
1471 onLoad={handleListLoad}
1472 {...(anchoredEndSpace ? { anchoredEndSpace } : {})}
1473 contentInsetEndAdjustment={anchoredEndSpace ? contentInsetEndAdjustment : 0}
1474 maintainScrollAtEnd={
1475 citationPositioning ||
1476 (restoringThreadPosition && rememberedPosition?.atEnd === false) ||
1477 anchoredEndSpace ||
1478 !liveFollowEnabled ||
1479 fullscreenAppRowId !== null
1480 ? false
1481 : isWorking && !syncing && !prefersReducedMotion && settlingListIdentity === null
1482 ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH
1483 : TIMELINE_MAINTAIN_SCROLL_AT_END
1484 }
1485 maintainVisibleContentPosition={
1486 findActive ||
1487 citationPositioning ||
1488 (restoringThreadPosition && rememberedPosition?.atEnd === false)
1489 ? false
1490 : maintainVisibleContentPosition
1491 }
1492 maintainScrollAtEndThreshold={1}
1493 onScroll={handleScroll}
1494 onItemSizeChanged={scheduleMinimapRefresh}
1495 onMetricsChange={scheduleMinimapRefresh}
1496 // Keyboard scrolling only moves the focused element; F6 and clicks land here.
1497 tabIndex={-1}
1498 data-workspace-focus-default
1499 className={cn(
1500 "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",
1501 topFadeEnabled && "topbar-scroll-fade",
1502 )}
1503 ListHeaderComponent={listHeader}
1504 ListFooterComponent={timelineListFooter}
1505 />
1506 <TimelineMinimap
1507 items={minimapItems}
1508 hasPersistentGutter={minimapHasPersistentGutter}
1509 hitStripWidth={minimapHitStripWidth}
1510 currentIndex={minimapCurrentIndex}
1511 atEnd={minimapAtEnd}
1512 stripMap={minimapStripMap}
1513 onWheel={forwardMinimapWheel}
1514 onSelect={(item) => {
1515 navigateTimeline();
1516 void listRef.current?.scrollToIndex({
1517 index: item.rowIndex,
1518 animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
1519 viewOffset: TIMELINE_MINIMAP_TARGET_OFFSET,
1520 });
1521 }}
1522 />
1523 </TooltipScrollDismissArea>
1524 </TimelineRowActivityCtx>
1525 </MarkdownFindContext>
1526 </>
1527 );
1528 });
1529
1530 function TimelineHistoryControl(props: MessagesTimelineHistoryControls) {
1531 const gt = useGT();
1532 const messages = useMessages();
1533 if (!props.hasMoreHistory && props.error === null) {
1534 return null;
1535 }
1536 return (
1537 <div className="messages-timeline-row-frame">
1538 <div className="chat-content-lane flex flex-col gap-1.5 pb-2">
1539 {props.hasMoreHistory ? (
1540 <button
1541 type="button"
1542 disabled={props.loading}
1543 aria-label={gt("Load earlier turns")}
1544 onClick={() => props.onLoadEarlier()}
1545 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"
1546 >
1547 <span aria-hidden="true" className="h-px flex-1 bg-border/70" />
1548 <span className="shrink-0">
1549 {props.loading ? gt("Loading earlier turns…") : gt("Load earlier turns")}
1550 </span>
1551 <span aria-hidden="true" className="h-px flex-1 bg-border/70" />
1552 </button>
1553 ) : null}
1554 {props.error !== null ? (
1555 <p role="status" className="text-center text-muted-foreground text-xs">
1556 {threadErrorText(props.error, messages)}
1557 </p>
1558 ) : null}
1559 </div>
1560 </div>
1561 );
1562 }
1563
1564 function isMessageRow(row: MessagesTimelineRow) {
1565 return row.kind === "message" && row.message.role !== "system";
1566 }
1567
1568 // LegendList recycles a row's container once it leaves the draw buffer, which
1569 // moves a native selection's ends onto other rows. Pin the selected rows.
1570 function useSelectedTimelineRowIds(viewport: HTMLElement | null) {
1571 const [rowIds, setRowIds] = useState<ReadonlyArray<string>>([]);
1572 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to document selectionchange to track which timeline rows a native selection covers
1573 useEffect(() => {
1574 if (!viewport) return;
1575 const update = () => {
1576 const selection = document.getSelection();
1577 const range =
1578 selection && !selection.isCollapsed && selection.rangeCount > 0
1579 ? selection.getRangeAt(0)
1580 : null;
1581 const next: string[] = [];
1582 if (range?.intersectsNode(viewport)) {
1583 for (const row of viewport.querySelectorAll<HTMLElement>("[data-timeline-row-id]")) {
1584 const rowId = row.dataset.timelineRowId;
1585 if (rowId && range.intersectsNode(row)) next.push(rowId);
1586 }
1587 }
1588 setRowIds((current) =>
1589 current.length === next.length && current.every((id, i) => id === next[i]) ? current : next,
1590 );
1591 };
1592 document.addEventListener("selectionchange", update);
1593 return () => {
1594 document.removeEventListener("selectionchange", update);
1595 setRowIds([]);
1596 };
1597 }, [viewport]);
1598 return rowIds;
1599 }
1600
1601 // Rows between the selected ones are covered too, even if not mounted right now.
1602 function timelineRowSpanIndices(
1603 rows: ReadonlyArray<MessagesTimelineRow>,
1604 rowIds: ReadonlyArray<string>,
1605 ): number[] {
1606 if (rowIds.length === 0) return [];
1607 const selected = new Set(rowIds);
1608 const first = rows.findIndex((row) => selected.has(row.id));
1609 const last = rows.findLastIndex((row) => selected.has(row.id));
1610 if (first < 0) return [];
1611 return Array.from({ length: last - first + 1 }, (_, i) => first + i);
1612 }
1613
1614 function keyExtractor(item: MessagesTimelineRow) {
1615 return item.id;
1616 }
1617
1618 // LegendList estimates unmeasured rows from their type's average. Long messages of equal length
1619 // can differ in height by orders of magnitude, so each gets its own type to avoid nested-update loops.
1620 function getItemType(item: MessagesTimelineRow) {
1621 if (item.kind !== "message") return item.kind;
1622 const lengthBucket = Math.max(0, Math.floor(Math.log2(item.message.text.length / 1000)));
1623 return lengthBucket < 2
1624 ? `message:${item.message.role}:${lengthBucket}`
1625 : `message:${item.message.id}`;
1626 }
1627
1628 const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: TimelineRow }) {
1629 const isExpandedToolGroup = row.kind === "work" && row.isExpandedToolGroup;
1630 const isSubagentGroup = row.kind === "event" && row.projectedItem.item.type === "subagent";
1631 const isWorkLogRow =
1632 row.kind === "work" ||
1633 row.kind === "work-live" ||
1634 row.kind === "work-toggle" ||
1635 row.kind === "thinking";
1636 const isExpandedToolGroupHeader =
1637 (row.kind === "work-toggle" || row.kind === "work-live" || row.kind === "thinking") &&
1638 row.expanded === true;
1639
1640 return (
1641 <div
1642 className={cn(
1643 isWorkLogRow || isSubagentGroup
1644 ? undefined
1645 : row.kind === "turn-fold" || row.kind === "working"
1646 ? "pb-1.5"
1647 : row.kind === "message" && row.groupedWithNext
1648 ? "pb-1"
1649 : (row.kind === "message" &&
1650 row.message.role === "assistant" &&
1651 !row.showAssistantMeta) ||
1652 row.kind === "worktree-setup" ||
1653 row.kind === "event" ||
1654 row.kind === "attempt-fold" ||
1655 row.kind === "html-render" ||
1656 row.kind === "sent-message" ||
1657 row.kind === "mcp-app" ||
1658 row.kind === "viewed-images"
1659 ? "pb-2"
1660 : "pb-4",
1661 (row.kind === "message" && row.message.role === "assistant") ||
1662 row.kind === "assistant-meta"
1663 ? "group/assistant"
1664 : null,
1665 )}
1666 data-timeline-row-id={row.id}
1667 data-timeline-row-kind={row.kind}
1668 data-message-id={
1669 row.kind === "message" || row.kind === "assistant-meta" ? row.message.id : undefined
1670 }
1671 data-message-role={row.kind === "message" ? row.message.role : undefined}
1672 >
1673 {isWorkLogRow ? (
1674 <WorkLogBlock
1675 continues={row.continuesWorkLog}
1676 layout={
1677 isExpandedToolGroup
1678 ? "group-content"
1679 : isExpandedToolGroupHeader
1680 ? "group-header"
1681 : "standalone"
1682 }
1683 >
1684 {row.kind === "work" ? (
1685 <WorkGroupSection
1686 anchorKey={row.id}
1687 groupedEntries={row.groupedEntries}
1688 isExpandedToolGroup={row.isExpandedToolGroup}
1689 displayLabel={row.displayLabel}
1690 />
1691 ) : null}
1692 {row.kind === "work-live" ? <LiveWorkEntryTimelineRow row={row} /> : null}
1693 {row.kind === "work-toggle" ? <WorkGroupToggleTimelineRow row={row} /> : null}
1694 {row.kind === "thinking" ? <ThinkingTimelineRow row={row} /> : null}
1695 </WorkLogBlock>
1696 ) : null}
1697 {row.kind === "turn-fold" ? <TurnFoldTimelineRow key={row.id} row={row} /> : null}
1698 {row.kind === "attempt-fold" ? <AttemptFoldTimelineRow row={row} /> : null}
1699 {row.kind === "context-compaction" ? <ContextCompactionTimelineRow row={row} /> : null}
1700 {row.kind === "message" && row.message.role === "user" ? <UserMessageRow row={row} /> : null}
1701 {row.kind === "message" && row.message.role === "assistant" ? (
1702 <AssistantTimelineRow row={row} />
1703 ) : null}
1704 {row.kind === "assistant-meta" ? <AssistantMetaTimelineRow row={row} /> : null}
1705 {row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
1706 {row.kind === "html-render" ? <HtmlRenderTimelineRow row={row} /> : null}
1707 {row.kind === "sent-message" ? <SentMessageTimelineRow row={row} /> : null}
1708 {row.kind === "viewed-images" ? <ViewedImagesTimelineRow row={row} /> : null}
1709 {row.kind === "mcp-app" ? <McpAppTimelineRow row={row} /> : null}
1710 {row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
1711 {row.kind === "worktree-setup" ? <WorktreeSetupTimelineRow row={row} /> : null}
1712 {row.kind === "event" ? <V2EventTimelineRow row={row} /> : null}
1713 </div>
1714 );
1715 });
1716
1717 function WorktreeSetupTimelineRow({
1718 row,
1719 }: {
1720 row: Extract<TimelineRow, { kind: "worktree-setup" }>;
1721 }) {
1722 const ctx = use(TimelineRowCtx);
1723 const terminalId = row.snapshot.setupScript?.terminalId ?? null;
1724 const openTerminal = ctx.onOpenWorktreeSetupTerminal;
1725 const onOpenTerminal = openTerminal && terminalId ? () => openTerminal(terminalId) : null;
1726 return (
1727 <WorktreeSetupCard
1728 snapshot={row.snapshot}
1729 embedded={row.embedded}
1730 onCancel={row.embedded ? null : ctx.onCancelWorktreeSetup}
1731 onWorkLocally={
1732 !row.embedded && row.snapshot.phase === "running" ? ctx.onWorktreeSetupWorkLocally : null
1733 }
1734 onOpenTerminal={onOpenTerminal}
1735 />
1736 );
1737 }
1738
1739 function ContextCompactionTimelineRow({
1740 row,
1741 }: {
1742 row: Extract<TimelineRow, { kind: "context-compaction" }>;
1743 }) {
1744 const gt = useGT();
1745 const label =
1746 row.title && row.compacted
1747 ? row.tokenCounts
1748 ? gt("{title} {before} → {after} tokens", { title: row.title, ...row.tokenCounts })
1749 : row.title
1750 : row.label;
1751 const content = (
1752 <span className="flex min-w-0 items-center gap-1.5">
1753 {row.failed ? (
1754 <CircleAlertIcon aria-hidden="true" className="size-3 shrink-0" />
1755 ) : (
1756 <Minimize2Icon aria-hidden="true" className="size-3" />
1757 )}
1758 {row.tokenCounts ? (
1759 <>
1760 {row.title ? (
1761 <T>
1762 <Var>{row.title}</Var> <Var>{row.tokenCounts.before}</Var>
1763 <ArrowRightIcon aria-hidden="true" className="size-3" />
1764 <Var>{row.tokenCounts.after}</Var> tokens
1765 </T>
1766 ) : (
1767 <T>
1768 Context compacted <Var>{row.tokenCounts.before}</Var>
1769 <ArrowRightIcon aria-hidden="true" className="size-3" />
1770 <Var>{row.tokenCounts.after}</Var> tokens
1771 </T>
1772 )}
1773 </>
1774 ) : (
1775 label
1776 )}
1777 {row.failure ? (
1778 // oxlint-disable-next-line t3code/no-untranslated-copy -- separator before server-authored failure text
1779 <span className="min-w-0 truncate opacity-80">&middot; {row.failure}</span>
1780 ) : null}
1781 </span>
1782 );
1783 return (
1784 <div
1785 role="separator"
1786 aria-label={row.failure ? `${label}: ${row.failure}` : label}
1787 className={cn(
1788 "mx-auto flex w-full max-w-(--chat-content-max-width) items-center gap-3 py-1 text-xs",
1789 row.failed ? "text-destructive" : "text-muted-foreground",
1790 )}
1791 >
1792 <span className={cn("h-px flex-1", row.failed ? "bg-destructive/30" : "bg-border/70")} />
1793 <span
1794 ref={row.active ? observeVisibleAnimation : undefined}
1795 className="relative min-w-0 overflow-hidden"
1796 >
1797 {content}
1798 {row.active ? <ActivityShimmerOverlay>{content}</ActivityShimmerOverlay> : null}
1799 </span>
1800 <span className={cn("h-px flex-1", row.failed ? "bg-destructive/30" : "bg-border/70")} />
1801 </div>
1802 );
1803 }
1804
1805 function useDeferredWorkLoading(
1806 row: { expanded: boolean; deferredWorkItemIds?: ReadonlyArray<string> },
1807 onToggle: () => void,
1808 ) {
1809 const gt = useGT();
1810 const ctx = use(TimelineRowCtx);
1811 const loadWork = useAtomCommand(threadEnvironment.loadEarlierHistory, { reportFailure: false });
1812 const ref = parseScopedThreadKey(ctx.routeThreadKey);
1813 const environmentId = ref?.environmentId;
1814 const threadId = ref?.threadId;
1815 const anchorsKey = row.deferredWorkItemIds?.join("\n") ?? "";
1816 const [failed, setFailed] = useState(false);
1817 const load = () => {
1818 if (!anchorsKey || environmentId === undefined || threadId === undefined) return;
1819 void Promise.all(
1820 anchorsKey
1821 .split("\n")
1822 .map((workAnchorId) => loadWork({ environmentId, input: { threadId, workAnchorId } })),
1823 ).then((results) =>
1824 setFailed(
1825 results.some((result) => result._tag === "Failure" || result.value._tag === "error"),
1826 ),
1827 );
1828 };
1829 const loadOnExpand = useEffectEvent(load);
1830 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restored expanded folds load their deferred server history on mount.
1831 useEffect(() => {
1832 if (row.expanded && anchorsKey && environmentId && threadId) loadOnExpand();
1833 }, [row.expanded, anchorsKey, environmentId, threadId]);
1834 const error = anchorsKey && failed ? gt("Couldn't load work. Click to retry.") : null;
1835 const loading = ref !== null && row.expanded && anchorsKey !== "" && !failed;
1836 const toggle = () => {
1837 setFailed(false);
1838 if (error && row.expanded) load();
1839 else onToggle();
1840 };
1841
1842 return { loading, error, toggle };
1843 }
1844
1845 function WorkHistorySkeleton() {
1846 const gt = useGT();
1847 return (
1848 <div role="status" aria-label={gt("Loading work history")} className="space-y-2 px-1 pb-1 pt-3">
1849 {[0, 1, 2].map((index) => (
1850 <div key={index} className="flex items-center gap-2" aria-hidden="true">
1851 <Skeleton className="size-3 shrink-0" />
1852 <Skeleton
1853 shape="pill"
1854 className={index === 0 ? "h-2.5 w-2/5" : index === 1 ? "h-2.5 w-3/5" : "h-2.5 w-1/3"}
1855 />
1856 </div>
1857 ))}
1858 </div>
1859 );
1860 }
1861
1862 function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-fold" }> }) {
1863 const ctx = use(TimelineRowCtx);
1864 const { loading, error, toggle } = useDeferredWorkLoading(row, () =>
1865 ctx.onToggleTurnFold(row.runId),
1866 );
1867
1868 return (
1869 <div className="group/timeline-row border-b border-border/60 pb-2 pe-0.5 pt-1">
1870 <div className="relative flex items-center gap-1">
1871 <button
1872 type="button"
1873 aria-expanded={row.expanded}
1874 data-scroll-anchor-ignore
1875 onClick={toggle}
1876 aria-busy={loading}
1877 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"
1878 >
1879 <span>
1880 {row.label}
1881 {error ? ` · ${error}` : ""}
1882 </span>
1883 {row.expanded ? (
1884 <ChevronDownIcon className="size-3.5" />
1885 ) : (
1886 <ChevronRightIcon className="size-3.5" />
1887 )}
1888 </button>
1889 <TimelineRowTimestamp
1890 createdAt={row.createdAt}
1891 timestampFormat={ctx.timestampFormat}
1892 className="ms-auto"
1893 />
1894 </div>
1895 {loading ? <WorkHistorySkeleton /> : null}
1896 </div>
1897 );
1898 }
1899
1900 function AttemptFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "attempt-fold" }> }) {
1901 const ctx = use(TimelineRowCtx);
1902 const { loading, error, toggle } = useDeferredWorkLoading(row, () =>
1903 ctx.onToggleAttemptFold(row.attemptId),
1904 );
1905
1906 return (
1907 <div>
1908 <button
1909 type="button"
1910 aria-expanded={row.expanded}
1911 data-scroll-anchor-ignore
1912 data-superseded-attempt-id={row.attemptId}
1913 onClick={toggle}
1914 aria-busy={loading}
1915 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"
1916 >
1917 {row.expanded ? (
1918 <ChevronDownIcon className="size-3.5 shrink-0 text-muted-foreground" />
1919 ) : (
1920 <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" />
1921 )}
1922 <span className="text-xs font-medium text-foreground/80">
1923 {row.label}
1924 {error ? ` · ${error}` : ""}
1925 </span>
1926 <span className="text-2xs text-muted-foreground">
1927 <T>Cut off by a steer</T>
1928 </span>
1929 </button>
1930 {loading ? <WorkHistorySkeleton /> : null}
1931 </div>
1932 );
1933 }