repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/__tests__/progress.test.ts

Raw
File outline
import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
import { describe, expect, it, vi } from "vitest";
import {
	type AgentControls,
	initialReducerState,
	mapSessionEvent,
	reduceProgress,
	type UltraProgressEvent,
} from "../progress.ts";

// AgentSessionEvent is a large discriminated union whose message-bearing
// variants carry full AgentMessage / AssistantMessage objects. The mapping
// only ever reads the validated field paths, so the fixtures build minimal
// shapes and cast — exercising exactly the paths the real session emits.
const ev = (e: unknown): AgentSessionEvent => e as AgentSessionEvent;

const AGENT = "review#0";
const PHASE = "review";

function map(e: unknown): UltraProgressEvent | null {
	return mapSessionEvent(ev(e), AGENT, PHASE);
}

describe("mapSessionEvent", () => {
	it("maps a scripted session sequence to tagged ultra events", () => {
		// tool_execution_start -> message_update(text_delta) -> tool_execution_end -> agent_end
		const start = map({ type: "agent_start" });
		const toolStart = map({
			type: "tool_execution_start",
			toolCallId: "t1",
			toolName: "read",
			args: { file: "a.ts" },
		});
		const delta = map({
			type: "message_update",
			message: {},
			assistantMessageEvent: {
				type: "text_delta",
				contentIndex: 0,
				delta: "hello ",
				partial: {},
			},
		});
		const toolEnd = map({
			type: "tool_execution_end",
			toolCallId: "t1",
			toolName: "read",
			// content and details deliberately differ: the mapping must read
			// `result.details` (the validated structured-output path), never content.
			result: { content: "CONTENT_TEXT", details: { verdict: "DETAILS_VAL" } },
			isError: false,
		});
		const end = map({ type: "agent_end", messages: [], willRetry: false });

		// every mapped event is tagged with the agent id + phase it was given
		for (const e of [start, toolStart, delta, toolEnd, end]) {
			expect(e).not.toBeNull();
			expect(e?.agentId).toBe(AGENT);
			expect(e?.phase).toBe(PHASE);
		}

		expect(start).toMatchObject({ kind: "start" });
		expect(toolStart).toMatchObject({ kind: "action", toolName: "read" });
		expect(toolStart?.text).toContain("a.ts");
		expect(delta).toMatchObject({ kind: "delta", text: "hello " });
		expect(toolEnd).toMatchObject({ kind: "action", toolName: "read" });
		expect(end).toMatchObject({ kind: "end", status: "done" });

		// the discriminating assertion: details is read, content is not
		expect(toolEnd?.text).toContain("DETAILS_VAL");
		expect(toolEnd?.text).not.toContain("CONTENT_TEXT");
	});

	it("maps thinking deltas to delta events", () => {
		const e = map({
			type: "message_update",
			message: {},
			assistantMessageEvent: {
				type: "thinking_delta",
				contentIndex: 0,
				delta: "pondering",
				partial: {},
			},
		});
		expect(e).toMatchObject({ kind: "delta", text: "pondering" });
	});

	it("flags a tool error on the action event", () => {
		const e = map({
			type: "tool_execution_end",
			toolCallId: "t9",
			toolName: "bash",
			result: { content: "boom", details: undefined },
			isError: true,
		});
		expect(e).toMatchObject({
			kind: "action",
			toolName: "bash",
			status: "error",
		});
	});

	it("returns null for events that do not map", () => {
		expect(map({ type: "turn_start" })).toBeNull();
		expect(map({ type: "message_start", message: {} })).toBeNull();
		expect(
			map({ type: "queue_update", steering: [], followUp: [] }),
		).toBeNull();
		// a message_update whose inner event is not a text/thinking delta
		expect(
			map({
				type: "message_update",
				message: {},
				assistantMessageEvent: {
					type: "text_start",
					contentIndex: 0,
					partial: {},
				},
			}),
		).toBeNull();
	});

	it("never attaches controls (the runner owns the live session)", () => {
		const e = map({ type: "agent_start" });
		expect(e?.controls).toBeUndefined();
	});
});

// --- reducer -------------------------------------------------------------

const pe = (
	e: Partial<UltraProgressEvent> &
		Pick<UltraProgressEvent, "agentId" | "phase" | "kind">,
): UltraProgressEvent => e;

function fold(events: UltraProgressEvent[]) {
	return events.reduce(reduceProgress, initialReducerState());
}

describe("reduceProgress", () => {
	it("starts empty", () => {
		const s = initialReducerState();
		expect(s.rows).toEqual([]);
		expect(s.transcripts).toEqual({});
		expect(s.phases).toEqual([]);
		expect(s.phase).toBeUndefined();
		expect(s).toMatchObject({ total: 0, done: 0, dropped: 0 });
	});

	it("formats tool call rows from structured args and does not replace them with raw results", () => {
		const s = fold([
			pe({
				agentId: "a",
				phase: "p1",
				kind: "action",
				toolName: "bash",
				args: { command: "git status --short\nsecond line" },
				text: JSON.stringify({ command: "git status --short" }),
			}),
			pe({
				agentId: "a",
				phase: "p1",
				kind: "action",
				toolName: "bash",
				result: { content: [{ type: "text", text: "RAW RESULT" }] },
				text: "RAW RESULT",
			}),
		]);

		expect(s.rows[0].action).toContain("bash $ git status --short");
		expect(s.rows[0].action).not.toContain("RAW RESULT");
	});

	it("summarizes structured_output rows instead of dumping JSON", () => {
		const s = fold([
			pe({
				agentId: "a",
				phase: "review",
				kind: "action",
				toolName: "structured_output",
				args: {
					findings: [
						{ title: "A very long finding title", file: "a.ts" },
						{ title: "Another finding", file: "b.ts" },
					],
				},
				text: JSON.stringify({
					findings: [{ title: "A very long finding title" }],
				}),
			}),
		]);

		expect(s.rows[0].action).toBe("structured output · 2 findings");
		expect(s.rows[0].action).not.toContain('{"findings"');
	});

	it("folds a scripted stream into one upserted row + transcript", () => {
		const s = fold([
			pe({ agentId: "a", phase: "p1", kind: "start" }),
			pe({
				agentId: "a",
				phase: "p1",
				kind: "action",
				toolName: "read",
				text: "a.ts",
			}),
			pe({ agentId: "a", phase: "p1", kind: "delta", text: "hello " }),
			pe({ agentId: "a", phase: "p1", kind: "delta", text: "world" }),
			pe({ agentId: "a", phase: "p1", kind: "end", status: "done" }),
		]);

		expect(s.rows).toHaveLength(1);
		expect(s.rows[0]).toMatchObject({
			agentId: "a",
			phase: "p1",
			status: "done",
		});
		expect(s.rows[0].action).toContain("read");
		// transcript accumulates the streamed deltas verbatim + the tool action
		expect(s.transcripts.a).toContain("hello world");
		expect(s.transcripts.a).toContain("read");
		expect(s).toMatchObject({ total: 1, done: 1, dropped: 0 });
		expect(s.phases).toEqual(["p1"]);
		expect(s.phase).toBe("p1");
	});

	it("upserts idempotently — a later event updates the row, never appends", () => {
		const s = fold([
			pe({ agentId: "a", phase: "p1", kind: "start" }),
			pe({ agentId: "b", phase: "p1", kind: "start" }),
			pe({ agentId: "a", phase: "p1", kind: "end", status: "done" }),
		]);
		expect(s.rows.map((r) => r.agentId)).toEqual(["a", "b"]); // order preserved
		expect(s.rows[0]).toMatchObject({ agentId: "a", status: "done" }); // updated in place
		expect(s.rows[1]).toMatchObject({ agentId: "b", status: "running" });
		expect(s.total).toBe(2);
	});

	it("accumulates transcripts per agent and isolates agents", () => {
		const s = fold([
			pe({ agentId: "a", phase: "p1", kind: "delta", text: "secretA" }),
			pe({ agentId: "b", phase: "p1", kind: "delta", text: "secretB" }),
			pe({ agentId: "a", phase: "p1", kind: "delta", text: "-more" }),
		]);
		expect(s.transcripts.a).toBe("secretA-more");
		expect(s.transcripts.b).toBe("secretB");
		expect(s.transcripts.a).not.toContain("secretB");
		expect(s.transcripts.b).not.toContain("secretA");
	});

	it("updates done/dropped tallies on terminal events", () => {
		const s = fold([
			pe({ agentId: "a", phase: "p1", kind: "end", status: "done" }),
			pe({ agentId: "b", phase: "p1", kind: "end", status: "dropped" }),
			pe({ agentId: "c", phase: "p1", kind: "end", status: "timeout" }),
		]);
		expect(s).toMatchObject({ total: 3, done: 1, dropped: 2 });
	});

	it("tracks the phase counter as distinct phases arrive in order", () => {
		const s = fold([
			pe({ agentId: "a", phase: "review", kind: "start" }),
			pe({ agentId: "a", phase: "review", kind: "end", status: "done" }),
			pe({ agentId: "v0", phase: "verify", kind: "start" }),
		]);
		expect(s.phases).toEqual(["review", "verify"]);
		expect(s.phase).toBe("verify");
	});

	it("retains model, timing, and usage metadata across later events", () => {
		const usage = {
			input: 100,
			output: 20,
			total: 120,
			cacheRead: 10,
			cacheWrite: 0,
			cost: 0.1,
		};
		const s = fold([
			pe({
				agentId: "a",
				phase: "p1",
				kind: "start",
				tier: "small",
				model: "openai/gpt-5-mini",
				thinkingLevel: "low",
				startedAt: 1000,
			}),
			pe({ agentId: "a", phase: "p1", kind: "delta", text: "x" }),
			pe({ agentId: "a", phase: "p1", kind: "end", status: "done", usage }),
		]);

		expect(s.rows[0]).toMatchObject({
			tier: "small",
			model: "openai/gpt-5-mini",
			thinkingLevel: "low",
			startedAt: 1000,
			usage,
		});
	});

	it("binds per-agent controls from the event onto the row", () => {
		const controls: AgentControls = { steer: vi.fn(), abort: vi.fn() };
		const s = fold([
			pe({ agentId: "a", phase: "p1", kind: "start", controls }),
			pe({ agentId: "a", phase: "p1", kind: "delta", text: "x" }), // later event w/o controls
		]);
		expect(s.rows[0].controls).toBe(controls); // retained across later events
	});

	it("returns a new state object and preserves identity of unchanged rows", () => {
		const s0 = fold([
			pe({ agentId: "a", phase: "p1", kind: "start" }),
			pe({ agentId: "b", phase: "p1", kind: "start" }),
		]);
		const s1 = reduceProgress(
			s0,
			pe({ agentId: "a", phase: "p1", kind: "end", status: "done" }),
		);
		expect(s1).not.toBe(s0); // pure: new state
		expect(s1.rows[1]).toBe(s0.rows[1]); // unchanged row keeps reference (ui memoization)
		expect(s1.rows[0]).not.toBe(s0.rows[0]); // changed row is fresh
	});

	it("end-to-end: mapped session events fold into the expected board state", () => {
		const raw = [
			{ type: "agent_start" },
			{
				type: "tool_execution_start",
				toolCallId: "t1",
				toolName: "grep",
				args: { pattern: "x" },
			},
			{
				type: "message_update",
				message: {},
				assistantMessageEvent: {
					type: "text_delta",
					contentIndex: 0,
					delta: "done.",
					partial: {},
				},
			},
			{ type: "agent_end", messages: [], willRetry: false },
		];
		const mapped = raw
			.map((r) => mapSessionEvent(ev(r), "g0", "review"))
			.filter((e): e is UltraProgressEvent => e !== null);
		const s = mapped.reduce(reduceProgress, initialReducerState());

		expect(s.rows).toHaveLength(1);
		expect(s.rows[0]).toMatchObject({
			agentId: "g0",
			phase: "review",
			status: "done",
		});
		expect(s.rows[0].action).toContain("grep");
		expect(s.transcripts.g0).toContain("done.");
		expect(s).toMatchObject({ total: 1, done: 1 });
	});
});