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

thread-work-log.tsx

1,055 lines36.4 KB

1import * as Haptics from "expo-haptics";
2import { Image } from "expo-image";
3import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
4import { MaskedView } from "@expo/ui/community/masked-view";
5import type { LegendListRef } from "@legendapp/list/react-native";
6import { AnimatedLegendList } from "@legendapp/list/reanimated";
7import { useIsFocused } from "@react-navigation/native";
8import {
9 memo,
10 useCallback,
11 useEffect,
12 useId,
13 useLayoutEffect,
14 useMemo,
15 useRef,
16 useState,
17 type ComponentProps,
18 type ReactNode,
19} from "react";
20import {
21 AccessibilityInfo,
22 AppState,
23 type ColorValue,
24 Pressable,
25 ScrollView,
26 StyleSheet,
27 View,
28} from "react-native";
29import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
30import type { EnvironmentId, ToolActivityIcon } from "@t3tools/contracts";
31import { toolActivityFaviconUrl } from "@t3tools/shared/favicon";
32​
33import { AppText as Text } from "../../components/AppText";
34import { T3Wordmark } from "../../components/T3Wordmark";
35import { cn } from "../../lib/cn";
36import { THREAD_WORK_ROW_MIN_HEIGHT, type deriveThreadWorkLogSizing } from "../../lib/layout";
37import 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 highlighted?: boolean;
80}) {
81 if (props.icon === "t3-code") {
82 return (
83 <T3Wordmark
84 height={10}
85 {...(props.highlighted ? { colorClassName: "accent-foreground" } : { color: props.color })}
86 />
87 );
88 }
89 return (
90 <SymbolView
91 name={props.icon === "browser" ? { ios: "globe", android: "public" } : props.icon}
92 size={14}
93 weight="medium"
94 {...(props.highlighted
95 ? { tintColorClassName: "accent-foreground" }
96 : { tintColor: props.color })}
97 type="monochrome"
98 />
99 );
101​
102export function ThreadDisclosureChevron(props: {
103 readonly expanded: boolean;
104 readonly collapsedDirection: "right" | "down";
105 readonly size: number;
106 readonly tintColor: ColorValue;
107}) {
108 const expandedAngle = props.collapsedDirection === "right" ? 90 : 180;
109 const rotation = useSharedValue(props.expanded ? expandedAngle : 0);
110​
111 useLayoutEffect(() => {
112 rotation.value = withTiming(props.expanded ? expandedAngle : 0, {
113 duration: THREAD_DISCLOSURE_TRANSITION_MS,
114 reduceMotion: ReduceMotion.System,
115 });
116 }, [expandedAngle, props.expanded, rotation]);
117​
118 const rotationStyle = useAnimatedStyle(() => ({
119 transform: [{ rotate: `${rotation.value}deg` }],
120 }));
121​
122 return (
123 <Animated.View
124 accessible={false}
125 accessibilityElementsHidden
126 importantForAccessibility="no-hide-descendants"
127 pointerEvents="none"
128 style={[{ width: props.size, height: props.size }, rotationStyle]}
129 >
130 <SymbolView
131 name={props.collapsedDirection === "right" ? "chevron.right" : "chevron.down"}
132 size={props.size}
133 tintColor={props.tintColor}
134 type="monochrome"
135 />
136 </Animated.View>
137 );
139​
140function ShimmerWorkContent(props: {
141 readonly environmentId?: EnvironmentId;
142 readonly highlighted: boolean;
143 readonly icon: WorkContentIcon;
144 readonly iconSubtleColor: ColorValue;
145 readonly label: string;
146 readonly onTextLayout?: ComponentProps<typeof Text>["onTextLayout"];
147 readonly showIcon: boolean;
148 readonly themeAppearance?: "light" | "dark";
149 readonly toolIcon?: ToolActivityIcon;
150}) {
151 return (
152 <View className="flex-row items-center gap-1.5">
153 <View className="h-6 w-6 shrink-0 items-center justify-center">
154 {props.showIcon && props.toolIcon && props.environmentId ? (
155 <ToolActivityIconView
156 environmentId={props.environmentId}
157 icon={props.toolIcon}
158 fallback={props.icon}
159 fallbackColor={props.iconSubtleColor}
160 themeAppearance={props.themeAppearance ?? "light"}
161 />
162 ) : props.showIcon ? (
163 <WorkLogIcon
164 icon={props.icon}
165 color={props.iconSubtleColor}
166 highlighted={props.highlighted}
167 />
168 ) : null}
169 </View>
170 <Text
171 className={cn(
172 "min-w-0 shrink text-sm",
173 props.highlighted ? "text-foreground" : "text-foreground-muted",
174 )}
175 numberOfLines={1}
176 onTextLayout={props.onTextLayout}
177 >
178 {props.label}
179 </Text>
180 </View>
181 );
183​
184export function ShimmeringWorkContent(props: {
185 readonly environmentId?: EnvironmentId;
186 readonly icon: WorkContentIcon;
187 readonly iconSubtleColor: ColorValue;
188 readonly label: string;
189 readonly showIcon: boolean;
190 readonly themeAppearance?: "light" | "dark";
191 readonly toolIcon?: ToolActivityIcon;
192}) {
193 const [availableWidth, setAvailableWidth] = useState(0);
194 const [textWidth, setTextWidth] = useState(0);
195 const [appIsActive, setAppIsActive] = useState(AppState.currentState === "active");
196 const [reducedMotion, setReducedMotion] = useState(true);
197 const screenIsFocused = useIsFocused();
198 const progress = useSharedValue(0);
199 const gradientId = `work-shimmer-${useId().replaceAll(":", "")}`;
200 const contentWidth = Math.min(availableWidth, SHIMMER_ICON_AND_GAP_WIDTH + Math.ceil(textWidth));
201​
202 useEffect(() => {
203 const subscription = AppState.addEventListener("change", (state) => {
204 setAppIsActive(state === "active");
205 });
206 return () => subscription.remove();
207 }, []);
208​
209 useEffect(() => {
210 void AccessibilityInfo.isReduceMotionEnabled().then(setReducedMotion);
211 const subscription = AccessibilityInfo.addEventListener(
212 "reduceMotionChanged",
213 setReducedMotion,
214 );
215 return () => subscription.remove();
216 }, []);
217​
218 useEffect(() => {
219 cancelAnimation(progress);
220 progress.value = 0;
221 if (contentWidth <= 0 || reducedMotion || !appIsActive || !screenIsFocused) return;
222​
223 progress.value = withRepeat(
224 withSequence(
225 withTiming(1, {
226 duration: SHIMMER_SWEEP_MS,
227 easing: Easing.linear,
228 reduceMotion: ReduceMotion.Never,
229 }),
230 withDelay(
231 SHIMMER_PAUSE_MS,
232 withTiming(0, { duration: 0, reduceMotion: ReduceMotion.Never }),
233 ),
234 ),
235 -1,
236 false,
237 undefined,
238 ReduceMotion.Never,
239 );
240 return () => cancelAnimation(progress);
241 }, [appIsActive, contentWidth, progress, reducedMotion, screenIsFocused]);
242​
243 const sweepStyle = useAnimatedStyle(() => ({
244 transform: [{ translateX: -SHIMMER_WIDTH + progress.value * (contentWidth + SHIMMER_WIDTH) }],
245 }));
246 const counterSweepStyle = useAnimatedStyle(() => ({
247 transform: [{ translateX: SHIMMER_WIDTH - progress.value * (contentWidth + SHIMMER_WIDTH) }],
248 }));
249​
250 return (
251 <View
252 className="min-w-0 flex-1 overflow-hidden"
253 onLayout={(event) => setAvailableWidth(event.nativeEvent.layout.width)}
254 >
255 <ShimmerWorkContent
256 environmentId={props.environmentId}
257 highlighted={false}
258 icon={props.icon}
259 iconSubtleColor={props.iconSubtleColor}
260 label={props.label}
261 showIcon={props.showIcon}
262 themeAppearance={props.themeAppearance}
263 toolIcon={props.toolIcon}
264 onTextLayout={(event) => setTextWidth(event.nativeEvent.lines[0]?.width ?? 0)}
265 />
266 {!reducedMotion && appIsActive && screenIsFocused && contentWidth > 0 ? (
267 <Animated.View
268 className="absolute inset-y-0 left-0 overflow-hidden"
269 pointerEvents="none"
270 accessible={false}
271 accessibilityElementsHidden
272 importantForAccessibility="no-hide-descendants"
273 style={[{ width: SHIMMER_WIDTH }, sweepStyle]}
274 >
275 <MaskedView
276 style={StyleSheet.absoluteFill}
277 maskElement={
278 <Svg width="100%" height="100%">
279 <Defs>
280 <LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
281 <Stop offset="0" stopColor="white" stopOpacity={0} />
282 <Stop offset="0.15" stopColor="white" stopOpacity={0.12} />
283 <Stop offset="0.35" stopColor="white" stopOpacity={0.55} />
284 <Stop offset="0.5" stopColor="white" stopOpacity={1} />
285 <Stop offset="0.65" stopColor="white" stopOpacity={0.55} />
286 <Stop offset="0.85" stopColor="white" stopOpacity={0.12} />
287 <Stop offset="1" stopColor="white" stopOpacity={0} />
288 </LinearGradient>
289 </Defs>
290 <Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
291 </Svg>
292 }
293 >
294 <Animated.View style={[{ width: availableWidth }, counterSweepStyle]}>
295 <ShimmerWorkContent
296 environmentId={props.environmentId}
297 highlighted
298 icon={props.icon}
299 iconSubtleColor={props.iconSubtleColor}
300 label={props.label}
301 showIcon={props.showIcon}
302 themeAppearance={props.themeAppearance}
303 toolIcon={props.toolIcon}
304 />
305 </Animated.View>
306 </MaskedView>
307 </Animated.View>
308 ) : null}
309 </View>
310 );
312​
313function stripShellWrapper(value: string): string {
314 const trimmed = value.trim();
315 const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
316 return (match?.[1] ?? trimmed).trim();
318​
319function compactActivityDetail(detail: string | null): string | null {
320 if (!detail) {
321 return null;
322 }
323​
324 const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
325 return cleaned.length > 0 ? cleaned : null;
327​
328function workRowSymbolName(icon: ThreadFeedActivity["icon"]): AppSymbolName {
329 switch (icon) {
330 case "agent":
331 return { ios: "sparkles", android: "auto_awesome" };
332 case "alert":
333 return { ios: "exclamationmark.triangle", android: "error" };
334 case "browser":
335 return { ios: "safari", android: "public" };
336 case "check":
337 return { ios: "checkmark", android: "check" };
338 case "command":
339 return { ios: "terminal", android: "terminal" };
340 case "computer":
341 return { ios: "desktopcomputer", android: "desktop_windows" };
342 case "edit":
343 return { ios: "square.and.pencil", android: "edit" };
344 case "eye":
345 return { ios: "eye", android: "visibility" };
346 case "globe":
347 return { ios: "globe", android: "public" };
348 case "hammer":
349 return { ios: "hammer", android: "construction" };
350 case "message":
351 return { ios: "bubble.left", android: "chat_bubble" };
352 case "warning":
353 return { ios: "xmark", android: "close" };
354 case "wrench":
355 return { ios: "wrench", android: "build" };
356 case "zap":
357 return { ios: "bolt", android: "bolt" };
358 }
360​
361// Entering fades only for rows created moments ago: rows remount whenever the
362// list scrolls them back into view, and old rows must not replay an entrance.
363const FRESH_ROW_WINDOW_MS = 3_000;
364function isFreshRow(createdAt: string): boolean {
365 const timestamp = Date.parse(createdAt);
366 return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS;
368​
369// The minimum matches min-h-8 below. Exact sizing is disabled when native
370// accessibility scaling can make the single-line text taller than that minimum.
371const WORK_ROW_HEIGHT = THREAD_WORK_ROW_MIN_HEIGHT;
372const WORK_ROW_GAP = 1; // gap-px
373const WORK_LOG_BOTTOM_MARGIN = 3.5; // mb-1 with the mobile 14px rem
374const WORK_GROUP_MAX_HEIGHT = 256;
375const WORK_GROUP_EDGE_FADE_HEIGHT = 12;
376​
377export const WORK_GROUP_TOGGLE_HEIGHT = THREAD_WORK_ROW_MIN_HEIGHT;
378​
379function workLogRowsHeight(
380 activities: ReadonlyArray<ThreadFeedActivity>,
381 rowHeight = WORK_ROW_HEIGHT,
382): number {
383 return activities.length * rowHeight + Math.max(0, activities.length - 1) * WORK_ROW_GAP;
385​
386export function collapsedWorkLogHeight(activities: ReadonlyArray<ThreadFeedActivity>): number {
387 if (activities.length === 0) {
388 return 0;
389 }
390 const height = workLogRowsHeight(activities);
391 return (
392 WORK_LOG_BOTTOM_MARGIN +
393 (activities[0]?.groupedToolDetail ? Math.min(height, WORK_GROUP_MAX_HEIGHT) : height)
394 );
396​
397interface ThreadWorkLogProps {
398 readonly activities: ReadonlyArray<ThreadFeedActivity>;
399 readonly anchorKey: string;
400 readonly environmentId: EnvironmentId;
401 readonly copiedRowId: string | null;
402 readonly expandedRows: Readonly<Record<string, boolean>>;
403 readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
404 readonly scrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
405 readonly iconSubtleColor: ColorValue;
406 readonly themeAppearance: "light" | "dark";
407 readonly onCopyRow: (rowId: string, value: string) => void;
408 readonly onToggleRow: (rowId: string, anchorKey: string) => void;
409 readonly renderImage: MarkdownImageRenderer;
411​
412export function ThreadWorkLog(props: ThreadWorkLogProps) {
413 const renderRow = useCallback(
414 (row: ThreadFeedActivity) => (
415 <ThreadWorkLogRow
416 key={row.id}
417 row={row}
418 anchorKey={props.anchorKey}
419 copied={props.copiedRowId === row.id}
420 expanded={props.expandedRows[row.id] ?? false}
421 environmentId={props.environmentId}
422 iconSubtleColor={props.iconSubtleColor}
423 onCopyRow={props.onCopyRow}
424 onToggleRow={props.onToggleRow}
425 renderImage={props.renderImage}
426 themeAppearance={props.themeAppearance}
427 />
428 ),
429 [
430 props.anchorKey,
431 props.copiedRowId,
432 props.expandedRows,
433 props.environmentId,
434 props.iconSubtleColor,
435 props.onCopyRow,
436 props.onToggleRow,
437 props.renderImage,
438 props.themeAppearance,
439 ],
440 );
441​
442 if (props.activities.length === 0) {
443 return null;
444 }
445​
446 return (
447 <View className="-mx-1 mb-1 px-1 py-0">
448 {props.activities[0]?.groupedToolDetail ? (
449 <ThreadWorkGroupList
450 activities={props.activities}
451 expandedRows={props.expandedRows}
452 groupId={props.anchorKey}
453 rowSizing={props.rowSizing}
454 scrollPositions={props.scrollPositions}
455 renderRow={renderRow}
456 />
457 ) : (
458 <View className="gap-px">{props.activities.map(renderRow)}</View>
459 )}
460 </View>
461 );
463​
464function ThreadWorkGroupList(props: {
465 readonly activities: ReadonlyArray<ThreadFeedActivity>;
466 readonly expandedRows: Readonly<Record<string, boolean>>;
467 readonly groupId: string;
468 readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
469 readonly scrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
470 readonly renderRow: (row: ThreadFeedActivity) => ReactNode;
471}) {
472 const estimatedRowsHeight = workLogRowsHeight(
473 props.activities,
474 props.rowSizing.estimatedRowHeight,
475 );
476 const [initialPosition] = useState(() => {
477 const position = props.scrollPositions.get(props.groupId);
478 return props.activities.some((row) => row.id === position?.rowId) ? position : undefined;
479 });
480 const [initialScrollIndex] = useState(() =>
481 resolveThreadWorkGroupInitialScroll(props.activities, initialPosition),
482 );
483 const [restoringPosition, setRestoringPosition] = useState(initialScrollIndex !== undefined);
484 const listRef = useRef<LegendListRef>(null);
485 const loadedRef = useRef(false);
486 const userScrollingRef = useRef(false);
487 const pendingAppendHeightRef = useRef<number | null>(null);
488 const previousContent = useRef({
489 rows: props.activities,
490 height: Math.max(estimatedRowsHeight, initialPosition?.contentHeight ?? 0),
491 expandedRows: props.expandedRows,
492 });
493 const [measuredContent, setMeasuredContent] = useState(() => ({
494 height: Math.max(estimatedRowsHeight, initialPosition?.contentHeight ?? 0),
495 rowCount: props.activities.length,
496 }));
497 const contentHeight = Math.max(
498 1,
499 measuredContent.height +
500 Math.max(0, props.activities.length - measuredContent.rowCount) *
501 (props.rowSizing.estimatedRowHeight + WORK_ROW_GAP),
502 );
503 const height = Math.min(contentHeight, WORK_GROUP_MAX_HEIGHT);
504 const scrollOffset = useSharedValue(initialPosition?.scrollOffset ?? 0);
505 const sharedValues = useMemo(() => ({ scrollOffset }), [scrollOffset]);
506 const gradientId = `work-group-fade-${useId().replaceAll(":", "")}`;
507 const fadeFraction = WORK_GROUP_EDGE_FADE_HEIGHT / height;
508​
509 // Opaque covers remove each edge fade at the scroll boundary. Scroll offset
510 // stays on the UI thread; only content-size changes update React state.
511 const topCoverStyle = useAnimatedStyle(() => ({
512 opacity: 1 - Math.min(1, Math.max(0, scrollOffset.value) / WORK_GROUP_EDGE_FADE_HEIGHT),
513 }));
514 const bottomCoverStyle = useAnimatedStyle(() => ({
515 opacity:
516 1 -
517 Math.min(
518 1,
519 Math.max(0, contentHeight - height - scrollOffset.value) / WORK_GROUP_EDGE_FADE_HEIGHT,
520 ),
521 }));
522 const rememberPosition = useCallback(() => {
523 if (!loadedRef.current) return;
524 const state = listRef.current?.getState();
525 const position = state && resolveWorkGroupScrollAnchor(state);
526 if (!state || !position) return;
527 props.scrollPositions.set(props.groupId, {
528 ...position,
529 contentHeight: state.contentLength,
530 });
531 }, [props.groupId, props.scrollPositions]);
532 const finishPendingAppend = useCallback(() => {
533 const targetHeight = pendingAppendHeightRef.current;
534 const state = listRef.current?.getState();
535 if (
536 targetHeight !== null &&
537 state &&
538 !userScrollingRef.current &&
539 Math.abs(state.scrollLength - targetHeight) <= 1
540 ) {
541 pendingAppendHeightRef.current = null;
542 void listRef.current?.scrollToEnd({ animated: false });
543 }
544 }, []);
545 const onContentSizeChange = useCallback(
546 (_width: number, nextHeight: number) => {
547 const previous = previousContent.current;
548 const detailsChanged = previous.expandedRows !== props.expandedRows;
549 const followAppend =
550 loadedRef.current &&
551 shouldFollowThreadWorkGroupAppend({
552 previousRows: previous.rows,
553 rows: props.activities,
554 previousContentHeight: previous.height,
555 contentHeight: nextHeight,
556 viewportHeight: Math.min(previous.height, WORK_GROUP_MAX_HEIGHT),
557 scrollOffset: scrollOffset.value,
558 detailsChanged,
559 userScrolling: userScrollingRef.current,
560 });
561 previousContent.current = {
562 rows: props.activities,
563 height: nextHeight,
564 expandedRows: props.expandedRows,
565 };
566 setMeasuredContent((current) =>
567 current.height === nextHeight && current.rowCount === props.activities.length
568 ? current
569 : { height: nextHeight, rowCount: props.activities.length },
570 );
571 // Follow new calls only, never a detail toggle or a growing tool result.
572 if (followAppend) {
573 pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
574 } else if (detailsChanged || userScrollingRef.current || previous.rows !== props.activities) {
575 pendingAppendHeightRef.current = null;
576 } else if (pendingAppendHeightRef.current !== null) {
577 pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
578 }
579 // A short group can grow its viewport on this append. Wait for that
580 // layout before calculating the end offset, rather than jumping twice.
581 finishPendingAppend();
582 rememberPosition();
583 },
584 [props.activities, props.expandedRows, scrollOffset, finishPendingAppend, rememberPosition],
585 );
586 const getFixedItemSize = useCallback(
587 (row: ThreadFeedActivity, index: number) =>
588 props.expandedRows[row.id] || props.rowSizing.fixedRowHeight === undefined
589 ? undefined
590 : props.rowSizing.fixedRowHeight + (index < props.activities.length - 1 ? WORK_ROW_GAP : 0),
591 [props.activities.length, props.expandedRows, props.rowSizing.fixedRowHeight],
592 );
593 const renderItem = useCallback(
594 ({ item, index }: { item: ThreadFeedActivity; index: number }) => (
595 <View className={index < props.activities.length - 1 ? "pb-px" : undefined}>
596 {props.renderRow(item)}
597 </View>
598 ),
599 [props.activities.length, props.renderRow],
600 );
601​
602 return (
603 <MaskedView
604 style={{ height }}
605 maskElement={
606 <View style={StyleSheet.absoluteFill} pointerEvents="none">
607 <Svg width="100%" height="100%">
608 <Defs>
609 <LinearGradient id={gradientId} x1="0%" x2="0%" y1="0%" y2="100%">
610 <Stop offset={0} stopColor="white" stopOpacity={0} />
611 <Stop offset={fadeFraction} stopColor="white" stopOpacity={1} />
612 <Stop offset={1 - fadeFraction} stopColor="white" stopOpacity={1} />
613 <Stop offset={1} stopColor="white" stopOpacity={0} />
614 </LinearGradient>
615 </Defs>
616 <Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
617 </Svg>
618 <Animated.View
619 className="absolute inset-x-0 top-0 bg-white"
620 style={[{ height: WORK_GROUP_EDGE_FADE_HEIGHT }, topCoverStyle]}
621 />
622 <Animated.View
623 className="absolute inset-x-0 bottom-0 bg-white"
624 style={[{ height: WORK_GROUP_EDGE_FADE_HEIGHT }, bottomCoverStyle]}
625 />
626 </View>
627 }
628 >
629 <AnimatedLegendList
630 ref={listRef}
631 data={props.activities}
632 keyExtractor={workLogRowKey}
633 estimatedItemSize={props.rowSizing.estimatedRowHeight + WORK_ROW_GAP}
634 getFixedItemSize={getFixedItemSize}
635 initialScrollIndex={initialScrollIndex}
636 // Bootstrap overscan is only 50px. An offset inside expanded detail can
637 // otherwise leave its own row unmeasured until after scroll restoration.
638 alwaysRender={
639 restoringPosition && initialPosition ? { keys: [initialPosition.rowId] } : undefined
640 }
641 recycleItems={false}
642 extraData={props.renderRow}
643 renderItem={renderItem}
644 sharedValues={sharedValues}
645 onContentSizeChange={onContentSizeChange}
646 onLayout={finishPendingAppend}
647 onLoad={() => {
648 loadedRef.current = true;
649 setRestoringPosition(false);
650 rememberPosition();
651 }}
652 onScroll={rememberPosition}
653 onScrollBeginDrag={() => {
654 userScrollingRef.current = true;
655 pendingAppendHeightRef.current = null;
656 }}
657 onScrollEndDrag={() => {
658 userScrollingRef.current = false;
659 }}
660 onMomentumScrollBegin={() => {
661 userScrollingRef.current = true;
662 pendingAppendHeightRef.current = null;
663 }}
664 onMomentumScrollEnd={() => {
665 userScrollingRef.current = false;
666 rememberPosition();
667 }}
668 maintainVisibleContentPosition
669 nestedScrollEnabled
670 directionalLockEnabled
671 showsVerticalScrollIndicator
672 scrollsToTop={false}
673 bounces={false}
674 keyboardShouldPersistTaps="handled"
675 // MaskedView bridges through a native host whose absolute-fill bounds
676 // can lag behind a resize. Keep the list's viewport at the group's
677 // current height when expanding details or appending calls.
678 style={[StyleSheet.absoluteFill, { height }]}
679 />
680 </MaskedView>
681 );
683​
684function workLogRowKey(row: ThreadFeedActivity): string {
685 return row.id;
687​
688const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
689 props: Omit<
690 ThreadWorkLogProps,
691 "activities" | "copiedRowId" | "expandedRows" | "rowSizing" | "scrollPositions"
692 > & {
693 readonly row: ThreadFeedActivity;
694 readonly copied: boolean;
695 readonly expanded: boolean;
696 },
697) {
698 const { row, expanded } = props;
699 const canExpand = row.canExpand;
700 const fullDetail = expanded ? row.getFullDetail() : null;
701 const viewedImagePath = workEntryViewedImagePath(row.workEntry);
702 const toolPresentation = resolveWorkEntryToolPresentation(row.workEntry);
703 const previewText =
704 toolPresentation?.displayName ?? compactActivityDetail(row.detail) ?? row.summary;
705 const displayText =
706 !toolPresentation && expanded && row.workEntry.command?.trim() ? "Command" : previewText;
707 const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
708 const failed = row.status === "failure";
709 const toolIcon = row.workEntry.toolIcon ?? row.workEntry.toolSource?.icon;
710 const hasSpecialToolIcon =
711 toolPresentation !== null || row.workEntry.toolSurface !== undefined || toolIcon !== undefined;
712 const icon =
713 toolPresentation?.icon ??
714 (failed && !hasSpecialToolIcon ? "xmark" : workRowSymbolName(row.icon));
715​
716 return (
717 <Animated.View
718 layout={WORK_LOG_LAYOUT_TRANSITION}
719 className="overflow-hidden"
720 {...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
721 >
722 <Pressable
723 accessibilityRole={canExpand ? "button" : undefined}
724 accessibilityLabel={failed ? `${previewText}, tool call failed` : previewText}
725 accessibilityHint={
726 canExpand ? "Double tap to show full details. Long press to copy." : "Long press to copy."
727 }
728 accessibilityState={canExpand ? { expanded } : undefined}
729 hitSlop={4}
730 onPress={() => {
731 if (canExpand) {
732 void Haptics.selectionAsync();
733 props.onToggleRow(row.id, props.anchorKey);
734 }
735 }}
736 onLongPress={() => props.onCopyRow(row.id, row.getCopyText())}
737 className="rounded-md px-0.5 py-0 active:bg-subtle"
738 >
739 <View className="min-h-8 flex-row items-center gap-1.5">
740 {row.live ? (
741 <ShimmeringWorkContent
742 environmentId={props.environmentId}
743 icon={icon}
744 iconSubtleColor={props.iconSubtleColor}
745 label={displayText}
746 showIcon
747 themeAppearance={props.themeAppearance}
748 toolIcon={toolIcon}
749 />
750 ) : (
751 <>
752 <View className="h-6 w-6 shrink-0 items-center justify-center">
753 {failed && !hasSpecialToolIcon ? (
754 <WorkLogIcon
755 icon={icon}
756 color={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
757 />
758 ) : (
759 <ToolActivityIconView
760 environmentId={props.environmentId}
761 icon={toolIcon}
762 fallback={icon}
763 fallbackColor={props.iconSubtleColor}
764 themeAppearance={props.themeAppearance}
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 && hasSpecialToolIcon ? (
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-adaptive-rose-600-400"
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 );
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 );
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 );
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 ]}
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 );
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" };