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