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

thread-work-log.tsx

1,256 lines43.5 KB

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