diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 22e7ad3c2..b148fa8fc 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13533,7 +13533,10 @@ function renderKeyAccounts(p) { // the key is what's needed; a name is only for telling keys apart const name = input(addingKey.name, t("Name (optional), e.g. Team")); name.oninput = () => { addingKey.name = name.value; }; - const key = input(addingKey.key, t("paste an API key"), "password"); + // a provider asked with a key of its own when the user has none (Zen's + // public, #1795) adds that one when nothing is pasted, and says so + const key = input(addingKey.key, p.anonKey ? t("paste an API key, or leave empty for {key}: free models only", { key: p.anonKey }) : t("paste an API key"), "password"); + if (p.anonKey) key.title = key.placeholder; key.oninput = () => { addingKey.key = key.value; }; // several keys pasted into the one field: the box takes them all key.onpaste = (e) => { @@ -13546,7 +13549,7 @@ function renderKeyAccounts(p) { const add = el("button", "text primary", t("Add")); const go = async () => { add.classList.add("busy"); - const id = await keyFingerprint(key.value.trim()); + const id = await keyFingerprint(key.value.trim() || p.anonKey || ""); if (await accountAction("keys/add", { id: p.id, name: name.value, key: key.value, protocol: addingKey.protocol || "" }, t("Key added — it takes over when the ones before it run out"))) { addingKey = null; justAdded = id; renderProviders(); setTimeout(() => { justAdded = ""; }, 2000); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 9afa66bc3..6fe7aef14 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1544,6 +1544,7 @@ const I18N = { "optional: free models need no key": "可不填:免费模型无需密钥", "free models with no key": "免费模型,无需密钥", "paste an API key": "粘贴 API 密钥", + "paste an API key, or leave empty for {key}: free models only": "粘贴 API 密钥,或留空使用 {key}:仅限免费模型", "Show": "显示", "Hide": "隐藏", "Get a key ↗": "获取密钥 ↗", @@ -5971,6 +5972,7 @@ const I18N = { "optional: free models need no key": "可不填:免費模型無需金鑰", "free models with no key": "免費模型,無需金鑰", "paste an API key": "貼上 API 金鑰", + "paste an API key, or leave empty for {key}: free models only": "貼上 API 金鑰,或留空使用 {key}:僅限免費模型", "Show": "顯示", "Hide": "隱藏", "Get a key ↗": "取得金鑰 ↗", @@ -10374,6 +10376,7 @@ const I18N = { "optional: free models need no key": "任意:無料モデルにはキー不要", "free models with no key": "キー不要の無料モデル", "paste an API key": "APIキーを貼り付け", + "paste an API key, or leave empty for {key}: free models only": "APIキーを貼り付け、空欄なら {key}:無料モデルのみ", "Show": "表示", "Hide": "非表示", "Get a key ↗": "キーを取得 ↗", @@ -14796,6 +14799,7 @@ const I18N = { "optional: free models need no key": "optional: kostenlose Modelle brauchen keinen Schlüssel", "free models with no key": "kostenlose Modelle ohne Schlüssel", "paste an API key": "API-Schlüssel einfügen", + "paste an API key, or leave empty for {key}: free models only": "API-Schlüssel einfügen, oder leer lassen für {key}: nur kostenlose Modelle", "Show": "Anzeigen", "Hide": "Ausblenden", "Get a key ↗": "Schlüssel holen ↗", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 28b2d459f..54fb7db0e 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -160,6 +160,10 @@ type providerJSON struct { Masked string `json:"masked"` Optional bool `json:"optional"` } `json:"key"` + // AnonKey is the key Add another key adds when nothing is pasted + // (provider.AnonymousKey: OpenCode Zen's public, #1795), while the + // provider doesn't have it yet + AnonKey string `json:"anonKey,omitempty"` Ready bool `json:"ready"` Chosen []string `json:"chosen"` // the user's explicit picks, if any Fallback []string `json:"fallback"` // where requests go when this one can't take them @@ -564,6 +568,9 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON { out.Move.State = "" } } + if anon := p.AnonymousKey(); anon != "" && p.Account == nil && !p.HasKey(anon) { + out.AnonKey = anon + } out.KeyList = p.KeyList() if out.KeyList == nil { out.KeyList = []provider.KeyInfo{} diff --git a/internal/gui/tests/zen-anon-key.test.cjs b/internal/gui/tests/zen-anon-key.test.cjs new file mode 100644 index 000000000..4cdec884f --- /dev/null +++ b/internal/gui/tests/zen-anon-key.test.cjs @@ -0,0 +1,118 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #1795 (cuddly-guacamole): Add another key on an OpenCode Zen provider +// that has a key of the user's own says what an empty field adds, public, +// the key Zen's free models answer with none of the user's, as adding a +// Zen provider with no key says its free models need none. Add with +// nothing pasted posts keys/add, and the new row is marked. A provider +// with no such key (anonKey) keeps "paste an API key". In every language, +// at a wide and a narrow window, with no page error. +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 PUBLIC_ID = "efa1f375d7"; // sha256("public")[:5], provider.keyID + +const zen = () => ({ + id: "opencode-zen", name: "OpenCode Zen", icon: "opencode", preset: "opencode-zen", chat: "https://opencode.ai/zen/v1", responses: "", anthropic: "", catalog: "opencode", + models: [{ id: "big-pickle", name: "", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-z…zzzz" }, anonKey: "public", balanceToken: { takes: false, set: false }, proxy: "", + keyList: [{ id: "aaaaaaaaaa", name: "", masked: "sk-z…zzzz", on: true, active: true }], +}); +const relay = () => ({ + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "big", name: "", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "", + keyList: [{ id: "bbbbbbbbbb", name: "", masked: "sk-…one", on: true, active: true }], +}); + +function serve(lang, posts) { + const z = zen(); + const providers = { providers: [z, relay()], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, 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:"${lang}",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); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/keys/add" && route.request().method() === "POST") { + posts.push(route.request().postDataJSON()); + z.keyList = [...z.keyList, { id: PUBLIC_ID, name: "", masked: "••••••", on: true }]; + delete z.anonKey; + return json(providers); + } + 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)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { another: "Add another key", add: "Add", hint: "paste an API key, or leave empty for public: free models only", plain: "paste an API key" }, + zh: { another: "添加另一个密钥", add: "添加", hint: "粘贴 API 密钥,或留空使用 public:仅限免费模型", plain: "粘贴 API 密钥" }, + "zh-TW": { another: "新增另一個金鑰", add: "新增", hint: "貼上 API 金鑰,或留空使用 public:僅限免費模型", plain: "貼上 API 金鑰" }, + ja: { another: "別のキーを追加", add: "追加", hint: "APIキーを貼り付け、空欄なら public:無料モデルのみ", plain: "APIキーを貼り付け" }, + de: { another: "Weiteren Schlüssel hinzufügen", add: "Hinzufügen", hint: "API-Schlüssel einfügen, oder leer lassen für public: nur kostenlose Modelle", plain: "API-Schlüssel einfügen" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [900, 560]) { + const w = words[lang]; + const open = async (t, name, row) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + let page; + t.after(async () => { + if (process.env.ARTIFACT_DIR && page) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name}-zen-anon-key.png`) }); + } + await browser.close(); + }); + page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + // localhost is a secure context, where the page can hash the new key to mark its row + await page.goto("http://localhost/?view=providers"); + await page.locator(".row.provider", { hasText: row }).first().click(); + await page.locator(".editor .accts .acc.add").waitFor(); + await page.getByRole("button", { name: w.another }).click(); + await page.locator(".acc.adding input[type=password]").waitFor(); + return { page, errors, posts }; + }; + + test(`${engine} ${lang} ${width}px: Zen's Add another key says an empty field adds public, and adds it`, async (t) => { + const { page, errors, posts } = await open(t, "zen", "OpenCode Zen"); + const field = page.locator(".acc.adding input[type=password]"); + assert.equal(await field.getAttribute("placeholder"), w.hint); + assert.equal(await field.getAttribute("title"), w.hint, "the whole hint, where the field cuts it short"); + await page.locator(".acc.adding").getByRole("button", { name: w.add, exact: true }).click(); + for (let i = 0; i < 60 && !posts.length; i++) await new Promise((r) => setTimeout(r, 50)); + assert.deepEqual(posts.map((b) => [b.id, b.key]), [["opencode-zen", ""]]); + await page.locator(`.acc.new[data-account-id="${PUBLIC_ID}"]`).waitFor(); + assert.equal(await page.locator(".acc.adding").count(), 0); + // the box fits the window: nothing runs off its right edge + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}px: a provider with no key of its own to add keeps "paste an API key"`, async (t) => { + const { page, errors } = await open(t, "relay", "Relay"); + const field = page.locator(".acc.adding input[type=password]"); + assert.equal(await field.getAttribute("placeholder"), w.plain); + assert.equal(await field.getAttribute("title"), null); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/zen_anon_key_test.go b/internal/gui/zen_anon_key_test.go new file mode 100644 index 000000000..9d42851d2 --- /dev/null +++ b/internal/gui/zen_anon_key_test.go @@ -0,0 +1,97 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// #1795 (cuddly-guacamole): an OpenCode Zen provider with a key of the +// user's own, given Add another key with nothing pasted, adds public, the +// key Zen's free models answer with no key of the user's, as a new Zen +// provider saved with no key gets it. The provider's row offers it +// (anonKey) until it has it; asked again it says it has it. Any other +// provider still wants a key pasted, and never offers one. +func TestZenAddAnotherKeyEmptyAddsPublic(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + mux := http.NewServeMux() + providerRoutes(mux, nil) + call := func(method, path, body string) (int, string) { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) + return w.Code, w.Body.String() + } + anonOf := func(id string) string { + t.Helper() + code, body := call("GET", "/api/providers", "") + if code != 200 { + t.Fatalf("providers: %d %s", code, body) + } + var out struct { + Providers []struct { + ID string `json:"id"` + AnonKey string `json:"anonKey"` + } `json:"providers"` + } + if err := json.Unmarshal([]byte(body), &out); err != nil { + t.Fatal(err) + } + for _, p := range out.Providers { + if p.ID == id { + return p.AnonKey + } + } + t.Fatalf("no %s in %s", id, body) + return "" + } + + zen, err := provider.FromPreset("opencode-zen") + if err != nil { + t.Fatal(err) + } + zen.ID, zen.Key = "opencode-zen", "sk-own-zen-key" + if err := provider.Save(zen); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "http://127.0.0.1:1/v1", Key: "sk-relay-1"}); err != nil { + t.Fatal(err) + } + if got := anonOf("opencode-zen"); got != provider.OpenCodeAnonymousKey { + t.Fatalf("Zen with its own key offers %q", got) + } + if got := anonOf("relay"); got != "" { + t.Fatalf("a relay offers %q", got) + } + + if code, body := call("POST", "/api/keys/add", `{"id":"opencode-zen","name":"","key":" ","protocol":""}`); code != 200 { + t.Fatalf("empty key on Zen: %d %s", code, body) + } + p, _ := provider.Find("opencode-zen") + if p.Key != "sk-own-zen-key" || len(p.Keys) != 1 || p.Keys[0].Key != provider.OpenCodeAnonymousKey || p.Keys[0].Off { + t.Fatalf("Zen keys: first %q, others %+v", p.Key, p.Keys) + } + if got := anonOf("opencode-zen"); got != "" { + t.Fatalf("Zen with public still offers %q", got) + } + code, body := call("POST", "/api/keys/add", `{"id":"opencode-zen","name":"","key":"","protocol":""}`) + if code == 200 || !strings.Contains(body, "already has public") { + t.Fatalf("public twice: %d %s", code, body) + } + + code, body = call("POST", "/api/keys/add", `{"id":"relay","name":"","key":"","protocol":""}`) + if code == 200 || !strings.Contains(body, "paste the key to add") { + t.Fatalf("empty key on a relay: %d %s", code, body) + } + if p, _ := provider.Find("relay"); p.Key != "sk-relay-1" || len(p.Keys) != 0 { + t.Fatalf("relay keys %q %+v", p.Key, p.Keys) + } +} diff --git a/internal/provider/keys.go b/internal/provider/keys.go index 27b4c1aac..e0010c2ba 100644 --- a/internal/provider/keys.go +++ b/internal/provider/keys.go @@ -108,9 +108,6 @@ func AddKey(id, name, key string, proto Protocol) error { if err := keyProtocolOK(proto); err != nil { return err } - if key == "" { - return errors.New("paste the key to add") - } p, err := Find(id) if err != nil { return err @@ -118,10 +115,20 @@ func AddKey(id, name, key string, proto Protocol) error { if p.Account != nil { return errors.New("a signed-in account has no keys") } - for _, k := range p.KeyList() { - if k.ID == keyID(key) { - return fmt.Errorf("%s already has this key", p.Name) + // nothing pasted: the key the provider is asked with when the user has + // none (OpenCode Zen's public, #1795); for any other, nothing to add + anon := false + if key == "" { + if key = p.AnonymousKey(); key == "" { + return errors.New("paste the key to add") } + anon = true + } + if p.HasKey(key) { + if anon { + return fmt.Errorf("%s already has %s, the key its free models answer with none of yours", p.Name, key) + } + return fmt.Errorf("%s already has this key", p.Name) } if p.Key == "" { p.Key, p.KeyName, p.KeyProtocol = key, name, proto @@ -131,6 +138,28 @@ func AddKey(id, name, key string, proto Protocol) error { return Save(*p) } +// AnonymousKey is the key the provider is asked with when the user has +// none of their own, "" when it has no such key: OpenCode Zen's public, +// which its free models answer (normalize gives it to a Zen provider +// saved with no key). +func (p Provider) AnonymousKey() string { + if p.Preset == "opencode-zen" { + return OpenCodeAnonymousKey + } + return "" +} + +// HasKey reports whether key is one of the provider's, on or off. +func (p Provider) HasKey(key string) bool { + id := keyID(key) + for _, k := range p.KeyList() { + if k.ID == id { + return true + } + } + return false +} + // SplitKeys is the keys in text pasted at once: one a line, or separated // by commas, semicolons or spaces, trimmed of quotes, each once. func SplitKeys(text string) []string { diff --git a/internal/provider/opencode_zen_test.go b/internal/provider/opencode_zen_test.go index 5d0c9b361..0d5279acb 100644 --- a/internal/provider/opencode_zen_test.go +++ b/internal/provider/opencode_zen_test.go @@ -3,6 +3,7 @@ package provider import ( "encoding/json" "path/filepath" + "strings" "testing" "github.com/yetone/magpie/internal/catalog" @@ -83,3 +84,41 @@ func TestOpenCodeZenNeedsNoKey(t *testing.T) { t.Fatal("a relay with no key") } } + +// #1795: Add another key on an OpenCode Zen provider with a key of the +// user's own, with nothing pasted, adds public behind it, as a new Zen +// provider saved with no key has it; asked again, it says it has it. Kilo, +// whose free models need no key too, has no such key to add. +func TestZenAddKeyEmptyIsPublic(t *testing.T) { + isolate(t) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + zen, err := FromPreset("opencode-zen") + if err != nil { + t.Fatal(err) + } + zen.ID, zen.Key = "zen", "sk-own" + if err := Save(zen); err != nil { + t.Fatal(err) + } + if err := AddKey("zen", "", "", ""); err != nil { + t.Fatal(err) + } + p, _ := Find("zen") + if on := p.KeysOn(); len(on) != 2 || on[0].Key != "sk-own" || on[1].Key != OpenCodeAnonymousKey { + t.Fatalf("keys on %+v", on) + } + if err := AddKey("zen", "", "", ""); err == nil || !strings.Contains(err.Error(), "already has public") { + t.Fatalf("public twice: %v", err) + } + kilo, err := FromPreset("kilo") + if err != nil { + t.Fatal(err) + } + kilo.ID, kilo.Key = "kilo", "sk-kilo" + if err := Save(kilo); err != nil { + t.Fatal(err) + } + if err := AddKey("kilo", "", "", ""); err == nil { + t.Fatal("Kilo took an empty key") + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 4a76245b3..ac3376c1a 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -1063,8 +1063,8 @@ func normalize(p Provider) Provider { // OpenCode Zen serves its free models (-free) signed out, to the key // OpenCode itself sends then: a Zen provider saved with no key of its // own asks with that one - if p.Preset == "opencode-zen" && p.Key == "" { - p.Key = OpenCodeAnonymousKey + if anon := p.AnonymousKey(); anon != "" && p.Key == "" { + p.Key = anon } // a Zen provider saved before its preset had System One for Jev // (01huadalang: its Jev was asked as a chat model, and failed), an