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

thread-subagent-group.tsx

210 lines8.5 KB

1import { useAtomValue } from "@effect/atom-react";
2import { StackActions, 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 ServerProvider,
11} from "@t3tools/contracts";
12import { 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 { useEnvironments } from "../../state/environments";
23import { useServerConfigs } from "../../state/entities";
24import { SubagentRow } from "./SubagentRow";
25import { useVisibleSecondClock } from "./use-visible-second-clock";
26import { subagentThreadTarget } from "./threadAgentsPresentation";
27import { WorkLogBlock } from "./work-log-layout";
28​
29import { useOpenThreadInspector } from "./thread-inspector-navigation";
30​
31type SubagentItem = Extract<OrchestrationV2TurnItem, { type: "subagent" }>;
32type AgentTiming = Pick<OrchestrationV2Subagent, "status" | "startedAt" | "completedAt">;
33​
34function SubagentElapsed({ agents }: { readonly agents: ReadonlyArray<AgentTiming> }) {
35 const live = agents.some((agent) => isActiveSubagentStatus(agent.status));
36 const nowMs = useVisibleSecondClock(live);
37 const elapsed = subagentCardElapsed(agents, nowMs);
38 return elapsed ? (
39 <Text className="shrink-0 text-xs tabular-nums text-foreground-muted">{elapsed}</Text>
40 ) : null;
42​
43function SubagentAvatar(props: {
44 readonly item: SubagentItem;
45 readonly provider: ServerProvider | undefined;
46}) {
47 // A remote task's own driver is only a "remote" label.
48 const driver =
49 props.provider?.driver ??
50 (props.item.remoteChild === undefined ? props.item.driver : undefined);
51 return (
52 <View
53 accessible={false}
54 className="h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border bg-card"
55 >
56 {driver === undefined ? (
57 <SymbolView name="sparkles" size={13} tintColorClassName="accent-icon-muted" />
58 ) : (
59 <ProviderIcon provider={driver} iconUrl={props.provider?.iconUrl} size={15} />
60 )}
61 </View>
62 );
64​
65export function ThreadSubagentGroup(props: {
66 readonly activities: ReadonlyArray<ThreadFeedActivity>;
67 readonly environmentId: EnvironmentId;
68 readonly anchorKey: string;
69 readonly expandedRows: Readonly<Record<string, boolean>>;
70 readonly iconSubtleColor: ColorValue;
71 readonly onToggleRow: (rowId: string, anchorKey: string) => void;
72}) {
73 const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId));
74 const navigation = useNavigation();
75 const openInspector = useOpenThreadInspector();
76 const members = props.activities.flatMap(({ projectedItem }) =>
77 projectedItem.item.type === "subagent" ? [projectedItem.item] : [],
78 );
79 const liveAgents = useAtomValue(
80 environmentThreadDetails.threadAtom(scopeThreadRef(props.environmentId, members[0]!.threadId)),
81 (thread) => thread?.projection.subagents,
82 );
83 const { presentationById } = useEnvironments();
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 serverConfigs = useServerConfigs();
102 // A task in a linked environment runs a provider instance of that environment.
103 const providerOf = (item: SubagentItem) =>
104 (item.remoteChild === undefined
105 ? config
106 : serverConfigs.get(item.remoteChild.environmentId)
107 )?.providers.find((provider) => provider.instanceId === item.providerInstanceId);
108 return (
109 <WorkLogBlock>
110 {grouped ? (
111 <Pressable
112 accessibilityRole="button"
113 accessibilityLabel={`${label}, ${summary}`}
114 accessibilityState={{ expanded }}
115 onPress={() => props.onToggleRow(props.anchorKey, props.anchorKey)}
116 className="min-h-14 flex-row items-center gap-3 rounded-lg py-2 active:bg-subtle"
117 >
118 <View className="flex-row items-center">
119 {agents.slice(0, 3).map((agent, index) => (
120 <View key={agent.item.id} style={{ marginLeft: index === 0 ? 0 : -7 }}>
121 <SubagentAvatar item={agent.item} provider={providerOf(agent.item)} />
122 </View>
123 ))}
124 {agents.length > 3 ? (
125 <View className="-ml-2 h-7 w-7 items-center justify-center rounded-full border border-border bg-card">
126 <Text className="text-2xs text-foreground-muted">+{agents.length - 3}</Text>
127 </View>
128 ) : null}
129 </View>
130 <View className="min-w-0 flex-1 gap-0.5">
131 <Text numberOfLines={1} className="font-t3-medium text-sm text-foreground">
132 {label}
133 </Text>
134 <Text
135 numberOfLines={1}
136 className={cn(
137 "text-2xs text-foreground-muted",
138 agents.some((agent) => isActiveSubagentStatus(agent.status))
139 ? "text-adaptive-sky-600-400"
140 : agents.some((agent) => agent.status === "failed") &&
141 "text-adaptive-rose-600-400",
142 )}
143 >
144 {summary}
145 </Text>
146 </View>
147 <SubagentElapsed agents={agents} />
148 <SymbolView
149 name={expanded ? "chevron.up" : "chevron.down"}
150 size={11}
151 tintColor={props.iconSubtleColor}
152 />
153 </Pressable>
154 ) : null}
155 {!grouped || expanded ? (
156 <View className="mb-1 gap-px rounded-xl border border-border bg-card/30 p-1">
157 {agents.map((agent) => {
158 // A task in a linked environment opens there, if this app is connected to it.
159 const target = subagentThreadTarget(agent, props.environmentId, (id) =>
160 presentationById.has(id),
161 );
162 return (
163 <Pressable
164 key={agent.item.id}
165 accessible
166 accessibilityRole={target === null ? undefined : "link"}
167 accessibilityHint={
168 target !== null
169 ? "Opens this agent's thread"
170 : agent.remoteChild !== undefined
171 ? `Runs on ${agent.remoteChild.label}`
172 : "Provider-managed agent"
173 }
174 disabled={target === null}
175 onPress={() => {
176 if (target === null) return;
177 if (
178 openInspector(
179 { environmentId: props.environmentId, threadId: members[0]!.threadId },
180 {
181 type: "thread",
182 environmentId: target.environmentId,
183 threadId: target.threadId,
184 },
185 )
186 )
187 return;
188 navigation.dispatch(
189 StackActions.push("Thread", {
190 environmentId: String(target.environmentId),
191 threadId: String(target.threadId),
192 }),
193 );
194 }}
195 className="rounded-lg px-3 py-3 active:bg-subtle"
196 >
197 <SubagentRow
198 environmentId={props.environmentId}
199 subagent={agent}
200 canOpenRemote={target !== null}
201 elapsed={<SubagentElapsed agents={[agent]} />}
202 />
203 </Pressable>
204 );
205 })}
206 </View>
207 ) : null}
208 </WorkLogBlock>
209 );