repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(ultra): show planned workflow agents

d166551b06f4ba0babc1fd00ccb9ed955000e4af

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (10)

extensions/ultra/README.md

Modified
70 70 If a run is aborted, the next run of the same workflow name, cwd, and args reuses completed matching steps and runs the missing/changed steps.
71 71 A completed run marks its journal complete, so later runs start fresh.
73 -Expanded workflow tool output renders each sub-agent as a multiline block: identity/status, resolved model metadata, elapsed time and reported tokens, then latest action.
74 -Configured tiers are shown as `tier → provider/model`; collapsed output remains summary-only.
73 +Expanded workflow tool output renders every phase from the start and each known sub-agent as a multiline block.
74 +Known agents appear queued before launch; dynamic fan-outs show `agents not planned yet`; conditional phases show `conditional` until their selectors resolve.
75 +Rows then transition through queued, running, done, dropped, or skipped without disappearing.
76 +Verified Nerd Font icons reinforce each state while text labels preserve meaning without glyph support.
77 +Configured tiers are shown as `tier → provider/model`; collapsed output remains counts-only.
76 79 Workflow results include aggregate token and cost usage from completed sub-agent turns when the provider reports it.
77 80 The final JSON contains `tokenUsage` with `input`, `output`, `total`, `cacheRead`, `cacheWrite`, and `cost`.

extensions/ultra/__tests__/engine.test.ts

Modified
131 +// ---------------------------------------------------------------------------
132 +// planned progress
133 +// ---------------------------------------------------------------------------
135 +describe("runWorkflow — planned progress", () => {
136 + it("publishes every phase before agents launch and resolves exact agent ids", async () => {
137 + const events: UltraProgressEvent[] = [];
138 + const fr = fakeRunner((args) => {
139 + args.onProgress?.({
140 + agentId: args.agentId,
141 + phase: args.phase,
142 + kind: "start",
143 + });
144 + return { ok: true, value: args.item ?? "one-result" };
145 + });
146 + const s = spec({
147 + phases: [
148 + { id: "one", kind: "single", step: { prompt: "one" } },
150 + id: "literal",
151 + kind: "fanout",
152 + over: ["a", "b"],
153 + step: { prompt: "{item}" },
154 + },
156 + id: "dynamic",
157 + kind: "fanout",
158 + over: "{one.results}",
159 + step: { prompt: "{item}" },
160 + },
162 + id: "conditional",
163 + kind: "single",
164 + when: "{args.enabled}",
165 + step: { prompt: "conditional" },
166 + } as Phase,
167 + ],
168 + });
170 + await runWorkflow(
171 + s,
172 + { enabled: false },
173 + baseDeps({
174 + stepRunner: fr.runner,
175 + onProgress: (event) => events.push(event),
176 + }),
177 + );
179 + expect(events[0]).toEqual({
180 + kind: "plan",
181 + phases: [
182 + { phase: "one", status: "resolved", agentIds: ["one#0"] },
184 + phase: "literal",
185 + status: "resolved",
186 + agentIds: ["literal#0", "literal#1"],
187 + },
188 + { phase: "dynamic", status: "agents-pending", agentIds: [] },
190 + phase: "conditional",
191 + status: "condition-pending",
192 + agentIds: [],
193 + },
194 + ],
195 + });
196 + for (const phase of ["one", "literal", "dynamic"]) {
197 + const resolved = events.findIndex(
198 + (event) =>
199 + event.kind === "phase" &&
200 + event.phase === phase &&
201 + event.status === "resolved",
202 + );
203 + const started = events.findIndex(
204 + (event) => event.kind === "start" && event.phase === phase,
205 + );
206 + expect(resolved).toBeGreaterThan(0);
207 + expect(started).toBeGreaterThan(resolved);
208 + expect(events).toContainEqual(
209 + expect.objectContaining({ kind: "phase", phase, status: "done" }),
210 + );
212 + expect(events).toContainEqual({
213 + kind: "phase",
214 + phase: "conditional",
215 + status: "skipped",
216 + agentIds: [],
217 + });
218 + expect(
219 + events.some(
220 + (event) => event.kind === "start" && event.phase === "conditional",
221 + ),
222 + ).toBe(false);
223 + });
225 + it("publishes resolved and done transitions for an empty fanout", async () => {
226 + const events: UltraProgressEvent[] = [];
227 + await runWorkflow(
228 + spec({
229 + phases: [
230 + { id: "empty", kind: "fanout", over: [], step: { prompt: "x" } },
231 + ],
232 + }),
233 + undefined,
234 + baseDeps({
235 + stepRunner: fakeRunner(() => ({ ok: true, value: 1 })).runner,
236 + onProgress: (event) => events.push(event),
237 + }),
238 + );
240 + expect(events).toContainEqual({
241 + kind: "phase",
242 + phase: "empty",
243 + status: "resolved",
244 + agentIds: [],
245 + });
246 + expect(events).toContainEqual({
247 + kind: "phase",
248 + phase: "empty",
249 + status: "done",
250 + agentIds: [],
251 + });
252 + });
253 +});
131 255 // ---------------------------------------------------------------------------
132 256 // conditional phase skipping
133 257 // ---------------------------------------------------------------------------
174 298 it("runs a phase when its selector resolves to a non-empty value", async () => {
299 + const events: UltraProgressEvent[] = [];
175 300 const fr = fakeRunner(() => ({ ok: true, value: "ran" }));
176 301 const s = spec({
177 302 phases: [
187 312 const res = await runWorkflow(
189 314 { enabled: true },
190 - baseDeps({ stepRunner: fr.runner }),
315 + baseDeps({
316 + stepRunner: fr.runner,
317 + onProgress: (event) => events.push(event),
318 + }),
193 321 expect(fr.calls).toHaveLength(1);
322 + expect(events[0]).toEqual({
323 + kind: "plan",
324 + phases: [
326 + phase: "conditional",
327 + status: "condition-pending",
328 + agentIds: [],
329 + },
330 + ],
331 + });
332 + expect(events).toContainEqual({
333 + kind: "phase",
334 + phase: "conditional",
335 + status: "resolved",
336 + agentIds: ["conditional#0"],
337 + });
338 + expect(events).toContainEqual({
339 + kind: "phase",
340 + phase: "conditional",
341 + status: "done",
342 + agentIds: ["conditional#0"],
343 + });
194 344 expect(res.phases[0]).toEqual({
195 345 id: "conditional",
196 346 ran: 1,
539 689 // ---------------------------------------------------------------------------
541 691 describe("runWorkflow — abort", () => {
542 - it("aborting mid-phase stops the pool, surfaces partial counts, and emits no end for un-launched agents", async () => {
692 + it("aborting mid-phase stops the pool, surfaces partial counts, and drops un-launched agents", async () => {
543 693 const controller = new AbortController();
544 694 const events: UltraProgressEvent[] = [];
545 695 const fr = fakeRunner(async (args) => {
572 722 expect(res.phases[0].ran).toBe(2); // only the first concurrency-window launched
573 723 expect(res.phases[0].ok).toBe(2);
574 724 expect(res.phases[0].dropped).toBe(4); // 4 un-launched, counted as dropped
575 - // No phantom end for the never-launched agents.
576 - const endIds = events.filter((e) => e.kind === "end").map((e) => e.agentId);
577 - expect(endIds).not.toContain("f#2");
578 - expect(endIds).not.toContain("f#5");
725 + const endIds = events
726 + .filter((event) => event.kind === "end")
727 + .map((event) => event.agentId);
728 + expect(endIds).toContain("f#2");
729 + expect(endIds).toContain("f#5");
581 732 it("a pre-aborted signal launches no steps and reports every item dropped", async () => {

extensions/ultra/__tests__/progress.test.ts

Modified
144 144 expect(s.transcripts).toEqual({});
145 145 expect(s.phases).toEqual([]);
146 146 expect(s.phase).toBeUndefined();
147 - expect(s).toMatchObject({ total: 0, done: 0, dropped: 0 });
147 + expect(s).toMatchObject({
148 + total: 0,
149 + queued: 0,
150 + running: 0,
151 + done: 0,
152 + dropped: 0,
153 + later: 0,
154 + });
155 + });
157 + it("seeds queued agents and pending phases from a workflow plan", () => {
158 + const s = reduceProgress(initialReducerState(), {
159 + kind: "plan",
160 + phases: [
162 + phase: "research",
163 + status: "resolved",
164 + agentIds: ["research#0"],
165 + },
166 + { phase: "verify", status: "agents-pending", agentIds: [] },
168 + phase: "publish",
169 + status: "condition-pending",
170 + agentIds: [],
171 + },
172 + ],
173 + } as unknown as UltraProgressEvent);
175 + expect(s.phases.map((phase) => phase.phase)).toEqual([
176 + "research",
177 + "verify",
178 + "publish",
179 + ]);
180 + expect(s.rows).toEqual([
181 + expect.objectContaining({
182 + agentId: "research#0",
183 + status: "queued",
184 + }),
185 + ]);
186 + expect(s.phase).toBeUndefined();
187 + expect(s).toMatchObject({
188 + total: 1,
189 + queued: 1,
190 + running: 0,
191 + done: 0,
192 + dropped: 0,
193 + later: 2,
194 + });
195 + });
197 + it("resolves pending agents before start and transitions queued to running", () => {
198 + const planned = reduceProgress(initialReducerState(), {
199 + kind: "plan",
200 + phases: [{ phase: "verify", status: "agents-pending", agentIds: [] }],
201 + } as unknown as UltraProgressEvent);
202 + const resolved = reduceProgress(planned, {
203 + kind: "phase",
204 + phase: "verify",
205 + status: "resolved",
206 + agentIds: ["verify#0", "verify#1"],
207 + } as unknown as UltraProgressEvent);
209 + expect(resolved.rows.map((row) => row.status)).toEqual([
210 + "queued",
211 + "queued",
212 + ]);
213 + expect(resolved).toMatchObject({ queued: 2, running: 0, later: 0 });
214 + const running = reduceProgress(
215 + resolved,
216 + pe({ agentId: "verify#0", phase: "verify", kind: "start" }),
217 + );
218 + expect(running.rows.map((row) => row.status)).toEqual([
219 + "running",
220 + "queued",
221 + ]);
222 + expect(running).toMatchObject({ queued: 1, running: 1, later: 0 });
223 + });
225 + it("removes provisional agent rows when a phase is skipped", () => {
226 + const planned = reduceProgress(initialReducerState(), {
227 + kind: "plan",
228 + phases: [
229 + { phase: "publish", status: "resolved", agentIds: ["publish#0"] },
230 + ],
231 + } as unknown as UltraProgressEvent);
232 + const skipped = reduceProgress(planned, {
233 + kind: "phase",
234 + phase: "publish",
235 + status: "skipped",
236 + agentIds: [],
237 + } as unknown as UltraProgressEvent);
239 + expect(skipped.rows).toEqual([]);
240 + expect(skipped.phases[0]).toMatchObject({
241 + phase: "publish",
242 + status: "skipped",
243 + });
244 + expect(skipped).toMatchObject({ total: 0, queued: 0, later: 0 });
150 247 it("formats tool call rows from structured args and does not replace them with raw results", () => {
220 317 expect(s.transcripts.a).toContain("hello world");
221 318 expect(s.transcripts.a).toContain("read");
222 319 expect(s).toMatchObject({ total: 1, done: 1, dropped: 0 });
223 - expect(s.phases).toEqual(["p1"]);
320 + expect(s.phases.map((phase) => phase.phase)).toEqual(["p1"]);
224 321 expect(s.phase).toBe("p1");
263 360 pe({ agentId: "a", phase: "review", kind: "end", status: "done" }),
264 361 pe({ agentId: "v0", phase: "verify", kind: "start" }),
266 - expect(s.phases).toEqual(["review", "verify"]);
363 + expect(s.phases.map((phase) => phase.phase)).toEqual(["review", "verify"]);
267 364 expect(s.phase).toBe("verify");

extensions/ultra/__tests__/ui.test.ts

Modified
104 104 expect(out).toContain("Review the diff from every angle.");
107 + it("renders the complete icon-led planned-work vocabulary in phase order", () => {
108 + const s = stateFrom([
110 + kind: "plan",
111 + phases: [
112 + { phase: "done", status: "resolved", agentIds: ["done#0"] },
113 + { phase: "active", status: "resolved", agentIds: ["active#0"] },
114 + { phase: "queued", status: "resolved", agentIds: ["queued#0"] },
115 + { phase: "verify", status: "agents-pending", agentIds: [] },
117 + phase: "publish",
118 + status: "condition-pending",
119 + agentIds: [],
120 + },
121 + { phase: "skip", status: "skipped", agentIds: [] },
122 + { phase: "failed", status: "resolved", agentIds: ["failed#0"] },
123 + ],
124 + } as unknown as UltraProgressEvent,
125 + pe({ agentId: "done#0", phase: "done", kind: "start" }),
126 + pe({ agentId: "done#0", phase: "done", kind: "end", status: "done" }),
127 + pe({ agentId: "active#0", phase: "active", kind: "start" }),
128 + pe({ agentId: "failed#0", phase: "failed", kind: "start" }),
129 + pe({
130 + agentId: "failed#0",
131 + phase: "failed",
132 + kind: "end",
133 + status: "failed",
134 + }),
135 + ]);
136 + const expanded = toolText(s, { expanded: true, isPartial: true });
138 + for (const icon of ["󰗠", "󰐌", "󰅐", "󰭙", "󰘬", "󰅙"])
139 + expect(expanded).toContain(icon);
140 + for (const label of [
141 + "done",
142 + "running",
143 + "queued",
144 + "agents not planned yet",
145 + "conditional",
146 + "skipped",
147 + "dropped",
148 + ])
149 + expect(expanded).toContain(label);
150 + expect(expanded.indexOf("done#0")).toBeLessThan(
151 + expanded.indexOf("active#0"),
152 + );
153 + expect(expanded.indexOf("active#0")).toBeLessThan(
154 + expanded.indexOf("queued#0"),
155 + );
157 + const collapsed = toolText(s, { expanded: false, isPartial: true });
158 + expect(collapsed).toContain("1 active");
159 + expect(collapsed).toContain("1 queued");
160 + expect(collapsed).toContain("2 later");
161 + expect(collapsed).not.toContain("done#0");
162 + });
107 164 it("truncation keeps ellipsis in the surrounding style span", () => {
108 165 const s = stateFrom([
109 166 pe({ agentId: "scan#0", phase: "scan", kind: "start" }),
326 383 expect(out).toContain("Review the diff from every angle.");
386 + it("shows planning placeholders but skips them during focus navigation", () => {
387 + const { overlay } = makeOverlay({ rows: 24 });
388 + overlay.handleProgress({
389 + kind: "plan",
390 + phases: [
391 + { phase: "a", status: "resolved", agentIds: ["a#0"] },
392 + { phase: "pending", status: "agents-pending", agentIds: [] },
393 + { phase: "b", status: "resolved", agentIds: ["b#0"] },
394 + ],
395 + });
397 + let out = overlay.render(80).join("\n");
398 + expect(out).toContain("agents not planned yet");
399 + expect(out).toContain("transcript: a#0");
400 + overlay.handleInput(K.down);
401 + out = overlay.render(80).join("\n");
402 + expect(out).toContain("transcript: b#0");
403 + });
329 405 it("focusing agent k shows its deltas and not the others'", () => {
330 406 const { overlay } = makeOverlay({ rows: 24 });
331 407 for (const id of ["a", "b", "c"]) {

extensions/ultra/__tests__/wire.test.ts

Modified
1 1 import { describe, expect, it, vi } from "vitest";
2 -import type { UltraProgressEvent } from "../progress.ts";
2 +import type { AgentProgressEvent, UltraProgressEvent } from "../progress.ts";
3 3 import type { DiscoveredWorkflow, WorkflowSpec } from "../spec.ts";
4 4 import {
5 5 completeWorkflowNames,
211 211 // ---------------------------------------------------------------------------
213 213 describe("makeToolProgressSink", () => {
214 - const ev = (over: Partial<UltraProgressEvent>): UltraProgressEvent => ({
214 + const ev = (over: Partial<AgentProgressEvent>): AgentProgressEvent => ({
215 215 agentId: "a#0",
216 216 phase: "p",
217 217 kind: "start",
218 218 ...over,
221 + it("publishes all planned phases and queued agents on the first update", () => {
222 + const onUpdate = vi.fn();
223 + const { sink } = makeToolProgressSink(onUpdate);
224 + const plan: UltraProgressEvent = {
225 + kind: "plan",
226 + phases: [
227 + { phase: "one", status: "resolved", agentIds: ["one#0"] },
228 + { phase: "verify", status: "agents-pending", agentIds: [] },
229 + ],
230 + };
232 + sink(plan);
234 + const first = onUpdate.mock.calls[0][0];
235 + expect(
236 + first.details.phases.map((phase: { phase: string }) => phase.phase),
237 + ).toEqual(["one", "verify"]);
238 + expect(first.details.rows).toEqual([
239 + expect.objectContaining({ agentId: "one#0", status: "queued" }),
240 + ]);
241 + expect(first.content[0].text).toContain("1 queued");
242 + expect(first.content[0].text).toContain("1 later");
243 + });
221 245 it("calls onUpdate with { content, details: reducerState } on every event, accumulating", () => {
222 246 const onUpdate = vi.fn();
223 247 const { sink, getState } = makeToolProgressSink(onUpdate);

extensions/ultra/engine.ts

Modified
12 12 // CONTRACT NOTES
13 13 // - The engine resolves `step.prompt` and forwards it to the runner ALREADY
14 14 // RESOLVED; the runner uses it verbatim (runner.ts top-of-file contract).
15 -// - The engine generates each launched step's `agentId` (`<phase>#<index>`),
16 -// so it — and only it — can distinguish a launched-but-failed step from an
17 -// un-launched (aborted) slot. A tool-using step that times out leaves a
18 -// phantom "running" board row (the hung session never maps `agent_end`), so
19 -// the engine closes that row with a synthetic `end` carrying a DROP_STATUSES
20 -// token (`"dropped"`) — NOT the free-form reason (a free-form `status` would
21 -// be miscounted as "done" by the reducer). The reason rides along as `text`.
22 -// Idempotent against any `end` the runner already emitted.
15 +// - The engine assigns every planned step an `agentId` (`<phase>#<index>`).
16 +// Failed and un-launched aborted slots receive synthetic `end` events with
17 +// reducer-safe `"dropped"` status; the free-form reason rides in `text`.
23 18 // - The authoritative per-phase `dropped` count is derived from the step
24 19 // results (`isAborted` ∥ `!ok`), independent of the progress stream — the
25 20 // synthetic `end` is board-only.
31 26 resolveTemplate,
32 27 } from "./interp.ts";
33 28 import { isAborted, mapWithConcurrency } from "./pool.ts";
34 -import type { AgentControls, UltraProgressEvent } from "./progress.ts";
29 +import type {
30 + AgentControls,
31 + PlannedPhase,
32 + UltraProgressEvent,
33 +} from "./progress.ts";
35 34 import type { RunStepResult, StepRunner, TokenUsage } from "./runner.ts";
36 35 import type { Phase, Step, WorkflowSpec } from "./spec.ts";
114 113 const tokenUsage = zeroUsage();
115 114 const steeredBox = { value: false };
116 115 const forward = makeForwarder(deps, steeredBox);
116 + forward({ kind: "plan", phases: planPhases(spec) });
118 118 for (const phase of spec.phases) {
120 120 phase.when !== undefined &&
121 121 !phaseEnabled(resolveSelector(phase.when, { args, results }))
123 + forward({
124 + kind: "phase",
125 + phase: phase.id,
126 + status: "skipped",
127 + agentIds: [],
128 + });
123 129 results[phase.id] = [];
124 130 phaseResults[phase.id] = [];
125 131 phases.push({ id: phase.id, ran: 0, ok: 0, dropped: 0 });
134 140 step: resolveStep(phase.step, { args, results, item }),
142 + const agentIds = resolved.map((_, index) => `${phase.id}#${index}`);
143 + forward({
144 + kind: "phase",
145 + phase: phase.id,
146 + status: "resolved",
147 + agentIds,
148 + });
137 150 const cap = phase.concurrency ?? deps.concurrency;
138 151 const slots = await mapWithConcurrency(
156 169 onProgress: forward,
158 171 if (res.ok) await deps.journal?.set(key, res);
159 - // Launched-but-failed: close the (possibly phantom) board row. Only
160 - // reached for launched steps — un-launched aborted slots never run
161 - // this fn, so they correctly get no synthetic end.
172 + // Launched failure: close the planned board row. Un-launched aborted
173 + // slots are closed during positional result normalization below.
162 174 if (!res.ok) {
163 175 forward({
164 176 agentId,
181 193 let dropped = 0;
182 194 const values: unknown[] = [];
183 195 const outcomeSlots: PhaseSlotResult[] = [];
184 - for (const slot of slots) {
196 + for (const [index, slot] of slots.entries()) {
185 197 if (isAborted(slot)) {
198 + forward({
199 + agentId: `${phase.id}#${index}`,
200 + phase: phase.id,
201 + kind: "end",
202 + status: "dropped",
203 + text: "aborted",
204 + });
186 205 dropped++;
187 206 values.push(null);
188 207 outcomeSlots.push({ ok: false, value: null, reason: "aborted" });
208 227 results[phase.id] = values;
209 228 phaseResults[phase.id] = outcomeSlots;
210 229 phases.push({ id: phase.id, ran, ok, dropped });
230 + forward({
231 + kind: "phase",
232 + phase: phase.id,
233 + status: "done",
234 + agentIds,
235 + });
211 236 // An all-dropped phase (`ok === 0`) is left visible in these counts and the
212 237 // workflow continues — a later phase may legitimately act on an empty set.
234 259 // Internals
235 260 // ---------------------------------------------------------------------------
262 +function planPhases(spec: WorkflowSpec): PlannedPhase[] {
263 + return spec.phases.map((phase) => {
264 + if (phase.when !== undefined) {
265 + return {
266 + phase: phase.id,
267 + status: "condition-pending",
268 + agentIds: [],
269 + };
271 + if (phase.kind === "single") {
272 + return {
273 + phase: phase.id,
274 + status: "resolved",
275 + agentIds: [`${phase.id}#0`],
276 + };
278 + if (Array.isArray(phase.over)) {
279 + return {
280 + phase: phase.id,
281 + status: "resolved",
282 + agentIds: phase.over.map((_, index) => `${phase.id}#${index}`),
283 + };
285 + return { phase: phase.id, status: "agents-pending", agentIds: [] };
286 + });
237 289 function zeroUsage(): TokenUsage {
238 290 return {
239 291 input: 0,
291 343 return (event) => {
292 344 const sink = deps.onProgress;
293 345 if (!sink) return;
294 - if (event.controls) {
346 + if ("controls" in event && event.controls) {
295 347 sink({ ...event, controls: wrapControls(event.controls, steeredBox) });
296 348 } else {
297 349 sink(event);

extensions/ultra/progress.ts

Modified
18 18 // Event types (the `deps.onProgress` contract — design line 242)
19 19 // ---------------------------------------------------------------------------
21 -/** Lifecycle stage of a single mapped progress event. */
22 -export type ProgressKind = "start" | "action" | "delta" | "end";
21 +/** Lifecycle stage of a single mapped agent event. */
22 +export type AgentProgressKind = "start" | "action" | "delta" | "end";
25 25 * Live control surface for one running sub-agent. Bound by the runner (which
39 39 * directly by the runner/engine (coarse start/end, dropped items). `controls`
40 40 * is attached by the runner, never by `mapSessionEvent`.
42 -export interface UltraProgressEvent {
42 +export interface AgentProgressEvent {
43 43 agentId: string;
44 44 phase: string;
45 - kind: ProgressKind;
45 + kind: AgentProgressKind;
46 46 /** Tool name for `action` events (tool start/end). */
47 47 toolName?: string;
48 48 /** Tool call id for native tool rendering. */
67 67 controls?: AgentControls;
70 +export type PhasePlanStatus =
71 + | "resolved"
72 + | "agents-pending"
73 + | "condition-pending"
74 + | "done"
75 + | "skipped";
77 +export interface PlannedPhase {
78 + phase: string;
79 + status: PhasePlanStatus;
80 + agentIds: readonly string[];
83 +export type UltraProgressEvent =
84 + | AgentProgressEvent
85 + | { kind: "plan"; phases: readonly PlannedPhase[] }
86 + | ({ kind: "phase" } & PlannedPhase);
70 88 // ---------------------------------------------------------------------------
71 -// mapSessionEvent — pure AgentSessionEvent -> UltraProgressEvent
89 +// mapSessionEvent — pure AgentSessionEvent -> AgentProgressEvent
72 90 // ---------------------------------------------------------------------------
74 92 const MAX_PREVIEW = 120;
172 190 event: AgentSessionEvent,
173 191 agentId: string,
174 192 phase: string,
175 -): UltraProgressEvent | null {
193 +): AgentProgressEvent | null {
176 194 const base = { agentId, phase } as const;
178 196 switch (event.type) {
221 239 // Reducer — folds an UltraProgressEvent stream into board + transcript state
222 240 // ---------------------------------------------------------------------------
224 -/** Terminal classification of a board row. */
225 -export type AgentStatus = "running" | "done" | "dropped";
242 +/** Lifecycle classification of an agent board row. */
243 +export type AgentStatus = "queued" | "running" | "done" | "dropped";
227 245 /** One live board row: an agent's status + its latest action. */
228 246 export interface AgentRow {
241 259 controls?: AgentControls;
244 -/**
245 - * Folded view of a run, consumed by both `ui.ts` sinks.
246 - *
247 - * `total` is agents-*seen* (rows grow as agents launch), not the fanout width —
248 - * the width is not derivable from a pure event stream, so a freshly-queued
249 - * agent is not yet counted until its first event arrives.
250 - */
262 +/** Folded planned and live view consumed by both `ui.ts` sinks. */
251 263 export interface ProgressMeta {
252 264 workflowName?: string;
253 265 workflowDescription?: string;
270 282 /** agentId -> accumulated transcript (text/thinking deltas + tool action lines). */
271 283 transcripts: Readonly<Record<string, string>>;
272 284 transcriptItems: Readonly<Record<string, readonly TranscriptItem[]>>;
273 - /** Distinct phase ids in arrival order — the phase counter (`phase N/len`). */
274 - phases: readonly string[];
275 - /** Current (latest-seen) phase id. */
285 + /** Planned phases in specification order. */
286 + phases: readonly PlannedPhase[];
287 + /** Current engine phase; initial planning does not select one. */
276 288 phase: string | undefined;
277 - /** Agents seen so far. */
289 + /** Known agents. */
278 290 total: number;
291 + queued: number;
292 + running: number;
279 293 /** Agents that ended successfully. */
280 294 done: number;
281 295 /** Agents that ended dropped/failed. */
282 296 dropped: number;
297 + /** Phases whose agent count or run decision still depends on earlier results. */
298 + later: number;
285 301 /** A fresh, empty reducer state. */
293 309 phases: [],
294 310 phase: undefined,
295 311 total: 0,
312 + queued: 0,
313 + running: 0,
296 314 done: 0,
297 315 dropped: 0,
316 + later: 0,
309 328 /** The coarse board label for an `action` event. */
310 -function actionLabel(event: UltraProgressEvent): string {
329 +function actionLabel(event: AgentProgressEvent): string {
311 330 const text =
312 331 event.args !== undefined
313 332 ? conciseArgs(event.toolName, event.args)
322 341 /** Text contributed to the per-agent transcript by this event (may be empty). */
323 -function transcriptText(event: UltraProgressEvent): string {
342 +function transcriptText(event: AgentProgressEvent): string {
324 343 switch (event.kind) {
325 344 case "delta":
326 345 return event.text ?? "";
336 -function transcriptItem(event: UltraProgressEvent): TranscriptItem | undefined {
355 +function transcriptItem(event: AgentProgressEvent): TranscriptItem | undefined {
337 356 if (event.kind === "delta") return { kind: "text", text: event.text ?? "" };
338 357 if (event.kind !== "action" || !event.toolName) return undefined;
339 358 const fallback = actionLabel(event);
351 370 function nextRow(
352 371 prev: AgentRow | undefined,
353 - event: UltraProgressEvent,
372 + event: AgentProgressEvent,
354 373 ): AgentRow {
355 374 const base: AgentRow = prev ?? {
356 375 agentId: event.agentId,
412 +/** A queued row seeded before its agent session exists. */
413 +function queuedRow(agentId: string, phase: string): AgentRow {
414 + return { agentId, phase, status: "queued", action: "" };
417 +function withCounts(
418 + state: Omit<
419 + ReducerState,
420 + "total" | "queued" | "running" | "done" | "dropped" | "later"
421 + >,
422 +): ReducerState {
423 + let queued = 0;
424 + let running = 0;
425 + let done = 0;
426 + let dropped = 0;
427 + for (const row of state.rows) {
428 + if (row.status === "queued") queued++;
429 + else if (row.status === "running") running++;
430 + else if (row.status === "done") done++;
431 + else dropped++;
433 + const later = state.phases.filter(
434 + (phase) =>
435 + phase.status === "agents-pending" || phase.status === "condition-pending",
436 + ).length;
437 + return {
438 + ...state,
439 + total: state.rows.length,
440 + queued,
441 + running,
442 + done,
443 + dropped,
444 + later,
445 + };
448 +function applyPlan(
449 + state: ReducerState,
450 + phases: readonly PlannedPhase[],
451 +): ReducerState {
452 + const planned = phases.map((phase) => ({
453 + ...phase,
454 + agentIds: [...phase.agentIds],
455 + }));
456 + return withCounts({
457 + ...state,
458 + phases: planned,
459 + phase: undefined,
460 + rows: planned.flatMap((phase) =>
461 + phase.agentIds.map((agentId) => queuedRow(agentId, phase.phase)),
462 + ),
463 + });
466 +function applyPhase(
467 + state: ReducerState,
468 + event: Extract<UltraProgressEvent, { kind: "phase" }>,
469 +): ReducerState {
470 + const phase = {
471 + phase: event.phase,
472 + status: event.status,
473 + agentIds: [...event.agentIds],
474 + };
475 + const phases = state.phases.some((entry) => entry.phase === event.phase)
476 + ? state.phases.map((entry) => (entry.phase === event.phase ? phase : entry))
477 + : [...state.phases, phase];
478 + const keep = new Set(event.agentIds);
479 + const rows = state.rows.filter(
480 + (row) => row.phase !== event.phase || keep.has(row.agentId),
481 + );
482 + for (const agentId of event.agentIds) {
483 + if (!rows.some((row) => row.agentId === agentId))
484 + rows.push(queuedRow(agentId, event.phase));
486 + return withCounts({
487 + ...state,
488 + phases,
489 + phase: event.phase,
490 + rows,
491 + });
394 - * Pure reducer: fold one `UltraProgressEvent` into the board/transcript state,
395 - * returning a NEW state. Rows are upserted by `agentId` (idempotent — a later
396 - * event updates the row in place, never appends); unchanged rows keep their
397 - * reference identity so `ui.ts` can memoize. Tallies are recomputed from row
398 - * statuses, so re-applying an event can never double-count.
495 + * Pure reducer: fold planning, phase, and agent events into one ordered board.
496 + * Agent rows are upserted by id; counts are always derived from current state.
400 498 export function reduceProgress(
401 499 state: ReducerState,
402 500 event: UltraProgressEvent,
403 501 ): ReducerState {
404 - const idx = state.rows.findIndex((r) => r.agentId === event.agentId);
502 + if (event.kind === "plan") return applyPlan(state, event.phases);
503 + if (event.kind === "phase") return applyPhase(state, event);
505 + const idx = state.rows.findIndex((row) => row.agentId === event.agentId);
405 506 const prev = idx >= 0 ? state.rows[idx] : undefined;
406 507 const row = nextRow(prev, event);
407 508 const rows =
408 509 idx >= 0
409 - ? state.rows.map((r, i) => (i === idx ? row : r))
510 + ? state.rows.map((entry, i) => (i === idx ? row : entry))
410 511 : [...state.rows, row];
412 513 const added = transcriptText(event);
429 530 : state.transcriptItems;
431 - const phases = state.phases.includes(event.phase)
532 + const phases = state.phases.some((phase) => phase.phase === event.phase)
432 533 ? state.phases
433 - : [...state.phases, event.phase];
534 + : [
535 + ...state.phases,
537 + phase: event.phase,
538 + status: "resolved" as const,
539 + agentIds: [event.agentId],
540 + },
541 + ];
435 - let done = 0;
436 - let dropped = 0;
437 - for (const r of rows) {
438 - if (r.status === "done") done++;
439 - else if (r.status === "dropped") dropped++;
440 - }
442 - return {
543 + return withCounts({
443 544 workflowName: state.workflowName,
444 545 workflowDescription: state.workflowDescription,
447 548 transcriptItems,
448 549 phases,
449 550 phase: event.phase,
450 - total: rows.length,
451 - done,
452 - dropped,
453 - };
551 + });

extensions/ultra/runner.ts

Modified
32 32 import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
33 33 import {
34 34 type AgentControls,
35 + type AgentProgressEvent,
35 36 mapSessionEvent,
36 37 type UltraProgressEvent,
37 38 } from "./progress.ts";
485 486 function emitCompleteStart(
486 487 opts: RunStepOptions,
487 488 meta: Pick<
488 - UltraProgressEvent,
489 + AgentProgressEvent,
489 490 "tier" | "model" | "thinkingLevel" | "startedAt"
491 492 ): void {

extensions/ultra/ui.ts

Modified
36 36 type AgentControls,
37 37 type AgentStatus,
38 38 initialReducerState,
39 + type PlannedPhase,
39 40 type ReducerState,
40 41 reduceProgress,
41 42 type TranscriptItem,
47 48 // ---------------------------------------------------------------------------
49 50 const STATUS_ICON: Record<AgentStatus, string> = {
50 - running: "●",
51 - done: "✓",
52 - dropped: "✗",
51 + queued: "󰅐",
52 + running: "󰐌",
53 + done: "󰗠",
54 + dropped: "󰅙",
57 +const PHASE_ICON = {
58 + "agents-pending": "󰭙",
59 + "condition-pending": "󰘬",
60 + skipped: "−",
61 +} as const;
55 63 const RESET = /\x1b\[0m/g;
57 65 function fitLine(text: string, width: number): string {
60 68 return text.includes("\x1b") ? out : out.replace(RESET, "");
63 -/** `phase N/len` from the reducer's ordered phase list (empty until a phase arrives). */
71 +/** `phase N/len` from the reducer's ordered phase plan. */
64 72 function phaseCounter(state: ReducerState): string {
65 73 if (state.phases.length === 0) return "";
66 - const idx = state.phase ? state.phases.indexOf(state.phase) + 1 : 0;
74 + const idx = state.phase
75 + ? state.phases.findIndex((phase) => phase.phase === state.phase) + 1
76 + : 0;
67 77 return `phase ${idx}/${state.phases.length}`;
70 -/** One-line aggregate: `phase N/len · done/total done · K✗`. */
80 +/** One-line aggregate with terminal, active, queued, and later work counts. */
71 81 function summaryLine(state: ReducerState): string {
72 82 const parts: string[] = [];
73 83 const pc = phaseCounter(state);
74 84 if (pc) parts.push(pc);
75 85 parts.push(`${state.done}/${state.total} done`);
86 + if (state.running > 0) parts.push(`${state.running} active`);
87 + if (state.queued > 0) parts.push(`${state.queued} queued`);
88 + if (state.later > 0)
89 + parts.push(`${state.later} later phase${state.later === 1 ? "" : "s"}`);
76 90 if (state.dropped > 0) parts.push(`${state.dropped}✗`);
77 91 return parts.join(" · ");
139 +type DisplayRow =
140 + | { kind: "agent"; row: ReducerState["rows"][number] }
141 + | { kind: "phase"; phase: PlannedPhase };
143 +function displayRows(state: ReducerState): DisplayRow[] {
144 + const out: DisplayRow[] = [];
145 + const seen = new Set<string>();
146 + for (const phase of state.phases) {
147 + const rows = state.rows.filter((row) => row.phase === phase.phase);
148 + if (
149 + phase.status === "agents-pending" ||
150 + phase.status === "condition-pending" ||
151 + phase.status === "skipped" ||
152 + (phase.status === "done" && rows.length === 0)
153 + ) {
154 + out.push({ kind: "phase", phase });
155 + continue;
157 + for (const row of rows) {
158 + seen.add(row.agentId);
159 + out.push({ kind: "agent", row });
162 + for (const row of state.rows) {
163 + if (!seen.has(row.agentId)) out.push({ kind: "agent", row });
165 + return out;
168 +function phaseLabel(phase: PlannedPhase): string {
169 + switch (phase.status) {
170 + case "agents-pending":
171 + return `${PHASE_ICON[phase.status]} ${phase.phase} · agents not planned yet`;
172 + case "condition-pending":
173 + return `${PHASE_ICON[phase.status]} ${phase.phase} · conditional`;
174 + case "skipped":
175 + return `${PHASE_ICON[phase.status]} ${phase.phase} · skipped`;
176 + case "done":
177 + return `󰗠 ${phase.phase} · done · no agents`;
178 + case "resolved":
179 + return phase.phase;
183 +function phaseDetail(phase: PlannedPhase): string | undefined {
184 + if (phase.status === "agents-pending")
185 + return "earlier results determine which agents are needed";
186 + if (phase.status === "condition-pending")
187 + return "earlier results determine whether this phase runs";
188 + return undefined;
191 +function queuedDetail(state: ReducerState, phase: string): string {
192 + return state.phase === phase
193 + ? "waiting for concurrency slot"
194 + : "starts when phase begins";
125 197 function divider(label: string, width: number): string {
126 198 const w = Math.max(1, width);
127 199 const text = ` ${label} `;
171 243 return lines.map((l) => fitLine(l, w));
174 - // Expanded: identity first, then an indented metadata/action tree.
175 - for (const row of state.rows) {
246 + // Expanded: specification order, including non-agent planning rows.
247 + for (const display of displayRows(state)) {
248 + if (display.kind === "phase") {
249 + lines.push(theme.fg("dim", fitLine(phaseLabel(display.phase), w)));
250 + const detail = phaseDetail(display.phase);
251 + if (detail) lines.push(theme.fg("muted", fitLine(` └ ${detail}`, w)));
252 + continue;
254 + const { row } = display;
176 255 const icon = STATUS_ICON[row.status];
177 - lines.push(
178 - theme.fg("dim", fitLine(`${icon} ${row.agentId} · ${row.status}`, w)),
179 - );
256 + let identity = `${icon} ${row.agentId} · ${row.status}`;
257 + if (row.status === "queued")
258 + identity += ` · ${queuedDetail(state, row.phase)}`;
259 + lines.push(theme.fg("dim", fitLine(identity, w)));
180 260 for (const detail of agentDetailLines(row)) {
181 261 lines.push(theme.fg("muted", fitLine(` ${detail}`, w)));
220 300 function asReducerState(details: unknown): ReducerState {
221 301 const d = details as Partial<ReducerState> | null | undefined;
222 - return d && Array.isArray(d.phases) && Array.isArray(d.rows)
302 + const phaseStatuses: readonly string[] = [
303 + "resolved",
304 + "agents-pending",
305 + "condition-pending",
306 + "done",
307 + "skipped",
308 + ];
309 + const agentStatuses: readonly string[] = [
310 + "queued",
311 + "running",
312 + "done",
313 + "dropped",
314 + ];
315 + const phasesValid =
316 + Array.isArray(d?.phases) &&
317 + d.phases.every(
318 + (phase) =>
319 + typeof phase === "object" &&
320 + phase !== null &&
321 + typeof phase.phase === "string" &&
322 + phaseStatuses.includes(phase.status) &&
323 + Array.isArray(phase.agentIds) &&
324 + phase.agentIds.every((agentId: unknown) => typeof agentId === "string"),
325 + );
326 + const rowsValid =
327 + Array.isArray(d?.rows) &&
328 + d.rows.every(
329 + (row) =>
330 + typeof row === "object" &&
331 + row !== null &&
332 + typeof row.agentId === "string" &&
333 + typeof row.phase === "string" &&
334 + agentStatuses.includes(row.status),
335 + );
336 + return d && phasesValid && rowsValid
223 337 ? (d as ReducerState)
224 338 : initialReducerState();
386 500 const now = this.now();
387 501 // Terminal events bypass the throttle so the final board is never lost
388 502 // behind the render window.
389 - const force = event.kind === "end";
503 + const force = event.kind === "end" || event.kind === "phase";
390 504 if (force || now - this.lastRenderAt >= this.throttleMs) {
391 505 this.lastRenderAt = now;
392 506 this.host.requestRender();
579 693 const maxLines = Math.max(1, this.host.terminal.rows - 3);
580 694 const fixedAfterRows = 3; // border + transcript title + footer
581 - const maxAgentRows = Math.min(
582 - state.rows.length,
695 + const display = displayRows(state);
696 + const maxWorkRows = Math.min(
697 + display.length,
583 698 Math.max(0, maxLines - lines.length - fixedAfterRows),
700 + const focusedId = this.focusedRow()?.agentId;
701 + const focusedDisplay = display.findIndex(
702 + (item) => item.kind === "agent" && item.row.agentId === focusedId,
703 + );
585 704 const rowStart =
586 - maxAgentRows >= state.rows.length
705 + maxWorkRows >= display.length
588 707 : Math.min(
589 - Math.max(0, this.focusIndex - Math.floor(maxAgentRows / 2)),
590 - Math.max(0, state.rows.length - maxAgentRows),
708 + Math.max(0, focusedDisplay - Math.floor(maxWorkRows / 2)),
709 + Math.max(0, display.length - maxWorkRows),
592 - state.rows
593 - .slice(rowStart, rowStart + maxAgentRows)
594 - .forEach((row, offset) => {
595 - const i = rowStart + offset;
596 - const focused = i === this.focusIndex;
597 - const marker = focused ? "▶" : " ";
598 - const icon = STATUS_ICON[row.status];
599 - let line = `${marker} ${icon} ${row.agentId} · ${row.status}`;
600 - if (row.action) line += ` · ${row.action}`;
601 - lines.push(this.theme.fg(focused ? "accent" : "dim", fitLine(line, w)));
602 - });
711 + for (const item of display.slice(rowStart, rowStart + maxWorkRows)) {
712 + if (item.kind === "phase") {
713 + lines.push(
714 + this.theme.fg("dim", fitLine(` ${phaseLabel(item.phase)}`, w)),
715 + );
716 + const detail = phaseDetail(item.phase);
717 + if (detail)
718 + lines.push(this.theme.fg("muted", fitLine(` └ ${detail}`, w)));
719 + continue;
721 + const { row } = item;
722 + const focused = row.agentId === focusedId;
723 + const marker = focused ? "▶" : " ";
724 + const icon = STATUS_ICON[row.status];
725 + let line = `${marker} ${icon} ${row.agentId} · ${row.status}`;
726 + if (row.status === "queued")
727 + line += ` · ${queuedDetail(state, row.phase)}`;
728 + if (row.action) line += ` · ${row.action}`;
729 + lines.push(this.theme.fg(focused ? "accent" : "dim", fitLine(line, w)));
604 732 const focusedRow = this.focusedRow();
605 733 lines.push(

extensions/ultra/wire.ts

Modified
171 171 * `renderResult`; this `content` is just the textual fallback). */
172 172 function summarize(state: ReducerState): string {
173 173 const phase = state.phase ? `${state.phase}: ` : "";
174 - return `${phase}${state.done}/${state.total} done${state.dropped ? `, ${state.dropped} dropped` : ""}`;
174 + return [
175 + `${phase}${state.done}/${state.total} done`,
176 + state.running ? `${state.running} active` : "",
177 + state.queued ? `${state.queued} queued` : "",
178 + state.later ? `${state.later} later` : "",
179 + state.dropped ? `${state.dropped} dropped` : "",
181 + .filter(Boolean)
182 + .join(", ");
198 206 // which propagates back into every step that emitted an event and
199 207 // fails the whole run. Only the command overlay (never serialized)
200 208 // keeps controls.
201 - state = reduceProgress(state, { ...event, controls: undefined });
209 + const safe =
210 + "agentId" in event ? { ...event, controls: undefined } : event;
211 + state = reduceProgress(state, safe);
202 212 onUpdate({
203 213 content: [{ type: "text", text: summarize(state) }],
204 214 details: state,