diff --git a/internal/cli/accounts_cli.go b/internal/cli/accounts_cli.go index 90ba77054..cf11e0b62 100644 --- a/internal/cli/accounts_cli.go +++ b/internal/cli/accounts_cli.go @@ -357,7 +357,7 @@ func accountRows(ls []provider.Login, now time.Time) []accountRow { wg.Add(1) go func(agent string) { defer wg.Done() - u := provider.LoginUsage(ctx, agent) + u := provider.LoginUsageShown(ctx, agent) mu.Lock() usage[agent] = u mu.Unlock() diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 1ffb97bdd..e9e7f249f 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13842,6 +13842,8 @@ function quotaError(err, q) { if (/^couldn't reach chatgpt\.com for the usage read/.test(err)) return t("Couldn't reach ChatGPT — check the network or the proxy"); if (/^ChatGPT's usage reply isn't one magpie reads/.test(err)) return t("ChatGPT answered in a form magpie doesn't read — hover for what it sent"); if (/^a ChatGPT API account's usage isn't told through OpenAI's API/.test(err)) return t("OpenAI's API doesn't tell a ChatGPT API account's usage — see chatgpt.com/settings/usage, or add the account as ChatGPT to see it here"); + // a switched-off subscription is not read (errLeftAlone, login_usage.go) + if (/^not read yet: this subscription is switched off/.test(err)) return t("Switched off, so no allowance is read — switch it on and refresh"); const bal = balanceError(err); if (bal) return bal; // a plugin's own usage read failed: its first line (aqiu817/magpie-sensenova#1) diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index b8b8fc634..8ba8f1ef9 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2135,6 +2135,7 @@ const I18N = { "Stop using this account": "停用这个账号", "Use this account too": "同时启用这个账号", "No allowance reported": "暂无额度数据", + "Switched off, so no allowance is read — switch it on and refresh": "已关闭,不读取额度 — 打开开关后再刷新", "No plan": "无订阅", "resets {in}": "{in}重置", "in {n}m": "{n} 分钟后", @@ -7111,6 +7112,7 @@ const I18N = { "Stop using this account": "停用這個帳號", "Use this account too": "同時啟用這個帳號", "No allowance reported": "暫無額度資料", + "Switched off, so no allowance is read — switch it on and refresh": "已關閉,不讀取額度 — 開啟開關後再重新整理", "No plan": "無訂閱", "resets {in}": "{in}重置", "in {n}m": "{n} 分鐘後", @@ -12063,6 +12065,7 @@ const I18N = { "Stop using this account": "このアカウントの使用を停止", "Use this account too": "このアカウントも使用", "No allowance reported": "利用枠の情報なし", + "Switched off, so no allowance is read — switch it on and refresh": "オフのため利用枠を読みません — オンにして更新してください", "No plan": "プランなし", "resets {in}": "{in}にリセット", "in {n}m": "{n} 分後", @@ -17046,6 +17049,7 @@ const I18N = { "Stop using this account": "Dieses Konto nicht mehr verwenden", "Use this account too": "Dieses Konto ebenfalls verwenden", "No allowance reported": "Kein Kontingent gemeldet", + "Switched off, so no allowance is read — switch it on and refresh": "Ausgeschaltet, das Kontingent wird nicht gelesen — einschalten und neu laden", "No plan": "Kein Tarif", "resets {in}": "Reset {in}", "in {n}m": "in {n} Min.", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index c271acfeb..69c68e62c 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -2892,7 +2892,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { defer cancel() // and each account's daily check-in, for its row's Check in now agent := r.URL.Query().Get("agent") - writeJSON(rw, provider.LoginCheckins(agent, provider.WithCapped(provider.LoginUsage(ctx, agent)))) + writeJSON(rw, provider.LoginCheckins(agent, provider.WithCapped(provider.LoginUsageShown(ctx, agent)))) }) // Switching the account an agent is signed in to, among those magpie // remembers, and forgetting one. diff --git a/internal/gui/tests/claude-off-usage-card.test.cjs b/internal/gui/tests/claude-off-usage-card.test.cjs new file mode 100644 index 000000000..79fa75d6a --- /dev/null +++ b/internal/gui/tests/claude-off-usage-card.test.cjs @@ -0,0 +1,60 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Kunlin03 on X: a Claude Pro account added in magpie, the Claude Code switch +// off, said "No allowance reported" on its card. The gateway now answers an +// account of a switched-off provider with its last reading, or, never read, +// that it is switched off (login_usage.go); the card says so in the user's +// language, not "No allowance reported" or "Allowance unavailable". +// Chromium and WebKit, every language. 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"); +const claude = () => ({ + id: "claude", name: "Claude Code", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "", + models: [], agents: [], fallback: [], headers: {}, keyList: [], + account: { + agent: "claude", agentName: "Claude Code", agentIcon: "claude-color", user: "pro@example.com", plan: "Pro", + logins: [{ user: "pro@example.com", plan: "Pro", active: true, on: true }], + }, +}); +const serve = (lang, web) => 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:${JSON.stringify(lang)},theme:"dark",web:${web}};` }); + 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: "dark" } }); + if (url.pathname === "/api/providers") return json({ providers: [claude()], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/login/usage") return json({ + "pro@example.com": { provider: "claude", plan: "Pro", windows: [], error: "not read yet: this subscription is switched off in magpie, so nothing is read for it" }, + }); + 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 want = { en: "Switched off, so no allowance is read — switch it on and refresh", zh: "已关闭,不读取额度 — 打开开关后再刷新", "zh-TW": "已關閉,不讀取額度 — 開啟開關後再重新整理", ja: "オフのため利用枠を読みません — オンにして更新してください", de: "Ausgeschaltet, das Kontingent wird nicht gelesen — einschalten und neu laden" }; +const langs = ["en", "zh", "zh-TW", "ja", "de"]; +for (const [engine, browserType] of [["chromium", chromium], ["webkit", webkit]]) { + test(engine + ": a switched-off Claude account's card says it is switched off", async (t) => { + const browser = await browserType.launch(); + t.after(() => browser.close()); + for (const width of [1000, 390]) for (const lang of langs) { + const at = `${lang} ${width}`; + const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + await page.route("**/*", serve(lang, false)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Claude Code" }).first().click(); + const line = page.locator('.editor .accts .acc[data-account-id="pro@example.com"] .aq .aq-none'); + await line.waitFor(); + assert.equal((await line.textContent()).trim(), want[lang === "en" ? "en" : lang], at); + await context.close(); + } + }); +} diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go index 1b9c887cf..d31281d61 100644 --- a/internal/provider/login_usage.go +++ b/internal/provider/login_usage.go @@ -100,6 +100,36 @@ func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota return out } +// errLeftAlone is what a card says of an account whose provider is switched +// off or removed: nothing is read for it in the background, and it is no +// failed read. keepLast gives the reading kept from before ("not read yet"). +var errLeftAlone = errors.New("not read yet: this subscription is switched off in magpie, so nothing is read for it") + +// LoginUsageShown is LoginUsage for the account lists (the editor's cards, +// `magpie accounts`): a provider magpie leaves alone (switched off or +// removed) makes no request, and its accounts show what was last known of +// them, as leftAlone promises, not an empty card ("No allowance reported", +// Kunlin03 on X: a Claude Pro account with the Claude Code switch off). +// LoginUsage itself stays empty for it: warm-ups and switching read it and +// must not take a kept reading for a fresh one. +func LoginUsageShown(ctx context.Context, agent string) map[string]SubscriptionQuota { + if !settings.AccountDiscoveryOff() && leftAlone(agent) { + if logins, ok := usageLogins(agent); ok { + return keptLoginUsage(logins) + } + } + return LoginUsage(ctx, agent) +} + +// keptLoginUsage is each of logins' last reading, asking no one. +func keptLoginUsage(logins []Login) map[string]SubscriptionQuota { + out := map[string]SubscriptionQuota{} + for _, l := range logins { + out[l.User] = keepLast(SubscriptionQuota{Provider: loginProvider(l), Plan: l.Plan, Windows: []QuotaWindow{}, Error: errLeftAlone.Error()}, l.User) + } + return out +} + // loginUsageAt is LoginUsage and when the oldest of its readings was made: // one taken from the cache is up to a minute old already, and Allowances // counts its own minute from then, not from when it asked (#1295). And diff --git a/internal/provider/login_usage_shown_test.go b/internal/provider/login_usage_shown_test.go new file mode 100644 index 000000000..96f813789 --- /dev/null +++ b/internal/provider/login_usage_shown_test.go @@ -0,0 +1,41 @@ +package provider + +import ( + "context" + "testing" + "time" +) + +// A Claude account whose provider is switched off showed "No allowance +// reported": LoginUsage answered nothing for it. The account lists show what +// was last known of it, or say it is switched off, and read nothing +// (Kunlin03 on X: a Claude Pro account, Claude Code switch off). +func TestLoginUsageShownOfSwitchedOffClaude(t *testing.T) { + home := claudeHome(t) + claudeSignIn(t, home, time.Now().Add(24*time.Hour)) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + lastQuotas.Lock() + lastQuotas.m, lastQuotas.loaded = nil, false + lastQuotas.Unlock() + writeFile(t, Path(), map[string]any{"providers": []map[string]any{{"id": "claude", "off": true}}}) + if !leftAlone("claude") { + t.Fatal("claude not left alone") + } + at := time.Now().Add(-time.Hour).Truncate(time.Second) + keepLast(SubscriptionQuota{Provider: "claude", User: "pro@example.com", ReadAt: &at, + Windows: []QuotaWindow{{Name: "5 hours", Span: 5 * time.Hour, Used: 12}}}, "") + + got := keptLoginUsage([]Login{{Agent: "claude", User: "pro@example.com", Plan: "Pro"}, {Agent: "claude", User: "new@example.com", Plan: "Pro"}}) + if q := got["pro@example.com"]; q.Error != "" || len(q.Windows) != 1 || q.Windows[0].Used != 12 || !q.ReadDeferred { + t.Fatalf("a read account shows its last reading: %+v", q) + } + if q := got["new@example.com"]; q.Error != errLeftAlone.Error() || len(q.Windows) != 0 { + t.Fatalf("an account never read says it is switched off: %+v", q) + } + if n := len(LoginUsage(context.Background(), "claude")); n != 0 { + t.Fatalf("LoginUsage, which callers act on, answered %d readings for a provider left alone", n) + } + if len(LoginUsageShown(context.Background(), "claude")) != len(Logins("claude")) { + t.Fatal("LoginUsageShown skipped an account") + } +} diff --git a/internal/provider/quota_last.go b/internal/provider/quota_last.go index b011cb4d6..fa2d34941 100644 --- a/internal/provider/quota_last.go +++ b/internal/provider/quota_last.go @@ -142,7 +142,7 @@ func hadReading(provider, user string) bool { // vendor's HTTP call, so its error carries errNotAsked wrapped: "Get // \"https://…\": not read yet: …". func readDeferred(err string) bool { - for _, e := range []error{errNotAsked, errClaudeNotAsked, errClaudeSaved} { + for _, e := range []error{errNotAsked, errClaudeNotAsked, errClaudeSaved, errLeftAlone} { if strings.Contains(err, e.Error()) { return true }