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 } = use(TimelineRowActivityCtx);
377 if (isPreparingWorktree || isCompacting) return <WorkLogRow label="" />;
378 // A failed group keeps this disclosure while an approval waits, but nothing is thinking then.
379 const live = ctx.pendingApprovals.size === 0;
380 const activity = (
381 <LiveActivityRow
382 label={liveAnswerPreview ?? "Thinking"}
383 iconName="brain"
384 active={live}
385 shimmer={live}
386 />
387 );
388 const { groupId } = row;
389 if (groupId === undefined) return activity;
390 return (
391 <button
392 type="button"
393 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"
394 aria-expanded={row.expanded === true}
395 onClick={() => ctx.onToggleWorkGroup(groupId, row.id)}
396 >
397 {activity}
398 </button>
399 );
400}
401
402function LiveActivityRow({
403 label,
404 iconName,
405 toolIcon,
406 failed = false,
407 active = false,
408 shimmer = false,
409}: {
410 label: ReactNode;
411 iconName?: WorkEntryIconName;
412 toolIcon?: ToolActivityIcon | undefined;
413 failed?: boolean;
414 active?: boolean;
415 shimmer?: boolean;
416}) {
417 const animated = active && !failed;
418 const showShimmer = animated && shimmer;
419 return (
420 <div
421 ref={animated ? observeVisibleAnimation : undefined}
422 className="relative min-h-6 w-fit max-w-full min-w-0 overflow-hidden rounded-md text-sm leading-relaxed"
423 >
424 <LiveActivityContent
425 label={label}
426 iconName={iconName}
427 toolIcon={toolIcon}
428 failed={failed}
429 announceFailure={failed}
430 active={animated && !shimmer}
431 />
432 {showShimmer ? (
433 <ActivityShimmerOverlay>
434 <LiveActivityContent label={label} iconName={iconName} toolIcon={toolIcon} highlighted />
435 </ActivityShimmerOverlay>
436 ) : null}
437 </div>
438 );
439}
440
441function LiveActivityContent({
442 label,
443 iconName,
444 toolIcon,
445 failed = false,
446 announceFailure = false,
447 active = false,
448 highlighted = false,
449}: {
450 label: ReactNode;
451 iconName: WorkEntryIconName | undefined;
452 toolIcon?: ToolActivityIcon | undefined;
453 failed?: boolean;
454 announceFailure?: boolean;
455 active?: boolean;
456 highlighted?: boolean;
457}) {
458 const showTrailingFailureMark =
459 failed && iconName !== undefined && !toolIconAcceptsTint(toolIcon);
460
461 return (
462 <WorkLogRow
463 icon={
464 iconName ? (
465 <span
466 className={cn(
467 "flex size-4 items-center justify-center",
468 failed
469 ? failedToolIconClassName
470 : highlighted
471 ? "text-foreground"
472 : "text-icon-muted",
473 )}
474 role={announceFailure ? "img" : undefined}
475 aria-label={announceFailure ? "Tool call failed" : undefined}
476 >
477 <ToolActivityIconView
478 icon={toolIcon}
479 fallbackName={iconName}
480 className="block size-4 shrink-0 stroke-2"
481 muted={!highlighted}
482 />
483 </span>
484 ) : null
485 }
486 label={
487 <span
488 className={cn(
489 "block truncate",
490 highlighted && "text-foreground",
491 active && "live-tool-shine",
492 )}
493 >
494 {label}
495 </span>
496 }
497 trailing={
498 showTrailingFailureMark ? (
499 <XIcon aria-hidden className={cn("size-3 shrink-0", failedToolIconClassName)} />
500 ) : null
501 }
502 />
503 );
504}
505
506export function LiveWorkEntryTimelineRow({
507 row,
508}: {
509 row: Extract<TimelineRow, { kind: "work-live" }>;
510}) {
511 const ctx = use(TimelineRowCtx);
512 const threadTarget = useThreadReadTarget(row.entry, ctx.activeThreadEnvironmentId);
513 const label = liveWorkEntryLabel(row.entry, ctx.workspaceRoot, row.active);
514 const threadLabel = threadReadLabel(label, threadTarget);
515
516 const item = row.entry.projectedItem?.item;
517 const pendingApproval =
518 item?.type === "approval_request" ? ctx.pendingApprovals.get(item.requestId) : undefined;
519 if (pendingApproval) return <TimelinePendingApprovalRow approval={pendingApproval} />;
520
521 const failed = workEntryDisplayIndicatesToolFailure(row.entry);
522 const thoughtLine =
523 row.thought && !row.expanded
524 ? liveThoughtLine((row.thought.detail ?? "").slice(0, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH))
525 : "";
526 const thoughtIsStatus = thoughtLine !== "" && row.entry === row.thought;
527
528 return (
529 <button
530 type="button"
531 className={cn(
532 "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",
533 thoughtLine ? "flex-col items-start" : "min-h-6 items-center",
534 )}
535 aria-label={
536 failed
537 ? `${thoughtLine ? `${thoughtLine} ` : ""}${threadLabel?.text ?? label}, tool call failed`
538 : undefined
539 }
540 aria-expanded={row.expanded}
541 onClick={() => ctx.onToggleWorkGroup(row.groupId, row.id)}
542 >
543 {thoughtLine ? (
544 <WorkLogRow
545 icon={
546 <span className="flex size-4 items-center justify-center text-icon-muted">
547 <ToolActivityIconView
548 icon={undefined}
549 fallbackName="brain"
550 className="block size-4 shrink-0 stroke-2"
551 muted
552 />
553 </span>
554 }
555 label={
556 <span className="line-clamp-4">
557 <ChatMarkdown
558 inline
559 text={thoughtLine}
560 cwd={ctx.markdownCwd}
561 parseRawHtml={false}
562 extraRemarkPlugins={THOUGHT_PREVIEW_PLUGINS}
563 />
564 </span>
565 }
566 wrapLabel
567 />
568 ) : null}
569 <LiveActivityRow
570 label={
571 thoughtIsStatus ? (
572 row.active ? (
573 "Thinking"
574 ) : (
575 "Thought"
576 )
577 ) : row.entry.itemType === "reasoning" ? (
578 <ChatMarkdown
579 inline
580 text={(row.entry.detail ?? label).slice(0, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH)}
581 cwd={ctx.markdownCwd}
582 parseRawHtml={false}
583 extraRemarkPlugins={row.active ? THINKING_PREVIEW_PLUGINS : THOUGHT_PREVIEW_PLUGINS}
584 />
585 ) : threadLabel ? (
586 <ThreadReadLabel
587 label={threadLabel}
588 environmentId={ctx.activeThreadEnvironmentId}
589 linked={false}
590 />
591 ) : (
592 label
593 )
594 }
595 iconName={workEntryIconName(row.entry)}
596 toolIcon={row.entry.toolIcon ?? row.entry.toolSource?.icon}
597 failed={failed}
598 active={row.active}
599 />
600 </button>
601 );
602}
603
604export function WorkGroupToggleTimelineRow({
605 row,
606}: {
607 row: Extract<TimelineRow, { kind: "work-toggle" }>;
608}) {
609 const ctx = use(TimelineRowCtx);
610 return (
611 <WorkGroupHeader
612 label={row.summary}
613 iconName={row.toolSurface ?? toolGroupSummaryIconName(row.summaryKind)}
614 toolIcon={row.toolIcon}
615 failed={row.hasFailure}
616 expanded={row.expanded}
617 createdAt={row.createdAt}
618 timestampFormat={ctx.timestampFormat}
619 onToggle={() => ctx.onToggleWorkGroup(row.groupId, row.id)}
620 />
621 );
622}
623
624function WorkGroupHeader(props: {
625 label: string;
626 iconName: WorkEntryIconName;
627 toolIcon?: ToolActivityIcon | undefined;
628 failed?: boolean | undefined;
629 expanded: boolean;
630 createdAt: string;
631 timestampFormat: TimestampFormat;
632 onToggle: () => void;
633}) {
634 return (
635 <WorkLogButton
636 aria-label={props.failed ? `${props.label}, tool call failed` : props.label}
637 aria-expanded={props.expanded}
638 onClick={props.onToggle}
639 icon={
640 <ToolActivityIconView
641 icon={props.toolIcon}
642 fallbackName={props.iconName}
643 className="size-4 shrink-0 stroke-2 text-icon-muted"
644 muted
645 />
646 }
647 label={<span className="block truncate">{props.label}</span>}
648 trailing={
649 <TimelineRowTimestamp createdAt={props.createdAt} timestampFormat={props.timestampFormat} />
650 }
651 />
652 );
653}