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 { ScreenStack } 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 { environmentThreadDetails } from "../../state/threads";
22import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
23import { NativeHeader, NativeScreen } from "../../native/ThemedScreenStack";
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 turn = useThreadTurnSubagents(target);
50 const subagents = turn?.subagents ?? [];
51 const hasLiveAgent = (turn?.liveCount ?? 0) > 0;
52
53 const openChildThread = (childThreadId: ThreadId) => {
54 void Haptics.selectionAsync();
55 // Replace this leaf sheet so the child enters the workspace stack expected by Home's Back button.
56 navigation.dispatch(
57 StackActions.replace("Thread", {
58 environmentId: target.environmentId,
59 threadId: childThreadId,
60 }),
61 );
62 };
63
64 const content = (
65 <ScrollView
66 nestedScrollEnabled
67 className="flex-1"
68 // UIKit must inset content beneath the floating translucent iOS header.
69 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
70 contentContainerClassName="px-5 pb-6"
71 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
72 >
73 {subagents.length === 0 ? (
74 <Text className="pt-6 text-center text-sm text-foreground-muted">
75 No agents in this turn.
76 </Text>
77 ) : (
78 subagents.map((subagent) => (
79 <AgentRow
80 key={subagent.id}
81 subagent={subagent}
82 environmentId={target.environmentId}
83 tickSeconds={hasLiveAgent}
84 onOpen={openChildThread}
85 />
86 ))
87 )}
88 </ScrollView>
89 );
90
91 if (Platform.OS === "ios") {
92 // Plain formSheets lack stack headers; host one in a nested native stack.
93 return (
94 <View collapsable={false} className="flex-1 bg-sheet">
95 <ScreenStack style={{ flex: 1 }}>
96 <NativeScreen
97 activityState={2}
98 enabled
99 isNativeStack
100 screenId="thread-agents-sheet-native"
101 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
102 className="flex-1 bg-sheet"
103 >
104 {content}
105 <NativeHeader
106 backgroundColor="rgba(0,0,0,0)"
107 tintColorClassName="accent-foreground"
108 hideBackButton
109 hideShadow={false}
110 title="Agents"
111 titleColorClassName="accent-foreground"
112 titleFontSize={18}
113 titleFontWeight="800"
114 translucent
115 />
116 </NativeScreen>
117 </ScreenStack>
118 </View>
119 );
120 }
121
122 return (
123 <View collapsable={false} className="flex-1 bg-sheet">
124 <NativeStackScreenOptions options={{ sheetCornerRadius: 28 }} />
125 <AndroidSheetHeader title="Agents" onBack={() => navigation.goBack()} />
126 <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>
127 </View>
128 );
129}
130
131function AgentRow(props: {
132 readonly environmentId: EnvironmentId;
133 readonly subagent: OrchestrationV2Subagent;
134 readonly tickSeconds: boolean;
135 readonly onOpen: (childThreadId: ThreadId) => void;
136}) {
137 const { subagent } = props;
138 const childThreadId = subagent.childThreadId;
139
140 const row = (
141 <View className="border-b border-border py-3.5">
142 <SubagentRow
143 environmentId={props.environmentId}
144 subagent={subagent}
145 elapsed={<AgentElapsed subagent={subagent} tickSeconds={props.tickSeconds} />}
146 />
147 </View>
148 );
149
150 if (childThreadId === null) {
151 return (
152 <View
153 accessible
154 accessibilityHint="Provider-managed agent. Its work appears in the transcript."
155 >
156 {row}
157 </View>
158 );
159 }
160
161 return (
162 <Pressable
163 accessibilityRole="link"
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
173function AgentElapsed(props: {
174 readonly subagent: OrchestrationV2Subagent;
175 readonly tickSeconds: boolean;
176}) {
177 const elapsed = useSubagentElapsed(props.subagent, props.tickSeconds);
178 return elapsed === null ? null : (
179 <Text className="shrink-0 text-xs tabular-nums text-foreground-muted">{elapsed}</Text>
180 );
181}
182
183function useSubagentElapsed(
184 subagent: Pick<OrchestrationV2Subagent, "status" | "startedAt" | "completedAt">,
185 tickSeconds: boolean,
186): string | null {
187 const [nowMs, setNowMs] = useState(() => Date.now());
188 const running = isOrchestrationV2WorkActive(subagent.status);
189 useEffect(() => {
190 if (!tickSeconds || !running) return;
191 const intervalId = setInterval(() => setNowMs(Date.now()), 1_000);
192 return () => clearInterval(intervalId);
193 }, [running, tickSeconds]);
194 const elapsedMs = deriveSubagentElapsedMs(
195 {
196 status: subagent.status,
197 startedAt: subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt),
198 completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt),
199 },
200 nowMs,
201 );
202 return elapsedMs === null || elapsedMs === 0 ? null : formatDuration(elapsedMs);
203}