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

subagentRuntime.test.ts

399 lines13.2 KB

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 workflowOpeningHeadline,
17 workflowOpeningParentThreadId,
18} from "./subagentRuntime.ts";
19​
20const at = (iso: string) => DateTime.makeUnsafe(iso);
21​
22type ProjectedSubagent = Parameters<typeof projectedSubagentsToRuntime>[0][number];
23​
24function subagent(overrides: Partial<ProjectedSubagent> = {}): ProjectedSubagent {
25 return {
26 id: "coordinator",
27 title: "probe",
28 prompt: "export const meta = …",
29 model: "claude-opus-5[1m]",
30 status: "running" satisfies OrchestrationV2Subagent["status"],
31 result: null,
32 startedAt: at("2026-08-01T10:00:00.000Z"),
33 completedAt: null,
34 updatedAt: at("2026-08-01T10:00:05.000Z"),
35 ...overrides,
36 };
38​
39const member = (
40 overrides: Partial<OrchestrationV2SubagentWorkflow["agents"][number]> = {},
41): OrchestrationV2SubagentWorkflow["agents"][number] => ({
42 index: 1,
43 label: "alpha:one",
44 state: "running",
45 phaseIndex: 1,
46 phaseTitle: "Alpha",
47 ...overrides,
48});
49​
50const groupsOf = (subagents: ReadonlyArray<ProjectedSubagent>) =>
51 deriveWorkflowGroups(projectedSubagentsToRuntime(subagents));
52​
53describe("projectedSubagentsToRuntime workflow expansion", () => {
54 it("leaves a plain subagent flat", () => {
55 const [agent, ...rest] = projectedSubagentsToRuntime([subagent()]);
56 expect(rest).toEqual([]);
57 expect(agent?.kind).toBe("subagent");
58 expect(agent?.phases).toEqual([]);
59 });
60​
61 it("projects a coordinator plus one row per member", () => {
62 const rows = projectedSubagentsToRuntime([
63 subagent({
64 workflow: {
65 name: "probe-wf",
66 phases: [
67 { index: 1, title: "Alpha" },
68 { index: 2, title: "Beta" },
69 ],
70 agents: [member(), member({ index: 2, label: "alpha:two", state: "queued" })],
71 totalTokens: 1000,
72 },
73 }),
74 ]);
75 expect(rows.map((row) => row.kind)).toEqual(["workflow", "workflow_agent", "workflow_agent"]);
76 expect(rows[0]?.workflowName).toBe("probe-wf");
77 expect(rows[0]?.usage?.totalTokens).toBe(1000);
78 expect(rows[1]).toMatchObject({
79 id: "coordinator:agent:1",
80 title: "alpha:one",
81 parentAgentId: "coordinator",
82 phaseIndex: 1,
83 phaseTitle: "Alpha",
84 status: "running",
85 });
86 expect(rows[2]?.status).toBe("pending");
87 expect(rows[2]?.startedAt).toBeNull();
88 });
89​
90 it("uses a settled member's wall-clock completion separately from its execution duration", () => {
91 const [, settled] = projectedSubagentsToRuntime([
92 subagent({
93 status: "completed",
94 completedAt: at("2026-08-01T10:00:09.000Z"),
95 workflow: {
96 phases: [],
97 agents: [
98 member({
99 state: "completed",
100 startedAt: Date.UTC(2026, 7, 1, 10, 0, 0),
101 durationMs: 1500,
102 completedAt: Date.UTC(2026, 7, 1, 10, 0, 4, 432),
103 totalTokens: 71_141,
104 toolCalls: 3,
105 prompt: "Reply with exactly: A1",
106 result: "A1",
107 }),
108 ],
109 },
110 }),
111 ]);
112 expect(settled?.status).toBe("completed");
113 expect(settled?.completedAt).toBe("2026-08-01T10:00:04.432Z");
114 expect(settled?.result).toBe("A1");
115 expect(settled?.progress).toBe("Reply with exactly: A1");
116 expect(settled?.usage).toEqual({ totalTokens: 71_141, toolUses: 3, durationMs: 1500 });
117 });
118​
119 it.each(["completed", "cancelled", "failed"] as const)(
120 "settles unfinished members when the coordinator is %s",
121 (status) => {
122 const groups = groupsOf([
123 subagent({
124 status,
125 completedAt: at("2026-08-01T10:00:09.000Z"),
126 workflow: {
127 phases: [],
128 agents: [
129 member(),
130 member({ index: 2, state: "queued" }),
131 member({
132 index: 3,
133 state: "completed",
134 startedAt: Date.UTC(2026, 7, 1, 10, 0, 0),
135 durationMs: 1500,
136 }),
137 ],
138 },
139 }),
140 ]);
141 expect(groups[0]?.workflow.status).toBe(status);
142 const members = groups[0]?.phases.flatMap((phase) => phase.members);
143 expect(members?.map((agent) => agent.status)).toEqual([status, status, "completed"]);
144 expect(members?.map((agent) => agent.completedAt)).toEqual([
145 "2026-08-01T10:00:09.000Z",
146 "2026-08-01T10:00:09.000Z",
147 "2026-08-01T10:00:01.500Z",
148 ]);
149 },
150 );
151​
152 it("surfaces a retried member through the row's activation count", () => {
153 const [, retried] = projectedSubagentsToRuntime([
154 subagent({ workflow: { phases: [], agents: [member({ attempt: 3 })] } }),
155 ]);
156 expect(retried?.activationCount).toBe(3);
157 expect(retried?.attempt).toBe(3);
158 });
159});
160​
161describe("deriveWorkflowGroups over a dynamic workflow", () => {
162 it("groups members under their phases and counts the run", () => {
163 const groups = groupsOf([
164 subagent({
165 workflow: {
166 name: "probe-wf",
167 phases: [
168 { index: 1, title: "Alpha" },
169 { index: 2, title: "Beta" },
170 ],
171 agents: [
172 member({ state: "completed" }),
173 member({ index: 2, label: "alpha:two", state: "failed" }),
174 member({ index: 3, label: "beta:one", phaseIndex: 2, phaseTitle: "Beta" }),
175 member({
176 index: 4,
177 label: "beta:two",
178 phaseIndex: 2,
179 phaseTitle: "Beta",
180 state: "queued",
181 }),
182 ],
183 },
184 }),
185 ]);
186 const group = groups[0];
187 expect(group?.phases.map((phase) => [phase.title, phase.state])).toEqual([
188 ["Alpha", "done"],
189 ["Beta", "running"],
190 ]);
191 expect(group?.phases.map((phase) => phase.settledCount)).toEqual([2, 0]);
192 expect(group?.phases.flatMap((phase) => phase.members)).toHaveLength(4);
193 expect(group?.unphasedMembers).toEqual([]);
194 });
195​
196 it("shows a phase the script only reached at runtime", () => {
197 const groups = groupsOf([
198 subagent({
199 workflow: {
200 phases: [{ index: 1, title: "Alpha" }],
201 agents: [
202 member({ state: "completed" }),
203 member({ index: 2, label: "dynamic:late", phaseIndex: 3, phaseTitle: "Gamma" }),
204 ],
205 },
206 }),
207 ]);
208 const group = groups[0];
209 expect(group?.phases.map((phase) => phase.title)).toEqual(["Alpha", "Gamma"]);
210 expect(group?.unphasedMembers).toEqual([]);
211 });
212​
213 it.each([false, true])("keeps a reported phase title, missing title first=%s", (missingFirst) => {
214 const agents = [member({ phaseTitle: "Review" }), member({ index: 2, phaseTitle: undefined })];
215 const groups = groupsOf([
216 subagent({ workflow: { phases: [], agents: missingFirst ? agents.toReversed() : agents } }),
217 ]);
218 expect(groups[0]?.phases[0]?.title).toBe("Review");
219 });
220​
221 it("keeps unphased members with their workflow and excludes unrelated agents", () => {
222 const runtime = projectedSubagentsToRuntime([
223 subagent({ id: "ordinary" }),
224 subagent({
225 id: "__proto__",
226 workflow: {
227 phases: [],
228 agents: [member({ phaseIndex: undefined, phaseTitle: undefined })],
229 },
230 }),
231 subagent({ id: "constructor", workflow: { phases: [], agents: [] } }),
232 subagent({ id: "orphan", workflow: { phases: [], agents: [member()] } }),
233 ]);
234 const groups = deriveWorkflowGroups(runtime.filter((agent) => agent.id !== "orphan"));
235 expect(groups.map((group) => group.workflow.id)).toEqual(["__proto__", "constructor"]);
236 expect(groups[0]?.phases).toEqual([]);
237 expect(groups[0]?.unphasedMembers.map((agent) => agent.title)).toEqual(["alpha:one"]);
238 expect(groups[1]?.phases).toEqual([]);
239 expect(groups[1]?.unphasedMembers).toEqual([]);
240 });
241});
242​
243describe("resolveWorkflowOpening", () => {
244 const SCRIPT = '// probe\nexport const meta = { name: "probe-wf" };\nconst GROUPS = [];';
245 const childThread = {
246 id: ThreadId.make("child"),
247 lineage: {
248 parentThreadId: ThreadId.make("parent"),
249 relationshipToParent: "subagent" as const,
250 rootThreadId: ThreadId.make("parent"),
251 },
252 creationSource: "provider" as const,
253 };
254 const coordinator = (workflow?: OrchestrationV2SubagentWorkflow) => ({
255 ...subagent({
256 title: "Run the alpha workflow",
257 childThreadId: "child",
258 ...(workflow === undefined ? {} : { workflow }),
259 }),
260 driver: ProviderDriverKind.make("claudeAgent"),
261 providerInstanceId: ProviderInstanceId.make("claude"),
262 });
263 const brief = (text: string, workflowScript?: boolean) => ({
264 id: "message-1",
265 role: "user",
266 text,
267 ...(workflowScript === undefined ? {} : { workflowScript }),
268 });
269​
270 it("opens a marked thread with the coordinator's plan and members", () => {
271 const opening = resolveWorkflowOpening({
272 thread: childThread,
273 messages: [brief(SCRIPT, true)],
274 parentSubagents: [
275 coordinator({
276 name: "probe-wf",
277 phases: [{ index: 1, title: "Alpha" }],
278 agents: [member({ childThreadId: ThreadId.make("member-1") })],
279 }),
280 ],
281 });
282 expect(opening).toMatchObject({
283 messageId: "message-1",
284 script: SCRIPT,
285 name: "probe-wf",
286 description: "Run the alpha workflow",
287 });
288 expect(
289 opening?.group?.phases.map((phase) => ({
290 title: phase.title,
291 members: phase.members.map((agent) => [agent.title, agent.status, agent.childThreadId]),
292 })),
293 ).toEqual([{ title: "Alpha", members: [["alpha:one", "running", "member-1"]] }]);
294 });
295​
296 it("recognizes an unmarked script before the parent loads", () => {
297 const opening = resolveWorkflowOpening({
298 thread: childThread,
299 messages: [brief(SCRIPT)],
300 parentSubagents: null,
301 });
302 expect(opening).toMatchObject({ script: SCRIPT, name: null, group: null });
303 });
304​
305 it("recognizes an unmarked first message from the parent's workflow row", () => {
306 const opening = resolveWorkflowOpening({
307 thread: childThread,
308 messages: [brief("Run the alpha workflow.")],
309 parentSubagents: [coordinator({ name: "probe-wf", phases: [], agents: [] })],
310 });
311 expect(opening?.name).toBe("probe-wf");
312 });
313​
314 it("leaves an ordinary subagent thread and other threads alone", () => {
315 expect(
316 resolveWorkflowOpening({
317 thread: childThread,
318 messages: [brief("Audit the last five commits.")],
319 parentSubagents: [coordinator()],
320 }),
321 ).toBeNull();
322 expect(
323 resolveWorkflowOpening({
324 thread: {
325 ...childThread,
326 lineage: { ...childThread.lineage, relationshipToParent: null, parentThreadId: null },
327 },
328 messages: [brief(SCRIPT)],
329 parentSubagents: null,
330 }),
331 ).toBeNull();
332 expect(isWorkflowScriptMessage({ role: "user", text: "Explain `export const meta`." })).toBe(
333 false,
334 );
335 expect(isWorkflowScriptMessage({ role: "assistant", text: SCRIPT })).toBe(false);
336 });
337​
338 it("trusts a brief marked as not a script even when its text looks like one", () => {
339 expect(isWorkflowScriptMessage(brief(SCRIPT, false))).toBe(false);
340 expect(
341 resolveWorkflowOpening({
342 thread: childThread,
343 messages: [brief(SCRIPT, false)],
344 parentSubagents: [coordinator()],
345 }),
346 ).toBeNull();
347 expect(
348 workflowOpeningParentThreadId({ thread: childThread, messages: [brief(SCRIPT, false)] }),
349 ).toBeNull();
350 });
351​
352 it("loads the parent only for a thread that opens with a workflow script", () => {
353 expect(
354 workflowOpeningParentThreadId({ thread: childThread, messages: [brief(SCRIPT, true)] }),
355 ).toBe("parent");
356 expect(workflowOpeningParentThreadId({ thread: childThread, messages: [brief(SCRIPT)] })).toBe(
357 "parent",
358 );
359 expect(
360 workflowOpeningParentThreadId({
361 thread: childThread,
362 messages: [brief("Audit the last five commits.")],
363 }),
364 ).toBeNull();
365 });
366​
367 it("heads the opening with the workflow name, description, and agent tally", () => {
368 const opening = resolveWorkflowOpening({
369 thread: childThread,
370 messages: [brief(SCRIPT, true)],
371 parentSubagents: [
372 coordinator({
373 name: "probe-wf",
374 phases: [{ index: 1, title: "Alpha" }],
375 agents: [
376 member(),
377 member({ index: 2, label: "alpha:two", state: "completed" }),
378 member({ index: 3, label: "loose", state: "failed", phaseIndex: undefined }),
379 ],
380 }),
381 ],
382 });
383 expect(opening && workflowOpeningHeadline(opening)).toEqual({
384 title: "probe-wf",
385 description: "Run the alpha workflow",
386 agents: "3 agents · 1 working · 1 done · 1 failed",
387 });
388 const unloaded = resolveWorkflowOpening({
389 thread: childThread,
390 messages: [brief(SCRIPT)],
391 parentSubagents: null,
392 });
393 expect(unloaded && workflowOpeningHeadline(unloaded)).toEqual({
394 title: "Workflow",
395 description: null,
396 agents: null,
397 });
398 });
399});