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

thread-subagent-group.tsx

193 lines7.8 KB

1import { useAtomValue } from "@effect/atom-react";
2import { StackActions, useIsFocused, useNavigation } from "@react-navigation/native";
3import { scopeThreadRef } from "@t3tools/client-runtime/environment";
4import { summarizeSubagentStatuses } from "@t3tools/client-runtime/state/subagent-display";
5import { isActiveSubagentStatus } from "@t3tools/client-runtime/state/subagentRuntime";
6import type {
7 EnvironmentId,
8 OrchestrationV2Subagent,
9 OrchestrationV2TurnItem,
10} from "@t3tools/contracts";
11import { useEffect, useState } from "react";
12import { AppState, Pressable, View, type ColorValue } from "react-native";
13​
14import { AppText as Text } from "../../components/ui/AppText";
15import { SymbolView } from "../../components/ui/AppSymbol";
16import { ProviderIcon } from "../../components/ProviderIcon";
17import { cn } from "../../lib/cn";
18import type { ThreadFeedActivity } from "../../lib/threadActivity";
19import { serverEnvironment } from "../../state/server";
20import { environmentThreadDetails } from "../../state/threads";
21import { subagentCardElapsed } from "./subagent-card-presentation";
22import { SubagentRow } from "./SubagentRow";
23import { WorkLogBlock } from "./work-log-layout";
24​
25import { useOpenThreadInspector } from "./thread-inspector-navigation";
26​
27type SubagentItem = Extract<OrchestrationV2TurnItem, { type: "subagent" }>;
28type AgentTiming = Pick<OrchestrationV2Subagent, "status" | "startedAt" | "completedAt">;
29​
30function SubagentElapsed({ agents }: { readonly agents: ReadonlyArray<AgentTiming> }) {
31 const focused = useIsFocused();
32 const live = agents.some((agent) => isActiveSubagentStatus(agent.status));
33 const [nowMs, setNowMs] = useState(() => Date.now());
34 const [appActive, setAppActive] = useState(() => AppState.currentState === "active");
35 useEffect(() => {
36 const subscription = AppState.addEventListener("change", (state) =>
37 setAppActive(state === "active"),
38 );
39 return () => subscription.remove();
40 }, []);
41 useEffect(() => {
42 if (!live || !focused || !appActive) return;
43 const intervalId = setInterval(() => setNowMs(Date.now()), 1_000);
44 return () => clearInterval(intervalId);
45 }, [appActive, focused, live]);
46 const elapsed = subagentCardElapsed(agents, nowMs);
47 return elapsed ? (
48 <Text className="shrink-0 text-xs tabular-nums text-foreground-muted">{elapsed}</Text>
49 ) : null;
51​
52function SubagentAvatar(props: {
53 readonly item: SubagentItem;
54 readonly iconUrl?: string | null | undefined;
55}) {
56 return (
57 <View
58 accessible={false}
59 className="h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border bg-card"
60 >
61 <ProviderIcon provider={props.item.driver} iconUrl={props.iconUrl} size={15} />
62 </View>
63 );
65​
66export function ThreadSubagentGroup(props: {
67 readonly activities: ReadonlyArray<ThreadFeedActivity>;
68 readonly environmentId: EnvironmentId;
69 readonly anchorKey: string;
70 readonly expandedRows: Readonly<Record<string, boolean>>;
71 readonly iconSubtleColor: ColorValue;
72 readonly onToggleRow: (rowId: string, anchorKey: string) => void;
73}) {
74 const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId));
75 const navigation = useNavigation();
76 const openInspector = useOpenThreadInspector();
77 const members = props.activities.flatMap(({ projectedItem }) =>
78 projectedItem.item.type === "subagent" ? [projectedItem.item] : [],
79 );
80 const liveAgents = useAtomValue(
81 environmentThreadDetails.threadAtom(scopeThreadRef(props.environmentId, members[0]!.threadId)),
82 (thread) => thread?.projection.subagents,
83 );
84 const agents = members.map((item) => {
85 const live = liveAgents?.find((agent) => agent.id === item.subagentId);
86 return {
87 ...item,
88 item,
89 status: live?.status ?? item.status,
90 startedAt: live?.startedAt ?? item.startedAt,
91 completedAt: live?.completedAt ?? item.completedAt,
92 result: live?.result ?? item.result,
93 progress: live?.progress ?? item.progress,
94 model: live?.model ?? null,
95 };
96 });
97 const grouped = agents.length > 1;
98 const label = `${agents.length} subagents`;
99 const summary = summarizeSubagentStatuses(agents.map((agent) => agent.status));
100 const expanded = props.expandedRows[props.anchorKey] ?? false;
101 const iconUrl = (item: SubagentItem) =>
102 config?.providers.find((provider) => provider.instanceId === item.providerInstanceId)?.iconUrl;
103 return (
104 <WorkLogBlock>
105 {grouped ? (
106 <Pressable
107 accessibilityRole="button"
108 accessibilityLabel={`${label}, ${summary}`}
109 accessibilityState={{ expanded }}
110 onPress={() => props.onToggleRow(props.anchorKey, props.anchorKey)}
111 className="min-h-14 flex-row items-center gap-3 rounded-lg py-2 active:bg-subtle"
112 >
113 <View className="flex-row items-center">
114 {agents.slice(0, 3).map((agent, index) => (
115 <View key={agent.item.id} style={{ marginLeft: index === 0 ? 0 : -7 }}>
116 <SubagentAvatar item={agent.item} iconUrl={iconUrl(agent.item)} />
117 </View>
118 ))}
119 {agents.length > 3 ? (
120 <View className="-ml-2 h-7 w-7 items-center justify-center rounded-full border border-border bg-card">
121 <Text className="text-2xs text-foreground-muted">+{agents.length - 3}</Text>
122 </View>
123 ) : null}
124 </View>
125 <View className="min-w-0 flex-1 gap-0.5">
126 <Text numberOfLines={1} className="font-t3-medium text-sm text-foreground">
127 {label}
128 </Text>
129 <Text
130 numberOfLines={1}
131 className={cn(
132 "text-2xs text-foreground-muted",
133 agents.some((agent) => isActiveSubagentStatus(agent.status))
134 ? "text-adaptive-sky-600-400"
135 : agents.some((agent) => agent.status === "failed") &&
136 "text-adaptive-rose-600-400",
137 )}
138 >
139 {summary}
140 </Text>
141 </View>
142 <SubagentElapsed agents={agents} />
143 <SymbolView
144 name={expanded ? "chevron.up" : "chevron.down"}
145 size={11}
146 tintColor={props.iconSubtleColor}
147 />
148 </Pressable>
149 ) : null}
150 {!grouped || expanded ? (
151 <View className="mb-1 gap-px rounded-xl border border-border bg-card/30 p-1">
152 {agents.map((agent) => {
153 const threadId = agent.childThreadId;
154 return (
155 <Pressable
156 key={agent.item.id}
157 accessible
158 accessibilityRole={threadId === null ? undefined : "link"}
159 accessibilityHint={
160 threadId === null ? "Provider-managed agent" : "Opens this agent's thread"
161 }
162 disabled={threadId === null}
163 onPress={() => {
164 if (threadId === null) return;
165 if (
166 openInspector(
167 { environmentId: props.environmentId, threadId: members[0]!.threadId },
168 { type: "thread", environmentId: props.environmentId, threadId },
169 )
170 )
171 return;
172 navigation.dispatch(
173 StackActions.push("Thread", {
174 environmentId: String(props.environmentId),
175 threadId: String(threadId),
176 }),
177 );
178 }}
179 className="rounded-lg px-3 py-3 active:bg-subtle"
180 >
181 <SubagentRow
182 environmentId={props.environmentId}
183 subagent={agent}
184 elapsed={<SubagentElapsed agents={[agent]} />}
185 />
186 </Pressable>
187 );
188 })}
189 </View>
190 ) : null}
191 </WorkLogBlock>
192 );