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