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

subagentRuntime.test.ts

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