Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/minimax/__tests__/contract.test.ts

Raw
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import {
	fauxAssistantMessage,
	fauxToolCall,
	InMemoryCredentialStore,
	type JsonObject,
} from "@earendil-works/pi-ai";
import type {
	ExtensionFactory,
	ExtensionUIDialogOptions,
} from "@earendil-works/pi-coding-agent";
import { SessionManager } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
	type PiSessionOptions,
} from "../../../test/fixture/create-pi-session.ts";

let fixture: PiSession | undefined;
const temporary: string[] = [];
const observed = {
	activity: [] as unknown[],
	results: [] as {
		toolName: string;
		structuredContent: unknown;
		details: unknown;
		isError: boolean;
	}[],
};
// Independent listener: the quota extension contract and codemode-visible structured output.
const observer: ExtensionFactory = (pi) => {
	pi.events.on("quota:provider-activity", (data) => {
		observed.activity.push(data);
	});
	pi.on("tool_result", (event) => {
		observed.results.push({
			toolName: event.toolName,
			structuredContent: event.structuredContent,
			details: event.details,
			isError: event.isError,
		});
	});
};
afterEach(async () => {
	await fixture?.dispose();
	fixture = undefined;
	vi.unstubAllGlobals();
	observed.activity.length = 0;
	observed.results.length = 0;
	for (const dir of temporary.splice(0))
		await rm(dir, { recursive: true, force: true });
});
async function setup(
	key: string | null = "sk-cp-fixture",
	videoApproval?: "ask" | "always",
	options: Partial<PiSessionOptions> = {},
) {
	const credentials = new InMemoryCredentialStore();
	if (key)
		await credentials.modify("minimax", async () => ({ type: "api_key", key }));
	fixture = await createPiSession({
		extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		credentials,
		userSettings: videoApproval ? { minimax: { videoApproval } } : {},
		...options,
		extensionFactories: [observer, ...(options.extensionFactories ?? [])],
		env: {
			MINIMAX_API_KEY: undefined,
			PI_MINIMAX_VIDEO_APPROVAL: undefined,
			PI_MINIMAX_REGION: undefined,
			PI_MINIMAX_DEBUG: "0",
			...options.env,
		},
	});
	expect(fixture.errors).toEqual([]);
	const runtime = fixture.session.modelRuntime;
	const image = runtime.getModelOfType("image", "minimax-media", "image-01");
	if (!image) throw new Error("Image model absent");
	return { runtime, image };
}
const jpeg = Buffer.from([255, 216, 255, 224, 0, 0]).toString("base64");
const input = { input: [{ type: "text" as const, text: "A red square" }] };

const QUOTA = "https://www.minimax.io/v1/token_plan/remains";
const remains = {
	base_resp: { status_code: 0 },
	model_remains: [
		{ model_name: "video", current_weekly_remaining_percent: 10 },
		{
			model_name: "general",
			current_interval_remaining_percent: 93,
			current_weekly_remaining_percent: 92,
		},
	],
};
const QUOTA_LINE = "M Plan left 5h 93% · wk 92%";
type Handler = (
	url: string | URL | Request,
	init?: RequestInit,
) => Response | Promise<Response>;
/** Routes the non-consuming quota read separately from consuming API requests. */
function api(handler: Handler, quota: Handler = () => Response.json(remains)) {
	return vi.fn(async (url: string | URL | Request, init?: RequestInit) =>
		String(url) === QUOTA ? quota(url, init) : handler(url, init),
	);
}
type Calls = { mock: { calls: unknown[][] } };
const apiCalls = (fetch: Calls) =>
	fetch.mock.calls.filter((c) => String(c[0]) !== QUOTA) as [
		string | URL | Request,
		RequestInit | undefined,
	][];
const quotaCalls = (fetch: Calls) =>
	fetch.mock.calls.filter((c) => String(c[0]) === QUOTA) as [
		string,
		RequestInit | undefined,
	][];
const posts = (fetch: Calls) =>
	apiCalls(fetch).filter((c) => c[1]?.method === "POST");
function textOf(value: { content: { type: string; text?: string }[] }) {
	return value.content.map((b) => (b.type === "text" ? b.text : "")).join("");
}
function lastStructured(toolName: string) {
	return observed.results.filter((r) => r.toolName === toolName).at(-1);
}
function useUI(select: (...args: never[]) => Promise<string | undefined>) {
	const runner = fixture!.session.extensionRunner;
	const confirm = vi.fn(async () => true);
	runner.setUIContext(
		{
			...runner.createCommandContext().ui,
			select: select as never,
			confirm,
		},
		"tui",
	);
	return { runner, confirm };
}

describe("MiniMax native image slice", () => {
	it.each([null, "ambiguous", "sk-api-payg", "sk-cp-fixture"])(
		"keeps unrelated model discovery usable with MiniMax credential %s",
		async (key) => {
			const { runtime } = await setup(key);
			const fetch = vi.fn();
			vi.stubGlobal("fetch", fetch);
			const images = await runtime.getAvailableOfType("image");
			expect(images.some((model) => model.provider === "minimax-media")).toBe(
				key === "sk-cp-fixture",
			);
			await expect(
				runtime.getAvailableOfType("classifier"),
			).resolves.toBeDefined();
			await expect(runtime.getAvailable()).resolves.toBeDefined();
			expect(fetch).not.toHaveBeenCalled();
		},
	);

	it("retains valid partial images and their estimate when another image is malformed", async () => {
		const { runtime, image } = await setup();
		const fetch = api(async () =>
			Response.json({
				data: { image_base64: [jpeg, "not-an-image"] },
			}),
		);
		const value = await runtime.generateImages(image, input, {
			fetch,
			...{ n: 2 },
		});
		expect(value.stopReason).toBe("error");
		expect(value.output.filter((block) => block.type === "image")).toHaveLength(
			1,
		);
		expect(value.usage?.cost).toMatchObject({
			total: 0.0035,
			totalFromProvider: false,
		});
		const provenance = JSON.parse(
			value.output.find((block) => block.type === "text")?.text ?? "{}",
		);
		expect(provenance).toMatchObject({
			actualImages: 1,
			requestedImages: 2,
			partial: true,
			accounting: {
				remainingConsumption: "unknown",
				providerCharge: "unknown",
			},
		});
		expect(apiCalls(fetch)).toHaveLength(1);
	});

	it("reuses ONLY existing minimax credentials, preserves chat, returns native usage, quota and activity event", async () => {
		const { runtime, image } = await setup();
		const before = runtime.getModels("minimax").map((m) => [m.id, m.api]);
		expect(before.length).toBeGreaterThan(0);
		const fetch = api(
			async (url: string | URL | Request, init?: RequestInit) => {
				expect(String(url)).toBe("https://api.minimax.io/v1/image_generation");
				expect(new Headers(init?.headers).get("Authorization")).toBe(
					"Bearer sk-cp-fixture",
				);
				expect(JSON.parse(String(init?.body))).toMatchObject({
					model: "image-01",
					response_format: "base64",
					n: 1,
					width: 512,
					height: 512,
				});
				return Response.json({
					id: "fixture",
					data: { image_base64: [jpeg] },
					base_resp: { status_code: 0 },
				});
			},
		);
		const result = await runtime.generateImages(image, input, { fetch });
		expect(result.stopReason, result.errorMessage).toBe("stop");
		expect(result.output[0]).toEqual({
			type: "image",
			data: jpeg,
			mimeType: "image/jpeg",
		});
		expect(result.usage?.cost.total).toBe(0.0035);
		const provenance = JSON.parse(
			result.output.find((b) => b.type === "text")?.text ?? "{}",
		);
		expect(provenance.accounting).toMatchObject({
			kind: "catalog-estimate",
			unit: "image",
			tokens: "not reported",
			providerCharge: "unknown",
			creditsConsumed: "unknown",
		});
		expect(provenance.quota).toMatchObject({
			fiveHourLeft: 93,
			weeklyLeft: 92,
			observedAt: expect.any(Number),
		});
		expect(runtime.getModels("minimax").map((m) => [m.id, m.api])).toEqual(
			before,
		);
		expect(await runtime.getAuth("minimax-media")).toMatchObject({
			auth: { apiKey: ["sk", "cp", "fixture"].join("-") },
		});
		expect(apiCalls(fetch)).toHaveLength(1);
		const [[, quotaInit] = []] = quotaCalls(fetch);
		expect(quotaInit).toMatchObject({ method: "GET", redirect: "error" });
		expect(new Headers(quotaInit?.headers).get("Authorization")).toBe(
			"Bearer sk-cp-fixture",
		);
		expect(quotaInit?.body).toBeUndefined();
		expect(observed.activity).toEqual([{ provider: "minimax" }]);
	});
	it.each([
		["HTTP 500", () => new Response("boom", { status: 500 })],
		[
			"network failure",
			() => {
				throw new Error("offline");
			},
		],
		["malformed body", () => new Response("not json")],
	] as const)(
		"quota %s never fails image generation and still emits activity",
		async (_name, quota) => {
			const { runtime, image } = await setup();
			const fetch = api(
				() => Response.json({ data: { image_base64: [jpeg] } }),
				quota,
			);
			const value = await runtime.generateImages(image, input, { fetch });
			expect(value.stopReason).toBe("stop");
			const provenance = JSON.parse(
				value.output.find((b) => b.type === "text")?.text ?? "{}",
			);
			expect(provenance.quota).toBeUndefined();
			expect(quotaCalls(fetch)).toHaveLength(1);
			expect(observed.activity).toEqual([{ provider: "minimax" }]);
		},
	);
	it.each(["missing", "ambiguous", "sk-api-payg"])(
		"rejects %s credentials without generation",
		async (key) => {
			const { runtime, image } = await setup(key === "missing" ? null : key);
			const fetch = vi.fn();
			const result = await runtime.generateImages(image, input, { fetch });
			expect(result.stopReason).toBe("error");
			expect(result.usage).toBeUndefined();
			expect(fetch).not.toHaveBeenCalled();
			expect(observed.activity).toEqual([]);
		},
	);
	it("rejects agent approval metadata as an unsupported option", async () => {
		const { runtime, image } = await setup();
		const fetch = vi.fn();
		const result = await runtime.generateImages(image, input, {
			fetch,
			metadata: { approve: true },
		});
		expect(result.stopReason).toBe("error");
		expect(fetch).not.toHaveBeenCalled();
	});
	it("settles cancellation while the execution credential lookup remains pending", async () => {
		const { runtime, image } = await setup();
		const registry =
			fixture!.session.extensionRunner.createCommandContext().modelRegistry;
		const auth = await registry.getProviderAuth("minimax");
		const resolving = vi
			.spyOn(registry, "getProviderAuth")
			.mockResolvedValueOnce(auth)
			.mockImplementation(() => new Promise(() => {}));
		const controller = new AbortController();
		const fetch = vi.fn();
		const pending = runtime.generateImages(image, input, {
			fetch,
			signal: controller.signal,
		});
		await vi.waitFor(() =>
			expect(resolving.mock.calls.length).toBeGreaterThanOrEqual(2),
		);
		controller.abort();
		expect((await pending).stopReason).toBe("aborted");
		expect(fetch).not.toHaveBeenCalled();
	});

	it("propagates cancellation to HTTP without retry", async () => {
		const { runtime, image } = await setup();
		const controller = new AbortController();
		let requestSignal: AbortSignal | undefined;
		const fetch = vi.fn(
			async (_url: string | URL | Request, init?: RequestInit) => {
				requestSignal = init?.signal ?? undefined;
				controller.abort();
				throw new Error("aborted");
			},
		);
		const result = await runtime.generateImages(image, input, {
			fetch,
			signal: controller.signal,
		});
		expect(requestSignal?.aborted).toBe(true);
		expect(result.stopReason).toBe("aborted");
		expect(fetch).toHaveBeenCalledOnce();
	});
	it("rejects references and malformed replies; partial count uses actual images", async () => {
		const { runtime, image } = await setup();
		const fetch = api(async () =>
			Response.json({ data: { image_base64: [jpeg] } }),
		);
		const invalid = await runtime.generateImages(
			image,
			{ input: [{ type: "image", data: jpeg, mimeType: "image/jpeg" }] },
			{ fetch },
		);
		expect(invalid.stopReason).toBe("error");
		expect(fetch).not.toHaveBeenCalled();
		const result = await runtime.generateImages(image, input, {
			fetch,
			...{ n: 2 },
		});
		expect(result.usage?.cost.total).toBe(0.0035);
		expect(
			result.output.some(
				(b) => b.type === "text" && b.text.includes('"partial":true'),
			),
		).toBe(true);
		const malformed = await runtime.generateImages(image, input, {
			fetch: api(async () =>
				Response.json({
					data: { image_urls: ["http://private.invalid/?secret=signed"] },
				}),
			),
		});
		expect(malformed.stopReason).toBe("error");
		expect(malformed.usage).toBeUndefined();
	});
});

async function invoke(name: string, args: JsonObject) {
	if (!fixture) throw new Error("Fixture unavailable");
	fixture.setResponses([
		fauxAssistantMessage(fauxToolCall(name, args), { stopReason: "toolUse" }),
		fauxAssistantMessage("Done"),
	]);
	await fixture.session.prompt("Exercise fixture tool");
	const messages = fixture.session.messages.filter(
		(m) => m.role === "toolResult" && m.toolName === name,
	);
	const value = messages.at(-1);
	if (value?.role !== "toolResult")
		throw new Error("Missing native tool result");
	return value;
}
describe("MiniMax cheap operations need no approval", () => {
	it("runs image, understanding and speech noninteractively without any setting, and never opens a dialog with UI", async () => {
		const { runtime, image } = await setup();
		const fetch = api(async (url) => {
			const path = new URL(String(url)).pathname;
			if (path === "/v1/image_generation")
				return Response.json({ data: { image_base64: [jpeg] } });
			if (path === "/v1/coding_plan/vlm")
				return Response.json({ content: "red" });
			return Response.json({
				data: { audio: "494433", status: 2 },
				extra_info: { usage_characters: 2 },
			});
		});
		vi.stubGlobal("fetch", fetch);
		const source = join(fixture!.cwd, "input.jpg");
		await writeFile(source, Buffer.from(jpeg, "base64"));
		const run = async (suffix: string) => {
			expect(
				(await runtime.generateImages(image, input, { fetch })).stopReason,
			).toBe("stop");
			expect(
				(await invoke("minimax_understand_image", { prompt: "Color?", source }))
					.isError,
			).toBe(false);
			expect(
				(
					await invoke("minimax_speech", {
						text: "Hi",
						outputPath: join(fixture!.cwd, `hi-${suffix}.mp3`),
					})
				).isError,
			).toBe(false);
		};
		await run("headless");
		const select = vi.fn(async () => "Submit once");
		const { runner, confirm } = useUI(select);
		await runner.emit({ type: "session_start", reason: "reload" });
		await run("ui");
		expect(select).not.toHaveBeenCalled();
		expect(confirm).not.toHaveBeenCalled();
		expect(apiCalls(fetch)).toHaveLength(6);
		expect(observed.activity).toHaveLength(6);
	});
});
describe("MiniMax speech artifact", () => {
	it("returns caller-owned MP3, concise text, native estimate using reported chars, quota and structured content", async () => {
		await setup();
		const path = join(fixture!.cwd, "speech.mp3");
		const fetch = api(
			async (url: string | URL | Request, init?: RequestInit) => {
				expect(String(url)).toBe("https://api.minimax.io/v1/t2a_v2");
				expect(JSON.parse(String(init?.body))).toMatchObject({
					model: "speech-2.8-turbo",
					output_format: "hex",
					stream: false,
				});
				return Response.json({
					data: { audio: "494433", status: 2 },
					extra_info: { usage_characters: 6, audio_length: 972 },
					base_resp: { status_code: 0 },
				});
			},
		);
		vi.stubGlobal("fetch", fetch);
		const value = await invoke("minimax_speech", {
			text: "Hello.",
			outputPath: path,
		});
		expect(value.isError).toBe(false);
		expect(await readFile(path)).toEqual(Buffer.from("ID3"));
		expect(value.usage?.cost.total).toBeCloseTo(0.00036);
		expect(textOf(value)).toBe(
			`Saved MP3 → ${path} · 6 chars · est $0.00036 · ${QUOTA_LINE}`,
		);
		expect(value.details).toMatchObject({
			artifact: { path, format: "mp3" },
			providerMeasurements: { usage_characters: 6, audio_length: 972 },
			encodedDuration: "not measured",
			quota: { fiveHourLeft: 93, weeklyLeft: 92 },
		});
		expect(lastStructured("minimax_speech")?.structuredContent).toEqual(
			value.details,
		);
		expect(observed.activity).toEqual([{ provider: "minimax" }]);
		const duplicate = await invoke("minimax_speech", {
			text: "Hello.",
			outputPath: path,
		});
		expect(duplicate.isError).toBe(true);
		expect(lastStructured("minimax_speech")).toMatchObject({
			isError: true,
			structuredContent: { error: expect.stringContaining("already exists") },
		});
		expect(apiCalls(fetch)).toHaveLength(1);
		expect(observed.activity).toHaveLength(1);
	});
	it("does not turn missing character usage into free speech", async () => {
		await setup();
		vi.stubGlobal(
			"fetch",
			api(async () => Response.json({ data: { audio: "494433", status: 2 } })),
		);
		const value = await invoke("minimax_speech", {
			text: "Hi",
			outputPath: join(fixture!.cwd, "unknown.mp3"),
		});
		expect(value.isError).toBe(false);
		expect(value.usage).toBeUndefined();
		expect(textOf(value)).toContain("est unknown");
		expect(value.details).toMatchObject({
			accounting: { kind: "unknown", providerCharge: "unknown" },
		});
	});
});
describe("MiniMax explicit understanding", () => {
	it("returns answer text plus one meta line, labeled estimate, quota and structured answer", async () => {
		await setup();
		const source = join(fixture!.cwd, "input.jpg");
		await writeFile(source, Buffer.from(jpeg, "base64"));
		const fetch = api(
			async (url: string | URL | Request, init?: RequestInit) => {
				expect(String(url)).toBe("https://api.minimax.io/v1/coding_plan/vlm");
				expect(JSON.parse(String(init?.body))).toEqual({
					prompt: "Name color",
					image_url: `data:image/jpeg;base64,${jpeg}`,
				});
				return Response.json({ content: "red", base_resp: { status_code: 0 } });
			},
		);
		vi.stubGlobal("fetch", fetch);
		const value = await invoke("minimax_understand_image", {
			prompt: "Name color",
			source,
		});
		expect(value.isError).toBe(false);
		expect(textOf(value)).toBe(
			`red\n\nMiniMax vlm · est $0.01 · ${QUOTA_LINE}`,
		);
		expect(value.usage?.cost).toMatchObject({
			total: 0.01,
			totalFromProvider: false,
		});
		expect(value.details).toMatchObject({
			answer: "red",
			accounting: {
				kind: "catalog-estimate",
				unit: "request",
				providerCharge: "unknown",
				tokens: "not reported",
			},
		});
		expect(
			lastStructured("minimax_understand_image")?.structuredContent,
		).toEqual(value.details);
		expect(apiCalls(fetch)).toHaveLength(1);
		expect(observed.activity).toEqual([{ provider: "minimax" }]);
	});
	it("keeps the answer when the quota read fails", async () => {
		await setup();
		const source = join(fixture!.cwd, "input.jpg");
		await writeFile(source, Buffer.from(jpeg, "base64"));
		vi.stubGlobal(
			"fetch",
			api(
				() => Response.json({ content: "blue" }),
				() => new Response(null, { status: 302, headers: { location: "/x" } }),
			),
		);
		const value = await invoke("minimax_understand_image", {
			prompt: "Name color",
			source,
		});
		expect(value.isError).toBe(false);
		expect(textOf(value)).toBe("blue\n\nMiniMax vlm · est $0.01");
		expect(value.details).not.toHaveProperty("quota");
		expect(observed.activity).toEqual([{ provider: "minimax" }]);
	});
	it("returns structured errors without requests or activity", async () => {
		await setup();
		const fetch = vi.fn();
		vi.stubGlobal("fetch", fetch);
		const value = await invoke("minimax_understand_image", {
			prompt: "Name color",
			source: "relative.jpg",
		});
		expect(value.isError).toBe(true);
		expect(textOf(value)).toBe(
			"Image source must be absolute local path or public HTTPS URL.",
		);
		expect(lastStructured("minimax_understand_image")).toMatchObject({
			isError: true,
			structuredContent: {
				errorKind: "local-or-incompatible",
				error: "Image source must be absolute local path or public HTTPS URL.",
			},
		});
		expect(fetch).not.toHaveBeenCalled();
		expect(observed.activity).toEqual([]);
	});
});

describe("MiniMax H3 ownership and resumption", () => {
	it("persists acknowledgment before observation; native estimate appears once across polling/reload", async () => {
		await setup("sk-cp-fixture", "always");
		let polls = 0;
		const fetch = api(
			async (url: string | URL | Request, init?: RequestInit) => {
				if (init?.method === "POST") {
					expect(JSON.parse(String(init.body))).toMatchObject({
						model: "MiniMax-H3",
						duration: 4,
						resolution: "768P",
						ratio: "1:1",
						content: [{ type: "text", text: "A red ball" }],
					});
					return Response.json({ task_id: "task-owned" });
				}
				expect(String(url)).toBe(
					"https://api.minimax.io/v2/query/video_generation/task-owned",
				);
				polls++;
				return Response.json({
					task: {
						id: "task-owned",
						model: "MiniMax-H3",
						status: polls === 1 ? "running" : "succeeded",
						usage:
							polls === 1
								? {}
								: {
										output_seconds: 4,
										input_seconds: 0,
										input_image_count: 0,
										total_tokens: 130196,
										completion_tokens: 130196,
									},
						content: {
							url: "https://127.0.0.1/video.mp4?signature=do-not-expose",
						},
					},
				});
			},
		);
		vi.stubGlobal("fetch", fetch);
		const submitted = await invoke("minimax_video", {
			action: "submit",
			job: "ball",
			prompt: "A red ball",
		});
		expect(submitted.isError).toBe(false);
		expect(submitted.details).toMatchObject({
			state: "pending",
			taskId: "task-owned",
			quota: { fiveHourLeft: 93 },
		});
		expect(textOf(submitted)).toBe(
			`H3 job ball · task task-owned · pending · ${QUOTA_LINE}`,
		);
		expect(submitted.usage).toBeUndefined();
		expect(apiCalls(fetch)).toHaveLength(1);
		expect(
			fixture!.session.sessionManager
				.getEntries()
				.filter((e) => e.type === "custom")
				.at(-1),
		).toMatchObject({
			customType: "minimax.h3.job.v1",
			data: { taskId: "task-owned", job: "ball", state: "pending" },
		});
		const pending = await invoke("minimax_video", {
			action: "status",
			job: "ball",
		});
		expect(pending.details).toMatchObject({ state: "pending" });
		expect(textOf(pending)).toBe("H3 job ball · task task-owned · pending");
		expect(pending.usage).toBeUndefined();
		expect(quotaCalls(fetch)).toHaveLength(1);
		const finished = await invoke("minimax_video", {
			action: "status",
			job: "ball",
		});
		expect(finished.details).toMatchObject({
			state: "completed",
			encodedDuration: "not measured",
			providerMeasurements: { total_tokens: 130196, output_seconds: 4 },
			accounting: {
				kind: "catalog-estimate",
				unit: "provider-reported output second",
			},
			quota: { weeklyLeft: 92 },
		});
		expect(textOf(finished)).toBe(
			`H3 job ball · task task-owned · completed · est $0.32 · ${QUOTA_LINE}`,
		);
		expect(finished.usage?.cost.total).toBe(0.32);
		expect(finished.usage?.totalTokens).toBe(0);
		expect(quotaCalls(fetch)).toHaveLength(2);
		expect(observed.activity).toHaveLength(2);
		await fixture!.session.extensionRunner.emit({
			type: "session_shutdown",
			reason: "reload",
		});
		await fixture!.session.extensionRunner.emit({
			type: "session_start",
			reason: "reload",
		});
		const resumed = await invoke("minimax_video", {
			action: "status",
			job: "ball",
		});
		expect(resumed.usage).toBeUndefined();
		expect(resumed.details).toMatchObject({
			accountingDelivery: "already emitted; not recounted",
		});
		// Repeat observations must not present the estimate as a fresh charge.
		expect(textOf(resumed)).toBe(
			"H3 job ball · task task-owned · completed · counted earlier",
		);
		expect(quotaCalls(fetch)).toHaveLength(2);
		const duplicate = await invoke("minimax_video", {
			action: "submit",
			job: "ball",
			prompt: "A red ball",
		});
		expect(duplicate.details).toMatchObject({ taskId: "task-owned" });
		expect(posts(fetch)).toHaveLength(1);
		const before = fetch.mock.calls.length;
		const stranger = await invoke("minimax_video", {
			action: "status",
			job: "unowned",
		});
		expect(stranger.isError).toBe(true);
		expect(fetch).toHaveBeenCalledTimes(before);
		const listed = await invoke("minimax_video", { action: "list" });
		expect(textOf(listed)).toBe("H3 job ball · task task-owned · completed");
		expect(lastStructured("minimax_video")?.structuredContent).toMatchObject({
			jobs: [{ job: "ball", state: "completed" }],
			networkRequests: 0,
		});
		const retrieved = await invoke("minimax_video", {
			action: "retrieve",
			job: "ball",
			outputPath: join(fixture!.cwd, "output.mp4"),
		});
		expect(retrieved.isError).toBe(true);
		expect(retrieved.usage).toBeUndefined();
		expect(JSON.stringify(retrieved)).not.toContain("do-not-expose");
		expect(JSON.stringify(retrieved)).not.toContain("127.0.0.1");
	});
	it("records unknown submit outcome; same job never resubmits", async () => {
		await setup("sk-cp-fixture", "always");
		const fetch = vi.fn(async () => {
			throw new Error("network interrupted");
		});
		vi.stubGlobal("fetch", fetch);
		const lost = await invoke("minimax_video", {
			action: "submit",
			job: "lost",
			prompt: "A ball",
		});
		expect(lost.isError).toBe(true);
		expect(lost.details).toMatchObject({ state: "unknown", job: "lost" });
		expect(lastStructured("minimax_video")?.structuredContent).toMatchObject({
			state: "unknown",
			job: "lost",
		});
		await invoke("minimax_video", {
			action: "submit",
			job: "lost",
			prompt: "A ball",
		});
		const observedJob = await invoke("minimax_video", {
			action: "status",
			job: "lost",
		});
		expect(observedJob.details).toMatchObject({ state: "unknown" });
		expect(fetch).toHaveBeenCalledOnce();
		expect(observed.activity).toEqual([]);
	});
	it.each(["cancelled", "deleted"])(
		"reports upstream %s instead of inventing cancellation/refund",
		async (action) => {
			await setup("sk-cp-fixture", "always");
			const fetch = api(
				async (_url: string | URL | Request, init?: RequestInit) => {
					return Response.json(
						init?.method === "POST"
							? { task_id: "task-cancel" }
							: init?.method === "DELETE"
								? { task_id: "task-cancel", action, status: action }
								: {
										task: {
											id: "task-cancel",
											model: "MiniMax-H3",
											status: "queued",
											usage: {},
										},
									},
					);
				},
			);
			vi.stubGlobal("fetch", fetch);
			await invoke("minimax_video", {
				action: "submit",
				job: "cancel",
				prompt: "A ball",
			});
			const cancelled = await invoke("minimax_video", {
				action: "cancel",
				job: "cancel",
			});
			expect(cancelled.details).toMatchObject({
				state: action,
				upstreamAction: action,
			});
			expect(textOf(cancelled)).toBe(
				`H3 job cancel · task task-cancel · ${action} · upstream action; no refund claim.`,
			);
			expect(cancelled.usage).toBeUndefined();
			if (action === "deleted")
				expect(cancelled.details).toMatchObject({
					accounting: { kind: "unknown" },
				});
			expect(
				apiCalls(fetch).filter((c) => c[1]?.method === "DELETE"),
			).toHaveLength(1);
		},
	);
});

describe("MiniMax local discovery", () => {
	it("reports tiered spending, conditional unavailable and unverified tier without any HTTP", async () => {
		await setup();
		const fetch = vi.fn();
		vi.stubGlobal("fetch", fetch);
		const value = await invoke("minimax_capabilities", {});
		expect(value.isError).toBe(false);
		expect(fetch).not.toHaveBeenCalled();
		expect(value.details).toMatchObject({
			networkRequests: 0,
			accountTier: "unknown",
			credential: { state: "subscription-key-prefix" },
			spending: {
				image: "no-approval",
				understanding: "no-approval",
				speech: "no-approval",
				video: "blocked-noninteractive-until-videoApproval-always",
			},
			videoApproval: { source: "default", value: "ask" },
			conditional: expect.arrayContaining([
				{
					operation: "transcription",
					state: "unavailable-unverified",
					reason: expect.any(String),
				},
			]),
		});
		expect(textOf(value)).not.toContain("{");
		expect(textOf(value)).toContain("Purchased Credits");
		expect(lastStructured("minimax_capabilities")?.structuredContent).toEqual(
			value.details,
		);
		expect(JSON.stringify(value)).not.toContain("sk-cp-fixture");
		expect(observed.activity).toEqual([]);
	});
	it("reports CN unavailable without probe", async () => {
		await setup("sk-cp-fixture", "always");
		process.env["PI_MINIMAX_REGION"] = "cn";
		const fetch = vi.fn();
		vi.stubGlobal("fetch", fetch);
		const value = await invoke("minimax_capabilities", {});
		expect(value.details).toMatchObject({
			region: "cn",
			core: expect.arrayContaining([
				expect.objectContaining({
					availability: "blocked",
					blocker: "CN media routes not established",
				}),
			]),
		});
		const image = fixture!.session.modelRuntime.getModelOfType(
			"image",
			"minimax-media",
			"image-01",
		)!;
		const generated = await fixture!.session.modelRuntime.generateImages(
			image,
			input,
			{ fetch },
		);
		expect(generated.stopReason).toBe("error");
		expect(fetch).not.toHaveBeenCalled();
	});
});

function stubH3() {
	let acknowledged = 0;
	const fetch = api(async (_url, init) =>
		Response.json(
			init?.method === "POST" ? { task_id: `task-${++acknowledged}` } : {},
		),
	);
	vi.stubGlobal("fetch", fetch);
	return fetch;
}
const submit = (job: string, extra: JsonObject = {}) =>
	invoke("minimax_video", {
		action: "submit",
		job,
		prompt: "A ball",
		...extra,
	});
const jobEntries = (job: string) =>
	fixture!.session.sessionManager
		.getEntries()
		.filter(
			(e) =>
				e.type === "custom" &&
				e.customType === "minimax.h3.job.v1" &&
				(e.data as { job?: string }).job === job,
		);

describe("MiniMax tiered H3 approval", () => {
	it("blocks noninteractive H3 submit by default with an actionable error and zero requests", async () => {
		await setup();
		const fetch = stubH3();
		const value = await submit("headless");
		expect(value.isError).toBe(true);
		expect(textOf(value)).toContain("minimax.videoApproval");
		expect(textOf(value)).toContain("PI_MINIMAX_VIDEO_APPROVAL=always");
		expect(fetch).not.toHaveBeenCalled();
		expect(jobEntries("headless")).toEqual([]);
		expect(observed.activity).toEqual([]);
	});
	it.each([
		["always", undefined, true],
		["ask", "always", false],
		["invalid", "always", false],
	] as const)(
		"env %s overrides USER %s without fallthrough",
		async (env, user, allowed) => {
			await setup("sk-cp-fixture", user, {
				env: { PI_MINIMAX_VIDEO_APPROVAL: env },
			});
			const fetch = stubH3();
			const value = await submit("env");
			expect(value.isError).toBe(!allowed);
			expect(posts(fetch)).toHaveLength(allowed ? 1 : 0);
		},
	);
	it.each([
		[undefined, "always", false],
		["always", "ask", true],
	] as const)(
		"trusted project %s never authorizes or revokes USER %s",
		async (user, project, allowed) => {
			await setup("sk-cp-fixture", user, { projectTrusted: true });
			await mkdir(join(fixture!.cwd, ".pi"), { recursive: true });
			await writeFile(
				join(fixture!.cwd, ".pi", "settings.json"),
				JSON.stringify({ minimax: { videoApproval: project } }),
			);
			const fetch = stubH3();
			const value = await submit("project");
			expect(value.isError).toBe(!allowed);
			expect(posts(fetch)).toHaveLength(allowed ? 1 : 0);
		},
	);
	it.each([true, false])(
		"region obeys trusted project only: trust %s",
		async (trusted) => {
			const { runtime, image } = await setup("sk-cp-fixture", undefined, {
				projectTrusted: trusted,
			});
			await mkdir(join(fixture!.cwd, ".pi"), { recursive: true });
			await writeFile(
				join(fixture!.cwd, ".pi", "settings.json"),
				JSON.stringify({ minimax: { region: "cn" } }),
			);
			const fetch = api(async () =>
				Response.json({ data: { image_base64: [jpeg] } }),
			);
			const value = await runtime.generateImages(image, input, { fetch });
			expect(value.stopReason).toBe(trusted ? "error" : "stop");
			expect(apiCalls(fetch)).toHaveLength(trusted ? 0 : 1);
		},
	);
	it("asks with cost disclosure; once, session allowance, cancel and dismissal behave exactly", async () => {
		await setup();
		const answers: (string | undefined)[] = [
			"Submit once",
			"Allow H3 for this session",
			"Cancel",
			undefined,
		];
		const select = vi.fn(
			async (
				_title: string,
				_options: string[],
				_opts?: ExtensionUIDialogOptions,
			) => answers.shift(),
		);
		const { runner, confirm } = useUI(select);
		await runner.emit({ type: "session_start", reason: "reload" });
		const fetch = stubH3();

		expect(
			(await submit("once", { duration: 6, resolution: "2K" })).isError,
		).toBe(false);
		expect(select).toHaveBeenCalledTimes(1);
		const [title, options, opts] = select.mock.calls[0]!;
		expect(title).toContain("6s at 2K");
		expect(title).toContain("$0.78");
		expect(title).toContain("0.08 USD/s at 768P");
		expect(title).toContain("0.13 USD/s at 2K");
		expect(title).toMatch(/weekly-only/);
		expect(title).toMatch(/Go plan lacks H3/);
		expect(title).toMatch(/Credits/);
		expect(options).toEqual([
			"Submit once",
			"Allow H3 for this session",
			"Cancel",
		]);
		expect(opts?.signal).toBeInstanceOf(AbortSignal);

		expect((await submit("session-1")).isError).toBe(false);
		expect(select).toHaveBeenCalledTimes(2);
		expect((await submit("session-2")).isError).toBe(false);
		expect(select).toHaveBeenCalledTimes(2);
		expect(posts(fetch)).toHaveLength(3);

		// A new session_start forgets the allowance.
		await runner.emit({ type: "session_start", reason: "reload" });
		const before = fetch.mock.calls.length;
		const cancelled = await submit("cancelled");
		expect(cancelled.isError).toBe(true);
		expect(textOf(cancelled)).toContain("declined");
		const dismissed = await submit("dismissed");
		expect(dismissed.isError).toBe(true);
		expect(select).toHaveBeenCalledTimes(4);
		expect(fetch).toHaveBeenCalledTimes(before);
		expect(jobEntries("cancelled")).toEqual([]);
		expect(jobEntries("dismissed")).toEqual([]);
		expect(confirm).not.toHaveBeenCalled();
	});
	it("abort while the select dialog is open sends nothing", async () => {
		await setup();
		let dialogSignal: AbortSignal | undefined;
		const select = vi.fn(
			async (_t: string, _o: string[], opts?: ExtensionUIDialogOptions) =>
				new Promise<string | undefined>((resolve) => {
					dialogSignal = opts?.signal;
					opts?.signal?.addEventListener("abort", () => resolve(undefined), {
						once: true,
					});
					void fixture!.session.abort();
				}),
		);
		const { runner } = useUI(select);
		await runner.emit({ type: "session_start", reason: "reload" });
		const fetch = stubH3();
		fixture!.setResponses([
			fauxAssistantMessage(
				fauxToolCall("minimax_video", {
					action: "submit",
					job: "aborted",
					prompt: "A ball",
				}),
				{ stopReason: "toolUse" },
			),
			fauxAssistantMessage("Done"),
		]);
		await fixture!.session.prompt("Abort during dialog");
		expect(select).toHaveBeenCalledOnce();
		expect(dialogSignal?.aborted).toBe(true);
		expect(fetch).not.toHaveBeenCalled();
		expect(jobEntries("aborted")).toEqual([]);
	});
	it("USER always submits without opening a dialog even when UI exists", async () => {
		await setup("sk-cp-fixture", "always");
		const select = vi.fn(async () => "Cancel");
		const { runner } = useUI(select);
		await runner.emit({ type: "session_start", reason: "reload" });
		const fetch = stubH3();
		expect((await submit("always")).isError).toBe(false);
		expect(select).not.toHaveBeenCalled();
		expect(posts(fetch)).toHaveLength(1);
	});
});
describe("MiniMax durable native accounting", () => {
	it("reopens actual persisted session with fresh extension, keeps task ownership, does not recount known value", async () => {
		const cwd = await mkdtemp(join(tmpdir(), "minimax-session-"));
		temporary.push(cwd);
		const manager = SessionManager.create(cwd, join(cwd, "sessions"));
		await setup("sk-cp-fixture", "always", { cwd, sessionManager: manager });
		const fetch = api(
			async (_url: string | URL | Request, init?: RequestInit) =>
				Response.json(
					init?.method === "POST"
						? { task_id: "persistent-task" }
						: {
								task: {
									id: "persistent-task",
									model: "MiniMax-H3",
									status: "succeeded",
									usage: {
										output_seconds: 4,
										input_seconds: 0,
										input_image_count: 0,
									},
								},
							},
				),
		);
		vi.stubGlobal("fetch", fetch);
		await invoke("minimax_video", {
			action: "submit",
			job: "persist",
			prompt: "A ball",
		});
		const intent = manager
			.getEntries()
			.find((e) => e.type === "custom" && e.customType === "minimax.h3.job.v1");
		const original = JSON.stringify(intent);
		const complete = await invoke("minimax_video", {
			action: "status",
			job: "persist",
		});
		expect(complete.usage?.cost.total).toBe(0.32);
		expect(JSON.stringify(intent)).toBe(original);
		const path = manager.getSessionFile();
		if (!path) throw new Error("Persisted fixture missing path");
		await fixture!.dispose();
		fixture = undefined;
		await setup("sk-cp-fixture", "always", {
			cwd,
			sessionManager: SessionManager.open(path),
		});
		vi.stubGlobal("fetch", fetch);
		const resumed = await invoke("minimax_video", {
			action: "status",
			job: "persist",
		});
		expect(resumed.usage).toBeUndefined();
		expect(resumed.details).toMatchObject({
			taskId: "persistent-task",
			state: "completed",
		});
		const calls = fetch.mock.calls.length;
		await fixture!.dispose();
		fixture = undefined;
		const fork = SessionManager.inMemory(cwd);
		for (const entry of manager.getEntries())
			if (entry.type === "custom")
				fork.appendCustomEntry(entry.customType, entry.data);
		await setup("sk-cp-fixture", "always", { cwd, sessionManager: fork });
		vi.stubGlobal("fetch", fetch);
		const foreign = await invoke("minimax_video", {
			action: "status",
			job: "persist",
		});
		expect(foreign.isError).toBe(true);
		expect(fetch).toHaveBeenCalledTimes(calls);
	});
});

it("nested codemode-style calls retain native usage, structured content, per-job concurrency lock, persisted dedup", async () => {
	const cwd = await mkdtemp(join(tmpdir(), "minimax-nested-"));
	temporary.push(cwd);
	const manager = SessionManager.create(cwd, join(cwd, "sessions"));
	const ready = Promise.withResolvers<void>(),
		release = Promise.withResolvers<void>();
	const bridge: ExtensionFactory = (pi) => {
		pi.registerTool({
			name: "nested_noop",
			label: "Noop",
			description: "Bounded record fixture",
			parameters: Type.Object({}),
			async execute() {
				return { content: [{ type: "text", text: "ok" }], details: {} };
			},
		});
		pi.registerTool({
			name: "nested_h3",
			label: "Nested fixture",
			description: "Fixture nested API",
			parameters: Type.Object({ job: Type.String() }),
			async execute(_id, params, _signal, _update, ctx) {
				for (let i = 0; i < 256; i++) await ctx.executeTool("nested_noop", {});
				const first = ctx.executeTool("minimax_video", {
					action: "status",
					job: params.job,
				});
				await ready.promise;
				const second = await ctx.executeTool("minimax_video", {
					action: "status",
					job: params.job,
				});
				const third = await ctx.executeTool("minimax_video", {
					action: "status",
					job: params.job,
				});
				release.resolve();
				const final = await first;
				return {
					content: final.result.content,
					details: {
						secondError: second.isError,
						thirdError: third.isError,
						completed: !final.isError,
						structured: final.result.structuredContent ?? null,
					},
				};
			},
		});
	};
	await setup("sk-cp-fixture", "always", {
		cwd,
		sessionManager: manager,
		extensionFactories: [bridge],
	});
	const fetch = api(
		async (_url: string | URL | Request, init?: RequestInit) => {
			if (init?.method === "POST")
				return Response.json({ task_id: "nested-task" });
			ready.resolve();
			await release.promise;
			return Response.json({
				task: {
					id: "nested-task",
					model: "MiniMax-H3",
					status: "succeeded",
					usage: { output_seconds: 4, input_seconds: 0, input_image_count: 0 },
				},
			});
		},
	);
	vi.stubGlobal("fetch", fetch);
	await invoke("minimax_video", {
		action: "submit",
		job: "nested",
		prompt: "A ball",
	});
	const nested = await invoke("nested_h3", { job: "nested" });
	expect(nested.isError).toBe(false);
	expect(nested.details).toMatchObject({
		secondError: true,
		thirdError: true,
		completed: true,
		structured: { job: "nested", taskId: "nested-task", state: "completed" },
	});
	expect(nested.usage?.cost.total).toBe(0.32);
	expect(nested.nestedCalls?.calls).toHaveLength(256);
	expect(nested.nestedCalls?.complete).toBe(false);
	expect(
		nested.nestedCalls?.calls.some((call) => call.name === "minimax_video"),
	).toBe(false);
	expect(apiCalls(fetch)).toHaveLength(2);
	const path = manager.getSessionFile();
	if (!path) throw new Error("Persisted nested fixture absent");
	await fixture!.dispose();
	fixture = undefined;
	await setup("sk-cp-fixture", "always", {
		cwd,
		sessionManager: SessionManager.open(path),
	});
	vi.stubGlobal("fetch", fetch);
	const again = await invoke("minimax_video", {
		action: "status",
		job: "nested",
	});
	expect(again.usage).toBeUndefined();
	expect(again.details).toMatchObject({ state: "completed" });
});
it.each([
	[401, "authentication"],
	[403, "entitlement"],
	[402, "allowance-exhausted"],
	[429, "rate-limit"],
] as const)(
	"H3 rejection HTTP %s remains distinguishable with zero retries",
	async (status, kind) => {
		await setup("sk-cp-fixture", "always");
		const fetch = vi.fn(async () => Response.json({}, { status }));
		vi.stubGlobal("fetch", fetch);
		const failed = await invoke("minimax_video", {
			action: "submit",
			job: "rejected",
			prompt: "A ball",
		});
		expect(failed.isError).toBe(true);
		expect(failed.details).toMatchObject({
			state: "failed",
			errorKind: kind,
			failureKind: kind,
		});
		expect(failed.usage).toBeUndefined();
		await invoke("minimax_video", {
			action: "submit",
			job: "rejected",
			prompt: "A ball",
		});
		expect(fetch).toHaveBeenCalledOnce();
		expect(observed.activity).toEqual([]);
	},
);