From c483feadfd88a5b8de8541de0567f3856822bde5 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 13:33:47 +0800 Subject: [PATCH] usage: OpenCode Zen's card says OpenCode tells no key its balance, and Go at /inference/go gets its plan card (ttmrmx on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ttmrmx on X: "magpie 里 OpenCode Zen/Go 这个供应商的余额卡片不显示". Cause, two parts: - An OpenCode Zen key (opencode.ai/zen, /inference) had no balance source, so KeyBalances skipped it without a word and the Usage page drew no card. OpenCode has no balance a key can read. In sst/opencode, packages/console/app/src/lib/inference-proxy.ts serves only the model routes. /zen/v1/balance, /zen/v1/credits, /zen/v1/usage and /zen/v1/billing all 404, and billing.mdx shows the credits only in the console (Overview -> Credits, to owners and admins). No endpoint was invented. - planQuotaSourceOf matched only /zen/go. models.dev now gives Go as opencode.ai/inference/go/openai/v1, so a Go provider saved there got no plan card at all. openCodeGateway() now tells go/zen/other (custom is the user's own) for both URL shapes, and Go at either one reads https://opencode.ai/zen/go/v1/usage. What changed: - A Zen key's card now carries errOpenCodeNoBalance and seeAt (https://opencode.ai/console). It reads "OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits", with an "Open the console ↗" button. That is one button with the needsAccessKey "Open settings" one (#1821), so the bytes stay small. - A provider with its own BalanceURL is still asked that URL. - Strings are in zh, zh-TW, ja and de. - coreScriptBudget: rebased onto f76201a84, whose 1,469,000 already holds the card (~390 bytes; the tray panel draws it too); unchanged. TestCoreScriptBudget re-run after the rebase: ok. - Plugins: there is no OpenCode built-in mover, and this is a key provider, so the change is all in magpie. Run, all on this tree (HEAD 94919109c): - Old code: TestOpenCodeZenSaysItTellsNoBalance (adapted), TestPlanQuotaSource, TestPlanQuotas and opencode-zen-balance.test.cjs all fail on a detached HEAD checkout; they pass here. - Real use, in a sandbox (go build -tags dev, sandbox HOME, ports 3486/3487, never the live config), with the owner's OpenCode key copied read-only: - /api/usage/quotas gives the Zen variant the new error and seeAt. - Both Go providers (/zen/go and /inference/go) request the usage URL and show the vendor's real 401 "This API key has expired". The owner's key is expired, so no live Go reading was seen. There's no Zen account with credit either, so the console page itself wasn't checked against a balance. - A Playwright screenshot shows the card. Clicking the button posted /api/open with the console URL. - go test -p 4 ./... -timeout 45m: every package ok except these. - internal/agent timed out at 45m under load; alone it is ok in 1184s (#2723, #2544). - gateway TestClaudeAccountsSpentFallBackToCodex and TestMaxRPMWaitsForRoomInTheMinute pass alone -count=3 (#2858/#2859, #1791). - gui TestCoreScriptBudget was mine; fixed above. - gofmt -l clean. go vet: darwin all; GOOS=windows provider and gui; GOOS=linux provider (gui needs cgo/wails for linux). - GUI, chromium + webkit, en/zh/zh-TW/ja/de at 900 and 420px, 2 workers. The full suite was stopped at ~416 tests (load 160-500). Its reds were in agent-*/account-* files, which this doesn't touch (#1544, #1949). - The targeted set passed: quota-*, balance-*, key-balance-card, opencode-*, usage-access-key-card, gui-de/ja/zh-tw, i18n-keys, panel-usage, panel-balance-order, panel-quota-refresh, tray-usages, usage-quota-head, glm/plugin-quota-error, gateway-key-quotas, usage-remote-cards, usage-card-refresh and deprecated-subscriptions. - Exceptions: gateway-key-quotas (ja launch timeout) and panel-usage (zh) were red under load and pass alone. - quota-name-translated and quota-count-wrap (webkit) are red alone here and on origin/main f76201a84, with the same asserts. That is #2228, commented. --- internal/gui/assets/app.js | 13 ++- internal/gui/assets/i18n.js | 8 ++ internal/gui/core_budget_test.go | 2 +- .../gui/tests/opencode-zen-balance.test.cjs | 101 ++++++++++++++++ internal/provider/balance.go | 44 ++++++- internal/provider/opencode_balance_test.go | 109 ++++++++++++++++++ internal/provider/opencode_endpoints.go | 26 +++++ internal/provider/planquota.go | 10 +- internal/provider/planquota_test.go | 21 +++- internal/provider/subscription_usage.go | 4 + 10 files changed, 322 insertions(+), 16 deletions(-) create mode 100644 internal/gui/tests/opencode-zen-balance.test.cjs create mode 100644 internal/provider/opencode_balance_test.go diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 68c997e1b..3f5a534cc 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13121,6 +13121,8 @@ function balanceError(err) { if (/takes the API key, not the access token/.test(err)) return t("The Balance URL …/api/usage/token takes the API key, not the access token — set it to …/api/user/self in the provider's settings"); if (/takes the API key, not the login token/.test(err)) return t("The Balance URL …/v1/usage takes the API key, not the login token — set it to …/api/v1/user/profile in the provider's settings"); if (/New-Api-User/i.test(err)) return t("Add the header New-Api-User = your user ID (shown in the site's personal settings) to the provider's Headers"); + // errOpenCodeNoBalance: not a reading that failed + if (/^OpenCode tells no API key its balance/.test(err)) return t("OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits"); return ""; } @@ -17794,12 +17796,13 @@ function quotaWindows(sub) { e.title = sub.error; // read again from here too: a failed reading is the one most wanted e.prepend(quotaRefresh(sub)); - // a plan that needs the access key the provider hasn't: the way to - // give it, one click away (#1821) - if (sub.needsAccessKey && sub.provider) { - const go = el("button", "quota-fix", t("Open settings")); + // one click away: the access key a plan needs (#1821), or the + // vendor's page for a balance it tells no key (seeAt, Zen's console) + const key = sub.needsAccessKey && sub.provider; + if (key || sub.seeAt) { + const go = el("button", "quota-fix", t(key ? "Open settings" : "Open the console ↗")); go.type = "button"; - go.onclick = (ev) => { ev.stopPropagation(); openProvider(sub.provider); }; + go.onclick = (ev) => { ev.stopPropagation(); key ? openProvider(sub.provider) : api("open", { url: sub.seeAt }).catch(() => {}); }; e.append(" ", go); } return e; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7d11c7fee..aae6e937a 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2721,6 +2721,8 @@ const I18N = { "MCP · Month": "MCP · 本月", "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 doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode 不会把余额告诉 API Key — 请在 OpenCode 控制台的 Overview → Credits 查看 Zen 的余额", + "Open the console ↗": "打开控制台 ↗", "{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} 不认这个 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", @@ -6422,6 +6424,8 @@ const I18N = { "MCP · Month": "MCP · 本月", "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 doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode 不會把餘額告訴 API Key — 請在 OpenCode 主控台的 Overview → Credits 查看 Zen 的餘額", + "Open the console ↗": "開啟主控台 ↗", "{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} 不認這個 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", @@ -10128,6 +10132,8 @@ const I18N = { "MCP · Month": "MCP · 月", "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 doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode は API キーに残高を教えません — Zen のクレジットは OpenCode コンソールの Overview → Credits で確認してください", + "Open the console ↗": "コンソールを開く ↗", "{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} がこのキーを受け付けませんでした — 期限切れ、削除済み、または入力ミスです。プロバイダ設定で有効なキーを貼り付けてください", "OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go の応答は magpie が読めない形式です — ホバーで内容を表示", "7 days · Opus": "7 日 · Opus", @@ -13844,6 +13850,8 @@ const I18N = { "MCP · Month": "MCP · Monat", "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 doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode nennt einem API-Schlüssel sein Guthaben nicht — sieh Zens Guthaben in der OpenCode-Konsole unter Overview → Credits", + "Open the console ↗": "Konsole öffnen ↗", "{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} hat diesen Schlüssel nicht angenommen — er ist abgelaufen, gelöscht oder vertippt; 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", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index c5f936f92..26823042d 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -16,7 +16,7 @@ import ( // raises them and says why in its commit. const ( appScriptBudget = 1_269_000 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397) - coreScriptBudget = 1_469_000 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5% + coreScriptBudget = 1_469_000 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/tests/opencode-zen-balance.test.cjs b/internal/gui/tests/opencode-zen-balance.test.cjs new file mode 100644 index 000000000..4b7dfbba1 --- /dev/null +++ b/internal/gui/tests/opencode-zen-balance.test.cjs @@ -0,0 +1,101 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// ttmrmx on X: OpenCode Zen's balance card wasn't shown at all. OpenCode +// tells no API key its balance (Zen's credits are on the console only), +// so the card now says that, in the user's language, with the reason in +// its tooltip and a button that opens the console (seeAt). The editor's +// "Check balance" says the same (balanceError). No backend, the API is +// faked here. +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"); +// errOpenCodeNoBalance's words (internal/provider/balance.go) +const ZEN = "OpenCode tells no API key its balance: Zen's pay-as-you-go credits are shown only in the OpenCode console (https://opencode.ai/console, Overview → Credits, to the workspace's owners and admins)"; +const CONSOLE = "https://opencode.ai/console"; + +const quotas = [ + { provider: "opencode-zen", name: "OpenCode Zen", icon: "opencode", error: ZEN, seeAt: CONSOLE, windows: [] }, + { provider: "kimi", name: "Kimi", icon: "kimi-color", error: "HTTP 503", windows: [] }, +]; + +function serve(lang, opened) { + const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" }; + return async (route) => { + const req = route.request(); + const url = new URL(req.url()); + const json = (body) => route.fulfill({ json: body }); + 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({ agents: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/usage/quotas") return json(quotas); + if (url.pathname === "/api/usage/quotas/history") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/open") { + opened.push(JSON.parse(req.postData() || "{}").url); + return route.fulfill({ status: 204, body: "" }); + } + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const said = "OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits"; +const button = "Open the console ↗"; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [900, 420]) { + test(`${engine} ${lang} ${width}px: an OpenCode Zen key's card says OpenCode tells no balance and opens the console`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const errors = []; + const opened = []; + const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.addInitScript(() => { + window.__opened = []; + window.open = (url) => { window.__opened.push(url); return null; }; + }); + await page.route("**/*", serve(lang, opened)); + // app.js is large: its first load on a busy machine takes more than 5s + await page.goto("http://magpie.test/?view=usage", { timeout: 30000 }); + + const err = page.locator(".subscription-card", { hasText: "OpenCode Zen" }).locator(".subscription-error"); + await err.waitFor(); + assert.equal(await err.getAttribute("title"), ZEN, "the reason in the tooltip"); + const [words, open, generic] = await page.evaluate(([a, b]) => [t(a), t(b), t("Allowance unavailable")], [said, button]); + if (lang !== "en") { + assert.notEqual(words, said, `${lang} has its own words for the card`); + assert.notEqual(open, button, `${lang} has its own words for the button`); + } + assert.ok((await err.textContent()).includes(words), await err.textContent()); + assert.ok(!(await err.textContent()).includes(generic)); + const go = err.locator(".quota-fix"); + assert.equal((await go.textContent()).trim(), open); + // a card that failed for another reason has no such button + assert.equal(await page.locator(".subscription-card", { hasText: "Kimi" }).locator(".quota-fix").count(), 0); + const [e, b] = [await err.boundingBox(), await go.boundingBox()]; + assert.ok(e.x + e.width <= width && b.x + b.width <= width, "the error and its button fit the page"); + + await go.click(); + // in a browser api("open") is window.open (the app posts /api/open) + await page.waitForFunction(() => window.__opened.length > 0); + assert.deepEqual(await page.evaluate(() => window.__opened), [CONSOLE]); + assert.deepEqual(opened, []); + assert.equal(new URL(page.url()).searchParams.get("view"), "usage", "the page stays where it was"); + // the editor's Check balance says the same + assert.equal(await page.evaluate((z) => balanceError(z), ZEN), words); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/balance.go b/internal/provider/balance.go index 98d491551..a55962093 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -1211,6 +1211,10 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [ ctx = p.Via(ctx) p = keyQueryOf(p) src, ok := balanceSourceOf(p) + if !ok && p.Account == nil && p.Key != "" && openCodeZen(p) { + // a balance the vendor keeps from the key: said so, not left out + return "", nil, nil, nil, true, errOpenCodeNoBalance + } if !ok || p.Account != nil || p.Key == "" { return "", nil, nil, nil, false, nil } @@ -1309,6 +1313,35 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [ return amount, nil, split, nil, true, err } +// OpenCodeConsole is where OpenCode shows a workspace's credits: the +// Credits card on the console's Overview, to its owners and admins. +const OpenCodeConsole = "https://opencode.ai/console" + +// errOpenCodeNoBalance is a Zen key's balance, which OpenCode tells no +// key: Zen's routes (/zen/v1, the inference API's /inference/v1) have no +// usage or balance query, only Go's /zen/go/v1/usage, which tells Go's +// windows and not the credits (proxyInference's paths in sst/opencode's +// packages/console/app/src/lib/inference-proxy.ts; /zen/v1/usage and +// /inference/v1/usage answer 404), and its docs give the balance only on +// the console's Credits card (console/billing.mdx, "Check your balance"). +// The card used to be left out unsaid (ttmrmx on X). +var errOpenCodeNoBalance = errors.New("OpenCode tells no API key its balance: Zen's pay-as-you-go credits are shown only in the OpenCode console (" + OpenCodeConsole + ", Overview → Credits, to the workspace's owners and admins)") + +// openCodeZen says p is at OpenCode Zen, whose credits OpenCode keeps from +// the key, and not at Go, whose windows are its card (planQuotaSourceOf). +func openCodeZen(p Provider) bool { + zen := false + for _, b := range []string{p.Chat, p.Responses, p.Anthropic} { + switch openCodeGateway(b) { + case "go": + return false + case "zen": + zen = true + } + } + return zen +} + // balanceMethodOf is the HTTP method a Balance URL is asked with: GET // when none is named, else GET or POST in any case. Another is an error, // never a GET in its place. @@ -1409,11 +1442,12 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { continue } src, ok := balanceSourceOf(p) - if !ok && !clineKeyCard(p) { + zen := !ok && openCodeZen(p) + if !ok && !clineKeyCard(p) && !zen { continue } others := 0 - if src.token != "" { + if src.token != "" || zen { // the account's balance is the same whichever key asks jobs = append(jobs, job{p, ""}) continue @@ -1473,6 +1507,12 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { if errors.Is(err, errNoBalance) { return // a reply with no balance for this key: no card } + if errors.Is(err, errOpenCodeNoBalance) { + // nothing to read or keep: where the balance is shown + q.Error, q.SeeAt = err.Error(), OpenCodeConsole + out[i] = q + return + } if err != nil { q.Error = err.Error() } else { diff --git a/internal/provider/opencode_balance_test.go b/internal/provider/opencode_balance_test.go new file mode 100644 index 000000000..4558a9f02 --- /dev/null +++ b/internal/provider/opencode_balance_test.go @@ -0,0 +1,109 @@ +package provider + +import ( + "context" + "errors" + "net/http" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/agentenv" +) + +// noVendor answers no request and keeps what was asked: OpenCode tells +// a Zen key no balance, so there is nothing to ask. +type noVendor struct{ asked *[]string } + +func (n noVendor) RoundTrip(r *http.Request) (*http.Response, error) { + *n.asked = append(*n.asked, r.URL.String()) + return nil, errors.New("no network in this test") +} + +// ttmrmx on X: an OpenCode Zen key's balance card wasn't shown at all. +// OpenCode tells no key the workspace's credits, so the card says that, +// and where they are shown, on every surface that asks a key's balance: +// the Usage page's cards (KeyBalances) and the editor, TUI and CLI +// (Balance). One card a provider, however many keys: the credits are the +// workspace's. +func TestOpenCodeZenSaysItTellsNoBalance(t *testing.T) { + isolate(t) + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", 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 agentenv.Vars { + t.Setenv(v, "") + } + keyBalanceCache.data = nil + t.Cleanup(func() { keyBalanceCache.data = nil }) + old := http.DefaultClient.Transport + var asked []string + http.DefaultClient.Transport = noVendor{&asked} + t.Cleanup(func() { http.DefaultClient.Transport = old }) + + zen := Provider{ID: "opencode-zen", Name: "OpenCode Zen", Chat: "https://opencode.ai/zen/v1", Responses: "https://opencode.ai/zen/v1", + Anthropic: "https://opencode.ai/zen", Key: "zen-a", Keys: []KeyAccount{{Key: "zen-a"}, {Key: "zen-b", Name: "spare"}}} + for _, p := range []Provider{ + zen, + // Zen at the inference API, models.dev's URL for it + {ID: "zen-inference", Name: "Zen", Chat: "https://opencode.ai/inference/openai/v1", Key: "zen-c"}, + // OpenCode Go: its plan windows are its card, not a balance + {ID: "opencode-go", Name: "OpenCode Go", Chat: "https://opencode.ai/zen/go/v1", Key: "go-k"}, + // a provider of the user's own at the inference API: its vendor's + {ID: "custom", Name: "Custom", Chat: "https://opencode.ai/inference/custom/acme/v1", Key: "c"}, + } { + if err := Save(p); err != nil { + t.Fatal(err) + } + } + var lines []string + for _, q := range KeyBalances(context.Background()) { + lines = append(lines, q.Provider+"|"+q.User+"|"+q.Balance+"|"+q.SeeAt) + if !strings.HasPrefix(q.Error, "OpenCode tells no API key its balance") || !strings.Contains(q.Error, "Overview → Credits") { + t.Errorf("%s's card says %q", q.Provider, q.Error) + } + } + want := "opencode-zen|||https://opencode.ai/console,zen-inference|||https://opencode.ai/console" + if got := strings.Join(lines, ","); got != want { + t.Fatalf("cards:\n%s\nwant\n%s", got, want) + } + if len(asked) != 0 { + t.Fatalf("asked %v", asked) + } + amount, ok, err := Balance(context.Background(), zen) + if !ok || amount != "" || !errors.Is(err, errOpenCodeNoBalance) { + t.Fatalf("Balance = %q %v %v", amount, ok, err) + } + // a Balance URL of the user's own is still asked + zen.BalanceURL = "https://opencode.ai/somewhere" + if _, ok, err := Balance(context.Background(), zen); !ok || errors.Is(err, errOpenCodeNoBalance) { + t.Fatalf("own Balance URL: %v %v", ok, err) + } + if strings.Join(asked, ",") != "https://opencode.ai/somewhere" { + t.Fatalf("asked %v", asked) + } +} + +func TestOpenCodeGateway(t *testing.T) { + for base, want := range map[string]string{ + "https://opencode.ai/zen/v1": "zen", + "https://opencode.ai/zen": "zen", + "https://opencode.ai/inference/openai/v1": "zen", + "https://opencode.ai/inference/anthropic": "zen", + "https://opencode.ai/zen/go/v1": "go", + "https://opencode.ai/zen/go": "go", + "https://opencode.ai/inference/go/openai/v1": "go", + "https://opencode.ai/inference/go/anthropic": "go", + "https://opencode.ai/inference/custom/x/v1": "", + "https://opencode.ai/console": "", + "https://example.com/zen/go/v1": "", + "": "", + } { + if got := openCodeGateway(base); got != want { + t.Errorf("%q: %q, want %q", base, got, want) + } + } +} diff --git a/internal/provider/opencode_endpoints.go b/internal/provider/opencode_endpoints.go index e39b2d863..f49cbf7d2 100644 --- a/internal/provider/opencode_endpoints.go +++ b/internal/provider/opencode_endpoints.go @@ -29,6 +29,32 @@ func openCodeRoot(base string) (root, catalogID string) { return "", "" } +// openCodeGateway says which of OpenCode's gateways base is at: "go" for +// Go's (…/zen/go, or the inference API's …/inference/go, whatever follows: +// /v1, or /openai/v1 and /anthropic, the URLs models.dev and Go's docs +// give since October 2026), "zen" for Zen's (…/zen, …/inference: the +// workspace's pay-as-you-go credits), "" for any other, a provider of the +// user's own at …/inference/custom among them, which its vendor bills. +func openCodeGateway(base string) string { + u, err := url.Parse(strings.TrimSpace(base)) + if err != nil || !openCodeHost(u.Hostname()) { + return "" + } + seg := strings.Split(strings.Trim(u.Path, "/"), "/") + if seg[0] != "zen" && seg[0] != "inference" { + return "" + } + if len(seg) > 1 { + switch seg[1] { + case "go": + return "go" + case "custom": + return "" + } + } + return "zen" +} + // openCodeGemini is the base of Gemini's generateContent at the gateway // root is: models/{model}:streamGenerateContent is asked under it. Zen's // /zen/v1 relays it to the inference API's Google route, reading the key diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index e0defa263..476e5d6fd 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -37,6 +37,12 @@ type planQuotaSource struct { func planQuotaSourceOf(p Provider) (planQuotaSource, bool) { for _, base := range []string{p.Chat, p.Anthropic, p.Responses} { coding := strings.Contains(base, "/api/coding/") + if openCodeGateway(base) == "go" { + // Go at Zen's gateway or at the inference API, the URL + // models.dev and Go's docs give since October 2026: the same + // key, told its windows at the same usage query + return planQuotaSource{"https://opencode.ai/zen/go/v1/usage", true, readOpenCodeGo, true}, true + } switch hostOf(base) { case "open.bigmodel.cn": return planQuotaSource{"https://open.bigmodel.cn/api/monitor/usage/quota/limit", false, readZhipuPlan, coding}, true @@ -55,10 +61,6 @@ func planQuotaSourceOf(p Provider) (planQuotaSource, bool) { // a Coding Plan key (sk-cp-…) is told its windows; a // pay-as-you-go key isn't, and gets no card (#387) return planQuotaSource{"https://" + hostOf(base) + "/v1/token_plan/remains", true, readMiniMaxPlan, false}, true - case "opencode.ai": - if u := strings.TrimSuffix(base, "/"); strings.HasSuffix(u, "/zen/go") || strings.Contains(u, "/zen/go/") { - return planQuotaSource{"https://opencode.ai/zen/go/v1/usage", true, readOpenCodeGo, true}, true - } case "ollama.com": // Ollama Cloud's included allowance (#1888); a key with none // gets no card diff --git a/internal/provider/planquota_test.go b/internal/provider/planquota_test.go index 858fd102a..2ca41b1e4 100644 --- a/internal/provider/planquota_test.go +++ b/internal/provider/planquota_test.go @@ -27,6 +27,14 @@ func TestPlanQuotaSource(t *testing.T) { {Provider{Chat: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go"}, "https://opencode.ai/zen/go/v1/usage", true, true}, {Provider{Anthropic: "https://opencode.ai/zen/go"}, "https://opencode.ai/zen/go/v1/usage", true, true}, {Provider{Chat: "https://opencode.ai/zen/v1"}, "", false, false}, // Zen is pay as you go + // Go at the inference API, as models.dev and Go's docs give it + // since October 2026 (ttmrmx on X: no card) + {Provider{Chat: "https://opencode.ai/inference/go/openai/v1"}, "https://opencode.ai/zen/go/v1/usage", true, true}, + {Provider{Chat: "https://opencode.ai/inference/go/v1", Anthropic: "https://opencode.ai/inference/go"}, "https://opencode.ai/zen/go/v1/usage", true, true}, + {Provider{Anthropic: "https://opencode.ai/inference/go/anthropic"}, "https://opencode.ai/zen/go/v1/usage", true, true}, + {Provider{Chat: "https://opencode.ai/inference/openai/v1"}, "", false, false}, // Zen's + {Provider{Chat: "https://opencode.ai/inference/custom/acme/v1"}, "", false, false}, // the user's own provider + {Provider{Chat: "https://example.com/zen/go/v1"}, "", false, false}, {Provider{Chat: "https://api.kimi.com/coding/v1", Anthropic: "https://api.kimi.com/coding"}, "https://api.kimi.com/coding/v1/usages", true, true}, {Provider{Anthropic: "https://api.kimi.ai/coding/"}, "https://api.kimi.ai/coding/v1/usages", true, true}, {Provider{Chat: "https://api.commandcode.ai/provider/v1", Anthropic: "https://api.commandcode.ai/provider"}, "https://api.commandcode.ai/alpha/billing/credits", true, false}, @@ -335,6 +343,8 @@ func TestPlanQuotas(t *testing.T) { Keys: []KeyAccount{{Key: "glm-a"}, {Key: "glm-b", Name: "home"}, {Key: "glm-off", Off: true}}}, {ID: "glm-api", Name: "GLM API", Chat: "https://open.bigmodel.cn/api/paas/v4", Key: "glm-payg"}, {ID: "go", Name: "OpenCode Go", Chat: "https://opencode.ai/zen/go/v1", Key: "go-k"}, + // Go at models.dev's URL for it: the same card (ttmrmx on X) + {ID: "go-inference", Name: "OpenCode Go", Chat: "https://opencode.ai/inference/go/openai/v1", Key: "go-k"}, {ID: "zen", Name: "Zen", Chat: "https://opencode.ai/zen/v1", Key: "zen-k"}, {ID: "minimax-cn", Name: "MiniMax (China)", Chat: "https://api.minimaxi.com/v1", Anthropic: "https://api.minimaxi.com/anthropic", Key: "sk-cp-k"}, {ID: "minimax-payg", Name: "MiniMax API", Anthropic: "https://api.minimaxi.com/anthropic", Key: "sk-api-k"}, @@ -347,7 +357,7 @@ func TestPlanQuotas(t *testing.T) { for _, q := range PlanQuotas(context.Background()) { got[q.Provider+"/"+q.User] = q } - if len(got) != 4 { + if len(got) != 5 { t.Fatalf("cards: %+v", got) } if q := got["minimax-cn/"]; len(q.Windows) != 2 || q.Windows[0].Name != "5 hours" && q.Windows[0].Name != "Allowance" || q.Windows[0].Used != 25 || q.Windows[1].Name != "7 days" || q.Windows[1].Used != 4 { @@ -370,6 +380,9 @@ func TestPlanQuotas(t *testing.T) { if q := got["go/"]; q.Name != "OpenCode Go" || len(q.Windows) != 1 || q.Windows[0].Name != "5 hours" { t.Errorf("go: %+v", q) } + if q := got["go-inference/"]; len(q.Windows) != 1 || q.Windows[0].Name != "5 hours" || q.Error != "" { + t.Errorf("go at the inference API: %+v", q) + } // The custom GLM provider is recognized by its endpoint, not its id // or key labels, and the provenance survives PlanQuotas' cache. reset := time.UnixMilli(4102444800000) @@ -380,7 +393,7 @@ func TestPlanQuotas(t *testing.T) { t.Errorf("%s/%s: hidden=%v", q.Provider, q.User, hidden) } } - if qs := notShown(PlanQuotas(context.Background()), []SubscriptionQuota{sub}); len(qs) != 2 { + if qs := notShown(PlanQuotas(context.Background()), []SubscriptionQuota{sub}); len(qs) != 3 { t.Fatalf("cached plans after deduplication: %+v", qs) } // A restart loses the in-memory provenance; a failed read restores @@ -393,10 +406,10 @@ func TestPlanQuotas(t *testing.T) { lastQuotas.m, lastQuotas.loaded = nil, false lastQuotas.Unlock() qs := PlanQuotas(context.Background()) - if len(qs) != 4 { + if len(qs) != 5 { t.Fatalf("restored plans: %+v", qs) } - if kept := notShown(qs, []SubscriptionQuota{sub}); len(kept) != 2 { + if kept := notShown(qs, []SubscriptionQuota{sub}); len(kept) != 3 { t.Fatalf("restored plans after deduplication: %+v", kept) } } diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 313e0a4f2..af6bbfd0e 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -135,6 +135,10 @@ type SubscriptionQuota struct { // its provider hasn't (accessKeyCard, #1821): the Usage page offers // the provider's settings to give it in. NeedsAccessKey bool `json:"needsAccessKey,omitempty"` + // SeeAt is the vendor's page that shows what its API tells no key: + // OpenCode Zen's credits, on its console (errOpenCodeNoBalance). The + // Usage page offers to open it. + SeeAt string `json:"seeAt,omitempty"` // AsOf is when an allowance shown in place of one that couldn't be // read was read (see keepLast); nil for a reading just made. AsOf *time.Time `json:"asOf,omitempty"`