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 { useIsFocused } from "@react-navigation/native";
5import { useEffect, useId, useLayoutEffect, useState, type ComponentProps } from "react";
6import {
7 AccessibilityInfo,
8 AppState,
9 type ColorValue,
10 Pressable,
11 ScrollView,
12 StyleSheet,
13 View,
14} from "react-native";
15import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
16
17import { AppText as Text } from "../../components/AppText";
18import { cn } from "../../lib/cn";
19import type { ThreadFeedActivity } from "../../lib/threadActivity";
20import type { ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation";
21import Animated, {
22 cancelAnimation,
23 Easing,
24 FadeIn,
25 FadeOut,
26 LinearTransition,
27 ReduceMotion,
28 useAnimatedStyle,
29 useSharedValue,
30 withDelay,
31 withRepeat,
32 withSequence,
33 withTiming,
34} from "react-native-reanimated";
35
36const SHIMMER_WIDTH = 72;
37const SHIMMER_SWEEP_MS = 1_350;
38const SHIMMER_PAUSE_MS = 1_450;
39const SHIMMER_ICON_AND_GAP_WIDTH = 30;
40export const THREAD_DISCLOSURE_TRANSITION_MS = 180;
41const WORK_LOG_LAYOUT_TRANSITION = LinearTransition.duration(THREAD_DISCLOSURE_TRANSITION_MS);
42const WORK_LOG_DETAIL_ENTER_TRANSITION = FadeIn.duration(140);
43const WORK_LOG_DETAIL_EXIT_TRANSITION = FadeOut.duration(120);
44
45export function ThreadDisclosureChevron(props: {
46 readonly expanded: boolean;
47 readonly collapsedDirection: "right" | "down";
48 readonly size: number;
49 readonly tintColor: ColorValue;
50}) {
51 const expandedAngle = props.collapsedDirection === "right" ? 90 : 180;
52 const rotation = useSharedValue(props.expanded ? expandedAngle : 0);
53
54 useLayoutEffect(() => {
55 rotation.value = withTiming(props.expanded ? expandedAngle : 0, {
56 duration: THREAD_DISCLOSURE_TRANSITION_MS,
57 reduceMotion: ReduceMotion.System,
58 });
59 }, [expandedAngle, props.expanded, rotation]);
60
61 const rotationStyle = useAnimatedStyle(() => ({
62 transform: [{ rotate: `${rotation.value}deg` }],
63 }));
64
65 return (
66 <Animated.View
67 accessible={false}
68 accessibilityElementsHidden
69 importantForAccessibility="no-hide-descendants"
70 pointerEvents="none"
71 style={[{ width: props.size, height: props.size }, rotationStyle]}
72 >
73 <SymbolView
74 name={props.collapsedDirection === "right" ? "chevron.right" : "chevron.down"}
75 size={props.size}
76 tintColor={props.tintColor}
77 type="monochrome"
78 />
79 </Animated.View>
80 );
81}
82
83function ShimmerWorkContent(props: {
84 readonly highlighted: boolean;
85 readonly icon: AppSymbolName;
86 readonly iconSubtleColor: ColorValue;
87 readonly label: string;
88 readonly onTextLayout?: ComponentProps<typeof Text>["onTextLayout"];
89 readonly showIcon: boolean;
90}) {
91 return (
92 <View className="flex-row items-center gap-1.5">
93 <View className="h-6 w-6 shrink-0 items-center justify-center">
94 {props.showIcon ? (
95 <SymbolView
96 name={props.icon}
97 size={14}
98 weight="medium"
99 {...(props.highlighted
100 ? { tintColorClassName: "accent-foreground" as const }
101 : { tintColor: props.iconSubtleColor })}
102 type="monochrome"
103 />
104 ) : null}
105 </View>
106 <Text
107 className={cn(
108 "min-w-0 shrink text-sm",
109 props.highlighted ? "text-foreground" : "text-foreground-muted",
110 )}
111 numberOfLines={1}
112 onTextLayout={props.onTextLayout}
113 >
114 {props.label}
115 </Text>
116 </View>
117 );
118}
119
120export function ShimmeringWorkContent(props: {
121 readonly icon: AppSymbolName;
122 readonly iconSubtleColor: ColorValue;
123 readonly label: string;
124 readonly showIcon: boolean;
125}) {
126 const [availableWidth, setAvailableWidth] = useState(0);
127 const [textWidth, setTextWidth] = useState(0);
128 const [appIsActive, setAppIsActive] = useState(AppState.currentState === "active");
129 const [reducedMotion, setReducedMotion] = useState(true);
130 const screenIsFocused = useIsFocused();
131 const progress = useSharedValue(0);
132 const gradientId = `work-shimmer-${useId().replaceAll(":", "")}`;
133 const contentWidth = Math.min(availableWidth, SHIMMER_ICON_AND_GAP_WIDTH + Math.ceil(textWidth));
134
135 useEffect(() => {
136 const subscription = AppState.addEventListener("change", (state) => {
137 setAppIsActive(state === "active");
138 });
139 return () => subscription.remove();
140 }, []);
141
142 useEffect(() => {
143 void AccessibilityInfo.isReduceMotionEnabled().then(setReducedMotion);
144 const subscription = AccessibilityInfo.addEventListener(
145 "reduceMotionChanged",
146 setReducedMotion,
147 );
148 return () => subscription.remove();
149 }, []);
150
151 useEffect(() => {
152 cancelAnimation(progress);
153 progress.value = 0;
154 if (contentWidth <= 0 || reducedMotion || !appIsActive || !screenIsFocused) return;
155
156 progress.value = withRepeat(
157 withSequence(
158 withTiming(1, {
159 duration: SHIMMER_SWEEP_MS,
160 easing: Easing.linear,
161 reduceMotion: ReduceMotion.Never,
162 }),
163 withDelay(
164 SHIMMER_PAUSE_MS,
165 withTiming(0, { duration: 0, reduceMotion: ReduceMotion.Never }),
166 ),
167 ),
168 -1,
169 false,
170 undefined,
171 ReduceMotion.Never,
172 );
173 return () => cancelAnimation(progress);
174 }, [appIsActive, contentWidth, progress, reducedMotion, screenIsFocused]);
175
176 const sweepStyle = useAnimatedStyle(() => ({
177 transform: [{ translateX: -SHIMMER_WIDTH + progress.value * (contentWidth + SHIMMER_WIDTH) }],
178 }));
179 const counterSweepStyle = useAnimatedStyle(() => ({
180 transform: [{ translateX: SHIMMER_WIDTH - progress.value * (contentWidth + SHIMMER_WIDTH) }],
181 }));
182
183 return (
184 <View
185 className="min-w-0 flex-1 overflow-hidden"
186 onLayout={(event) => setAvailableWidth(event.nativeEvent.layout.width)}
187 >
188 <ShimmerWorkContent
189 highlighted={false}
190 icon={props.icon}
191 iconSubtleColor={props.iconSubtleColor}
192 label={props.label}
193 showIcon={props.showIcon}
194 onTextLayout={(event) => setTextWidth(event.nativeEvent.lines[0]?.width ?? 0)}
195 />
196 {!reducedMotion && appIsActive && screenIsFocused && contentWidth > 0 ? (
197 <Animated.View
198 className="absolute inset-y-0 left-0 overflow-hidden"
199 pointerEvents="none"
200 accessible={false}
201 accessibilityElementsHidden
202 importantForAccessibility="no-hide-descendants"
203 style={[{ width: SHIMMER_WIDTH }, sweepStyle]}
204 >
205 <MaskedView
206 style={StyleSheet.absoluteFill}
207 maskElement={
208 <Svg width="100%" height="100%">
209 <Defs>
210 <LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
211 <Stop offset="0" stopColor="white" stopOpacity={0} />
212 <Stop offset="0.15" stopColor="white" stopOpacity={0.12} />
213 <Stop offset="0.35" stopColor="white" stopOpacity={0.55} />
214 <Stop offset="0.5" stopColor="white" stopOpacity={1} />
215 <Stop offset="0.65" stopColor="white" stopOpacity={0.55} />
216 <Stop offset="0.85" stopColor="white" stopOpacity={0.12} />
217 <Stop offset="1" stopColor="white" stopOpacity={0} />
218 </LinearGradient>
219 </Defs>
220 <Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
221 </Svg>
222 }
223 >
224 <Animated.View style={[{ width: availableWidth }, counterSweepStyle]}>
225 <ShimmerWorkContent
226 highlighted
227 icon={props.icon}
228 iconSubtleColor={props.iconSubtleColor}
229 label={props.label}
230 showIcon={props.showIcon}
231 />
232 </Animated.View>
233 </MaskedView>
234 </Animated.View>
235 ) : null}
236 </View>
237 );
238}
239
240function stripShellWrapper(value: string): string {
241 const trimmed = value.trim();
242 const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
243 return (match?.[1] ?? trimmed).trim();
244}
245
246function compactActivityDetail(detail: string | null): string | null {
247 if (!detail) {
248 return null;
249 }
250
251 const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
252 return cleaned.length > 0 ? cleaned : null;
253}
254
255function workRowSymbolName(icon: ThreadFeedActivity["icon"]): AppSymbolName {
256 switch (icon) {
257 case "agent":
258 return { ios: "sparkles", android: "auto_awesome" };
259 case "alert":
260 return { ios: "exclamationmark.triangle", android: "error" };
261 case "check":
262 return { ios: "checkmark", android: "check" };
263 case "command":
264 return { ios: "terminal", android: "terminal" };
265 case "edit":
266 return { ios: "square.and.pencil", android: "edit" };
267 case "eye":
268 return { ios: "eye", android: "visibility" };
269 case "globe":
270 return { ios: "globe", android: "public" };
271 case "hammer":
272 return { ios: "hammer", android: "construction" };
273 case "message":
274 return { ios: "bubble.left", android: "chat_bubble" };
275 case "warning":
276 return { ios: "xmark", android: "close" };
277 case "wrench":
278 return { ios: "wrench", android: "build" };
279 case "zap":
280 return { ios: "bolt", android: "bolt" };
281 }
282}
283
284// Entering fades only for rows created moments ago: rows remount whenever the
285// list scrolls them back into view, and old rows must not replay an entrance.
286const FRESH_ROW_WINDOW_MS = 3_000;
287function isFreshRow(createdAt: string): boolean {
288 const timestamp = Date.parse(createdAt);
289 return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS;
290}
291
292// Pre-measurement heights for the feed's getFixedItemSize. Collapsed work-log
293// rows are single-line (numberOfLines={1}) inside a min-height that stays
294// taller than text-sm at every supported base font size, so row height is
295// deterministic. Values mirror the classNames below. A mismatch only costs a
296// one-time correction on measure.
297const WORK_ROW_HEIGHT = 32; // min-h-8
298const WORK_ROW_GAP = 1; // gap-px
299const WORK_LOG_BOTTOM_MARGIN = 4; // mb-1
300
301export const WORK_GROUP_TOGGLE_HEIGHT = 32; // min-h-8
302
303export function collapsedWorkLogHeight(activities: ReadonlyArray<ThreadFeedActivity>): number {
304 const rows = activities;
305 if (rows.length === 0) {
306 return 0;
307 }
308 return WORK_LOG_BOTTOM_MARGIN + rows.length * WORK_ROW_HEIGHT + (rows.length - 1) * WORK_ROW_GAP;
309}
310
311export function ThreadWorkLog(props: {
312 readonly activities: ReadonlyArray<ThreadFeedActivity>;
313 readonly copiedRowId: string | null;
314 readonly expandedRows: Readonly<Record<string, boolean>>;
315 readonly iconSubtleColor: import("react-native").ColorValue;
316 readonly onCopyRow: (rowId: string, value: string) => void;
317 readonly onToggleRow: (rowId: string) => void;
318}) {
319 const rows = props.activities.map((activity) => ({
320 ...activity,
321 detail: compactActivityDetail(activity.detail),
322 }));
323
324 if (rows.length === 0) {
325 return null;
326 }
327
328 return (
329 <View className="-mx-1 mb-1 px-1 py-0">
330 <View className="gap-px">
331 {rows.map((row) => {
332 const expanded = props.expandedRows[row.id] ?? false;
333 const canExpand = row.canExpand;
334 const fullDetail = expanded ? row.getFullDetail() : null;
335 const displayText = row.detail ?? row.summary;
336 const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
337 const failed = row.status === "failure";
338 const showIcon = !row.groupedToolDetail || iconIsDestructive || failed;
339
340 return (
341 <Animated.View
342 key={row.id}
343 layout={WORK_LOG_LAYOUT_TRANSITION}
344 className="overflow-hidden"
345 {...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
346 >
347 <Pressable
348 accessibilityRole={canExpand ? "button" : undefined}
349 accessibilityLabel={failed ? `${displayText}, tool call failed` : displayText}
350 accessibilityHint={
351 canExpand
352 ? "Double tap to show full details. Long press to copy."
353 : "Long press to copy."
354 }
355 accessibilityState={canExpand ? { expanded } : undefined}
356 hitSlop={4}
357 onPress={() => {
358 if (canExpand) {
359 void Haptics.selectionAsync();
360 props.onToggleRow(row.id);
361 }
362 }}
363 onLongPress={() => props.onCopyRow(row.id, row.getCopyText())}
364 className="rounded-md px-0.5 py-0 active:bg-subtle"
365 >
366 <View className="min-h-8 flex-row items-center gap-1.5">
367 {row.live ? (
368 <ShimmeringWorkContent
369 icon={workRowSymbolName(row.icon)}
370 iconSubtleColor={props.iconSubtleColor}
371 label={displayText}
372 showIcon={showIcon}
373 />
374 ) : (
375 <>
376 <View className="h-6 w-6 shrink-0 items-center justify-center">
377 {showIcon ? (
378 <SymbolView
379 name={
380 failed
381 ? { ios: "xmark", android: "close" }
382 : workRowSymbolName(row.icon)
383 }
384 size={14}
385 weight="medium"
386 tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
387 type="monochrome"
388 />
389 ) : null}
390 </View>
391 <Text
392 className={cn(
393 "min-w-0 flex-1 text-sm text-foreground-muted",
394 iconIsDestructive && "font-t3-medium text-adaptive-rose-600-400",
395 )}
396 numberOfLines={1}
397 >
398 {displayText}
399 </Text>
400 </>
401 )}
402
403 <View className="shrink-0 flex-row items-center gap-px">
404 {props.copiedRowId === row.id ? (
405 <Text className="pr-1 font-t3-medium text-3xs text-adaptive-emerald-600-400">
406 Copied
407 </Text>
408 ) : null}
409 <View className="h-4 w-4 items-center justify-center">
410 {canExpand ? (
411 <ThreadDisclosureChevron
412 expanded={expanded}
413 collapsedDirection="down"
414 size={11}
415 tintColor={props.iconSubtleColor}
416 />
417 ) : null}
418 </View>
419 </View>
420 </View>
421 </Pressable>
422
423 {fullDetail ? (
424 <Animated.View
425 entering={WORK_LOG_DETAIL_ENTER_TRANSITION}
426 exiting={WORK_LOG_DETAIL_EXIT_TRANSITION}
427 layout={WORK_LOG_LAYOUT_TRANSITION}
428 className="ml-7 border-l border-adaptive-neutral-300-a60-white-a12 pb-1 pl-3 pt-0.5"
429 >
430 <ScrollView
431 nestedScrollEnabled
432 directionalLockEnabled
433 showsVerticalScrollIndicator
434 className="max-h-60"
435 contentContainerStyle={{ paddingRight: 8 }}
436 >
437 <Text
438 selectable
439 className="font-mono text-2xs leading-normal text-foreground-muted"
440 >
441 {fullDetail}
442 </Text>
443 </ScrollView>
444 </Animated.View>
445 ) : null}
446 </Animated.View>
447 );
448 })}
449 </View>
450 </View>
451 );
452}
453
454export function ThreadWorkGroupToggle(props: {
455 readonly expanded: boolean;
456 readonly hiddenCount: number;
457 readonly iconSubtleColor: import("react-native").ColorValue;
458 readonly summary: string;
459 readonly summaryKind: ToolGroupSummaryKind;
460 readonly hasFailure: boolean;
461 readonly shimmer: boolean;
462 readonly onToggle: () => void;
463}) {
464 const accessibilityLabel = props.hasFailure
465 ? `${props.summary}, tool call failed`
466 : props.summary;
467 const icon = toolGroupSummarySymbolName(props.summaryKind);
468
469 return (
470 <View className="-mx-1 px-1 py-0">
471 <Pressable
472 accessibilityRole="button"
473 accessibilityState={{ expanded: props.expanded }}
474 accessibilityLabel={accessibilityLabel}
475 accessibilityHint={`Double tap to ${props.expanded ? "hide" : "show"} ${props.hiddenCount} tool ${props.hiddenCount === 1 ? "call" : "calls"}.`}
476 hitSlop={4}
477 onPress={() => {
478 void Haptics.selectionAsync();
479 props.onToggle();
480 }}
481 className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0 active:bg-subtle"
482 >
483 {props.shimmer ? (
484 <ShimmeringWorkContent
485 icon={icon}
486 iconSubtleColor={props.iconSubtleColor}
487 label={props.summary}
488 showIcon
489 />
490 ) : (
491 <>
492 <View className="h-6 w-6 items-center justify-center">
493 <SymbolView
494 name={icon}
495 size={14}
496 tintColor={props.iconSubtleColor}
497 type="monochrome"
498 />
499 </View>
500 <Text className="min-w-0 flex-1 text-sm text-foreground-muted" numberOfLines={1}>
501 {props.summary}
502 </Text>
503 </>
504 )}
505 <ThreadDisclosureChevron
506 expanded={props.expanded}
507 collapsedDirection="down"
508 size={11}
509 tintColor={props.iconSubtleColor}
510 />
511 </Pressable>
512 </View>
513 );
514}
515
516function toolGroupSummarySymbolName(kind: ToolGroupSummaryKind): AppSymbolName {
517 switch (kind) {
518 case "read":
519 return { ios: "eye", android: "visibility" };
520 case "edit":
521 return { ios: "square.and.pencil", android: "edit" };
522 case "command":
523 return { ios: "terminal", android: "terminal" };
524 case "search":
525 return { ios: "globe", android: "public" };
526 case "code-search":
527 return "magnifyingglass";
528 case "other":
529 return { ios: "wrench", android: "build" };
530 case "agent-tool":
531 return { ios: "sparkles", android: "auto_awesome" };
532 case "tone-tool":
533 return { ios: "bolt", android: "bolt" };
534 case "dynamic-tool":
535 case "update":
536 case "mixed":
537 return { ios: "hammer", android: "construction" };
538 }
539}