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

thread-subagent-group.tsx

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