Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { ThreadTurnSubagents } from "@t3tools/client-runtime/state/thread-subagents";
3import {
4 isOrchestrationV2WorkActive,
5 type EnvironmentId,
6 type OrchestrationV2Subagent,
7 type ThreadId,
8} from "@t3tools/contracts";
9import { deriveSubagentElapsedMs, formatDuration } from "@t3tools/shared/orchestrationTiming";
10import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
11import * as DateTime from "effect/DateTime";
12import { Atom } from "effect/reactivity";
13import * as Haptics from "expo-haptics";
14import { Platform, Pressable, ScrollView, View } from "react-native";
15import { ScreenStack } from "react-native-screens";
16import { useSafeAreaInsets } from "react-native-safe-area-context";
17
18import { AndroidSheetHeader } from "../../components/ui/AndroidScreenHeader";
19import { AppText as Text } from "../../components/ui/AppText";
20import { environmentThreadDetails } from "../../state/threads";
21import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
22import { NativeHeader, NativeScreen } from "../../native/ThemedScreenStack";
23import { useEnvironments } from "../../state/environments";
24import { SubagentRow } from "./SubagentRow";
25import { useVisibleSecondClock } from "./use-visible-second-clock";
26import { ScreenContent } from "../../components/ui/ScreenContent";
27import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
28import { subagentThreadTarget } from "./threadAgentsPresentation";
29
30import { useOpenThreadInspector } from "./thread-inspector-navigation";
31
32const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
33
34type AgentsTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
35
36const EMPTY_TURN_SUBAGENTS_ATOM = Atom.make<ThreadTurnSubagents | null>(null).pipe(
37 Atom.withLabel("mobile-thread-turn-subagents:empty"),
38);
39
40export function useThreadTurnSubagents(target: AgentsTarget | null): ThreadTurnSubagents | null {
41 return useAtomValue(
42 target === null
43 ? EMPTY_TURN_SUBAGENTS_ATOM
44 : environmentThreadDetails.turnSubagentsAtom(target),
45 );
46}
47
48export function ThreadAgentsSheet({ route }: StaticScreenProps<AgentsTarget>) {
49 const { layout } = useAdaptiveWorkspaceLayout();
50 const target = route.params;
51 const navigation = useNavigation();
52 const openInspector = useOpenThreadInspector();
53 const insets = useSafeAreaInsets();
54 const turn = useThreadTurnSubagents(target);
55 const subagents = turn?.subagents ?? [];
56 const hasLiveAgent = (turn?.liveCount ?? 0) > 0;
57
58 const openChildThread = (child: { environmentId: EnvironmentId; threadId: ThreadId }) => {
59 void Haptics.selectionAsync();
60 if (
61 openInspector(target, {
62 type: "thread",
63 environmentId: child.environmentId,
64 threadId: child.threadId,
65 })
66 )
67 return;
68 // Replace this leaf sheet so the child enters the workspace stack expected by Home's Back button.
69 navigation.dispatch(
70 StackActions.replace("Thread", {
71 environmentId: child.environmentId,
72 threadId: child.threadId,
73 }),
74 );
75 };
76
77 const content = (
78 <ScrollView
79 nestedScrollEnabled
80 className="flex-1"
81 // UIKit must inset content beneath the floating translucent iOS header.
82 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
83 contentContainerClassName="px-5 pb-6"
84 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
85 >
86 {subagents.length === 0 ? (
87 <Text className="pt-6 text-center text-sm text-foreground-muted">
88 No agents in this turn.
89 </Text>
90 ) : (
91 subagents.map((subagent) => (
92 <AgentRow
93 key={subagent.id}
94 subagent={subagent}
95 environmentId={target.environmentId}
96 tickSeconds={hasLiveAgent}
97 onOpen={openChildThread}
98 />
99 ))
100 )}
101 </ScrollView>
102 );
103
104 if (Platform.OS === "ios") {
105 // Plain formSheets lack stack headers; host one in a nested native stack.
106 return (
107 <View collapsable={false} className="flex-1 bg-sheet">
108 <ScreenStack style={{ flex: 1 }}>
109 <NativeScreen
110 activityState={2}
111 enabled
112 isNativeStack
113 screenId="thread-agents-sheet-native"
114 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
115 className="flex-1 bg-sheet"
116 >
117 {content}
118 <NativeHeader
119 backgroundColor="rgba(0,0,0,0)"
120 tintColorClassName="accent-foreground"
121 hideBackButton
122 hideShadow={false}
123 title="Agents"
124 titleColorClassName="accent-foreground"
125 titleFontSize={18}
126 titleFontWeight="800"
127 translucent
128 />
129 </NativeScreen>
130 </ScreenStack>
131 </View>
132 );
133 }
134
135 return (
136 <View collapsable={false} className="flex-1 bg-sheet">
137 <NativeStackScreenOptions options={{ sheetCornerRadius: 28 }} />
138 <AndroidSheetHeader title="Agents" onBack={() => navigation.goBack()} />
139 <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>
140 </View>
141 );
142}
143
144function AgentRow(props: {
145 readonly environmentId: EnvironmentId;
146 readonly subagent: OrchestrationV2Subagent;
147 readonly tickSeconds: boolean;
148 readonly onOpen: (child: { environmentId: EnvironmentId; threadId: ThreadId }) => void;
149}) {
150 const { subagent } = props;
151 const { presentationById } = useEnvironments();
152 const target = subagentThreadTarget(subagent, props.environmentId, (id) =>
153 presentationById.has(id),
154 );
155
156 const row = (
157 <View className="border-b border-border py-3.5">
158 <SubagentRow
159 environmentId={props.environmentId}
160 subagent={subagent}
161 canOpenRemote={target !== null}
162 elapsed={<AgentElapsed subagent={subagent} tickSeconds={props.tickSeconds} />}
163 />
164 </View>
165 );
166
167 if (target === null) {
168 return (
169 <View
170 accessible
171 accessibilityHint={
172 subagent.remoteChild === undefined
173 ? "Provider-managed agent. Its work appears in the transcript."
174 : `Runs on ${subagent.remoteChild.label}. Connect to it to open its thread.`
175 }
176 >
177 {row}
178 </View>
179 );
180 }
181
182 return (
183 <Pressable
184 accessibilityRole="link"
185 accessibilityHint="Opens this agent's thread"
186 onPress={() => props.onOpen(target)}
187 className="active:opacity-70"
188 >
189 {row}
190 </Pressable>
191 );
192}
193
194function AgentElapsed(props: {
195 readonly subagent: OrchestrationV2Subagent;
196 readonly tickSeconds: boolean;
197}) {
198 const elapsed = useSubagentElapsed(props.subagent, props.tickSeconds);
199 return elapsed === null ? null : (
200 <Text className="shrink-0 text-xs tabular-nums text-foreground-muted">{elapsed}</Text>
201 );
202}
203
204function useSubagentElapsed(
205 subagent: Pick<OrchestrationV2Subagent, "status" | "startedAt" | "completedAt">,
206 tickSeconds: boolean,
207): string | null {
208 const running = isOrchestrationV2WorkActive(subagent.status);
209 const nowMs = useVisibleSecondClock(tickSeconds && running);
210 const elapsedMs = deriveSubagentElapsedMs(
211 {
212 status: subagent.status,
213 startedAt: subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt),
214 completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt),
215 },
216 nowMs,
217 );
218 return elapsedMs === null || elapsedMs === 0 ? null : formatDuration(elapsedMs);
219}