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

ThreadAgentsSheet.tsx

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