Files
magpie/internal/provider/opencode_balance_test.go
T
yetone c483feadfd usage: OpenCode Zen's card says OpenCode tells no key its balance, and Go at /inference/go gets its plan card (ttmrmx on X)
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.
2026-10-19 13:42:21 +08:00

110 lines
4.1 KiB
Go

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)
}
}
}