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

thread-subagent-group.tsx

271 lines10.8 KB

1import { useAtomValue } from "@effect/atom-react";
2import { useGT, useMessages, plural, part } from "gt-react-native";
3import { StackActions, useNavigation } from "@react-navigation/native";
4import { scopeThreadRef } from "@t3tools/client-runtime/environment";
5import {
6 resolveProviderInstanceDisplayName,
7 shouldShowInstanceBadge,
8} from "@t3tools/client-runtime/state/provider-instance-display";
9import { summarizeSubagentStatuses } from "@t3tools/client-runtime/state/subagent-display";
10import { isActiveSubagentStatus } from "@t3tools/client-runtime/state/subagentRuntime";
11import type {
12 EnvironmentId,
13 OrchestrationV2Subagent,
14 OrchestrationV2TurnItem,
15 ServerConfig,
16} from "@t3tools/contracts";
17import { Pressable, View, type ColorValue } from "react-native";
18​
19import { AppText as Text } from "../../components/ui/AppText";
20import { SymbolView } from "../../components/ui/AppSymbol";
21import { ProviderIcon, ProviderInstanceIcon } from "../../components/ProviderIcon";
22import { cn } from "../../lib/cn";
23import type { ThreadFeedActivity } from "../../lib/threadActivity";
24import { serverEnvironment } from "../../state/server";
25import { environmentThreadDetails } from "../../state/threads";
26import { subagentCardElapsed } from "./subagent-card-presentation";
27import { useServerConfigs } from "../../state/entities";
28import { SubagentRow } from "./SubagentRow";
29import { useVisibleSecondClock } from "./use-visible-second-clock";
30import { subagentThreadTarget } from "./threadAgentsPresentation";
31import { useLinkedThreadReach } from "../../state/linkedThread";
32import { WorkLogBlock } from "./work-log-layout";
33​
34import { useOpenThreadInspector } from "./thread-inspector-navigation";
35import { useOpenLinkedThreadRead } from "./useOpenLinkedThread";
36​
37type SubagentItem = Extract<OrchestrationV2TurnItem, { type: "subagent" }>;
38type AgentTiming = Pick<OrchestrationV2Subagent, "status" | "startedAt" | "completedAt">;
39​
40function SubagentElapsed({ agents }: { readonly agents: ReadonlyArray<AgentTiming> }) {
41 const live = agents.some((agent) => isActiveSubagentStatus(agent.status));
42 const nowMs = useVisibleSecondClock(live);
43 const messages = useMessages();
44 const elapsed = subagentCardElapsed(agents, nowMs, messages);
45 return elapsed ? (
46 <Text className="shrink-0 text-xs tabular-nums text-foreground-muted">{elapsed}</Text>
47 ) : null;
49​
50function SubagentAvatar(props: {
51 readonly item: SubagentItem;
52 readonly config: ServerConfig | null | undefined;
53}) {
54 const providers = props.config?.providers ?? [];
55 const provider = providers.find(
56 (candidate) => candidate.instanceId === props.item.providerInstanceId,
57 );
58 // A remote task's own driver is only a "remote" label.
59 const driver =
60 provider?.driver ?? (props.item.remoteChild === undefined ? props.item.driver : undefined);
61 const badgeEntries = providers.map((candidate) => {
62 const rawConfig = props.config?.settings.providerInstances[candidate.instanceId]?.config;
63 const instanceConfig =
64 rawConfig !== null && typeof rawConfig === "object"
65 ? (rawConfig as Readonly<Record<string, unknown>>)
66 : null;
67 const agentId = instanceConfig?.source === "local" ? undefined : instanceConfig?.agentId;
68 return {
69 ...candidate,
70 driverKind: candidate.driver,
71 acpRegistryAgentId: typeof agentId === "string" ? agentId.trim() || undefined : undefined,
72 };
73 });
74 const badgeEntry = badgeEntries.find(
75 (candidate) => candidate.instanceId === props.item.providerInstanceId,
76 );
77 const showBadge =
78 provider !== undefined &&
79 badgeEntry !== undefined &&
80 shouldShowInstanceBadge(badgeEntry, badgeEntries);
81 return (
82 <View
83 accessible={false}
84 className="h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border bg-card"
85 >
86 {showBadge ? (
87 <ProviderInstanceIcon
88 provider={provider.driver}
89 iconUrl={provider.iconUrl}
90 size={15}
91 displayName={resolveProviderInstanceDisplayName(provider)}
92 accentColor={provider.accentColor}
93 showBadge
94 />
95 ) : driver === undefined ? (
96 <SymbolView name="robot" size={13} tintColorClassName="accent-icon-muted" />
97 ) : (
98 <ProviderIcon provider={driver} iconUrl={provider?.iconUrl} size={15} />
99 )}
100 </View>
101 );
103​
104export function ThreadSubagentGroup(props: {
105 readonly activities: ReadonlyArray<ThreadFeedActivity>;
106 readonly environmentId: EnvironmentId;
107 readonly anchorKey: string;
108 readonly expandedRows: Readonly<Record<string, boolean>>;
109 readonly iconSubtleColor: ColorValue;
110 readonly onToggleRow: (rowId: string, anchorKey: string) => void;
111}) {
112 const gt = useGT();
113 const messages = useMessages();
114 const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId));
115 const navigation = useNavigation();
116 const openInspector = useOpenThreadInspector();
117 const openLinkedRead = useOpenLinkedThreadRead();
118 const members = props.activities.flatMap(({ projectedItem }) =>
119 projectedItem.item.type === "subagent" ? [projectedItem.item] : [],
120 );
121 const liveAgents = useAtomValue(
122 environmentThreadDetails.threadAtom(scopeThreadRef(props.environmentId, members[0]!.threadId)),
123 (thread) => thread?.projection.subagents,
124 );
125 const agents = members.map((item) => {
126 const live = liveAgents?.find((agent) => agent.id === item.subagentId);
127 return {
128 ...item,
129 item,
130 status: live?.status ?? item.status,
131 startedAt: live?.startedAt ?? item.startedAt,
132 completedAt: live?.completedAt ?? item.completedAt,
133 result: live?.result ?? item.result,
134 progress: live?.progress ?? item.progress,
135 model: live?.model ?? null,
136 modelSelection: live?.modelSelection,
137 };
138 });
139 const reach = useLinkedThreadReach(props.environmentId, agents);
140 const grouped = agents.length > 1;
141 const label = gt`${plural(
142 { count: agents.length },
143 {
144 one: part`${{ count: agents.length }} subagent`,
145 other: part`${{ count: agents.length }} subagents`,
146 },
147 )}`;
148 const summary = summarizeSubagentStatuses(
149 agents.map((agent) => agent.status),
150 messages,
151 );
152 const expanded = props.expandedRows[props.anchorKey] ?? false;
153 const serverConfigs = useServerConfigs();
154 // A task in a linked environment runs a provider instance of that environment.
155 const configOf = (item: SubagentItem) =>
156 item.remoteChild === undefined ? config : serverConfigs.get(item.remoteChild.environmentId);
157 return (
158 <WorkLogBlock>
159 {grouped ? (
160 <Pressable
161 accessibilityRole="button"
162 accessibilityLabel={gt`${{ label }}, ${{ summary }}`}
163 accessibilityState={{ expanded }}
164 onPress={() => props.onToggleRow(props.anchorKey, props.anchorKey)}
165 className="min-h-14 flex-row items-center gap-3 rounded-lg py-2 active:bg-subtle"
166 >
167 <View className="flex-row items-center">
168 {agents.slice(0, 3).map((agent, index) => (
169 <View key={agent.item.id} style={{ marginLeft: index === 0 ? 0 : -7 }}>
170 <SubagentAvatar item={agent.item} config={configOf(agent.item)} />
171 </View>
172 ))}
173 {agents.length > 3 ? (
174 <View className="-ml-2 h-7 w-7 items-center justify-center rounded-full border border-border bg-card">
175 <Text className="text-2xs text-foreground-muted">+{agents.length - 3}</Text>
176 </View>
177 ) : null}
178 </View>
179 <View className="min-w-0 flex-1 gap-0.5">
180 <Text numberOfLines={1} className="font-t3-medium text-sm text-foreground">
181 {label}
182 </Text>
183 <Text
184 numberOfLines={1}
185 className={cn(
186 "text-2xs text-foreground-muted",
187 agents.some((agent) => isActiveSubagentStatus(agent.status))
188 ? "text-adaptive-sky-600-400"
189 : agents.some((agent) => agent.status === "failed") &&
190 "text-adaptive-rose-600-400",
191 )}
192 >
193 {summary}
194 </Text>
195 </View>
196 <SubagentElapsed agents={agents} />
197 <SymbolView
198 name={expanded ? "chevron.up" : "chevron.down"}
199 size={11}
200 tintColor={props.iconSubtleColor}
201 />
202 </Pressable>
203 ) : null}
204 {!grouped || expanded ? (
205 <View className="mb-1 gap-px rounded-xl border border-border bg-card/30 p-1">
206 {agents.map((agent) => {
207 // A task in a linked environment opens there, if this app is connected to it.
208 const target = subagentThreadTarget(
209 agent,
210 props.environmentId,
211 reach.ownConnection,
212 reach.isLinked,
213 );
214 return (
215 <Pressable
216 key={agent.item.id}
217 accessible
218 accessibilityRole={target === null ? undefined : "link"}
219 accessibilityHint={
220 target === null
221 ? gt`Provider-managed agent`
222 : target.linked === undefined
223 ? gt`Opens this agent's thread`
224 : gt`Opens a read-only view of this agent's thread on ${{ label: target.linked.label }}`
225 }
226 disabled={target === null}
227 onPress={() => {
228 if (target === null) return;
229 if (target.linked !== undefined) {
230 openLinkedRead(target, target.linked, agent.title, {
231 source: {
232 environmentId: props.environmentId,
233 threadId: members[0]!.threadId,
234 },
235 });
236 return;
237 }
238 if (
239 openInspector(
240 { environmentId: props.environmentId, threadId: members[0]!.threadId },
241 {
242 type: "thread",
243 environmentId: target.environmentId,
244 threadId: target.threadId,
245 },
246 )
247 )
248 return;
249 navigation.dispatch(
250 StackActions.push("Thread", {
251 environmentId: String(target.environmentId),
252 threadId: String(target.threadId),
253 }),
254 );
255 }}
256 className="rounded-lg px-3 py-3 active:bg-subtle"
257 >
258 <SubagentRow
259 environmentId={props.environmentId}
260 subagent={agent}
261 canOpenRemote={target !== null}
262 elapsed={<SubagentElapsed agents={[agent]} />}
263 />
264 </Pressable>
265 );
266 })}
267 </View>
268 ) : null}
269 </WorkLogBlock>
270 );