repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ultra/__tests__/wire.test.ts
RawFile outline
- validSpec line 16
- specWithParams line 21
- discovered line 27
- formatUltraResultMarkdown line 41
- renders empty final result with refuted findings and drops line 42
- renders final result titles before raw JSON line 84
- renders aggregate token and cost usage when present line 99
- includes raw JSON only when expanded line 119
- background result messages line 137
- formats start and completion messages for detached workflow runs line 138
- formatWorkflowResultMessage line 167
- formats the aggregate JSON so /ultra command results enter the session line 168
- makes an empty result explicit instead of looking like no run happened line 195
- makeToolProgressSink line 213
- ev line 214
- calls onUpdate with { content, details: reducerState } on every event, accumulating line 221
- emits fresh details each call (renderResult tracks live state, not a frozen snapshot) line 240
- strips non-cloneable `controls` so Pi can structured-clone details + result (regression) line 253
- completeWorkflowNames line 286
- list line 287
- filters by prefix and returns {value,label} items line 293
- is case-insensitive and returns all names for an empty prefix line 300
- returns null when nothing matches line 311
- resolveWorkflowInput line 320
- list line 321
- parses an inline spec (ephemeral mode) line 326
- looks a named workflow up among discovered (persisted mode) line 335
- maps a bare positional remainder to the spec's declared args.params line 341
- ignores a positional remainder when the spec declares no params line 352
- prefers an explicit JSON args object over the positional remainder line 357
- throws with the available names for an unknown name line 372
- throws when neither name nor spec is provided line 378
- propagates a parse error for a malformed inline spec line 384
- validates a named workflow's spec, surfacing parseWorkflow's error on a malformed saved file line 390
- parseCommandLine line 411
- returns {} for an empty line line 412
- extracts a bare name line 416
- parses a trailing JSON object as args (retaining the raw rest) line 420
- keeps non-JSON trailing text as `rest` (for positional mapping) line 428
- mapPositionalArgs line 444
- fills declared params in order from whitespace tokens line 445
- soaks remaining tokens into the last declared param (free-text tail) line 450
- returns undefined for an empty remainder or no declared params line 462
import { describe, expect, it, vi } from "vitest";
import type { UltraProgressEvent } from "../progress.ts";
import type { DiscoveredWorkflow, WorkflowSpec } from "../spec.ts";
import {
completeWorkflowNames,
formatBackgroundAcceptedMessage,
formatBackgroundResultMessage,
formatUltraResultMarkdown,
formatWorkflowResultMessage,
makeToolProgressSink,
mapPositionalArgs,
parseCommandLine,
resolveWorkflowInput,
} from "../wire.ts";
const validSpec = (name: string): WorkflowSpec => ({
name,
phases: [{ id: "p", kind: "single", step: { prompt: "hi" } }],
});
const specWithParams = (name: string, params: string[]): WorkflowSpec => ({
name,
args: { params },
phases: [{ id: "p", kind: "single", step: { prompt: "hi {args.base}" } }],
});
const discovered = (
name: string,
source: DiscoveredWorkflow["source"],
): DiscoveredWorkflow => ({
name,
source,
path: `/${source}/${name}.json`,
spec: validSpec(name),
});
// ---------------------------------------------------------------------------
// makeToolProgressSink — folds engine events, pushes through onUpdate
// ---------------------------------------------------------------------------
describe("formatUltraResultMarkdown", () => {
it("renders empty final result with refuted findings and drops", () => {
const markdown = formatUltraResultMarkdown({
workflow: "review",
phases: [
{ id: "review", ran: 3, ok: 2, dropped: 1 },
{ id: "verify", ran: 2, ok: 2, dropped: 0 },
],
phaseResults: {
review: [
{ ok: false, value: null, reason: "timeout" },
{
ok: true,
value: {
findings: [{ title: "possible issue", file: "a.ts" }],
},
},
],
verify: [
{
ok: true,
value: {
title: "possible issue",
real: false,
file: "a.ts",
why: "not reproducible",
},
},
],
},
result: [],
steered: false,
});
expect(markdown).toContain("# ultra review");
expect(markdown).toContain("No final results");
expect(markdown).toContain("review: 2/3 ok, 1 dropped");
expect(markdown).toContain("review#0: timeout");
expect(markdown).toContain("Refuted findings");
expect(markdown).toContain("possible issue");
expect(markdown).toContain("not reproducible");
});
it("renders final result titles before raw JSON", () => {
const markdown = formatUltraResultMarkdown({
workflow: "review",
phases: [{ id: "verify", ran: 1, ok: 1, dropped: 0 }],
phaseResults: {},
result: [{ title: "real bug", file: "src/a.ts", why: "confirmed" }],
steered: false,
});
expect(markdown).toContain("Final results");
expect(markdown).toContain("real bug");
expect(markdown).toContain("src/a.ts");
expect(markdown).not.toContain("```json");
});
it("renders aggregate token and cost usage when present", () => {
const markdown = formatUltraResultMarkdown({
workflow: "review",
phases: [],
phaseResults: {},
result: [],
steered: false,
tokenUsage: {
input: 100,
output: 40,
total: 140,
cacheRead: 20,
cacheWrite: 5,
cost: 0.1234,
},
});
expect(markdown).toContain("Usage: 140 tokens (100 in, 40 out) · $0.1234");
});
it("includes raw JSON only when expanded", () => {
const result = {
workflow: "review",
phases: [],
phaseResults: {},
result: [],
steered: false,
};
expect(formatUltraResultMarkdown(result)).not.toContain("```json");
expect(formatUltraResultMarkdown(result, true)).toContain("```json");
});
});
// ---------------------------------------------------------------------------
// formatWorkflowResultMessage — session/LLM payload
// ---------------------------------------------------------------------------
describe("background result messages", () => {
it("formats start and completion messages for detached workflow runs", () => {
const result = {
workflow: "review",
phases: [{ id: "p", ran: 1, ok: 1, dropped: 0 }],
phaseResults: {},
result: [{ title: "bug" }],
steered: false,
tokenUsage: {
input: 1,
output: 2,
total: 3,
cacheRead: 0,
cacheWrite: 0,
cost: 0,
},
};
expect(formatBackgroundAcceptedMessage("run-1", "review")).toBe(
'ultra background run "review" started: run-1',
);
expect(formatBackgroundResultMessage("run-1", result)).toContain(
'ultra background run "review" complete: run-1',
);
expect(formatBackgroundResultMessage("run-1", result)).toContain(
'"title": "bug"',
);
});
});
describe("formatWorkflowResultMessage", () => {
it("formats the aggregate JSON so /ultra command results enter the session", () => {
const content = formatWorkflowResultMessage({
workflow: "review",
phases: [
{ id: "review", ran: 3, ok: 3, dropped: 0 },
{ id: "verify", ran: 2, ok: 1, dropped: 1 },
],
phaseResults: {
review: [
{
ok: true,
value: { findings: [{ title: "candidate", file: "a.ts" }] },
},
],
verify: [{ ok: true, value: { title: "real bug", real: true } }],
},
result: [{ title: "real bug", real: true }],
steered: false,
});
expect(content).toContain('ultra workflow "review" result');
expect(content).toContain('"title": "real bug"');
expect(content).toContain('"phaseResults"');
expect(content).toContain('"candidate"');
expect(content).toContain('"id": "verify"');
});
it("makes an empty result explicit instead of looking like no run happened", () => {
const content = formatWorkflowResultMessage({
workflow: "review",
phases: [{ id: "review", ran: 3, ok: 3, dropped: 0 }],
phaseResults: { review: [{ ok: true, value: { findings: [] } }] },
result: [],
steered: false,
});
expect(content).toContain("Result is empty");
expect(content).toContain('"result": []');
});
});
// ---------------------------------------------------------------------------
// makeToolProgressSink — folds engine events, pushes through onUpdate
// ---------------------------------------------------------------------------
describe("makeToolProgressSink", () => {
const ev = (over: Partial<UltraProgressEvent>): UltraProgressEvent => ({
agentId: "a#0",
phase: "p",
kind: "start",
...over,
});
it("calls onUpdate with { content, details: reducerState } on every event, accumulating", () => {
const onUpdate = vi.fn();
const { sink, getState } = makeToolProgressSink(onUpdate);
sink(ev({ agentId: "a#0", kind: "start" }));
sink(ev({ agentId: "a#1", kind: "start" }));
sink(ev({ agentId: "a#0", kind: "end", status: "done" }));
expect(onUpdate).toHaveBeenCalledTimes(3);
const last = onUpdate.mock.calls[2][0] as {
content: unknown[];
details: { total: number; done: number };
};
expect(Array.isArray(last.content)).toBe(true);
expect(last.details.total).toBe(2);
expect(last.details.done).toBe(1);
expect(getState().total).toBe(2);
});
it("emits fresh details each call (renderResult tracks live state, not a frozen snapshot)", () => {
const seen: number[] = [];
const onUpdate = vi.fn((r: { details: { total: number } }) =>
seen.push(r.details.total),
);
const { sink } = makeToolProgressSink(onUpdate);
sink(ev({ agentId: "a#0" }));
sink(ev({ agentId: "a#1" }));
expect(seen).toEqual([1, 2]); // details changed between calls
});
it("strips non-cloneable `controls` so Pi can structured-clone details + result (regression)", () => {
// The runner attaches `controls` (functions — incl. NOOP_CONTROLS on the
// tool-less complete path) to EVERY event. Pi structured-clones the tool
// `details` (per-tick onUpdate + final result); a function in the state
// throws "The object can not be cloned." and fails the whole run.
const noopControls = { steer: () => {}, abort: () => {} };
const updates: { details: unknown }[] = [];
const onUpdate = vi.fn((u: { details: unknown }) => updates.push(u));
const { sink, getState } = makeToolProgressSink(onUpdate);
sink(ev({ agentId: "a#0", kind: "start", controls: noopControls }));
sink(
ev({
agentId: "a#0",
kind: "end",
status: "done",
controls: noopControls,
}),
);
// Both the live onUpdate payload and the final state must clone cleanly.
expect(() => structuredClone(updates[0].details)).not.toThrow();
expect(() => structuredClone(getState())).not.toThrow();
// And the run is still tracked correctly.
expect(getState().rows[0].controls).toBeUndefined();
expect(getState().done).toBe(1);
});
});
// ---------------------------------------------------------------------------
// completeWorkflowNames — getArgumentCompletions logic
// ---------------------------------------------------------------------------
describe("completeWorkflowNames", () => {
const list = [
discovered("ultra-review", "bundled"),
discovered("audit", "project"),
discovered("ui-sweep", "global"),
];
it("filters by prefix and returns {value,label} items", () => {
expect(completeWorkflowNames(list, "u")).toEqual([
{ value: "ultra-review", label: "ultra-review", description: "bundled" },
{ value: "ui-sweep", label: "ui-sweep", description: "global" },
]);
});
it("is case-insensitive and returns all names for an empty prefix", () => {
expect(completeWorkflowNames(list, "")?.map((i) => i.value)).toEqual([
"ultra-review",
"audit",
"ui-sweep",
]);
expect(completeWorkflowNames(list, "AUD")?.map((i) => i.value)).toEqual([
"audit",
]);
});
it("returns null when nothing matches", () => {
expect(completeWorkflowNames(list, "zzz")).toBeNull();
});
});
// ---------------------------------------------------------------------------
// resolveWorkflowInput — name (persisted) vs inline spec (ephemeral)
// ---------------------------------------------------------------------------
describe("resolveWorkflowInput", () => {
const list = [
discovered("ultra-review", "bundled"),
discovered("audit", "project"),
];
it("parses an inline spec (ephemeral mode)", () => {
const out = resolveWorkflowInput(
{ spec: validSpec("inline"), args: { x: 1 } },
list,
);
expect(out.spec.name).toBe("inline");
expect(out.args).toEqual({ x: 1 });
});
it("looks a named workflow up among discovered (persisted mode)", () => {
const out = resolveWorkflowInput({ name: "audit" }, list);
expect(out.spec.name).toBe("audit");
expect(out.args).toBeUndefined();
});
it("maps a bare positional remainder to the spec's declared args.params", () => {
const wf: DiscoveredWorkflow = {
name: "rev",
source: "bundled",
path: "/bundled/rev.json",
spec: specWithParams("rev", ["base"]),
};
const out = resolveWorkflowInput({ name: "rev" }, [wf], "main");
expect(out.args).toEqual({ base: "main" });
});
it("ignores a positional remainder when the spec declares no params", () => {
const out = resolveWorkflowInput({ name: "audit" }, list, "main");
expect(out.args).toBeUndefined();
});
it("prefers an explicit JSON args object over the positional remainder", () => {
const wf: DiscoveredWorkflow = {
name: "rev",
source: "bundled",
path: "/bundled/rev.json",
spec: specWithParams("rev", ["base"]),
};
const out = resolveWorkflowInput(
{ name: "rev", args: { base: "dev" } },
[wf],
"main",
);
expect(out.args).toEqual({ base: "dev" });
});
it("throws with the available names for an unknown name", () => {
expect(() => resolveWorkflowInput({ name: "missing" }, list)).toThrow(
/ultra-review|audit/,
);
});
it("throws when neither name nor spec is provided", () => {
expect(() => resolveWorkflowInput({}, list)).toThrow(
/name.*spec|spec.*name/i,
);
});
it("propagates a parse error for a malformed inline spec", () => {
expect(() =>
resolveWorkflowInput({ spec: { phases: [] } }, list),
).toThrow();
});
it("validates a named workflow's spec, surfacing parseWorkflow's error on a malformed saved file", () => {
// Discovery stores the raw JSON.parse output cast to WorkflowSpec — a saved
// file can be JSON-valid with a `name` yet structurally malformed (no
// `phases`). Resolving by name must run parseWorkflow so `/ultra <name>`
// fails fast with the TypeBox path error, not a cryptic mid-run crash.
const malformed: DiscoveredWorkflow = {
name: "broken",
source: "project",
path: "/project/broken.json",
spec: { name: "broken" } as unknown as WorkflowSpec,
};
expect(() => resolveWorkflowInput({ name: "broken" }, [malformed])).toThrow(
/Invalid workflow spec/,
);
});
});
// ---------------------------------------------------------------------------
// parseCommandLine — `/ultra <name> [json-args]`
// ---------------------------------------------------------------------------
describe("parseCommandLine", () => {
it("returns {} for an empty line", () => {
expect(parseCommandLine(" ")).toEqual({});
});
it("extracts a bare name", () => {
expect(parseCommandLine("ultra-review")).toEqual({ name: "ultra-review" });
});
it("parses a trailing JSON object as args (retaining the raw rest)", () => {
expect(parseCommandLine('ultra-review {"base":"main","n":2}')).toEqual({
name: "ultra-review",
args: { base: "main", n: 2 },
rest: '{"base":"main","n":2}',
});
});
it("keeps non-JSON trailing text as `rest` (for positional mapping)", () => {
expect(parseCommandLine("ultra-review main")).toEqual({
name: "ultra-review",
rest: "main",
});
expect(parseCommandLine("ultra-review [1,2]")).toEqual({
name: "ultra-review",
rest: "[1,2]",
});
});
});
// ---------------------------------------------------------------------------
// mapPositionalArgs — bare `/ultra <name> <tok...>` → declared args.params
// ---------------------------------------------------------------------------
describe("mapPositionalArgs", () => {
it("fills declared params in order from whitespace tokens", () => {
expect(mapPositionalArgs("main", ["base"])).toEqual({ base: "main" });
expect(mapPositionalArgs("a b", ["x", "y"])).toEqual({ x: "a", y: "b" });
});
it("soaks remaining tokens into the last declared param (free-text tail)", () => {
// single free-text param keeps the whole remainder
expect(mapPositionalArgs("add a dark-mode toggle", ["task"])).toEqual({
task: "add a dark-mode toggle",
});
// only the LAST param soaks; earlier params take one token each
expect(mapPositionalArgs("main fix the bug", ["base", "task"])).toEqual({
base: "main",
task: "fix the bug",
});
});
it("returns undefined for an empty remainder or no declared params", () => {
expect(mapPositionalArgs(" ", ["base"])).toBeUndefined();
expect(mapPositionalArgs("main", [])).toBeUndefined();
});
});