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