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