Open History to see the last commit
1import type { OrchestrationThreadActivity, TurnId } from "@t3tools/contracts";
2
3/**
4 * Derivation of workflow-run view models from thread activities.
5 *
6 * Workflow state arrives as three activity kinds emitted by the server:
7 * - `task.started` / `task.completed` — lifecycle (shared with plain tasks)
8 * - `task.workflow-updated` — cumulative snapshot (phases, agents, logs),
9 * upserted under a stable activity id per task
10 * - `task.workflow-meta` — run handles (script path, transcript dir, run id)
11 *
12 * Everything here parses `activity.payload` defensively: payloads are
13 * `unknown` end-to-end and originate from an undocumented SDK surface, so a
14 * malformed field must degrade to less detail, never throw.
15 */
16
17export type WorkflowAgentStatus = "queued" | "running" | "done" | "error";
18
19export interface WorkflowRunAgent {
20 index: number;
21 status: WorkflowAgentStatus;
22 state: string;
23 label?: string | undefined;
24 phaseIndex?: number | undefined;
25 phaseTitle?: string | undefined;
26 agentId?: string | undefined;
27 agentType?: string | undefined;
28 model?: string | undefined;
29 isolation?: "worktree" | "remote" | undefined;
30 attempt?: number | undefined;
31 queuedAt?: number | undefined;
32 startedAt?: number | undefined;
33 lastProgressAt?: number | undefined;
34 cached?: boolean | undefined;
35 remoteSessionId?: string | undefined;
36 lastToolName?: string | undefined;
37 lastToolSummary?: string | undefined;
38 promptPreview?: string | undefined;
39 resultPreview?: string | undefined;
40 error?: string | undefined;
41 tokens?: number | undefined;
42 toolCalls?: number | undefined;
43 durationMs?: number | undefined;
44}
45
46export interface WorkflowRunPhase {
47 index: number;
48 title: string;
49 kind?: string | undefined;
50 agents: WorkflowRunAgent[];
51}
52
53export interface WorkflowRunUsage {
54 totalTokens?: number | undefined;
55 toolUses?: number | undefined;
56 durationMs?: number | undefined;
57}
58
59export interface WorkflowRunHandlesView {
60 runId?: string | undefined;
61 taskType?: string | undefined;
62 scriptPath?: string | undefined;
63 transcriptDir?: string | undefined;
64 sessionUrl?: string | undefined;
65 warning?: string | undefined;
66}
67
68export type WorkflowRunStatus = "running" | "completed" | "failed" | "stopped";
69
70export interface WorkflowRun {
71 taskId: string;
72 status: WorkflowRunStatus;
73 createdAt: string;
74 updatedAt: string;
75 /** Monotonic per-derivation change counter — bumped on every applied
76 * workflow activity so renderers can cheaply detect content changes even
77 * when timestamps collide at millisecond precision. */
78 revision: number;
79 turnId: TurnId | null;
80 name?: string | undefined;
81 description?: string | undefined;
82 completionSummary?: string | undefined;
83 phases: WorkflowRunPhase[];
84 logs: string[];
85 usage?: WorkflowRunUsage | undefined;
86 handles?: WorkflowRunHandlesView | undefined;
87 agentCounts: {
88 total: number;
89 queued: number;
90 running: number;
91 done: number;
92 error: number;
93 };
94}
95
96function asRecord(value: unknown): Record<string, unknown> | undefined {
97 return value !== null && typeof value === "object" && !Array.isArray(value)
98 ? (value as Record<string, unknown>)
99 : undefined;
100}
101
102function asString(value: unknown): string | undefined {
103 return typeof value === "string" && value.trim().length > 0 ? value : undefined;
104}
105
106function asNumber(value: unknown): number | undefined {
107 return typeof value === "number" && Number.isFinite(value) ? value : undefined;
108}
109
110export function deriveWorkflowAgentStatus(input: {
111 state: string;
112 startedAt?: number;
113}): WorkflowAgentStatus {
114 if (input.state === "done") {
115 return "done";
116 }
117 if (input.state === "error") {
118 return "error";
119 }
120 // "start" plus any state a future SDK adds: running once work has begun.
121 return input.startedAt !== undefined ? "running" : "queued";
122}
123
124function parseAgentEntry(entry: Record<string, unknown>): WorkflowRunAgent | undefined {
125 const index = asNumber(entry.index);
126 const state = asString(entry.state);
127 if (index === undefined || state === undefined) {
128 return undefined;
129 }
130 const startedAt = asNumber(entry.startedAt);
131 const isolation =
132 entry.isolation === "worktree" || entry.isolation === "remote" ? entry.isolation : undefined;
133 return {
134 index,
135 state,
136 status: deriveWorkflowAgentStatus({ state, ...(startedAt !== undefined ? { startedAt } : {}) }),
137 ...(asString(entry.label) !== undefined ? { label: asString(entry.label) } : {}),
138 ...(asNumber(entry.phaseIndex) !== undefined ? { phaseIndex: asNumber(entry.phaseIndex) } : {}),
139 ...(asString(entry.phaseTitle) !== undefined ? { phaseTitle: asString(entry.phaseTitle) } : {}),
140 ...(asString(entry.agentId) !== undefined ? { agentId: asString(entry.agentId) } : {}),
141 ...(asString(entry.agentType) !== undefined ? { agentType: asString(entry.agentType) } : {}),
142 ...(asString(entry.model) !== undefined ? { model: asString(entry.model) } : {}),
143 ...(isolation !== undefined ? { isolation } : {}),
144 ...(asNumber(entry.attempt) !== undefined ? { attempt: asNumber(entry.attempt) } : {}),
145 ...(asNumber(entry.queuedAt) !== undefined ? { queuedAt: asNumber(entry.queuedAt) } : {}),
146 ...(startedAt !== undefined ? { startedAt } : {}),
147 ...(asNumber(entry.lastProgressAt) !== undefined
148 ? { lastProgressAt: asNumber(entry.lastProgressAt) }
149 : {}),
150 ...(entry.cached === true ? { cached: true } : {}),
151 ...(asString(entry.remoteSessionId) !== undefined
152 ? { remoteSessionId: asString(entry.remoteSessionId) }
153 : {}),
154 ...(asString(entry.lastToolName) !== undefined
155 ? { lastToolName: asString(entry.lastToolName) }
156 : {}),
157 ...(asString(entry.lastToolSummary) !== undefined
158 ? { lastToolSummary: asString(entry.lastToolSummary) }
159 : {}),
160 ...(asString(entry.promptPreview) !== undefined
161 ? { promptPreview: asString(entry.promptPreview) }
162 : {}),
163 ...(asString(entry.resultPreview) !== undefined
164 ? { resultPreview: asString(entry.resultPreview) }
165 : {}),
166 ...(asString(entry.error) !== undefined ? { error: asString(entry.error) } : {}),
167 ...(asNumber(entry.tokens) !== undefined ? { tokens: asNumber(entry.tokens) } : {}),
168 ...(asNumber(entry.toolCalls) !== undefined ? { toolCalls: asNumber(entry.toolCalls) } : {}),
169 ...(asNumber(entry.durationMs) !== undefined ? { durationMs: asNumber(entry.durationMs) } : {}),
170 };
171}
172
173interface ParsedWorkflowProgress {
174 phases: Array<{ index: number; title: string; kind?: string | undefined }>;
175 agents: WorkflowRunAgent[];
176 logs: string[];
177}
178
179function parseWorkflowProgress(value: unknown): ParsedWorkflowProgress {
180 const parsed: ParsedWorkflowProgress = { phases: [], agents: [], logs: [] };
181 if (!Array.isArray(value)) {
182 return parsed;
183 }
184 // Later entries for the same index win: snapshots are cumulative and the
185 // runner may re-emit an agent slot on retry.
186 const agentsByIndex = new Map<number, WorkflowRunAgent>();
187 const phasesByIndex = new Map<
188 number,
189 { index: number; title: string; kind?: string | undefined }
190 >();
191 for (const raw of value) {
192 const entry = asRecord(raw);
193 if (!entry) {
194 continue;
195 }
196 switch (entry.type) {
197 case "workflow_agent": {
198 const agent = parseAgentEntry(entry);
199 if (agent) {
200 agentsByIndex.set(agent.index, agent);
201 }
202 break;
203 }
204 case "workflow_phase": {
205 const index = asNumber(entry.index);
206 const title = asString(entry.title);
207 if (index !== undefined && title !== undefined) {
208 phasesByIndex.set(index, {
209 index,
210 title,
211 ...(asString(entry.kind) !== undefined ? { kind: asString(entry.kind) } : {}),
212 });
213 }
214 break;
215 }
216 case "workflow_log": {
217 const message = asString(entry.message);
218 if (message !== undefined) {
219 parsed.logs.push(message);
220 }
221 break;
222 }
223 default:
224 break;
225 }
226 }
227 parsed.agents = [...agentsByIndex.values()].toSorted((a, b) => a.index - b.index);
228 parsed.phases = [...phasesByIndex.values()].toSorted((a, b) => a.index - b.index);
229 return parsed;
230}
231
232function parseUsage(value: unknown): WorkflowRunUsage | undefined {
233 const record = asRecord(value);
234 if (!record) {
235 return undefined;
236 }
237 const totalTokens = asNumber(record.total_tokens);
238 const toolUses = asNumber(record.tool_uses);
239 const durationMs = asNumber(record.duration_ms);
240 if (totalTokens === undefined && toolUses === undefined && durationMs === undefined) {
241 return undefined;
242 }
243 return {
244 ...(totalTokens !== undefined ? { totalTokens } : {}),
245 ...(toolUses !== undefined ? { toolUses } : {}),
246 ...(durationMs !== undefined ? { durationMs } : {}),
247 };
248}
249
250export function groupWorkflowAgentsByPhase(parsed: {
251 phases: ReadonlyArray<{ index: number; title: string; kind?: string | undefined }>;
252 agents: ReadonlyArray<WorkflowRunAgent>;
253}): WorkflowRunPhase[] {
254 const phases = new Map<number, WorkflowRunPhase>();
255 for (const phase of parsed.phases) {
256 phases.set(phase.index, { ...phase, agents: [] });
257 }
258 const UNPHASED = -1;
259 for (const agent of parsed.agents) {
260 const phaseIndex = agent.phaseIndex ?? UNPHASED;
261 let phase = phases.get(phaseIndex);
262 if (!phase) {
263 phase = {
264 index: phaseIndex,
265 title: agent.phaseTitle ?? (phaseIndex === UNPHASED ? "Agents" : `Phase ${phaseIndex}`),
266 agents: [],
267 };
268 phases.set(phaseIndex, phase);
269 }
270 phase.agents.push(agent);
271 }
272 return [...phases.values()]
273 .filter(
274 (phase) => phase.agents.length > 0 || parsed.phases.some((p) => p.index === phase.index),
275 )
276 .toSorted((a, b) => a.index - b.index);
277}
278
279type MutableWorkflowRun = WorkflowRun;
280
281function isWorkflowTaskStartedPayload(payload: Record<string, unknown>): boolean {
282 return payload.taskType === "local_workflow" || asString(payload.workflowName) !== undefined;
283}
284
285/** Task ids owned by a workflow run — used to suppress duplicate work-log rows. */
286export function collectWorkflowTaskIds(
287 activities: ReadonlyArray<OrchestrationThreadActivity>,
288): Set<string> {
289 const taskIds = new Set<string>();
290 for (const activity of activities) {
291 const payload = asRecord(activity.payload);
292 const taskId = payload ? asString(payload.taskId) : undefined;
293 if (!taskId) {
294 continue;
295 }
296 if (
297 activity.kind === "task.workflow-updated" ||
298 activity.kind === "task.workflow-meta" ||
299 (activity.kind === "task.started" &&
300 payload !== undefined &&
301 isWorkflowTaskStartedPayload(payload))
302 ) {
303 taskIds.add(taskId);
304 }
305 }
306 return taskIds;
307}
308
309/**
310 * Millisecond timestamps collide, so equal-time activities are ordered by
311 * provider sequence when present, then by lifecycle rank — a task.completed
312 * must never be applied before the task.started that creates its run.
313 */
314const WORKFLOW_ACTIVITY_RANK: Record<string, number> = {
315 "task.started": 0,
316 "task.workflow-meta": 1,
317 "task.workflow-updated": 1,
318 "task.completed": 2,
319};
320
321function compareWorkflowActivityOrder(
322 a: OrchestrationThreadActivity,
323 b: OrchestrationThreadActivity,
324): number {
325 if (a.sequence !== undefined && b.sequence !== undefined && a.sequence !== b.sequence) {
326 return a.sequence - b.sequence;
327 }
328 const byTime = a.createdAt.localeCompare(b.createdAt);
329 if (byTime !== 0) {
330 return byTime;
331 }
332 const byRank = (WORKFLOW_ACTIVITY_RANK[a.kind] ?? 1) - (WORKFLOW_ACTIVITY_RANK[b.kind] ?? 1);
333 if (byRank !== 0) {
334 return byRank;
335 }
336 return a.id.localeCompare(b.id);
337}
338
339export function deriveWorkflowRuns(
340 activities: ReadonlyArray<OrchestrationThreadActivity>,
341 options?: { readonly sessionActive?: boolean | undefined },
342): WorkflowRun[] {
343 const ordered = [...activities].toSorted(compareWorkflowActivityOrder);
344 const workflowTaskIds = collectWorkflowTaskIds(activities);
345 const runs = new Map<string, MutableWorkflowRun>();
346
347 const ensureRun = (taskId: string, activity: OrchestrationThreadActivity): MutableWorkflowRun => {
348 const existing = runs.get(taskId);
349 if (existing) {
350 return existing;
351 }
352 const run: MutableWorkflowRun = {
353 taskId,
354 status: "running",
355 createdAt: activity.createdAt,
356 updatedAt: activity.createdAt,
357 turnId: activity.turnId,
358 revision: 0,
359 phases: [],
360 logs: [],
361 agentCounts: { total: 0, queued: 0, running: 0, done: 0, error: 0 },
362 };
363 runs.set(taskId, run);
364 return run;
365 };
366
367 for (const activity of ordered) {
368 const payload = asRecord(activity.payload);
369 if (!payload) {
370 continue;
371 }
372 const taskId = asString(payload.taskId);
373 if (!taskId) {
374 continue;
375 }
376
377 switch (activity.kind) {
378 case "task.started": {
379 if (!isWorkflowTaskStartedPayload(payload) && !runs.has(taskId)) {
380 break;
381 }
382 const run = ensureRun(taskId, activity);
383 run.revision += 1;
384 run.createdAt = activity.createdAt;
385 run.turnId = activity.turnId;
386 const name = asString(payload.workflowName);
387 if (name !== undefined) {
388 run.name = name;
389 }
390 const detail = asString(payload.detail);
391 if (detail !== undefined) {
392 run.description = detail;
393 }
394 break;
395 }
396 case "task.workflow-updated": {
397 const run = ensureRun(taskId, activity);
398 run.revision += 1;
399 run.updatedAt = activity.createdAt;
400 const description = asString(payload.description);
401 if (description !== undefined && run.description === undefined) {
402 run.description = description;
403 }
404 const parsed = parseWorkflowProgress(payload.workflowProgress);
405 run.phases = groupWorkflowAgentsByPhase(parsed);
406 run.logs = parsed.logs;
407 run.agentCounts = {
408 total: parsed.agents.length,
409 queued: parsed.agents.filter((agent) => agent.status === "queued").length,
410 running: parsed.agents.filter((agent) => agent.status === "running").length,
411 done: parsed.agents.filter((agent) => agent.status === "done").length,
412 error: parsed.agents.filter((agent) => agent.status === "error").length,
413 };
414 const usage = parseUsage(payload.usage);
415 if (usage !== undefined) {
416 run.usage = usage;
417 }
418 break;
419 }
420 case "task.workflow-meta": {
421 const run = ensureRun(taskId, activity);
422 run.revision += 1;
423 run.updatedAt = activity.createdAt;
424 const name = asString(payload.workflowName);
425 if (name !== undefined) {
426 run.name = name;
427 }
428 run.handles = {
429 ...(asString(payload.runId) !== undefined ? { runId: asString(payload.runId) } : {}),
430 ...(asString(payload.taskType) !== undefined
431 ? { taskType: asString(payload.taskType) }
432 : {}),
433 ...(asString(payload.scriptPath) !== undefined
434 ? { scriptPath: asString(payload.scriptPath) }
435 : {}),
436 ...(asString(payload.transcriptDir) !== undefined
437 ? { transcriptDir: asString(payload.transcriptDir) }
438 : {}),
439 ...(asString(payload.sessionUrl) !== undefined
440 ? { sessionUrl: asString(payload.sessionUrl) }
441 : {}),
442 ...(asString(payload.warning) !== undefined
443 ? { warning: asString(payload.warning) }
444 : {}),
445 };
446 break;
447 }
448 case "task.completed": {
449 // Order-robust terminal handling: a completion for a known workflow
450 // task creates the run if its task.started has not been applied yet
451 // (adopted runs can carry inverted provider sequences across CLI
452 // restarts); the later-applied started only fills metadata and can
453 // never resurrect a terminal status.
454 if (!runs.has(taskId) && !workflowTaskIds.has(taskId)) {
455 break;
456 }
457 const run = ensureRun(taskId, activity);
458 run.revision += 1;
459 run.updatedAt = activity.createdAt;
460 run.status =
461 payload.status === "failed"
462 ? "failed"
463 : payload.status === "stopped"
464 ? "stopped"
465 : "completed";
466 const detail = asString(payload.detail);
467 if (detail !== undefined) {
468 run.completionSummary = detail;
469 }
470 break;
471 }
472 default:
473 break;
474 }
475 }
476
477 // A workflow cannot outlive its provider session: when the session is gone
478 // and no task_notification ever arrived (crash, interrupt, app restart),
479 // surface the run as stopped instead of running forever. Runs derived only
480 // from snapshot/meta activities (no task.started — e.g. after a checkpoint
481 // revert trimmed it) are kept intentionally: partial history still renders.
482 const sessionActive = options?.sessionActive ?? true;
483 return [...runs.values()]
484 .map((run) =>
485 run.status === "running" && !sessionActive ? terminalizeInterruptedRun(run) : run,
486 )
487 .toSorted((a, b) => a.createdAt.localeCompare(b.createdAt) || a.taskId.localeCompare(b.taskId));
488}
489
490/**
491 * Settle a run whose session died before a terminal task notification:
492 * the run becomes "stopped" and its in-flight agents settle to "error" so
493 * nothing keeps rendering (or polling) as live work.
494 */
495function terminalizeInterruptedRun(run: WorkflowRun): WorkflowRun {
496 const settleAgent = (agent: WorkflowRunAgent): WorkflowRunAgent =>
497 agent.status === "running" || agent.status === "queued"
498 ? { ...agent, status: "error", error: agent.error ?? "Interrupted before completion" }
499 : agent;
500 const phases = run.phases.map((phase) => ({ ...phase, agents: phase.agents.map(settleAgent) }));
501 const agents = phases.flatMap((phase) => phase.agents);
502 return {
503 ...run,
504 status: "stopped",
505 phases,
506 agentCounts: {
507 total: agents.length,
508 queued: agents.filter((agent) => agent.status === "queued").length,
509 running: agents.filter((agent) => agent.status === "running").length,
510 done: agents.filter((agent) => agent.status === "done").length,
511 error: agents.filter((agent) => agent.status === "error").length,
512 },
513 };
514}
515
516export function isRemoteWorkflowRun(run: WorkflowRun): boolean {
517 return run.handles?.taskType === "remote_agent" || run.handles?.sessionUrl !== undefined;
518}
519
520export function workflowRunTitle(run: WorkflowRun): string {
521 return run.name ?? run.description ?? "Workflow";
522}
523
524export function formatWorkflowDuration(durationMs: number): string {
525 const totalSeconds = Math.max(0, Math.round(durationMs / 1000));
526 const minutes = Math.floor(totalSeconds / 60);
527 const seconds = totalSeconds % 60;
528 if (minutes === 0) {
529 return `${seconds}s`;
530 }
531 const hours = Math.floor(minutes / 60);
532 if (hours === 0) {
533 return `${minutes}m ${seconds.toString().padStart(2, "0")}s`;
534 }
535 return `${hours}h ${(minutes % 60).toString().padStart(2, "0")}m`;
536}
537
538export function formatWorkflowTokens(totalTokens: number): string {
539 if (totalTokens < 1000) {
540 return `${totalTokens}`;
541 }
542 if (totalTokens < 1_000_000) {
543 return `${(totalTokens / 1000).toFixed(totalTokens < 10_000 ? 1 : 0)}k`;
544 }
545 return `${(totalTokens / 1_000_000).toFixed(1)}M`;
546}