Open History to see the last commit
1import * as Haptics from "expo-haptics";
2import { Image } from "expo-image";
3import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
4import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
5import { MaskedView } from "@expo/ui/community/masked-view";
6import { useIsFocused, useNavigation } from "@react-navigation/native";
7import { useEffect, useId, useState, type ComponentProps } from "react";
8import { AccessibilityInfo, AppState, type ColorValue, Pressable, View } from "react-native";
9import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
10
11import { AppText as Text } from "../../components/AppText";
12import { T3_CODE_BRAND_MARK_SOURCE } from "../../components/brandAssets";
13import { cn } from "../../lib/cn";
14import { threadFeedActivityIsVisible, type ThreadFeedActivity } from "../../lib/threadActivity";
15import {
16 type ToolGroupSummaryKind,
17 workEntryViewedImagePath,
18} from "@t3tools/client-runtime/work-log/presentation";
19import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText";
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";
34import { useV2ItemSupport } from "../../state/v2-item-support";
35import { ThreadActivityInspector } from "./ThreadActivityInspector";
36import {
37 resolveThreadActivityMetadata,
38 resolveThreadActivityStatus,
39} from "./thread-activity-row-presentation";
40
41const SHIMMER_WIDTH = 72;
42const SHIMMER_SWEEP_MS = 1_350;
43const SHIMMER_PAUSE_MS = 1_450;
44const SHIMMER_ICON_AND_GAP_WIDTH = 30;
45export const THREAD_DISCLOSURE_TRANSITION_MS = 180;
46const WORK_LOG_LAYOUT_TRANSITION = LinearTransition.duration(THREAD_DISCLOSURE_TRANSITION_MS);
47const WORK_LOG_DETAIL_ENTER_TRANSITION = FadeIn.duration(140);
48const WORK_LOG_DETAIL_EXIT_TRANSITION = FadeOut.duration(120);
49
50function ShimmerWorkContent(props: {
51 readonly highlighted: boolean;
52 readonly icon: AppSymbolName;
53 readonly iconSubtleColor: ColorValue;
54 readonly label: string;
55 readonly onTextLayout?: ComponentProps<typeof Text>["onTextLayout"];
56 readonly showIcon: boolean;
57}) {
58 return (
59 <View className="flex-row items-center gap-1.5">
60 <View className="h-6 w-6 shrink-0 items-center justify-center">
61 {props.showIcon ? (
62 <SymbolView
63 name={props.icon}
64 size={14}
65 weight="medium"
66 {...(props.highlighted
67 ? { tintColorClassName: "accent-foreground" as const }
68 : { tintColor: props.iconSubtleColor })}
69 type="monochrome"
70 />
71 ) : null}
72 </View>
73 <Text
74 className={cn(
75 "min-w-0 shrink text-sm",
76 props.highlighted ? "text-foreground" : "text-foreground-muted",
77 )}
78 numberOfLines={1}
79 onTextLayout={props.onTextLayout}
80 >
81 {props.label}
82 </Text>
83 </View>
84 );
85}
86
87export function ShimmeringWorkContent(props: {
88 readonly icon: AppSymbolName;
89 readonly iconSubtleColor: ColorValue;
90 readonly label: string;
91 readonly showIcon: boolean;
92}) {
93 const [availableWidth, setAvailableWidth] = useState(0);
94 const [textWidth, setTextWidth] = useState(0);
95 const [appIsActive, setAppIsActive] = useState(AppState.currentState === "active");
96 const [reducedMotion, setReducedMotion] = useState(true);
97 const screenIsFocused = useIsFocused();
98 const progress = useSharedValue(0);
99 const gradientId = `work-shimmer-${useId().replaceAll(":", "")}`;
100 const contentWidth = Math.min(availableWidth, SHIMMER_ICON_AND_GAP_WIDTH + Math.ceil(textWidth));
101
102 useEffect(() => {
103 const subscription = AppState.addEventListener("change", (state) => {
104 setAppIsActive(state === "active");
105 });
106 return () => subscription.remove();
107 }, []);
108
109 useEffect(() => {
110 void AccessibilityInfo.isReduceMotionEnabled().then(setReducedMotion);
111 const subscription = AccessibilityInfo.addEventListener(
112 "reduceMotionChanged",
113 setReducedMotion,
114 );
115 return () => subscription.remove();
116 }, []);
117
118 useEffect(() => {
119 cancelAnimation(progress);
120 progress.value = 0;
121 if (contentWidth <= 0 || reducedMotion || !appIsActive || !screenIsFocused) return;
122
123 progress.value = withRepeat(
124 withSequence(
125 withTiming(1, {
126 duration: SHIMMER_SWEEP_MS,
127 easing: Easing.linear,
128 reduceMotion: ReduceMotion.Never,
129 }),
130 withDelay(
131 SHIMMER_PAUSE_MS,
132 withTiming(0, { duration: 0, reduceMotion: ReduceMotion.Never }),
133 ),
134 ),
135 -1,
136 false,
137 undefined,
138 ReduceMotion.Never,
139 );
140 return () => cancelAnimation(progress);
141 }, [appIsActive, contentWidth, progress, reducedMotion, screenIsFocused]);
142
143 const sweepStyle = useAnimatedStyle(() => ({
144 transform: [{ translateX: -SHIMMER_WIDTH + progress.value * (contentWidth + SHIMMER_WIDTH) }],
145 }));
146 const counterSweepStyle = useAnimatedStyle(() => ({
147 transform: [{ translateX: SHIMMER_WIDTH - progress.value * (contentWidth + SHIMMER_WIDTH) }],
148 }));
149
150 return (
151 <View
152 className="min-w-0 flex-1"
153 onLayout={(event) => setAvailableWidth(event.nativeEvent.layout.width)}
154 >
155 <ShimmerWorkContent
156 highlighted={false}
157 icon={props.icon}
158 iconSubtleColor={props.iconSubtleColor}
159 label={props.label}
160 showIcon={props.showIcon}
161 onTextLayout={(event) => setTextWidth(event.nativeEvent.lines[0]?.width ?? 0)}
162 />
163 {!reducedMotion && appIsActive && screenIsFocused && contentWidth > 0 ? (
164 <Animated.View
165 className="absolute inset-y-0 left-0 overflow-hidden"
166 pointerEvents="none"
167 accessible={false}
168 accessibilityElementsHidden
169 importantForAccessibility="no-hide-descendants"
170 style={[{ width: SHIMMER_WIDTH }, sweepStyle]}
171 >
172 <MaskedView
173 className="absolute inset-0"
174 maskElement={
175 <Svg width="100%" height="100%">
176 <Defs>
177 <LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
178 <Stop offset="0" stopColor="white" stopOpacity={0} />
179 <Stop offset="0.15" stopColor="white" stopOpacity={0.12} />
180 <Stop offset="0.35" stopColor="white" stopOpacity={0.55} />
181 <Stop offset="0.5" stopColor="white" stopOpacity={1} />
182 <Stop offset="0.65" stopColor="white" stopOpacity={0.55} />
183 <Stop offset="0.85" stopColor="white" stopOpacity={0.12} />
184 <Stop offset="1" stopColor="white" stopOpacity={0} />
185 </LinearGradient>
186 </Defs>
187 <Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
188 </Svg>
189 }
190 >
191 <Animated.View style={[{ width: availableWidth }, counterSweepStyle]}>
192 <ShimmerWorkContent
193 highlighted
194 icon={props.icon}
195 iconSubtleColor={props.iconSubtleColor}
196 label={props.label}
197 showIcon={props.showIcon}
198 />
199 </Animated.View>
200 </MaskedView>
201 </Animated.View>
202 ) : null}
203 </View>
204 );
205}
206
207function stripShellWrapper(value: string): string {
208 const trimmed = value.trim();
209 const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
210 return (match?.[1] ?? trimmed).trim();
211}
212
213function compactActivityDetail(detail: string | null): string | null {
214 if (!detail) {
215 return null;
216 }
217
218 const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
219 return cleaned.length > 0 ? cleaned : null;
220}
221
222function workRowSymbolName(icon: ThreadFeedActivity["icon"]): AppSymbolName {
223 switch (icon) {
224 case "agent":
225 return { ios: "sparkles", android: "auto_awesome" };
226 case "alert":
227 return { ios: "exclamationmark.triangle", android: "error" };
228 case "check":
229 return { ios: "checkmark", android: "check" };
230 case "command":
231 return { ios: "terminal", android: "terminal" };
232 case "edit":
233 return { ios: "square.and.pencil", android: "edit" };
234 case "eye":
235 return { ios: "eye", android: "visibility" };
236 case "globe":
237 return { ios: "globe", android: "public" };
238 case "hammer":
239 return { ios: "hammer", android: "construction" };
240 case "message":
241 return { ios: "bubble.left", android: "chat_bubble" };
242 case "warning":
243 return { ios: "xmark", android: "close" };
244 case "wrench":
245 return { ios: "wrench", android: "build" };
246 case "zap":
247 return { ios: "bolt", android: "bolt" };
248 }
249}
250
251function WorkRowIcon(props: {
252 readonly row: ThreadFeedActivity;
253 readonly iconSubtleColor: import("react-native").ColorValue;
254 readonly failed: boolean;
255}) {
256 if (props.row.logo === "t3-code") {
257 return (
258 <Image
259 source={T3_CODE_BRAND_MARK_SOURCE}
260 accessibilityIgnoresInvertColors
261 style={{ width: 16, height: 16, borderRadius: 4 }}
262 />
263 );
264 }
265
266 const iconIsDestructive = props.row.icon === "alert" || props.row.icon === "warning";
267 return (
268 <SymbolView
269 name={props.failed ? { ios: "xmark", android: "close" } : workRowSymbolName(props.row.icon)}
270 size={14}
271 weight="medium"
272 tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
273 type="monochrome"
274 />
275 );
276}
277
278function ThreadActivityThreadRow(props: {
279 readonly activity: ThreadFeedActivity;
280 readonly environmentId: EnvironmentId;
281 readonly iconColor: import("react-native").ColorValue;
282}) {
283 const row = props.activity.projectedItem;
284 const support = useV2ItemSupport({
285 environmentId: props.environmentId,
286 sourceThreadId: row.sourceThreadId,
287 sourceItemId: row.sourceItemId,
288 });
289 const navigation = useNavigation();
290 const item = row.item;
291 let targetThreadId: ThreadId | null = null;
292 let label = "Open related thread";
293 let providerDriver = support.providerSession?.driver ?? null;
294 let providerInstanceId = support.providerSession?.providerInstanceId ?? null;
295 let model = support.providerSession?.model ?? null;
296
297 if (item.type === "thread_created") {
298 targetThreadId = item.targetThreadId;
299 label = "Open created thread";
300 providerInstanceId = item.targetProviderInstanceId;
301 model = item.targetModel;
302 } else if (item.type === "subagent") {
303 targetThreadId = support.subagent?.childThreadId ?? item.childThreadId;
304 label = "Open subagent thread";
305 providerDriver = support.subagent?.driver ?? item.driver;
306 providerInstanceId = support.subagent?.providerInstanceId ?? item.providerInstanceId;
307 model = support.subagent?.model ?? model;
308 } else if (item.type === "fork") {
309 targetThreadId =
310 item.targetThreadId === row.sourceThreadId && item.source.type === "run"
311 ? item.source.threadId
312 : item.targetThreadId;
313 label = targetThreadId === item.targetThreadId ? "Open forked thread" : "Open parent thread";
314 }
315
316 const metadata = resolveThreadActivityMetadata({ providerDriver, providerInstanceId, model });
317 const status = resolveThreadActivityStatus(item.status);
318 const statusDotClassName =
319 status.tone === "success"
320 ? "bg-emerald-500"
321 : status.tone === "danger"
322 ? "bg-rose-500"
323 : status.tone === "warning"
324 ? "bg-amber-500"
325 : "bg-sky-500";
326
327 return (
328 <View className="mb-2 min-h-11 flex-row items-center gap-2 rounded-xl border border-continuous border-adaptive-neutral-950-a10-white-a10 bg-card px-2.5 py-1.5">
329 <View
330 accessible
331 accessibilityRole="text"
332 accessibilityLabel={status.label}
333 className={cn("size-2 shrink-0 rounded-full", statusDotClassName)}
334 />
335
336 <Text className="min-w-0 flex-1 text-sm text-foreground" numberOfLines={1}>
337 <Text className="font-t3-medium text-foreground">{props.activity.summary}</Text>
338 {metadata ? <Text className="text-foreground-muted opacity-60"> · {metadata}</Text> : null}
339 </Text>
340
341 <Pressable
342 accessibilityRole="link"
343 accessibilityLabel={label}
344 disabled={targetThreadId === null}
345 hitSlop={10}
346 onPress={() => {
347 if (targetThreadId === null) return;
348 void Haptics.selectionAsync();
349 navigation.navigate("Thread", {
350 environmentId: props.environmentId,
351 threadId: targetThreadId,
352 });
353 }}
354 className="h-8 shrink-0 flex-row items-center gap-1 rounded-lg bg-adaptive-neutral-950-a5-white-a5 py-1.5 pl-2.5 pr-1.5 active:bg-adaptive-neutral-950-a10-white-a10 disabled:opacity-40"
355 >
356 <Text className="font-t3-medium text-sm text-foreground">Open</Text>
357 <SymbolView name="arrow.right" size={11} tintColor={props.iconColor} type="monochrome" />
358 </Pressable>
359 </View>
360 );
361}
362
363// Entering fades only for rows created moments ago: rows remount whenever the
364// list scrolls them back into view, and old rows must not replay an entrance.
365const FRESH_ROW_WINDOW_MS = 3_000;
366function isFreshRow(createdAt: string): boolean {
367 const timestamp = Date.parse(createdAt);
368 return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS;
369}
370
371// Routine neutral tool activity carries no signal worth a row. Prominent
372// linked activity stays visible so its live status and thread affordance do.
373export function visibleWorkLogActivities(
374 activities: ReadonlyArray<ThreadFeedActivity>,
375): ReadonlyArray<ThreadFeedActivity> {
376 return activities.filter(threadFeedActivityIsVisible);
377}
378
379export function ThreadWorkLog(props: {
380 readonly activities: ReadonlyArray<ThreadFeedActivity>;
381 readonly copiedRowId: string | null;
382 readonly currentThreadId: ThreadId;
383 readonly environmentId: EnvironmentId;
384 readonly expandedRows: Readonly<Record<string, boolean>>;
385 readonly iconSubtleColor: import("react-native").ColorValue;
386 readonly onCopyRow: (rowId: string, value: string) => void;
387 readonly onToggleRow: (rowId: string) => void;
388 readonly workspaceRoot?: string | null;
389 readonly renderImage?: MarkdownImageRenderer;
390}) {
391 const rows = visibleWorkLogActivities(props.activities).map((activity) => ({
392 ...activity,
393 detail: compactActivityDetail(activity.detail),
394 }));
395
396 if (rows.length === 0) {
397 return null;
398 }
399
400 return (
401 <View className="-mx-1 mb-1 px-1 py-0">
402 <View className="gap-px">
403 {rows.map((row) => {
404 const expanded = props.expandedRows[row.id] ?? false;
405 const canExpand = row.canExpand;
406 const viewedImagePath = workEntryViewedImagePath(row.workEntry);
407 const displayText = row.detail ?? row.summary;
408 const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
409 const failed = row.status === "failure";
410 const showIcon = !row.groupedToolDetail || iconIsDestructive || failed;
411
412 if (row.prominent) {
413 return (
414 <Animated.View
415 key={row.id}
416 layout={WORK_LOG_LAYOUT_TRANSITION}
417 className="overflow-hidden"
418 {...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
419 >
420 <ThreadActivityThreadRow
421 activity={row}
422 environmentId={props.environmentId}
423 iconColor={props.iconSubtleColor}
424 />
425 </Animated.View>
426 );
427 }
428
429 return (
430 <Animated.View
431 key={row.id}
432 layout={WORK_LOG_LAYOUT_TRANSITION}
433 className="overflow-hidden"
434 {...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
435 >
436 <Pressable
437 accessibilityRole={canExpand ? "button" : undefined}
438 accessibilityLabel={failed ? `${displayText}, tool call failed` : displayText}
439 accessibilityHint={
440 canExpand
441 ? "Double tap to show full details. Long press to copy."
442 : "Long press to copy."
443 }
444 accessibilityState={canExpand ? { expanded } : undefined}
445 hitSlop={4}
446 onPress={() => {
447 if (canExpand) {
448 void Haptics.selectionAsync();
449 props.onToggleRow(row.id);
450 }
451 }}
452 onLongPress={() => props.onCopyRow(row.id, row.getCopyText())}
453 className="rounded-md px-0.5 py-0 active:bg-subtle"
454 >
455 <View className="min-h-8 flex-row items-center gap-1.5">
456 {row.live ? (
457 <ShimmeringWorkContent
458 icon={workRowSymbolName(row.icon)}
459 iconSubtleColor={props.iconSubtleColor}
460 label={displayText}
461 showIcon={showIcon}
462 />
463 ) : (
464 <>
465 <View className="h-6 w-6 shrink-0 items-center justify-center">
466 {showIcon ? (
467 <WorkRowIcon
468 row={row}
469 failed={failed}
470 iconSubtleColor={props.iconSubtleColor}
471 />
472 ) : null}
473 </View>
474 <Text
475 className={cn(
476 "min-w-0 flex-1 text-sm text-foreground-muted",
477 iconIsDestructive && "font-t3-medium text-adaptive-rose-600-400",
478 )}
479 numberOfLines={1}
480 >
481 {displayText}
482 </Text>
483 </>
484 )}
485
486 <View className="shrink-0 flex-row items-center gap-px">
487 {props.copiedRowId === row.id ? (
488 <Text className="pr-1 font-t3-medium text-3xs text-adaptive-emerald-600-400">
489 Copied
490 </Text>
491 ) : null}
492 <View className="h-4 w-4 items-center justify-center">
493 {canExpand ? (
494 <SymbolView
495 name={
496 expanded
497 ? { ios: "chevron.up", android: "keyboard_arrow_up" }
498 : { ios: "chevron.down", android: "keyboard_arrow_down" }
499 }
500 size={11}
501 tintColor={props.iconSubtleColor}
502 type="monochrome"
503 />
504 ) : null}
505 </View>
506 </View>
507 </View>
508 </Pressable>
509
510 {expanded && canExpand ? (
511 <Animated.View
512 entering={WORK_LOG_DETAIL_ENTER_TRANSITION}
513 exiting={WORK_LOG_DETAIL_EXIT_TRANSITION}
514 layout={WORK_LOG_LAYOUT_TRANSITION}
515 className="ml-7 overflow-hidden border-l border-adaptive-neutral-300-a60-white-a12 pb-1 pl-3 pt-0.5"
516 >
517 {viewedImagePath && props.renderImage ? (
518 <View className="pb-1.5">
519 {props.renderImage({ href: viewedImagePath, alt: null, title: null })}
520 </View>
521 ) : null}
522 <ThreadActivityInspector
523 activity={row}
524 currentThreadId={props.currentThreadId}
525 environmentId={props.environmentId}
526 iconColor={props.iconSubtleColor}
527 workspaceRoot={props.workspaceRoot}
528 />
529 </Animated.View>
530 ) : null}
531 </Animated.View>
532 );
533 })}
534 </View>
535 </View>
536 );
537}
538
539export function ThreadWorkGroupToggle(props: {
540 readonly expanded: boolean;
541 readonly hiddenCount: number;
542 readonly iconSubtleColor: import("react-native").ColorValue;
543 readonly summary: string;
544 readonly summaryKind: ToolGroupSummaryKind;
545 readonly hasFailure: boolean;
546 readonly shimmer: boolean;
547 readonly onToggle: () => void;
548}) {
549 const accessibilityLabel = props.hasFailure
550 ? `${props.summary}, tool call failed`
551 : props.summary;
552 const icon = toolGroupSummarySymbolName(props.summaryKind);
553
554 return (
555 <View className="-mx-1 mb-1 px-1 py-0">
556 <Pressable
557 accessibilityRole="button"
558 accessibilityState={{ expanded: props.expanded }}
559 accessibilityLabel={accessibilityLabel}
560 accessibilityHint={`Double tap to ${props.expanded ? "hide" : "show"} ${props.hiddenCount} tool ${props.hiddenCount === 1 ? "call" : "calls"}.`}
561 hitSlop={4}
562 onPress={() => {
563 void Haptics.selectionAsync();
564 props.onToggle();
565 }}
566 className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0 active:bg-subtle"
567 >
568 {props.shimmer ? (
569 <ShimmeringWorkContent
570 icon={icon}
571 iconSubtleColor={props.iconSubtleColor}
572 label={props.summary}
573 showIcon
574 />
575 ) : (
576 <>
577 <View className="h-6 w-6 items-center justify-center">
578 <SymbolView
579 name={icon}
580 size={14}
581 tintColor={props.iconSubtleColor}
582 type="monochrome"
583 />
584 </View>
585 <Text className="min-w-0 flex-1 text-sm text-foreground-muted" numberOfLines={1}>
586 {props.summary}
587 </Text>
588 </>
589 )}
590 <SymbolView
591 name={
592 props.expanded
593 ? { ios: "chevron.up", android: "keyboard_arrow_up" }
594 : { ios: "chevron.down", android: "keyboard_arrow_down" }
595 }
596 size={11}
597 tintColor={props.iconSubtleColor}
598 type="monochrome"
599 />
600 </Pressable>
601 </View>
602 );
603}
604
605function toolGroupSummarySymbolName(kind: ToolGroupSummaryKind): AppSymbolName {
606 switch (kind) {
607 case "read":
608 return { ios: "eye", android: "visibility" };
609 case "edit":
610 return { ios: "square.and.pencil", android: "edit" };
611 case "command":
612 return { ios: "terminal", android: "terminal" };
613 case "search":
614 return { ios: "globe", android: "public" };
615 case "code-search":
616 return "magnifyingglass";
617 case "other":
618 return { ios: "wrench", android: "build" };
619 case "agent-tool":
620 return { ios: "sparkles", android: "auto_awesome" };
621 case "tone-tool":
622 return { ios: "bolt", android: "bolt" };
623 case "dynamic-tool":
624 case "update":
625 case "mixed":
626 return { ios: "hammer", android: "construction" };
627 }
628}