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