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

thread-work-log.tsx

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