Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { ThreadTurnSubagents } from "@t3tools/client-runtime/state/thread-subagents";
3import type { EnvironmentId, OrchestrationV2Subagent, ThreadId } from "@t3tools/contracts";
4import { formatDuration } from "@t3tools/shared/orchestrationTiming";
5import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
6import * as DateTime from "effect/DateTime";
7import * as Haptics from "expo-haptics";
8import { useEffect, useState } from "react";
9import { Platform, Pressable, ScrollView, View } from "react-native";
10import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
11import { useSafeAreaInsets } from "react-native-safe-area-context";
12
13import { AndroidSheetHeader } from "../../components/AndroidScreenHeader";
14import { AppText as Text } from "../../components/AppText";
15import { SymbolView } from "../../components/AppSymbol";
16import { useUniwindTheme } from "../../lib/useUniwindTheme";
17import { environmentThreadDetails } from "../../state/threads";
18import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
19import { resolveSubagentRowPresentation } from "./threadAgentsPresentation";
20
21import { SubagentStatusDot } from "./SubagentStatusDot";
22
23const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
24
25type AgentsTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
26
27export function useThreadTurnSubagents(target: AgentsTarget): ThreadTurnSubagents | null {
28 return useAtomValue(environmentThreadDetails.turnSubagentsAtom(target));
29}
30
31export function ThreadAgentsSheet({ route }: StaticScreenProps<AgentsTarget>) {
32 const target = route.params;
33 const navigation = useNavigation();
34 const insets = useSafeAreaInsets();
35 const theme = useUniwindTheme();
36 const turn = useThreadTurnSubagents(target);
37 const subagents = turn?.subagents ?? [];
38 const hasLiveAgent = (turn?.liveCount ?? 0) > 0;
39
40 const openChildThread = (childThreadId: ThreadId) => {
41 void Haptics.selectionAsync();
42 // Replace rather than push: the sheet is a leaf, and the child thread
43 // belongs in the workspace stack where Home's back button expects it.
44 navigation.dispatch(
45 StackActions.replace("Thread", {
46 environmentId: target.environmentId,
47 threadId: childThreadId,
48 }),
49 );
50 };
51
52 const content = (
53 <ScrollView
54 className="flex-1"
55 // The iOS header is translucent and floats over this view; UIKit has to
56 // inset the content or the first row sits underneath the title.
57 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
58 contentContainerClassName="px-5 pb-6"
59 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
60 >
61 {subagents.length === 0 ? (
62 <Text className="pt-6 text-center text-sm text-foreground-muted">
63 No agents in this turn.
64 </Text>
65 ) : (
66 subagents.map((subagent) => (
67 <AgentRow
68 key={subagent.id}
69 subagent={subagent}
70 tickSeconds={hasLiveAgent}
71 onOpen={openChildThread}
72 />
73 ))
74 )}
75 </ScrollView>
76 );
77
78 if (Platform.OS === "ios") {
79 // A plain formSheet screen never renders a stack header, so it comes from
80 // a nested native stack inside the sheet (same shape as the git sheet).
81 return (
82 <View collapsable={false} className="flex-1 bg-sheet">
83 <ScreenStack style={{ flex: 1 }}>
84 <Screen
85 activityState={2}
86 enabled
87 isNativeStack
88 screenId="thread-agents-sheet-native"
89 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
90 style={{ backgroundColor: theme["--color-sheet"], flex: 1 }}
91 >
92 {content}
93 <ScreenStackHeaderConfig
94 backgroundColor="rgba(0,0,0,0)"
95 color={theme["--color-foreground"]}
96 hideBackButton
97 hideShadow={false}
98 title="Agents"
99 titleColor={theme["--color-foreground"]}
100 titleFontSize={18}
101 titleFontWeight="800"
102 translucent
103 />
104 </Screen>
105 </ScreenStack>
106 </View>
107 );
108 }
109
110 return (
111 <View collapsable={false} className="flex-1 bg-sheet">
112 <AndroidSheetHeader title="Agents" onBack={() => navigation.goBack()} />
113 {content}
114 </View>
115 );
116}
117
118function AgentRow(props: {
119 readonly subagent: OrchestrationV2Subagent;
120 readonly tickSeconds: boolean;
121 readonly onOpen: (childThreadId: ThreadId) => void;
122}) {
123 const { subagent } = props;
124 const presentation = resolveSubagentRowPresentation(subagent);
125 const childThreadId = subagent.childThreadId;
126 const elapsed = useSubagentElapsed(subagent, props.tickSeconds);
127
128 const row = (
129 <View className="min-h-14 flex-row items-center gap-3 border-b border-border py-3">
130 <SubagentStatusDot tone={presentation.tone} placement="sheet" />
131 <View className="min-w-0 flex-1 gap-0.5">
132 <Text className="font-t3-medium text-sm text-foreground" numberOfLines={1}>
133 {presentation.title}
134 </Text>
135 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
136 {presentation.detail ?? presentation.statusLabel}
137 </Text>
138 </View>
139 {elapsed === null ? null : (
140 <Text className="shrink-0 text-2xs tabular-nums text-foreground-muted">{elapsed}</Text>
141 )}
142 {presentation.canOpenThread ? (
143 <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-subtle" />
144 ) : null}
145 </View>
146 );
147
148 if (childThreadId === null) {
149 return (
150 <View
151 accessible
152 accessibilityLabel={`${presentation.title}, ${presentation.statusLabel}`}
153 accessibilityHint="Provider-managed agent. Its work appears in the transcript."
154 >
155 {row}
156 </View>
157 );
158 }
159
160 return (
161 <Pressable
162 accessibilityRole="link"
163 accessibilityLabel={`${presentation.title}, ${presentation.statusLabel}`}
164 accessibilityHint="Opens this agent's thread"
165 onPress={() => props.onOpen(childThreadId)}
166 className="active:opacity-70"
167 >
168 {row}
169 </Pressable>
170 );
171}
172
173/**
174 * Elapsed time for one agent. Only a roster with live work subscribes to the
175 * shared second tick, so a settled sheet never repaints.
176 */
177function useSubagentElapsed(
178 subagent: Pick<OrchestrationV2Subagent, "startedAt" | "completedAt">,
179 tickSeconds: boolean,
180): string | null {
181 const [nowMs, setNowMs] = useState(() => Date.now());
182 const running = subagent.completedAt === null;
183 useEffect(() => {
184 if (!tickSeconds || !running) return;
185 const intervalId = setInterval(() => setNowMs(Date.now()), 1_000);
186 return () => clearInterval(intervalId);
187 }, [running, tickSeconds]);
188 if (subagent.startedAt === null) return null;
189 const startedAtMs = DateTime.toEpochMillis(subagent.startedAt);
190 const endMs =
191 subagent.completedAt === null ? nowMs : DateTime.toEpochMillis(subagent.completedAt);
192 return endMs <= startedAtMs ? null : formatDuration(endMs - startedAtMs);
193}