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