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 { useEffect, useState } from "react";
15import { Platform, Pressable, ScrollView, View } from "react-native";
16import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
17import { useSafeAreaInsets } from "react-native-safe-area-context";
18
19import { AndroidSheetHeader } from "../../components/ui/AndroidScreenHeader";
20import { AppText as Text } from "../../components/ui/AppText";
21import { useUniwindTheme } from "../../lib/useUniwindTheme";
22import { environmentThreadDetails } from "../../state/threads";
23import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
24import { SubagentRow } from "./SubagentRow";
25import { ScreenContent } from "../../components/ui/ScreenContent";
26import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
27
28const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
29
30type AgentsTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
31
32const EMPTY_TURN_SUBAGENTS_ATOM = Atom.make<ThreadTurnSubagents | null>(null).pipe(
33 Atom.withLabel("mobile-thread-turn-subagents:empty"),
34);
35
36export function useThreadTurnSubagents(target: AgentsTarget | null): ThreadTurnSubagents | null {
37 return useAtomValue(
38 target === null
39 ? EMPTY_TURN_SUBAGENTS_ATOM
40 : environmentThreadDetails.turnSubagentsAtom(target),
41 );
42}
43
44export function ThreadAgentsSheet({ route }: StaticScreenProps<AgentsTarget>) {
45 const { layout } = useAdaptiveWorkspaceLayout();
46 const target = route.params;
47 const navigation = useNavigation();
48 const insets = useSafeAreaInsets();
49 const theme = useUniwindTheme();
50 const turn = useThreadTurnSubagents(target);
51 const subagents = turn?.subagents ?? [];
52 const hasLiveAgent = (turn?.liveCount ?? 0) > 0;
53
54 const openChildThread = (childThreadId: ThreadId) => {
55 void Haptics.selectionAsync();
56 // Replace rather than push: the sheet is a leaf, and the child thread
57 // belongs in the workspace stack where Home's back button expects it.
58 navigation.dispatch(
59 StackActions.replace("Thread", {
60 environmentId: target.environmentId,
61 threadId: childThreadId,
62 }),
63 );
64 };
65
66 const content = (
67 <ScrollView
68 nestedScrollEnabled
69 className="flex-1"
70 // The iOS header is translucent and floats over this view; UIKit has to
71 // inset the content or the first row sits underneath the title.
72 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
73 contentContainerClassName="px-5 pb-6"
74 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
75 >
76 {subagents.length === 0 ? (
77 <Text className="pt-6 text-center text-sm text-foreground-muted">
78 No agents in this turn.
79 </Text>
80 ) : (
81 subagents.map((subagent) => (
82 <AgentRow
83 key={subagent.id}
84 subagent={subagent}
85 environmentId={target.environmentId}
86 tickSeconds={hasLiveAgent}
87 onOpen={openChildThread}
88 />
89 ))
90 )}
91 </ScrollView>
92 );
93
94 if (Platform.OS === "ios") {
95 // A plain formSheet screen never renders a stack header, so it comes from
96 // a nested native stack inside the sheet (same shape as the git sheet).
97 return (
98 <View collapsable={false} className="flex-1 bg-sheet">
99 <ScreenStack style={{ flex: 1 }}>
100 <Screen
101 activityState={2}
102 enabled
103 isNativeStack
104 screenId="thread-agents-sheet-native"
105 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
106 style={{ backgroundColor: theme["--color-sheet"], flex: 1 }}
107 >
108 {content}
109 <ScreenStackHeaderConfig
110 backgroundColor="rgba(0,0,0,0)"
111 color={theme["--color-foreground"]}
112 hideBackButton
113 hideShadow={false}
114 title="Agents"
115 titleColor={theme["--color-foreground"]}
116 titleFontSize={18}
117 titleFontWeight="800"
118 translucent
119 />
120 </Screen>
121 </ScreenStack>
122 </View>
123 );
124 }
125
126 return (
127 <View collapsable={false} className="flex-1 bg-sheet">
128 <NativeStackScreenOptions options={{ sheetCornerRadius: 28 }} />
129 <AndroidSheetHeader title="Agents" onBack={() => navigation.goBack()} />
130 <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>
131 </View>
132 );
133}
134
135function AgentRow(props: {
136 readonly environmentId: EnvironmentId;
137 readonly subagent: OrchestrationV2Subagent;
138 readonly tickSeconds: boolean;
139 readonly onOpen: (childThreadId: ThreadId) => void;
140}) {
141 const { subagent } = props;
142 const childThreadId = subagent.childThreadId;
143
144 const row = (
145 <View className="border-b border-border py-3.5">
146 <SubagentRow
147 environmentId={props.environmentId}
148 subagent={subagent}
149 elapsed={<AgentElapsed subagent={subagent} tickSeconds={props.tickSeconds} />}
150 />
151 </View>
152 );
153
154 if (childThreadId === null) {
155 return (
156 <View
157 accessible
158 accessibilityHint="Provider-managed agent. Its work appears in the transcript."
159 >
160 {row}
161 </View>
162 );
163 }
164
165 return (
166 <Pressable
167 accessibilityRole="link"
168 accessibilityHint="Opens this agent's thread"
169 onPress={() => props.onOpen(childThreadId)}
170 className="active:opacity-70"
171 >
172 {row}
173 </Pressable>
174 );
175}
176
177function AgentElapsed(props: {
178 readonly subagent: OrchestrationV2Subagent;
179 readonly tickSeconds: boolean;
180}) {
181 const elapsed = useSubagentElapsed(props.subagent, props.tickSeconds);
182 return elapsed === null ? null : (
183 <Text className="shrink-0 text-xs tabular-nums text-foreground-muted">{elapsed}</Text>
184 );
185}
186
187function useSubagentElapsed(
188 subagent: Pick<OrchestrationV2Subagent, "status" | "startedAt" | "completedAt">,
189 tickSeconds: boolean,
190): string | null {
191 const [nowMs, setNowMs] = useState(() => Date.now());
192 const running = isOrchestrationV2WorkActive(subagent.status);
193 useEffect(() => {
194 if (!tickSeconds || !running) return;
195 const intervalId = setInterval(() => setNowMs(Date.now()), 1_000);
196 return () => clearInterval(intervalId);
197 }, [running, tickSeconds]);
198 const elapsedMs = deriveSubagentElapsedMs(
199 {
200 status: subagent.status,
201 startedAt: subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt),
202 completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt),
203 },
204 nowMs,
205 );
206 return elapsedMs === null || elapsedMs === 0 ? null : formatDuration(elapsedMs);
207}