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