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

TimelineWorkGroupRows.tsx

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