Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

subagentRuntime.ts

941 lines35.0 KB

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