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