From 89ffc58f5ba7defe2d2dd5cb4ff69a6bb774d9ab Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 2 Nov 2026 03:46:34 +0800 Subject: [PATCH] gui: a card's Refresh says the read's failure, and Claude Code's first-run screens say what to do (#4817, uiuing) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From uiuing's branch (1eeb8928b, 66818dbf6), adapted. A usage card's Refresh showed nothing when the read came back as a card with an error: only a thrown request reached status. quotaRefresh now says the refreshed card's error through quotaError, for a single account and for a provider whose cards were replaced (the one kept in quotas). quotaError reads the helper's new "stays on its first-run screens" and an older magpie's "shows its first-run notes" as "Finish Claude Code's first-run setup, then refresh", in en, zh, zh-TW, ja and de. Comments in quotaError and quotaRefresh were cut so the core scripts stay in their budget (1,533,732 of 1,533,802; main was at 1,533,780), with no raise. Run at the pushed head, on mote: node --test of claude-quota-onboarding, quota-refresh-order, usage-card-refresh, usage-refresh, usage-refresh-flight, account-refresh, editor-quota-quiet, usage-no-reading, usage-remote-cards, tray-usages, glm-quota-error, claude-usage-asked, allowance-open-read, api-key-usage, key-balance-card, copilot-signed-out-account, signin-again, plugin-git and i18n-keys (chromium and webkit, every language each file runs, 440px where it sets it): 287 of 287. go test -run 'Budget|I18n|Lang' ./internal/gui ok. go test -run "Claude|TUI" ./internal/gateway ok. The full ./internal/gateway (-timeout 45m, before the rebase onto 6b3a6d42c) is ok but for TestCodexPoolSaysTheClientsVersion, #4807 (another test's Codex identity reaches it in a full run); nothing Claude or GUI. Broken by hand: without the new status line, 13 of the 31 tests in claude-quota-onboarding and quota-refresh-order go red (all ten engine/language cases and three VM ones). Not tried: the real app's card against a real signed-in Claude Code that stays on its notes. Co-authored-by: 胡峻果 --- docs/subsystems/gui-shell.md | 15 +++ internal/gui/assets/app.js | 28 ++-- internal/gui/assets/i18n.js | 4 + .../tests/claude-quota-onboarding.test.cjs | 120 ++++++++++++++++++ .../gui/tests/quota-refresh-order.test.cjs | 45 +++++++ 5 files changed, 197 insertions(+), 15 deletions(-) create mode 100644 internal/gui/tests/claude-quota-onboarding.test.cjs diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index af5dadee5..443a86001 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -70,6 +70,21 @@ languages, at 440 and 360px. Redrawing the cards preserves their refresh controls and any running turn. The reply updates the reading immediately; the icon then finishes its current full turn before stopping (no rotation under reduced motion). +A manual refresh whose HTTP reply succeeds but whose requested card has +an error reports that error through the status line too (#4817), including +when the card already showed it. Errors on other cards in the reply do +not become the requested account's error. An unnamed provider or remote +summary that gains named cards reports only failures accepted from that +reply; an older error replaced by a newer reading is not reported again. +Claude Code's first-run screens are gone through by the helper itself +(claude-subscription-bridge.md); one it can't get past ends the read, and +that is said on the editor row, Usage card, tray card and refresh notice: +finish Claude Code's first-run setup, then refresh; `magpie claude-code` +names the executable, including a build magpie downloaded. The original +error stays in the card's tooltip, and the read never falls back to `-p`. +`claude-quota-onboarding.test.cjs` presses the active account's button in +both engines and all five languages, with an account error in a successful +HTTP reply, then a successful read after setup and an unrelated card error. ### Streamed output speed diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 9b97b2bf8..cd83d0620 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13546,8 +13546,9 @@ function loginUsageOf(agent) { const SIGN_IN_GONE = /sign-in has (expired|lapsed)|sign in again/i; function quotaError(err, q) { - // signed in again in place, settings kept, from the row's Sign in again - // (blue12345655 on Discord looked for a way to add it again, found none) + // first-run screens the helper can't pass (#4817) + if (/^Claude Code: claude-tui: .{0,40}(stays on its first-run screens|shows its first-run notes)/.test(err)) return t("Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable."); + // signed in again in place from the row's Sign in again (blue12345655) if (/sign-in has expired/.test(err)) return t("Signed out — choose Sign in again on this account under Providers"); // a Copilot account GitHub refused the token of (copilot_lapsed.go), as // its row says it, in English or already in the user's language @@ -13565,14 +13566,11 @@ function quotaError(err, q) { // it with (accessKeyCard, #1821): the card used to be left out unsaid if (/^this plan's usage is read with the account's access key: give its SecretId/.test(err)) return t("This plan's usage needs the account's SecretId and SecretKey — give them in the provider's settings"); if (/^this plan's usage is read with the account's access key/.test(err)) return t("This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings"); - // ZCode with no GLM Coding Plan and no Start Plan left: nothing to spend, - // not a failed read (#1001). The plugin's card (NO_START, packages/zcode) - // names no way out, so it is said here; anchored on the whole sentence so - // the sign-in errors and "could not be read" are left alone. + // ZCode with no plan left: nothing to spend, not a failed read (#1001); + // the plugin's card names no way out. Whole sentence, so others pass. 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 + // an OpenCode Go key's windows (planquota.go): only the subscribing + // member's key reads them; said with the way out 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"); // a GLM key Zhipu or Z.ai refused (zhipuRefused, planquota.go): the key @@ -13589,9 +13587,8 @@ function quotaError(err, q) { // a remote magpie's gateway key card (#1547, remote_key_limits.go) if (/^remote magpie is too old to tell this key's limit/.test(err)) return t("That computer's magpie is too old to tell this key's limit — update magpie there"); if (/answered its key's limit in a form magpie doesn't read$/.test(err)) return t("That computer answered this key's limit in a form magpie doesn't read — hover for more"); - // a ClinePass card with its balance but not its limits (#79): the - // built-in key card (clineLimitsUnread, cline_usage.go) and the Cline - // plugin both begin their error with these words + // a ClinePass card with its balance but not its limits (#79): the key + // card (cline_usage.go) and the Cline plugin both begin so if (/^ClinePass limits couldn't be read/.test(err)) return t("ClinePass limits couldn't be read — hover for why"); const bal = balanceError(err); if (bal) return bal; @@ -18293,11 +18290,10 @@ function quotaRefresh(q, then) { const began = quotaRefreshVersion; try { const qs = await api("usage/quotas/refresh?provider=" + encodeURIComponent(q.provider) + (q.user ? "&user=" + encodeURIComponent(q.user) : ""), {}); - const fresh = Array.isArray(qs) && qs.find(x => usageAcctKey(x) === key); + let fresh = Array.isArray(qs) && qs.find(x => usageAcctKey(x) === key); if (fresh) { quotaRefreshVersions.set(key, ++quotaRefreshVersion); - // The reply includes every card, but only this one was refreshed. - // Another card may have completed its own refresh in the meantime. + // only this card was read; others may be newer const kept = quotas || []; quotas = kept.some(x => usageAcctKey(x) === key) ? kept.map(x => usageAcctKey(x) === key ? fresh : x) : [...kept, fresh]; quotasAt = Date.now(); @@ -18313,12 +18309,14 @@ function quotaRefresh(q, then) { } if (!placed) next.push(...replacement); quotas = keepRefreshedQuotas(next, began); quotasAt = Date.now(); + fresh = !q.user && replacement.find(x => x.error && quotas.includes(x)); // Protect the new identities and the old keys they replaced, so a // pending GET can neither erase the new cards nor restore the old. const version = ++quotaRefreshVersion; for (const x of [q, ...before, ...quotas]) if (belongs(x)) quotaRefreshVersions.set(usageAcctKey(x), version); } if (then) await then(); + if (fresh?.error) status(quotaError(fresh.error, fresh), "err"); } catch (err) { statusErr(err); } finally { diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 4e31f0823..2146763ee 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3125,6 +3125,7 @@ const I18N = { "Other Models": "其他模型", "Total": "合计", "Allowance unavailable": "暂时无法获取额度", + "Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable.": "请先完成 Claude Code 的首次启动引导,再刷新。运行 magpie claude-code 可查看应启动的程式路径。", "Allowance unavailable: {why}": "暂时无法获取额度:{why}", "Nothing read on that computer yet — refresh this card to have it read": "那台电脑还没有读过额度 — 刷新这张卡片让它读取", "That computer's magpie doesn't share its quotas yet — update magpie there": "那台电脑的 magpie 还不能共享额度 — 请在那台电脑上更新 magpie", @@ -7479,6 +7480,7 @@ const I18N = { "Other Models": "其他模型", "Total": "合計", "Allowance unavailable": "暫時無法取得額度", + "Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable.": "請先完成 Claude Code 的首次啟動導引,再重新整理。執行 magpie claude-code 可查看應啟動的程式路徑。", "Allowance unavailable: {why}": "暫時無法取得額度:{why}", "Nothing read on that computer yet — refresh this card to have it read": "那臺電腦還沒有讀過額度 — 重新整理這張卡片讓它讀取", "That computer's magpie doesn't share its quotas yet — update magpie there": "那臺電腦的 magpie 還不能共享額度 — 請在那臺電腦上更新 magpie", @@ -11837,6 +11839,7 @@ const I18N = { "Other Models": "その他のモデル", "Total": "合計", "Allowance unavailable": "利用枠を取得できません", + "Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable.": "Claude Code の初回設定を完了してから更新してください。magpie claude-code を実行すると、起動する実行ファイルを確認できます。", "Allowance unavailable: {why}": "利用枠を取得できません:{why}", "Nothing read on that computer yet — refresh this card to have it read": "そのコンピューターではまだ読み取っていません — このカードを更新すると読み取ります", "That computer's magpie doesn't share its quotas yet — update magpie there": "そのコンピューターの magpie はまだ利用枠を共有できません — そちらの magpie を更新してください", @@ -16206,6 +16209,7 @@ const I18N = { "Other Models": "Andere Modelle", "Total": "Gesamt", "Allowance unavailable": "Kontingent nicht verfügbar", + "Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable.": "Schließe die Ersteinrichtung von Claude Code ab und aktualisiere dann erneut. Mit magpie claude-code findest du die zu startende Programmdatei.", "Allowance unavailable: {why}": "Kontingent nicht verfügbar: {why}", "Nothing read on that computer yet — refresh this card to have it read": "Auf diesem Computer wurde noch nichts gelesen — diese Karte aktualisieren, um es lesen zu lassen", "That computer's magpie doesn't share its quotas yet — update magpie there": "Das magpie dieses Computers teilt seine Kontingente noch nicht — aktualisiere magpie dort", diff --git a/internal/gui/tests/claude-quota-onboarding.test.cjs b/internal/gui/tests/claude-quota-onboarding.test.cjs new file mode 100644 index 000000000..493c50717 --- /dev/null +++ b/internal/gui/tests/claude-quota-onboarding.test.cjs @@ -0,0 +1,120 @@ +// The current Claude account can be signed in without its interactive +// first-run setup. Its /usage helper goes through those screens; one it +// can't get past ends the read. A successful refresh HTTP reply still +// carries that account's error: pressing Refresh must say what failed +// and how to recover, on every surface, without changing the account or +// falling back to print mode. +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 = process.env.MAGPIE_QUOTA_ASSETS || path.resolve(__dirname, "../assets"); +const user = "current@example.invalid", other = "saved@example.invalid"; +// The error the helper ends a read with when a first-run screen stays +// (claudetui's onboard), the screen's text after it cut short; and the +// one the reporter's gateway returned before it went through them +// (#4817), as an older remote magpie still says it. +const error = "Claude Code: claude-tui: Claude Code's interactive mode stays on its first-run screens, its onboarding not done; run Claude Code once in a terminal and go through them: Security notes:"; +const olderError = "Claude Code: claude-tui: Claude Code's interactive mode shows its first-run notes, its onboarding not done: Security notes:"; +const advice = "Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable."; +const provider = { id: "claude", name: "Claude Code", icon: "claude", models: [], agents: [], key: {}, + account: { agent: "claude", agentName: "Claude Code", user, logins: [ + { user, plan: "pro", active: true, on: true }, { user: other, plan: "pro", active: false, on: true }, + ] } }; + +function serve(lang, state) { + return async route => { + const url = new URL(route.request().url()), json = body => route.fulfill({ json: body }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ lang, theme: "light", web: false })};` }); + 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: [provider], presets: [], excluded: [], plugins: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/claude/mode") return json({ tui: true }); + if (url.pathname === "/api/login/usage") return json(Object.fromEntries(state.cards.map(q => [q.user, q]))); + if (url.pathname === "/api/usage/quotas/refresh") { + assert.equal(route.request().method(), "POST"); + assert.equal(url.searchParams.get("provider"), "claude"); + assert.equal(url.searchParams.get("user"), user); + state.refreshes++; + if (state.recovered) state.cards[0] = { provider: "claude", name: "Claude Code", user, readAt: new Date().toISOString(), windows: [{ name: "5 hours", used: 18 }] }; + return json(state.cards); + } + if (url.pathname === "/api/usage/quotas") return json(state.cards); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname.startsWith("/api/")) { + assert.equal(route.request().method(), "GET", `unexpected mutation: ${url.pathname}`); + return json({}); + } + if (url.host !== "magpie.test" || !/^\/[\w./-]*$/.test(url.pathname)) return route.fulfill({ status: 404, body: "" }); + 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: "" }); } + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang}: clicking the current Claude account's refresh reports onboarding and recovers`, async t => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width: 440, height: 760 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], state = { refreshes: 0, recovered: false, cards: [ + { provider: "claude", name: "Claude Code", user, plan: "pro", windows: [], error }, + { provider: "claude", name: "Claude Code", user: other, windows: [{ name: "7 days", used: 10 }] }, + ] }; + page.on("pageerror", e => errors.push(e.message)); + await page.route("**/*", serve(lang, state)); + await page.goto("http://magpie.test/?view=providers"); + const providerRow = page.locator('.row.provider[data-id="claude"]'); + await providerRow.waitFor({ timeout: 60000 }); + await providerRow.click(); + const row = page.locator("#modal .acc", { hasText: user }); + await row.locator(".aq-none").waitFor(); + const want = await page.evaluate(k => t(k), advice); + await row.locator(".quota-refresh").click(); + await page.locator('#status[role="alert"]').waitFor(); + assert.equal(await page.locator("#status").textContent(), want); + assert.equal(state.refreshes, 1, "one press reads only this account"); + assert.equal(await row.locator(".aq-none").textContent(), want); + assert.equal(await row.locator(".aq").getAttribute("title"), error, "the original detail stays available"); + if (lang !== "en") assert.notEqual(want, advice, "the recovery advice is translated"); + const fits = await row.locator(".aq-none").evaluate(e => { + const r = document.createRange(); r.selectNodeContents(e); + return [...r.getClientRects()].every(b => b.left >= 0 && b.right <= innerWidth + 1); + }); + assert.ok(fits, "the recovery advice fits the narrow account row"); + if (process.env.ARTIFACT_DIR && ["en", "zh"].includes(lang)) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `claude-quota-${engine}-${lang}.png`) }); + } + + // The shared wording also reaches Usage and the tray, without a + // refresh of their own or any account-setting mutation. + const siblings = await page.evaluate(q => ({ + usage: quotaWindows(q).textContent, + panel: panelQuotaCard(q).querySelector(".pq-sub.err").textContent, + }), state.cards[0]); + for (const text of Object.values(siblings)) assert.ok(text.includes(want), text); + assert.equal(await page.evaluate(() => quotaError("network is unreachable")), await page.evaluate(() => t("Allowance unavailable")), "unrelated errors keep their classification"); + assert.equal(await page.evaluate(e => quotaError(e), olderError), want, "an older magpie's words are read too"); + + await page.waitForFunction(() => !quotaRefreshing.size); + // Simulate the next read after the user completes setup. Another + // account's failure in the same HTTP reply is not this click's error. + state.recovered = true; + state.cards[1] = { ...state.cards[1], windows: [], error: "another account failed" }; + await page.evaluate(() => status("")); + await row.locator(".quota-refresh").click(); + await row.locator(".aq-w").waitFor(); + await page.waitForFunction(() => !quotaRefreshing.size); + assert.equal(state.refreshes, 2); + assert.equal(await row.locator(".aq-none").count(), 0); + assert.equal(await page.locator("#status").textContent(), "", "a successful target read doesn't report another account's error"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/quota-refresh-order.test.cjs b/internal/gui/tests/quota-refresh-order.test.cjs index 073922e6b..f7d2b8cbe 100644 --- a/internal/gui/tests/quota-refresh-order.test.cjs +++ b/internal/gui/tests/quota-refresh-order.test.cjs @@ -25,6 +25,7 @@ function page(m = "window") { const usageAcctKey = q => q.provider + "\\n" + (q.user || "").toLowerCase(); const quotaCycleHolds = new Map(); // past cycles' estimates (#2009), cleared by a refresh const t = x => x; + const quotaError = err => err; const calm = () => true; const document = { querySelectorAll: () => [] }; const el = () => ({ dataset: {}, classList: { add() {}, remove() {}, toggle() {} }, setAttribute() {} }); @@ -110,6 +111,50 @@ test("a card that comes back under another key still shows the reply", async () assert.deepEqual(plain(p.cards()).map(q => [q.user, q.windows[0].used]), [["a@x.com", 32]], "the refreshed card's reply was dropped"); }); +test("refresh errors: a newly named account reports the reading's failure", async () => { + const p = page(), unnamed = card("", 0), other = { ...card("b@x.com", 0), provider: "codex" }; + p.seed([unnamed, other]); + const refresh = p.refresh(unnamed); + const failed = { ...card("a@x.com", 0), error: "this Claude account needs setup", windows: [] }; + p.answer(0, [failed, { ...other, error: "another provider failed" }]); await refresh; + assert.deepEqual(plain(p.errors), [failed.error]); + assert.equal(p.cards()[0].error, failed.error); +}); + +test("refresh errors: a remote summary reports its failed child, not a local card", async () => { + const p = page(), summary = { ...card("", 0), provider: "home", from: "Home" }; + const local = { ...card("b@x.com", 0), provider: "codex" }; + p.seed([summary, local]); + const refresh = p.refresh(summary); + const failed = { ...card("a@x.com", 0), provider: "home/claude", from: "Home", error: "remote account needs setup", windows: [] }; + p.answer(0, [{ ...local, error: "local account failed" }, failed]); await refresh; + assert.deepEqual(plain(p.errors), [failed.error]); + assert.equal(p.cards().find(q => q.provider === "home/claude").error, failed.error); +}); + +test("refresh errors: a missing named account doesn't report another account's error", async () => { + const p = page(), a = card("a@x.com", 0); + p.seed([a]); + const refresh = p.refresh(a); + p.answer(0, [{ ...card("b@x.com", 0), error: "another account failed", windows: [] }]); await refresh; + assert.deepEqual(plain(p.errors), []); +}); + +for (const newerFailed of [false, true]) { + test(`refresh errors: a renamed reply cannot report an older error over a newer ${newerFailed ? "failure" : "reading"}`, async () => { + const p = page(), unnamed = card("", 0), b = card("b@x.com", 0); + p.seed([unnamed, b]); + const first = p.refresh(unnamed), second = p.refresh(b); + const newer = newerFailed ? { ...card("b@x.com", 0), error: "newer failure", windows: [] } : card("b@x.com", 61); + p.answer(1, [card("", 0), newer]); await second; + // Distinct objects, as separate JSON replies are. The first read's + // old error is discarded by keepRefreshedQuotas, not shown anew. + p.answer(0, [card("a@x.com", 32), { ...card("b@x.com", 0), error: "older failure", windows: [] }]); await first; + assert.deepEqual(plain(p.errors), newerFailed ? [newer.error] : []); + assert.deepEqual(plain(p.cards().find(q => q.user === b.user)), newer); + }); +} + test("an account first named by refresh survives an older whole-page reply", async () => { const p = page(), unnamed = card("", 0); p.seed([unnamed]);