Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import { classifyTaskAgentKind, type OrchestrationThreadActivity } from "@t3tools/contracts";
3import {
4 deriveAgentPanelModel,
5 foldSubagentActivities,
6 formatSubagentModelLabel,
7 formatSubagentTokenCount,
8 isAgentAttributedToolActivity,
9 isSubagentActivityKind,
10 isTimelineBypassActivity,
11 workflowCardMembers,
12} from "./subagentRuntime.ts";
13
14let sequence = 0;
15/**
16 * Fixtures model POST-INGESTION rows: ingestion stamps agentKind on every
17 * task.* payload, so the helper stamps too (same classifier). Pass an
18 * explicit agentKind (or agentKind: undefined via legacy()) to override.
19 */
20function activity(
21 kind: string,
22 payload: Record<string, unknown>,
23 at = `2026-08-01T10:00:${String(sequence).padStart(2, "0")}.000Z`,
24): OrchestrationThreadActivity {
25 sequence += 1;
26 const stamped =
27 kind.startsWith("task.") && !("agentKind" in payload)
28 ? {
29 ...payload,
30 agentKind: classifyTaskAgentKind({
31 taskType: typeof payload.taskType === "string" ? payload.taskType : undefined,
32 agentId: typeof payload.agentId === "string" ? payload.agentId : undefined,
33 }),
34 }
35 : payload;
36 return {
37 id: `activity-${sequence}`,
38 tone: "info",
39 kind,
40 summary: kind,
41 payload: stamped,
42 turnId: null,
43 createdAt: at,
44 } as unknown as OrchestrationThreadActivity;
45}
46
47/** A pre-stamp row (legacy thread / old server): no agentKind at all. */
48function legacyActivity(
49 kind: string,
50 payload: Record<string, unknown>,
51): OrchestrationThreadActivity {
52 sequence += 1;
53 return {
54 id: `activity-${sequence}`,
55 tone: "info",
56 kind,
57 summary: kind,
58 payload,
59 turnId: null,
60 createdAt: `2026-08-01T10:00:${String(sequence).padStart(2, "0")}.000Z`,
61 } as unknown as OrchestrationThreadActivity;
62}
63
64function fold(rows: ReadonlyArray<OrchestrationThreadActivity>) {
65 return foldSubagentActivities(rows);
66}
67
68describe("foldSubagentActivities", () => {
69 it("builds an agent from start → progress → completion", () => {
70 const agents = fold([
71 activity("task.started", {
72 taskId: "task-1",
73 title: "Audit auth flow",
74 role: "explorer",
75 }),
76 activity("task.progress", {
77 taskId: "task-1",
78 lastToolName: "Read",
79 typedUsage: { totalTokens: 1200, toolUses: 3 },
80 }),
81 activity("task.completed", {
82 taskId: "task-1",
83 status: "completed",
84 summary: "Found 2 issues",
85 typedUsage: { totalTokens: 5000, toolUses: 9 },
86 }),
87 ]);
88 expect(agents).toHaveLength(1);
89 const agent = agents[0]!;
90 expect(agent.title).toBe("Audit auth flow");
91 expect(agent.role).toBe("explorer");
92 expect(agent.status).toBe("completed");
93 expect(agent.result).toBe("Found 2 issues");
94 expect(agent.usage?.totalTokens).toBe(5000);
95 expect(agent.activationCount).toBe(1);
96 expect(agent.completedAt).not.toBeNull();
97 });
98
99 it("progress can create an agent when its start row aged out of retention", () => {
100 const agents = fold([
101 activity("task.progress", {
102 taskId: "task-orphan",
103 title: "Recovered agent",
104 role: "verifier",
105 typedUsage: { totalTokens: 100 },
106 }),
107 ]);
108 expect(agents).toHaveLength(1);
109 expect(agents[0]!.title).toBe("Recovered agent");
110 expect(agents[0]!.status).toBe("running");
111 });
112
113 it("completion before start stays terminal; a late start only fills metadata", () => {
114 const agents = fold([
115 activity("task.completed", {
116 taskId: "task-2",
117 status: "failed",
118 summary: "boom",
119 role: "fixer",
120 }),
121 activity("task.started", { taskId: "task-2", title: "Late metadata", role: "fixer" }),
122 ]);
123 expect(agents).toHaveLength(1);
124 const agent = agents[0]!;
125 expect(agent.title).toBe("Late metadata");
126 expect(agent.role).toBe("fixer");
127 // The late start must NOT reopen the terminal activation as a new run.
128 expect(agent.status).toBe("failed");
129 expect(agent.error).toBe("boom");
130 });
131
132 it("duplicate terminal events are idempotent (timestamps do not slide)", () => {
133 const agents = fold([
134 activity("task.started", { taskId: "task-3", taskType: "local_agent" }),
135 activity(
136 "task.completed",
137 { taskId: "task-3", status: "completed" },
138 "2026-08-01T11:00:00.000Z",
139 ),
140 activity(
141 "task.completed",
142 { taskId: "task-3", status: "completed" },
143 "2026-08-01T12:00:00.000Z",
144 ),
145 ]);
146 expect(agents[0]!.completedAt).toBe("2026-08-01T11:00:00.000Z");
147 });
148
149 it("reactivation increments the run count and clears result/error", () => {
150 const agents = fold([
151 activity("task.started", { taskId: "task-4", taskType: "local_agent" }),
152 activity("task.completed", { taskId: "task-4", status: "completed", summary: "run 1 done" }),
153 activity("task.updated", { taskId: "task-4", status: "running" }),
154 ]);
155 const agent = agents[0]!;
156 expect(agent.activationCount).toBe(2);
157 expect(agent.result).toBeNull();
158 expect(agent.completedAt).toBeNull();
159 expect(agent.status).toBe("running");
160 });
161
162 it("idle is nonterminal: an idle agent resumes without losing identity", () => {
163 const agents = fold([
164 activity("task.started", { taskId: "codex-child-1", title: "Marlow", role: "explorer" }),
165 activity("task.updated", { taskId: "codex-child-1", status: "idle" }),
166 activity("task.updated", { taskId: "codex-child-1", status: "running" }),
167 ]);
168 expect(agents).toHaveLength(1);
169 expect(agents[0]!.activationCount).toBe(2);
170 expect(agents[0]!.status).toBe("running");
171 });
172
173 it("cumulative usage max-merges: duplicate and late frames never shrink or double-count", () => {
174 const agents = fold([
175 activity("task.started", { taskId: "task-5", taskType: "local_agent" }),
176 activity("task.progress", {
177 taskId: "task-5",
178 typedUsage: { totalTokens: 900, inputTokens: 700 },
179 }),
180 activity("task.progress", {
181 taskId: "task-5",
182 typedUsage: { totalTokens: 900, inputTokens: 700 },
183 }),
184 activity("task.progress", { taskId: "task-5", typedUsage: { totalTokens: 500 } }),
185 ]);
186 expect(agents[0]!.usage).toEqual({ totalTokens: 900, inputTokens: 700 });
187 });
188
189 it("usage snapshots enrich an existing agent without changing its status", () => {
190 const [agent] = fold([
191 activity("task.started", { taskId: "usage-waiting", taskType: "local_agent" }),
192 activity("task.progress", { taskId: "usage-waiting", status: "waiting" }),
193 activity("task.progress", {
194 taskId: "usage-waiting",
195 usageSnapshot: true,
196 typedUsage: { totalTokens: 1_200 },
197 }),
198 ]);
199
200 expect(agent?.status).toBe("waiting");
201 expect(agent?.usage?.totalTokens).toBe(1_200);
202 });
203
204 it("a retained usage snapshot can still reconstruct a running agent", () => {
205 const [agent] = fold([
206 activity("task.progress", {
207 taskId: "usage-only",
208 usageSnapshot: true,
209 typedUsage: { totalTokens: 800 },
210 }),
211 ]);
212
213 expect(agent?.status).toBe("running");
214 expect(agent?.usage?.totalTokens).toBe(800);
215 });
216
217 it("partial terminal usage preserves known breakdown fields", () => {
218 const agents = fold([
219 activity("task.started", { taskId: "task-6", taskType: "local_agent" }),
220 activity("task.progress", {
221 taskId: "task-6",
222 typedUsage: { totalTokens: 800, inputTokens: 600, outputTokens: 150 },
223 }),
224 activity("task.completed", {
225 taskId: "task-6",
226 status: "completed",
227 typedUsage: { totalTokens: 1000 },
228 }),
229 ]);
230 expect(agents[0]!.usage).toEqual({ totalTokens: 1000, inputTokens: 600, outputTokens: 150 });
231 });
232
233 it("skips malformed rows individually without failing the fold", () => {
234 const agents = fold([
235 activity("task.started", { taskId: "task-7", title: "Good", taskType: "local_agent" }),
236 activity("task.progress", { bogus: true }),
237 activity("task.progress", { taskId: 42 }),
238 ]);
239 expect(agents).toHaveLength(1);
240 expect(agents[0]!.title).toBe("Good");
241 });
242
243 it("bounds repeated strings at 180 chars and the activity ring at 6 deduped entries", () => {
244 const long = "x".repeat(500);
245 const rows = [activity("task.started", { taskId: "task-8", taskType: "local_agent" })];
246 for (let i = 0; i < 10; i += 1) {
247 rows.push(activity("task.progress", { taskId: "task-8", summary: `${long}-${i}` }));
248 }
249 rows.push(activity("task.progress", { taskId: "task-8", summary: `${long}-9` }));
250 const agents = fold(rows);
251 const agent = agents[0]!;
252 expect(agent.recentActivity.length).toBeLessThanOrEqual(6);
253 for (const entry of agent.recentActivity) {
254 expect(entry.summary.length).toBeLessThanOrEqual(180);
255 }
256 // Consecutive identical summaries dedupe (truncation makes them equal).
257 const summaries = agent.recentActivity.map((entry) => entry.summary);
258 expect(new Set(summaries).size).toBe(summaries.length);
259 });
260
261 it("plan tasks are not agents", () => {
262 const agents = fold([activity("task.started", { taskId: "plan-1", taskType: "plan" })]);
263 expect(agents).toHaveLength(0);
264 });
265
266 it("workflow members key by stable slot and attach to their coordinator", () => {
267 const agents = fold([
268 activity("task.started", {
269 taskId: "wf-1",
270 taskType: "local_workflow",
271 title: "audit-auth-flow",
272 workflowName: "audit-auth-flow",
273 }),
274 activity("task.progress", {
275 taskId: "wf-1",
276 phases: [
277 { index: 0, title: "Audit" },
278 { index: 1, title: "Verify" },
279 ],
280 }),
281 activity("task.progress", {
282 taskId: "wf-1:wf:0",
283 title: "audit:entrypoints",
284 status: "running",
285 parentAgentId: "wf-1",
286 agentIndex: 0,
287 phaseIndex: 0,
288 phaseTitle: "Audit",
289 timelineBypass: true,
290 }),
291 ]);
292 const workflow = agents.find((agent) => agent.id === "wf-1");
293 const member = agents.find((agent) => agent.id === "wf-1:wf:0");
294 expect(workflow?.kind).toBe("workflow");
295 expect(workflow?.phases).toEqual([
296 { index: 0, title: "Audit" },
297 { index: 1, title: "Verify" },
298 ]);
299 expect(member?.kind).toBe("workflow_agent");
300 expect(member?.parentAgentId).toBe("wf-1");
301 });
302
303 it("a workflow member retry (attempt bump) is a reactivation of the same slot", () => {
304 const agents = fold([
305 activity("task.progress", {
306 taskId: "wf-2:wf:1",
307 title: "verify:refresh",
308 status: "failed",
309 error: "attempt 1 died",
310 parentAgentId: "wf-2",
311 attempt: 1,
312 }),
313 activity("task.progress", {
314 taskId: "wf-2:wf:1",
315 title: "verify:refresh",
316 status: "running",
317 parentAgentId: "wf-2",
318 attempt: 2,
319 }),
320 ]);
321 expect(agents).toHaveLength(1);
322 const member = agents[0]!;
323 expect(member.activationCount).toBeGreaterThanOrEqual(2);
324 expect(member.error).toBeNull();
325 expect(member.status).toBe("running");
326 });
327
328 it("drops non-http(s) session urls at the fold boundary", () => {
329 const agents = fold([
330 activity("task.started", {
331 taskId: "wf-3",
332 taskType: "local_workflow",
333 runHandles: { sessionUrl: "javascript:alert(1)", runId: "run-1" },
334 }),
335 ]);
336 expect(agents[0]!.runHandles?.sessionUrl).toBeUndefined();
337 expect(agents[0]!.runHandles?.runId).toBe("run-1");
338 });
339});
340
341describe("deriveAgentPanelModel", () => {
342 const roster = fold([
343 activity("task.started", { taskId: "wf-1", taskType: "local_workflow", title: "audit" }),
344 activity("task.progress", {
345 taskId: "wf-1",
346 phases: [
347 { index: 0, title: "Audit" },
348 { index: 1, title: "Verify" },
349 ],
350 }),
351 activity("task.progress", {
352 taskId: "wf-1:wf:0",
353 title: "audit:a",
354 status: "completed",
355 parentAgentId: "wf-1",
356 agentIndex: 0,
357 phaseIndex: 0,
358 }),
359 activity("task.completed", { taskId: "wf-1:wf:0", status: "completed", parentAgentId: "wf-1" }),
360 activity("task.progress", {
361 taskId: "wf-1:wf:1",
362 title: "verify:b",
363 status: "running",
364 parentAgentId: "wf-1",
365 agentIndex: 1,
366 phaseIndex: 1,
367 typedUsage: { totalTokens: 4000 },
368 }),
369 activity("task.started", { taskId: "direct-1", title: "Marlow", role: "explorer" }),
370 activity("task.updated", { taskId: "direct-1", status: "idle" }),
371 ]);
372
373 it("groups workflow members by phase and separates direct spawns", () => {
374 const model = deriveAgentPanelModel({ agents: roster });
375 expect(model.workflows).toHaveLength(1);
376 const group = model.workflows[0]!;
377 expect(group.phases).toHaveLength(2);
378 expect(group.phases[0]!.state).toBe("done");
379 expect(group.phases[1]!.state).toBe("running");
380 expect(model.directAgents.map((agent) => agent.id)).toEqual(["direct-1"]);
381 });
382
383 it("counts idle deliberately and waiting as active", () => {
384 const model = deriveAgentPanelModel({ agents: roster });
385 expect(model.idleCount).toBe(1);
386 // wf-1 coordinator + member 1 running.
387 expect(model.runningCount).toBeGreaterThanOrEqual(1);
388 expect(model.idleCount + model.runningCount + model.waitingCount + model.settledCount).toBe(
389 roster.length,
390 );
391 });
392
393 it("keeps direct spawns in first-seen order as their activity changes", () => {
394 const directRoster = fold([
395 activity("task.started", { taskId: "direct-a", title: "First" }, "2026-08-01T11:00:00.000Z"),
396 activity("task.started", { taskId: "direct-b", title: "Second" }, "2026-08-01T11:00:01.000Z"),
397 activity(
398 "task.progress",
399 { taskId: "direct-a", summary: "Newest activity" },
400 "2026-08-01T11:00:02.000Z",
401 ),
402 ]);
403
404 expect(
405 deriveAgentPanelModel({ agents: directRoster }).directAgents.map((agent) => agent.id),
406 ).toEqual(["direct-a", "direct-b"]);
407 });
408
409 it("keeps first-seen order after the roster retention ranking runs", () => {
410 const starts = Array.from({ length: 101 }, (_, index) =>
411 activity(
412 "task.started",
413 { taskId: `capped-${index}`, title: `Agent ${index}` },
414 `2026-08-01T12:${String(Math.floor(index / 60)).padStart(2, "0")}:${String(
415 index % 60,
416 ).padStart(2, "0")}.000Z`,
417 ),
418 );
419 const cappedRoster = fold([
420 ...starts,
421 activity(
422 "task.progress",
423 { taskId: "capped-0", summary: "Newest activity" },
424 "2026-08-01T12:02:00.000Z",
425 ),
426 ]);
427
428 const ids = deriveAgentPanelModel({ agents: cappedRoster }).directAgents.map(
429 (agent) => agent.id,
430 );
431 expect(ids).toHaveLength(100);
432 expect(ids.slice(0, 3)).toEqual(["capped-0", "capped-2", "capped-3"]);
433 expect(ids.at(-1)).toBe("capped-100");
434 });
435
436 it("a phase with only pending members never reads as running", () => {
437 const pendingRoster = fold([
438 activity("task.started", { taskId: "wf-9", taskType: "local_workflow" }),
439 activity("task.progress", {
440 taskId: "wf-9",
441 phases: [{ index: 0, title: "Fix" }],
442 }),
443 activity("task.progress", {
444 taskId: "wf-9:wf:0",
445 title: "fixer",
446 status: "pending",
447 parentAgentId: "wf-9",
448 agentIndex: 0,
449 phaseIndex: 0,
450 }),
451 ]);
452 const model = deriveAgentPanelModel({ agents: pendingRoster });
453 // "pending" counts as active liveness (queued work), so the phase reads
454 // running only if a member is genuinely pending/running — this asserts
455 // the settled-count rule: no member settled, phase not done.
456 expect(model.workflows[0]!.phases[0]!.state).not.toBe("done");
457 });
458
459 it("v2 projection wins outright and sources are never merged", () => {
460 const v2Agent = { ...roster[0]!, id: "v2-only", title: "From v2" };
461 const model = deriveAgentPanelModel({ agents: roster, v2Projection: [v2Agent] });
462 const allIds = [
463 ...model.workflows.map((group) => group.workflow.id),
464 ...model.directAgents.map((agent) => agent.id),
465 ];
466 expect(allIds).toContain("v2-only");
467 expect(allIds).not.toContain("direct-1");
468 });
469
470 it("orphaned members fall back to the direct list", () => {
471 const orphans = fold([
472 activity("task.progress", {
473 taskId: "gone:wf:0",
474 title: "orphan",
475 status: "running",
476 parentAgentId: "gone",
477 }),
478 ]);
479 const model = deriveAgentPanelModel({ agents: orphans });
480 expect(model.workflows).toHaveLength(0);
481 expect(model.directAgents.map((agent) => agent.id)).toEqual(["gone:wf:0"]);
482 });
483});
484
485describe("workflowCardMembers", () => {
486 it("orders by urgency (failed, running, waiting) and reports overflow", () => {
487 const roster = fold([
488 activity("task.started", { taskId: "wf-1", taskType: "local_workflow" }),
489 ...[..."abcdefghij"].map((letter, index) =>
490 activity("task.progress", {
491 taskId: `wf-1:wf:${index}`,
492 title: `agent-${letter}`,
493 status: index === 3 ? "failed" : index < 3 ? "completed" : "running",
494 ...(index === 3 ? { error: "died" } : {}),
495 parentAgentId: "wf-1",
496 agentIndex: index,
497 phaseIndex: 0,
498 phaseTitle: "Work",
499 }),
500 ),
501 ]);
502 const model = deriveAgentPanelModel({ agents: roster });
503 const { visible, overflow } = workflowCardMembers(model.workflows[0]!, 8);
504 expect(visible).toHaveLength(8);
505 expect(overflow).toBe(2);
506 expect(visible[0]!.status).toBe("failed");
507 expect(visible.filter((agent) => agent.status === "completed").length).toBeLessThanOrEqual(2);
508 });
509});
510
511describe("timeline predicates", () => {
512 it("recognizes subagent activity kinds as fold input", () => {
513 for (const kind of [
514 "task.started",
515 "task.progress",
516 "task.updated",
517 "task.completed",
518 "tool.progress",
519 ]) {
520 expect(isSubagentActivityKind(kind)).toBe(true);
521 }
522 expect(isSubagentActivityKind("tool.completed")).toBe(false);
523 });
524
525 it("attributed tool rows are re-homed; unattributed rows stay in the timeline", () => {
526 expect(isAgentAttributedToolActivity(activity("tool.completed", { agentId: "task-1" }))).toBe(
527 true,
528 );
529 expect(isAgentAttributedToolActivity(activity("tool.completed", {}))).toBe(false);
530 expect(isAgentAttributedToolActivity(activity("tool.completed", { agentId: " " }))).toBe(
531 false,
532 );
533 });
534
535 it("timelineBypass rows never render in the parent chat", () => {
536 expect(isTimelineBypassActivity(activity("task.progress", { timelineBypass: true }))).toBe(
537 true,
538 );
539 expect(isTimelineBypassActivity(activity("task.progress", {}))).toBe(false);
540 });
541});
542
543describe("formatSubagentTokenCount", () => {
544 it("formats plain counters", () => {
545 expect(formatSubagentTokenCount(950)).toBe("950");
546 expect(formatSubagentTokenCount(41200)).toBe("41.2k");
547 expect(formatSubagentTokenCount(247000)).toBe("247k");
548 expect(formatSubagentTokenCount(1_400_000)).toBe("1.4M");
549 });
550});
551
552describe("model and effort attribution", () => {
553 it("carries model/effort from start rows and refines model from later rows", () => {
554 const agents = fold([
555 activity("task.started", {
556 taskId: "task-m",
557 title: "Verify math",
558 model: "sonnet",
559 effort: "high",
560 }),
561 // Later row refines with the authoritative API model id; effort absent
562 // must not clear the known value.
563 activity("task.progress", { taskId: "task-m", model: "claude-sonnet-5[1m]" }),
564 ]);
565 expect(agents).toHaveLength(1);
566 expect(agents[0]!.model).toBe("claude-sonnet-5[1m]");
567 expect(agents[0]!.effort).toBe("high");
568 });
569
570 it("formatSubagentModelLabel compacts ids and appends effort", () => {
571 expect(formatSubagentModelLabel("claude-sonnet-5[1m]", "high")).toBe("sonnet-5[1m] · high");
572 expect(formatSubagentModelLabel("claude-opus-4-20250514", null)).toBe("opus-4");
573 expect(formatSubagentModelLabel("gpt-5.6-sol", "low")).toBe("gpt-5.6-sol · low");
574 expect(formatSubagentModelLabel(null, "high")).toBeNull();
575 });
576});
577
578describe("background task exclusion", () => {
579 it("shells and monitors never join the roster (from any lifecycle row)", () => {
580 const agents = fold([
581 activity("task.started", { taskId: "shell-1", taskType: "shell", title: "Run 12s stall" }),
582 activity("task.progress", { taskId: "shell-2", taskType: "shell", title: "Run stall" }),
583 activity("task.completed", { taskId: "mon-1", taskType: "monitor", status: "completed" }),
584 activity("task.started", { taskId: "agent-1", taskType: "subagent", title: "Real agent" }),
585 ]);
586 expect(agents.map((agent) => agent.id)).toEqual(["agent-1"]);
587 });
588
589 it("rows without a taskType stay in the roster (workflow members, Codex children)", () => {
590 const agents = fold([
591 activity("task.progress", { taskId: "wf-1:wf:0", status: "running", parentAgentId: "wf-1" }),
592 ]);
593 expect(agents).toHaveLength(1);
594 });
595
596 it("the server stamp is the only classifier: no stamp means no roster row", () => {
597 const agents = fold([
598 // Stamped background: agent-looking fields don't matter.
599 activity("task.started", {
600 taskId: "bg-1",
601 agentKind: "background",
602 role: "watcher",
603 model: "sonnet",
604 }),
605 // Stamped agent: plain row still joins the roster.
606 activity("task.started", { taskId: "ag-1", agentKind: "agent", detail: "plain row" }),
607 // Legacy pre-stamp rows (old threads/servers) stay in the work log —
608 // exactly their pre-upgrade behavior.
609 legacyActivity("task.started", { taskId: "old-task", detail: "tailing logs" }),
610 legacyActivity("task.progress", { taskId: "old-task", summary: "still tailing" }),
611 ]);
612 expect(agents.map((agent) => agent.id)).toEqual(["ag-1"]);
613 });
614
615 it("membership is sticky: a stampless later row still reaches a known agent", () => {
616 const agents = fold([
617 activity("task.started", { taskId: "a1", taskType: "local_agent", title: "Agent" }),
618 // Terminal row missing the stamp (defensive: adapters synthesize some
619 // rows) — sticky membership still routes it to the agent.
620 legacyActivity("task.completed", { taskId: "a1", status: "completed", summary: "done" }),
621 ]);
622 expect(agents).toHaveLength(1);
623 expect(agents[0]!.status).toBe("completed");
624 expect(agents[0]!.result).toBe("done");
625 });
626});
627
628describe("session-derived interruption", () => {
629 it("dead session interrupts live agents but preserves idle and settled", () => {
630 const rows = [
631 activity("task.started", { taskId: "live-1", taskType: "local_agent" }),
632 activity("task.started", { taskId: "idle-1", taskType: "local_agent" }),
633 activity("task.updated", { taskId: "idle-1", status: "idle" }),
634 activity("task.started", { taskId: "done-1", taskType: "local_agent" }),
635 activity("task.completed", { taskId: "done-1", status: "completed" }),
636 ];
637 const dead = foldSubagentActivities(rows, { sessionLive: false });
638 expect(dead.find((agent) => agent.id === "live-1")?.status).toBe("interrupted");
639 expect(dead.find((agent) => agent.id === "idle-1")?.status).toBe("idle");
640 expect(dead.find((agent) => agent.id === "done-1")?.status).toBe("completed");
641 const alive = foldSubagentActivities(rows, { sessionLive: true });
642 expect(alive.find((agent) => agent.id === "live-1")?.status).toBe("running");
643 });
644});
645
646describe("terminal robustness", () => {
647 it("task.updated creating an agent (start row aged out) counts one activation", () => {
648 const agents = fold([
649 activity("task.updated", { taskId: "orphan-u", status: "running", role: "worker" }),
650 ]);
651 expect(agents).toHaveLength(1);
652 expect(agents[0]!.activationCount).toBe(1);
653 expect(agents[0]!.status).toBe("running");
654 });
655
656 it("a late start after a terminal task.updated does not reopen the run", () => {
657 const agents = fold([
658 activity("task.updated", { taskId: "t1", status: "failed", role: "worker" }),
659 activity("task.started", { taskId: "t1", taskType: "local_agent", title: "Late" }),
660 ]);
661 expect(agents).toHaveLength(1);
662 expect(agents[0]!.status).toBe("failed");
663 expect(agents[0]!.title).toBe("Late");
664 });
665
666 it("a completion after a terminal task.updated still enriches result and usage", () => {
667 // Claude commonly emits terminal task.updated before task.completed;
668 // the completion carries the summary and final usage the update lacked.
669 const agents = fold([
670 activity("task.started", { taskId: "te-1", taskType: "local_agent" }),
671 activity(
672 "task.updated",
673 { taskId: "te-1", status: "completed", endedAt: "2026-08-01T10:59:00.000Z" },
674 "2026-08-01T11:00:00.000Z",
675 ),
676 activity(
677 "task.completed",
678 {
679 taskId: "te-1",
680 status: "completed",
681 summary: "final answer",
682 typedUsage: { totalTokens: 4200, toolUses: 7 },
683 },
684 "2026-08-01T11:00:01.000Z",
685 ),
686 ]);
687 const agent = agents[0]!;
688 expect(agent.status).toBe("completed");
689 expect(agent.result).toBe("final answer");
690 expect(agent.usage?.totalTokens).toBe(4200);
691 // Timestamps stay pinned to the transition that settled the run.
692 expect(agent.completedAt).toBe("2026-08-01T10:59:00.000Z");
693 });
694
695 it("duplicate completions keep the FIRST result, not the last", () => {
696 const agents = fold([
697 activity("task.started", { taskId: "t2", taskType: "local_agent" }),
698 activity("task.completed", { taskId: "t2", status: "completed", summary: "first result" }),
699 activity("task.completed", { taskId: "t2", status: "completed", summary: "second result" }),
700 ]);
701 expect(agents[0]!.result).toBe("first result");
702 });
703
704 it("provider endedAt wins over ingestion time on the settling transition", () => {
705 const agents = fold([
706 activity("task.started", { taskId: "t3", taskType: "local_agent" }),
707 activity(
708 "task.updated",
709 { taskId: "t3", status: "failed", endedAt: "2026-08-01T09:59:59.000Z" },
710 "2026-08-01T10:00:30.000Z",
711 ),
712 ]);
713 expect(agents[0]!.completedAt).toBe("2026-08-01T09:59:59.000Z");
714 });
715
716 it("workflow retries count each attempt once", () => {
717 const agents = fold([
718 activity("task.progress", {
719 taskId: "wf-r:wf:0",
720 parentAgentId: "wf-r",
721 status: "running",
722 attempt: 1,
723 }),
724 activity("task.progress", {
725 taskId: "wf-r:wf:0",
726 parentAgentId: "wf-r",
727 status: "failed",
728 attempt: 1,
729 }),
730 activity("task.progress", {
731 taskId: "wf-r:wf:0",
732 parentAgentId: "wf-r",
733 status: "running",
734 attempt: 2,
735 }),
736 ]);
737 expect(agents[0]!.activationCount).toBe(2);
738 });
739});
740
741describe("phase membership", () => {
742 it("members with unknown phase indices land in unphasedMembers, never vanish", () => {
743 const model = deriveAgentPanelModel({
744 agents: fold([
745 activity("task.started", {
746 taskId: "wf-p",
747 taskType: "local_workflow",
748 phases: [{ index: 0, title: "Only phase" }],
749 }),
750 activity("task.progress", {
751 taskId: "wf-p:wf:0",
752 parentAgentId: "wf-p",
753 status: "running",
754 phaseIndex: 0,
755 }),
756 activity("task.progress", {
757 taskId: "wf-p:wf:9",
758 parentAgentId: "wf-p",
759 status: "running",
760 phaseIndex: 9,
761 }),
762 ]),
763 });
764 const group = model.workflows[0]!;
765 const visible = [
766 ...group.phases.flatMap((phase) => phase.members),
767 ...group.unphasedMembers,
768 ].map((member) => member.id);
769 expect(visible).toContain("wf-p:wf:0");
770 expect(visible).toContain("wf-p:wf:9");
771 });
772});
773
774describe("coordinator settle cascade", () => {
775 it("members without their own terminal row settle when the coordinator does", () => {
776 const agents = fold([
777 activity("task.started", { taskId: "wf-1", taskType: "local_workflow" }),
778 activity("task.progress", {
779 taskId: "wf-1:wf:0",
780 title: "stalled member",
781 status: "running",
782 parentAgentId: "wf-1",
783 }),
784 activity("task.completed", {
785 taskId: "wf-1",
786 status: "completed",
787 taskType: "local_workflow",
788 }),
789 ]);
790 const member = agents.find((agent) => agent.id === "wf-1:wf:0");
791 expect(member?.status).toBe("completed");
792 expect(member?.completedAt).not.toBeNull();
793 });
794
795 it("a failed coordinator marks unfinished members interrupted, not completed", () => {
796 const agents = fold([
797 activity("task.started", { taskId: "wf-2", taskType: "local_workflow" }),
798 activity("task.progress", {
799 taskId: "wf-2:wf:0",
800 status: "running",
801 parentAgentId: "wf-2",
802 }),
803 activity("task.completed", { taskId: "wf-2", status: "failed", taskType: "local_workflow" }),
804 ]);
805 const member = agents.find((agent) => agent.id === "wf-2:wf:0");
806 expect(member?.status).toBe("interrupted");
807 });
808});
809
810describe("task type classification is a denylist", () => {
811 it("unknown agent-flavored types (local_agent, future names) join the roster", () => {
812 const agents = fold([
813 activity("task.started", {
814 taskId: "a1",
815 taskType: "local_agent",
816 title: "Math test 1",
817 role: "claude",
818 }),
819 activity("task.started", { taskId: "a2", taskType: "some_future_agent_kind", title: "X" }),
820 ]);
821 expect(agents.map((agent) => agent.id).toSorted()).toEqual(["a1", "a2"]);
822 });
823});
824
825describe("nested agents vs subagent shells", () => {
826 it("a nested agent (agentId + agent taskType) stays in the roster; its shells do not", () => {
827 const agents = fold([
828 activity("task.started", {
829 taskId: "nested-1",
830 taskType: "local_agent",
831 agentId: "parent-agent",
832 title: "Nested researcher",
833 }),
834 activity("task.started", {
835 taskId: "shell-1",
836 taskType: "local_bash",
837 agentId: "parent-agent",
838 title: "Nested sleep",
839 }),
840 ]);
841 expect(agents.map((agent) => agent.id)).toEqual(["nested-1"]);
842 });
843});