Files
magpie/internal/gui/tests/azure-endpoint.test.cjs
T
yetone c35471cf5b provider: Azure OpenAI, asked at the user's own resource on its v1 API with the key in api-key, for Codex, Claude Code and chat clients alike, and brought in from other apps instead of left out — Azure OpenAI had no preset, and importing an Azure entry from Alma was skipped with "magpie doesn't support Azure OpenAI yet". A new Azure OpenAI preset (vendor) has no URL of its own: its editor asks for the resource's endpoint in a field above the key, focused first, with https://<resource>.openai.azure.com as the placeholder and a hint on where the portal shows it and that the model ids are the deployments' names (en and zh); adding without one says "Your resource's endpoint is needed" and sends nothing, and Save refuses one without an endpoint too. Whatever is pasted — the bare endpoint, …/openai, …/openai/v1/, a classic deployment URL with its api-version, a *.cognitiveservices.azure.com or *.services.ai.azure.com host, or only the resource's name — is saved as https://<host>/openai/v1 for both chat completions and Responses. magpie uses the v1 GA API rather than the classic /openai/deployments/<name>/…?api-version= paths: the paths match OpenAI's, the body's model is the deployment's name, and no api-version is needed (the reasoning is in internal/provider/azure.go). The key goes in api-key, never as a Bearer, which Azure takes as an Entra ID token; nothing sends Authorization or x-api-key there. Deployments named after GPT/o/codex models go to Responses first, as OpenAI's do, and others to chat completions. Chat bodies ask max_completion_tokens instead of max_tokens and drop thinking/enable_thinking, both in passthrough and in Claude Code's translated requests, and the Test probe asks max_completion_tokens as well. The model list is the resource's deployments (/openai/deployments?api-version=2022-12-01), falling back to /openai/v1/models, with the key in api-key; when neither answers, the error says to type the deployment names in as model ids. Before a list, no catalog models are offered, since a model the resource hasn't deployed would be turned away. An Alma azure entry, and any imported entry at a resource's host, becomes the preset at its v1 base; an Alma azure entry with no endpoint is skipped as "it has no Azure OpenAI endpoint", and one at a non-Azure host (an API Management gateway) keeps its URL and is still signed with api-key. Adds the lobe-icons Azure icon. Tested in Go against fake resources (httptest): TestAzureRoutes checks that Codex /v1/responses, a chat client's /v1/chat/completions and Claude Code's /v1/messages on both a GPT-named and another deployment reach /openai/v1/responses or /openai/v1/chat/completions with api-key set, no Authorization or x-api-key, the deployment name as the model, max_completion_tokens and no thinking; TestAzureBase covers each pasted form and the hosts that aren't resources; TestAzurePresetSaved covers the endpoint required, both URLs on the v1 base, api-key-only headers, Native, the probe's URL and body, and nothing available before a list; TestAzureModels covers deployments first, the v1 fallback and a refused key's message; TestImportAzure covers Alma rows with an endpoint, with a bare resource name and with none, plus a classic URL from another app. azure-endpoint.test.cjs, in Chromium and WebKit, en and zh, checks the field, placeholder, hint and focus, the warning without an endpoint with nothing sent and the page not scrolled, the endpoint sent as chat and responses with the key, and that OpenAI's editor has no such field. add-sheet and old-webkit pass. go build -tags nogui (and GOOS=linux, GOOS=windows), go vet and go test -tags nogui ./... pass (TestClaudeAccountNamedAsItsLogin failed under load and passes alone). Not tried against a real Azure resource: whether a key still lists deployments with api-version 2022-12-01, whether Azure's Responses API accepts every field Codex sends, Claude models on Azure AI Foundry's Anthropic endpoint (not wired), Entra ID tokens, and API Management custom domains beyond keeping their URL. Not tried in the real Wails window.
2026-09-30 02:17:15 +08:00

114 lines
6.8 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// Azure OpenAI's editor asks for the resource's endpoint (no host magpie
// knows serves it): a field above the key, focused first, with the portal's
// shape as its placeholder and a hint on where to find it and that the
// model ids are the deployments' names. Adding without one says so and
// sends nothing; with one, the endpoint goes as both chat and Responses.
// Nothing moves the page. English and Chinese; no backend, the API is
// faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const presets = [
{ id: "openai", name: "OpenAI", icon: "openai", kind: "vendor", chat: "https://api.openai.com/v1", added: false },
{ id: "azure", name: "Azure OpenAI", icon: "azure-color", kind: "vendor", added: false, catalog: "azure, openai",
note: "your resource's endpoint and key", endpoint: "https://<resource>.openai.azure.com",
endpointHint: "Your resource's endpoint, from Keys and Endpoint in the Azure portal. magpie asks its v1 API; the model ids are your deployments' names." },
];
const providers = [{ id: "openrouter", name: "OpenRouter", icon: "openai", preset: "openrouter", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }];
function server(lang, saves) {
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json({ providers, presets, excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/provider/save") {
saves.push(route.request().postDataJSON());
return json({ providers, presets, excluded: [], gateway: { running: true, window: true } });
}
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/gateway/trace") return json({ routes: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const L = {
en: { field: "Endpoint", hint: /Keys and Endpoint in the Azure portal.*deployments' names/, needed: "Your resource's endpoint is needed", add: "Add" },
zh: { field: "终结点", hint: /Azure 门户的「密钥和终结点」.*部署名称/, needed: "需要填写你的资源终结点", add: "添加" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": Azure OpenAI asks for its endpoint", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh"]) {
await t.test(lang, async () => {
const w = L[lang];
const saves = [];
const page = await (await browser.newContext({ viewport: { width: 900, height: 700 } })).newPage();
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, saves));
await page.goto("http://magpie.test/?view=providers");
await page.locator("#addProvider").click();
const sheet = page.locator("#addSheet");
await sheet.locator(".tile .n", { hasText: /^Azure OpenAI$/ }).click();
const ed = page.locator(".editor.new");
await ed.locator(".ehead b", { hasText: "Azure OpenAI" }).waitFor();
// the field, above the key, focused first; the OpenAI preset has none
const label = ed.locator("label", { hasText: new RegExp("^" + w.field + "$") });
assert.equal(await label.count(), 1);
const endpoint = ed.locator("input.endpoint");
assert.equal(await endpoint.getAttribute("placeholder"), "https://<resource>.openai.azure.com");
assert.equal(await endpoint.getAttribute("type"), "url");
assert.match(await endpoint.locator("xpath=following-sibling::div[contains(@class,'hint')]").textContent(), w.hint);
await page.waitForFunction(() => document.activeElement?.classList.contains("endpoint"));
const key = ed.locator("input[type=password]").first();
const [ey, ky] = [await endpoint.boundingBox(), await key.boundingBox()].map((b) => b.y);
assert(ey < ky, "the endpoint above the key");
// no endpoint: said, nothing sent, the page where it was
await key.fill("az-key");
const y = await page.evaluate(() => document.scrollingElement.scrollTop);
await ed.locator(".bar button.primary", { hasText: w.add }).click();
assert.equal(await ed.locator(".editor-error").textContent(), w.needed);
assert.equal(saves.length, 0);
assert.equal(await page.evaluate(() => document.activeElement?.classList.contains("endpoint")), true);
assert.equal(await page.evaluate(() => document.scrollingElement.scrollTop), y);
// with one: sent as both chat and Responses, with the key
await endpoint.fill("https://contoso.openai.azure.com/");
await ed.locator(".bar button.primary", { hasText: w.add }).click();
await page.waitForFunction(() => !document.querySelector(".editor.new"));
assert.equal(saves.length, 1);
const s = saves[0];
assert.equal(s.preset, "azure");
assert.equal(s.key, "az-key");
assert.equal(s.chat, "https://contoso.openai.azure.com/");
assert.equal(s.responses, "https://contoso.openai.azure.com/");
// another preset's editor has no endpoint field
await page.locator("#addProvider").click();
await sheet.locator(".tile .n", { hasText: /^OpenAI$/ }).click();
await ed.locator(".ehead b", { hasText: "OpenAI" }).waitFor();
assert.equal(await ed.locator("input.endpoint").count(), 0);
assert.deepEqual(errors, []);
await page.context().close();
});
}
});
}