Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

TimelineWorkGroupRows.tsx

637 lines20.7 KB

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