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

subagentRuntime.test.ts

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