Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/voice/__tests__/native-setup-ui.test.ts

Raw
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
import type { TUI } from "@earendil-works/pi-tui";
import { describe, expect, it, vi } from "vitest";
import { runNativeSetup } from "../src/native-setup-ui.ts";

const fake = fileURLToPath(
	new URL("../__e2e__/fake-native.mjs", import.meta.url),
);
const tui = { requestRender() {} } as unknown as TUI;
const theme = {
	fg: (_color: string, value: string) => value,
	bold: (value: string) => value,
} as unknown as Theme;

function context(approved: boolean) {
	const screens: string[] = [];
	const custom = vi.fn(
		async (factory: Parameters<ExtensionContext["ui"]["custom"]>[0]) => {
			let result: boolean | undefined;
			const view = await factory(tui, theme, {} as never, (value) => {
				result = value === true;
			});
			screens.push(view.render(80).join("\n"));
			view.handleInput?.(approved ? "y" : "n");
			return result;
		},
	);
	const ctx = {
		ui: { custom, notify: vi.fn(), setWidget: vi.fn(), select: vi.fn() },
	} as unknown as ExtensionContext;
	return { ctx, screens };
}

const options = {
	command: [process.execPath, fake, "--scenario", "needs-setup"],
	preview: true,
};

type Trace = {
	direction: string;
	value: {
		method?: string;
		params?: { accepted_licenses?: string[] };
		event?: string;
		pid?: number;
		code?: number;
	};
};
async function readTrace(path: string): Promise<Trace[]> {
	return (await readFile(path, "utf8"))
		.trim()
		.split("\n")
		.map((line) => JSON.parse(line) as Trace);
}

describe("native setup UI", () => {
	it("approves setup and hands off the same inspected live process", async () => {
		const { ctx } = context(true);
		const prepared = await runNativeSetup(ctx, options);
		try {
			expect(prepared).toMatchObject({
				command: options.command,
				preview: true,
				profile: { id: "basic", installed: true },
			});
			expect(ctx.ui.custom).toHaveBeenCalledOnce();
			expect(ctx.ui.notify).toHaveBeenCalledWith(
				"Voice uses a fake test backend, not verified native speech.",
				"warning",
			);
			if (!prepared) throw new Error("Setup did not transfer its client");
			await expect(prepared.client.request("service.ping")).resolves.toEqual({
				instance: prepared.client.serviceInfo?.instance,
			});
		} finally {
			await prepared?.client.close();
		}
	});

	it.each(["needs-setup", "license", "consent"])(
		"declined or blocked %s setup neither installs nor starts audio, then exits cleanly",
		async (scenario) => {
			const root = await mkdtemp(join(tmpdir(), "pi-voice-declined-"));
			const trace = join(root, "wire.ndjson");
			try {
				const { ctx, screens } = context(false);
				await expect(
					runNativeSetup(ctx, {
						...options,
						command: [
							process.execPath,
							fake,
							"--scenario",
							scenario,
							"--wire-trace",
							trace,
						],
					}),
				).resolves.toBeUndefined();
				if (scenario === "consent")
					expect(ctx.ui.custom).not.toHaveBeenCalled();
				else expect(ctx.ui.custom).toHaveBeenCalledOnce();
				if (scenario === "license")
					expect(screens.join("\n")).toContain("Fake Model License");
				const entries = await readTrace(trace);
				const methods = entries
					.filter((entry) => entry.direction === "inbound")
					.map((entry) => entry.value.method);
				expect(methods).not.toContain("assets.install");
				expect(methods).not.toContain("resource.open");
				expect(entries).toContainEqual({
					direction: "lifecycle",
					value: { event: "exit", code: 0 },
				});
				const pid = entries.find(
					(entry) =>
						entry.direction === "lifecycle" && entry.value.event === "start",
				)?.value.pid;
				expect(pid).toBeTypeOf("number");
				if (pid === undefined) throw new Error("Fake omitted process identity");
				expect(() => process.kill(pid, 0)).toThrow();
			} finally {
				await rm(root, { recursive: true, force: true });
			}
		},
	);

	it("rejects an unavailable explicit profile before asking for consent", async () => {
		const { ctx } = context(true);
		await expect(
			runNativeSetup(ctx, { ...options, profile: "missing" }),
		).rejects.toThrow("Configured voice profile");
		expect(ctx.ui.custom).not.toHaveBeenCalled();
	});

	it("requires sound capability before consent", async () => {
		const { ctx } = context(true);
		await expect(
			runNativeSetup(ctx, {
				...options,
				command: [process.execPath, fake, "--scenario", "no-sounds"],
			}),
		).rejects.toThrow("offers no profile");
		expect(ctx.ui.custom).not.toHaveBeenCalled();
	});

	it("displays the required license before submitting exactly its approved identity", async () => {
		const root = await mkdtemp(join(tmpdir(), "pi-voice-license-"));
		const trace = join(root, "wire.ndjson");
		let prepared: Awaited<ReturnType<typeof runNativeSetup>>;
		try {
			const { ctx, screens } = context(true);
			prepared = await runNativeSetup(ctx, {
				...options,
				command: [
					process.execPath,
					fake,
					"--scenario",
					"license",
					"--wire-trace",
					trace,
				],
			});
			expect(prepared?.profile.installed).toBe(true);
			expect(screens.join("\n")).toContain("Fake Model License");
			const entries = await readTrace(trace);
			const installs = entries.filter(
				(entry) =>
					entry.direction === "inbound" &&
					entry.value.method === "assets.install",
			);
			expect(installs).toHaveLength(1);
			expect(installs[0]?.value.params?.accepted_licenses).toEqual([
				"licensed-model",
			]);
			expect(
				entries.some(
					(entry) =>
						entry.direction === "inbound" &&
						entry.value.method === "resource.open",
				),
			).toBe(false);
		} finally {
			await prepared?.client.close();
			await rm(root, { recursive: true, force: true });
		}
	});
});