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

threadAgentsPresentation.ts

298 lines9.8 KB

1import { resolveLinkedThreadOpen } from "@t3tools/client-runtime/linked-thread";
2import {
3 formatSubagentDisplayTitle,
4 resolveSubagentMetadata,
5 subagentCardDetail,
6 subagentDetailPreview,
7} from "@t3tools/client-runtime/state/subagent-display";
8import {
9 isActiveSubagentStatus,
10 promptTitle,
11 type RuntimeSubagent,
12 type SubagentWorkflowGroup,
13} from "@t3tools/client-runtime/state/subagentRuntime";
14import { REASONING_EFFORT_OPTION_IDS } from "@t3tools/client-runtime/state/thread-execution";
15import type {
16 EnvironmentId,
17 OrchestrationV2Subagent,
18 ServerProvider,
19 ThreadId,
20} from "@t3tools/contracts";
21import { copySorted } from "@t3tools/shared/Array";
22import { resolveSelectableModel } from "@t3tools/shared/model";
23import { msg } from "gt-react-native";
24​
25import { m, type MessageResolver } from "../../i18n/messages";
26​
27export type SubagentRowTone = "working" | "completed" | "failed" | "stopped";
28​
29export function orderAgentsSheetRows<T extends Pick<OrchestrationV2Subagent, "status">>(
30 subagents: ReadonlyArray<T>,
31): ReadonlyArray<T> {
32 return copySorted(
33 subagents,
34 (left, right) =>
35 Number(isActiveSubagentStatus(right.status)) - Number(isActiveSubagentStatus(left.status)),
36 );
38​
39export interface SubagentRowPresentation {
40 readonly title: string;
41 readonly detail: string | null;
42 readonly statusLabel: string;
43 readonly tone: SubagentRowTone;
44 readonly live: boolean;
45 readonly canOpenThread: boolean;
46 /** The linked environment the task runs in, when it runs in one. */
47 readonly runsOn: string | null;
49​
50export interface SubagentThreadTarget {
51 readonly environmentId: EnvironmentId;
52 readonly threadId: ThreadId;
53 /** Set when the thread is read through the environment that links to it, not opened there. */
54 readonly linked?: { readonly viaEnvironmentId: EnvironmentId; readonly label: string };
56​
57/**
58 * Where an agent's thread opens: here, in the linked environment that runs it when this app is
59 * connected there, or read-only through this environment's link. Once the link is gone a saved
60 * environment opens in place, where the app can reconnect to it; with neither, the read-only view
61 * says what to link again. Null when there is no thread.
62 */
63export function subagentThreadTarget(
64 subagent: Pick<OrchestrationV2Subagent, "childThreadId" | "remoteChild">,
65 environmentId: EnvironmentId,
66 ownConnection: (environmentId: EnvironmentId) => { readonly connected: boolean } | undefined,
67 /** Whether `environmentId` still holds a link to the given environment. */
68 isLinked: (environmentId: EnvironmentId) => boolean,
69): SubagentThreadTarget | null {
70 if (subagent.childThreadId !== null) {
71 return { environmentId, threadId: subagent.childThreadId };
72 }
73 const remote = subagent.remoteChild;
74 if (remote === undefined) return null;
75 const target = { environmentId: remote.environmentId, threadId: remote.threadId };
76 const open = resolveLinkedThreadOpen({
77 environmentId: remote.environmentId,
78 viaEnvironmentId: environmentId,
79 own: ownConnection(remote.environmentId),
80 linked: isLinked(remote.environmentId),
81 });
82 return open === "direct"
83 ? target
84 : { ...target, linked: { viaEnvironmentId: environmentId, label: remote.label } };
86​
87function rowTitle(
88 subagent: Pick<OrchestrationV2Subagent, "title" | "prompt">,
89 resolve: MessageResolver,
90): string {
91 const title = subagent.title?.trim();
92 if (title) return formatSubagentDisplayTitle(title);
93 const prompt = subagent.prompt.trim();
94 if (prompt.length === 0) return resolve(msg("Subagent"));
95 return promptTitle(prompt);
97​
98function rowTone(status: OrchestrationV2Subagent["status"]): SubagentRowTone {
99 if (isActiveSubagentStatus(status)) return "working";
100 if (status === "completed") return "completed";
101 if (status === "failed") return "failed";
102 return "stopped";
104​
105function rowStatusLabel(
106 status: OrchestrationV2Subagent["status"],
107 resolve: MessageResolver,
108): string {
109 switch (status) {
110 case "pending":
111 case "running":
112 return resolve(msg({ context: "agent status" })`Working`);
113 case "waiting":
114 return resolve(msg({ context: "agent status" })`Waiting`);
115 case "idle":
116 return resolve(msg({ context: "agent status" })`Idle`);
117 case "completed":
118 return resolve(msg({ context: "agent status" })`Completed`);
119 case "failed":
120 return resolve(msg({ context: "agent status" })`Failed`);
121 case "cancelled":
122 return resolve(msg({ context: "agent status" })`Cancelled`);
123 case "interrupted":
124 return resolve(msg({ context: "agent status" })`Interrupted`);
125 }
127​
128export function resolveSubagentRowPresentation(
129 subagent: Pick<
130 OrchestrationV2Subagent,
131 "title" | "prompt" | "status" | "progress" | "result" | "childThreadId" | "remoteChild"
132 >,
133 canOpenRemote = false,
134 resolve: MessageResolver = m,
135): SubagentRowPresentation {
136 const live = isActiveSubagentStatus(subagent.status);
137 return {
138 title: rowTitle(subagent, resolve),
139 detail: subagentDetailPreview(subagent),
140 statusLabel: rowStatusLabel(subagent.status, resolve),
141 tone: rowTone(subagent.status),
142 live,
143 canOpenThread:
144 subagent.childThreadId !== null || (subagent.remoteChild !== undefined && canOpenRemote),
145 runsOn: subagent.remoteChild?.label ?? null,
146 };
148​
149export type WorkflowRailTone = SubagentRowTone | "queued";
150​
151export interface WorkflowRailItem {
152 readonly key: string;
153 readonly title: string;
154 readonly members: ReadonlyArray<RuntimeSubagent>;
155 readonly completedCount: number;
156 readonly tone: WorkflowRailTone;
158​
159function railTone(members: ReadonlyArray<RuntimeSubagent>): WorkflowRailTone {
160 if (members.every((member) => member.status === "pending")) return "queued";
161 if (members.some((member) => isActiveSubagentStatus(member.status) || member.status === "idle")) {
162 return "working";
163 }
164 if (members.some((member) => member.status === "failed")) return "failed";
165 return members.every((member) => member.status === "completed") ? "completed" : "stopped";
167​
168export function workflowRail(
169 group: SubagentWorkflowGroup,
170 resolve: MessageResolver = m,
171): ReadonlyArray<WorkflowRailItem> {
172 const items = group.phases.map((phase) => ({
173 key: String(phase.index),
174 title: phase.title,
175 members: phase.members,
176 }));
177 if (group.unphasedMembers.length > 0) {
178 items.push({
179 key: "unphased",
180 title:
181 items.length === 0
182 ? resolve(msg("Agents"))
183 : resolve(msg({ context: "group of agents outside any workflow phase" })`Other`),
184 members: group.unphasedMembers,
185 });
186 }
187 return items.map((item) => ({
188 ...item,
189 completedCount: item.members.filter((member) => member.status === "completed").length,
190 tone: railTone(item.members),
191 }));
193​
194export function nextWorkflowSelection(
195 rail: ReadonlyArray<WorkflowRailItem>,
196 selected: string | null,
197 tapped?: string,
198): string | null {
199 const open = rail.some((item) => item.key === selected) ? selected : null;
200 if (tapped !== undefined) return tapped === open ? null : tapped;
201 if (open !== null) return null;
202 const filled = rail.filter((item) => item.members.length > 0);
203 return (
204 (
205 filled.find((item) => item.tone === "working") ??
206 filled.find((item) => item.tone === "failed") ??
207 filled.at(-1)
208 )?.key ?? null
209 );
211​
212function capitalize(value: string): string {
213 return value.charAt(0).toUpperCase() + value.slice(1);
215​
216export function workflowMemberMetadata(
217 member: Pick<RuntimeSubagent, "model" | "effort" | "speed">,
218 provider: Pick<ServerProvider, "driver" | "models"> | undefined,
219 resolve: MessageResolver = m,
220) {
221 const model = member.model?.trim()
222 ? resolveSubagentMetadata({ model: member.model, provider }, resolve).modelLabel
223 : null;
224 const slug = provider
225 ? resolveSelectableModel(provider.driver, member.model, provider.models)
226 : null;
227 const effortChoice = provider?.models
228 .find((candidate) => candidate.slug === slug)
229 ?.capabilities?.optionDescriptors?.flatMap((descriptor) =>
230 descriptor.type === "select" &&
231 (descriptor.role === "reasoning" || REASONING_EFFORT_OPTION_IDS.includes(descriptor.id))
232 ? descriptor.options
233 : [],
234 )
235 .find((option) => option.id === member.effort);
236 return {
237 model,
238 effort: member.effort ? (effortChoice?.label ?? capitalize(member.effort)) : null,
239 speed: member.speed ? capitalize(member.speed) : null,
240 fast: member.speed === "fast",
241 };
243​
244export function workflowMemberDetail(
245 member: Pick<RuntimeSubagent, "status" | "progress" | "result" | "error">,
246) {
247 return {
248 detail: subagentCardDetail(subagentDetailPreview(member)),
249 error: member.status === "failed" ? subagentCardDetail(member.error) : null,
250 };
252​
253export function resolveSubagentStopTarget(
254 subagent: Pick<
255 OrchestrationV2Subagent,
256 | "id"
257 | "threadId"
258 | "childThreadId"
259 | "status"
260 | "origin"
261 | "driver"
262 | "runId"
263 | "nativeTaskRef"
264 | "workflow"
265 >,
266) {
267 if (!isActiveSubagentStatus(subagent.status)) return null;
268 if (subagent.workflow !== undefined) {
269 return subagent.status === "running" &&
270 subagent.origin === "provider_native" &&
271 subagent.driver === "claudeAgent" &&
272 Boolean(subagent.nativeTaskRef?.nativeId)
273 ? {
274 kind: "workflow" as const,
275 input: { threadId: subagent.threadId, subagentId: subagent.id },
276 }
277 : null;
278 }
279 if (subagent.origin === "app_owned" && subagent.childThreadId !== null) {
280 return {
281 kind: "subagent" as const,
282 input: { threadId: subagent.threadId, subagentId: subagent.id },
283 };
284 }
285 if (
286 subagent.origin === "provider_native" &&
287 subagent.driver === "claudeAgent" &&
288 subagent.runId !== null &&
289 subagent.nativeTaskRef?.strength === "strong" &&
290 subagent.nativeTaskRef.nativeId !== null
291 ) {
292 return {
293 kind: "subagent" as const,
294 input: { threadId: subagent.threadId, subagentId: subagent.id },
295 };
296 }
297 return null;