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

thread-work-log.tsx

1,290 lines44.7 KB

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