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

subagentRuntime.test.ts

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