repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ultra/__tests__/ui.test.ts
RawFile outline
- K line 21
- makeOverlay line 34
- beforeAll line 57
- theme line 63
- pe line 68
- stateFrom line 73
- renderTool line 77
- toolText line 89
- ultra tool sink — renderUltraResult line 96
- header shows workflow name and description when supplied line 97
- truncation keeps ellipsis in the surrounding style span line 107
- scripted line 129
- collapsed: shows phase/agent counts + summary + expand hint, never bodies line 148
- expanded: shows per-agent statuses + latest action + dropped agents line 163
- expanded: renders each agent as identity plus model, usage, and action lines line 176
- never emits bodies when expanded=false (sentinels absent collapsed, present expanded) line 221
- tracks fresh details — render state N then N+1, the lines change line 228
- isPartial drives the running marker on the header line 244
- tolerates missing details (headless / no run yet) line 252
- tolerates a foreign (non-ReducerState) details without crashing the render loop line 270
- ultra command overlay — focus + drill-in transcript (7b) line 291
- header shows workflow name and description when supplied line 292
- focusing agent k shows its deltas and not the others line 306
- auto-focuses the first agent in a new phase so verifier transcripts are visible during the run line 349
- keeps rendered overlay within terminal height minus a 3-row safety margin line 382
- renders transcript markdown with Pi's markdown renderer line 397
- renders transcript title as a compact divider header line 408
- Alt+Up/Alt+Down scroll transcript when PageUp/PageDown is intercepted by the terminal line 418
- follow-mode pins to the newest line until the user scrolls, then re-pins line 436
- throttles re-render requests to the window, but state stays fresh; terminal events bypass it line 479
- type line 519
- ultra command overlay — steer + per-agent abort (7c) line 523
- s+text on a RUNNING agent calls controls.steer and marks steered at enqueue time line 524
- x aborts the focused agent via controls.abort line 548
- steering a FINISHED agent routes to followUp, not steer, and does not taint the run line 560
- global Esc triggers the run-level abort line 582
- Esc inside steer-input cancels the buffer; it does NOT abort the run line 590
- a rejecting steer is caught (no floating rejection) line 610
- the tool sink exposes NO controls path (read-only) — render never invokes steer/abort line 626
import type {
Theme,
ToolRenderResultOptions,
} from "@earendil-works/pi-coding-agent";
import { initTheme } from "@earendil-works/pi-coding-agent";
import { beforeAll, describe, expect, it, vi } from "vitest";
import {
type AgentControls,
initialReducerState,
reduceProgress,
type UltraProgressEvent,
} from "../progress.ts";
import {
type OverlayAgentControls,
type OverlayHost,
renderUltraResult,
UltraOverlayComponent,
} from "../ui.ts";
// Real terminal byte sequences (verified against pi-tui's matchesKey).
const K = {
esc: "\x1b",
tab: "\t",
up: "\x1b[A",
down: "\x1b[B",
altUp: "\x1bp",
altDown: "\x1bn",
pageUp: "\x1b[5~",
pageDown: "\x1b[6~",
enter: "\r",
backspace: "\x7f",
};
function makeOverlay(opts: {
rows?: number;
now?: () => number;
throttleMs?: number;
onRunAbort?: () => void;
}) {
const requestRender = vi.fn();
const host: OverlayHost = {
requestRender,
terminal: { rows: opts.rows ?? 24, columns: 80 },
};
const overlay = new UltraOverlayComponent({
host,
theme,
onRunAbort: opts.onRunAbort ?? vi.fn(),
now: opts.now,
throttleMs: opts.throttleMs,
});
return { overlay, requestRender, host };
}
// `keyHint` (used by the collapsed tool view) reads the global theme; the host
// initialises it in prod, so the fakes-only harness must do the same once.
beforeAll(() => {
initTheme();
});
// A no-op theme: `fg`/`bold` return the text verbatim so assertions can target
// plain substrings. (`keyHint` uses the *global* theme, not this one.)
const theme = {
fg: (_c: string, t: string) => t,
bold: (t: string) => t,
} as unknown as Theme;
const pe = (
e: Partial<UltraProgressEvent> &
Pick<UltraProgressEvent, "agentId" | "phase" | "kind">,
): UltraProgressEvent => e;
function stateFrom(events: UltraProgressEvent[]) {
return events.reduce(reduceProgress, initialReducerState());
}
function renderTool(
state: ReturnType<typeof initialReducerState>,
options: ToolRenderResultOptions,
width = 80,
): string[] {
return renderUltraResult(
{ content: [], details: state },
options,
theme,
).render(width);
}
const toolText = (
state: ReturnType<typeof initialReducerState>,
options: ToolRenderResultOptions,
): string => renderTool(state, options).join("\n");
// --- Layer 7a — TOOL sink (renderResult) ---------------------------------
describe("ultra tool sink — renderUltraResult", () => {
it("header shows workflow name and description when supplied", () => {
const s = initialReducerState({
workflowName: "review",
workflowDescription: "Review the diff from every angle.",
});
const out = toolText(s, { expanded: false, isPartial: true });
expect(out).toContain("review");
expect(out).toContain("Review the diff from every angle.");
});
it("truncation keeps ellipsis in the surrounding style span", () => {
const s = stateFrom([
pe({ agentId: "scan#0", phase: "scan", kind: "start" }),
pe({
agentId: "scan#0",
phase: "scan",
kind: "action",
toolName: "bash",
text: JSON.stringify({
command: "python3 - <<'PY'\n" + "x".repeat(200),
}),
}),
]);
const out = renderTool(s, { expanded: true, isPartial: true }, 54).join(
"\n",
);
expect(out).toContain("...");
expect(out).not.toContain("\x1b[0m...\x1b[0m");
});
// A run with a running agent whose latest action + transcript carry distinct
// sentinels, plus a dropped (timeout) agent.
const scripted = stateFrom([
pe({ agentId: "a", phase: "review", kind: "start" }),
pe({
agentId: "a",
phase: "review",
kind: "action",
toolName: "read",
text: "/SECRET-ACTION",
}),
pe({
agentId: "a",
phase: "review",
kind: "delta",
text: "SECRET-TRANSCRIPT-BODY",
}),
pe({ agentId: "b", phase: "review", kind: "start" }),
pe({ agentId: "b", phase: "review", kind: "end", status: "timeout" }),
]);
it("collapsed: shows phase/agent counts + summary + expand hint, never bodies", () => {
const out = toolText(scripted, { expanded: false, isPartial: true });
// aggregate counts + phase counter present
expect(out).toContain("phase 1/1");
expect(out).toContain("0/2 done");
expect(out).toContain("1✗");
// the collapsed expand affordance
expect(out).toContain("to expand");
// NEVER emits per-agent action lines or transcript bodies when collapsed
expect(out).not.toContain("/SECRET-ACTION");
expect(out).not.toContain("SECRET-TRANSCRIPT-BODY");
// not even the per-agent ids
expect(out).not.toContain("agentId");
});
it("expanded: shows per-agent statuses + latest action + dropped agents", () => {
const out = toolText(scripted, { expanded: true, isPartial: true });
// running agent + its latest action
expect(out).toContain("a");
expect(out).toContain("running");
expect(out).toContain("/SECRET-ACTION");
// dropped agent surfaced
expect(out).toContain("b");
expect(out).toContain("dropped");
// transcript bodies are NEVER rendered by the tool sink, even expanded
expect(out).not.toContain("SECRET-TRANSCRIPT-BODY");
});
it("expanded: renders each agent as identity plus model, usage, and action lines", () => {
const s = stateFrom([
pe({
agentId: "plan#0",
phase: "plan",
kind: "start",
tier: "small",
model: "openai/gpt-5-mini",
thinkingLevel: "low",
startedAt: Date.now() - 18_000,
}),
pe({
agentId: "plan#0",
phase: "plan",
kind: "action",
toolName: "read",
text: "docs/phase-1.html",
}),
pe({
agentId: "plan#0",
phase: "plan",
kind: "end",
status: "done",
usage: {
input: 1800,
output: 300,
total: 2100,
cacheRead: 0,
cacheWrite: 0,
cost: 0,
},
}),
]);
const lines = renderTool(s, { expanded: true, isPartial: false }, 100);
const out = lines.join("\n");
expect(out).toContain("plan#0 · done");
expect(out).toContain("├ model");
expect(out).toContain("small → openai/gpt-5-mini · low");
expect(out).toContain("├ usage");
expect(out).toContain("2.1k tokens");
expect(out).toContain("└ action");
expect(out).toContain("read docs/phase-1.html");
});
it("never emits bodies when expanded=false (sentinels absent collapsed, present expanded)", () => {
const collapsed = toolText(scripted, { expanded: false, isPartial: false });
const expanded = toolText(scripted, { expanded: true, isPartial: false });
expect(collapsed).not.toContain("/SECRET-ACTION");
expect(expanded).toContain("/SECRET-ACTION");
});
it("tracks fresh details — render state N then N+1, the lines change", () => {
const sN = stateFrom([
pe({ agentId: "a", phase: "p", kind: "end", status: "done" }),
]);
const sN1 = stateFrom([
pe({ agentId: "a", phase: "p", kind: "end", status: "done" }),
pe({ agentId: "b", phase: "p", kind: "end", status: "done" }),
]);
const opts: ToolRenderResultOptions = { expanded: false, isPartial: true };
const tN = toolText(sN, opts);
const tN1 = toolText(sN1, opts);
expect(tN).toContain("1/1 done");
expect(tN1).toContain("2/2 done");
expect(tN).not.toEqual(tN1); // not a frozen snapshot
});
it("isPartial drives the running marker on the header", () => {
const s = stateFrom([pe({ agentId: "a", phase: "p", kind: "start" })]);
expect(toolText(s, { expanded: false, isPartial: true })).toContain("⏳");
expect(toolText(s, { expanded: false, isPartial: false })).not.toContain(
"⏳",
);
});
it("tolerates missing details (headless / no run yet)", () => {
const comp = renderUltraResult(
{
content: [],
details: undefined as unknown as ReturnType<typeof initialReducerState>,
},
{ expanded: false, isPartial: false },
theme,
);
expect(() => comp.render(80)).not.toThrow();
expect(comp.render(80).join("\n")).toContain("0/0 done");
});
// Regression: a truthy `details` that is NOT a ReducerState — a resumed or
// foreign tool result, a structured-output payload, a serialization double-wrap
// — must fall back to an empty board, NEVER throw. An uncaught throw here is
// fatal: it escapes tool-error handling and crashes the whole TUI render loop
// (`state.phases.length` on an object without `phases`).
it("tolerates a foreign (non-ReducerState) details without crashing the render loop", () => {
const foreign = { results: [{ ok: true }] } as unknown as ReturnType<
typeof initialReducerState
>;
for (const options of [
{ expanded: false, isPartial: false },
{ expanded: true, isPartial: true }, // expanded also reads `state.rows`
] as const) {
const comp = renderUltraResult(
{ content: [], details: foreign },
options,
theme,
);
expect(() => comp.render(80)).not.toThrow();
expect(comp.render(80).join("\n")).toContain("0/0 done");
}
});
});
// --- Layer 7b — COMMAND overlay: board + drill-in transcript --------------
describe("ultra command overlay — focus + drill-in transcript (7b)", () => {
it("header shows workflow name and description when supplied", () => {
const requestRender = vi.fn();
const overlay = new UltraOverlayComponent({
host: { requestRender, terminal: { rows: 24, columns: 80 } },
theme,
onRunAbort: vi.fn(),
workflowName: "review",
workflowDescription: "Review the diff from every angle.",
});
const out = overlay.render(80).join("\n");
expect(out).toContain("review");
expect(out).toContain("Review the diff from every angle.");
});
it("focusing agent k shows its deltas and not the others'", () => {
const { overlay } = makeOverlay({ rows: 24 });
for (const id of ["a", "b", "c"]) {
overlay.handleProgress(pe({ agentId: id, phase: "p", kind: "start" }));
}
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "delta", text: "AAA-DELTA" }),
);
overlay.handleProgress(
pe({ agentId: "b", phase: "p", kind: "delta", text: "BBB-DELTA" }),
);
overlay.handleProgress(
pe({ agentId: "c", phase: "p", kind: "delta", text: "CCC-DELTA" }),
);
// default focus is the first agent
let out = overlay.render(60).join("\n");
expect(out).toContain("transcript: a");
expect(out).toContain("AAA-DELTA");
expect(out).not.toContain("BBB-DELTA");
expect(out).not.toContain("CCC-DELTA");
// Tab advances focus → b
overlay.handleInput(K.tab);
out = overlay.render(60).join("\n");
expect(out).toContain("transcript: b");
expect(out).toContain("BBB-DELTA");
expect(out).not.toContain("AAA-DELTA");
expect(out).not.toContain("CCC-DELTA");
// ↓ advances focus → c
overlay.handleInput(K.down);
out = overlay.render(60).join("\n");
expect(out).toContain("transcript: c");
expect(out).toContain("CCC-DELTA");
// ↑ moves focus back → b
overlay.handleInput(K.up);
out = overlay.render(60).join("\n");
expect(out).toContain("transcript: b");
expect(out).toContain("BBB-DELTA");
});
it("auto-focuses the first agent in a new phase so verifier transcripts are visible during the run", () => {
const { overlay } = makeOverlay({ rows: 12 });
for (let i = 0; i < 3; i++) {
overlay.handleProgress(
pe({ agentId: `review#${i}`, phase: "review", kind: "start" }),
);
overlay.handleProgress(
pe({
agentId: `review#${i}`,
phase: "review",
kind: "end",
status: "done",
}),
);
}
overlay.handleProgress(
pe({ agentId: "verify#0", phase: "verify", kind: "start" }),
);
overlay.handleProgress(
pe({
agentId: "verify#0",
phase: "verify",
kind: "delta",
text: "VERIFY-DELTA",
}),
);
const out = overlay.render(60).join("\n");
expect(out).toContain("transcript: verify#0");
expect(out).toContain("VERIFY-DELTA");
});
it("keeps rendered overlay within terminal height minus a 3-row safety margin", () => {
const { overlay } = makeOverlay({ rows: 12 });
for (let i = 0; i < 8; i++) {
overlay.handleProgress(
pe({ agentId: `a${i}`, phase: "p", kind: "start" }),
);
}
for (let i = 0; i < 20; i++) {
overlay.handleProgress(
pe({ agentId: "a7", phase: "p", kind: "delta", text: `L${i}\n` }),
);
}
expect(overlay.render(60).length).toBeLessThanOrEqual(9);
});
it("renders transcript markdown with Pi's markdown renderer", () => {
const { overlay } = makeOverlay({ rows: 24 });
overlay.handleProgress(pe({ agentId: "a", phase: "p", kind: "start" }));
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "delta", text: "**bold**" }),
);
const out = overlay.render(60).join("\n");
expect(out).toContain("bold");
expect(out).not.toContain("**bold**");
});
it("renders transcript title as a compact divider header", () => {
const { overlay } = makeOverlay({ rows: 16 });
overlay.handleProgress(pe({ agentId: "a", phase: "p", kind: "start" }));
const lines = overlay.render(50);
const header = lines.find((l) => l.includes("transcript: a"));
expect(header).toBeDefined();
expect(header).toMatch(/─.*transcript: a.*─/);
expect(lines.some((l) => l === "transcript: a")).toBe(false);
});
it("Alt+Up/Alt+Down scroll transcript when PageUp/PageDown is intercepted by the terminal", () => {
const { overlay } = makeOverlay({ rows: 12 });
overlay.handleProgress(pe({ agentId: "a", phase: "p", kind: "start" }));
for (let i = 0; i < 10; i++) {
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "delta", text: `L${i}\n` }),
);
}
expect(overlay.render(40).join("\n")).toContain("L9");
overlay.handleInput(K.altUp);
let out = overlay.render(40).join("\n");
expect(out).toContain("L0");
expect(out).not.toContain("L9");
overlay.handleInput(K.altDown);
out = overlay.render(40).join("\n");
expect(out).toContain("L9");
});
it("follow-mode pins to the newest line until the user scrolls, then re-pins", () => {
// rows=12 with a 3-row safety margin leaves room for a transcript tail.
const { overlay } = makeOverlay({ rows: 12 });
overlay.handleProgress(pe({ agentId: "a", phase: "p", kind: "start" }));
for (let i = 0; i < 10; i++) {
overlay.handleProgress(
pe({
agentId: "a",
phase: "p",
kind: "delta",
text: i < 9 ? `L${i}\n` : `L${i}`,
}),
);
}
// follow-mode shows the newest tail, not the head
let out = overlay.render(40).join("\n");
expect(out).toContain("L9");
expect(out).not.toContain("L0");
// scroll up → follow disengages, view moves to the head
overlay.handleInput(K.pageUp);
out = overlay.render(40).join("\n");
expect(out).toContain("L0");
expect(out).not.toContain("L9");
// new deltas arrive WHILE scrolled → view stays put (does not jump to newest)
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "delta", text: "\nL10" }),
);
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "delta", text: "\nL11" }),
);
out = overlay.render(40).join("\n");
expect(out).toContain("L0");
expect(out).not.toContain("L11");
// scroll back to the bottom → follow re-engages, newest shown again
overlay.handleInput(K.pageDown);
out = overlay.render(40).join("\n");
expect(out).toContain("L11");
});
it("throttles re-render requests to the window, but state stays fresh; terminal events bypass it", () => {
let clock = 0;
const { overlay, requestRender } = makeOverlay({
now: () => clock,
throttleMs: 80,
});
clock = 0;
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "delta", text: "x" }),
); // leading edge
clock = 10;
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "delta", text: "y" }),
); // throttled
clock = 50;
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "delta", text: "z" }),
); // throttled
expect(requestRender).toHaveBeenCalledTimes(1);
clock = 100;
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "delta", text: "w" }),
); // window elapsed
expect(requestRender).toHaveBeenCalledTimes(2);
clock = 110;
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "end", status: "done" }),
); // forced
expect(requestRender).toHaveBeenCalledTimes(3);
// every delta was folded despite the throttle — no lost state
expect(overlay.render(80).join("\n")).toContain("xyzw");
});
});
// --- Layer 7c — steer + per-agent abort (command overlay only) ------------
function type(overlay: UltraOverlayComponent, text: string) {
for (const ch of text) overlay.handleInput(ch);
}
describe("ultra command overlay — steer + per-agent abort (7c)", () => {
it("s+text on a RUNNING agent calls controls.steer and marks steered at enqueue time", () => {
const steer = vi.fn().mockResolvedValue(undefined);
const followUp = vi.fn().mockResolvedValue(undefined);
const controls: AgentControls = { steer, abort: vi.fn() };
(controls as OverlayAgentControls).followUp = followUp;
const { overlay } = makeOverlay({ rows: 24 });
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "start", controls }),
);
expect(overlay.steered).toBe(false);
overlay.handleInput("s"); // enter steer sub-mode
// the message itself contains 's' and 'x' — in steer mode they are TEXT,
// not the steer/abort commands (Esc-collision guard).
type(overlay, "use bash xtools");
expect(overlay.steered).toBe(false); // not yet enqueued
overlay.handleInput(K.enter); // submit
expect(steer).toHaveBeenCalledTimes(1);
expect(steer).toHaveBeenCalledWith("use bash xtools");
expect(followUp).not.toHaveBeenCalled();
expect(overlay.steered).toBe(true); // synchronous, before the promise settles
});
it("x aborts the focused agent via controls.abort", () => {
const abort = vi.fn();
const controls: AgentControls = { steer: vi.fn(), abort };
const { overlay } = makeOverlay({ rows: 24 });
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "start", controls }),
);
overlay.handleProgress(pe({ agentId: "b", phase: "p", kind: "start" }));
overlay.handleInput("x"); // focus is a
expect(abort).toHaveBeenCalledTimes(1);
});
it("steering a FINISHED agent routes to followUp, not steer, and does not taint the run", () => {
const steer = vi.fn();
const followUp = vi.fn().mockResolvedValue(undefined);
const controls: AgentControls = { steer, abort: vi.fn() };
(controls as OverlayAgentControls).followUp = followUp;
const { overlay } = makeOverlay({ rows: 24 });
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "start", controls }),
);
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "end", status: "done" }),
);
overlay.handleInput("s");
type(overlay, "rerun");
overlay.handleInput(K.enter);
expect(followUp).toHaveBeenCalledWith("rerun");
expect(steer).not.toHaveBeenCalled();
expect(overlay.steered).toBe(false); // follow-up is not a steer taint
});
it("global Esc triggers the run-level abort", () => {
const onRunAbort = vi.fn();
const { overlay } = makeOverlay({ rows: 24, onRunAbort });
overlay.handleProgress(pe({ agentId: "a", phase: "p", kind: "start" }));
overlay.handleInput(K.esc);
expect(onRunAbort).toHaveBeenCalledTimes(1);
});
it("Esc inside steer-input cancels the buffer; it does NOT abort the run", () => {
const onRunAbort = vi.fn();
const steer = vi.fn();
const controls: AgentControls = { steer, abort: vi.fn() };
const { overlay } = makeOverlay({ rows: 24, onRunAbort });
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "start", controls }),
);
overlay.handleInput("s"); // steer mode
type(overlay, "half typed");
overlay.handleInput(K.esc); // cancel the buffer, back to normal mode
expect(onRunAbort).not.toHaveBeenCalled();
expect(steer).not.toHaveBeenCalled();
// a fresh Esc in normal mode now aborts the run
overlay.handleInput(K.esc);
expect(onRunAbort).toHaveBeenCalledTimes(1);
});
it("a rejecting steer is caught (no floating rejection)", async () => {
const steer = vi.fn().mockRejectedValue(new Error("boom"));
const controls: AgentControls = { steer, abort: vi.fn() };
const { overlay } = makeOverlay({ rows: 24 });
overlay.handleProgress(
pe({ agentId: "a", phase: "p", kind: "start", controls }),
);
overlay.handleInput("s");
type(overlay, "go");
expect(() => overlay.handleInput(K.enter)).not.toThrow();
expect(steer).toHaveBeenCalledWith("go");
// let the rejected promise settle — the .catch() handles it, no crash
await Promise.resolve();
await Promise.resolve();
});
it("the tool sink exposes NO controls path (read-only) — render never invokes steer/abort", () => {
// Re-assert the surface split: feeding controls-bearing state to the tool
// renderer must not call them; it only draws.
const steer = vi.fn();
const abort = vi.fn();
const controls: AgentControls = { steer, abort };
const s = stateFrom([
pe({ agentId: "a", phase: "p", kind: "start", controls }),
]);
renderUltraResult(
{ content: [], details: s },
{ expanded: true, isPartial: true },
theme,
).render(80);
expect(steer).not.toHaveBeenCalled();
expect(abort).not.toHaveBeenCalled();
});
});