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