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

thread-work-log.tsx

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