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

thread-work-log.tsx

1,242 lines42.9 KB

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