Open History to see the last commit
1import {
2 NonNegativeInt,
3 EventId,
4 type OrchestrationThreadActivity,
5 TurnId,
6} from "@t3tools/contracts";
7import { describe, expect, it } from "vite-plus/test";
8
9import {
10 collectWorkflowTaskIds,
11 deriveWorkflowAgentStatus,
12 deriveWorkflowRuns,
13 groupWorkflowAgentsByPhase,
14 isRemoteWorkflowRun,
15 type WorkflowRunAgent,
16} from "./workflow-logic.ts";
17
18let nextActivityId = 0;
19
20function buildActivity(overrides: {
21 id?: string;
22 createdAt?: string;
23 kind?: string;
24 summary?: string;
25 tone?: OrchestrationThreadActivity["tone"];
26 payload?: Record<string, unknown>;
27 turnId?: string;
28 sequence?: number;
29}): OrchestrationThreadActivity {
30 return {
31 id: EventId.make(overrides.id ?? `activity-${nextActivityId++}`),
32 createdAt: overrides.createdAt ?? "2026-02-23T00:00:00.000Z",
33 kind: overrides.kind ?? "task.started",
34 // summary/kind must be trimmed non-empty branded strings.
35 summary: overrides.summary ?? "Workflow",
36 tone: overrides.tone ?? "info",
37 payload: overrides.payload ?? {},
38 turnId: overrides.turnId ? TurnId.make(overrides.turnId) : null,
39 ...(overrides.sequence !== undefined
40 ? { sequence: NonNegativeInt.make(overrides.sequence) }
41 : {}),
42 };
43}
44
45describe("deriveWorkflowAgentStatus", () => {
46 it("maps terminal states directly", () => {
47 expect(deriveWorkflowAgentStatus({ state: "done" })).toBe("done");
48 expect(deriveWorkflowAgentStatus({ state: "error" })).toBe("error");
49 });
50
51 it("treats start without startedAt as queued and with startedAt as running", () => {
52 expect(deriveWorkflowAgentStatus({ state: "start" })).toBe("queued");
53 expect(deriveWorkflowAgentStatus({ state: "start", startedAt: 123 })).toBe("running");
54 });
55
56 it("renders unknown future states as running once startedAt is present", () => {
57 expect(deriveWorkflowAgentStatus({ state: "reticulating", startedAt: 1 })).toBe("running");
58 expect(deriveWorkflowAgentStatus({ state: "reticulating" })).toBe("queued");
59 });
60});
61
62describe("groupWorkflowAgentsByPhase", () => {
63 const agent = (over: Partial<WorkflowRunAgent> & { index: number }): WorkflowRunAgent => ({
64 state: "start",
65 status: "queued",
66 ...over,
67 });
68
69 it("groups agents under their phase and synthesizes an Agents phase for unphased agents", () => {
70 const phases = groupWorkflowAgentsByPhase({
71 phases: [{ index: 0, title: "Plan" }],
72 agents: [
73 agent({ index: 0, phaseIndex: 0 }),
74 agent({ index: 1 }), // no phaseIndex -> synthetic "Agents" phase (index -1)
75 ],
76 });
77 expect(phases.map((phase) => phase.title)).toEqual(["Agents", "Plan"]);
78 const synthetic = phases.find((phase) => phase.title === "Agents");
79 expect(synthetic?.index).toBe(-1);
80 expect(synthetic?.agents.map((entry) => entry.index)).toEqual([1]);
81 });
82
83 it("falls back to a Phase <n> title when the phase is unknown but an agent references it", () => {
84 const phases = groupWorkflowAgentsByPhase({
85 phases: [],
86 agents: [agent({ index: 0, phaseIndex: 2 })],
87 });
88 expect(phases).toHaveLength(1);
89 expect(phases[0]?.title).toBe("Phase 2");
90 });
91
92 it("prefers an agent-supplied phaseTitle for an otherwise-unknown phase", () => {
93 const phases = groupWorkflowAgentsByPhase({
94 phases: [],
95 agents: [agent({ index: 0, phaseIndex: 5, phaseTitle: "Custom" })],
96 });
97 expect(phases[0]?.title).toBe("Custom");
98 });
99});
100
101function workflowStartedActivity(taskId: string, extra?: Record<string, unknown>) {
102 return buildActivity({
103 id: `start-${taskId}`,
104 kind: "task.started",
105 createdAt: "2026-02-23T00:00:01.000Z",
106 turnId: "turn-1",
107 payload: { taskId, taskType: "local_workflow", workflowName: "spec", ...extra },
108 });
109}
110
111function workflowUpdatedActivity(
112 taskId: string,
113 workflowProgress: unknown[],
114 extra?: Record<string, unknown>,
115) {
116 return buildActivity({
117 id: `updated-${taskId}`,
118 kind: "task.workflow-updated",
119 createdAt: "2026-02-23T00:00:02.000Z",
120 payload: { taskId, description: "spec workflow", workflowProgress, ...extra },
121 });
122}
123
124describe("deriveWorkflowRuns", () => {
125 it("derives a single running->completed lifecycle from started + updated + meta + completed", () => {
126 const runs = deriveWorkflowRuns([
127 workflowStartedActivity("task-1"),
128 workflowUpdatedActivity("task-1", [
129 { type: "workflow_phase", index: 0, title: "Plan" },
130 { type: "workflow_agent", index: 0, state: "done", phaseIndex: 0 },
131 { type: "workflow_log", message: "kicked off" },
132 ]),
133 buildActivity({
134 id: "meta-task-1",
135 kind: "task.workflow-meta",
136 createdAt: "2026-02-23T00:00:03.000Z",
137 payload: {
138 taskId: "task-1",
139 runId: "wf_abc",
140 scriptPath: "/x/s.js",
141 transcriptDir: "/x/t",
142 },
143 }),
144 buildActivity({
145 id: "complete-task-1",
146 kind: "task.completed",
147 createdAt: "2026-02-23T00:00:04.000Z",
148 payload: { taskId: "task-1", status: "completed", detail: "all done" },
149 }),
150 ]);
151
152 expect(runs).toHaveLength(1);
153 const run = runs[0]!;
154 expect(run.taskId).toBe("task-1");
155 expect(run.status).toBe("completed");
156 expect(run.name).toBe("spec");
157 expect(run.completionSummary).toBe("all done");
158 expect(run.handles?.runId).toBe("wf_abc");
159 expect(run.logs).toEqual(["kicked off"]);
160 expect(run.agentCounts).toEqual({ total: 1, queued: 0, running: 0, done: 1, error: 0 });
161 expect(run.turnId).toBe(TurnId.make("turn-1"));
162 });
163
164 it("maps failed and stopped completion statuses", () => {
165 const failed = deriveWorkflowRuns([
166 workflowStartedActivity("task-f"),
167 buildActivity({
168 id: "complete-task-f",
169 kind: "task.completed",
170 createdAt: "2026-02-23T00:00:04.000Z",
171 payload: { taskId: "task-f", status: "failed" },
172 }),
173 ]);
174 expect(failed[0]?.status).toBe("failed");
175
176 const stopped = deriveWorkflowRuns([
177 workflowStartedActivity("task-s"),
178 buildActivity({
179 id: "complete-task-s",
180 kind: "task.completed",
181 createdAt: "2026-02-23T00:00:04.000Z",
182 payload: { taskId: "task-s", status: "stopped" },
183 }),
184 ]);
185 expect(stopped[0]?.status).toBe("stopped");
186 });
187
188 it("derives agent status per entry (queued/running/done/error/unknown-with-startedAt)", () => {
189 const runs = deriveWorkflowRuns([
190 workflowStartedActivity("task-1"),
191 workflowUpdatedActivity("task-1", [
192 { type: "workflow_agent", index: 0, state: "start" },
193 { type: "workflow_agent", index: 1, state: "start", startedAt: 100 },
194 { type: "workflow_agent", index: 2, state: "done" },
195 { type: "workflow_agent", index: 3, state: "error" },
196 { type: "workflow_agent", index: 4, state: "reticulating", startedAt: 5 },
197 ]),
198 ]);
199 expect(runs[0]?.agentCounts).toEqual({
200 total: 5,
201 queued: 1,
202 running: 2,
203 done: 1,
204 error: 1,
205 });
206 });
207
208 it("lets a later agent entry with the same index win", () => {
209 const runs = deriveWorkflowRuns([
210 workflowStartedActivity("task-1"),
211 workflowUpdatedActivity("task-1", [
212 { type: "workflow_agent", index: 0, state: "start" },
213 { type: "workflow_agent", index: 0, state: "done" },
214 ]),
215 ]);
216 expect(runs[0]?.agentCounts.total).toBe(1);
217 expect(runs[0]?.agentCounts.done).toBe(1);
218 expect(runs[0]?.agentCounts.queued).toBe(0);
219 });
220
221 it("drops malformed progress entries without throwing", () => {
222 const runs = deriveWorkflowRuns([
223 workflowStartedActivity("task-1"),
224 workflowUpdatedActivity("task-1", [
225 { type: "workflow_agent", state: "start" }, // missing index
226 { type: "workflow_agent", index: 1 }, // missing state
227 "not an object",
228 null,
229 { type: "workflow_mystery", index: 9 },
230 { type: "workflow_agent", index: 2, state: "done" },
231 ]),
232 ]);
233 expect(runs[0]?.agentCounts.total).toBe(1);
234 expect(runs[0]?.agentCounts.done).toBe(1);
235 });
236
237 it("parses per-agent tokens, tool calls, and duration from the snapshot", () => {
238 const runs = deriveWorkflowRuns([
239 workflowStartedActivity("task-1"),
240 workflowUpdatedActivity("task-1", [
241 {
242 type: "workflow_agent",
243 index: 0,
244 state: "done",
245 tokens: 94_200,
246 toolCalls: 47,
247 durationMs: 423_000,
248 },
249 ]),
250 ]);
251 const agent = runs[0]?.phases.flatMap((phase) => phase.agents)[0];
252 expect(agent?.tokens).toBe(94_200);
253 expect(agent?.toolCalls).toBe(47);
254 expect(agent?.durationMs).toBe(423_000);
255 });
256
257 it("parses snake_case usage from the updated snapshot", () => {
258 const runs = deriveWorkflowRuns([
259 workflowStartedActivity("task-1"),
260 workflowUpdatedActivity("task-1", [{ type: "workflow_agent", index: 0, state: "done" }], {
261 usage: { total_tokens: 1200, tool_uses: 3, duration_ms: 4500 },
262 }),
263 ]);
264 expect(runs[0]?.usage).toEqual({ totalTokens: 1200, toolUses: 3, durationMs: 4500 });
265 });
266
267 it("ignores plain (non-workflow) tasks entirely", () => {
268 const runs = deriveWorkflowRuns([
269 buildActivity({
270 id: "plain-start",
271 kind: "task.started",
272 payload: { taskId: "plain-1", taskType: "plan" },
273 }),
274 buildActivity({
275 id: "plain-progress",
276 kind: "task.progress",
277 payload: { taskId: "plain-1", summary: "thinking" },
278 }),
279 buildActivity({
280 id: "plain-complete",
281 kind: "task.completed",
282 payload: { taskId: "plain-1", status: "completed" },
283 }),
284 ]);
285 expect(runs).toEqual([]);
286 });
287
288 it("terminalizes a still-running run and settles in-flight agents when the session is gone", () => {
289 const runs = deriveWorkflowRuns(
290 [
291 workflowStartedActivity("task-1"),
292 workflowUpdatedActivity("task-1", [
293 { type: "workflow_agent", index: 0, state: "done" },
294 { type: "workflow_agent", index: 1, state: "start", startedAt: 1000 },
295 { type: "workflow_agent", index: 2, state: "start" },
296 ]),
297 ],
298 { sessionActive: false },
299 );
300 const run = runs[0];
301 expect(run?.status).toBe("stopped");
302 const agents = run?.phases.flatMap((phase) => phase.agents) ?? [];
303 expect(agents.map((agent) => agent.status)).toEqual(["done", "error", "error"]);
304 expect(agents[1]?.error).toBe("Interrupted before completion");
305 expect(run?.agentCounts).toEqual({ total: 3, queued: 0, running: 0, done: 1, error: 2 });
306 });
307
308 it("applies a completion even when it sorts before its task.started", () => {
309 const completed = buildActivity({
310 id: "completed-task-1",
311 kind: "task.completed",
312 createdAt: "2026-02-23T00:00:00.500Z",
313 sequence: 1,
314 payload: { taskId: "task-1", status: "completed", detail: "done" },
315 });
316 // Same-timestamp + inverted sequence (adopted runs can reset provider
317 // sequence): the started activity sorts after the completion.
318 const started = { ...workflowStartedActivity("task-1"), sequence: NonNegativeInt.make(5) };
319 const runs = deriveWorkflowRuns([completed, started]);
320 expect(runs).toHaveLength(1);
321 expect(runs[0]?.status).toBe("completed");
322 expect(runs[0]?.name).toBe("spec");
323 });
324
325 it("keeps a running run untouched while the session is active", () => {
326 const runs = deriveWorkflowRuns(
327 [
328 workflowStartedActivity("task-1"),
329 workflowUpdatedActivity("task-1", [
330 { type: "workflow_agent", index: 0, state: "start", startedAt: 1000 },
331 ]),
332 ],
333 { sessionActive: true },
334 );
335 expect(runs[0]?.status).toBe("running");
336 expect(runs[0]?.phases.flatMap((phase) => phase.agents)[0]?.status).toBe("running");
337 });
338
339 it("detects remote runs from session handles", () => {
340 const runs = deriveWorkflowRuns([
341 workflowStartedActivity("task-remote"),
342 buildActivity({
343 id: "meta-remote",
344 kind: "task.workflow-meta",
345 createdAt: "2026-02-23T00:00:03.000Z",
346 payload: { taskId: "task-remote", sessionUrl: "https://example.com/run" },
347 }),
348 ]);
349 expect(runs).toHaveLength(1);
350 expect(isRemoteWorkflowRun(runs[0]!)).toBe(true);
351 });
352});
353
354describe("collectWorkflowTaskIds", () => {
355 it("collects workflow task ids via workflowName, local_workflow task type, and workflow kinds", () => {
356 const ids = collectWorkflowTaskIds([
357 buildActivity({
358 id: "s1",
359 kind: "task.started",
360 payload: { taskId: "by-name", workflowName: "spec" },
361 }),
362 buildActivity({
363 id: "s2",
364 kind: "task.started",
365 payload: { taskId: "by-type", taskType: "local_workflow" },
366 }),
367 buildActivity({
368 id: "u1",
369 kind: "task.workflow-updated",
370 payload: { taskId: "by-updated", workflowProgress: [] },
371 }),
372 buildActivity({
373 id: "m1",
374 kind: "task.workflow-meta",
375 payload: { taskId: "by-meta" },
376 }),
377 ]);
378 expect([...ids].sort()).toEqual(["by-meta", "by-name", "by-type", "by-updated"]);
379 });
380
381 it("does not collect plain task ids", () => {
382 const ids = collectWorkflowTaskIds([
383 buildActivity({
384 id: "plain",
385 kind: "task.started",
386 payload: { taskId: "plain-1", taskType: "plan" },
387 }),
388 buildActivity({
389 id: "plain-progress",
390 kind: "task.progress",
391 payload: { taskId: "plain-1" },
392 }),
393 ]);
394 expect(ids.has("plain-1")).toBe(false);
395 expect(ids.size).toBe(0);
396 });
397});