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

thread-subagent-group.tsx

235 lines9.6 KB

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