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

workflowGroups.ts

247 lines9.9 KB

1/**
2 * The workflow card's view model, shared by web and mobile: groups the runtime
3 * subagents of a thread projection into one card per workflow run, its phases,
4 * and the members that ran in each. Both clients feed this the output of
5 * `projectedSubagentsToRuntime`, so the grouping has a single source of truth.
6 *
7 * Workflow cards always come from the thread roster: a run outlives the turn
8 * that launched it, and its coordinator carries no orchestration run id, so a
9 * turn-scoped roster would drop it. Direct spawns are the opposite: a thread
10 * accumulates every agent it ever spawned, so a surface that shows "this
11 * turn" passes that turn's roster as `directScope`.
12 */
13import {
14 isActiveSubagentStatus,
15 isTerminalSubagentStatus,
16 type RuntimeSubagent,
17 type SubagentRunHandles,
18} from "./subagentRuntime.ts";
19​
20export interface WorkflowPhaseGroup {
21 readonly index: number;
22 readonly title: string;
23 readonly members: ReadonlyArray<RuntimeSubagent>;
24 /**
25 * done = every member settled (success or error); running = any active.
26 * skipped = the run is over (terminal coordinator) and this phase never
27 * got a member: the rail must not keep advertising work that will never
28 * arrive. A paused run is resumable, so its unreached phases stay pending.
29 */
30 readonly state: "pending" | "running" | "done" | "skipped";
31 readonly activeCount: number;
32 readonly settledCount: number;
34​
35export interface WorkflowAgentGroup {
36 readonly workflow: RuntimeSubagent;
37 /** Workflow name plus the unique run suffix, ready for the card header. */
38 readonly label: string;
39 readonly phases: ReadonlyArray<WorkflowPhaseGroup>;
40 /** Members with no resolvable phase (orphans render under the workflow). */
41 readonly unphasedMembers: ReadonlyArray<RuntimeSubagent>;
43​
44export interface AgentPanelModel {
45 readonly workflows: ReadonlyArray<WorkflowAgentGroup>;
46 /**
47 * Spawns that belong to no workflow card, scoped to `directScope`. A direct
48 * caller (web, tests) gets the whole roster; a turn-scoped surface passes
49 * that turn's roster so old turns never resurface.
50 */
51 readonly directAgents: ReadonlyArray<RuntimeSubagent>;
52 /** Whether the panel has a workflow card or a direct row to show. */
53 readonly hasAgents: boolean;
54 /**
55 * Thread-wide live agents. Not scoped to `directScope`: a running workflow
56 * member has to keep its card's elapsed timers moving, and it never appears
57 * in a turn's direct rows.
58 */
59 readonly liveCount: number;
61​
62const EMPTY_PANEL_MODEL: AgentPanelModel = {
63 workflows: [],
64 directAgents: [],
65 hasAgents: false,
66 liveCount: 0,
67};
68​
69export function deriveAgentPanelModel(
70 agents: ReadonlyArray<RuntimeSubagent>,
71 directScope: ReadonlyArray<RuntimeSubagent> = agents,
72): AgentPanelModel {
73 if (agents.length === 0 && directScope.length === 0) {
74 return EMPTY_PANEL_MODEL;
75 }
76​
77 const workflows = agents
78 .filter((agent) => agent.kind === "workflow")
79 .slice()
80 .sort((a, b) => a.firstSeenAt.localeCompare(b.firstSeenAt) || a.id.localeCompare(b.id));
81 const workflowIds = new Set(workflows.map((workflow) => workflow.id));
82 const members = new Map<string, RuntimeSubagent[]>();
83 const direct: RuntimeSubagent[] = [];
84​
85 // Members are always read from the thread roster: a workflow card must show
86 // its agents even when the caller scopes direct rows to one turn.
87 for (const agent of agents) {
88 if (agent.kind === "workflow") {
89 continue;
90 }
91 if (agent.parentAgentId !== null && workflowIds.has(agent.parentAgentId)) {
92 const list = members.get(agent.parentAgentId) ?? [];
93 list.push(agent);
94 members.set(agent.parentAgentId, list);
95 }
96 }
97 for (const agent of directScope) {
98 if (agent.kind === "workflow") {
99 continue;
100 }
101 if (agent.parentAgentId !== null && workflowIds.has(agent.parentAgentId)) {
102 continue;
103 }
104 // Orphaned members (coordinator aged out) fall back to the direct list.
105 direct.push(agent);
106 }
107​
108 const workflowGroups: WorkflowAgentGroup[] = workflows.map((workflow) => {
109 const workflowMembers = members.get(workflow.id) ?? [];
110 const knownPhases =
111 workflow.phases.length > 0
112 ? workflow.phases
113 : (() => {
114 const derived = new Map<number, string>();
115 for (const member of workflowMembers) {
116 if (member.phaseIndex !== null && !derived.has(member.phaseIndex)) {
117 derived.set(
118 member.phaseIndex,
119 member.phaseTitle ?? `Phase ${member.phaseIndex + 1}`,
120 );
121 }
122 }
123 return Array.from(derived.entries())
124 .map(([index, title]) => ({ index, title }))
125 .slice()
126 .sort((a, b) => a.index - b.index);
127 })();
128​
129 const knownPhaseIndices = new Set(knownPhases.map((phase) => phase.index));
130 // A terminal coordinator means the run is over, nothing in it is still
131 // waiting to start. Pi (like any multi-phase workflow) declares its whole
132 // phase list up front, so a run that completed, failed, or was stopped
133 // before a phase began leaves that phase with no members — deriving phase
134 // state from membership alone then painted a finished run's last phase
135 // "pending" forever. A paused run is NOT terminal: it is resumable, so its
136 // unreached phases must keep reading pending for the rail to advance.
137 const runFinished = isTerminalSubagentStatus(workflow.status);
138 const phases = knownPhases.map((phase) => {
139 const phaseMembers = workflowMembers
140 .filter((member) => member.phaseIndex === phase.index)
141 .slice()
142 .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
143 const activeCount = phaseMembers.filter(
144 // Idle members count as active for phase-liveness: a resumable member
145 // has not finished the phase.
146 (member) => isActiveSubagentStatus(member.status) || member.status === "idle",
147 ).length;
148 const settledCount = phaseMembers.filter((member) =>
149 isTerminalSubagentStatus(member.status),
150 ).length;
151 const state: "pending" | "running" | "done" | "skipped" =
152 phaseMembers.length === 0
153 ? runFinished
154 ? "skipped"
155 : "pending"
156 : activeCount > 0
157 ? // The run is over even if a member is still idle: the coordinator
158 // having settled is what decides, and a finished run cannot leave
159 // a live phase behind.
160 runFinished
161 ? "done"
162 : "running"
163 : settledCount === phaseMembers.length
164 ? "done"
165 : runFinished
166 ? "skipped"
167 : "pending";
168 return {
169 index: phase.index,
170 title: phase.title,
171 members: phaseMembers,
172 state,
173 activeCount,
174 settledCount,
175 };
176 });
177​
178 // Unknown phase indices land here too — a member must never vanish just
179 // because its phase row was lost.
180 const unphasedMembers = workflowMembers
181 .filter((member) => member.phaseIndex === null || !knownPhaseIndices.has(member.phaseIndex))
182 .slice()
183 .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
184​
185 return { workflow, label: formatWorkflowRunLabel(workflow), phases, unphasedMembers };
186 });
187​
188 let liveCount = 0;
189 for (const agent of agents) {
190 // A workflow coordinator with members is a container for those members, not
191 // work of its own: it reports running for the whole run. Counting it would
192 // report one more agent working than there are.
193 if (agent.kind === "workflow" && (members.get(agent.id) ?? []).length > 0) continue;
194 if (isActiveSubagentStatus(agent.status)) liveCount += 1;
195 }
196​
197 return {
198 workflows: workflowGroups,
199 // Updates and retention ranking must never reshuffle rows that remain
200 // visible.
201 directAgents: direct
202 .slice()
203 .sort((a, b) => a.firstSeenAt.localeCompare(b.firstSeenAt) || a.id.localeCompare(b.id)),
204 hasAgents: workflowGroups.length > 0 || direct.length > 0,
205 liveCount,
206 };
208​
209/**
210 * The short, stable tail of a workflow run id, for telling two runs of the
211 * same workflow apart. Pi's writer names a run `<slug>-<ts36>-<rand>`
212 * (`generateRunId` in @quintinshaw/pi-dynamic-workflows), so the last two
213 * hyphen-separated segments are exactly the part that differs between two runs
214 * of one workflow: the slug identifies the workflow, the timestamp plus random
215 * tail identifies the run. `null` when there is nothing usable (missing or
216 * hyphen-only id), so a caller degrades to the bare name rather than rendering
217 * an empty or broken label.
218 */
219export function workflowRunSuffix(runId: string | null | undefined): string | null {
220 const trimmed = runId?.trim();
221 if (!trimmed) return null;
222 const segments = trimmed.split("-").filter((segment) => segment.length > 0);
223 if (segments.length === 0) return null;
224 // Whole id when it has fewer than two usable segments. Cap the tail so an
225 // un-hyphenated foreign id cannot blow up a one-line card label; Pi's own
226 // tail is 6-7 chars of base36 plus the separator.
227 const suffix = segments.slice(-2).join("-");
228 return suffix.length > 32 ? suffix.slice(-32) : suffix;
230​
231/**
232 * The workflow card's one-line identity: the workflow name plus the run's own
233 * suffix (`pi_workflow_phase_pending_fix · mu5n6tcx-i253rw`). Two runs of the
234 * same workflow share the name, so without the suffix the card renders the
235 * same label twice. When the name already carries the suffix (the interrupted
236 * fallback sets the name to the full run id) the suffix is not repeated.
237 */
238export function formatWorkflowRunLabel(workflow: {
239 readonly workflowName: string | null;
240 readonly title: string;
241 readonly runHandles: SubagentRunHandles | null;
242}): string {
243 const name = workflow.workflowName ?? workflow.title;
244 const suffix = workflowRunSuffix(workflow.runHandles?.runId);
245 if (!suffix || name.includes(suffix)) return name;
246 return `${name} · ${suffix}`;