The best way to control Claude Code, Codex and more from any computer or phone

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