// Dynamic workflows a session runs in the background, and what the board can // honestly say about them. // // WHAT CLAUDE CODE GIVES THE DECK, AND WHAT IT DOES NOT. A workflow is started // by the `Workflow` tool, which returns at once (`status: "async_launched"`, // with the task id, the run id and meta.name of the script). There is no hook // for its progress and none for its end. Three things name it afterwards: // - the `` Claude Code submits when the task ends, through // UserPromptSubmit, with the task id and completed | failed | stopped; // - `background_tasks` on every Stop: the work still in flight when the turn // ended, as {id, type, status, name?}. A snapshot, and the only list; // - the session's own silence (sweepStaleSessions, STALE_SESSION_MS). // Steps done and total are the CLI's own screen: no hook, transcript record // or file the deck reads carries them, so a workflow is drawn without a // figure, and `steps` is read only if something ever fills it. // // SAME EVENTS IN ANY ORDER, SAME END STATE (reducer.ts). A notice may overtake // the launch it ends: the end is kept by task id (`taskEnds`), and the launch // that arrives later is born settled. An ending is never undone, and the // earliest one wins, so a replayed log or a second deck changes nothing. import { rootAgentId, type GraphState } from "./graph-state"; import type { AgentNodeData, BackgroundWorkflow, BackgroundWorkflowEnd, HookPayload } from "./types"; /** The most workflows kept per session, oldest settled first out. */ export const MAX_WORKFLOWS = 20; /** The most task endings kept for launches still to come. */ const MAX_TASK_ENDS = 50; const own = (o: unknown, k: string): unknown => (o && typeof o === "object" ? (o as Record)[k] : undefined); const str = (v: unknown): string | undefined => (typeof v === "string" && v.trim() ? v.trim() : undefined); /** A tool_response may arrive as the object or as its JSON text. */ function responseOf(p: HookPayload): unknown { const r = p.tool_response; if (typeof r !== "string") return r; try { return JSON.parse(r); } catch { return undefined; } } function rootOf(state: GraphState, sessionId: string): AgentNodeData | undefined { return state.agents.get(rootAgentId(sessionId)); } function listOf(root: AgentNodeData): BackgroundWorkflow[] { return (root.workflows ??= []); } function trim(root: AgentNodeData): void { const list = root.workflows; if (!list) return; while (list.length > MAX_WORKFLOWS) { const at = list.findIndex(w => w.state !== "running"); list.splice(at >= 0 ? at : 0, 1); } } function settle(w: BackgroundWorkflow, state: BackgroundWorkflowEnd, at: number): void { w.state = w.state === "running" ? state : w.state; w.endedAt = Math.min(w.endedAt ?? at, at); w.startedAt = Math.min(w.startedAt, w.endedAt); } function rememberEnd(root: AgentNodeData, id: string, state: BackgroundWorkflowEnd, at: number): void { const ends = (root.taskEnds ??= {}); const prev = ends[id]; ends[id] = prev ? { state: prev.state, at: Math.min(prev.at, at) } : { state, at }; const keys = Object.keys(ends); for (let i = 0; i < keys.length - MAX_TASK_ENDS; i++) delete ends[keys[i]]; } /** Add the run, born settled when its ending was heard first. */ function open(root: AgentNodeData, id: string, at: number, fields: { name?: string; runId?: string }): void { const list = listOf(root); const known = list.find(w => w.id === id); if (known) { if (fields.name && !known.name) known.name = fields.name; if (fields.runId && !known.runId) known.runId = fields.runId; known.startedAt = Math.min(known.startedAt, at); return; } const w: BackgroundWorkflow = { id, state: "running", startedAt: at, ...(fields.name ? { name: fields.name } : {}), ...(fields.runId ? { runId: fields.runId } : {}) }; const end = root.taskEnds?.[id]; if (end) settle(w, end.state, end.at); list.push(w); trim(root); } /** A `Workflow` call that came back launched in the background. */ export function applyWorkflowLaunch(state: GraphState, p: HookPayload, sessionId: string, now: number): void { if (p.tool_name !== "Workflow") return; const out = responseOf(p); const id = str(own(out, "taskId")); if (!id || own(out, "status") !== "async_launched") return; const root = rootOf(state, sessionId); if (!root) return; open(root, id, now, { name: str(own(out, "workflowName")), runId: str(own(out, "runId")) }); } /** A background task's notice: the workflow it names is over. Any task's end * is kept, because the launch may not have been heard yet. */ export function applyTaskEnd(state: GraphState, sessionId: string, notice: { taskId: string; state: BackgroundWorkflowEnd }, now: number): void { const root = rootOf(state, sessionId); if (!root) return; const w = root.workflows?.find(x => x.id === notice.taskId); if (w) { settle(w, notice.state, now); return; } rememberEnd(root, notice.taskId, notice.state, now); } /** The work still in flight when a turn ended (`background_tasks` of a Stop): * a workflow in it is running, one the board holds running and the list no * longer has is over, outcome unknown. A hook with no such field says nothing. */ export function applyBackgroundSnapshot(state: GraphState, p: HookPayload, sessionId: string, now: number): void { const tasks = (p as { background_tasks?: unknown }).background_tasks; if (!Array.isArray(tasks)) return; const root = rootOf(state, sessionId); if (!root) return; const present = new Set(); for (const t of tasks) { if (own(t, "type") !== "workflow") continue; const id = str(own(t, "id")); if (!id) continue; present.add(id); open(root, id, now, { name: str(own(t, "name")) }); } // A snapshot older than a launch cannot speak for it (delivery out of order). for (const w of root.workflows ?? []) if (w.state === "running" && !present.has(w.id) && w.startedAt <= now) settle(w, "done", now); } /** A session nobody has heard from, or that ended, has nothing running. */ export function settleWorkflows(root: AgentNodeData, at: number): boolean { let changed = false; for (const w of root.workflows ?? []) { if (w.state !== "running") continue; settle(w, "stopped", at); changed = true; } return changed; } /** The workflows still running once the turn is over, oldest first. None for a * session that ended. While a turn runs, the turn's own work is the working * row's, as for agents (live-activity.ts). */ export function backgroundWorkflows(root: AgentNodeData): BackgroundWorkflow[] { if (root.closedAt != null || !root.workflows) return []; const over = root.state !== "active" || root.waiting?.kind === "idle"; const endedAt = root.lastTurnEndAt; return root.workflows .filter(w => w.state === "running" && (over || (endedAt != null && w.startedAt <= endedAt))) .sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : 1)); }