Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/voice/src/native-setup-ui.ts

Raw
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
import { type KeyId, truncateToWidth } from "@earendil-works/pi-tui";
import { approveNativeSetup } from "./native-setup-approval.ts";
import { SpeakClient } from "./speak-client.ts";
import type { Plan, Profile } from "./speak-protocol.ts";
import { type PreparedSpeech, supportsSpeechProfile } from "./speech-events.ts";

export type NativeSetupUiOptions = Readonly<{
	command: readonly string[];
	profile?: string;
	preview: boolean;
	signal?: AbortSignal;
	cancelShortcut?: KeyId;
}>;

/** Inspect, approve and prepare native-owned speech assets without extension writes. */
export async function runNativeSetup(
	ctx: ExtensionContext,
	options: NativeSetupUiOptions,
): Promise<PreparedSpeech | undefined> {
	if (options.command.length === 0 || options.command.some((part) => !part))
		throw new Error("Voice command requires nonempty executable arguments.");
	const client = new SpeakClient(options.command);
	let transferred = false;
	let operation: string | undefined;
	const abort = async () => {
		if (operation) {
			try {
				await client.request("operation.cancel", { operation });
			} catch {
				// Closing fences an operation whose control path is unavailable.
			}
		}
		await client.close();
	};
	const onAbort = () => void abort();
	options.signal?.addEventListener("abort", onAbort, { once: true });
	try {
		options.signal?.throwIfAborted();
		setupWidget(ctx, "Inspecting speech service…", options.cancelShortcut);
		const info = await client.start();
		if (info.io_mode === "fake")
			ctx.ui.notify(
				"Voice uses a fake test backend, not verified native speech.",
				"warning",
			);
		const profile = await selectProfile(
			ctx,
			info.profiles,
			options.profile,
			options.preview,
		);
		options.signal?.throwIfAborted();
		const result = await client.request<{ plan: Plan }>("assets.plan", {
			profile: profile.id,
		});
		const plan = result.plan;
		if (!plan || plan.profile !== profile.id)
			throw new Error("Speech service returned an invalid asset plan.");
		if (plan.blockers.length > 0) {
			ctx.ui.notify(
				`Voice setup unavailable: ${plan.blockers[0] ?? "unknown blocker"}`,
				"warning",
			);
			return undefined;
		}
		if (!plan.ready || plan.writes_required) {
			const requiredLicenses = plan.items.filter(
				(item) => item.license.acceptance_required,
			);
			setupWidget(ctx, "Review speech assets…", options.cancelShortcut);
			const approved = await approveNativeSetup(
				ctx,
				plan.download_bytes > 0
					? "Install speech assets?"
					: "Prepare speech assets?",
				planDetails(plan),
				options.signal,
				options.cancelShortcut,
				requiredLicenses.length > 0 ? undefined : planSummary(plan),
				requiredLicenses.length > 0
					? `accept ${requiredLicenses.map((item) => item.license.name).join(", ")}`
					: undefined,
			);
			options.signal?.throwIfAborted();
			if (!approved) return undefined;
			setupWidget(ctx, "Preparing speech assets…", options.cancelShortcut);
			const accepted = await client.request<{ operation: string }>(
				"assets.install",
				{
					plan: plan.id,
					approved: true,
					accepted_licenses: requiredLicenses.map((item) => item.id),
				},
				{
					...(options.signal ? { signal: options.signal } : {}),
					timeoutMs: 5_000,
				},
			);
			operation = accepted.operation;
			const terminal = await client.waitForOperation(operation, {
				...(options.signal ? { signal: options.signal } : {}),
				timeoutMs: 1_800_000,
			});
			operation = undefined;
			if (terminal.outcome !== "completed")
				throw new Error(
					`Speech asset installation ${terminal.outcome}: ${terminal.reason}`,
				);
		}
		options.signal?.throwIfAborted();
		const inspected = await client.request<{ profiles: Profile[] }>(
			"service.info",
		);
		const installedProfile = inspected.profiles.find(
			(candidate) => candidate.id === profile.id,
		);
		if (
			!installedProfile?.installed ||
			!supportsSpeechProfile(installedProfile, options.preview)
		)
			throw new Error("Speech service did not prepare the selected profile.");
		setupWidget(ctx, "Speech service ready", options.cancelShortcut);
		transferred = true;
		return {
			client,
			command: options.command,
			profile: installedProfile,
			preview: options.preview,
		};
	} finally {
		options.signal?.removeEventListener("abort", onAbort);
		if (!transferred) await abort();
	}
}

async function selectProfile(
	ctx: ExtensionContext,
	profiles: readonly Profile[],
	explicit: string | undefined,
	preview: boolean,
): Promise<Profile> {
	const suitable = profiles.filter((profile) =>
		supportsSpeechProfile(profile, preview),
	);
	if (explicit !== undefined) {
		const profile = suitable.find((candidate) => candidate.id === explicit);
		if (!profile)
			throw new Error(
				"Configured voice profile is unavailable or lacks duplex speech capabilities.",
			);
		return profile;
	}
	const only = suitable[0];
	if (suitable.length === 1 && only) return only;
	if (suitable.length === 0)
		throw new Error(
			"Speech service offers no profile with capture, recognition, render and synthesis.",
		);
	const selected = await ctx.ui.select(
		"Select voice profile",
		suitable.map((profile) => profile.id),
	);
	const profile = suitable.find((candidate) => candidate.id === selected);
	if (!profile) throw new Error("Voice profile selection cancelled.");
	return profile;
}

function planSummary(plan: Plan): string {
	return [
		plan.download_bytes > 0
			? `${formatBytes(plan.download_bytes)} download · ${formatBytes(plan.installed_bytes)} installed.`
			: plan.ready
				? "Already prepared · no download."
				: `Prepare ${formatBytes(plan.installed_bytes)}.`,
		`${plan.items.length} native-owned asset${plan.items.length === 1 ? "" : "s"}.`,
		...(plan.items.some((item) => item.license.acceptance_required)
			? ["License review required · open details before continuing."]
			: []),
	].join("\n");
}

function planDetails(plan: Plan): string {
	return [
		`Profile: ${plan.profile}`,
		`Download total: ${formatBytes(plan.download_bytes)}`,
		`Installed total: ${formatBytes(plan.installed_bytes)}`,
		"",
		...plan.items.flatMap((item) => [
			`${item.id} · ${item.kind} · ${item.cached ? "cached" : formatBytes(item.download_bytes)}`,
			`Destination: ${item.destination}`,
			`Source: ${item.source}`,
			`SHA-256: ${item.sha256}`,
			`License: ${item.license.name}${item.license.acceptance_required ? " · acceptance required" : ""}`,
			`License URL: ${item.license.url}`,
			"",
		]),
	].join("\n");
}

function formatBytes(bytes: number): string {
	const value = Number.isFinite(bytes) ? Math.max(0, bytes) : 0;
	const unit =
		value >= 1e9 ? "GB" : value >= 1e6 ? "MB" : value >= 1e3 ? "KB" : "B";
	const divisor =
		unit === "GB" ? 1e9 : unit === "MB" ? 1e6 : unit === "KB" ? 1e3 : 1;
	return `${(value / divisor).toFixed(unit === "B" ? 0 : 1).replace(/\.0$/u, "")} ${unit}`;
}

function setupWidget(
	ctx: ExtensionContext,
	label: string,
	cancelShortcut?: KeyId,
): void {
	ctx.ui.setWidget(
		"voice",
		(_tui, theme) => ({
			invalidate() {},
			// One column of padding on each side.
			render: (width: number) =>
				[
					truncateToWidth(
						`${theme.fg("accent", theme.bold("Voice"))}  ${label}`,
						Math.max(0, width - 2),
					),
					truncateToWidth(
						theme.fg("muted", cancelShortcut ? `${cancelShortcut} cancel` : ""),
						Math.max(0, width - 2),
					),
				].map((line) => ` ${line}`),
		}),
		{ placement: "aboveEditor" },
	);
}