Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/quota/__tests__/contract.test.ts

Raw
import {
	mkdirSync,
	mkdtempSync,
	readdirSync,
	readFileSync,
	rmSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
	InMemoryCredentialStore,
	type OAuthCredential,
} from "@earendil-works/pi-ai";
import { initTheme } from "@earendil-works/pi-coding-agent";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";
import { codexAccountId } from "../src/providers/codex.ts";

describe("quota contract", () => {
	let session: PiSession | undefined;

	afterEach(async () => {
		vi.unstubAllGlobals();
		await session?.dispose();
		session = undefined;
	});

	it("loads in real Pi extension runtime", async () => {
		const extensionPath = fileURLToPath(
			new URL("../index.ts", import.meta.url),
		);
		session = await createPiSession({ extensionPaths: [extensionPath] });

		expect(session.extensions).toHaveLength(1);
		expect(session.extensions[0]!.path).toBe(extensionPath);
	}, 15000);

	it("writes its opt-in lifecycle trace inside the fixture sandbox", async () => {
		const root = mkdtempSync(path.join(tmpdir(), "pi-ext-quota-debug-"));
		try {
			const extensionPath = fileURLToPath(
				new URL("../index.ts", import.meta.url),
			);
			session = await createPiSession({
				cwd: root,
				extensionPaths: [extensionPath],
				env: { PI_QUOTA_DEBUG: "1" },
			});
			const runner = session.session.extensionRunner;
			await runner.emit({ type: "session_start", reason: "startup" });
			await runner.emit({ type: "session_shutdown", reason: "quit" });
			const stateHome = session.env["XDG_STATE_HOME"];
			if (!stateHome) throw new Error("missing sandbox state home");
			const directory = path.join(stateHome, "pi-ext", "debug", "quota");
			const [file] = readdirSync(directory);
			if (!file) throw new Error("missing debug file");
			const events = readFileSync(path.join(directory, file), "utf8")
				.trim()
				.split("\n")
				.map((line) => JSON.parse(line).event);
			expect(events).toEqual(
				expect.arrayContaining(["session.start", "session.shutdown"]),
			);
		} finally {
			await session?.dispose();
			session = undefined;
			rmSync(root, { recursive: true, force: true });
		}
	});

	function codexToken(accountId: string) {
		const claim = Buffer.from(
			JSON.stringify({
				"https://api.openai.com/auth": { chatgpt_account_id: accountId },
			}),
		).toString("base64url");
		return `header.${claim}.signature`;
	}

	function quotaCommandContext(
		model: string | { provider: string; api: string } = "openai-codex",
	) {
		if (!session) throw new Error("missing session");
		initTheme("default", false);
		const runner = session.session.extensionRunner;
		const ui = {
			...runner.getUIContext(),
			setStatus: vi.fn(),
			setWidget: vi.fn(),
		};
		runner.setUIContext(ui, "tui");
		const ctx = Object.create(runner.createCommandContext());
		Object.defineProperty(ctx, "model", {
			value: typeof model === "string" ? { provider: model } : model,
		});
		const command = runner.getCommand("quota");
		if (!command) throw new Error("missing /quota command");
		return { command, ctx };
	}

	function installCodexRefresh(
		refresh: (credential: OAuthCredential) => Promise<OAuthCredential>,
	) {
		if (!session) throw new Error("missing session");
		const runtime = session.session.modelRuntime;
		const provider = runtime.getProvider("openai-codex");
		if (!provider?.auth.oauth) throw new Error("missing native Codex OAuth");
		runtime.registerNativeProvider({
			...provider,
			auth: {
				...provider.auth,
				oauth: {
					...provider.auth.oauth,
					refresh: (credential, _signal) => refresh(credential),
					toAuth: async (credential) => ({ apiKey: credential.access }),
				},
			},
		});
	}

	it("does not restore the widget after dismissal while a provider fetch is pending", async () => {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("openai-codex", async () => ({
			type: "oauth",
			access: codexToken("acct-race"),
			refresh: "refresh-race",
			expires: Date.now() + 3_600_000,
		}));
		const extensionPath = fileURLToPath(
			new URL("../index.ts", import.meta.url),
		);
		session = await createPiSession({
			credentials,
			extensionPaths: [extensionPath],
		});
		let resolveFetch!: (response: Response) => void;
		const fetch = vi.fn(
			() => new Promise<Response>((resolve) => (resolveFetch = resolve)),
		);
		vi.stubGlobal("fetch", fetch);
		const { command, ctx } = quotaCommandContext();

		const opening = command.handler("", ctx);
		await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
		await command.handler("", ctx);
		resolveFetch(Response.json({ rate_limit: {} }));
		await opening;

		const widgetCalls = vi.mocked(ctx.ui.setWidget).mock.calls;
		expect(widgetCalls.at(-1)?.[1]).toBeUndefined();
		expect(session.errors).toEqual([]);
	}, 15000);

	it("keeps newest A quota through A→B→A and stale A fallback", async () => {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("openai-codex", async () => ({
			type: "oauth",
			access: codexToken("acct-aba"),
			refresh: "refresh-aba",
			expires: Date.now() + 3_600_000,
		}));
		await credentials.modify("anthropic", async () => ({
			type: "api_key",
			key: "anthropic-test-key",
		}));
		const extensionPath = fileURLToPath(
			new URL("../index.ts", import.meta.url),
		);
		session = await createPiSession({
			credentials,
			extensionPaths: [extensionPath],
		});
		const runner = session.session.extensionRunner;
		const ui = {
			...runner.getUIContext(),
			setStatus: vi.fn(),
			setWidget: vi.fn(),
		};
		runner.setUIContext(ui, "tui");
		const codex = session.session.modelRuntime.getModels("openai-codex")[0];
		const anthropic = session.session.modelRuntime.getModels("anthropic")[0];
		if (!codex || !anthropic) throw new Error("missing native quota models");
		const requests: Array<{
			resolve: (response: Response) => void;
			reject: (error: Error) => void;
		}> = [];
		vi.stubGlobal(
			"fetch",
			vi.fn(
				() =>
					new Promise<Response>((resolve, reject) =>
						requests.push({ resolve, reject }),
					),
			),
		);
		const firstA = session.session.setModel(codex);
		await vi.waitFor(() => expect(requests).toHaveLength(1));
		const opening = runner
			.getCommand("quota")
			?.handler("", runner.createCommandContext());
		if (!opening) throw new Error("missing /quota command");
		const switchingB = session.session.setModel(anthropic);
		await vi.waitFor(() => expect(requests).toHaveLength(2));
		const latestA = session.session.setModel(codex);
		await vi.waitFor(() => expect(requests).toHaveLength(3));
		requests[2]?.resolve(
			Response.json({
				rate_limit: {
					primary_window: { used_percent: 20, limit_window_seconds: 18000 },
				},
			}),
		);
		requests[0]?.resolve(
			Response.json({
				rate_limit: {
					primary_window: { used_percent: 80, limit_window_seconds: 18000 },
				},
			}),
		);
		requests[1]?.resolve(Response.json({ five_hour: { utilization: 35 } }));
		await Promise.all([firstA, switchingB, latestA, opening]);

		await runner
			.getCommand("quota")
			?.handler("", runner.createCommandContext());
		const fallback = runner
			.getCommand("quota")
			?.handler("", runner.createCommandContext());
		if (!fallback) throw new Error("missing /quota command");
		await vi.waitFor(() => expect(requests).toHaveLength(4));
		requests[3]?.reject(new Error("offline"));
		await fallback;

		expect(JSON.stringify(vi.mocked(ui.setWidget).mock.calls.at(-1))).toContain(
			"20%",
		);
		expect(session.errors).toEqual([]);
	}, 15000);

	it("keeps response-header quota when an older poll fails over", async () => {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("openai-codex", async () => ({
			type: "oauth",
			access: codexToken("acct-headers"),
			refresh: "refresh-headers",
			expires: Date.now() + 3_600_000,
		}));
		const extensionPath = fileURLToPath(
			new URL("../index.ts", import.meta.url),
		);
		session = await createPiSession({
			credentials,
			extensionPaths: [extensionPath],
		});
		const runner = session.session.extensionRunner;
		const ui = {
			...runner.getUIContext(),
			setStatus: vi.fn(),
			setWidget: vi.fn(),
		};
		runner.setUIContext(ui, "tui");
		const codex = session.session.modelRuntime.getModels("openai-codex")[0];
		if (!codex) throw new Error("missing native Codex model");
		const requests: Array<{
			resolve: (response: Response) => void;
			reject: (error: Error) => void;
		}> = [];
		vi.stubGlobal(
			"fetch",
			vi.fn(
				() =>
					new Promise<Response>((resolve, reject) =>
						requests.push({ resolve, reject }),
					),
			),
		);
		const selecting = session.session.setModel(codex);
		await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
		const opening = runner
			.getCommand("quota")
			?.handler("", runner.createCommandContext());
		if (!opening) throw new Error("missing /quota command");
		await runner.emit({
			type: "after_provider_response",
			status: 200,
			headers: { "x-codex-primary-used-percent": "42" },
		});
		requests[0]?.resolve(
			Response.json({
				rate_limit: {
					primary_window: { used_percent: 80, limit_window_seconds: 18000 },
					secondary_window: { used_percent: 12, limit_window_seconds: 604800 },
				},
				credits: { balance: "12.5" },
			}),
		);
		await Promise.all([selecting, opening]);
		await runner
			.getCommand("quota")
			?.handler("", runner.createCommandContext());
		const fallback = runner
			.getCommand("quota")
			?.handler("", runner.createCommandContext());
		if (!fallback) throw new Error("missing /quota command");
		await vi.waitFor(() => expect(requests).toHaveLength(2));
		requests[1]?.reject(new Error("offline"));
		await fallback;

		const widget = JSON.stringify(vi.mocked(ui.setWidget).mock.calls.at(-1));
		expect(widget).toContain("42%");
		expect(widget).toContain("5h");
		expect(widget).toContain("Weekly");
		expect(widget).toContain("Credits");
		expect(widget).toContain("12.5 left");
		expect(widget).not.toContain("credits left");
		expect(widget).not.toContain("80%");
		expect(session.errors).toEqual([]);
	}, 15000);

	it("retains metadata from two successive partial headers while a poll is pending", async () => {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("openai-codex", async () => ({
			type: "oauth",
			access: codexToken("synthetic-two-headers"),
			refresh: "unused",
			expires: Date.now() + 3600000,
		}));
		session = await createPiSession({
			credentials,
			extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		});
		let resolve!: (response: Response) => void;
		const fetch = vi.fn(
			() =>
				new Promise<Response>((done) => {
					resolve = done;
				}),
		);
		vi.stubGlobal("fetch", fetch);
		const runner = session.session.extensionRunner;
		const ui = {
			...runner.getUIContext(),
			setStatus: vi.fn(),
			setWidget: vi.fn(),
		};
		runner.setUIContext(ui, "tui");
		const codex = session.session.modelRuntime.getModels("openai-codex")[0]!;
		const selecting = session.session.setModel(codex);
		await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
		const opening = runner
			.getCommand("quota")!
			.handler("", runner.createCommandContext());
		await runner.emit({
			type: "after_provider_response",
			status: 200,
			headers: {
				"x-codex-primary-used-percent": "20",
				"x-codex-primary-window-minutes": "10080",
				"x-codex-primary-reset-at": String(
					Math.floor(Date.now() / 1000) + 7200,
				),
			},
		});
		await runner.emit({
			type: "after_provider_response",
			status: 200,
			headers: { "x-codex-primary-used-percent": "42" },
		});
		resolve(
			Response.json({
				rate_limit: {
					primary_window: { used_percent: 80, limit_window_seconds: 18000 },
				},
			}),
		);
		await Promise.all([selecting, opening]);
		const rows = ui.setWidget.mock.calls.at(-1)?.[1] as string[];
		expect(rows.join("\n")).toContain("Weekly");
		expect(rows.join("\n")).toContain("42%");
		expect(rows.join("\n")).toContain("resets in");
		expect(rows.join("\n")).not.toContain("5h");
		expect(session.errors).toEqual([]);
	}, 15000);

	it("keeps header-only Groq quota across refreshes that cannot poll", async () => {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("groq", async () => ({
			type: "api_key",
			key: "synthetic-key",
		}));
		session = await createPiSession({
			credentials,
			extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		});
		const runner = session.session.extensionRunner;
		const ui = {
			...runner.getUIContext(),
			setStatus: vi.fn(),
			setWidget: vi.fn(),
		};
		runner.setUIContext(ui, "tui");
		vi.stubGlobal(
			"fetch",
			vi.fn(async () => {
				throw new Error("Groq quota must not poll");
			}),
		);
		const model = session.session.modelRuntime.getModels("groq")[0];
		if (!model) throw new Error("missing native Groq model");
		await session.session.setModel(model);
		// Live chat-completion sample, 2026-10-28.
		await runner.emit({
			type: "after_provider_response",
			status: 200,
			headers: {
				"x-ratelimit-limit-requests": "1000",
				"x-ratelimit-limit-tokens": "8000",
				"x-ratelimit-remaining-requests": "999",
				"x-ratelimit-remaining-tokens": "7986",
				"x-ratelimit-reset-requests": "1m26.4s",
				"x-ratelimit-reset-tokens": "105ms",
			},
		});
		const command = runner.getCommand("quota");
		if (!command) throw new Error("missing /quota command");
		await command.handler("", runner.createCommandContext());
		const rows = JSON.stringify(vi.mocked(ui.setWidget).mock.calls.at(-1));
		expect(rows).toContain("Requests/day");
		expect(rows).toContain("1 / 1,000 used");
		expect(rows).not.toContain("resets");
		expect(rows).not.toContain("Quota unavailable");
		expect(fetch).not.toHaveBeenCalled();
		expect(session.errors).toEqual([]);
	}, 15000);

	it("renders a weekly-only Codex response-header quota in /quota", async () => {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("openai-codex", async () => ({
			type: "oauth",
			access: codexToken("acct-weekly"),
			refresh: "refresh-weekly",
			expires: Date.now() + 3_600_000,
		}));
		const extensionPath = fileURLToPath(
			new URL("../index.ts", import.meta.url),
		);
		session = await createPiSession({
			credentials,
			extensionPaths: [extensionPath],
		});
		const runner = session.session.extensionRunner;
		const ui = {
			...runner.getUIContext(),
			setStatus: vi.fn(),
			setWidget: vi.fn(),
		};
		runner.setUIContext(ui, "tui");
		vi.stubGlobal(
			"fetch",
			vi.fn(async () => Response.json({ rate_limit: {} })),
		);
		const codex = session.session.modelRuntime.getModels("openai-codex")[0];
		if (!codex) throw new Error("missing native Codex model");
		await session.session.setModel(codex);
		await runner
			.getCommand("quota")
			?.handler("", runner.createCommandContext());
		await runner.emit({
			type: "after_provider_response",
			status: 200,
			headers: {
				"x-codex-secondary-used-percent": "42",
				"x-codex-secondary-window-minutes": "10080",
			},
		});

		const widget = JSON.stringify(vi.mocked(ui.setWidget).mock.calls.at(-1));
		expect(widget).toContain("Weekly");
		expect(widget).toContain("42%");
		expect(widget).not.toContain("5h");
		expect(session.errors).toEqual([]);
	}, 15000);

	it("uses active stored Codex OAuth token, never fixture auth files", async () => {
		const credentials = new InMemoryCredentialStore();
		const token = codexToken("acct-active");
		await credentials.modify("openai-codex", async () => ({
			type: "oauth",
			access: token,
			refresh: "refresh-active",
			expires: Date.now() + 3_600_000,
		}));
		const root = mkdtempSync(path.join(tmpdir(), "pi-ext-quota-auth-"));
		try {
			const extensionPath = fileURLToPath(
				new URL("../index.ts", import.meta.url),
			);
			session = await createPiSession({
				cwd: root,
				credentials,
				extensionPaths: [extensionPath],
			});
			writeFileSync(
				path.join(session.agentDir, "auth.json"),
				JSON.stringify({
					"openai-codex": {
						type: "oauth",
						access: codexToken("acct-default"),
						refresh: "refresh-default",
						expires: Date.now() + 3_600_000,
						accountId: "acct-default",
					},
				}),
			);
			const codexHome = path.join(session.env["HOME"]!, ".codex");
			mkdirSync(codexHome, { recursive: true });
			writeFileSync(
				path.join(codexHome, "auth.json"),
				JSON.stringify({
					tokens: {
						access_token: codexToken("acct-codex"),
						account_id: "acct-codex",
					},
				}),
			);
			const fetch = vi.fn(async (_input: string | URL, _init?: RequestInit) => {
				return Response.json({ rate_limit: {} });
			});
			vi.stubGlobal("fetch", fetch);

			const { command, ctx } = quotaCommandContext();
			await command.handler("", ctx);

			expect(fetch).toHaveBeenCalledTimes(1);
			const [url, init] = fetch.mock.calls[0]!;
			expect(String(url)).toBe("https://chatgpt.com/backend-api/wham/usage");
			const headers = new Headers(init?.headers);
			expect(headers.get("Authorization")).toBe(`Bearer ${token}`);
			expect(headers.get("ChatGPT-Account-Id")).toBe("acct-active");
			expect(session.errors).toEqual([]);
		} finally {
			await session?.dispose();
			session = undefined;
			rmSync(root, { recursive: true, force: true });
		}
	}, 15000);

	it.each([
		["malformed token", "not-a-jwt"],
		["missing Codex account claim", "header.e30.signature"],
		["no OAuth credential", undefined],
	] as const)(
		"does not request Codex quota with %s",
		async (_name, access) => {
			const credentials = new InMemoryCredentialStore();
			if (access) {
				await credentials.modify("openai-codex", async () => ({
					type: "oauth",
					access,
					refresh: "refresh",
					expires: Date.now() + 3_600_000,
				}));
			}
			const extensionPath = fileURLToPath(
				new URL("../index.ts", import.meta.url),
			);
			session = await createPiSession({
				credentials,
				extensionPaths: [extensionPath],
			});
			const fetch = vi.fn(async (input: string | URL) => {
				throw new Error(`unexpected network endpoint: ${input}`);
			});
			vi.stubGlobal("fetch", fetch);

			const { command, ctx } = quotaCommandContext();
			await command.handler("", ctx);

			expect(fetch).not.toHaveBeenCalled();
			expect(session.errors).toEqual([]);
		},
		15000,
	);

	it("refreshes expired Codex OAuth before polling with refreshed account", async () => {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("openai-codex", async () => ({
			type: "oauth",
			access: codexToken("acct-old"),
			refresh: "refresh-old",
			expires: Date.now() - 1,
			account_id: "acct-old-credential",
		}));
		const extensionPath = fileURLToPath(
			new URL("../index.ts", import.meta.url),
		);
		session = await createPiSession({
			credentials,
			extensionPaths: [extensionPath],
		});
		const refreshed = codexToken("acct-refreshed");
		const refresh = vi.fn(async () => ({
			type: "oauth" as const,
			access: refreshed,
			refresh: "refresh-new",
			expires: Date.now() + 3_600_000,
			account_id: "acct-old-credential",
		}));
		installCodexRefresh(refresh);
		const fetch = vi.fn(async (_input: string | URL, _init?: RequestInit) =>
			Response.json({ rate_limit: {} }),
		);
		vi.stubGlobal("fetch", fetch);

		const { command, ctx } = quotaCommandContext();
		await command.handler("", ctx);

		expect(refresh).toHaveBeenCalledTimes(1);
		expect(fetch).toHaveBeenCalledTimes(1);
		const [url, init] = fetch.mock.calls[0]!;
		expect(String(url)).toBe("https://chatgpt.com/backend-api/wham/usage");
		const headers = new Headers(init?.headers);
		expect(headers.get("Authorization")).toBe(`Bearer ${refreshed}`);
		expect(headers.get("ChatGPT-Account-Id")).toBe("acct-refreshed");
		expect(session.errors).toEqual([]);
	}, 15000);

	it("derives Codex account identity only from the supplied token", () => {
		const encode = (value: unknown) =>
			Buffer.from(JSON.stringify(value)).toString("base64url");
		const token = `header.${encode({ "https://api.openai.com/auth": { chatgpt_account_id: "acct-session" } })}.signature`;
		expect(codexAccountId(token)).toBe("acct-session");
		expect(
			codexAccountId(
				`header.${encode({ account_id: "acct-other" })}.signature`,
			),
		).toBeUndefined();
		expect(
			codexAccountId(
				`header.${encode({ "https://api.openai.com/auth": { chatgpt_account_id: "\n" } })}.signature`,
			),
		).toBeUndefined();
		expect(codexAccountId("malformed-token")).toBeUndefined();
	});

	it.each([
		[
			"coexisting aliases and scoped limits",
			{
				five_hour: { utilization: 6 },
				seven_day: { utilization: 54 },
				limits: [
					{ kind: "session", percent: 6, is_active: false },
					{ kind: "weekly_all", percent: 54, is_active: false },
					{
						kind: "weekly_scoped",
						percent: 81,
						scope: { model: { display_name: "Fable" } },
						is_active: true,
					},
				],
			},
			3,
		],
		[
			"missing legacy windows",
			{
				limits: [
					{
						kind: "weekly_scoped",
						percent: 81,
						scope: { model: { display_name: "Fable" } },
						is_active: false,
					},
				],
			},
			1,
		],
	] as const)(
		"renders Anthropic %s through registered /quota",
		async (_name, response, bucketCount) => {
			const credentials = new InMemoryCredentialStore();
			await credentials.modify("anthropic", async () => ({
				type: "api_key",
				key: "synthetic-key",
			}));
			session = await createPiSession({
				credentials,
				extensionPaths: [
					fileURLToPath(new URL("../index.ts", import.meta.url)),
				],
			});
			const fetch = vi.fn(async (_input: string | URL) =>
				Response.json(response),
			);
			vi.stubGlobal("fetch", fetch);
			const { command, ctx } = quotaCommandContext("anthropic");
			await command.handler("", ctx);
			expect(String(fetch.mock.calls[0]?.[0] ?? "")).toBe(
				"https://api.anthropic.com/api/oauth/usage",
			);
			const rows = vi
				.mocked(ctx.ui.setWidget)
				.mock.calls.at(-1)?.[1] as string[];
			expect(rows.filter((line) => line.includes(" used"))).toHaveLength(
				bucketCount,
			);
			expect(rows.join("\n")).toContain("Fable");
			expect(rows.join("\n")).toContain("81%");
			expect(rows.join("\n")).not.toMatch(/[^0-9]0%/);
			expect(session.errors).toEqual([]);
		},
		15000,
	);

	it("shows current M Plan percentages and the binding shared window through /quota", async () => {
		const credentials = new InMemoryCredentialStore();
		const key = "sk-cp-synthetic-quota-key";
		await credentials.modify("minimax", async () => ({
			type: "api_key",
			key,
		}));
		session = await createPiSession({
			credentials,
			extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		});
		// Reduced live M Plan shape (2026-11-09), with synthetic reset times.
		const fetch = vi.fn(async (_input: string | URL, _init?: RequestInit) =>
			Response.json({
				model_remains: [
					{
						model_name: "general",
						current_interval_total_count: 0,
						current_interval_usage_count: 0,
						current_interval_remaining_percent: 99,
						end_time: Date.now() + 18000000,
						current_weekly_total_count: 0,
						current_weekly_usage_count: 0,
						current_weekly_remaining_percent: 97,
						weekly_end_time: Date.now() + 604800000,
					},
				],
				base_resp: { status_code: 0, status_msg: "success" },
			}),
		);
		vi.stubGlobal("fetch", fetch);
		const { command, ctx } = quotaCommandContext("minimax");
		await command.handler("", ctx);

		expect(fetch).toHaveBeenCalledTimes(1);
		const [url, init] = fetch.mock.calls[0]!;
		expect(String(url)).toBe("https://www.minimax.io/v1/token_plan/remains");
		expect(new Headers(init?.headers).get("Authorization")).toBe(
			`Bearer ${key}`,
		);
		expect(init?.redirect).toBe("error");
		const rows = vi.mocked(ctx.ui.setWidget).mock.calls.at(-1)?.[1] as string[];
		expect(rows.find((row) => row.includes("5h"))).toContain("1% used");
		expect(rows.find((row) => row.includes("Weekly"))).toContain("3% used");
		expect(rows.join("\n")).toContain("resets in");
		expect(rows.join("\n")).not.toContain("0 / 0");
		expect(rows.join("\n")).not.toContain(key);
		expect(vi.mocked(ctx.ui.setStatus).mock.calls.at(-1)?.[1]).toContain(
			"Weekly 3%",
		);
		expect(session.errors).toEqual([]);
	}, 15000);

	it.each(["provider", "auth"] as const)(
		"never sends MiniMax credentials through /quota with %s region mismatch",
		async (source) => {
			const key = ["sk", "cp", "fixture"].join("-");
			const credentials = new InMemoryCredentialStore();
			await credentials.modify("minimax", async () => ({
				type: "api_key",
				key,
			}));
			session = await createPiSession({
				credentials,
				extensionPaths: [
					fileURLToPath(new URL("../index.ts", import.meta.url)),
				],
			});
			const fetch = vi.fn();
			vi.stubGlobal("fetch", fetch);
			const { command, ctx } = quotaCommandContext("minimax");
			if (source === "provider") {
				const provider = ctx.modelRegistry.getProvider("minimax");
				if (!provider) throw new Error("Missing native MiniMax provider");
				vi.spyOn(ctx.modelRegistry, "getProvider").mockReturnValue({
					...provider,
					baseUrl: "https://api.minimaxi.com/anthropic",
				});
			} else {
				vi.spyOn(ctx.modelRegistry, "getProviderAuth").mockResolvedValue({
					auth: {
						apiKey: key,
						baseUrl: "https://api.minimaxi.com/anthropic",
					},
				});
			}
			await command.handler("", ctx);
			expect(fetch).not.toHaveBeenCalled();
			expect(
				JSON.stringify(vi.mocked(ctx.ui.setWidget).mock.calls),
			).not.toContain("sk-cp-fixture");
			expect(session.errors).toEqual([]);
		},
		15000,
	);

	async function secondaryQuotaSession() {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("anthropic", async () => ({
			type: "api_key",
			key: "synthetic-anthropic-key",
		}));
		await credentials.modify("minimax", async () => ({
			type: "api_key",
			key: "sk-cp-synthetic-secondary",
		}));
		// A sibling extension shares Pi's bus: it reports activity and hosts the footer.
		let bus!: { emit: (channel: string, data: unknown) => void };
		const segments = new Map<string, string>();
		session = await createPiSession({
			credentials,
			extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
			extensionFactories: [
				(pi) => {
					bus = pi.events;
					pi.events.on("footer:segment", (data) => {
						const segment = data as {
							id: string;
							text?: string;
							accept: () => void;
						};
						segment.accept();
						if (segment.text === undefined) segments.delete(segment.id);
						else segments.set(segment.id, segment.text);
					});
				},
			],
		});
		const calls = { anthropic: 0, minimax: 0 };
		vi.stubGlobal(
			"fetch",
			vi.fn(async (input: string | URL) => {
				const url = String(input);
				if (url === "https://api.anthropic.com/api/oauth/usage") {
					calls.anthropic++;
					return Response.json({ five_hour: { utilization: 35 } });
				}
				if (url === "https://www.minimax.io/v1/token_plan/remains") {
					calls.minimax++;
					return Response.json({
						model_remains: [
							{
								model_name: "general",
								current_interval_total_count: 0,
								current_interval_usage_count: 0,
								current_interval_remaining_percent: 88,
							},
						],
						base_resp: { status_code: 0, status_msg: "success" },
					});
				}
				throw new Error(`unexpected network endpoint: ${url}`);
			}),
		);
		const runner = session.session.extensionRunner;
		const ui = {
			...runner.getUIContext(),
			setStatus: vi.fn(),
			setWidget: vi.fn(),
		};
		initTheme("default", false);
		runner.setUIContext(ui, "tui");
		// Same-model selection emits no model_select; alternate models to trigger it.
		const model = (provider: string, index = 0) => {
			const found = session?.session.modelRuntime.getModels(provider)[index];
			if (!found) throw new Error(`missing native ${provider} model`);
			return found;
		};
		const openQuota = async () => {
			const command = runner.getCommand("quota");
			if (!command) throw new Error("missing /quota command");
			await command.handler("", runner.createCommandContext());
		};
		const widget = () =>
			(ui.setWidget.mock.calls.at(-1)?.[1] as string[] | undefined)?.join(
				"\n",
			) ?? "";
		return { bus, segments, calls, runner, model, openQuota, widget };
	}

	it("shows event-reported MiniMax quota beside the active Anthropic provider until session_start", async () => {
		const { bus, segments, calls, runner, model, openQuota, widget } =
			await secondaryQuotaSession();
		vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
		try {
			if (!session) throw new Error("missing session");
			await session.session.setModel(model("anthropic"));
			await openQuota();
			await vi.waitFor(() =>
				expect(segments.get("quota:anthropic")).toContain("35%"),
			);

			for (const invalid of [
				null,
				"minimax",
				{ provider: 7 },
				{ provider: "MiniMax" },
				{ provider: "google" },
				{ provider: "toString" },
			])
				bus.emit("quota:provider-activity", invalid);
			await new Promise((resolve) => setTimeout(resolve, 20));
			expect(calls.minimax).toBe(0);
			expect([...segments.keys()]).toEqual(["quota:anthropic"]);

			bus.emit("quota:provider-activity", { provider: "minimax" });
			await vi.waitFor(() =>
				expect(segments.get("quota:minimax")).toBe("MiniMax 5h 12%"),
			);
			expect(calls.minimax).toBe(1);
			expect(segments.get("quota:anthropic")).toMatch(/^5h 35%/);
			expect(widget()).toContain("● Anthropic");
			expect(widget()).toContain("● MiniMax");
			expect(widget()).toContain("12% used");

			// Periodic refresh and header updates keep the secondary provider.
			const before = { ...calls };
			await vi.advanceTimersByTimeAsync(300000);
			await vi.waitFor(() => {
				expect(calls.anthropic).toBe(before.anthropic + 1);
				expect(calls.minimax).toBe(before.minimax + 1);
			});
			await runner.emit({
				type: "after_provider_response",
				status: 200,
				headers: { "anthropic-ratelimit-unified-5h-utilization": "0.41" },
			});
			expect(segments.get("quota:anthropic")).toMatch(/^5h 41%/);
			expect(segments.get("quota:minimax")).toBe("MiniMax 5h 12%");
			expect(widget()).toContain("● MiniMax");

			await session.session.setModel(model("anthropic", 1));
			expect(calls.anthropic).toBe(before.anthropic + 2);
			expect(calls.minimax).toBe(before.minimax + 2);
			expect(segments.has("quota:minimax")).toBe(true);

			await runner.emit({ type: "session_start", reason: "startup" });
			expect(segments.size).toBe(0);
			await session.session.setModel(model("anthropic"));
			expect(calls.anthropic).toBe(before.anthropic + 3);
			await vi.waitFor(() =>
				expect(segments.has("quota:anthropic")).toBe(true),
			);
			expect(segments.has("quota:minimax")).toBe(false);
			expect(calls.minimax).toBe(before.minimax + 2);
			expect(session.errors).toEqual([]);
		} finally {
			vi.useRealTimers();
		}
	}, 15000);

	it("does not duplicate an event-reported provider that is already active", async () => {
		const { bus, segments, calls, model, openQuota, widget } =
			await secondaryQuotaSession();
		if (!session) throw new Error("missing session");
		await session.session.setModel(model("minimax"));
		await openQuota();
		const polled = calls.minimax;
		bus.emit("quota:provider-activity", { provider: "minimax" });
		await new Promise((resolve) => setTimeout(resolve, 20));
		expect(calls.minimax).toBe(polled);
		await session.session.setModel(model("minimax", 1));
		expect(calls.minimax).toBe(polled + 1);
		expect([...segments.keys()]).toEqual(["quota:minimax"]);
		expect(segments.get("quota:minimax")).toMatch(/^5h 12%/);
		expect(widget().match(/● MiniMax/g)).toHaveLength(1);
		expect(calls.anthropic).toBe(0);
		expect(session.errors).toEqual([]);
	}, 15000);

	it("renders independent Zai windows through registered /quota", async () => {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("zai", async () => ({
			type: "api_key",
			key: "synthetic-key",
		}));
		session = await createPiSession({
			credentials,
			extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		});
		vi.stubGlobal(
			"fetch",
			vi.fn(async () =>
				Response.json({
					success: true,
					data: {
						limits: [
							{
								type: "CREDIT_LIMIT",
								unit: 3,
								number: 5,
								usage: 12000,
								currentValue: 0,
								remaining: 12000,
								percentage: 0,
							},
							{
								type: "CREDIT_LIMIT",
								unit: 6,
								number: 1,
								usage: 60000,
								currentValue: 60021,
								remaining: 0,
								percentage: 100,
								nextResetTime: Date.now() + 3600000,
							},
						],
					},
				}),
			),
		);
		const { command, ctx } = quotaCommandContext("zai");
		await command.handler("", ctx);
		const rows = vi.mocked(ctx.ui.setWidget).mock.calls.at(-1)?.[1] as string[];
		const five = rows.find((line) => line.includes("5h"));
		const weekly = rows.find((line) => line.includes("Weekly"));
		expect(five).toContain("(0%)");
		expect(five).not.toContain("resets");
		expect(weekly).toContain("(100%)");
		expect(weekly).toContain("resets");
		expect(session.errors).toEqual([]);
	}, 15000);

	it("shows the routed physical provider's quota under a virtual selection", async () => {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("openrouter", async () => ({
			type: "api_key",
			key: "synthetic-key",
		}));
		session = await createPiSession({
			credentials,
			extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		});
		const fetch = vi.fn(async (_url: string | URL | Request) =>
			Response.json({
				data: {
					is_free_tier: true,
					free_model_daily_requests: { used: 1, limit: 50, remaining: 49 },
				},
			}),
		);
		vi.stubGlobal("fetch", fetch);
		const { command, ctx } = quotaCommandContext({
			provider: "grts",
			api: "pi-virtual",
		});
		Object.defineProperty(ctx, "sessionManager", {
			value: {
				getBranch: () => [
					{ type: "model_change" },
					{
						type: "message",
						message: {
							role: "assistant",
							provider: "openrouter",
							api: "openai-completions",
							stopReason: "stop",
						},
					},
				],
			},
		});
		await command.handler("", ctx);
		expect(String(fetch.mock.calls[0]?.[0])).toBe(
			"https://openrouter.ai/api/v1/key",
		);
		const rows = vi.mocked(ctx.ui.setWidget).mock.calls.at(-1)?.[1] as string[];
		expect(rows.join("\n")).toContain("OpenRouter");
		expect(rows.join("\n")).toContain("1 / 50 requests used");
		expect(session.errors).toEqual([]);
	}, 15000);

	it("keeps weekly-only Codex widget free of empty secondary header placeholders", async () => {
		const credentials = new InMemoryCredentialStore();
		await credentials.modify("openai-codex", async () => ({
			type: "oauth",
			access: codexToken("synthetic-weekly"),
			refresh: "unused",
			expires: Date.now() + 3600000,
		}));
		session = await createPiSession({
			credentials,
			extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		});
		vi.stubGlobal(
			"fetch",
			vi.fn(async () =>
				Response.json({
					rate_limit: {
						primary_window: { used_percent: 42, limit_window_seconds: 604800 },
						secondary_window: null,
					},
				}),
			),
		);
		const model = session.session.modelRuntime.getModels("openai-codex")[0];
		if (!model) throw new Error("missing native Codex model");
		await session.session.setModel(model);
		const { command, ctx } = quotaCommandContext();
		await command.handler("", ctx);
		await session.session.extensionRunner.emit({
			type: "after_provider_response",
			status: 200,
			headers: {
				"x-codex-primary-used-percent": "43",
				"x-codex-primary-window-minutes": "10080",
				"x-codex-secondary-used-percent": "0",
				"x-codex-secondary-window-minutes": "0",
			},
		});
		const rows = vi.mocked(ctx.ui.setWidget).mock.calls.at(-1)?.[1] as string[];
		expect(rows.join("\n")).not.toContain("Secondary");
		expect(rows.join("\n")).toContain("Weekly");
		expect(rows.join("\n")).toContain("43%");
		expect(rows.join("\n")).not.toContain("5h");
		expect(vi.mocked(ctx.ui.setStatus).mock.calls.at(-1)?.[1]).toContain(
			"Weekly 43%",
		);
		expect(session.errors).toEqual([]);
	}, 15000);

	it.each(["google", "google-gemini-cli"])(
		"never requests excluded Google provider %s",
		async (provider) => {
			session = await createPiSession({
				extensionPaths: [
					fileURLToPath(new URL("../index.ts", import.meta.url)),
				],
			});
			const fetch = vi.fn();
			vi.stubGlobal("fetch", fetch);
			const { command, ctx } = quotaCommandContext(provider);
			await command.handler("", ctx);
			expect(fetch).not.toHaveBeenCalled();
		},
		15000,
	);
});