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 // Member 1 is running; the wf-1 coordinator is a container, not a worker.
387 expect(model.runningCount).toBe(1);
388 // Every agent lands in exactly one bucket, except coordinators that stand
389 // in for their members.
390 expect(model.idleCount + model.runningCount + model.waitingCount + model.settledCount).toBe(
391 roster.length - 1,
392 );
393 });
394
395 it("omits a workflow coordinator from the working-agent count", () => {
396 const model = deriveAgentPanelModel({ agents: roster });
397 // One member still running plus one idle direct spawn. The coordinator
398 // reports running for the whole workflow and must not inflate the banner.
399 expect(model.liveCount).toBe(1);
400 });
401
402 it("omits a finished workflow coordinator from the settled count", () => {
403 const finished = fold([
404 activity("task.started", { taskId: "wf-2", taskType: "local_workflow", title: "sweep" }),
405 activity("task.progress", {
406 taskId: "wf-2:wf:0",
407 title: "sweep:a",
408 status: "completed",
409 parentAgentId: "wf-2",
410 agentIndex: 0,
411 phaseIndex: 0,
412 }),
413 activity("task.completed", {
414 taskId: "wf-2:wf:0",
415 status: "completed",
416 parentAgentId: "wf-2",
417 }),
418 activity("task.completed", { taskId: "wf-2", status: "completed" }),
419 ]);
420
421 const model = deriveAgentPanelModel({ agents: finished });
422
423 // Only the member settled. The coordinator stands in for it, so counting
424 // both would report two finished agents where one ran.
425 expect(model.settledCount).toBe(1);
426 expect(model.liveCount).toBe(0);
427 });
428
429 it("keeps direct spawns in first-seen order as their activity changes", () => {
430 const directRoster = fold([
431 activity("task.started", { taskId: "direct-a", title: "First" }, "2026-08-01T11:00:00.000Z"),
432 activity("task.started", { taskId: "direct-b", title: "Second" }, "2026-08-01T11:00:01.000Z"),
433 activity(
434 "task.progress",
435 { taskId: "direct-a", summary: "Newest activity" },
436 "2026-08-01T11:00:02.000Z",
437 ),
438 ]);
439
440 expect(
441 deriveAgentPanelModel({ agents: directRoster }).directAgents.map((agent) => agent.id),
442 ).toEqual(["direct-a", "direct-b"]);
443 });
444
445 it("keeps first-seen order after the roster retention ranking runs", () => {
446 const starts = Array.from({ length: 101 }, (_, index) =>
447 activity(
448 "task.started",
449 { taskId: `capped-${index}`, title: `Agent ${index}` },
450 `2026-08-01T12:${String(Math.floor(index / 60)).padStart(2, "0")}:${String(
451 index % 60,
452 ).padStart(2, "0")}.000Z`,
453 ),
454 );
455 const cappedRoster = fold([
456 ...starts,
457 activity(
458 "task.progress",
459 { taskId: "capped-0", summary: "Newest activity" },
460 "2026-08-01T12:02:00.000Z",
461 ),
462 ]);
463
464 const ids = deriveAgentPanelModel({ agents: cappedRoster }).directAgents.map(
465 (agent) => agent.id,
466 );
467 expect(ids).toHaveLength(100);
468 expect(ids.slice(0, 3)).toEqual(["capped-0", "capped-2", "capped-3"]);
469 expect(ids.at(-1)).toBe("capped-100");
470 });
471
472 it("a phase with only pending members never reads as running", () => {
473 const pendingRoster = fold([
474 activity("task.started", { taskId: "wf-9", taskType: "local_workflow" }),
475 activity("task.progress", {
476 taskId: "wf-9",
477 phases: [{ index: 0, title: "Fix" }],
478 }),
479 activity("task.progress", {
480 taskId: "wf-9:wf:0",
481 title: "fixer",
482 status: "pending",
483 parentAgentId: "wf-9",
484 agentIndex: 0,
485 phaseIndex: 0,
486 }),
487 ]);
488 const model = deriveAgentPanelModel({ agents: pendingRoster });
489 // "pending" counts as active liveness (queued work), so the phase reads
490 // running only if a member is genuinely pending/running — this asserts
491 // the settled-count rule: no member settled, phase not done.
492 expect(model.workflows[0]!.phases[0]!.state).not.toBe("done");
493 });
494
495 it("v2 projection wins outright and sources are never merged", () => {
496 const v2Agent = { ...roster[0]!, id: "v2-only", title: "From v2" };
497 const model = deriveAgentPanelModel({ agents: roster, v2Projection: [v2Agent] });
498 const allIds = [
499 ...model.workflows.map((group) => group.workflow.id),
500 ...model.directAgents.map((agent) => agent.id),
501 ];
502 expect(allIds).toContain("v2-only");
503 expect(allIds).not.toContain("direct-1");
504 });
505
506 it("orphaned members fall back to the direct list", () => {
507 const orphans = fold([
508 activity("task.progress", {
509 taskId: "gone:wf:0",
510 title: "orphan",
511 status: "running",
512 parentAgentId: "gone",
513 }),
514 ]);
515 const model = deriveAgentPanelModel({ agents: orphans });
516 expect(model.workflows).toHaveLength(0);
517 expect(model.directAgents.map((agent) => agent.id)).toEqual(["gone:wf:0"]);
518 });
519});
520
521describe("workflowCardMembers", () => {
522 it("orders by urgency (failed, running, waiting) and reports overflow", () => {
523 const roster = fold([
524 activity("task.started", { taskId: "wf-1", taskType: "local_workflow" }),
525 ...[..."abcdefghij"].map((letter, index) =>
526 activity("task.progress", {
527 taskId: `wf-1:wf:${index}`,
528 title: `agent-${letter}`,
529 status: index === 3 ? "failed" : index < 3 ? "completed" : "running",
530 ...(index === 3 ? { error: "died" } : {}),
531 parentAgentId: "wf-1",
532 agentIndex: index,
533 phaseIndex: 0,
534 phaseTitle: "Work",
535 }),
536 ),
537 ]);
538 const model = deriveAgentPanelModel({ agents: roster });
539 const { visible, overflow } = workflowCardMembers(model.workflows[0]!, 8);
540 expect(visible).toHaveLength(8);
541 expect(overflow).toBe(2);
542 expect(visible[0]!.status).toBe("failed");
543 expect(visible.filter((agent) => agent.status === "completed").length).toBeLessThanOrEqual(2);
544 });
545});
546
547describe("timeline predicates", () => {
548 it("recognizes subagent activity kinds as fold input", () => {
549 for (const kind of [
550 "task.started",
551 "task.progress",
552 "task.updated",
553 "task.completed",
554 "tool.progress",
555 ]) {
556 expect(isSubagentActivityKind(kind)).toBe(true);
557 }
558 expect(isSubagentActivityKind("tool.completed")).toBe(false);
559 });
560
561 it("attributed tool rows are re-homed; unattributed rows stay in the timeline", () => {
562 expect(isAgentAttributedToolActivity(activity("tool.completed", { agentId: "task-1" }))).toBe(
563 true,
564 );
565 expect(isAgentAttributedToolActivity(activity("tool.completed", {}))).toBe(false);
566 expect(isAgentAttributedToolActivity(activity("tool.completed", { agentId: " " }))).toBe(
567 false,
568 );
569 });
570
571 it("timelineBypass rows never render in the parent chat", () => {
572 expect(isTimelineBypassActivity(activity("task.progress", { timelineBypass: true }))).toBe(
573 true,
574 );
575 expect(isTimelineBypassActivity(activity("task.progress", {}))).toBe(false);
576 });
577});
578
579describe("formatSubagentTokenCount", () => {
580 it("formats plain counters", () => {
581 expect(formatSubagentTokenCount(950)).toBe("950");
582 expect(formatSubagentTokenCount(41200)).toBe("41.2k");
583 expect(formatSubagentTokenCount(247000)).toBe("247k");
584 expect(formatSubagentTokenCount(1_400_000)).toBe("1.4M");
585 });
586});
587
588describe("model and effort attribution", () => {
589 it("carries model/effort from start rows and refines model from later rows", () => {
590 const agents = fold([
591 activity("task.started", {
592 taskId: "task-m",
593 title: "Verify math",
594 model: "sonnet",
595 effort: "high",
596 }),
597 // Later row refines with the authoritative API model id; effort absent
598 // must not clear the known value.
599 activity("task.progress", { taskId: "task-m", model: "claude-sonnet-5[1m]" }),
600 ]);
601 expect(agents).toHaveLength(1);
602 expect(agents[0]!.model).toBe("claude-sonnet-5[1m]");
603 expect(agents[0]!.effort).toBe("high");
604 });
605
606 it("applies metadata-only updates without changing the current status", () => {
607 const waitingRows = [
608 activity("task.updated", {
609 taskId: "task-metadata",
610 title: "Check metadata",
611 status: "waiting",
612 }),
613 activity("task.updated", {
614 taskId: "task-metadata",
615 model: "gpt-5.6-sol",
616 effort: "high",
617 }),
618 ];
619 const waitingAgent = fold(waitingRows)[0]!;
620 expect(waitingAgent.status).toBe("waiting");
621 expect(formatSubagentModelLabel(waitingAgent.model, waitingAgent.effort)).toBe(
622 "gpt-5.6-sol · high",
623 );
624
625 const idleRows = [
626 ...waitingRows,
627 activity("task.updated", { taskId: "task-metadata", status: "idle" }),
628 activity("task.updated", { taskId: "task-metadata", model: "gpt-5.6-sol" }),
629 ];
630 expect(fold(idleRows)[0]!.status).toBe("idle");
631
632 const completedAgent = fold([
633 ...idleRows,
634 activity("task.progress", { taskId: "task-metadata", typedUsage: { totalTokens: 42 } }),
635 activity("task.completed", { taskId: "task-metadata", status: "completed" }),
636 activity("task.updated", { taskId: "task-metadata", effort: "high" }),
637 ])[0]!;
638 expect(completedAgent.status).toBe("completed");
639 expect(completedAgent.model).toBe("gpt-5.6-sol");
640 expect(completedAgent.effort).toBe("high");
641 });
642
643 it("formatSubagentModelLabel compacts ids and appends effort", () => {
644 expect(formatSubagentModelLabel("claude-sonnet-5[1m]", "high")).toBe("sonnet-5[1m] · high");
645 expect(formatSubagentModelLabel("claude-opus-4-20250514", null)).toBe("opus-4");
646 expect(formatSubagentModelLabel("gpt-5.6-sol", "low")).toBe("gpt-5.6-sol · low");
647 expect(formatSubagentModelLabel(null, "high")).toBeNull();
648 });
649});
650
651describe("background task exclusion", () => {
652 it("shells and monitors never join the roster (from any lifecycle row)", () => {
653 const agents = fold([
654 activity("task.started", { taskId: "shell-1", taskType: "shell", title: "Run 12s stall" }),
655 activity("task.progress", { taskId: "shell-2", taskType: "shell", title: "Run stall" }),
656 activity("task.completed", { taskId: "mon-1", taskType: "monitor", status: "completed" }),
657 activity("task.started", { taskId: "agent-1", taskType: "subagent", title: "Real agent" }),
658 ]);
659 expect(agents.map((agent) => agent.id)).toEqual(["agent-1"]);
660 });
661
662 it("rows without a taskType stay in the roster (workflow members, Codex children)", () => {
663 const agents = fold([
664 activity("task.progress", { taskId: "wf-1:wf:0", status: "running", parentAgentId: "wf-1" }),
665 ]);
666 expect(agents).toHaveLength(1);
667 });
668
669 it("the server stamp is the only classifier: no stamp means no roster row", () => {
670 const agents = fold([
671 // Stamped background: agent-looking fields don't matter.
672 activity("task.started", {
673 taskId: "bg-1",
674 agentKind: "background",
675 role: "watcher",
676 model: "sonnet",
677 }),
678 // Stamped agent: plain row still joins the roster.
679 activity("task.started", { taskId: "ag-1", agentKind: "agent", detail: "plain row" }),
680 // Legacy pre-stamp rows (old threads/servers) stay in the work log —
681 // exactly their pre-upgrade behavior.
682 legacyActivity("task.started", { taskId: "old-task", detail: "tailing logs" }),
683 legacyActivity("task.progress", { taskId: "old-task", summary: "still tailing" }),
684 ]);
685 expect(agents.map((agent) => agent.id)).toEqual(["ag-1"]);
686 });
687
688 it("membership is sticky: a stampless later row still reaches a known agent", () => {
689 const agents = fold([
690 activity("task.started", { taskId: "a1", taskType: "local_agent", title: "Agent" }),
691 // Terminal row missing the stamp (defensive: adapters synthesize some
692 // rows) — sticky membership still routes it to the agent.
693 legacyActivity("task.completed", { taskId: "a1", status: "completed", summary: "done" }),
694 ]);
695 expect(agents).toHaveLength(1);
696 expect(agents[0]!.status).toBe("completed");
697 expect(agents[0]!.result).toBe("done");
698 });
699});
700
701describe("session-derived interruption", () => {
702 it("dead session interrupts live agents but preserves idle and settled", () => {
703 const rows = [
704 activity("task.started", { taskId: "live-1", taskType: "local_agent" }),
705 activity("task.started", { taskId: "idle-1", taskType: "local_agent" }),
706 activity("task.updated", { taskId: "idle-1", status: "idle" }),
707 activity("task.started", { taskId: "done-1", taskType: "local_agent" }),
708 activity("task.completed", { taskId: "done-1", status: "completed" }),
709 ];
710 const dead = foldSubagentActivities(rows, { sessionLive: false });
711 expect(dead.find((agent) => agent.id === "live-1")?.status).toBe("interrupted");
712 expect(dead.find((agent) => agent.id === "idle-1")?.status).toBe("idle");
713 expect(dead.find((agent) => agent.id === "done-1")?.status).toBe("completed");
714 const alive = foldSubagentActivities(rows, { sessionLive: true });
715 expect(alive.find((agent) => agent.id === "live-1")?.status).toBe("running");
716 });
717});
718
719describe("terminal robustness", () => {
720 it("task.updated creating an agent (start row aged out) counts one activation", () => {
721 const agents = fold([
722 activity("task.updated", { taskId: "orphan-u", status: "running", role: "worker" }),
723 ]);
724 expect(agents).toHaveLength(1);
725 expect(agents[0]!.activationCount).toBe(1);
726 expect(agents[0]!.status).toBe("running");
727 });
728
729 it("a late start after a terminal task.updated does not reopen the run", () => {
730 const agents = fold([
731 activity("task.updated", { taskId: "t1", status: "failed", role: "worker" }),
732 activity("task.started", { taskId: "t1", taskType: "local_agent", title: "Late" }),
733 ]);
734 expect(agents).toHaveLength(1);
735 expect(agents[0]!.status).toBe("failed");
736 expect(agents[0]!.title).toBe("Late");
737 });
738
739 it("a completion after a terminal task.updated still enriches result and usage", () => {
740 // Claude commonly emits terminal task.updated before task.completed;
741 // the completion carries the summary and final usage the update lacked.
742 const agents = fold([
743 activity("task.started", { taskId: "te-1", taskType: "local_agent" }),
744 activity(
745 "task.updated",
746 { taskId: "te-1", status: "completed", endedAt: "2026-08-01T10:59:00.000Z" },
747 "2026-08-01T11:00:00.000Z",
748 ),
749 activity(
750 "task.completed",
751 {
752 taskId: "te-1",
753 status: "completed",
754 summary: "final answer",
755 typedUsage: { totalTokens: 4200, toolUses: 7 },
756 },
757 "2026-08-01T11:00:01.000Z",
758 ),
759 ]);
760 const agent = agents[0]!;
761 expect(agent.status).toBe("completed");
762 expect(agent.result).toBe("final answer");
763 expect(agent.usage?.totalTokens).toBe(4200);
764 // Timestamps stay pinned to the transition that settled the run.
765 expect(agent.completedAt).toBe("2026-08-01T10:59:00.000Z");
766 });
767
768 it("duplicate completions keep the FIRST result, not the last", () => {
769 const agents = fold([
770 activity("task.started", { taskId: "t2", taskType: "local_agent" }),
771 activity("task.completed", { taskId: "t2", status: "completed", summary: "first result" }),
772 activity("task.completed", { taskId: "t2", status: "completed", summary: "second result" }),
773 ]);
774 expect(agents[0]!.result).toBe("first result");
775 });
776
777 it("provider endedAt wins over ingestion time on the settling transition", () => {
778 const agents = fold([
779 activity("task.started", { taskId: "t3", taskType: "local_agent" }),
780 activity(
781 "task.updated",
782 { taskId: "t3", status: "failed", endedAt: "2026-08-01T09:59:59.000Z" },
783 "2026-08-01T10:00:30.000Z",
784 ),
785 ]);
786 expect(agents[0]!.completedAt).toBe("2026-08-01T09:59:59.000Z");
787 });
788
789 it("workflow retries count each attempt once", () => {
790 const agents = fold([
791 activity("task.progress", {
792 taskId: "wf-r:wf:0",
793 parentAgentId: "wf-r",
794 status: "running",
795 attempt: 1,
796 }),
797 activity("task.progress", {
798 taskId: "wf-r:wf:0",
799 parentAgentId: "wf-r",
800 status: "failed",
801 attempt: 1,
802 }),
803 activity("task.progress", {
804 taskId: "wf-r:wf:0",
805 parentAgentId: "wf-r",
806 status: "running",
807 attempt: 2,
808 }),
809 ]);
810 expect(agents[0]!.activationCount).toBe(2);
811 });
812});
813
814describe("phase membership", () => {
815 it("members with unknown phase indices land in unphasedMembers, never vanish", () => {
816 const model = deriveAgentPanelModel({
817 agents: fold([
818 activity("task.started", {
819 taskId: "wf-p",
820 taskType: "local_workflow",
821 phases: [{ index: 0, title: "Only phase" }],
822 }),
823 activity("task.progress", {
824 taskId: "wf-p:wf:0",
825 parentAgentId: "wf-p",
826 status: "running",
827 phaseIndex: 0,
828 }),
829 activity("task.progress", {
830 taskId: "wf-p:wf:9",
831 parentAgentId: "wf-p",
832 status: "running",
833 phaseIndex: 9,
834 }),
835 ]),
836 });
837 const group = model.workflows[0]!;
838 const visible = [
839 ...group.phases.flatMap((phase) => phase.members),
840 ...group.unphasedMembers,
841 ].map((member) => member.id);
842 expect(visible).toContain("wf-p:wf:0");
843 expect(visible).toContain("wf-p:wf:9");
844 });
845});
846
847describe("coordinator settle cascade", () => {
848 it("members without their own terminal row settle when the coordinator does", () => {
849 const agents = fold([
850 activity("task.started", { taskId: "wf-1", taskType: "local_workflow" }),
851 activity("task.progress", {
852 taskId: "wf-1:wf:0",
853 title: "stalled member",
854 status: "running",
855 parentAgentId: "wf-1",
856 }),
857 activity("task.completed", {
858 taskId: "wf-1",
859 status: "completed",
860 taskType: "local_workflow",
861 }),
862 ]);
863 const member = agents.find((agent) => agent.id === "wf-1:wf:0");
864 expect(member?.status).toBe("completed");
865 expect(member?.completedAt).not.toBeNull();
866 });
867
868 it("a failed coordinator marks unfinished members interrupted, not completed", () => {
869 const agents = fold([
870 activity("task.started", { taskId: "wf-2", taskType: "local_workflow" }),
871 activity("task.progress", {
872 taskId: "wf-2:wf:0",
873 status: "running",
874 parentAgentId: "wf-2",
875 }),
876 activity("task.completed", { taskId: "wf-2", status: "failed", taskType: "local_workflow" }),
877 ]);
878 const member = agents.find((agent) => agent.id === "wf-2:wf:0");
879 expect(member?.status).toBe("interrupted");
880 });
881});
882
883describe("task type classification is a denylist", () => {
884 it("unknown agent-flavored types (local_agent, future names) join the roster", () => {
885 const agents = fold([
886 activity("task.started", {
887 taskId: "a1",
888 taskType: "local_agent",
889 title: "Math test 1",
890 role: "claude",
891 }),
892 activity("task.started", { taskId: "a2", taskType: "some_future_agent_kind", title: "X" }),
893 ]);
894 expect(agents.map((agent) => agent.id).toSorted()).toEqual(["a1", "a2"]);
895 });
896});
897
898describe("nested agents vs subagent shells", () => {
899 it("a nested agent (agentId + agent taskType) stays in the roster; its shells do not", () => {
900 const agents = fold([
901 activity("task.started", {
902 taskId: "nested-1",
903 taskType: "local_agent",
904 agentId: "parent-agent",
905 title: "Nested researcher",
906 }),
907 activity("task.started", {
908 taskId: "shell-1",
909 taskType: "local_bash",
910 agentId: "parent-agent",
911 title: "Nested sleep",
912 }),
913 ]);
914 expect(agents.map((agent) => agent.id)).toEqual(["nested-1"]);
915 });
916});