From 972355cfbe7402eaf16548c1ce58041864b75ffb Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 30 Sep 2026 15:22:28 +0800 Subject: [PATCH] =?UTF-8?q?gui:=20a=20provider=20with=20no=20key=20opens?= =?UTF-8?q?=20its=20editor=20again,=20and=20a=20key's=20plan=20and=20balan?= =?UTF-8?q?ce=20show=20the=20last=20reading=20while=20the=20vendor=20is=20?= =?UTF-8?q?failing=20=E2=80=94=20willz=20on=20Discord:=20a=20local=20Ollam?= =?UTF-8?q?a=20added=20without=20a=20key=20only=20toggled=20its=20row=20wh?= =?UTF-8?q?en=20clicked,=20with=20"undefined=20is=20not=20an=20object=20(e?= =?UTF-8?q?valuating=20'copied=3F.key.set')".=20drawEditor=20set=20copied?= =?UTF-8?q?=20to=20false=20when=20the=20provider=20wasn't=20a=20copy,=20an?= =?UTF-8?q?d=20false=3F.key=20is=20undefined;=20it=20is=20null=20now.=20ch?= =?UTF-8?q?alice=20on=20Discord:=20a=20Command=20Code=20key's=20card=20rea?= =?UTF-8?q?d=20"Usage=20unavailable"=20=E2=80=94=20Command=20Code=20answer?= =?UTF-8?q?s=20billing/credits=20503=20at=20times,=20and=20a=20key's=20car?= =?UTF-8?q?ds,=20unlike=20a=20subscription's,=20kept=20no=20last=20reading?= =?UTF-8?q?:=20the=20balance=20showed=20the=20error=20and=20the=20plan=20c?= =?UTF-8?q?ard=20went.=20Both=20now=20keep=20the=20last=20good=20reading?= =?UTF-8?q?=20(quotas.json,=20under=20a=20sha256=20digest=20of=20the=20key?= =?UTF-8?q?,=20never=20the=20key)=20and=20show=20it=20with=20its=20time=20?= =?UTF-8?q?while=20the=20failure=20passes;=20a=20key=20never=20read=20stil?= =?UTF-8?q?l=20has=20no=20plan=20card.=20Tested=20with=20nokey-editor.test?= =?UTF-8?q?.cjs=20(an=20Ollama=20preset=20and=20a=20custom=20one=20without?= =?UTF-8?q?=20a=20key=20open=20in=20Chromium=20and=20WebKit,=20English=20a?= =?UTF-8?q?nd=20Chinese;=20fails=20without=20the=20change)=20and=20TestKey?= =?UTF-8?q?QuotasKeepLast=20(a=20fake=20Command=20Code=20going=20503,=20re?= =?UTF-8?q?adings=20reloaded=20from=20disk;=20fails=20without=20the=20chan?= =?UTF-8?q?ge).=20click-scroll=20passes;=20go=20vet,=20go=20build=20-tags?= =?UTF-8?q?=20nogui=20(darwin,=20GOOS=3Dlinux,=20GOOS=3Dwindows)=20and=20g?= =?UTF-8?q?o=20test=20-tags=20nogui=20./...=20pass=20(two=20Claude=20accou?= =?UTF-8?q?nt=20tests=20flaky=20under=20load=20pass=20alone).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gui/assets/app.js | 5 +- internal/gui/tests/README.md | 7 ++ internal/gui/tests/nokey-editor.test.cjs | 70 +++++++++++++++ internal/provider/balance.go | 3 +- internal/provider/key_quota_last_test.go | 104 +++++++++++++++++++++++ internal/provider/planquota.go | 14 ++- internal/provider/quota_last.go | 10 +++ 7 files changed, 210 insertions(+), 3 deletions(-) create mode 100644 internal/gui/tests/nokey-editor.test.cjs create mode 100644 internal/provider/key_quota_last_test.go diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index a631566bb..69a4b9c27 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -3577,7 +3577,10 @@ function drawEditor(p, presetID) { ed.append(...field(t("Endpoint"), endpoint, pr.endpointHint ? t(pr.endpointHint) : "")); } - const copied = !p && draft.copyOf && providers.providers.find((x) => x.id === draft.copyOf); + // null, not false, when there is none: false?.key is undefined, and a + // provider with no key read .set of it (willz: a local Ollama without a + // key opened no editor, its row just toggling) + const copied = (!p && draft.copyOf && providers.providers.find((x) => x.id === draft.copyOf)) || null; const key = input(draft.key || "", p?.key.set ? t("{masked} · paste a new key to replace it", { masked: p.key.masked }) : copied?.key.set ? t("{masked} · {name}'s key, or paste another", { masked: copied.key.masked, name: copied.name }) : t(pr?.noKey || p?.key.optional ? "optional for local servers" : "paste an API key"), "password"); key.oninput = () => { draft.key = key.value; }; key.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter" && isNew) save(); else if (e.key === "Escape") cancelEdit(); }; diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 4c7418c7d..4d1c10ecb 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -170,6 +170,13 @@ kiro-cli's own sign-in behind one of magpie's, then alone and first: its Remove is there both times, its title saying magpie only hides it and it shows again when Kiro signs in anew, and it posts login/forget; magpie's own account in use first has no Remove; in English and Chinese. + +`nokey-editor.test.cjs` opens two local Ollama providers saved with no key, +one from the preset and one custom, as /api/providers gives them: a click +on each row opens its editor (the key box saying one is optional) and +nothing throws, where the row only toggled; in Chromium and WebKit, English +and Chinese. + `old-webkit.test.cjs` holds the page to Safari 15.0, the WebKit macOS 12 can have (#220: a regex lookbehind in app.js, a syntax error before Safari 16.4, left the panel with its headings and nothing working). Every script in diff --git a/internal/gui/tests/nokey-editor.test.cjs b/internal/gui/tests/nokey-editor.test.cjs new file mode 100644 index 000000000..c0a2429f7 --- /dev/null +++ b/internal/gui/tests/nokey-editor.test.cjs @@ -0,0 +1,70 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A provider saved with no key — a local Ollama, from its preset or added as +// a custom provider — opens its editor on a click (willz on Discord: the row +// only toggled and WebKit said "undefined is not an object (evaluating +// 'copied?.key.set')"). The key box says one is optional, and nothing throws. +// The providers are what /api/providers gives for them. In English and Chinese. +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 local = (id, name, preset, icon) => ({ + id, name, icon, preset, host: "localhost:11434", chat: "http://localhost:11434/v1", responses: "", anthropic: "", catalog: "", + website: preset ? "https://ollama.com" : "", keysUrl: "", proxy: "", balanceToken: { takes: false, set: false }, + key: { set: false, masked: "", optional: true }, ready: true, chosen: [], fallback: [], routing: "", affinity: "", + models: [{ id: "qwen3:8b", name: "qwen3:8b", efforts: ["none", "low", "medium", "high"], given: true, images: false, on: true }], + exposed: 1, unlisted: false, off: false, fetched: "just now", agents: [], sponsored: false, keyList: [], +}); +const providers = { + providers: [local("ollama", "Ollama", "ollama", "ollama"), local("home-ollama", "Home Ollama", "", "")], + presets: [{ id: "ollama", name: "Ollama", icon: "ollama", kind: "local", noKey: true, chat: "http://localhost:11434/v1", anthropic: "http://localhost:11434", note: "your local models", website: "https://ollama.com", added: true }], + excluded: [], gateway: { running: true, window: true }, +}; + +function serve(lang) { + 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.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: { optional: "optional for local servers", cancel: "Cancel" }, zh: { optional: "本地服务可不填", cancel: "取消" } }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + test(`${engine} ${lang}: a provider with no key opens its editor`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=providers"); + for (const name of ["Ollama", "Home Ollama"]) { + await page.locator(".row.provider", { has: page.locator(".name", { hasText: new RegExp(`^${name}$`) }) }).click(); + const ed = page.locator(".editor"); + await ed.waitFor(); + assert.equal(await ed.locator(".ehead b").textContent(), name); + assert.equal(await ed.locator('input[type="password"]').first().getAttribute("placeholder"), w.optional); + assert.deepEqual(errors, [], `${name}: nothing throws`); + await ed.locator(".bar").getByRole("button", { name: w.cancel, exact: true }).click(); + await ed.waitFor({ state: "detached" }); + } + }); + } +} diff --git a/internal/provider/balance.go b/internal/provider/balance.go index 8a25e0378..b8469206d 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -754,7 +754,8 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { } else { q.Balance = amount } - out[i] = q + // the vendor failing a while shows the balance last read + out[i] = keepLast(q, keyTag("balance", j.p.Key)) }() } wg.Wait() diff --git a/internal/provider/key_quota_last_test.go b/internal/provider/key_quota_last_test.go new file mode 100644 index 000000000..5a82d7353 --- /dev/null +++ b/internal/provider/key_quota_last_test.go @@ -0,0 +1,104 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "sync/atomic" + "testing" +) + +// A Command Code key's plan and balance, read once, still show when +// billing/credits answers 503 for a while ("Couldn't verify your credit +// balance just now") — chalice on Discord: the key's card said only +// 暂时无法获取用量 — as a subscription's card does; a key that never +// answered has no plan card and its balance says why. +func TestKeyQuotasKeepLast(t *testing.T) { + isolate(t) + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + t.Setenv("PATH", h) + for _, v := range []string{"CLAUDE_CONFIG_DIR", "CODEX_HOME"} { + t.Setenv(v, "") + } + restart := func() { + lastQuotas.Lock() + lastQuotas.m, lastQuotas.loaded = nil, false + lastQuotas.Unlock() + ForgetBalances() + forgetPlanQuotas() + } + restart() + t.Cleanup(restart) + var down atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("X-Host")+r.URL.Path != "api.commandcode.ai/alpha/billing/credits" { + t.Errorf("asked %s%s", r.Header.Get("X-Host"), r.URL.Path) + w.WriteHeader(http.StatusNotFound) + return + } + if down.Load() || r.Header.Get("Authorization") != "Bearer cmd-a" { + w.WriteHeader(http.StatusServiceUnavailable) + w.Write([]byte(`{"error":{"message":"Couldn't verify your credit balance just now"}}`)) + return + } + w.Write([]byte(`{"credits":{"monthlyCredits":41.2,"purchasedCredits":5,"freeCredits":0}, + "windowLimits":{"limited":true,"fiveHour":{"used":3,"cap":10,"resetAt":4102444800000},"weekly":{"used":12,"cap":40,"resetAt":4102444800000}}}`)) + })) + defer srv.Close() + old := http.DefaultClient.Transport + http.DefaultClient.Transport = rewrite{srv} + t.Cleanup(func() { http.DefaultClient.Transport = old }) + + for _, p := range []Provider{ + {ID: "commandcode", Name: "commandCode", Preset: "commandcode", Key: "cmd-a", + Chat: "https://api.commandcode.ai/provider/v1", Responses: "https://api.commandcode.ai/provider/v1", Anthropic: "https://api.commandcode.ai/provider"}, + {ID: "cmd-new", Name: "Never read", Preset: "commandcode", Key: "cmd-b", Chat: "https://api.commandcode.ai/provider/v1"}, + } { + if err := Save(p); err != nil { + t.Fatal(err) + } + } + read := func() (plans, bals map[string]SubscriptionQuota) { + ForgetBalances() + forgetPlanQuotas() + plans, bals = map[string]SubscriptionQuota{}, map[string]SubscriptionQuota{} + for _, q := range PlanQuotas(context.Background()) { + plans[q.Provider] = q + } + for _, q := range KeyBalances(context.Background()) { + bals[q.Provider] = q + } + return + } + + plans, bals := read() + if q := plans["commandcode"]; len(q.Windows) != 2 || q.Windows[0].Used != 30 || q.AsOf != nil { + t.Fatalf("plan read: %+v", q) + } + if q := bals["commandcode"]; q.Balance != "$46.20" || q.AsOf != nil { + t.Fatalf("balance read: %+v", q) + } + + down.Store(true) + lastQuotas.Lock() + lastQuotas.m, lastQuotas.loaded = nil, false // read again from disk, as after a restart + lastQuotas.Unlock() + plans, bals = read() + if q := plans["commandcode"]; q.Error != "" || q.AsOf == nil || len(q.Windows) != 2 || q.Windows[1].Used != 30 || q.Name != "commandCode" { + t.Fatalf("plan while down: %+v", q) + } + if q := bals["commandcode"]; q.Error != "" || q.AsOf == nil || q.Balance != "$46.20" || q.Name != "commandCode" { + t.Fatalf("balance while down: %+v", q) + } + // a key never read: no plan card, and its balance says why + if q, ok := plans["cmd-new"]; ok { + t.Fatalf("plan of a key never read: %+v", q) + } + if q := bals["cmd-new"]; q.Error == "" || q.AsOf != nil { + t.Fatalf("balance of a key never read: %+v", q) + } +} diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index 24b073ea4..d87cb562d 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -365,9 +365,20 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota { plan, ws, err, team = tplan, tws, nil, true } } + // a vendor failing a while (Command Code answers billing/credits + // 503 at times) shows what was last read, as a subscription's + // card does, rather than no card or "Usage unavailable" + tag := keyTag("plan", j.key) switch { - case err != nil && !j.src.sure, err == nil && len(ws) == 0: + case err == nil && len(ws) == 0: return // a key with no plan + case err != nil && !j.src.sure: + // no plan, unless one was read before + q.Error = err.Error() + if q = keepLast(q, tag); q.AsOf != nil { + got[i] = &q + } + return case err != nil: q.Error = err.Error() default: @@ -376,6 +387,7 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota { q.Until, q.Renew = zhipuTerm(ctx, zcodeRoot(j.src.url), j.key) } } + q = keepLast(q, tag) got[i] = &q }() } diff --git a/internal/provider/quota_last.go b/internal/provider/quota_last.go index 2b1a3d9fa..fb856ce29 100644 --- a/internal/provider/quota_last.go +++ b/internal/provider/quota_last.go @@ -6,6 +6,8 @@ package provider // A reading that comes back replaces it at once. import ( + "crypto/sha256" + "encoding/hex" "encoding/json" "os" "path/filepath" @@ -40,6 +42,14 @@ func lastQuotasPath() string { return filepath.Join(filepath.Dir(Path()), "quota // rate limiting, failing or out of reach. A sign-in gone bad is not one. var passing = regexp.MustCompile(`(?i)rate.?limit|too many requests|429|internal server error|bad gateway|service unavailable|gateway timeout|deadline exceeded|timeout|timed out|connection (refused|reset)|no such host|network is unreachable|EOF|asks again`) +// keyTag names a key's card among the last readings, by what it is (a +// plan's windows, a balance) and a digest of the key, never the key: a +// key's card has no user to go by. +func keyTag(kind, key string) string { + sum := sha256.Sum256([]byte(key)) + return kind + " " + hex.EncodeToString(sum[:8]) +} + // keepLast is q, or the last reading of its account when q failed in // passing; a good reading is kept for next time. func keepLast(q SubscriptionQuota, user string) SubscriptionQuota {