Open History to see the last commit
1/**
2 * Native-provider subagent observability: a tolerant fold over persisted
3 * task.* / tool.* thread activities into orchestration-v2-shaped subagent
4 * state, plus the source-neutral panel model every client renders.
5 *
6 * This module is deliberately legacy-bridge code. When orchestration-v2's
7 * subagent projection is available for a thread, deriveAgentPanelModel
8 * prefers it (see the v2Projection parameter) and the fold is skipped; when
9 * the v1 orchestrator is retired this file is deleted. Field names and
10 * transition semantics copy the v2 stack (#4779) exactly so that swap is
11 * mechanical.
12 *
13 * Invariants encoded here trace to shipped bugs in the prior PRs (#4220,
14 * #3650, #4662): reusable identity vs one-shot activations, idle as a real
15 * nonterminal state, provider-specific usage merges, first-write terminal
16 * timestamps, reactivation clearing terminal detail, and order-robust
17 * folding (completion can create an agent; a late start only fills
18 * metadata).
19 */
20import * as DateTime from "effect/DateTime";
21import type { OrchestrationThreadActivity } from "@t3tools/contracts";
22
23export type RuntimeSubagentStatus =
24 | "pending"
25 | "running"
26 | "waiting"
27 | "idle"
28 | "completed"
29 | "failed"
30 | "cancelled"
31 | "interrupted";
32
33export interface SubagentUsage {
34 readonly totalTokens: number;
35 readonly inputTokens?: number;
36 readonly cachedInputTokens?: number;
37 readonly outputTokens?: number;
38 readonly reasoningOutputTokens?: number;
39 readonly toolUses?: number;
40 readonly durationMs?: number;
41}
42
43export interface SubagentActivityEntry {
44 readonly at: string;
45 readonly summary: string;
46}
47
48export interface SubagentWorkflowPhase {
49 readonly index: number;
50 readonly title: string;
51}
52
53export interface SubagentRunHandles {
54 readonly runId?: string;
55 readonly scriptPath?: string;
56 readonly transcriptDir?: string;
57 readonly sessionUrl?: string;
58}
59
60export interface RuntimeSubagent {
61 readonly id: string;
62 readonly kind: "subagent" | "workflow" | "workflow_agent";
63 readonly title: string;
64 readonly role: string | null;
65 readonly model: string | null;
66 readonly effort: string | null;
67 readonly status: RuntimeSubagentStatus;
68 readonly activationCount: number;
69 readonly usage: SubagentUsage | null;
70 readonly progress: string | null;
71 readonly lastToolName: string | null;
72 readonly result: string | null;
73 readonly error: string | null;
74 readonly outputFile: string | null;
75 readonly parentAgentId: string | null;
76 readonly agentIndex: number | null;
77 readonly phaseIndex: number | null;
78 readonly phaseTitle: string | null;
79 readonly attempt: number | null;
80 readonly workflowName: string | null;
81 readonly phases: ReadonlyArray<SubagentWorkflowPhase>;
82 readonly runHandles: SubagentRunHandles | null;
83 readonly recentActivity: ReadonlyArray<SubagentActivityEntry>;
84 /** First retained observation, used as the roster's stable display order. */
85 readonly firstSeenAt: string;
86 readonly startedAt: string | null;
87 readonly completedAt: string | null;
88 readonly updatedAt: string;
89}
90
91const TERMINAL_STATUSES: ReadonlySet<RuntimeSubagentStatus> = new Set([
92 "completed",
93 "failed",
94 "cancelled",
95 "interrupted",
96]);
97
98export function isTerminalSubagentStatus(status: RuntimeSubagentStatus): boolean {
99 return TERMINAL_STATUSES.has(status);
100}
101
102/** Active = the user may still need to care while it runs. Idle is settled-ish
103 * but resumable; waiting counts as active because it needs the user. */
104export function isActiveSubagentStatus(status: RuntimeSubagentStatus): boolean {
105 return status === "pending" || status === "running" || status === "waiting";
106}
107
108const RECENT_ACTIVITY_LIMIT = 6;
109const SUMMARY_CHAR_LIMIT = 180;
110const ROSTER_LIMIT = 100;
111
112/**
113 * True when this activity's payload does NOT belong on the Agents surface.
114 * Classification happens exactly once, server-side at ingestion
115 * (classifyTaskAgentKind → the persisted agentKind stamp); the client only
116 * reads it. Rows without a stamp — legacy threads, pre-stamp servers — are
117 * background by definition: they render in the ordinary work log, exactly
118 * as they did before this feature existed.
119 */
120export function isBackgroundTaskActivity(payload: Record<string, unknown>): boolean {
121 return payload.agentKind !== "agent";
122}
123
124function bounded(value: string): string {
125 return value.length <= SUMMARY_CHAR_LIMIT ? value : `${value.slice(0, SUMMARY_CHAR_LIMIT - 1)}…`;
126}
127
128/** Appends to the ring buffer, deduping consecutive identical summaries. */
129function appendActivity(
130 entries: ReadonlyArray<SubagentActivityEntry>,
131 at: string,
132 summary: string,
133): ReadonlyArray<SubagentActivityEntry> {
134 const boundedSummary = bounded(summary);
135 if (entries.length > 0 && entries[entries.length - 1]?.summary === boundedSummary) {
136 return entries;
137 }
138 const next = [...entries, { at, summary: boundedSummary }];
139 return next.length > RECENT_ACTIVITY_LIMIT ? next.slice(-RECENT_ACTIVITY_LIMIT) : next;
140}
141
142function asString(value: unknown): string | undefined {
143 return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
144}
145
146function asCount(value: unknown): number | undefined {
147 return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
148}
149
150function asUsage(value: unknown): SubagentUsage | undefined {
151 if (typeof value !== "object" || value === null) {
152 return undefined;
153 }
154 const record = value as Record<string, unknown>;
155 const totalTokens = asCount(record.totalTokens);
156 if (totalTokens === undefined) {
157 return undefined;
158 }
159 const usage: {
160 totalTokens: number;
161 inputTokens?: number;
162 cachedInputTokens?: number;
163 outputTokens?: number;
164 reasoningOutputTokens?: number;
165 toolUses?: number;
166 durationMs?: number;
167 } = { totalTokens };
168 const inputTokens = asCount(record.inputTokens);
169 if (inputTokens !== undefined) usage.inputTokens = inputTokens;
170 const cachedInputTokens = asCount(record.cachedInputTokens);
171 if (cachedInputTokens !== undefined) usage.cachedInputTokens = cachedInputTokens;
172 const outputTokens = asCount(record.outputTokens);
173 if (outputTokens !== undefined) usage.outputTokens = outputTokens;
174 const reasoningOutputTokens = asCount(record.reasoningOutputTokens);
175 if (reasoningOutputTokens !== undefined) usage.reasoningOutputTokens = reasoningOutputTokens;
176 const toolUses = asCount(record.toolUses);
177 if (toolUses !== undefined) usage.toolUses = toolUses;
178 const durationMs = asCount(record.durationMs);
179 if (durationMs !== undefined) usage.durationMs = durationMs;
180 return usage;
181}
182
183/**
184 * Provider-specific usage merge (#4779 semantics, verbatim):
185 * - max-merge (Codex-style cumulative frames): field-wise maximum, idempotent
186 * under duplicate or late frames. Cumulative totals never shrink.
187 * - accumulate (Claude-style activation deltas): not needed at this layer —
188 * Claude's task_progress usage is itself cumulative per task, so the fold
189 * also max-merges. The distinction matters when v2 sums activations.
190 * Field-wise: a terminal payload carrying only totalTokens must not wipe a
191 * known breakdown.
192 */
193function mergeUsageMax(
194 current: SubagentUsage | null,
195 incoming: SubagentUsage | undefined,
196): SubagentUsage | null {
197 if (!incoming) {
198 return current;
199 }
200 if (!current) {
201 return incoming;
202 }
203 const pick = (a: number | undefined, b: number | undefined): number | undefined =>
204 a === undefined ? b : b === undefined ? a : Math.max(a, b);
205 const merged: {
206 totalTokens: number;
207 inputTokens?: number;
208 cachedInputTokens?: number;
209 outputTokens?: number;
210 reasoningOutputTokens?: number;
211 toolUses?: number;
212 durationMs?: number;
213 } = { totalTokens: Math.max(current.totalTokens, incoming.totalTokens) };
214 const inputTokens = pick(current.inputTokens, incoming.inputTokens);
215 if (inputTokens !== undefined) merged.inputTokens = inputTokens;
216 const cachedInputTokens = pick(current.cachedInputTokens, incoming.cachedInputTokens);
217 if (cachedInputTokens !== undefined) merged.cachedInputTokens = cachedInputTokens;
218 const outputTokens = pick(current.outputTokens, incoming.outputTokens);
219 if (outputTokens !== undefined) merged.outputTokens = outputTokens;
220 const reasoningOutputTokens = pick(current.reasoningOutputTokens, incoming.reasoningOutputTokens);
221 if (reasoningOutputTokens !== undefined) merged.reasoningOutputTokens = reasoningOutputTokens;
222 const toolUses = pick(current.toolUses, incoming.toolUses);
223 if (toolUses !== undefined) merged.toolUses = toolUses;
224 const durationMs = pick(current.durationMs, incoming.durationMs);
225 if (durationMs !== undefined) merged.durationMs = durationMs;
226 return merged;
227}
228
229interface MutableAgent {
230 id: string;
231 kind: RuntimeSubagent["kind"];
232 title: string;
233 role: string | null;
234 model: string | null;
235 effort: string | null;
236 status: RuntimeSubagentStatus;
237 activationCount: number;
238 usage: SubagentUsage | null;
239 progress: string | null;
240 lastToolName: string | null;
241 result: string | null;
242 error: string | null;
243 outputFile: string | null;
244 parentAgentId: string | null;
245 agentIndex: number | null;
246 phaseIndex: number | null;
247 phaseTitle: string | null;
248 attempt: number | null;
249 workflowName: string | null;
250 phases: ReadonlyArray<SubagentWorkflowPhase>;
251 runHandles: SubagentRunHandles | null;
252 recentActivity: ReadonlyArray<SubagentActivityEntry>;
253 firstSeenAt: string;
254 startedAt: string | null;
255 completedAt: string | null;
256 updatedAt: string;
257}
258
259function kindFromPayload(
260 payload: Record<string, unknown>,
261 agentId: string,
262): RuntimeSubagent["kind"] {
263 if (asString(payload.taskType) === "local_workflow") {
264 return "workflow";
265 }
266 if (payload.parentAgentId !== undefined || agentId.includes(":wf:")) {
267 return "workflow_agent";
268 }
269 return "subagent";
270}
271
272/** Completion can create an agent (its start may have aged out of retention). */
273function getOrCreate(
274 agents: Map<string, MutableAgent>,
275 id: string,
276 payload: Record<string, unknown>,
277 at: string,
278): MutableAgent {
279 const existing = agents.get(id);
280 if (existing) {
281 return existing;
282 }
283 const created: MutableAgent = {
284 id,
285 kind: kindFromPayload(payload, id),
286 title: asString(payload.title) ?? asString(payload.detail) ?? id,
287 role: asString(payload.role) ?? null,
288 model: asString(payload.model) ?? null,
289 effort: asString(payload.effort) ?? null,
290 status: "pending",
291 activationCount: 0,
292 usage: null,
293 progress: null,
294 lastToolName: null,
295 result: null,
296 error: null,
297 outputFile: null,
298 parentAgentId: asString(payload.parentAgentId) ?? null,
299 agentIndex: asCount(payload.agentIndex) ?? null,
300 phaseIndex: asCount(payload.phaseIndex) ?? null,
301 phaseTitle: asString(payload.phaseTitle) ?? null,
302 attempt: asCount(payload.attempt) ?? null,
303 workflowName: asString(payload.workflowName) ?? null,
304 phases: [],
305 runHandles: null,
306 recentActivity: [],
307 firstSeenAt: at,
308 startedAt: null,
309 completedAt: null,
310 updatedAt: at,
311 };
312 agents.set(id, created);
313 return created;
314}
315
316/** Metadata fill from any payload: never downgrades known values to null. */
317function fillMetadata(agent: MutableAgent, payload: Record<string, unknown>): void {
318 const title = asString(payload.title);
319 if (title) agent.title = title;
320 const role = asString(payload.role);
321 if (role) agent.role = role;
322 const model = asString(payload.model);
323 if (model) agent.model = model;
324 const effort = asString(payload.effort);
325 if (effort) agent.effort = effort;
326 const parentAgentId = asString(payload.parentAgentId);
327 if (parentAgentId) {
328 agent.parentAgentId = parentAgentId;
329 if (agent.kind === "subagent") agent.kind = "workflow_agent";
330 }
331 const workflowName = asString(payload.workflowName);
332 if (workflowName) agent.workflowName = workflowName;
333 if (asString(payload.taskType) === "local_workflow") agent.kind = "workflow";
334 const agentIndex = asCount(payload.agentIndex);
335 if (agentIndex !== undefined) agent.agentIndex = agentIndex;
336 const phaseIndex = asCount(payload.phaseIndex);
337 if (phaseIndex !== undefined) agent.phaseIndex = phaseIndex;
338 const phaseTitle = asString(payload.phaseTitle);
339 if (phaseTitle) agent.phaseTitle = phaseTitle;
340 const attempt = asCount(payload.attempt);
341 if (attempt !== undefined) {
342 // A new attempt on a workflow slot is a reactivation of the same
343 // identity: clear the previous attempt's terminal detail so the status
344 // transition (terminal → running, in applyStatus) reads as a fresh run.
345 // The activation bump lives ONLY in applyStatus — bumping here too
346 // counted every retry twice (review finding: two attempts read "run 3").
347 if (agent.attempt !== null && attempt > agent.attempt) {
348 agent.result = null;
349 agent.error = null;
350 agent.completedAt = null;
351 }
352 agent.attempt = attempt;
353 }
354 const outputFile = asString(payload.outputFile);
355 if (outputFile) agent.outputFile = outputFile;
356 if (Array.isArray(payload.phases)) {
357 const phases: SubagentWorkflowPhase[] = [];
358 for (const entry of payload.phases) {
359 if (typeof entry !== "object" || entry === null) continue;
360 const record = entry as Record<string, unknown>;
361 const index = asCount(record.index);
362 const phaseName = asString(record.title);
363 if (index !== undefined && phaseName) {
364 phases.push({ index, title: phaseName });
365 }
366 }
367 if (phases.length > 0) {
368 agent.phases = phases.slice().sort((a, b) => a.index - b.index);
369 }
370 }
371 if (typeof payload.runHandles === "object" && payload.runHandles !== null) {
372 const record = payload.runHandles as Record<string, unknown>;
373 const runHandles: {
374 runId?: string;
375 scriptPath?: string;
376 transcriptDir?: string;
377 sessionUrl?: string;
378 } = {};
379 const runId = asString(record.runId);
380 if (runId) runHandles.runId = runId;
381 const scriptPath = asString(record.scriptPath);
382 if (scriptPath) runHandles.scriptPath = scriptPath;
383 const transcriptDir = asString(record.transcriptDir);
384 if (transcriptDir) runHandles.transcriptDir = transcriptDir;
385 // Defense-in-depth: the adapter already sanitizes, but payloads are not
386 // schema-validated on the read path (shipped XSS lesson).
387 const sessionUrl = asString(record.sessionUrl);
388 if (sessionUrl && /^https?:\/\//i.test(sessionUrl)) runHandles.sessionUrl = sessionUrl;
389 if (Object.keys(runHandles).length > 0) {
390 agent.runHandles = { ...agent.runHandles, ...runHandles };
391 }
392 }
393}
394
395function applyStatus(agent: MutableAgent, status: RuntimeSubagentStatus, at: string): void {
396 const wasTerminal = isTerminalSubagentStatus(agent.status);
397 const isTerminal = isTerminalSubagentStatus(status);
398 if (wasTerminal && isTerminal) {
399 // Duplicate terminal events are idempotent: first write wins, timestamps
400 // don't slide.
401 return;
402 }
403 if ((wasTerminal || agent.status === "idle") && (status === "running" || status === "pending")) {
404 // Reactivation: same identity, new run. Clear the previous run's terminal
405 // detail so a live card never shows the prior run's output.
406 agent.activationCount += 1;
407 agent.result = null;
408 agent.error = null;
409 agent.completedAt = null;
410 if (status === "running") {
411 agent.startedAt = at;
412 }
413 }
414 if (status === "running" && agent.startedAt === null) {
415 agent.startedAt = at;
416 }
417 if (isTerminal && agent.completedAt === null) {
418 agent.completedAt = at;
419 }
420 agent.status = status;
421}
422
423// Map, not object literal: payloads aren't schema-validated on the read
424// path, so a status like "toString" must miss instead of resolving an
425// inherited Function through the prototype chain.
426const TASK_COMPLETED_STATUS: ReadonlyMap<string, RuntimeSubagentStatus> = new Map([
427 ["completed", "completed"],
428 ["failed", "failed"],
429 ["stopped", "interrupted"],
430]);
431
432const KNOWN_STATUSES: ReadonlySet<string> = new Set([
433 "pending",
434 "running",
435 "waiting",
436 "idle",
437 "completed",
438 "failed",
439 "cancelled",
440 "interrupted",
441]);
442
443function asRuntimeStatus(value: unknown): RuntimeSubagentStatus | undefined {
444 return typeof value === "string" && KNOWN_STATUSES.has(value)
445 ? (value as RuntimeSubagentStatus)
446 : undefined;
447}
448
449/**
450 * Folds a thread's persisted activities into subagent state. Tolerant by
451 * construction: malformed rows are skipped individually; unknown kinds are
452 * ignored. Pure — memoize by activity-list identity at the atom layer.
453 *
454 * sessionLive=false derives interruption: background tasks die with their
455 * provider session, so agents whose terminal rows were lost (server
456 * restart, crash) must not read as running forever (review finding: a dead
457 * session left a panel full of "Working" agents while the sidebar showed
458 * nothing). Idle is preserved — a resumable Codex child stays resumable.
459 */
460export function foldSubagentActivities(
461 activities: ReadonlyArray<OrchestrationThreadActivity>,
462 options?: { readonly sessionLive?: boolean },
463): ReadonlyArray<RuntimeSubagent> {
464 const agents = new Map<string, MutableAgent>();
465
466 for (const activity of activities) {
467 if (typeof activity.payload !== "object" || activity.payload === null) {
468 continue;
469 }
470 const payload = activity.payload as Record<string, unknown>;
471 const at = activity.createdAt;
472
473 switch (activity.kind) {
474 case "task.started": {
475 const taskId = asString(payload.taskId);
476 if (!taskId) break;
477 // Only real agents join the roster. Shells, monitors, and plan-mode
478 // tasks are background work — they render in the ordinary work log,
479 // not the Agents surface (a "Run 12s stall" shell is not a subagent).
480 if (isBackgroundTaskActivity(payload)) break;
481 const agent = getOrCreate(agents, taskId, payload, at);
482 fillMetadata(agent, payload);
483 // Order-robustness: a start row arriving after a terminal state is a
484 // late/out-of-order delivery and only fills metadata — it must not
485 // reopen the run. Reactivation comes exclusively from explicit
486 // status transitions (task.updated / progress status). Guard on the
487 // status itself, not activationCount: a task first seen via a
488 // terminal task.updated has zero activations but is still settled
489 // (review finding: a late start reopened a failed child).
490 if (agent.activationCount === 0 && !isTerminalSubagentStatus(agent.status)) {
491 agent.activationCount = 1;
492 agent.startedAt = agent.startedAt ?? at;
493 agent.status = "running";
494 } else if (agent.status === "idle") {
495 applyStatus(agent, "running", at);
496 }
497 const detail = asString(payload.detail);
498 if (detail && agent.title === agent.id) agent.title = detail;
499 agent.updatedAt = at;
500 break;
501 }
502 case "task.progress": {
503 const taskId = asString(payload.taskId);
504 if (!taskId) break;
505 // Membership is sticky per taskId: rows after the first (terminal
506 // rows often carry only taskId+status, no marker fields) inherit the
507 // first row's classification instead of being re-judged.
508 const existed = agents.has(taskId);
509 if (!existed && isBackgroundTaskActivity(payload)) break;
510 const agent = getOrCreate(agents, taskId, payload, at);
511 fillMetadata(agent, payload);
512 if (agent.activationCount === 0) agent.activationCount = 1;
513 const explicitStatus = asRuntimeStatus(payload.status);
514 if (explicitStatus) {
515 applyStatus(agent, explicitStatus, at);
516 } else if (
517 (payload.usageSnapshot !== true || !existed) &&
518 !isTerminalSubagentStatus(agent.status) &&
519 agent.status !== "idle"
520 ) {
521 applyStatus(agent, "running", at);
522 }
523 const summary = asString(payload.summary);
524 if (summary) {
525 agent.progress = bounded(summary);
526 agent.recentActivity = appendActivity(agent.recentActivity, at, summary);
527 }
528 const lastToolName = asString(payload.lastToolName);
529 if (lastToolName) {
530 agent.lastToolName = lastToolName;
531 if (!summary) {
532 agent.recentActivity = appendActivity(agent.recentActivity, at, `▸ ${lastToolName}`);
533 }
534 }
535 const error = asString(payload.error);
536 if (error) agent.error = bounded(error);
537 agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));
538 agent.updatedAt = at;
539 break;
540 }
541 case "task.updated": {
542 const taskId = asString(payload.taskId);
543 if (!taskId) break;
544 // Membership is sticky per taskId: rows after the first (terminal
545 // rows often carry only taskId+status, no marker fields) inherit the
546 // first row's classification instead of being re-judged.
547 if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;
548 const agent = getOrCreate(agents, taskId, payload, at);
549 fillMetadata(agent, payload);
550 // A task first seen via task.updated (start row aged out) has run at
551 // least once — zero activations would misreport "run 0" and let a
552 // later start row treat it as never-started (review finding).
553 if (agent.activationCount === 0) agent.activationCount = 1;
554 const wasTerminal = isTerminalSubagentStatus(agent.status);
555 const status = asRuntimeStatus(payload.status);
556 if (status) applyStatus(agent, status, at);
557 const error = asString(payload.error);
558 if (error) agent.error = bounded(error);
559 // Provider end time beats ingestion time for the transition that
560 // actually settled the run (applyStatus fills completedAt with the
561 // activity timestamp first, so check the transition, not null).
562 const endedAt = asString(payload.endedAt);
563 if (endedAt && !wasTerminal && isTerminalSubagentStatus(agent.status)) {
564 agent.completedAt = endedAt;
565 }
566 agent.updatedAt = at;
567 break;
568 }
569 case "task.completed": {
570 const taskId = asString(payload.taskId);
571 if (!taskId) break;
572 // Membership is sticky per taskId: rows after the first (terminal
573 // rows often carry only taskId+status, no marker fields) inherit the
574 // first row's classification instead of being re-judged.
575 if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;
576 const agent = getOrCreate(agents, taskId, payload, at);
577 fillMetadata(agent, payload);
578 if (agent.activationCount === 0) agent.activationCount = 1;
579 // Already-terminal: status and timestamps are frozen (first write
580 // wins, duplicates must not slide them) but the completion still
581 // ENRICHES — Claude commonly emits terminal task.updated before
582 // task.completed, and the completion carries the result summary and
583 // final usage the update lacked (review finding: the early return
584 // dropped both). Fill-if-missing keeps duplicate completions from
585 // replacing the first result.
586 const summary = asString(payload.summary) ?? asString(payload.detail);
587 if (isTerminalSubagentStatus(agent.status)) {
588 if (summary) {
589 if (agent.status === "failed") {
590 agent.error = agent.error ?? bounded(summary);
591 } else {
592 agent.result = agent.result ?? bounded(summary);
593 }
594 }
595 agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));
596 break;
597 }
598 const status = TASK_COMPLETED_STATUS.get(asString(payload.status) ?? "") ?? "completed";
599 applyStatus(agent, status, at);
600 if (summary) {
601 if (status === "failed") {
602 agent.error = agent.error ?? bounded(summary);
603 } else {
604 agent.result = bounded(summary);
605 }
606 }
607 agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));
608 agent.updatedAt = at;
609 break;
610 }
611 case "tool.progress": {
612 // Agent-owned heartbeat: "what it's doing right now".
613 const taskId = asString(payload.taskId);
614 if (!taskId) break;
615 const agent = agents.get(taskId);
616 if (!agent) break;
617 const toolName = asString(payload.toolName);
618 if (toolName) {
619 agent.lastToolName = toolName;
620 agent.recentActivity = appendActivity(agent.recentActivity, at, `▸ ${toolName}`);
621 }
622 agent.updatedAt = at;
623 break;
624 }
625 default:
626 break;
627 }
628 }
629
630 // Consistency pass: when a workflow coordinator has settled, members that
631 // never received their own terminal row cannot still be in-flight — the
632 // run is over. Cascade the coordinator's outcome so stalled member rows
633 // don't read as working forever (live-test finding: statuses drifted
634 // whenever member terminal rows were lost or never emitted).
635 for (const agent of agents.values()) {
636 if (agent.kind !== "workflow" || !isTerminalSubagentStatus(agent.status)) {
637 continue;
638 }
639 for (const member of agents.values()) {
640 if (member.parentAgentId !== agent.id) {
641 continue;
642 }
643 if (isTerminalSubagentStatus(member.status) || member.status === "idle") {
644 continue;
645 }
646 member.status = agent.status === "completed" ? "completed" : "interrupted";
647 member.completedAt = member.completedAt ?? agent.completedAt ?? agent.updatedAt;
648 member.updatedAt = agent.updatedAt;
649 }
650 }
651
652 // Session death orphans every live agent: no process remains to finish
653 // them. Mirrors the server-side liveness registry clearing on
654 // session.exited, so panel and sidebar can never disagree.
655 if (options?.sessionLive === false) {
656 for (const agent of agents.values()) {
657 if (isActiveSubagentStatus(agent.status)) {
658 agent.status = "interrupted";
659 agent.completedAt = agent.completedAt ?? agent.updatedAt;
660 }
661 }
662 }
663
664 let roster = Array.from(agents.values());
665 if (roster.length > ROSTER_LIMIT) {
666 // Prefer live, then waiting/idle, then newest settled.
667 const rank = (agent: MutableAgent): number =>
668 isActiveSubagentStatus(agent.status) ? 0 : agent.status === "idle" ? 1 : 2;
669 roster = roster
670 .slice()
671 .sort((a, b) => rank(a) - rank(b) || b.updatedAt.localeCompare(a.updatedAt))
672 .slice(0, ROSTER_LIMIT);
673 }
674
675 return roster.map((agent) => ({ ...agent }));
676}
677
678export interface AgentPanelWorkflowGroup {
679 readonly workflow: RuntimeSubagent;
680 readonly phases: ReadonlyArray<{
681 readonly index: number;
682 readonly title: string;
683 readonly members: ReadonlyArray<RuntimeSubagent>;
684 /** done = every member settled (success or error); running = any active. */
685 readonly state: "pending" | "running" | "done";
686 readonly activeCount: number;
687 readonly settledCount: number;
688 }>;
689 /** Members with no resolvable phase (orphans render under the workflow). */
690 readonly unphasedMembers: ReadonlyArray<RuntimeSubagent>;
691}
692
693export interface AgentPanelModel {
694 readonly workflows: ReadonlyArray<AgentPanelWorkflowGroup>;
695 readonly directAgents: ReadonlyArray<RuntimeSubagent>;
696 readonly runningCount: number;
697 readonly waitingCount: number;
698 readonly idleCount: number;
699 readonly settledCount: number;
700 readonly totalTokens: number;
701 readonly hasAgents: boolean;
702 readonly liveCount: number;
703}
704
705const EMPTY_PANEL_MODEL: AgentPanelModel = {
706 workflows: [],
707 directAgents: [],
708 runningCount: 0,
709 waitingCount: 0,
710 idleCount: 0,
711 settledCount: 0,
712 totalTokens: 0,
713 hasAgents: false,
714 liveCount: 0,
715};
716
717export function emptyAgentPanelModel(): AgentPanelModel {
718 return EMPTY_PANEL_MODEL;
719}
720
721/**
722 * The v2 leg of the mapper swap (#5219 spec): project orchestration-v2
723 * subagent entities into the same runtime shape the native fold produced.
724 * The panel/CTA components never see which source fed them.
725 */
726export function projectedSubagentsToRuntime(
727 subagents: ReadonlyArray<{
728 readonly id: string;
729 readonly title: string | null;
730 readonly prompt: string;
731 readonly model: string | null;
732 readonly status:
733 | "pending"
734 | "running"
735 | "waiting"
736 | "completed"
737 | "failed"
738 | "cancelled"
739 | "interrupted";
740 readonly progress?: string | undefined;
741 readonly result: string | null;
742 readonly startedAt: DateTime.Utc | null;
743 readonly completedAt: DateTime.Utc | null;
744 readonly updatedAt: DateTime.Utc;
745 }>,
746): ReadonlyArray<RuntimeSubagent> {
747 return subagents.map((subagent) => {
748 const updatedAt = DateTime.formatIso(subagent.updatedAt);
749 const startedAt = subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt);
750 return {
751 id: subagent.id,
752 kind: "subagent" as const,
753 title:
754 subagent.title ??
755 (subagent.prompt.length > 80 ? `${subagent.prompt.slice(0, 77)}...` : subagent.prompt),
756 role: null,
757 model: subagent.model,
758 effort: null,
759 status: subagent.status,
760 activationCount: 1,
761 usage: null,
762 progress: subagent.progress ?? null,
763 lastToolName: null,
764 result: subagent.result,
765 error: subagent.status === "failed" ? (subagent.result ?? null) : null,
766 outputFile: null,
767 parentAgentId: null,
768 agentIndex: null,
769 phaseIndex: null,
770 phaseTitle: null,
771 attempt: null,
772 workflowName: null,
773 phases: [],
774 runHandles: null,
775 recentActivity: [],
776 firstSeenAt: startedAt ?? updatedAt,
777 startedAt,
778 completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt),
779 updatedAt,
780 } satisfies RuntimeSubagent;
781 });
782}
783
784/**
785 * Source-neutral view model. When the orchestration-v2 subagent projection
786 * exists for the thread, pass it as v2Projection and it wins outright — the
787 * two sources are never merged (duplicate-agents failure mode). Until v2
788 * lands, callers pass null and the native fold output is used.
789 */
790export function deriveAgentPanelModel({
791 agents,
792 v2Projection,
793}: {
794 readonly agents: ReadonlyArray<RuntimeSubagent>;
795 readonly v2Projection?: ReadonlyArray<RuntimeSubagent> | null;
796}): AgentPanelModel {
797 const source = v2Projection ?? agents;
798 if (source.length === 0) {
799 return EMPTY_PANEL_MODEL;
800 }
801
802 const workflows = source
803 .filter((agent) => agent.kind === "workflow")
804 .slice()
805 .sort((a, b) => a.firstSeenAt.localeCompare(b.firstSeenAt) || a.id.localeCompare(b.id));
806 const workflowIds = new Set(workflows.map((workflow) => workflow.id));
807 const members = new Map<string, RuntimeSubagent[]>();
808 const direct: RuntimeSubagent[] = [];
809
810 for (const agent of source) {
811 if (agent.kind === "workflow") {
812 continue;
813 }
814 if (agent.parentAgentId !== null && workflowIds.has(agent.parentAgentId)) {
815 const list = members.get(agent.parentAgentId) ?? [];
816 list.push(agent);
817 members.set(agent.parentAgentId, list);
818 } else {
819 // Orphaned members (coordinator aged out) fall back to the direct list.
820 direct.push(agent);
821 }
822 }
823
824 const workflowGroups: AgentPanelWorkflowGroup[] = workflows.map((workflow) => {
825 const workflowMembers = members.get(workflow.id) ?? [];
826 const knownPhases =
827 workflow.phases.length > 0
828 ? workflow.phases
829 : (() => {
830 const derived = new Map<number, string>();
831 for (const member of workflowMembers) {
832 if (member.phaseIndex !== null && !derived.has(member.phaseIndex)) {
833 derived.set(
834 member.phaseIndex,
835 member.phaseTitle ?? `Phase ${member.phaseIndex + 1}`,
836 );
837 }
838 }
839 return Array.from(derived.entries())
840 .map(([index, title]) => ({ index, title }))
841 .slice()
842 .sort((a, b) => a.index - b.index);
843 })();
844
845 const knownPhaseIndices = new Set(knownPhases.map((phase) => phase.index));
846 const phases = knownPhases.map((phase) => {
847 const phaseMembers = workflowMembers
848 .filter((member) => member.phaseIndex === phase.index)
849 .slice()
850 .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
851 const activeCount = phaseMembers.filter(
852 // Idle members count as active for phase-liveness: a resumable Codex
853 // member has not finished the phase.
854 (member) => isActiveSubagentStatus(member.status) || member.status === "idle",
855 ).length;
856 const settledCount = phaseMembers.filter((member) =>
857 isTerminalSubagentStatus(member.status),
858 ).length;
859 const state: "pending" | "running" | "done" =
860 phaseMembers.length === 0
861 ? "pending"
862 : activeCount > 0
863 ? "running"
864 : settledCount === phaseMembers.length
865 ? "done"
866 : "pending";
867 return {
868 index: phase.index,
869 title: phase.title,
870 members: phaseMembers,
871 state,
872 activeCount,
873 settledCount,
874 };
875 });
876
877 // Unknown phase indices land here too — a member must never vanish just
878 // because its phase row was lost (review finding).
879 const unphasedMembers = workflowMembers
880 .filter((member) => member.phaseIndex === null || !knownPhaseIndices.has(member.phaseIndex))
881 .slice()
882 .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
883
884 return { workflow, phases, unphasedMembers };
885 });
886
887 let runningCount = 0;
888 let waitingCount = 0;
889 let idleCount = 0;
890 let settledCount = 0;
891 let totalTokens = 0;
892 for (const agent of source) {
893 // A workflow coordinator with members is a container for those members, not
894 // work of its own: it reports running for the whole run and aggregates their
895 // usage upstream in some providers. Counting it would report one more agent
896 // working than there are, and double count tokens.
897 if (agent.kind === "workflow" && (members.get(agent.id) ?? []).length > 0) continue;
898 if (agent.status === "running" || agent.status === "pending") runningCount += 1;
899 else if (agent.status === "waiting") waitingCount += 1;
900 else if (agent.status === "idle") idleCount += 1;
901 else settledCount += 1;
902 totalTokens += agent.usage?.totalTokens ?? 0;
903 }
904
905 return {
906 workflows: workflowGroups,
907 // Updates and the >100-agent retention ranking must never reshuffle rows
908 // that remain visible.
909 directAgents: direct
910 .slice()
911 .sort((a, b) => a.firstSeenAt.localeCompare(b.firstSeenAt) || a.id.localeCompare(b.id)),
912 runningCount,
913 waitingCount,
914 idleCount,
915 settledCount,
916 totalTokens,
917 hasAgents: true,
918 liveCount: runningCount + waitingCount,
919 };
920}
921
922/**
923 * Members ordered by urgency for the capped inline workflow card: running and
924 * failed first, then waiting, then most recently updated.
925 */
926export function workflowCardMembers(
927 group: AgentPanelWorkflowGroup,
928 limit: number,
929): { readonly visible: ReadonlyArray<RuntimeSubagent>; readonly overflow: number } {
930 const all = [...group.phases.flatMap((phase) => phase.members), ...group.unphasedMembers];
931 const urgency = (agent: RuntimeSubagent): number => {
932 if (agent.status === "failed") return 0;
933 if (agent.status === "running") return 1;
934 if (agent.status === "waiting") return 2;
935 return 3;
936 };
937 const ordered = all
938 .slice()
939 .sort((a, b) => urgency(a) - urgency(b) || b.updatedAt.localeCompare(a.updatedAt));
940 return {
941 visible: ordered.slice(0, limit),
942 overflow: Math.max(0, ordered.length - limit),
943 };
944}
945
946/** Kinds the timeline should not render as generic rows (fold input only). */
947export function isSubagentActivityKind(kind: string): boolean {
948 return (
949 kind === "task.started" ||
950 kind === "task.progress" ||
951 kind === "task.updated" ||
952 kind === "task.completed" ||
953 kind === "tool.progress"
954 );
955}
956
957/**
958 * Quiet-timeline guarantee: tool rows attributed to an owning agent belong in
959 * the Agents surface, not the parent chat. Unattributed rows must stay.
960 */
961export function isAgentAttributedToolActivity(activity: OrchestrationThreadActivity): boolean {
962 if (typeof activity.payload !== "object" || activity.payload === null) {
963 return false;
964 }
965 const payload = activity.payload as Record<string, unknown>;
966 return typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
967}
968
969/** Timeline-bypassing synthesized rows (Codex children, workflow members). */
970export function isTimelineBypassActivity(activity: OrchestrationThreadActivity): boolean {
971 if (typeof activity.payload !== "object" || activity.payload === null) {
972 return false;
973 }
974 return (activity.payload as Record<string, unknown>).timelineBypass === true;
975}
976
977/**
978 * Compact model chip text: strips vendor prefixes/date-or-context suffixes
979 * ("claude-sonnet-5[1m]" → "sonnet-5[1m]", "claude-opus-4-20250514" →
980 * "opus-4"). Unknown ids pass through untouched; effort appends as "· high".
981 */
982export function formatSubagentModelLabel(
983 model: string | null,
984 effort: string | null,
985): string | null {
986 if (!model) {
987 return null;
988 }
989 const compact = model
990 .replace(/^claude-/, "")
991 .replace(/-\d{8}$/, "")
992 .replace(/-latest$/, "");
993 return effort ? `${compact} · ${effort}` : compact;
994}
995
996export function formatSubagentTokenCount(totalTokens: number): string {
997 if (totalTokens < 1000) {
998 return `${totalTokens}`;
999 }
1000 if (totalTokens < 1_000_000) {
1001 const value = totalTokens / 1000;
1002 return `${value >= 100 ? Math.round(value) : value.toFixed(1)}k`;
1003 }
1004 return `${(totalTokens / 1_000_000).toFixed(1)}M`;
1005}