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