From 40b7f8efde3ff2778d1f8b8625fa45fb226e140f Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 11 Oct 2026 00:05:23 +0800 Subject: [PATCH] provider, gui: an OpenCode Go key whose windows can't be read says why on its card, not "Allowance unavailable" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X report (sakulalalalalal, tweet 2108933449612775438): three OpenCode Go keys each read 暂时无法获取额度 while Codex usage showed fine. The card said only the generic text, and the reason sat in a hover tooltip a phone can't reach. Why a key reads none (opencode's console, zen/go/v1/usage.ts): Go's Lite row is looked up by the key's workspace AND the member who made it, so a key made by another member, or in another workspace, gets 403 EntitlementError "OpenCode Go subscription required." even when the workspace has Go. The owner's own sk- key answers exactly that. - planWindows: an OpenCode 403 says where Go belongs and which key to use; a 401 says the key was deleted or mistyped; any other error status carries the vendor's own message (vendorSaid: error.message, a string error, or message, capped at 200 chars), e.g. the new inference service's 503 "Inference routing is unavailable". - readOpenCodeGo: a 200 with no rolling/weekly/monthly window names the reply's field names (shapeOf, two levels, no values), since oc_sk_ keys and migrated workspaces are now served by a new service whose success shape we can't read yet. - quotaError (app.js): the three cases get their own card text, with zh, zh-TW, ja and de. Fixtures are the real 403/401 bodies from opencode.ai and the 503 body from opencode's inference-proxy.ts. Run: TestOpenCodeGoSaysWhyNoWindows fails on the old planquota.go (8 messages) and passes now; opencode-go-quota-error.test.cjs (chromium + webkit, en/zh/zh-TW/ja/de, 440px) fails without the app.js change; i18n-keys, balance-fix, quota-balance-error pass; go test ./... (provider timed out at 10m under other sessions' suites, then passed alone in 263s), gofmt -l, go vet (darwin, linux -tags nogui, windows) clean. --- internal/gui/assets/app.js | 6 ++ internal/gui/assets/i18n.js | 16 +++- .../tests/opencode-go-quota-error.test.cjs | 66 ++++++++++++++++ internal/provider/planquota.go | 77 ++++++++++++++++++- internal/provider/planquota_test.go | 47 +++++++++++ 5 files changed, 204 insertions(+), 8 deletions(-) create mode 100644 internal/gui/tests/opencode-go-quota-error.test.cjs diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 5e1f22b64..1c687185a 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11636,6 +11636,12 @@ function quotaError(err) { // card sentence, so the sign-in errors — which name the address themselves — // and "could not be read" are left alone. if (/^this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started$/.test(err)) return t("ZCode: no GLM Coding Plan, and no free Start Plan — subscribe to a GLM Coding Plan to use this account"); + // an OpenCode Go key's windows (planWindows, planquota.go): Go is the + // subscribing member's, in their workspace, so a key from anyone else + // reads none — said with the way out, as a phone can't hover for it + if (/^this key has no OpenCode Go subscription/.test(err)) return t("No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace"); + if (/^OpenCode didn't take this key/.test(err)) return t("OpenCode didn't take this key — paste a current one in the provider's settings"); + if (/^OpenCode Go's reply has no rolling/.test(err)) return t("OpenCode Go answered in a form magpie doesn't read — hover for what it sent"); // a remote magpie's card (remote_quotas.go) if (/^nothing read on that magpie yet/.test(err)) return t("Nothing read on that computer yet — refresh this card to have it read"); if (/^remote magpie doesn't share its quotas/.test(err)) return t("That computer's magpie doesn't share its quotas yet — update magpie there"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 983d9876c..0ab6efd8b 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2542,7 +2542,9 @@ const I18N = { "5 hours": "5 小时", "24 hours": "24 小时", "MCP · Month": "MCP · 本月", - "this key has no OpenCode Go subscription": "这个 Key 没有订阅 OpenCode Go", + "No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "这个 Key 没有 OpenCode Go — 请用订阅者本人在该工作区创建的 Key", + "OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode 不认这个 Key — 请在提供商设置里换一个有效的 Key", + "OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go 返回的格式 magpie 读不懂 — 悬停查看它返回了什么", "7 days · Opus": "7 天 · Opus", "7 days · Sonnet": "7 天 · Sonnet", "Cursor Models": "Cursor 模型", @@ -6614,7 +6616,9 @@ const I18N = { "5 hours": "5 小時", "24 hours": "24 小時", "MCP · Month": "MCP · 本月", - "this key has no OpenCode Go subscription": "這個 Key 沒有訂閱 OpenCode Go", + "No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "這個 Key 沒有 OpenCode Go — 請用訂閱者本人在該工作區建立的 Key", + "OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode 不認這個 Key — 請在供應商設定裡換一個有效的 Key", + "OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go 回傳的格式 magpie 讀不懂 — 懸停查看它回傳了什麼", "7 days · Opus": "7 天 · Opus", "7 days · Sonnet": "7 天 · Sonnet", "Cursor Models": "Cursor 模型", @@ -10690,7 +10694,9 @@ const I18N = { "5 hours": "5 時間", "24 hours": "24 時間", "MCP · Month": "MCP · 月", - "this key has no OpenCode Go subscription": "このキーには OpenCode Go のサブスクリプションがありません", + "No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "このキーには OpenCode Go がありません — 契約したメンバー本人がそのワークスペースで作ったキーを使ってください", + "OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode がこのキーを受け付けませんでした — プロバイダ設定で有効なキーを貼り付けてください", + "OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go の応答は magpie が読めない形式です — ホバーで内容を表示", "7 days · Opus": "7 日 · Opus", "7 days · Sonnet": "7 日 · Sonnet", "Cursor Models": "Cursor モデル", @@ -14765,7 +14771,9 @@ const I18N = { "5 hours": "5 Stunden", "24 hours": "24 Stunden", "MCP · Month": "MCP · Monat", - "this key has no OpenCode Go subscription": "dieser Schlüssel hat kein OpenCode-Go-Abo", + "No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "Kein OpenCode Go auf diesem Schlüssel — nimm einen Schlüssel, den das abonnierende Mitglied in diesem Workspace erstellt hat", + "OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode hat diesen Schlüssel nicht angenommen — füge in den Anbieter-Einstellungen einen gültigen ein", + "OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go hat in einer Form geantwortet, die magpie nicht liest — für den Inhalt darüberfahren", "7 days · Opus": "7 Tage · Opus", "7 days · Sonnet": "7 Tage · Sonnet", "Cursor Models": "Cursor-Modelle", diff --git a/internal/gui/tests/opencode-go-quota-error.test.cjs b/internal/gui/tests/opencode-go-quota-error.test.cjs new file mode 100644 index 000000000..0f1fb3179 --- /dev/null +++ b/internal/gui/tests/opencode-go-quota-error.test.cjs @@ -0,0 +1,66 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// An OpenCode Go key whose windows can't be read says why on its card, in +// every language, rather than "Allowance unavailable": a phone can't hover +// for the reason (planWindows, planquota.go). +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 server(lang) { + 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 = ${JSON.stringify({ 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({ 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/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 }); + }; +} + +// the errors planWindows gives, as built from OpenCode's real replies +const errs = [ + "this key has no OpenCode Go subscription: Go belongs to the member who subscribed, in that workspace, so use a key that member made there (opencode.ai, the workspace's API Keys)", + "OpenCode didn't take this key (401 Unauthorized: Unauthorized): it was deleted, or is mistyped", + "OpenCode Go's reply has no rolling, weekly or monthly window: fields plan, usage.fiveHour", +]; +const keys = [ + "No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace", + "OpenCode didn't take this key — paste a current one in the provider's settings", + "OpenCode Go answered in a form magpie doesn't read — hover for what it sent", +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine}: an OpenCode Go key's card says why it has no windows (${lang})`, 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: 440, height: 760 } })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang)); + await page.goto("http://magpie.test/?view=providers"); + await page.waitForFunction(() => typeof quotaError === "function"); + const said = await page.evaluate((errs) => errs.map((e) => quotaError(e)), errs); + const want = await page.evaluate((keys) => keys.map((k) => t(k)), keys); + const generic = await page.evaluate(() => t("Allowance unavailable")); + for (let i = 0; i < errs.length; i++) { + assert.equal(said[i], want[i], errs[i]); + assert.notEqual(said[i], generic); + if (lang !== "en") assert.notEqual(said[i], keys[i], `${lang} has its own words for: ${keys[i]}`); + } + // a 503 or anything else is still the vendor's words on hover only + assert.equal(await page.evaluate(() => quotaError("503 Service Unavailable: Inference routing is unavailable. Please retry later.")), generic); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index c1b0a3489..fbb5bb8fa 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -15,6 +15,7 @@ import ( "io" "math" "net/http" + "slices" "strconv" "strings" "sync" @@ -171,11 +172,43 @@ func readOpenCodeGo(b []byte) (string, []QuotaWindow, error) { out = append(out, q) } if len(out) == 0 { - return "", nil, fmt.Errorf("no usage in the reply") + return "", nil, fmt.Errorf("OpenCode Go's reply has no rolling, weekly or monthly window: %s", shapeOf(b)) } return "", out, nil } +// shapeOf names the fields of a JSON reply magpie couldn't read, two +// levels down, without their values: enough to see what the vendor sends +// now, with nothing of the account in it. +func shapeOf(b []byte) string { + var top map[string]json.RawMessage + if json.Unmarshal(b, &top) != nil { + if len(b) == 0 { + return "an empty reply" + } + return "a reply that isn't a JSON object" + } + var names []string + for k, v := range top { + var in map[string]json.RawMessage + if json.Unmarshal(v, &in) == nil && len(in) > 0 { + for k2 := range in { + names = append(names, k+"."+k2) + } + continue + } + names = append(names, k) + } + if len(names) == 0 { + return "an empty object" + } + slices.Sort(names) + if len(names) > 12 { + names = append(names[:12], "…") + } + return "fields " + strings.Join(names, ", ") +} + // readMiniMaxPlan reads MiniMax's /v1/token_plan/remains (#387): // // {"model_remains":[{"model_name":"general", @@ -462,15 +495,51 @@ func planWindows(ctx context.Context, src planQuotaSource, key string) (plan str } defer res.Body.Close() b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + openCode := strings.Contains(src.url, "opencode.ai") switch { - case res.StatusCode == http.StatusForbidden && strings.Contains(src.url, "opencode.ai"): - return "", nil, fmt.Errorf("this key has no OpenCode Go subscription") + case res.StatusCode == http.StatusForbidden && openCode: + // OpenCode keeps Go on the member who subscribed, in the workspace + // they subscribed in, and asks for it by the key's own member and + // workspace (zen/go/v1/usage.ts in sst/opencode): a key another + // member made, or one from another workspace, has none + return "", nil, fmt.Errorf("this key has no OpenCode Go subscription: Go belongs to the member who subscribed, in that workspace, so use a key that member made there (opencode.ai, the workspace's API Keys)") + case res.StatusCode == http.StatusUnauthorized && openCode: + return "", nil, fmt.Errorf("OpenCode didn't take this key (%s): it was deleted, or is mistyped", vendorSaid(b, res.Status)) case res.StatusCode >= 300: - return "", nil, fmt.Errorf("%s", res.Status) + return "", nil, fmt.Errorf("%s", vendorSaid(b, res.Status)) } return src.read(b) } +// vendorSaid is the status, and the reason in a vendor's error body +// ({"error":{"message":…}} or {"message":…}) when it gives one, so a card +// that can't be read says why, not only a number. +func vendorSaid(b []byte, status string) string { + var e struct { + Error json.RawMessage `json:"error"` + Message string `json:"message"` + } + if json.Unmarshal(b, &e) != nil { + return status + } + msg := e.Message + var inner struct { + Message string `json:"message"` + } + if json.Unmarshal(e.Error, &inner) == nil && inner.Message != "" { + msg = inner.Message + } else if s := ""; json.Unmarshal(e.Error, &s) == nil && s != "" { + msg = s + } + if msg = strings.TrimSpace(msg); msg == "" { + return status + } + if len(msg) > 200 { + msg = msg[:200] + "…" + } + return status + ": " + msg +} + // planKeyWindows asks the vendor for the plan key is on and its windows: // a Zhipu or Z.ai key with no plan of its own is a team's, whose windows // are asked with type=2 (zcode_team.go), and team says so. diff --git a/internal/provider/planquota_test.go b/internal/provider/planquota_test.go index ec0616438..c78888a6a 100644 --- a/internal/provider/planquota_test.go +++ b/internal/provider/planquota_test.go @@ -415,3 +415,50 @@ func TestReadKimiCode(t *testing.T) { t.Fatal("nothing read") } } + +// An OpenCode Go key whose windows can't be read says why, with the way +// out (sakulalalalalal on X: three Go keys, each "Allowance unavailable" +// and nothing more). The bodies are OpenCode's own, as zen/go/v1/usage +// answered on 2026-10-10: a key whose member has no Go, and a key it +// doesn't know. +func TestOpenCodeGoSaysWhyNoWindows(t *testing.T) { + bodies := map[string]struct { + status int + body string + }{ + "/nogo": {http.StatusForbidden, `{"type":"error","error":{"type":"EntitlementError","message":"OpenCode Go subscription required."}}`}, + "/unknown": {http.StatusUnauthorized, `{"type":"error","error":{"type":"AuthError","message":"Unauthorized"}}`}, + "/down": {http.StatusServiceUnavailable, `{"error":{"type":"api_error","message":"Inference routing is unavailable. Please retry later."}}`}, + "/other": {http.StatusOK, `{"usage":{"fiveHour":{"used":3}},"plan":"go"}`}, + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b := bodies[r.URL.Path] + w.WriteHeader(b.status) + w.Write([]byte(b.body)) + })) + defer srv.Close() + read := func(path string) string { + // the vendor's host, so the OpenCode rules apply + _, _, err := planWindows(context.Background(), planQuotaSource{url: srv.URL + path + "?opencode.ai", bearer: true, read: readOpenCodeGo}, "k") + if err == nil { + t.Fatalf("%s read as windows", path) + } + return err.Error() + } + for path, want := range map[string][]string{ + "/nogo": {"no OpenCode Go subscription", "member who subscribed"}, + "/unknown": {"OpenCode didn't take this key", "401 Unauthorized: Unauthorized"}, + "/down": {"503 Service Unavailable", "Inference routing is unavailable"}, + "/other": {"no rolling, weekly or monthly window", "usage.fiveHour", "plan"}, + } { + got := read(path) + for _, w := range want { + if !strings.Contains(got, w) { + t.Errorf("%s: %q doesn't say %q", path, got, w) + } + } + } + if got := read("/other"); strings.Contains(got, "3") || strings.Contains(got, "go\"") { + t.Errorf("an unread reply's values are kept out of the error: %q", got) + } +}