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

thread-work-log.tsx

1,380 lines47.7 KB

1import { SubagentStatusDot } from "./SubagentStatusDot";
2import { ThreadSubagentGroup } from "./thread-subagent-group";
3import {
4 WorkLogLabel,
5 WorkLogBlock,
6 WorkLogRows,
7 WorkLogIconSlot,
8 WorkLogPressable,
9} from "./work-log-layout";
10import { QuestionAnswerHistory } from "./QuestionAnswerHistory";
11import {
12 getQuestionAnswerPreview,
13 hasQuestionAnswer,
14} from "@t3tools/client-runtime/work-log/user-input";
15import * as Haptics from "expo-haptics";
16import { Image } from "expo-image";
17import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
18import { MaskedView } from "@expo/ui/community/masked-view";
19import type { LegendListRef } from "@legendapp/list/react-native";
20import { AnimatedLegendList } from "@legendapp/list/reanimated";
21import { useIsFocused } from "@react-navigation/native";
22import {
23 memo,
24 useCallback,
25 useEffect,
26 useId,
27 useLayoutEffect,
28 useMemo,
29 useRef,
30 useState,
31 type ComponentProps,
32 type ReactNode,
33} from "react";
34import {
35 AccessibilityInfo,
36 AppState,
37 type ColorValue,
38 Pressable,
39 ScrollView,
40 StyleSheet,
41 View,
42} from "react-native";
43import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
44import type { EnvironmentId, ToolActivityIcon } from "@t3tools/contracts";
45import { toolActivityFaviconUrl } from "@t3tools/shared/favicon";
46​
47import { AppText as Text } from "../../components/AppText";
48import { T3Wordmark } from "../../components/T3Wordmark";
49import { cn } from "../../lib/cn";
50import { THREAD_WORK_ROW_MIN_HEIGHT, type deriveThreadWorkLogSizing } from "../../lib/layout";
51import {
52 type AgentSpawnSummary,
53 type ThreadFeedActivity,
54 workEntryRowLabel,
55} from "../../lib/threadActivity";
56import {
57 resolveThreadWorkGroupInitialScroll,
58 shouldFollowThreadWorkGroupAppend,
59 type ThreadWorkGroupScrollPosition,
60} from "./thread-feed-live-follow";
61import {
62 resolveWorkEntryToolPresentation,
63 type ToolGroupSummaryKind,
64 workEntryViewedImagePath,
65} from "@t3tools/client-runtime/work-log/presentation";
66import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
67import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText";
68import Animated, {
69 cancelAnimation,
70 Easing,
71 FadeIn,
72 FadeOut,
73 LinearTransition,
74 ReduceMotion,
75 useAnimatedStyle,
76 useSharedValue,
77 withDelay,
78 withRepeat,
79 withSequence,
80 withTiming,
81} from "react-native-reanimated";
82import { useAssetUrl } from "../../state/assets";
83​
84const SHIMMER_WIDTH = 72;
85const SHIMMER_SWEEP_MS = 1_350;
86const SHIMMER_PAUSE_MS = 1_450;
87const SHIMMER_ICON_AND_GAP_WIDTH = 30;
88export const THREAD_DISCLOSURE_TRANSITION_MS = 180;
89const WORK_LOG_LAYOUT_TRANSITION = LinearTransition.duration(THREAD_DISCLOSURE_TRANSITION_MS);
90const WORK_LOG_DETAIL_ENTER_TRANSITION = FadeIn.duration(140);
91const WORK_LOG_DETAIL_EXIT_TRANSITION = FadeOut.duration(120);
92type WorkContentIcon = AppSymbolName | "browser" | "device" | "t3-code" | "pull-request";
93​
94function WorkLogIcon(props: {
95 readonly icon: WorkContentIcon;
96 readonly color: ColorValue;
97 readonly colorClassName?: string;
98 readonly highlighted?: boolean;
99}) {
100 const colorClassName = props.highlighted ? "accent-foreground" : props.colorClassName;
101 if (props.icon === "t3-code") {
102 return (
103 <T3Wordmark height={10} {...(colorClassName ? { colorClassName } : { color: props.color })} />
104 );
105 }
106 return (
107 <SymbolView
108 name={
109 props.icon === "pull-request"
110 ? "arrow.triangle.pull"
111 : props.icon === "browser"
112 ? { ios: "globe", android: "public" }
113 : props.icon === "device"
114 ? { ios: "iphone", android: "smartphone" }
115 : props.icon
116 }
117 size={14}
118 weight="medium"
119 {...(colorClassName ? { tintColorClassName: colorClassName } : { tintColor: props.color })}
120 type="monochrome"
121 />
122 );
124​
125export function ThreadDisclosureChevron(props: {
126 readonly expanded: boolean;
127 readonly collapsedDirection: "right" | "down";
128 readonly size: number;
129 readonly tintColor: ColorValue;
130}) {
131 const expandedAngle = props.collapsedDirection === "right" ? 90 : 180;
132 const rotation = useSharedValue(props.expanded ? expandedAngle : 0);
133​
134 useLayoutEffect(() => {
135 rotation.value = withTiming(props.expanded ? expandedAngle : 0, {
136 duration: THREAD_DISCLOSURE_TRANSITION_MS,
137 reduceMotion: ReduceMotion.System,
138 });
139 }, [expandedAngle, props.expanded, rotation]);
140​
141 const rotationStyle = useAnimatedStyle(() => ({
142 transform: [{ rotate: `${rotation.value}deg` }],
143 }));
144​
145 return (
146 <Animated.View
147 accessible={false}
148 accessibilityElementsHidden
149 importantForAccessibility="no-hide-descendants"
150 pointerEvents="none"
151 style={[{ width: props.size, height: props.size }, rotationStyle]}
152 >
153 <SymbolView
154 name={props.collapsedDirection === "right" ? "chevron.right" : "chevron.down"}
155 size={props.size}
156 tintColor={props.tintColor}
157 type="monochrome"
158 />
159 </Animated.View>
160 );
162​
163function ShimmerWorkContent(props: {
164 readonly textClassName?: string;
165 readonly compact?: boolean;
166 readonly environmentId?: EnvironmentId;
167 readonly highlighted: boolean;
168 readonly icon: WorkContentIcon;
169 readonly iconSubtleColor: ColorValue;
170 readonly label: string;
171 readonly onTextLayout?: ComponentProps<typeof Text>["onTextLayout"];
172 readonly showIcon: boolean;
173 readonly themeAppearance?: "light" | "dark";
174 readonly toolIcon?: ToolActivityIcon;
175}) {
176 return (
177 <View className="flex-row items-center gap-1.5">
178 {props.showIcon ? (
179 <View className="h-6 w-6 shrink-0 items-center justify-center">
180 {props.toolIcon && props.environmentId ? (
181 <ToolActivityIconView
182 environmentId={props.environmentId}
183 icon={props.toolIcon}
184 fallback={props.icon}
185 fallbackColor={props.iconSubtleColor}
186 themeAppearance={props.themeAppearance ?? "light"}
187 />
188 ) : (
189 <WorkLogIcon
190 icon={props.icon}
191 color={props.iconSubtleColor}
192 highlighted={props.highlighted}
193 />
194 )}
195 </View>
196 ) : null}
197 <Text
198 className={cn(
199 "min-w-0 shrink",
200 props.compact ? "text-xs" : "text-sm",
201 props.highlighted ? "text-foreground" : "text-foreground-muted",
202 props.textClassName,
203 )}
204 numberOfLines={1}
205 onTextLayout={props.onTextLayout}
206 >
207 {props.label}
208 </Text>
209 </View>
210 );
212​
213export function ShimmeringWorkContent(props: {
214 readonly className?: string;
215 readonly textClassName?: string;
216 /** Secondary line: no icon slot, caption size. */
217 readonly compact?: boolean;
218 readonly environmentId?: EnvironmentId;
219 readonly icon: WorkContentIcon;
220 readonly iconSubtleColor: ColorValue;
221 readonly label: string;
222 readonly showIcon: boolean;
223 readonly themeAppearance?: "light" | "dark";
224 readonly toolIcon?: ToolActivityIcon;
225}) {
226 const [availableWidth, setAvailableWidth] = useState(0);
227 const [textWidth, setTextWidth] = useState(0);
228 const [appIsActive, setAppIsActive] = useState(AppState.currentState === "active");
229 const [reducedMotion, setReducedMotion] = useState(true);
230 const screenIsFocused = useIsFocused();
231 const progress = useSharedValue(0);
232 const gradientId = `work-shimmer-${useId().replaceAll(":", "")}`;
233 const contentWidth = Math.min(
234 availableWidth,
235 (props.showIcon ? SHIMMER_ICON_AND_GAP_WIDTH : 0) + Math.ceil(textWidth),
236 );
237​
238 useEffect(() => {
239 const subscription = AppState.addEventListener("change", (state) => {
240 setAppIsActive(state === "active");
241 });
242 return () => subscription.remove();
243 }, []);
244​
245 useEffect(() => {
246 void AccessibilityInfo.isReduceMotionEnabled().then(setReducedMotion);
247 const subscription = AccessibilityInfo.addEventListener(
248 "reduceMotionChanged",
249 setReducedMotion,
250 );
251 return () => subscription.remove();
252 }, []);
253​
254 useEffect(() => {
255 cancelAnimation(progress);
256 progress.value = 0;
257 if (contentWidth <= 0 || reducedMotion || !appIsActive || !screenIsFocused) return;
258​
259 progress.value = withRepeat(
260 withSequence(
261 withTiming(1, {
262 duration: SHIMMER_SWEEP_MS,
263 easing: Easing.linear,
264 reduceMotion: ReduceMotion.Never,
265 }),
266 withDelay(
267 SHIMMER_PAUSE_MS,
268 withTiming(0, { duration: 0, reduceMotion: ReduceMotion.Never }),
269 ),
270 ),
271 -1,
272 false,
273 undefined,
274 ReduceMotion.Never,
275 );
276 return () => cancelAnimation(progress);
277 }, [appIsActive, contentWidth, progress, reducedMotion, screenIsFocused]);
278​
279 const sweepStyle = useAnimatedStyle(() => ({
280 transform: [{ translateX: -SHIMMER_WIDTH + progress.value * (contentWidth + SHIMMER_WIDTH) }],
281 }));
282 const counterSweepStyle = useAnimatedStyle(() => ({
283 transform: [{ translateX: SHIMMER_WIDTH - progress.value * (contentWidth + SHIMMER_WIDTH) }],
284 }));
285​
286 return (
287 <View
288 className={cn("min-w-0 flex-1 overflow-hidden", props.className)}
289 onLayout={(event) => setAvailableWidth(event.nativeEvent.layout.width)}
290 >
291 <ShimmerWorkContent
292 textClassName={props.textClassName}
293 compact={props.compact}
294 environmentId={props.environmentId}
295 highlighted={false}
296 icon={props.icon}
297 iconSubtleColor={props.iconSubtleColor}
298 label={props.label}
299 showIcon={props.showIcon}
300 themeAppearance={props.themeAppearance}
301 toolIcon={props.toolIcon}
302 onTextLayout={(event) => setTextWidth(event.nativeEvent.lines[0]?.width ?? 0)}
303 />
304 {!reducedMotion && appIsActive && screenIsFocused && contentWidth > 0 ? (
305 <Animated.View
306 className="absolute inset-y-0 left-0 overflow-hidden"
307 pointerEvents="none"
308 accessible={false}
309 accessibilityElementsHidden
310 importantForAccessibility="no-hide-descendants"
311 style={[{ width: SHIMMER_WIDTH }, sweepStyle]}
312 >
313 <MaskedView
314 style={StyleSheet.absoluteFill}
315 maskElement={
316 <Svg width="100%" height="100%">
317 <Defs>
318 <LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
319 <Stop offset="0" stopColor="white" stopOpacity={0} />
320 <Stop offset="0.15" stopColor="white" stopOpacity={0.12} />
321 <Stop offset="0.35" stopColor="white" stopOpacity={0.55} />
322 <Stop offset="0.5" stopColor="white" stopOpacity={1} />
323 <Stop offset="0.65" stopColor="white" stopOpacity={0.55} />
324 <Stop offset="0.85" stopColor="white" stopOpacity={0.12} />
325 <Stop offset="1" stopColor="white" stopOpacity={0} />
326 </LinearGradient>
327 </Defs>
328 <Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
329 </Svg>
330 }
331 >
332 <Animated.View style={[{ width: availableWidth }, counterSweepStyle]}>
333 <ShimmerWorkContent
334 textClassName={props.textClassName}
335 compact={props.compact}
336 environmentId={props.environmentId}
337 highlighted
338 icon={props.icon}
339 iconSubtleColor={props.iconSubtleColor}
340 label={props.label}
341 showIcon={props.showIcon}
342 themeAppearance={props.themeAppearance}
343 toolIcon={props.toolIcon}
344 />
345 </Animated.View>
346 </MaskedView>
347 </Animated.View>
348 ) : null}
349 </View>
350 );
352​
353function workRowSymbolName(icon: ThreadFeedActivity["icon"]): AppSymbolName {
354 switch (icon) {
355 case "agent":
356 return { ios: "sparkles", android: "auto_awesome" };
357 case "alert":
358 return { ios: "exclamationmark.triangle", android: "error" };
359 case "browser":
360 return { ios: "safari", android: "public" };
361 case "check":
362 return { ios: "checkmark", android: "check" };
363 case "command":
364 return { ios: "terminal", android: "terminal" };
365 case "computer":
366 return { ios: "desktopcomputer", android: "desktop_windows" };
367 case "edit":
368 return { ios: "square.and.pencil", android: "edit" };
369 case "eye":
370 return { ios: "eye", android: "visibility" };
371 case "globe":
372 return { ios: "globe", android: "public" };
373 case "hammer":
374 return { ios: "hammer", android: "construction" };
375 case "lock":
376 return { ios: "lock", android: "lock" };
377 case "message":
378 return { ios: "bubble.left", android: "chat_bubble" };
379 case "warning":
380 return { ios: "xmark", android: "close" };
381 case "wrench":
382 return { ios: "wrench", android: "build" };
383 case "zap":
384 return { ios: "bolt", android: "bolt" };
385 }
387​
388// Entering fades only for rows created moments ago: rows remount whenever the
389// list scrolls them back into view, and old rows must not replay an entrance.
390const FRESH_ROW_WINDOW_MS = 3_000;
391function isFreshRow(createdAt: string): boolean {
392 const timestamp = Date.parse(createdAt);
393 return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS;
395​
396// The minimum matches min-h-8 below. Exact sizing is disabled when native
397// accessibility scaling can make the single-line text taller than that minimum.
398const WORK_ROW_HEIGHT = THREAD_WORK_ROW_MIN_HEIGHT;
399const WORK_ROW_GAP = 1; // gap-px
400const WORK_LOG_BOTTOM_MARGIN = 3.5; // mb-1 with the mobile 14px rem
401const WORK_GROUP_MAX_HEIGHT = 256;
402const WORK_GROUP_EDGE_FADE_HEIGHT = 12;
403​
404export const WORK_GROUP_TOGGLE_HEIGHT = THREAD_WORK_ROW_MIN_HEIGHT;
405​
406function workLogRowsHeight(
407 activities: ReadonlyArray<ThreadFeedActivity>,
408 rowHeight = WORK_ROW_HEIGHT,
409): number {
410 return activities.length * rowHeight + Math.max(0, activities.length - 1) * WORK_ROW_GAP;
412​
413export function collapsedWorkLogHeight(
414 activities: ReadonlyArray<ThreadFeedActivity>,
415 continues = false,
416): number {
417 const bottomMargin = continues ? 0 : WORK_LOG_BOTTOM_MARGIN;
418 if (activities.length === 0) {
419 return 0;
420 }
421 if (activities[0]?.projectedItem.item.type === "subagent") {
422 return bottomMargin + WORK_ROW_HEIGHT;
423 }
424 const height = workLogRowsHeight(activities);
425 return (
426 bottomMargin +
427 (activities[0]?.groupedToolDetail ? Math.min(height, WORK_GROUP_MAX_HEIGHT) : height)
428 );
430​
431interface ThreadWorkLogProps {
432 readonly continuesWorkLog?: boolean | undefined;
433 readonly activities: ReadonlyArray<ThreadFeedActivity>;
434 readonly anchorKey: string;
435 readonly environmentId: EnvironmentId;
436 readonly copiedRowId: string | null;
437 readonly expandedRows: Readonly<Record<string, boolean>>;
438 readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
439 readonly scrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
440 readonly iconSubtleColor: ColorValue;
441 /** Feed background, painted as the scroll-edge fade over a long group. */
442 readonly edgeFadeColor: string;
443 readonly themeAppearance: "light" | "dark";
444 readonly onCopyRow: (rowId: string, value: string) => void;
445 readonly onToggleRow: (rowId: string, anchorKey: string) => void;
446 readonly renderImage: MarkdownImageRenderer;
447 readonly renderReasoning: (text: string) => ReactNode;
449​
450export function ThreadWorkLog(props: ThreadWorkLogProps) {
451 const renderRow = useCallback(
452 (row: ThreadFeedActivity) => (
453 <ThreadWorkLogRow
454 key={row.id}
455 row={row}
456 anchorKey={props.anchorKey}
457 copied={props.copiedRowId === row.id}
458 expanded={props.expandedRows[row.id] ?? false}
459 environmentId={props.environmentId}
460 iconSubtleColor={props.iconSubtleColor}
461 onCopyRow={props.onCopyRow}
462 onToggleRow={props.onToggleRow}
463 renderImage={props.renderImage}
464 renderReasoning={props.renderReasoning}
465 themeAppearance={props.themeAppearance}
466 />
467 ),
468 [
469 props.anchorKey,
470 props.copiedRowId,
471 props.expandedRows,
472 props.environmentId,
473 props.iconSubtleColor,
474 props.onCopyRow,
475 props.onToggleRow,
476 props.renderImage,
477 props.renderReasoning,
478 props.themeAppearance,
479 ],
480 );
481​
482 if (props.activities.length === 0) {
483 return null;
484 }
485​
486 if (props.activities[0]?.projectedItem.item.type === "subagent") {
487 return <ThreadSubagentGroup {...props} />;
488 }
489​
490 if (
491 props.activities[0]?.groupedToolDetail &&
492 props.activities.every((row) => row.projectedItem.item.type === "reasoning")
493 ) {
494 return (
495 <ScrollView nestedScrollEnabled className="ml-7 max-h-96 py-1">
496 {props.activities.map((row) => (
497 <View key={row.id}>{props.renderReasoning(row.workEntry.detail ?? "")}</View>
498 ))}
499 </ScrollView>
500 );
501 }
502​
503 return (
504 <WorkLogBlock continues={props.continuesWorkLog}>
505 {props.activities[0]?.groupedToolDetail ? (
506 <ThreadWorkGroupList
507 activities={props.activities}
508 edgeFadeColor={props.edgeFadeColor}
509 expandedRows={props.expandedRows}
510 groupId={props.anchorKey}
511 rowSizing={props.rowSizing}
512 scrollPositions={props.scrollPositions}
513 renderRow={renderRow}
514 />
515 ) : (
516 <WorkLogRows>{props.activities.map(renderRow)}</WorkLogRows>
517 )}
518 </WorkLogBlock>
519 );
521​
522function ThreadWorkGroupList(props: {
523 readonly activities: ReadonlyArray<ThreadFeedActivity>;
524 readonly edgeFadeColor: string;
525 readonly expandedRows: Readonly<Record<string, boolean>>;
526 readonly groupId: string;
527 readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
528 readonly scrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
529 readonly renderRow: (row: ThreadFeedActivity) => ReactNode;
530}) {
531 const estimatedRowsHeight = workLogRowsHeight(
532 props.activities,
533 props.rowSizing.estimatedRowHeight,
534 );
535 const [initialPosition] = useState(() => {
536 const position = props.scrollPositions.get(props.groupId);
537 return props.activities.some((row) => row.id === position?.rowId) ? position : undefined;
538 });
539 const [initialScrollIndex] = useState(() =>
540 resolveThreadWorkGroupInitialScroll(props.activities, initialPosition),
541 );
542 const [restoringPosition, setRestoringPosition] = useState(initialScrollIndex !== undefined);
543 const listRef = useRef<LegendListRef>(null);
544 const loadedRef = useRef(false);
545 const userScrollingRef = useRef(false);
546 const pendingAppendHeightRef = useRef<number | null>(null);
547 const previousContent = useRef({
548 rows: props.activities,
549 height: Math.max(estimatedRowsHeight, initialPosition?.contentHeight ?? 0),
550 expandedRows: props.expandedRows,
551 });
552 const [measuredContent, setMeasuredContent] = useState(() => ({
553 height: Math.max(estimatedRowsHeight, initialPosition?.contentHeight ?? 0),
554 rowCount: props.activities.length,
555 }));
556 const contentHeight = Math.max(
557 1,
558 measuredContent.height +
559 Math.max(0, props.activities.length - measuredContent.rowCount) *
560 (props.rowSizing.estimatedRowHeight + WORK_ROW_GAP),
561 );
562 const height = Math.min(contentHeight, WORK_GROUP_MAX_HEIGHT);
563 const scrollOffset = useSharedValue(initialPosition?.scrollOffset ?? 0);
564 const sharedValues = useMemo(() => ({ scrollOffset }), [scrollOffset]);
565​
566 // Each edge fades only while content continues past it. Scroll offset stays
567 // on the UI thread; only content-size changes update React state.
568 const topFadeStyle = useAnimatedStyle(() => ({
569 opacity: Math.min(1, Math.max(0, scrollOffset.value) / WORK_GROUP_EDGE_FADE_HEIGHT),
570 }));
571 const bottomFadeStyle = useAnimatedStyle(() => ({
572 opacity: Math.min(
573 1,
574 Math.max(0, contentHeight - height - scrollOffset.value) / WORK_GROUP_EDGE_FADE_HEIGHT,
575 ),
576 }));
577 const rememberPosition = useCallback(() => {
578 if (!loadedRef.current) return;
579 const state = listRef.current?.getState();
580 const position = state && resolveWorkGroupScrollAnchor(state);
581 if (!state || !position) return;
582 props.scrollPositions.set(props.groupId, {
583 ...position,
584 contentHeight: state.contentLength,
585 });
586 }, [props.groupId, props.scrollPositions]);
587 const finishPendingAppend = useCallback(() => {
588 const targetHeight = pendingAppendHeightRef.current;
589 const state = listRef.current?.getState();
590 if (
591 targetHeight !== null &&
592 state &&
593 !userScrollingRef.current &&
594 Math.abs(state.scrollLength - targetHeight) <= 1
595 ) {
596 pendingAppendHeightRef.current = null;
597 void listRef.current?.scrollToEnd({ animated: false });
598 }
599 }, []);
600 const onContentSizeChange = useCallback(
601 (nextHeight: number) => {
602 const previous = previousContent.current;
603 const detailsChanged = previous.expandedRows !== props.expandedRows;
604 const followAppend =
605 loadedRef.current &&
606 shouldFollowThreadWorkGroupAppend({
607 previousRows: previous.rows,
608 rows: props.activities,
609 previousContentHeight: previous.height,
610 contentHeight: nextHeight,
611 viewportHeight: Math.min(previous.height, WORK_GROUP_MAX_HEIGHT),
612 scrollOffset: scrollOffset.value,
613 detailsChanged,
614 userScrolling: userScrollingRef.current,
615 });
616 previousContent.current = {
617 rows: props.activities,
618 height: nextHeight,
619 expandedRows: props.expandedRows,
620 };
621 setMeasuredContent((current) =>
622 current.height === nextHeight && current.rowCount === props.activities.length
623 ? current
624 : { height: nextHeight, rowCount: props.activities.length },
625 );
626 // Follow new calls only, never a detail toggle or a growing tool result.
627 if (followAppend) {
628 pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
629 } else if (detailsChanged || userScrollingRef.current || previous.rows !== props.activities) {
630 pendingAppendHeightRef.current = null;
631 } else if (pendingAppendHeightRef.current !== null) {
632 pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
633 }
634 // A short group can grow its viewport on this append. Wait for that
635 // layout before calculating the end offset, rather than jumping twice.
636 finishPendingAppend();
637 rememberPosition();
638 },
639 [props.activities, props.expandedRows, scrollOffset, finishPendingAppend, rememberPosition],
640 );
641 // The native ScrollView reports its content size a frame or more after
642 // LegendList has laid the rows out, so a detail toggle rendered the group
643 // at its old height while the rows below already moved. Read the size
644 // LegendList computes on the JS thread instead; it settles in the same
645 // commit as the row measurement that changed it.
646 const onContentSizeChangeRef = useRef(onContentSizeChange);
647 useLayoutEffect(() => {
648 onContentSizeChangeRef.current = onContentSizeChange;
649 }, [onContentSizeChange]);
650 const subscribeToContentSize = useCallback((list: LegendListRef | null) => {
651 listRef.current = list;
652 if (!list) return;
653 const unsubscribe = list.getState().listen("totalSize", () => {
654 onContentSizeChangeRef.current(list.getState().contentLength);
655 });
656 onContentSizeChangeRef.current(list.getState().contentLength);
657 return unsubscribe;
658 }, []);
659 const getFixedItemSize = useCallback(
660 (row: ThreadFeedActivity, index: number) =>
661 props.expandedRows[row.id] || props.rowSizing.fixedRowHeight === undefined
662 ? undefined
663 : props.rowSizing.fixedRowHeight + (index < props.activities.length - 1 ? WORK_ROW_GAP : 0),
664 [props.activities.length, props.expandedRows, props.rowSizing.fixedRowHeight],
665 );
666 const renderItem = useCallback(
667 ({ item, index }: { item: ThreadFeedActivity; index: number }) => (
668 <View className={index < props.activities.length - 1 ? "pb-px" : undefined}>
669 {props.renderRow(item)}
670 </View>
671 ),
672 [props.activities.length, props.renderRow],
673 );
674​
675 return (
676 <View style={{ height, overflow: "hidden" }}>
677 <AnimatedLegendList
678 ref={subscribeToContentSize}
679 data={props.activities}
680 keyExtractor={workLogRowKey}
681 estimatedItemSize={props.rowSizing.estimatedRowHeight + WORK_ROW_GAP}
682 getFixedItemSize={getFixedItemSize}
683 initialScrollIndex={initialScrollIndex}
684 // Bootstrap overscan is only 50px. An offset inside expanded detail can
685 // otherwise leave its own row unmeasured until after scroll restoration.
686 alwaysRender={
687 restoringPosition && initialPosition ? { keys: [initialPosition.rowId] } : undefined
688 }
689 recycleItems={false}
690 extraData={props.renderRow}
691 renderItem={renderItem}
692 sharedValues={sharedValues}
693 onLayout={finishPendingAppend}
694 onLoad={() => {
695 loadedRef.current = true;
696 setRestoringPosition(false);
697 rememberPosition();
698 }}
699 onScroll={rememberPosition}
700 onScrollBeginDrag={() => {
701 userScrollingRef.current = true;
702 pendingAppendHeightRef.current = null;
703 }}
704 onScrollEndDrag={() => {
705 userScrollingRef.current = false;
706 }}
707 onMomentumScrollBegin={() => {
708 userScrollingRef.current = true;
709 pendingAppendHeightRef.current = null;
710 }}
711 onMomentumScrollEnd={() => {
712 userScrollingRef.current = false;
713 rememberPosition();
714 }}
715 maintainVisibleContentPosition
716 nestedScrollEnabled
717 directionalLockEnabled
718 showsVerticalScrollIndicator
719 scrollsToTop={false}
720 bounces={false}
721 keyboardShouldPersistTaps="handled"
722 style={{ height }}
723 />
724 <Animated.View
725 pointerEvents="none"
726 className="absolute inset-x-0 top-0"
727 style={[{ height: WORK_GROUP_EDGE_FADE_HEIGHT }, topFadeStyle]}
728 >
729 <EdgeFade color={props.edgeFadeColor} direction="down" />
730 </Animated.View>
731 <Animated.View
732 pointerEvents="none"
733 className="absolute inset-x-0 bottom-0"
734 style={[{ height: WORK_GROUP_EDGE_FADE_HEIGHT }, bottomFadeStyle]}
735 >
736 <EdgeFade color={props.edgeFadeColor} direction="up" />
737 </Animated.View>
738 </View>
739 );
741​
742/** A screen-colored gradient painted over the list edge that still has content past it. */
743function EdgeFade(props: { readonly color: string; readonly direction: "up" | "down" }) {
744 const gradientId = `work-group-fade-${useId().replaceAll(":", "")}`;
745 return (
746 <Svg width="100%" height="100%">
747 <Defs>
748 <LinearGradient id={gradientId} x1="0%" x2="0%" y1="0%" y2="100%">
749 <Stop
750 offset={0}
751 stopColor={props.color}
752 stopOpacity={props.direction === "down" ? 1 : 0}
753 />
754 <Stop
755 offset={1}
756 stopColor={props.color}
757 stopOpacity={props.direction === "down" ? 0 : 1}
758 />
759 </LinearGradient>
760 </Defs>
761 <Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
762 </Svg>
763 );
765​
766function workLogRowKey(row: ThreadFeedActivity): string {
767 return row.id;
769​
770const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
771 props: Omit<
772 ThreadWorkLogProps,
773 | "continuesWorkLog"
774 | "activities"
775 | "copiedRowId"
776 | "edgeFadeColor"
777 | "expandedRows"
778 | "rowSizing"
779 | "scrollPositions"
780 > & {
781 readonly row: ThreadFeedActivity;
782 readonly copied: boolean;
783 readonly expanded: boolean;
784 },
785) {
786 const { row, expanded } = props;
787 const failureItem = row.projectedItem.item;
788 if (failureItem.type === "error" && failureItem.status === "failed") {
789 const warning = failureItem.failure.class === "usage_limit";
790 const timestamp = new Date(row.createdAt);
791 const resetAt = failureItem.failure.resetAt;
792 const resetTime = resetAt
793 ? new Date(resetAt).toLocaleString(undefined, {
794 month: "short",
795 day: "numeric",
796 hour: "numeric",
797 minute: "2-digit",
798 })
799 : null;
800 const label = warning
801 ? `Usage limit reached.${resetTime ? ` Retry after ${resetTime}.` : ""}`
802 : row.summary;
803 return (
804 <WorkLogPressable
805 accessibilityLabel={warning ? label : `${row.summary}: ${failureItem.failure.message}`}
806 accessibilityHint="Long press to copy."
807 onLongPress={() => props.onCopyRow(row.id, row.getCopyText())}
808 >
809 <View className="flex-1 py-1">
810 <View className="flex-row items-center gap-1.5">
811 <WorkLogIconSlot>
812 <WorkLogIcon
813 icon="exclamationmark.circle"
814 color={props.iconSubtleColor}
815 colorClassName={warning ? "accent-warning-foreground" : "accent-danger-foreground"}
816 />
817 </WorkLogIconSlot>
818 <Text
819 className={
820 warning
821 ? "min-w-0 flex-1 font-t3-medium text-sm text-warning-foreground"
822 : "min-w-0 flex-1 font-t3-medium text-sm text-adaptive-rose-600-400"
823 }
824 >
825 {label}
826 </Text>
827 {props.copied ? (
828 <Text className="pr-1 font-t3-medium text-3xs text-adaptive-emerald-600-400">
829 Copied
830 </Text>
831 ) : null}
832 <Text
833 accessibilityLabel={timestamp.toLocaleString()}
834 className="shrink-0 text-xs text-foreground-subtle"
835 >
836 {timestamp.toLocaleString(undefined, {
837 month: "short",
838 day: "numeric",
839 hour: "numeric",
840 minute: "2-digit",
841 })}
842 </Text>
843 </View>
844 {!warning ? (
845 <Text selectable className="ml-7 text-sm text-foreground">
846 {failureItem.failure.message}
847 </Text>
848 ) : null}
849 </View>
850 </WorkLogPressable>
851 );
852 }
853 const canExpand = row.canExpand;
854 const reasoning = row.projectedItem.item.type === "reasoning" ? row.projectedItem.item : null;
855 const fullDetail = expanded && !reasoning ? row.getFullDetail() : null;
856 const viewedImagePath = workEntryViewedImagePath(row.workEntry);
857 const toolPresentation = resolveWorkEntryToolPresentation(row.workEntry);
858 const previewText = workEntryRowLabel(row.workEntry);
859 const answerPreview = row.workEntry.questionAnswer
860 ? getQuestionAnswerPreview(row.workEntry.questionAnswer)
861 : null;
862 const accessiblePreview = [previewText, answerPreview].filter(Boolean).join(": ");
863 const displayText = workEntryRowLabel(row.workEntry, expanded);
864 const isSystemNotice = row.projectedItem.item.type === "system_notice";
865 const isUsageLimit =
866 row.projectedItem.item.type === "error" &&
867 row.projectedItem.item.failure.class === "usage_limit" &&
868 row.projectedItem.item.status !== "completed";
869 const iconIsDestructive =
870 !isSystemNotice && !isUsageLimit && (row.icon === "alert" || row.icon === "warning");
871 const failed = row.status === "failure";
872 const toolIcon = row.workEntry.toolIcon ?? row.workEntry.toolSource?.icon;
873 const icon = reasoning ? "brain" : (toolPresentation?.icon ?? workRowSymbolName(row.icon));
874​
875 return (
876 <Animated.View
877 layout={WORK_LOG_LAYOUT_TRANSITION}
878 className="overflow-hidden"
879 {...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
880 >
881 <WorkLogPressable
882 accessibilityRole={canExpand ? "button" : undefined}
883 accessibilityLabel={failed ? `${accessiblePreview}, tool call failed` : accessiblePreview}
884 accessibilityHint={
885 canExpand
886 ? `Double tap to ${expanded ? "hide" : "show"} full details. Long press to copy.`
887 : "Long press to copy."
888 }
889 accessibilityState={canExpand ? { expanded } : undefined}
890 onPress={() => {
891 if (canExpand) {
892 void Haptics.selectionAsync();
893 props.onToggleRow(row.id, props.anchorKey);
894 }
895 }}
896 onLongPress={() => props.onCopyRow(row.id, row.getCopyText())}
897 >
898 {row.live && !expanded ? (
899 <ShimmeringWorkContent
900 environmentId={props.environmentId}
901 icon={icon}
902 iconSubtleColor={props.iconSubtleColor}
903 label={displayText}
904 showIcon
905 themeAppearance={props.themeAppearance}
906 toolIcon={toolIcon}
907 />
908 ) : (
909 <>
910 <WorkLogIconSlot>
911 {toolIcon ? (
912 <ToolActivityIconView
913 environmentId={props.environmentId}
914 icon={toolIcon}
915 fallback={icon}
916 fallbackColor={props.iconSubtleColor}
917 themeAppearance={props.themeAppearance}
918 />
919 ) : (
920 <WorkLogIcon
921 icon={icon}
922 color={props.iconSubtleColor}
923 colorClassName={
924 isUsageLimit
925 ? "accent-warning-foreground"
926 : iconIsDestructive
927 ? "accent-adaptive-rose-600-400"
928 : failed
929 ? "accent-danger-foreground/40"
930 : undefined
931 }
932 />
933 )}
934 </WorkLogIconSlot>
935 <WorkLogLabel
936 tone={isUsageLimit ? "warning" : iconIsDestructive ? "danger" : "default"}
937 >
938 {isSystemNotice ? row.summary : displayText}
939 {answerPreview ? (
940 <Text
941 className={
942 !expanded &&
943 row.workEntry.questionAnswer &&
944 hasQuestionAnswer(row.workEntry.questionAnswer)
945 ? "text-foreground"
946 : "text-foreground-subtle"
947 }
948 >{` ${answerPreview}`}</Text>
949 ) : null}
950 </WorkLogLabel>
951 </>
952 )}
953​
954 <View className="shrink-0 flex-row items-center gap-px">
955 {props.copied ? (
956 <Text className="pr-1 font-t3-medium text-3xs text-adaptive-emerald-600-400">
957 Copied
958 </Text>
959 ) : null}
960 {failed && toolIcon !== undefined ? (
961 <View
962 className="h-4 w-4 items-center justify-center"
963 accessibilityElementsHidden
964 importantForAccessibility="no-hide-descendants"
965 >
966 <SymbolView
967 name="xmark"
968 size={11}
969 tintColorClassName="accent-danger-foreground/40"
970 type="monochrome"
971 />
972 </View>
973 ) : null}
974 <View className="h-4 w-4 items-center justify-center">
975 {canExpand ? (
976 <ThreadDisclosureChevron
977 expanded={expanded}
978 collapsedDirection="down"
979 size={11}
980 tintColor={props.iconSubtleColor}
981 />
982 ) : null}
983 </View>
984 </View>
985 </WorkLogPressable>
986​
987 {expanded && (reasoning || fullDetail || viewedImagePath || row.workEntry.questionAnswer) ? (
988 <Animated.View
989 entering={WORK_LOG_DETAIL_ENTER_TRANSITION}
990 exiting={WORK_LOG_DETAIL_EXIT_TRANSITION}
991 layout={WORK_LOG_LAYOUT_TRANSITION}
992 className={reasoning ? "ml-7 py-1" : "ml-7 border-l border-border pb-1 pl-3 pt-0.5"}
993 >
994 {row.workEntry.questionAnswer ? (
995 <QuestionAnswerHistory
996 environmentId={props.environmentId}
997 answer={row.workEntry.questionAnswer}
998 />
999 ) : null}
1000 {viewedImagePath ? (
1001 <View className="pb-1.5">
1002 {props.renderImage({ href: viewedImagePath, alt: null, title: null })}
1003 </View>
1004 ) : null}
1005 <ScrollView
1006 nestedScrollEnabled
1007 directionalLockEnabled
1008 showsVerticalScrollIndicator
1009 className="max-h-60"
1010 contentContainerStyle={{ paddingRight: 8 }}
1012 {reasoning ? (
1013 props.renderReasoning(reasoning.text)
1014 ) : (
1015 <Text selectable className="font-mono text-2xs leading-normal text-foreground-muted">
1016 {fullDetail}
1017 </Text>
1018 )}
1019 </ScrollView>
1020 </Animated.View>
1021 ) : null}
1022 </Animated.View>
1023 );
1024});
1025​
1026export function ThreadWorkGroupToggle(props: {
1027 readonly environmentId: EnvironmentId;
1028 readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
1029 readonly expanded: boolean;
1030 readonly hiddenCount: number;
1031 readonly iconSubtleColor: import("react-native").ColorValue;
1032 readonly summary: string;
1033 readonly summaryKind: ToolGroupSummaryKind;
1034 readonly summaryToolIcon?: "browser" | "device" | "t3-code" | "pull-request" | "brain";
1035 readonly themeAppearance: "light" | "dark";
1036 readonly toolSurface?: import("@t3tools/contracts").ToolActivitySurface;
1037 readonly toolIcon?: ToolActivityIcon;
1038 readonly hasFailure: boolean;
1039 readonly shimmer: boolean;
1040 readonly onToggle: () => void;
1041}) {
1042 const accessibilityLabel = props.hasFailure
1043 ? `${props.summary}, tool call failed`
1044 : props.summary;
1045 const icon =
1046 props.summaryToolIcon ??
1047 (props.toolSurface
1048 ? workRowSymbolName(props.toolSurface)
1049 : toolGroupSummarySymbolName(props.summaryKind));
1050​
1051 return (
1052 <WorkLogBlock layout="group-header">
1053 <WorkLogPressable
1054 accessibilityRole="button"
1055 accessibilityState={{ expanded: props.expanded }}
1056 accessibilityLabel={accessibilityLabel}
1057 accessibilityHint={`Double tap to ${props.expanded ? "hide" : "show"} ${props.hiddenCount} tool ${props.hiddenCount === 1 ? "call" : "calls"}.`}
1058 onPress={() => {
1059 void Haptics.selectionAsync();
1060 props.onToggle();
1061 }}
1062 rowSizing={props.rowSizing}
1064 {props.shimmer ? (
1065 <ShimmeringWorkContent
1066 key={props.rowSizing.textSizeKey}
1067 environmentId={props.environmentId}
1068 icon={icon}
1069 iconSubtleColor={props.iconSubtleColor}
1070 label={props.summary}
1071 showIcon
1072 themeAppearance={props.themeAppearance}
1073 toolIcon={props.toolIcon}
1074 />
1075 ) : (
1076 <>
1077 <WorkLogIconSlot>
1078 <ToolActivityIconView
1079 environmentId={props.environmentId}
1080 icon={props.toolIcon}
1081 fallback={icon}
1082 fallbackColor={props.iconSubtleColor}
1083 themeAppearance={props.themeAppearance}
1084 />
1085 </WorkLogIconSlot>
1086 <WorkLogLabel key={props.rowSizing.textSizeKey}>{props.summary}</WorkLogLabel>
1087 </>
1088 )}
1089 <ThreadDisclosureChevron
1090 expanded={props.expanded}
1091 collapsedDirection="down"
1092 size={11}
1093 tintColor={props.iconSubtleColor}
1094 />
1095 </WorkLogPressable>
1096 </WorkLogBlock>
1097 );
1099​
1100/**
1101 * A batch of spawned subagents. The status line updates in place as members
1102 * report progress; expanding lists each member. Text nodes carry keys tied to
1103 * the row identity only, so a progress tick re-renders the labels without
1104 * remounting the card (see the batch key in appendActivityGroupRows).
1105 */
1106export const ThreadAgentSpawnCard = memo(function ThreadAgentSpawnCard(props: {
1107 readonly summary: AgentSpawnSummary;
1108 readonly expanded: boolean;
1109 readonly iconSubtleColor: ColorValue;
1110 readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
1111 readonly onToggle: () => void;
1112 readonly onCopy: () => void;
1113}) {
1114 const { summary, expanded } = props;
1115 const working = summary.tone === "working";
1116 const memberCount = summary.members.length;
1117 const canExpand = memberCount > 0;
1118 return (
1119 <Animated.View layout={WORK_LOG_LAYOUT_TRANSITION} className="-mx-1 mb-1 px-1">
1120 <Pressable
1121 accessibilityRole={canExpand ? "button" : undefined}
1122 accessibilityState={canExpand ? { expanded } : undefined}
1123 accessibilityLabel={`${summary.title}, ${summary.status}`}
1124 accessibilityHint={
1125 canExpand
1126 ? `Double tap to ${expanded ? "hide" : "show"} ${memberCount} ${memberCount === 1 ? "subagent" : "subagents"}. Long press to copy.`
1127 : "Long press to copy."
1129 hitSlop={4}
1130 onPress={() => {
1131 if (!canExpand) return;
1132 void Haptics.selectionAsync();
1133 props.onToggle();
1134 }}
1135 onLongPress={props.onCopy}
1136 className="rounded-xl border border-border-subtle bg-card px-2.5 py-2 active:bg-subtle"
1138 <View className="flex-row items-center gap-2">
1139 <View className="h-6 w-6 shrink-0 items-center justify-center">
1140 <SymbolView
1141 name={{ ios: "sparkles", android: "auto_awesome" }}
1142 size={14}
1143 weight="medium"
1144 tintColor={props.iconSubtleColor}
1145 type="monochrome"
1146 />
1147 </View>
1148 <View className="min-w-0 flex-1 gap-0.5">
1149 <Text
1150 key={props.rowSizing.textSizeKey}
1151 className="font-t3-medium text-sm text-foreground"
1152 numberOfLines={1}
1154 {summary.title}
1155 </Text>
1156 <View className="flex-row items-center gap-1.5">
1157 <SubagentStatusDot tone={summary.tone} />
1158 {working ? (
1159 <ShimmeringWorkContent
1160 key={props.rowSizing.textSizeKey}
1161 compact
1162 icon="brain"
1163 iconSubtleColor={props.iconSubtleColor}
1164 label={summary.status}
1165 showIcon={false}
1166 />
1167 ) : (
1168 <Text className="min-w-0 flex-1 text-xs text-foreground-muted" numberOfLines={1}>
1169 {summary.status}
1170 </Text>
1171 )}
1172 </View>
1173 </View>
1174 {canExpand ? (
1175 <ThreadDisclosureChevron
1176 expanded={expanded}
1177 collapsedDirection="down"
1178 size={11}
1179 tintColor={props.iconSubtleColor}
1180 />
1181 ) : null}
1182 </View>
1183 {expanded && canExpand ? (
1184 <Animated.View
1185 entering={WORK_LOG_DETAIL_ENTER_TRANSITION}
1186 exiting={WORK_LOG_DETAIL_EXIT_TRANSITION}
1187 layout={WORK_LOG_LAYOUT_TRANSITION}
1188 className="ml-8 mt-1.5 gap-1.5 border-l border-border pl-3"
1190 {summary.members.map((member) => (
1191 <View key={member.title} className="gap-px">
1192 <View className="flex-row items-center gap-1.5">
1193 <SubagentStatusDot tone={member.tone} />
1194 <Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
1195 {member.title}
1196 </Text>
1197 <Text className="shrink-0 text-2xs text-foreground-muted">{member.status}</Text>
1198 </View>
1199 {member.detail ? (
1200 <Text
1201 selectable
1202 className="pl-3 font-mono text-2xs leading-normal text-foreground-muted"
1203 numberOfLines={expanded ? 6 : 1}
1205 {member.detail}
1206 </Text>
1207 ) : null}
1208 </View>
1209 ))}
1210 </Animated.View>
1211 ) : null}
1212 </Pressable>
1213 </Animated.View>
1214 );
1215});
1216​
1217export function ThreadThinkingRow(props: {
1218 readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
1219 readonly iconSubtleColor: ColorValue;
1220}) {
1221 return (
1222 <View
1223 accessible
1224 accessibilityLabel="Thinking"
1225 className="-mx-1 min-h-8 flex-row items-center px-1.5 py-0"
1226 style={{ minHeight: props.rowSizing.estimatedRowHeight }}
1228 <ShimmeringWorkContent
1229 key={props.rowSizing.textSizeKey}
1230 icon="brain"
1231 iconSubtleColor={props.iconSubtleColor}
1232 label="Thinking"
1233 showIcon
1234 />
1235 </View>
1236 );
1238​
1239function ToolActivityIconView(props: {
1240 readonly environmentId: EnvironmentId;
1241 readonly icon?: ToolActivityIcon;
1242 readonly fallback: WorkContentIcon;
1243 readonly fallbackColor: ColorValue;
1244 readonly themeAppearance: "light" | "dark";
1245}) {
1246 if (!props.icon) {
1247 return <WorkLogIcon icon={props.fallback} color={props.fallbackColor} />;
1249 if (props.icon._tag === "website") {
1250 const source = toolActivityFaviconUrl(props.icon, props.themeAppearance, 32);
1251 return source ? (
1252 <ToolActivityImage
1253 key={source}
1254 source={source}
1255 fallback={props.fallback}
1256 color={props.fallbackColor}
1257 themeAppearance={props.themeAppearance}
1258 />
1259 ) : (
1260 <WorkLogIcon icon={props.fallback} color={props.fallbackColor} />
1261 );
1263 if (props.icon._tag === "themed-logo") {
1264 const source =
1265 props.themeAppearance === "dark"
1266 ? (props.icon.logoUrlDark ?? props.icon.logoUrl)
1267 : props.icon.logoUrl;
1268 return (
1269 <ToolActivityImage
1270 key={source}
1271 source={source}
1272 fallback={props.fallback}
1273 color={props.fallbackColor}
1274 themeAppearance={props.themeAppearance}
1275 />
1276 );
1278 return (
1279 <NativeAppToolActivityIcon
1280 environmentId={props.environmentId}
1281 app={props.icon.app}
1282 fallback={props.fallback}
1283 color={props.fallbackColor}
1284 themeAppearance={props.themeAppearance}
1285 />
1286 );
1288​
1289function NativeAppToolActivityIcon(props: {
1290 readonly environmentId: EnvironmentId;
1291 readonly app: Extract<ToolActivityIcon, { readonly _tag: "native-app" }>["app"];
1292 readonly fallback: WorkContentIcon;
1293 readonly color: ColorValue;
1294 readonly themeAppearance: "light" | "dark";
1295}) {
1296 const source = useAssetUrl(props.environmentId, {
1297 _tag: "native-app-icon",
1298 app: props.app,
1299 });
1300 return source ? (
1301 <ToolActivityImage
1302 key={source}
1303 source={source}
1304 fallback={props.fallback}
1305 color={props.color}
1306 themeAppearance={props.themeAppearance}
1307 />
1308 ) : (
1309 <WorkLogIcon icon={props.fallback} color={props.color} />
1310 );
1312​
1313function ToolActivityImage(props: {
1314 readonly source: string;
1315 readonly fallback: WorkContentIcon;
1316 readonly color: ColorValue;
1317 readonly themeAppearance: "light" | "dark";
1318}) {
1319 const [loaded, setLoaded] = useState(false);
1320 const [failed, setFailed] = useState(false);
1321 return (
1322 <View className="h-4 w-4 items-center justify-center overflow-hidden rounded-[3px] bg-background">
1323 {!loaded || failed ? <WorkLogIcon icon={props.fallback} color={props.color} /> : null}
1324 {!failed ? (
1325 <View
1326 style={[
1327 StyleSheet.absoluteFill,
1328 props.themeAppearance === "light" ? { filter: [{ brightness: 0.6 }] } : undefined,
1329 ]}
1331 <Image
1332 source={props.source}
1333 cachePolicy="memory-disk"
1334 contentFit="contain"
1335 style={[StyleSheet.absoluteFill, { opacity: loaded ? 0.7 : 0 }]}
1336 onLoad={() => setLoaded(true)}
1337 onError={() => setFailed(true)}
1338 />
1339 </View>
1340 ) : null}
1341 </View>
1342 );
1344​
1345function toolGroupSummarySymbolName(kind: ToolGroupSummaryKind): AppSymbolName {
1346 switch (kind) {
1347 case "pull-request":
1348 case "link-pr":
1349 case "unlink-pr":
1350 case "list-prs":
1351 return "arrow.triangle.pull";
1352 case "read":
1353 return { ios: "eye", android: "visibility" };
1354 case "edit":
1355 return { ios: "square.and.pencil", android: "edit" };
1356 case "thread-create":
1357 return { ios: "bubble.left", android: "chat" };
1358 case "command":
1359 return { ios: "terminal", android: "terminal" };
1360 case "device":
1361 return { ios: "iphone", android: "smartphone" };
1362 case "browser":
1363 case "search":
1364 return { ios: "globe", android: "public" };
1365 case "code-search":
1366 return "magnifyingglass";
1367 case "other":
1368 return { ios: "wrench", android: "build" };
1369 case "reasoning":
1370 return { ios: "brain", android: "psychology" };
1371 case "agent-tool":
1372 return { ios: "sparkles", android: "auto_awesome" };
1373 case "tone-tool":
1374 return { ios: "bolt", android: "bolt" };
1375 case "dynamic-tool":
1376 case "update":
1377 case "mixed":
1378 return { ios: "hammer", android: "construction" };