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