The best way to control Claude Code, Codex and more from any computer or phone

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