diff --git a/internal/gui/tests/provider-base-as-typed.test.cjs b/internal/gui/tests/provider-base-as-typed.test.cjs new file mode 100644 index 000000000..b892a83c6 --- /dev/null +++ b/internal/gui/tests/provider-base-as-typed.test.cjs @@ -0,0 +1,83 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A base URL typed in a custom provider's editor is saved as typed and opens +// as typed, for each API (JNDliuliuM on X: 点击保存之后再重新打开看,还是会被 +// 添加上/v1beta). The Save sends the URL as typed, and the editor opened +// again shows what the saved provider has. Chromium and WebKit. +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"); + +function serve(posts, providers) { + const state = { agents: [], profiles: [], settings: { lang: "en", theme: "light" } }; + 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:"en",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json({ providers, presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/provider/save") { + const body = route.request().postDataJSON(); + posts.push(body); + // the server keeps what it is sent + const at = providers.findIndex((p) => p.id === body.id); + if (at >= 0) providers[at] = { ...providers[at], chat: body.chat || "", responses: body.responses || "", anthropic: body.anthropic || "", gemini: body.gemini || "", baseAPI: body.baseAPI }; + return json({ providers, presets: [], excluded: [], gateway: { running: true, window: true } }); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + await route.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] }); + }; +} + +const CASES = [ + { api: "gemini", field: "gemini", typed: "https://relay.example.com" }, + { api: "gemini", field: "gemini", typed: "https://relay.example.com/v1" }, + { api: "openai", field: "chat", typed: "https://relay.example.com" }, + { api: "openai", field: "chat", typed: "https://relay.example.com/api" }, + { api: "responses", field: "responses", typed: "https://relay.example.com" }, + { api: "anthropic", field: "anthropic", typed: "https://relay.example.com/claude" }, +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: a typed base URL is saved and reopened as typed`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage(); + t.after(() => browser.close()); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + const models = [{ id: "m", name: "m", on: true }]; + const providers = CASES.map((c, i) => ({ + id: "p" + i, name: "P" + i, icon: "generic", chat: "", responses: "", anthropic: "", gemini: "", + baseAPI: c.api === "openai" ? "" : c.api, models, agents: [], fallback: [], headers: {}, key: { set: true, masked: "sk-…1234" }, keyList: [], ready: true, + [c.field]: "https://old.example.com/x", + })); + await page.route("**/*", serve(posts, providers)); + await page.goto("http://magpie.test/?view=providers"); + const ed = page.locator(".editor"); + const open = async (id) => { + if (await ed.count()) { await page.goto("http://magpie.test/?view=providers"); await ed.waitFor({ state: "detached" }); } + await page.locator(`#providers .row[data-id="${id}"]`).click(); + await ed.locator(".base-url").waitFor(); + }; + for (const [i, c] of CASES.entries()) { + await open("p" + i); + await ed.locator(".base-url").fill(c.typed); + const n = posts.length; + await ed.locator(":scope > .bar").getByRole("button", { name: "Save", exact: true }).click(); + for (let k = 0; k < 60 && posts.length === n; k++) await page.waitForTimeout(50); + assert.equal(posts.length, n + 1, "saved " + c.typed); + assert.equal(posts[n][c.field], c.typed, `${c.api} sent as typed`); + await open("p" + i); + assert.equal(await ed.locator(".base-url").inputValue(), c.typed, `${c.api} reopens as typed`); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/provider/detect.go b/internal/provider/detect.go index 375051ea9..725ae46d2 100644 --- a/internal/provider/detect.go +++ b/internal/provider/detect.go @@ -58,7 +58,7 @@ func DetectBase(base string, proto Protocol) string { if pu, err := url.Parse(u); err == nil && pu.Host != "" && strings.Trim(pu.Path, "/") == "v1" { return u + "beta" } - return GeminiBase(u) + return geminiVersioned(u) } if pu, err := url.Parse(u); err == nil && strings.Trim(pu.Path, "/") == "" { return u + "/v1" diff --git a/internal/provider/gemini_api.go b/internal/provider/gemini_api.go index b327e3ac8..ea4c71c5f 100644 --- a/internal/provider/gemini_api.go +++ b/internal/provider/gemini_api.go @@ -17,8 +17,9 @@ import ( var geminiMethod = lazyre.New(`/models(?:/[^/?#]*)?(?:[?#].*)?$`) // GeminiBase is the base a Gemini URL is kept as: trimmed, an endpoint or -// the model list pasted whole cut back to the base, and a bare host given -// Google's version (/v1beta), as the Gemini API's SDKs add it. +// the model list pasted whole cut back to the base. Only Google's own bare +// host is given its version (/v1beta); any other URL stays as typed, so a +// relay's root is not rewritten on the next open (JNDliuliuM on X). func GeminiBase(u string) string { u = strings.TrimRight(strings.TrimSpace(u), "/") if u == "" { @@ -28,6 +29,17 @@ func GeminiBase(u string) string { u = "https://" + u } u = strings.TrimRight(geminiMethod.ReplaceAllString(u, ""), "/") + if pu, err := url.Parse(u); err == nil && strings.EqualFold(pu.Hostname(), "generativelanguage.googleapis.com") && strings.Trim(pu.Path, "/") == "" { + return u + "/v1beta" + } + return u +} + +// geminiVersioned is GeminiBase with the /v1beta a bare host of any vendor +// is asked at, for a detection that proposes a base rather than keeping one +// the user typed. +func geminiVersioned(u string) string { + u = GeminiBase(u) if pu, err := url.Parse(u); err == nil && pu.Host != "" && strings.Trim(pu.Path, "/") == "" { return u + "/v1beta" } diff --git a/internal/provider/gemini_api_test.go b/internal/provider/gemini_api_test.go index 55b153bb2..7043cdcbf 100644 --- a/internal/provider/gemini_api_test.go +++ b/internal/provider/gemini_api_test.go @@ -16,7 +16,10 @@ func TestGeminiBase(t *testing.T) { "https://generativelanguage.googleapis.com/": "https://generativelanguage.googleapis.com/v1beta", "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse": "https://generativelanguage.googleapis.com/v1beta", "https://relay.example/proxy/v1beta/models": "https://relay.example/proxy/v1beta", - "https://relay.example/proxy/v1": "https://relay.example/proxy/v1", + "https://relay.example": "https://relay.example", + "https://relay.example/": "https://relay.example", + "relay.example:8080": "https://relay.example:8080", + "https://relay.example/proxy/v1": "https://relay.example/proxy/v1", } { if got := GeminiBase(in); got != want { t.Errorf("GeminiBase(%q) = %q, want %q", in, got, want) @@ -183,3 +186,36 @@ func TestAIStudioGeminiClearedStays(t *testing.T) { } } } + +// A relay's Gemini base typed without a version is saved and reopened as +// typed; only Google's own bare host is given /v1beta (JNDliuliuM on X: +// 点击保存之后再重新打开看,还是会被添加上/v1beta). +func TestGeminiBaseSavedAsTyped(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + for id, c := range map[string][2]string{ + "root": {"https://relay.example", "https://relay.example"}, + "v1": {"https://relay.example/v1", "https://relay.example/v1"}, + "prefix": {"https://relay.example/gemini", "https://relay.example/gemini"}, + "google": {"https://generativelanguage.googleapis.com", "https://generativelanguage.googleapis.com/v1beta"}, + } { + if err := Save(Provider{ID: id, Name: id, Key: "k", Gemini: c[0]}); err != nil { + t.Fatal(err) + } + got, err := Find(id) + if err != nil { + t.Fatal(err) + } + if got.Gemini != c[1] { + t.Errorf("%s: Gemini %q saved as %q, want %q", id, c[0], got.Gemini, c[1]) + } + } + // the other protocols' bases are kept as typed too + if err := Save(Provider{ID: "oa", Name: "oa", Key: "k", Chat: "https://relay.example", Responses: "https://relay.example/api"}); err != nil { + t.Fatal(err) + } + got, _ := Find("oa") + if got.Chat != "https://relay.example" || got.Responses != "https://relay.example/api" { + t.Errorf("openai bases changed: %q %q", got.Chat, got.Responses) + } +}