Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadAgentsSheet.tsx

255 lines8.7 KB

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