repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/web/__serial__/minimax.test.ts
Rawimport { afterEach, describe, expect, it, vi } from "vitest";
import {
isMinimaxAvailable,
minimaxSearch,
resolveMinimaxApiKey,
resolveMinimaxBaseUrl,
} from "../minimax.ts";
type FetchCall = {
url: string;
init: RequestInit;
body?: Record<string, unknown>;
};
const M_PLAN_KEY = ["sk", "cp", "test"].join("-");
const PAYG_KEY = ["sk", "api", "payg"].join("-");
const UNKNOWN_KEY = ["sk", "unknown"].join("-");
type MinimaxContextOptions = {
apiKey?: string;
providerBaseUrl?: string;
authBaseUrl?: string;
getProviderAuth?: () => Promise<unknown>;
};
function ctx({
apiKey = M_PLAN_KEY,
providerBaseUrl = "https://api.minimax.io/anthropic",
authBaseUrl,
getProviderAuth,
}: MinimaxContextOptions = {}) {
return {
cwd: process.cwd(),
isProjectTrusted: () => false,
modelRegistry: {
getProvider: (provider: string) =>
provider === "minimax"
? { id: "minimax", baseUrl: providerBaseUrl }
: undefined,
getProviderAuth:
getProviderAuth ??
(async () => ({
auth: {
apiKey,
...(authBaseUrl === undefined ? {} : { baseUrl: authBaseUrl }),
},
})),
getAll: () => [{ provider: "minimax-cn", baseUrl: "https://cn.test" }],
},
} as any;
}
function installJsonFetch(calls: FetchCall[], response: unknown, ok = true) {
const prev = globalThis.fetch;
globalThis.fetch = (async (
url: string | URL | Request,
init?: RequestInit,
) => {
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
calls.push({ url: String(url), init: init ?? {}, body });
return new Response(JSON.stringify(response), {
status: ok ? 200 : 500,
statusText: ok ? "OK" : "ERR",
headers: { "content-type": "application/json" },
});
}) as typeof fetch;
return () => {
globalThis.fetch = prev;
};
}
const SEARCH_RESPONSE = {
organic: [],
related_searches: [],
base_resp: { status_code: 0, status_msg: "ok" },
};
describe("minimax M Plan search client", () => {
const originalMinimaxHost = process.env["MINIMAX_API_HOST"];
let restoreFetch: (() => void) | undefined;
afterEach(() => {
restoreFetch?.();
restoreFetch = undefined;
if (originalMinimaxHost === undefined)
delete process.env["MINIMAX_API_HOST"];
else process.env["MINIMAX_API_HOST"] = originalMinimaxHost;
});
it("resolves Pi's full global minimax auth", async () => {
const registryKey = ["sk", "cp", "registry"].join("-");
expect(await resolveMinimaxApiKey(ctx({ apiKey: registryKey }))).toBe(
registryKey,
);
});
it("offers automatic search only for a valid M Plan key, without requests", async () => {
const fetchMock = vi.spyOn(globalThis, "fetch");
expect(await isMinimaxAvailable(ctx())).toBe(true);
expect(await isMinimaxAvailable(ctx({ apiKey: PAYG_KEY }))).toBe(false);
expect(await isMinimaxAvailable(ctx({ apiKey: UNKNOWN_KEY }))).toBe(false);
expect(fetchMock).not.toHaveBeenCalled();
});
it("uses the verified global endpoint despite unrelated model metadata", async () => {
const calls: FetchCall[] = [];
restoreFetch = installJsonFetch(calls, SEARCH_RESPONSE);
await minimaxSearch("pi docs", ctx());
const call = calls[0];
if (!call) throw new Error("missing fetch call");
expect(resolveMinimaxBaseUrl()).toBe("https://api.minimax.io");
expect(call.url).toBe("https://api.minimax.io/v1/coding_plan/search");
expect(call.body).toEqual({ q: "pi docs" });
expect((call.init.headers as Record<string, string>)["Authorization"]).toBe(
`Bearer ${M_PLAN_KEY}`,
);
expect(call.init.redirect).toBe("error");
});
it.each([
["CN provider", { providerBaseUrl: "https://api.minimaxi.com/anthropic" }],
["credential override", { authBaseUrl: "https://attacker.example/v1" }],
] satisfies [string, MinimaxContextOptions][])(
"rejects %s before sending its key",
async (_name, options) => {
const fetchMock = vi.spyOn(globalThis, "fetch");
await expect(minimaxSearch("query", ctx(options))).rejects.toThrow(
"endpoint/region mismatch",
);
expect(fetchMock).not.toHaveBeenCalled();
},
);
it.each([PAYG_KEY, UNKNOWN_KEY])(
"rejects %s before sending a search request",
async (apiKey) => {
const fetchMock = vi.spyOn(globalThis, "fetch");
await expect(minimaxSearch("query", ctx({ apiKey }))).rejects.toThrow(
apiKey === PAYG_KEY ? "PAYG" : "Ambiguous",
);
expect(fetchMock).not.toHaveBeenCalled();
},
);
it("rejects obsolete configurable endpoints before sending its registry key", async () => {
process.env["MINIMAX_API_HOST"] = "https://attacker.example";
const fetchMock = vi.spyOn(globalThis, "fetch");
await expect(minimaxSearch("query", ctx())).rejects.toThrow(
"web.minimax.apiHost is obsolete and ignored",
);
expect(fetchMock).not.toHaveBeenCalled();
});
it("cancels a pending credential resolution without requesting search", async () => {
const controller = new AbortController();
const reason = new Error("operator cancelled");
const fetchMock = vi.spyOn(globalThis, "fetch");
const pending = minimaxSearch(
"query",
ctx({ getProviderAuth: async () => await new Promise(() => {}) }),
controller.signal,
);
controller.abort(reason);
await expect(pending).rejects.toBe(reason);
expect(fetchMock).not.toHaveBeenCalled();
});
it.each([{}, { organic: "not-an-array" }])(
"rejects malformed organic results: %o",
async (payload) => {
restoreFetch = installJsonFetch([], payload);
await expect(minimaxSearch("query", ctx())).rejects.toThrow(
"invalid organic results",
);
},
);
});