1import { describe, expect, it } from "vite-plus/test";
2import {
3 ProviderDriverKind,
4 ProviderInstanceId,
5 ThreadId,
6 type OrchestrationV2Subagent,
7 type OrchestrationV2SubagentWorkflow,
8} from "@t3tools/contracts";
9import * as DateTime from "effect/DateTime";
10β
11import {
12 deriveWorkflowGroups,
13 isWorkflowScriptMessage,
14 projectedSubagentsToRuntime,
15 resolveWorkflowOpening,
16 workflowMemberModelSelection,
17} from "./subagentRuntime.ts";
18import { resolveSubagentMetadata } from "./subagentDisplay.ts";
19import { formatSubagentEffort } from "./threadExecution.ts";
20β
21const at = (iso: string) => DateTime.makeUnsafe(iso);
22β
23type ProjectedSubagent = Parameters<typeof projectedSubagentsToRuntime>[0][number];
24β
25function subagent(overrides: Partial<ProjectedSubagent> = {}): ProjectedSubagent {
26 return {
27 id: "coordinator",
28 title: "probe",
29 prompt: "export const meta = β¦",
30 model: "claude-opus-5[1m]",
31 status: "running" satisfies OrchestrationV2Subagent["status"],
32 result: null,
33 startedAt: at("2026-08-01T10:00:00.000Z"),
34 completedAt: null,
35 updatedAt: at("2026-08-01T10:00:05.000Z"),
36 ...overrides,
37 };
38}
39β
40const member = (
41 overrides: Partial<OrchestrationV2SubagentWorkflow["agents"][number]> = {},
42): OrchestrationV2SubagentWorkflow["agents"][number] => ({
43 index: 1,
44 label: "alpha:one",
45 state: "running",
46 phaseIndex: 1,
47 phaseTitle: "Alpha",
48 ...overrides,
49});
50β
51const groupsOf = (subagents: ReadonlyArray<ProjectedSubagent>) =>
52 deriveWorkflowGroups(projectedSubagentsToRuntime(subagents));
53β
54describe("projectedSubagentsToRuntime workflow expansion", () => {
55 it("uses a settled member's wall-clock completion separately from its execution duration", () => {
56 const [, settled] = projectedSubagentsToRuntime([
57 subagent({
58 status: "completed",
59 completedAt: at("2026-08-01T10:00:09.000Z"),
60 workflow: {
61 phases: [],
62 agents: [
63 member({
64 state: "completed",
65 model: "claude-opus-5[1m]",
66 effort: "xhigh",
67 speed: "standard",
68 startedAt: Date.UTC(2026, 7, 1, 10, 0, 0),
69 durationMs: 1500,
70 completedAt: Date.UTC(2026, 7, 1, 10, 0, 4, 432),
71 totalTokens: 71_141,
72 toolCalls: 3,
73 prompt: "Reply with exactly: A1",
74 result: "A1",
75 }),
76 ],
77 },
78 }),
79 ]);
80 expect(settled?.status).toBe("completed");
81 expect(settled?.completedAt).toBe("2026-08-01T10:00:04.432Z");
82 expect(settled?.result).toBe("A1");
83 expect(settled?.model).toBe("claude-opus-5[1m]");
84 expect(settled?.effort).toBe("xhigh");
85 expect(settled?.speed).toBe("standard");
86 expect(settled?.progress).toBe("Reply with exactly: A1");
87 expect(settled?.usage).toEqual({ totalTokens: 71_141, toolUses: 3, durationMs: 1500 });
88 const instanceId = ProviderInstanceId.make("claudeAgent");
89 expect(workflowMemberModelSelection(settled!, instanceId)).toEqual({
90 instanceId,
91 model: "claude-opus-5[1m]",
92 options: [
93 { id: "effort", value: "xhigh" },
94 { id: "fastMode", value: false },
95 ],
96 });
97 expect(workflowMemberModelSelection({ model: null, effort: "xhigh" }, instanceId)).toBe(
98 undefined,
99 );
100 const provider = {
101 driver: ProviderDriverKind.make("claudeAgent"),
102 models: [
103 { slug: "claude-opus-5", name: "Claude Opus 5", isCustom: false, capabilities: null },
104 ],
105 };
106 const modelSelection = workflowMemberModelSelection(settled!, instanceId);
107 const { modelSlug } = resolveSubagentMetadata({
108 model: settled!.model,
109 modelSelection,
110 provider,
111 });
112 expect(formatSubagentEffort({ modelSlug, modelSelection, provider })).toBe("xhigh");
113 });
114β
115 it("names a workflow by the model it runs on when the provider reports none", () => {
116 const [workflow] = projectedSubagentsToRuntime([subagent({ model: null })]);
117 expect(
118 resolveSubagentMetadata({
119 model: workflow!.model,
120 modelSelection: { model: "claude-opus-5-5" },
121 }).modelLabel,
122 ).toBe("Claude Opus 5.5");
123 expect(resolveSubagentMetadata({ model: workflow!.model }).modelLabel).toBe("Not reported");
124 });
125β
126 it.each(["completed", "cancelled", "failed"] as const)(
127 "settles unfinished members when the coordinator is %s",
128 (status) => {
129 const groups = groupsOf([
130 subagent({
131 status,
132 completedAt: at("2026-08-01T10:00:09.000Z"),
133 workflow: {
134 phases: [],
135 agents: [
136 member(),
137 member({ index: 2, state: "queued" }),
138 member({
139 index: 3,
140 state: "completed",
141 startedAt: Date.UTC(2026, 7, 1, 10, 0, 0),
142 durationMs: 1500,
143 }),
144 ],
145 },
146 }),
147 ]);
148 expect(groups[0]?.workflow.status).toBe(status);
149 const members = groups[0]?.phases.flatMap((phase) => phase.members);
150 expect(members?.map((agent) => agent.status)).toEqual([status, status, "completed"]);
151 expect(members?.map((agent) => agent.completedAt)).toEqual([
152 "2026-08-01T10:00:09.000Z",
153 "2026-08-01T10:00:09.000Z",
154 "2026-08-01T10:00:01.500Z",
155 ]);
156 expect(members?.[0]?.model).toBeNull();
157 expect(members?.[0]?.effort).toBeNull();
158 expect(members?.[0]?.speed).toBeUndefined();
159 },
160 );
161β
162 it("titles an untitled subagent from its prompt without splitting an emoji", () => {
163 const [untitled] = projectedSubagentsToRuntime([
164 subagent({ title: null, prompt: `${"a".repeat(76)}π and more work.` }),
165 ]);
166 expect(untitled?.title).toBe(`${"a".repeat(76)}...`);
167 });
168});
169β
170describe("deriveWorkflowGroups over a dynamic workflow", () => {
171 it("groups members under their phases and counts the run", () => {
172 const groups = groupsOf([
173 subagent({
174 workflow: {
175 name: "probe-wf",
176 phases: [
177 { index: 1, title: "Alpha" },
178 { index: 2, title: "Beta" },
179 ],
180 agents: [
181 member({ state: "completed" }),
182 member({ index: 2, label: "alpha:two", state: "failed" }),
183 member({ index: 3, label: "beta:one", phaseIndex: 2, phaseTitle: "Beta" }),
184 member({
185 index: 4,
186 label: "beta:two",
187 phaseIndex: 2,
188 phaseTitle: "Beta",
189 state: "queued",
190 }),
191 ],
192 },
193 }),
194 ]);
195 const group = groups[0];
196 expect(group?.phases.map((phase) => [phase.title, phase.state])).toEqual([
197 ["Alpha", "done"],
198 ["Beta", "running"],
199 ]);
200 expect(group?.phases.map((phase) => phase.settledCount)).toEqual([2, 0]);
201 expect(group?.phases.flatMap((phase) => phase.members)).toHaveLength(4);
202 expect(group?.unphasedMembers).toEqual([]);
203 });
204β
205 it.each([false, true])("keeps a reported phase title, missing title first=%s", (missingFirst) => {
206 const agents = [member({ phaseTitle: "Review" }), member({ index: 2, phaseTitle: undefined })];
207 const groups = groupsOf([
208 subagent({ workflow: { phases: [], agents: missingFirst ? agents.toReversed() : agents } }),
209 ]);
210 expect(groups[0]?.phases[0]?.title).toBe("Review");
211 });
212β
213 it("keeps unphased members with their workflow and excludes unrelated agents", () => {
214 const runtime = projectedSubagentsToRuntime([
215 subagent({ id: "ordinary" }),
216 subagent({
217 id: "__proto__",
218 workflow: {
219 phases: [],
220 agents: [member({ phaseIndex: undefined, phaseTitle: undefined })],
221 },
222 }),
223 subagent({ id: "constructor", workflow: { phases: [], agents: [] } }),
224 subagent({ id: "orphan", workflow: { phases: [], agents: [member()] } }),
225 ]);
226 const groups = deriveWorkflowGroups(runtime.filter((agent) => agent.id !== "orphan"));
227 expect(groups.map((group) => group.workflow.id)).toEqual(["__proto__", "constructor"]);
228 expect(groups[0]?.phases).toEqual([]);
229 expect(groups[0]?.unphasedMembers.map((agent) => agent.title)).toEqual(["alpha:one"]);
230 expect(groups[1]?.phases).toEqual([]);
231 expect(groups[1]?.unphasedMembers).toEqual([]);
232 });
233});
234β
235describe("resolveWorkflowOpening", () => {
236 const SCRIPT = '// probe\nexport const meta = { name: "probe-wf" };\nconst GROUPS = [];';
237 const childThread = {
238 id: ThreadId.make("child"),
239 lineage: {
240 parentThreadId: ThreadId.make("parent"),
241 relationshipToParent: "subagent" as const,
242 rootThreadId: ThreadId.make("parent"),
243 },
244 creationSource: "provider" as const,
245 };
246 const coordinator = (workflow?: OrchestrationV2SubagentWorkflow) => ({
247 ...subagent({
248 title: "Run the alpha workflow",
249 childThreadId: "child",
250 ...(workflow === undefined ? {} : { workflow }),
251 }),
252 driver: ProviderDriverKind.make("claudeAgent"),
253 providerInstanceId: ProviderInstanceId.make("claude"),
254 });
255 const brief = (text: string, workflowScript?: boolean) => ({
256 id: "message-1",
257 role: "user",
258 text,
259 ...(workflowScript === undefined ? {} : { workflowScript }),
260 });
261β
262 it("opens a marked thread with the coordinator's plan and members", () => {
263 const opening = resolveWorkflowOpening({
264 thread: childThread,
265 messages: [brief(SCRIPT, true)],
266 parentSubagents: [
267 coordinator({
268 name: "probe-wf",
269 phases: [{ index: 1, title: "Alpha" }],
270 agents: [member({ childThreadId: ThreadId.make("member-1") })],
271 }),
272 ],
273 });
274 expect(opening).toMatchObject({
275 messageId: "message-1",
276 script: SCRIPT,
277 name: "probe-wf",
278 description: "Run the alpha workflow",
279 });
280 expect(
281 opening?.group?.phases.map((phase) => ({
282 title: phase.title,
283 members: phase.members.map((agent) => [agent.title, agent.status, agent.childThreadId]),
284 })),
285 ).toEqual([{ title: "Alpha", members: [["alpha:one", "running", "member-1"]] }]);
286 });
287β
288 it("recognizes an unmarked script before the parent loads", () => {
289 const opening = resolveWorkflowOpening({
290 thread: childThread,
291 messages: [brief(SCRIPT)],
292 parentSubagents: null,
293 });
294 expect(opening).toMatchObject({ script: SCRIPT, name: null, group: null });
295 });
296β
297 it("leaves an ordinary subagent thread and other threads alone", () => {
298 expect(
299 resolveWorkflowOpening({
300 thread: childThread,
301 messages: [brief("Audit the last five commits.")],
302 parentSubagents: [coordinator()],
303 }),
304 ).toBeNull();
305 expect(
306 resolveWorkflowOpening({
307 thread: {
308 ...childThread,
309 lineage: { ...childThread.lineage, relationshipToParent: null, parentThreadId: null },
310 },
311 messages: [brief(SCRIPT)],
312 parentSubagents: null,
313 }),
314 ).toBeNull();
315 expect(isWorkflowScriptMessage({ role: "user", text: "Explain `export const meta`." })).toBe(
316 false,
317 );
318 expect(isWorkflowScriptMessage({ role: "assistant", text: SCRIPT })).toBe(false);
319 });
320});