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

ThreadAgentsSheet.tsx

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