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

thread-work-log.tsx

508 lines17.9 KB

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