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