gui: a provider with no key opens its editor again, and a key's plan and balance show the last reading while the vendor is failing — willz on Discord: a local Ollama added without a key only toggled its row when clicked, with "undefined is not an object (evaluating 'copied?.key.set')". drawEditor set copied to false when the provider wasn't a copy, and false?.key is undefined; it is null now. chalice on Discord: a Command Code key's card read "Usage unavailable" — Command Code answers billing/credits 503 at times, and a key's cards, unlike a subscription's, kept no last reading: the balance showed the error and the plan card went. Both now keep the last good reading (quotas.json, under a sha256 digest of the key, never the key) and show it with its time while the failure passes; a key never read still has no plan card. Tested with nokey-editor.test.cjs (an Ollama preset and a custom one without a key open in Chromium and WebKit, English and Chinese; fails without the change) and TestKeyQuotasKeepLast (a fake Command Code going 503, readings reloaded from disk; fails without the change). click-scroll passes; go vet, go build -tags nogui (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui ./... pass (two Claude account tests flaky under load pass alone).

This commit is contained in:
yetone
2026-09-30 15:22:28 +08:00
parent 190248d204
commit 972355cfbe
7 changed files with 210 additions and 3 deletions
+4 -1
View File
@@ -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(); };
+7
View File
@@ -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
+70
View File
@@ -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" });
}
});
}
}
+2 -1
View File
@@ -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()
+104
View File
@@ -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)
}
}
+13 -1
View File
@@ -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
}()
}
+10
View File
@@ -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 {