Open History to see the last commit
1import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow";
2import { WorkLogButton, WorkLogList, WorkLogRow } from "./WorkLog";
3import type { WorktreeSetupSnapshot } from "@t3tools/contracts";
4import { type ToolActivityIcon } from "@t3tools/contracts";
5import { liveThoughtLine } from "@t3tools/client-runtime/work-log/presentation";
6import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
7import { observeResize } from "~/lib/observeResize";
8import { tickTextContent } from "~/lib/tickTextContent";
9import { observeVisibleAnimation } from "../../lib/visibleAnimation";
10import { memo, use, useLayoutEffect, useRef, useState, type ReactNode } from "react";
11import { LegendList, type LegendListRef } from "@legendapp/list/react";
12import { workEntryDisplayIndicatesToolFailure } from "../../session-logic";
13import ChatMarkdown from "../ChatMarkdown";
14import { Minimize2Icon, XIcon } from "lucide-react";
15import { Button } from "../ui/button";
16import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";
17import {
18 liveWorkEntryLabel,
19 resolveWorkGroupScrollIndex,
20 shouldFollowWorkGroupAppend,
21 workEntryIsVisibleInGroup,
22 type MessagesTimelineRow,
23} from "./MessagesTimeline.logic";
24import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
25import { Spinner } from "../ui/spinner";
26import { WorktreeSetupCard } from "./WorktreeSetupCard";
27import { cn } from "~/lib/utils";
28import { type TimestampFormat } from "@t3tools/contracts/settings";
29import {
30 TimelineRowCtx,
31 TimelineRowActivityCtx,
32 WorkGroupViewCtx,
33 type TimelineWorkEntry,
34 type TimelineRow,
35} from "./timelineRowContext";
36import { TimelineRowTimestamp, ActivityShimmerOverlay } from "./TimelineRowParts";
37import {
38 failedToolIconClassName,
39 toolIconAcceptsTint,
40 type WorkEntryIconName,
41 ToolActivityIconView,
42} from "./TimelineToolActivityIcon";
43import {
44 useThreadReadTarget,
45 threadReadLabel,
46 ThreadReadLabel,
47 ReasoningTraceContent,
48 SimpleWorkEntryRow,
49} from "./TimelineWorkEntryRow";
50import {
51 THINKING_PREVIEW_PLUGINS,
52 THOUGHT_PREVIEW_PLUGINS,
53 THOUGHT_PREVIEW_SOURCE_MAX_LENGTH,
54 toolGroupSummaryIconName,
55 workEntryIconName,
56} from "./TimelineWorkEntryRow.logic";
57import { formatWorkingTimerNow } from "./TimelineWorkGroupRows.logic";
58
59export const WorkGroupSection = memo(function WorkGroupSection({
60 anchorKey,
61 disclosureAnchorKey = anchorKey,
62 groupedEntries,
63 isExpandedToolGroup,
64 displayLabel,
65}: {
66 anchorKey: string;
67 disclosureAnchorKey?: string;
68 groupedEntries: Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"];
69 isExpandedToolGroup: boolean;
70 displayLabel?: string | undefined;
71}) {
72 const {
73 workspaceRoot,
74 routeThreadKey,
75 onToggleWorkEntry,
76 onWorkEntryContentReady,
77 pendingApprovals,
78 } = use(TimelineRowCtx);
79 const nonEmptyEntries = groupedEntries.filter((entry) => {
80 const item = entry.projectedItem?.item;
81 return (
82 (item?.type === "approval_request" && pendingApprovals.has(item.requestId)) ||
83 workEntryIsVisibleInGroup(entry, isExpandedToolGroup)
84 );
85 });
86
87 if (nonEmptyEntries.length === 0) return null;
88 if (isExpandedToolGroup && nonEmptyEntries.every((entry) => entry.itemType === "reasoning")) {
89 return <ReasoningTraceContent entries={nonEmptyEntries} />;
90 }
91 if (isExpandedToolGroup) {
92 return (
93 <ExpandedWorkGroupEntries
94 key={`${routeThreadKey}:${anchorKey}`}
95 anchorKey={anchorKey}
96 disclosureAnchorKey={disclosureAnchorKey}
97 entries={nonEmptyEntries}
98 workspaceRoot={workspaceRoot}
99 />
100 );
101 }
102
103 return (
104 <section aria-label="Activity">
105 {nonEmptyEntries.map((workEntry) => (
106 <SimpleWorkEntryRow
107 key={workEntry.id}
108 workEntry={workEntry}
109 workspaceRoot={workspaceRoot}
110 displayLabel={displayLabel}
111 onToggleEntry={(collapsed) =>
112 onToggleWorkEntry(disclosureAnchorKey, collapsed, workEntry.id)
113 }
114 onContentReady={() => onWorkEntryContentReady?.(disclosureAnchorKey, workEntry.id)}
115 />
116 ))}
117 </section>
118 );
119});
120
121function WorkingTimer({ createdAt }: { createdAt: string }) {
122 return (
123 <span
124 ref={tickTextContent(() => formatWorkingTimerNow(createdAt), true)}
125 className="tabular-nums"
126 />
127 );
128}
129
130const compactWorkEntryHeight = 24;
131
132function ExpandedWorkGroupEntries({
133 anchorKey,
134 disclosureAnchorKey,
135 entries,
136 workspaceRoot,
137}: {
138 anchorKey: string;
139 disclosureAnchorKey: string;
140 entries: TimelineWorkEntry[];
141 workspaceRoot: string | undefined;
142}) {
143 const {
144 workGroupViewState: viewState,
145 onToggleWorkEntry,
146 onWorkEntryContentReady,
147 } = use(TimelineRowCtx);
148 const [initialScrollIndex] = useState(() =>
149 resolveWorkGroupScrollIndex(entries, viewState.scrollPositions.get(anchorKey)),
150 );
151 const [restoringPosition, setRestoringPosition] = useState(initialScrollIndex !== undefined);
152 const listRef = useRef<LegendListRef>(null);
153 const [expandedContentHeight, setExpandedContentHeight] = useState(0);
154 const [fades, setFades] = useState({ top: false, bottom: false, viewportHeight: 0 });
155 const [appendState, setAppendState] = useState({ entries, follow: false });
156 // Capture the pre-change edge once per incoming array, before new layout
157 // metrics arrive. Edge/viewport changes never turn a status update into a follow.
158 if (appendState.entries !== entries) {
159 setAppendState({
160 entries,
161 follow:
162 fades.viewportHeight > 0 &&
163 shouldFollowWorkGroupAppend(appendState.entries, entries, fades.bottom ? Infinity : 0),
164 });
165 }
166
167 const groupView = {
168 state: viewState,
169 onToggleEntry: (collapsed: boolean, entryId: string) =>
170 onToggleWorkEntry(disclosureAnchorKey, collapsed, entryId),
171 onContentReady: (entryId: string) => onWorkEntryContentReady?.(disclosureAnchorKey, entryId),
172 };
173 const updateScrollFades = () => {
174 const element = listRef.current?.getScrollableNode();
175 if (!element) return;
176 const distanceFromEnd = element.scrollHeight - element.clientHeight - element.scrollTop;
177 const viewportHeight = element.clientHeight;
178 const top = element.scrollTop > 1;
179 const bottom = distanceFromEnd > 1;
180 setFades((previous) =>
181 previous.top === top &&
182 previous.bottom === bottom &&
183 previous.viewportHeight === viewportHeight
184 ? previous
185 : { top, bottom, viewportHeight },
186 );
187 };
188
189 const handleScroll = () => {
190 const state = listRef.current?.getState();
191 const position = state && resolveWorkGroupScrollAnchor(state);
192 if (position) {
193 viewState.scrollPositions.set(anchorKey, {
194 entryId: position.rowId,
195 offset: position.offsetWithinRow,
196 });
197 }
198 updateScrollFades();
199 };
200
201 const handleLoad = () => {
202 const list = listRef.current;
203 const element = list?.getScrollableNode();
204 if (initialScrollIndex && list && element) {
205 // Bootstrap can report the restored target before the DOM has applied it.
206 // Reconcile once at load, before releasing the measured anchor row.
207 const offset = Math.max(
208 0,
209 Math.min(list.getState().scroll, element.scrollHeight - element.clientHeight),
210 );
211 if (Math.abs(element.scrollTop - offset) > 1) {
212 void list.scrollToOffset({ offset, animated: false });
213 }
214 }
215 setRestoringPosition(false);
216 };
217
218 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes the list scroller and its content with ResizeObserver to update scroll fades
219 useLayoutEffect(() => {
220 const element = listRef.current?.getScrollableNode();
221 if (!element) return;
222 updateScrollFades();
223 const content = element.firstElementChild;
224 return observeResize(content ? [element, content] : element, updateScrollFades);
225 }, [updateScrollFades]);
226
227 const renderEntry = ({ item }: { item: TimelineWorkEntry }) => (
228 <SimpleWorkEntryRow key={item.id} workEntry={item} workspaceRoot={workspaceRoot} />
229 );
230
231 const updateExpandedContentHeight = () => {
232 const state = listRef.current?.getState();
233 let height = 0;
234 for (const entryId of viewState.expandedEntries) {
235 if (state?.indexByKey(entryId) === undefined) continue;
236 height += Math.max(
237 0,
238 (state.sizes.get(entryId) ?? compactWorkEntryHeight) - compactWorkEntryHeight,
239 );
240 }
241 setExpandedContentHeight(height);
242 };
243
244 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads expanded row sizes from LegendList's measured state after layout
245 useLayoutEffect(updateExpandedContentHeight, [entries, updateExpandedContentHeight]);
246
247 return (
248 <WorkGroupViewCtx value={groupView}>
249 <WorkLogList>
250 <LegendList
251 ref={listRef}
252 data={entries}
253 extraData={workspaceRoot}
254 keyExtractor={workEntryKey}
255 renderItem={renderEntry}
256 estimatedItemSize={compactWorkEntryHeight}
257 drawDistance={240}
258 recycleItems
259 {...(initialScrollIndex ? { initialScrollIndex } : {})}
260 maintainScrollAtEnd={
261 appendState.follow ? { animated: false, on: { dataChange: true } } : false
262 }
263 maintainScrollAtEndThreshold={1 / Math.max(1, fades.viewportHeight)}
264 // Measure the restored row even when an intra-row offset puts its
265 // estimated bounds outside the list's small bootstrap render window.
266 {...(restoringPosition && initialScrollIndex
267 ? { alwaysRender: { indices: [initialScrollIndex.index] } }
268 : {})}
269 maintainVisibleContentPosition
270 onLoad={handleLoad}
271 onScroll={handleScroll}
272 onLayout={updateScrollFades}
273 onItemSizeChanged={updateExpandedContentHeight}
274 tabIndex={0}
275 role="region"
276 aria-label="Tool calls"
277 data-tool-group-scroll
278 style={{ maxHeight: `calc(min(18rem, 50dvh) + ${expandedContentHeight}px)` }}
279 className={cn(
280 "scrollbar-gutter-stable scroll-py-6 overflow-x-hidden rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70",
281 getVirtualizedScrollFadeClassName(fades),
282 )}
283 />
284 </WorkLogList>
285 </WorkGroupViewCtx>
286 );
287}
288
289const workEntryKey = (entry: TimelineWorkEntry) => entry.id;
290
291export function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "working" }> }) {
292 const { isCompacting, isPreparingWorktree, backgroundWorktreeSetup } =
293 use(TimelineRowActivityCtx);
294 const compacting = row.compacting === true || isCompacting;
295 const shimmer = isPreparingWorktree || compacting;
296 const label = isPreparingWorktree ? (
297 "Setting up worktree…"
298 ) : compacting ? (
299 <CompactingLabel createdAt={row.createdAt} />
300 ) : row.createdAt ? (
301 <>
302 Working for <WorkingTimer createdAt={row.createdAt} />
303 </>
304 ) : (
305 "Working..."
306 );
307 return (
308 <div className="border-b border-border/60 pb-2 pt-1">
309 <div className="flex h-6 min-w-0 items-baseline gap-2 px-1 text-sm leading-relaxed text-muted-foreground tabular-nums">
310 <span
311 ref={shimmer ? observeVisibleAnimation : undefined}
312 className="relative shrink-0 overflow-hidden whitespace-nowrap"
313 >
314 {label}
315 {shimmer ? <ActivityShimmerOverlay>{label}</ActivityShimmerOverlay> : null}
316 </span>
317 {backgroundWorktreeSetup ? (
318 <BackgroundWorktreeSetupChip snapshot={backgroundWorktreeSetup} />
319 ) : null}
320 </div>
321 </div>
322 );
323}
324
325function BackgroundWorktreeSetupChip({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
326 const ctx = use(TimelineRowCtx);
327 const terminalId = snapshot.setupScript?.terminalId ?? null;
328 const openTerminal = ctx.onOpenWorktreeSetupTerminal;
329 const onOpenTerminal = openTerminal && terminalId ? () => openTerminal(terminalId) : null;
330 const scriptName = snapshot.setupScript?.name ?? "Setup script";
331 return (
332 <Popover>
333 <PopoverTrigger
334 render={
335 <Button
336 variant="ghost-muted"
337 size="micro"
338 className="ml-auto min-w-0 shrink-0"
339 aria-label={`Background setup is still running: ${scriptName}. Show setup progress.`}
340 />
341 }
342 >
343 <Spinner className="size-3 shrink-0" />
344 <span className="truncate">Background setup</span>
345 </PopoverTrigger>
346 <PopoverPopup side="bottom" align="end" width="lg" padding="compact">
347 <WorktreeSetupCard
348 snapshot={snapshot}
349 embedded
350 onCancel={null}
351 onWorkLocally={null}
352 onOpenTerminal={onOpenTerminal}
353 />
354 </PopoverPopup>
355 </Popover>
356 );
357}
358
359function CompactingLabel({ createdAt }: { createdAt: string | null }) {
360 return (
361 <span className="inline-flex items-center gap-1.5">
362 <Minimize2Icon aria-hidden="true" className="size-3" />
363 {createdAt ? (
364 <span>
365 Compacting for <WorkingTimer createdAt={createdAt} />
366 </span>
367 ) : (
368 "Compacting…"
369 )}
370 </span>
371 );
372}
373
374export function ThinkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "thinking" }> }) {
375 const ctx = use(TimelineRowCtx);
376 const { isCompacting, isPreparingWorktree, liveAnswerPreview, providerStartingLabel } =
377 use(TimelineRowActivityCtx);
378 if (isPreparingWorktree || isCompacting) return <WorkLogRow label="" />;
379 // A failed group keeps this disclosure while an approval waits, but nothing is thinking then.
380 const live = ctx.pendingApprovals.size === 0;
381 const activity = (
382 <LiveActivityRow
383 label={providerStartingLabel ?? liveAnswerPreview ?? "Thinking"}
384 iconName="brain"
385 active={live}
386 shimmer={live}
387 />
388 );
389 const { groupId } = row;
390 if (groupId === undefined) return activity;
391 return (
392 <button
393 type="button"
394 className="group/live-work flex min-h-6 w-full max-w-full cursor-pointer items-center rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
395 aria-expanded={row.expanded === true}
396 onClick={() => ctx.onToggleWorkGroup(groupId, row.id)}
397 >
398 {activity}
399 </button>
400 );
401}
402
403function LiveActivityRow({
404 label,
405 iconName,
406 toolIcon,
407 failed = false,
408 active = false,
409 shimmer = false,
410}: {
411 label: ReactNode;
412 iconName?: WorkEntryIconName;
413 toolIcon?: ToolActivityIcon | undefined;
414 failed?: boolean;
415 active?: boolean;
416 shimmer?: boolean;
417}) {
418 const animated = active && !failed;
419 const showShimmer = animated && shimmer;
420 return (
421 <div
422 ref={animated ? observeVisibleAnimation : undefined}
423 className="relative min-h-6 w-fit max-w-full min-w-0 overflow-hidden rounded-md text-sm leading-relaxed"
424 >
425 <LiveActivityContent
426 label={label}
427 iconName={iconName}
428 toolIcon={toolIcon}
429 failed={failed}
430 announceFailure={failed}
431 active={animated && !shimmer}
432 />
433 {showShimmer ? (
434 <ActivityShimmerOverlay>
435 <LiveActivityContent label={label} iconName={iconName} toolIcon={toolIcon} highlighted />
436 </ActivityShimmerOverlay>
437 ) : null}
438 </div>
439 );
440}
441
442function LiveActivityContent({
443 label,
444 iconName,
445 toolIcon,
446 failed = false,
447 announceFailure = false,
448 active = false,
449 highlighted = false,
450}: {
451 label: ReactNode;
452 iconName: WorkEntryIconName | undefined;
453 toolIcon?: ToolActivityIcon | undefined;
454 failed?: boolean;
455 announceFailure?: boolean;
456 active?: boolean;
457 highlighted?: boolean;
458}) {
459 const showTrailingFailureMark =
460 failed && iconName !== undefined && !toolIconAcceptsTint(toolIcon);
461
462 return (
463 <WorkLogRow
464 icon={
465 iconName ? (
466 <span
467 className={cn(
468 "flex size-4 items-center justify-center",
469 failed
470 ? failedToolIconClassName
471 : highlighted
472 ? "text-foreground"
473 : "text-icon-muted",
474 )}
475 role={announceFailure ? "img" : undefined}
476 aria-label={announceFailure ? "Tool call failed" : undefined}
477 >
478 <ToolActivityIconView
479 icon={toolIcon}
480 fallbackName={iconName}
481 className="block size-4 shrink-0 stroke-2"
482 muted={!highlighted}
483 />
484 </span>
485 ) : null
486 }
487 label={
488 <span
489 className={cn(
490 "block truncate",
491 highlighted && "text-foreground",
492 active && "live-tool-shine",
493 )}
494 >
495 {label}
496 </span>
497 }
498 trailing={
499 showTrailingFailureMark ? (
500 <XIcon aria-hidden className={cn("size-3 shrink-0", failedToolIconClassName)} />
501 ) : null
502 }
503 />
504 );
505}
506
507export function LiveWorkEntryTimelineRow({
508 row,
509}: {
510 row: Extract<TimelineRow, { kind: "work-live" }>;
511}) {
512 const ctx = use(TimelineRowCtx);
513 const threadTarget = useThreadReadTarget(row.entry, ctx.activeThreadEnvironmentId);
514 const label = liveWorkEntryLabel(row.entry, ctx.workspaceRoot, row.active);
515 const threadLabel = threadReadLabel(label, threadTarget);
516
517 const item = row.entry.projectedItem?.item;
518 const pendingApproval =
519 item?.type === "approval_request" ? ctx.pendingApprovals.get(item.requestId) : undefined;
520 if (pendingApproval) return <TimelinePendingApprovalRow approval={pendingApproval} />;
521
522 const failed = workEntryDisplayIndicatesToolFailure(row.entry);
523 const thoughtLine =
524 row.thought && !row.expanded
525 ? liveThoughtLine((row.thought.detail ?? "").slice(0, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH))
526 : "";
527 const thoughtIsStatus = thoughtLine !== "" && row.entry === row.thought;
528
529 return (
530 <button
531 type="button"
532 className={cn(
533 "group/live-work flex w-full max-w-full cursor-pointer rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70",
534 thoughtLine ? "flex-col items-start" : "min-h-6 items-center",
535 )}
536 aria-label={
537 failed
538 ? `${thoughtLine ? `${thoughtLine} ` : ""}${threadLabel?.text ?? label}, tool call failed`
539 : undefined
540 }
541 aria-expanded={row.expanded}
542 onClick={() => ctx.onToggleWorkGroup(row.groupId, row.id)}
543 >
544 {thoughtLine ? (
545 <WorkLogRow
546 icon={
547 <span className="flex size-4 items-center justify-center text-icon-muted">
548 <ToolActivityIconView
549 icon={undefined}
550 fallbackName="brain"
551 className="block size-4 shrink-0 stroke-2"
552 muted
553 />
554 </span>
555 }
556 label={
557 <span className="line-clamp-4">
558 <ChatMarkdown
559 inline
560 text={thoughtLine}
561 cwd={ctx.markdownCwd}
562 parseRawHtml={false}
563 extraRemarkPlugins={THOUGHT_PREVIEW_PLUGINS}
564 />
565 </span>
566 }
567 wrapLabel
568 />
569 ) : null}
570 <LiveActivityRow
571 label={
572 thoughtIsStatus ? (
573 row.active ? (
574 "Thinking"
575 ) : (
576 "Thought"
577 )
578 ) : row.entry.itemType === "reasoning" ? (
579 <ChatMarkdown
580 inline
581 text={(row.entry.detail ?? label).slice(0, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH)}
582 cwd={ctx.markdownCwd}
583 parseRawHtml={false}
584 extraRemarkPlugins={row.active ? THINKING_PREVIEW_PLUGINS : THOUGHT_PREVIEW_PLUGINS}
585 />
586 ) : threadLabel ? (
587 <ThreadReadLabel
588 label={threadLabel}
589 environmentId={ctx.activeThreadEnvironmentId}
590 linked={false}
591 />
592 ) : (
593 label
594 )
595 }
596 iconName={workEntryIconName(row.entry)}
597 toolIcon={row.entry.toolIcon ?? row.entry.toolSource?.icon}
598 failed={failed}
599 active={row.active}
600 />
601 </button>
602 );
603}
604
605export function WorkGroupToggleTimelineRow({
606 row,
607}: {
608 row: Extract<TimelineRow, { kind: "work-toggle" }>;
609}) {
610 const ctx = use(TimelineRowCtx);
611 return (
612 <WorkGroupHeader
613 label={row.summary}
614 iconName={row.toolSurface ?? toolGroupSummaryIconName(row.summaryKind)}
615 toolIcon={row.toolIcon}
616 failed={row.hasFailure}
617 expanded={row.expanded}
618 createdAt={row.createdAt}
619 timestampFormat={ctx.timestampFormat}
620 onToggle={() => ctx.onToggleWorkGroup(row.groupId, row.id)}
621 />
622 );
623}
624
625function WorkGroupHeader(props: {
626 label: string;
627 iconName: WorkEntryIconName;
628 toolIcon?: ToolActivityIcon | undefined;
629 failed?: boolean | undefined;
630 expanded: boolean;
631 createdAt: string;
632 timestampFormat: TimestampFormat;
633 onToggle: () => void;
634}) {
635 return (
636 <WorkLogButton
637 aria-label={props.failed ? `${props.label}, tool call failed` : props.label}
638 aria-expanded={props.expanded}
639 onClick={props.onToggle}
640 icon={
641 <ToolActivityIconView
642 icon={props.toolIcon}
643 fallbackName={props.iconName}
644 className="size-4 shrink-0 stroke-2 text-icon-muted"
645 muted
646 />
647 }
648 label={<span className="block truncate">{props.label}</span>}
649 trailing={
650 <TimelineRowTimestamp createdAt={props.createdAt} timestampFormat={props.timestampFormat} />
651 }
652 />
653 );
654}