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 compacting = row.compacting ?? (isCompacting ? "Compacting…" : undefined);
290 const shimmer = isPreparingWorktree || compacting !== undefined;
291 const label = isPreparingWorktree ? (
292 "Setting up worktree…"
293 ) : compacting !== undefined ? (
294 <CompactingLabel label={compacting} />
295 ) : row.createdAt ? (
296 <>
297 Working for <WorkingTimer createdAt={row.createdAt} />
298 </>
299 ) : (
300 "Working..."
301 );
302 return (
303 <div className="border-b border-border/60 pb-2 pt-1">
304 <div className="flex h-6 min-w-0 items-baseline gap-2 px-1 text-sm leading-relaxed text-muted-foreground tabular-nums">
305 <span
306 ref={shimmer ? observeVisibleAnimation : undefined}
307 className="relative shrink-0 overflow-hidden whitespace-nowrap"
308 >
309 {label}
310 {shimmer ? <ActivityShimmerOverlay>{label}</ActivityShimmerOverlay> : null}
311 </span>
312 {backgroundWorktreeSetup ? (
313 <BackgroundWorktreeSetupChip snapshot={backgroundWorktreeSetup} />
314 ) : null}
315 </div>
316 </div>
317 );
318}
319
320function BackgroundWorktreeSetupChip({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
321 const ctx = use(TimelineRowCtx);
322 const terminalId = snapshot.setupScript?.terminalId ?? null;
323 const openTerminal = ctx.onOpenWorktreeSetupTerminal;
324 const onOpenTerminal = openTerminal && terminalId ? () => openTerminal(terminalId) : null;
325 const scriptName = snapshot.setupScript?.name ?? "Setup script";
326 return (
327 <Popover>
328 <PopoverTrigger
329 render={
330 <Button
331 variant="ghost-muted"
332 size="micro"
333 className="ml-auto min-w-0 shrink-0"
334 aria-label={`Background setup is still running: ${scriptName}. Show setup progress.`}
335 />
336 }
337 >
338 <Spinner className="size-3 shrink-0" />
339 <span className="truncate">Background setup</span>
340 </PopoverTrigger>
341 <PopoverPopup side="bottom" align="end" width="lg" padding="compact">
342 <WorktreeSetupCard
343 snapshot={snapshot}
344 embedded
345 onCancel={null}
346 onWorkLocally={null}
347 onOpenTerminal={onOpenTerminal}
348 />
349 </PopoverPopup>
350 </Popover>
351 );
352}
353
354function CompactingLabel({ label }: { label: string }) {
355 return (
356 <span className="inline-flex items-center gap-1.5">
357 <Minimize2Icon aria-hidden="true" className="size-3" />
358 {label}
359 </span>
360 );
361}
362
363export function ThinkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "thinking" }> }) {
364 const ctx = use(TimelineRowCtx);
365 const { isCompacting, isPreparingWorktree } = use(TimelineRowActivityCtx);
366 if (isPreparingWorktree || isCompacting) return <WorkLogRow label="" />;
367 const activity = <LiveActivityRow label="Thinking" iconName="brain" active shimmer />;
368 const { groupId } = row;
369 if (groupId === undefined) return activity;
370 return (
371 <button
372 type="button"
373 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"
374 aria-expanded={row.expanded === true}
375 onClick={() => ctx.onToggleWorkGroup(groupId, row.id)}
376 >
377 {activity}
378 </button>
379 );
380}
381
382function LiveActivityRow({
383 label,
384 iconName,
385 toolIcon,
386 failed = false,
387 active = false,
388 shimmer = false,
389}: {
390 label: ReactNode;
391 iconName?: WorkEntryIconName;
392 toolIcon?: ToolActivityIcon | undefined;
393 failed?: boolean;
394 active?: boolean;
395 shimmer?: boolean;
396}) {
397 const animated = active && !failed;
398 const showShimmer = animated && shimmer;
399 return (
400 <div
401 ref={animated ? observeVisibleAnimation : undefined}
402 className="relative min-h-6 w-fit max-w-full min-w-0 overflow-hidden rounded-md text-sm leading-relaxed"
403 >
404 <LiveActivityContent
405 label={label}
406 iconName={iconName}
407 toolIcon={toolIcon}
408 failed={failed}
409 announceFailure={failed}
410 active={animated && !shimmer}
411 />
412 {showShimmer ? (
413 <ActivityShimmerOverlay>
414 <LiveActivityContent label={label} iconName={iconName} toolIcon={toolIcon} highlighted />
415 </ActivityShimmerOverlay>
416 ) : null}
417 </div>
418 );
419}
420
421function LiveActivityContent({
422 label,
423 iconName,
424 toolIcon,
425 failed = false,
426 announceFailure = false,
427 active = false,
428 highlighted = false,
429}: {
430 label: ReactNode;
431 iconName: WorkEntryIconName | undefined;
432 toolIcon?: ToolActivityIcon | undefined;
433 failed?: boolean;
434 announceFailure?: boolean;
435 active?: boolean;
436 highlighted?: boolean;
437}) {
438 const showTrailingFailureMark =
439 failed && iconName !== undefined && !toolIconAcceptsTint(toolIcon);
440
441 return (
442 <WorkLogRow
443 icon={
444 iconName ? (
445 <span
446 className={cn(
447 "flex size-4 items-center justify-center",
448 failed
449 ? failedToolIconClassName
450 : highlighted
451 ? "text-foreground"
452 : "text-icon-muted",
453 )}
454 role={announceFailure ? "img" : undefined}
455 aria-label={announceFailure ? "Tool call failed" : undefined}
456 >
457 <ToolActivityIconView
458 icon={toolIcon}
459 fallbackName={iconName}
460 className="block size-4 shrink-0 stroke-2"
461 muted={!highlighted}
462 />
463 </span>
464 ) : null
465 }
466 label={
467 <span
468 className={cn(
469 "block truncate",
470 highlighted && "text-foreground",
471 active && "live-tool-shine",
472 )}
473 >
474 {label}
475 </span>
476 }
477 trailing={
478 showTrailingFailureMark ? (
479 <XIcon aria-hidden className={cn("size-3 shrink-0", failedToolIconClassName)} />
480 ) : null
481 }
482 />
483 );
484}
485
486export function LiveWorkEntryTimelineRow({
487 row,
488}: {
489 row: Extract<TimelineRow, { kind: "work-live" }>;
490}) {
491 const ctx = use(TimelineRowCtx);
492 const threadTarget = useThreadReadTarget(row.entry, ctx.activeThreadEnvironmentId);
493 const questionHeading = row.entry.questionAnswer
494 ? getQuestionTextPreview(row.entry.questionAnswer)
495 : "";
496 const label = questionHeading || liveWorkEntryLabel(row.entry, ctx.workspaceRoot, row.active);
497 const threadLabel = threadReadLabel(label, threadTarget);
498
499 const failed = workEntryDisplayIndicatesToolFailure(row.entry);
500 const thoughtLine = row.thought && !row.expanded ? liveThoughtLine(row.thought.detail ?? "") : "";
501 const thoughtIsStatus = thoughtLine !== "" && row.entry === row.thought;
502
503 return (
504 <button
505 type="button"
506 className={cn(
507 "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",
508 thoughtLine ? "flex-col items-start" : "min-h-6 items-center",
509 )}
510 aria-label={
511 failed
512 ? `${thoughtLine ? `${thoughtLine} ` : ""}${threadLabel?.text ?? label}, tool call failed`
513 : undefined
514 }
515 aria-expanded={row.expanded}
516 onClick={() => ctx.onToggleWorkGroup(row.groupId, row.id)}
517 >
518 {thoughtLine ? (
519 <WorkLogRow
520 icon={
521 <span className="flex size-4 items-center justify-center text-icon-muted">
522 <ToolActivityIconView
523 icon={undefined}
524 fallbackName="brain"
525 className="block size-4 shrink-0 stroke-2"
526 muted
527 />
528 </span>
529 }
530 label={
531 <span className="line-clamp-4">
532 <ChatMarkdown
533 inline
534 text={thoughtLine}
535 cwd={ctx.markdownCwd}
536 parseRawHtml={false}
537 extraRemarkPlugins={[[remarkThoughtPreview, "Thought"]]}
538 />
539 </span>
540 }
541 wrapLabel
542 />
543 ) : null}
544 <LiveActivityRow
545 label={
546 thoughtIsStatus ? (
547 row.active ? (
548 "Thinking"
549 ) : (
550 "Thought"
551 )
552 ) : row.entry.questionAnswer && hasQuestionAnswer(row.entry.questionAnswer) ? (
553 <span className="flex min-w-0 gap-1.5">
554 <span className="min-w-0 truncate">{label}</span>
555 <span className="min-w-0 truncate text-foreground">
556 {getQuestionAnswerPreview(row.entry.questionAnswer)}
557 </span>
558 </span>
559 ) : row.entry.itemType === "reasoning" ? (
560 <ChatMarkdown
561 inline
562 text={row.entry.detail ?? label}
563 cwd={ctx.markdownCwd}
564 parseRawHtml={false}
565 extraRemarkPlugins={[[remarkThoughtPreview, row.active ? "Thinking" : "Thought"]]}
566 />
567 ) : threadLabel ? (
568 <ThreadReadLabel
569 label={threadLabel}
570 environmentId={ctx.activeThreadEnvironmentId}
571 linked={false}
572 />
573 ) : (
574 label
575 )
576 }
577 iconName={workEntryIconName(row.entry)}
578 toolIcon={row.entry.toolIcon ?? row.entry.toolSource?.icon}
579 failed={failed}
580 active={row.active}
581 />
582 </button>
583 );
584}
585
586export function WorkGroupToggleTimelineRow({
587 row,
588}: {
589 row: Extract<TimelineRow, { kind: "work-toggle" }>;
590}) {
591 const ctx = use(TimelineRowCtx);
592 return (
593 <WorkGroupHeader
594 label={row.summary}
595 iconName={row.summaryToolIcon ?? row.toolSurface ?? toolGroupSummaryIconName(row.summaryKind)}
596 toolIcon={row.toolIcon}
597 failed={row.hasFailure}
598 expanded={row.expanded}
599 createdAt={row.createdAt}
600 timestampFormat={ctx.timestampFormat}
601 onToggle={() => ctx.onToggleWorkGroup(row.groupId, row.id)}
602 />
603 );
604}
605
606function WorkGroupHeader(props: {
607 label: string;
608 iconName: WorkEntryIconName;
609 toolIcon?: ToolActivityIcon | undefined;
610 failed?: boolean | undefined;
611 active?: boolean | undefined;
612 expanded: boolean;
613 createdAt: string;
614 timestampFormat: TimestampFormat;
615 onToggle: () => void;
616}) {
617 return (
618 <WorkLogButton
619 ref={props.active && !props.failed ? observeVisibleAnimation : undefined}
620 aria-label={props.failed ? `${props.label}, tool call failed` : props.label}
621 aria-expanded={props.expanded}
622 onClick={props.onToggle}
623 icon={
624 <ToolActivityIconView
625 icon={props.toolIcon}
626 fallbackName={props.iconName}
627 className="size-4 shrink-0 stroke-2 text-icon-muted"
628 muted
629 />
630 }
631 label={
632 <span className={cn("block truncate", props.active && !props.failed && "live-tool-shine")}>
633 {props.label}
634 </span>
635 }
636 trailing={
637 <TimelineRowTimestamp createdAt={props.createdAt} timestampFormat={props.timestampFormat} />
638 }
639 />
640 );
641}