From 817d35ffa9769a8d22270f42e7db43ae8cf62b4d Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 13 Nov 2026 23:04:53 +0800 Subject: [PATCH] usage: a window's whole follows the tokens pick's With cache (Anotiaww on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @Anotiaww asked (X 2121248031983194214) that the account cards' "Whole ≈ N tokens" on Usage → Overview follow the page's tokens pick. With cache, it now adds the window's routed cache read and written, scaled by the same share used as the input and output; the line reads "Whole ≈ N tokens with cache" and its tooltip says cache is included. Without cache nothing changes. Changing the pick redraws the cards. The tray panel shows no holds line, so it has nothing to follow. holdsLine and holdsUnknownLine move from app.js into the Usage plugin's page.js, beside usageWithCache, so the core script budget stays as it is (it had 14 bytes left). quotaWindows still calls them as globals. New words are said in zh, zh-TW, ja and de. Run (mica, both engines, every language): - quota-holds, i18n-keys, i18n-en-no-cjk: 16/16 ok. The new quota-holds test (pick With cache at 360 and 1000px, reload keeps it, pick back) went red in both engines with the cache left out and the old words, and again with no redraw on pick. - 185 GUI files that reach Usage or quotas, plus mobile-web, idle-ticks, old-webkit and every i18n file, concurrency 3. Reds: account-eye, account-mask, account-refresh-holds, claude-quota-onboarding, codex-auto-reset (de), key-balance-card (de), menu-scroll, mobile-web, old-webkit, quota-count-wrap. The same files are red at the base ac0b5c287 without this change (quota-count-wrap 1100px cut, alone), and each is filed (#5052, #3951, #5814, #6179, #4790, #6414, #6532, #3952, #6467, #3404). Run (mote): go vet, GOOS=linux vet -tags nogui, GOOS=windows vet, builds; go test -tags nogui ./internal/gui (TestCoreScriptBudget), ./internal/provider, ./internal/usage ok. Rebased on 077421733, where 5211fd3ba gave holdsLine a provider's currency (prov); page.js carries it. At this head (mica): quota-holds, quota-curve, currency-provider, currency, i18n-keys, i18n-en-no-cjk, quota-count-wrap 80/83; the reds are quota-count-wrap (#3404, red at 077421733 too) and quota-curve chromium en/zh (#4768), which passes 31/31 alone here and at 077421733. go test -tags nogui ./internal/gui (budgets) ok. Not run: the full go test ./... and the full GUI suite (both machines were loaded); the only Go change is a comment. --- docs/subsystems/gui-shell.md | 2 +- docs/subsystems/providers-accounts.md | 4 +- internal/gui/assets/app.js | 58 ----------------- internal/gui/assets/plugins/usage/i18n.js | 12 ++++ internal/gui/assets/plugins/usage/page.js | 66 +++++++++++++++++++ internal/gui/tests/quota-holds.test.cjs | 77 ++++++++++++++++++++++- internal/provider/window_holds.go | 3 +- 7 files changed, 160 insertions(+), 62 deletions(-) diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 7e6ce6a64..98bdeb0fe 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -666,7 +666,7 @@ covers it in both engines, every language and a narrow window. - An allowance card can be hidden from Usage › Overview (whqtian_07012 on Discord: StepFun's plan wanted, its balance not). The card's "…" button at its head's end (`quotaCardMore`; jen_celeus on X looked for a way to hide OpenCode Zen's card, which has no usage to show, and found none), a right-click, or a long press on a touch screen (`quotaCardMenus` in `plugins/usage/page.js`) opens the app menu with *Hide from Overview*. The button shows as the card is hovered and lies over the head's end, so the head at rest is laid out as before; where nothing hovers it is always shown with room kept for it, drawn at 22px and taken at 44 on a phone; an account of a card with several says *Hide this account from Overview*, and a plan card carrying its key's balance (`keyCards`) also offers *Hide its balance from Overview*, which keeps the plan. Each is kept by its tray card id and kind (`cardHideKey`: `stepfun|balance`, `kimi|me@x|plan`) in `settings.UsageCardsHidden` through the same `POST /api/usage/arrange` (`cardsHidden`), and kept by the Settings save. `overviewCards` leaves them out before `keyCards`, so routing, caps, the counting, the Accounts list, the tray panel (which has its own *Arrange*) and the menu bar cells never hear of it; a cell clicked for a hidden card shows it until the page is left (`usagePeek`). Such a card's menu offers *Show in Overview*, not Hide again, since the "{n} hidden" line leaves it out while it shows. A "{n} hidden" line under the cards (`#quotaHid`, `renderQuotaHid`) opens them, each with *Unhide*, and *Show all* from two. The line is drawn in `--muted`, not `--faint`, so it can be read and found (3:1 or more), and while any are hidden every card's menu ends with *Show {n} Hidden*, which opens the line with the keyboard on it and brings it into sight on the menu's click (`openHidden`; yuu003348 on Discord found no way back). See `TestUsageArrangeCardsHidden`, `usage-cards-hide.test.cjs`, `usage-card-more.test.cjs` and `usage-hidden-way-back.test.cjs`. - A card's quota rows can be hidden one group at a time from Overview (wangshaowei39 on X: Antigravity's Claude & GPT rows unwanted). A row's right-click or long press (`quotaRowMenuItems` in `plugins/usage/page.js`) adds *Hide {group} from Overview* to the card's menu, and the card's "…" lists each group. The group is a pool's or model family's name, else the window's (`windowGroup`), so a pool's 5-hour and weekly rows go together. Kept as `provider|group` in `settings.UsageWindowsHidden` through `POST /api/usage/arrange` (`windowsHidden`), every account of the provider alike, and kept by the Settings save. `overviewCards` hands the page a copy without them (`withoutHiddenRows`); caps, routing, counting, the tray panel and the menu bar read the full card. A card is never left with no row: a card with one group offers no Hide, and one whose every group is named shows all. The "{n} hidden" line counts the rows with the cards, each with *Unhide* (`hideQuotaRows`). See `TestUsageArrangeWindowsHidden` and `usage-rows-hide.test.cjs`. - A client in the Usage page's Agents list can be hidden from that list (ikunbots on X): its row's "…" button or right-click opens the row menu with *Hide from this list*, saved by client id in `settings.UsageAgentsHidden` through the same `POST /api/usage/arrange` (`agentsHidden`), and kept by the Settings save. The ledger, the totals and the chart still count a hidden client. A "{n} hidden" line under the list opens them, each with *Unhide* (`hideUsageAgent`), and while any are hidden the row menu ends with *Show {n} Hidden*, which opens it as the cards' does (`openHidden`). See `TestUsageArrangeAgentsHidden`, `usage-agents-hide.test.cjs` and `usage-hidden-way-back.test.cjs`. -- Usage › Overview's Agents, Models, Accounts and Gateway keys lists each fold under their heading (#2378): the heading is a `.fold` button with its chevron, as on the Gateway page, and the click doesn't move the page (`backToReader`). What is folded is kept per viewer in localStorage `magpie.usageFolded` (`mountUsageFolds`, `showUsageFolds`). The totals leave the cache out, as before, unless the tokens tile's label, a pop-up button (`usageTokensPick`, the app menu), is set to *With cache*: then the tile, the chart and every row's count and share add cache read and written (`usageTokens`), and the tile says the cache's count; kept in localStorage `magpie.usageWithCache`. The Sessions tab counts by the same pick (#2591): its tokens tile carries the same label pop-up and says the cache's count, and the list's rows, the projects and models bars and pickers, the day chart (whose day and week buckets carry the cache's counts), the calendar and the top sessions read `usageTokens` too, the top list ranked again by the count shown (`sessTokens`, `sessSums`, `renderSessChart`, `renderSessTop`); a pick made on that tab refreshes the tab, not the Overview. The per-session median and p90 stay counted in and out (`Stats.Overview`). The Requests tab's total already counts every token (`allTokens`). A token line in parts (the Requests strip's Tokens card, the Overview's and the Sessions tab's tokens tiles) wraps between its counts and keeps each whole (`usageParts`, `.parts`); only a count wider than its card on its own is cut. See `usage-overview-fold.test.cjs` and `sessions-cache-tokens.test.cjs`. +- Usage › Overview's Agents, Models, Accounts and Gateway keys lists each fold under their heading (#2378): the heading is a `.fold` button with its chevron, as on the Gateway page, and the click doesn't move the page (`backToReader`). What is folded is kept per viewer in localStorage `magpie.usageFolded` (`mountUsageFolds`, `showUsageFolds`). The totals leave the cache out, as before, unless the tokens tile's label, a pop-up button (`usageTokensPick`, the app menu), is set to *With cache*: then the tile, the chart and every row's count and share add cache read and written (`usageTokens`), and the tile says the cache's count; kept in localStorage `magpie.usageWithCache`. The Sessions tab counts by the same pick (#2591): its tokens tile carries the same label pop-up and says the cache's count, and the list's rows, the projects and models bars and pickers, the day chart (whose day and week buckets carry the cache's counts), the calendar and the top sessions read `usageTokens` too, the top list ranked again by the count shown (`sessTokens`, `sessSums`, `renderSessChart`, `renderSessTop`); a pick made on that tab refreshes the tab, not the Overview. The per-session median and p90 stay counted in and out (`Stats.Overview`). The account cards' whole-window estimate follows the same pick (Anotiaww on X): with cache, it adds the cache read and written that magpie routed in the window, scaled by the same share used, and says so (`holdsLine`, now in the Usage plugin's `page.js`, redrawn with the cards when the pick changes; `quota-holds.test.cjs`). The Requests tab's total already counts every token (`allTokens`). A token line in parts (the Requests strip's Tokens card, the Overview's and the Sessions tab's tokens tiles) wraps between its counts and keeps each whole (`usageParts`, `.parts`); only a count wider than its card on its own is cut. See `usage-overview-fold.test.cjs` and `sessions-cache-tokens.test.cjs`. - A click on a row of the Usage page's Requests (or Enter or Space on it) opens that one request on a page of its own, `#ledReqPane` in place of the list, not Routing (geesehowardt7 on X; `ledReqOpen`, `renderLedReq`): Requests ‹ or Escape goes back to the list where it was left and to its row (`ledReqClose`), and leaving the page closes it (`ledLeave`). The page heads with the model and status, then `ledDetail`: time, agent, source IP (`client_ip`; a loopback address is "This computer", a gateway row older than the field "Not recorded"), requested, provider, account, sent, served, effort, then status, error, duration, tokens, cost and the rest; Routing is the *View routing* link in it. A refresh keeps the page as it was opened (`usage-request-page.test.cjs`, `usage-ledger-detail.test.cjs`). - A request's details in the Usage ledger say its tokens at every width (#1839, `ledDetail`): "{i} in · {o} out · {r} cache read · {w} cache creation", 0 said as 0, with how much was written for 5 minutes and for an hour when it says so. A failure that spent nothing has no Tokens row. See `ledger-cache-tokens.test.cjs` and `usage-ledger-detail.test.cjs`. - The requests magpie makes by itself (a routing classifier's, a web search's, an image description's) are told apart from the agents' on the Usage page (#1839): magpie's row among the agents and its rows in the ledger carry a "magpie's own" mark (`ownBadge`), an account's, key's or model's row adds "{n} by magpie itself" from the summary's `own`, and an account's card says how many of the period's requests were magpie's own (`ownLine`, drawn again once the summary comes after the allowances). See `own-requests.test.cjs` and `TestSummaryCountsMagpiesOwnCallsApart`. diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 3b795282b..a8c77a34d 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -368,7 +368,9 @@ premium, so cycles whose calls' sizes differ compare on that figure. It is sent only when it differs from `Cost`; the card's figure is then a button that switches every card, past cycles too, between the two, kept in the browser (`holdsBase`, `quota-holds.test.cjs`, -`TestWindowHoldsBaseCostLeavesOutLongContextPremiums`). See +`TestWindowHoldsBaseCostLeavesOutLongContextPremiums`). `Tokens` counts input +and output; with the Usage page's tokens pick on *With cache* the card adds +`Routed.CacheRead` and `CacheWrite` over the same share used (`holdsLine`). See `TestWindowHoldsDryAgainAfterReset`, `TestWindowHoldsUsesObservedRefillStart` and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index f0a7491d3..fd32fbda7 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -18676,64 +18676,6 @@ function familyQuota(sub) { return [box, b]; } -// holdsLine: a window's whole (WindowHolds), how in its tooltip. With a -// baseCost (#5861, no long-context premium) its figure switches every card. -let holdsBase = kept("holdsBase", false); -function holdsCostText(h, prov) { - const c = fmtCost({ cost: holdsBase ? h.baseCost : h.cost }, prov); - return holdsBase ? t("≈ {cost} base", { cost: c }) : t("≈ {cost} API", { cost: c }); -} -function holdsLine(h, prov) { - const cost = (c) => fmtCost({ cost: c }, prov); - const line = el("span", "quota-holds"); - line.append(el("span", "", t("Whole ≈ {n} tokens", { n: fmtN(h.tokens) }) + (h.priced ? " ·" : ""))); - const two = h.priced && h.baseCost > 0; - if (two) { - const b = el("button", "quota-holds-cost", holdsCostText(h, prov)); - b.type = "button"; - b._holds = h; - b._prov = prov; - b.onclick = (e) => { - e.preventDefault(); - e.stopPropagation(); - holdsBase = !holdsBase; - keep("holdsBase", holdsBase); - for (const o of document.querySelectorAll(".quota-holds-cost")) if (o._holds) o.textContent = holdsCostText(o._holds, o._prov); - }; - line.append(" ", b); - } else if (h.priced) line.append(" ", el("span", "", "≈ " + cost(h.cost))); - const r = h.routed || {}; - line.title = [ - h.priced ? t("The whole window ≈ {tokens} tokens of input and output, ≈ {cost} at API list prices", { tokens: fmtN(h.tokens), cost: cost(h.cost) }) - : t("The whole window ≈ {tokens} tokens of input and output; some of its models have no API price", { tokens: fmtN(h.tokens) }), - ...(two ? [ - t("≈ {cost} at base rates, without long-context premiums: for comparing cycles", { cost: cost(h.baseCost) }), - t("Neither is an official dollar allowance or a fixed quota; click the figure to switch"), - ] : []), - t("Reckoned from what magpie routed through this account in this window: {tokens} tokens in {calls} calls, {cache} cache reads, over the {used} the vendor says is used", { tokens: fmtN(r.tokens || 0), calls: r.calls || 0, cache: fmtN(r.cacheRead || 0), used: Math.round(h.used) + "%" }), - t("Only magpie's calls are counted: if this account is also used elsewhere, this reads low"), - t("A heavier model fills a window sooner: this holds for the models used so far"), - ].join("\n"); - return line; -} - -// holdsWhy: why a whole isn't told (provider.Holds*); one not listed says nothing. -const holdsWhy = { - low: () => t("Under {n}% of it is used: a rounded share that small is too coarse to scale up", { n: 5 }), - clock: () => t("Its reset time isn't known, so neither is when it began"), - log: () => t("It began before magpie's request log, so some of its calls weren't seen"), - none: () => t("magpie hasn't routed a call through this account in it yet"), - credits: () => t("A call in it may have been paid from credits or extra usage, not from the window"), -}; -// holdsUnknownLine: a window whose whole the server couldn't reckon -// (#2045): "not enough data", muted, and why in its tooltip, where it said -// nothing before and a reader couldn't tell a gap from a fault. -function holdsUnknownLine(why) { - const line = el("span", "quota-holds-why", t("Whole: not enough data")); - line.title = t("The whole window can't be estimated from magpie's calls yet") + "\n" + holdsWhy[why](); - return line; -} - // isKeyCard: the card of a remote magpie's gateway keys (#1547, // remote_key_limits.go), "/~keys", one account per key; quotaName // says so by its name, which is the remote's. diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index 84c22b84b..3a9873dc5 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -69,6 +69,9 @@ magpie.strings({ "Show the gateway keys": "展开网关密钥", "Fold the gateway keys away": "收起网关密钥", "tokens with cache": "token(含缓存)", + "Whole ≈ {n} tokens with cache": "整窗 ≈ {n} tokens(含缓存)", + "The whole window ≈ {tokens} tokens, cache read and written included, ≈ {cost} at API list prices": "整个窗口 ≈ {tokens} tokens(含缓存读取与写入),按 API 标价 ≈ {cost}", + "The whole window ≈ {tokens} tokens, cache read and written included; some of its models have no API price": "整个窗口 ≈ {tokens} tokens(含缓存读取与写入);其中有模型没有 API 标价", "Count the cache's tokens in the totals, or leave them out": "选择 token 汇总是否计入缓存", "Without cache": "不含缓存", "Input and output": "输入与输出", @@ -344,6 +347,9 @@ magpie.strings({ "Show the gateway keys": "展開閘道金鑰", "Fold the gateway keys away": "收起閘道金鑰", "tokens with cache": "token(含快取)", + "Whole ≈ {n} tokens with cache": "整窗 ≈ {n} tokens(含快取)", + "The whole window ≈ {tokens} tokens, cache read and written included, ≈ {cost} at API list prices": "整個視窗 ≈ {tokens} tokens(含快取讀取與寫入),按 API 標價 ≈ {cost}", + "The whole window ≈ {tokens} tokens, cache read and written included; some of its models have no API price": "整個視窗 ≈ {tokens} tokens(含快取讀取與寫入);其中有模型沒有 API 標價", "Count the cache's tokens in the totals, or leave them out": "選擇 token 總計是否計入快取", "Without cache": "不含快取", "Input and output": "輸入與輸出", @@ -619,6 +625,9 @@ magpie.strings({ "Show the gateway keys": "ゲートウェイキーを表示", "Fold the gateway keys away": "ゲートウェイキーを折りたたむ", "tokens with cache": "トークン(キャッシュ込み)", + "Whole ≈ {n} tokens with cache": "枠全体 ≈ {n} トークン(キャッシュ込み)", + "The whole window ≈ {tokens} tokens, cache read and written included, ≈ {cost} at API list prices": "枠全体 ≈ {tokens} トークン(キャッシュの読み取りと書き込みを含む)、API 定価で ≈ {cost}", + "The whole window ≈ {tokens} tokens, cache read and written included; some of its models have no API price": "枠全体 ≈ {tokens} トークン(キャッシュの読み取りと書き込みを含む)。API 価格のないモデルが含まれます", "Count the cache's tokens in the totals, or leave them out": "合計にキャッシュのトークンを含めるかどうか", "Without cache": "キャッシュなし", "Input and output": "入力と出力", @@ -894,6 +903,9 @@ magpie.strings({ "Show the gateway keys": "Gateway-Schlüssel anzeigen", "Fold the gateway keys away": "Gateway-Schlüssel einklappen", "tokens with cache": "Token mit Cache", + "Whole ≈ {n} tokens with cache": "Gesamt ≈ {n} Tokens mit Cache", + "The whole window ≈ {tokens} tokens, cache read and written included, ≈ {cost} at API list prices": "Das ganze Fenster ≈ {tokens} Tokens, Cache-Lesen und -Schreiben eingerechnet, ≈ {cost} zu API-Listenpreisen", + "The whole window ≈ {tokens} tokens, cache read and written included; some of its models have no API price": "Das ganze Fenster ≈ {tokens} Tokens, Cache-Lesen und -Schreiben eingerechnet; einige seiner Modelle haben keinen API-Preis", "Count the cache's tokens in the totals, or leave them out": "Die Token des Caches in den Summen mitzählen oder weglassen", "Without cache": "Ohne Cache", "Input and output": "Eingabe und Ausgabe", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 25476a553..b18ff1ff7 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -788,11 +788,77 @@ function usageTokensPick() { // the tab it was picked on follows; the pick lives on the Overview's // and the Sessions tab's tokens tiles (#2591) (usageTab === "sessions" ? renderSessions : renderUsage)(); + // and the account cards' whole-window estimates (holdsLine) + if (usageTab !== "sessions" && quotas) renderQuotas(); }, "Token totals", "sess-menu"); }; return b; } +// holdsLine: a window's whole (WindowHolds), how in its tooltip. With a +// baseCost (#5861, no long-context premium) its figure switches every card. +let holdsBase = kept("holdsBase", false); +function holdsCostText(h, prov) { + const c = fmtCost({ cost: holdsBase ? h.baseCost : h.cost }, prov); + return holdsBase ? t("≈ {cost} base", { cost: c }) : t("≈ {cost} API", { cost: c }); +} +function holdsLine(h, prov) { + const cost = (c) => fmtCost({ cost: c }, prov); + const line = el("span", "quota-holds"); + const r = h.routed || {}; + // with the tokens tiles' "with cache" pick, the cache's tokens, read and + // written, scaled by the same share used (Anotiaww on X) + const cache = usageWithCache && h.used > 0 ? Math.round(((r.cacheRead || 0) + (r.cacheWrite || 0)) * 100 / h.used) : 0; + const tokens = fmtN(h.tokens + cache); + line.append(el("span", "", t(usageWithCache ? "Whole ≈ {n} tokens with cache" : "Whole ≈ {n} tokens", { n: tokens }) + (h.priced ? " ·" : ""))); + const two = h.priced && h.baseCost > 0; + if (two) { + const b = el("button", "quota-holds-cost", holdsCostText(h, prov)); + b.type = "button"; + b._holds = h; + b._prov = prov; + b.onclick = (e) => { + e.preventDefault(); + e.stopPropagation(); + holdsBase = !holdsBase; + keep("holdsBase", holdsBase); + for (const o of document.querySelectorAll(".quota-holds-cost")) if (o._holds) o.textContent = holdsCostText(o._holds, o._prov); + }; + line.append(" ", b); + } else if (h.priced) line.append(" ", el("span", "", "≈ " + cost(h.cost))); + line.title = [ + usageWithCache ? (h.priced ? t("The whole window ≈ {tokens} tokens, cache read and written included, ≈ {cost} at API list prices", { tokens, cost: cost(h.cost) }) + : t("The whole window ≈ {tokens} tokens, cache read and written included; some of its models have no API price", { tokens })) + : h.priced ? t("The whole window ≈ {tokens} tokens of input and output, ≈ {cost} at API list prices", { tokens, cost: cost(h.cost) }) + : t("The whole window ≈ {tokens} tokens of input and output; some of its models have no API price", { tokens }), + ...(two ? [ + t("≈ {cost} at base rates, without long-context premiums: for comparing cycles", { cost: cost(h.baseCost) }), + t("Neither is an official dollar allowance or a fixed quota; click the figure to switch"), + ] : []), + t("Reckoned from what magpie routed through this account in this window: {tokens} tokens in {calls} calls, {cache} cache reads, over the {used} the vendor says is used", { tokens: fmtN(r.tokens || 0), calls: r.calls || 0, cache: fmtN(r.cacheRead || 0), used: Math.round(h.used) + "%" }), + t("Only magpie's calls are counted: if this account is also used elsewhere, this reads low"), + t("A heavier model fills a window sooner: this holds for the models used so far"), + ].join("\n"); + return line; +} + +// holdsWhy: why a whole isn't told (provider.Holds*); one not listed says nothing. +const holdsWhy = { + low: () => t("Under {n}% of it is used: a rounded share that small is too coarse to scale up", { n: 5 }), + clock: () => t("Its reset time isn't known, so neither is when it began"), + log: () => t("It began before magpie's request log, so some of its calls weren't seen"), + none: () => t("magpie hasn't routed a call through this account in it yet"), + credits: () => t("A call in it may have been paid from credits or extra usage, not from the window"), +}; +// holdsUnknownLine: a window whose whole the server couldn't reckon +// (#2045): "not enough data", muted, and why in its tooltip, where it said +// nothing before and a reader couldn't tell a gap from a fault. +function holdsUnknownLine(why) { + const line = el("span", "quota-holds-why", t("Whole: not enough data")); + line.title = t("The whole window can't be estimated from magpie's calls yet") + "\n" + holdsWhy[why](); + return line; +} + function renderUsage() { const u = usage; const view = $("#view-usage"); diff --git a/internal/gui/tests/quota-holds.test.cjs b/internal/gui/tests/quota-holds.test.cjs index 037b08dfe..f0860d00b 100644 --- a/internal/gui/tests/quota-holds.test.cjs +++ b/internal/gui/tests/quota-holds.test.cjs @@ -29,7 +29,7 @@ const quotas = [ { name: "Credits", used: 30, holdsWhy: "clock" }, ] }, ]; -function serve(lang, cards = quotas) { +function serve(lang, cards = quotas, summary) { const settings = { lang, theme: "light", currency: "usd", chineseUnits: lang.startsWith("zh") }; const state = { agents: [], profiles: [], settings }; return async (r) => { @@ -44,6 +44,7 @@ function serve(lang, cards = quotas) { if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); if (url.pathname === "/api/usage/quotas") return json(cards); + if (url.pathname === "/api/usage" && summary) return json(summary); if (url.pathname === "/api/plugins") return json({ plugins: [] }); if (url.pathname.startsWith("/api/")) return json({}); const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); @@ -244,3 +245,77 @@ for (const [name, engine] of [["webkit", webkit], ["chromium", chromium]]) { } finally { await browser.close(); } }); } + +// Anotiaww on X: the whole-window estimate follows the Overview's tokens +// pick. With cache, it adds the cache read and written magpie routed in the +// window, scaled by the same share used, and says so on the line and in the +// tooltip; picked on the tokens tile, the cards follow at once, the pick is +// kept for the next load, and picked back the line is as it was. +const cacheCard = [{ provider: "claude", name: "Claude Code", icon: "claude-color", plan: "max", user: "dee@example.com", windows: [ + { name: "5 hours", used: 20, resetsAt: soon(2), holds: (() => { const h = holds(12345678, 85.4321, 20); h.routed.cacheWrite = 1000000; return h; })() }, +] }]; +// 12345678 in and out, and (52345678 + 1000000) cache over 20% used +const withCacheTokens = 12345678 + (52345678 + 1000000) * 5; +const summary = { calls: 30, errors: 0, input: 5000000, output: 2000000, reasoning: 0, cache_read: 90000000, cache_write: 0, unpriced: 0, cost: 0, bucket: "day", + series: [{ label: "Oct 15", time: new Date().toISOString(), calls: 30, input: 5000000, output: 2000000, cache_read: 90000000, cache_write: 0, cost: 0 }], + path: "~/.config/magpie/usage.jsonl", agents: [], models: [], accounts: [], callerKeys: [] }; +const withCache = { + en: { line: (n) => `Whole ≈ ${n} tokens with cache`, tip: "cache read and written included" }, + zh: { line: (n) => `整窗 ≈ ${n} tokens(含缓存)`, tip: "含缓存读取与写入" }, + "zh-TW": { line: (n) => `整窗 ≈ ${n} tokens(含快取)`, tip: "含快取讀取與寫入" }, + ja: { line: (n) => `枠全体 ≈ ${n} トークン(キャッシュ込み)`, tip: "キャッシュの読み取りと書き込みを含む" }, + de: { line: (n) => `Gesamt ≈ ${n} Tokens mit Cache`, tip: "Cache-Lesen und -Schreiben eingerechnet" }, +}; + +for (const [name, engine] of [["webkit", webkit], ["chromium", chromium]]) { + test(`${name}: the whole follows the tokens tile's with-cache pick, in every language`, async () => { + const browser = await engine.launch(); + try { + for (const lang of Object.keys(withCache)) { + for (const width of [360, 1000]) { + const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + await page.route("**/*", serve(lang, cacheCard, summary)); + await page.goto("http://magpie.test/?view=usage"); + await page.locator(".subscription-card .quota-holds").first().waitFor(); + await page.locator("#stats .kpi .kpi-pick").first().waitFor(); + const at = `${lang} ${width}px`; + const read = () => page.locator(".quota-holds").first().evaluate((l) => { + const card = l.closest(".subscription-card").getBoundingClientRect(), b = l.getBoundingClientRect(); + return { text: l.textContent, title: l.title, inCard: b.left >= card.left - 1 && b.right <= card.right + 1, + cut: [...l.children].some((s) => s.scrollWidth > s.clientWidth + 1 || s.getBoundingClientRect().right > card.right + 1) }; + }); + const plain = await read(); + assert.equal(plain.text, want[lang].line + " · ≈ $85.43", at); + assert.ok(!plain.title.includes(withCache[lang].tip), at); + const n = await page.evaluate((v) => fmtN(v), withCacheTokens); + // picked With cache on the tokens tile: the card follows at once + await page.locator("#stats .kpi .kpi-pick").first().click(); + const menu = page.locator(".proto-menu:visible"); + await menu.waitFor(); + await menu.locator(".pm-item").nth(1).click(); + await page.waitForFunction((t) => document.querySelector(".quota-holds")?.textContent.startsWith(t), withCache[lang].line(n)); + let got = await read(); + assert.equal(got.text, withCache[lang].line(n) + " · ≈ $85.43", at); + assert.ok(got.title.split("\n")[0].includes(withCache[lang].tip) && got.title.split("\n")[0].includes(n), `${at}: ${got.title}`); + assert.equal(got.title.split("\n").length, 4, at); + assert.ok(got.inCard && !got.cut, `${at}: ${JSON.stringify(got)}`); + // kept for the next load + await page.reload(); + await page.locator(".subscription-card .quota-holds").first().waitFor(); + assert.equal((await read()).text, withCache[lang].line(n) + " · ≈ $85.43", `${at}: not kept`); + // and back without: as it was + await page.locator("#stats .kpi .kpi-pick").first().click(); + await page.locator(".proto-menu:visible").waitFor(); + await page.locator(".proto-menu:visible .pm-item").nth(0).click(); + await page.waitForFunction((t) => document.querySelector(".quota-holds")?.textContent === t, plain.text); + got = await read(); + assert.deepEqual([got.text, got.title], [plain.text, plain.title], at); + await context.close(); + } + } + } finally { await browser.close(); } + }); +} diff --git a/internal/provider/window_holds.go b/internal/provider/window_holds.go index c94860f50..8d0ca0354 100644 --- a/internal/provider/window_holds.go +++ b/internal/provider/window_holds.go @@ -14,7 +14,8 @@ import ( // WindowHolds is a window's whole allowance reckoned from magpie's own // calls: Tokens of input and output (cache traffic aside, as the Usage -// page counts tokens) and, when every call's model has an API list price, +// page counts tokens unless its pick is With cache, when the card adds +// Routed's cache over Used itself) and, when every call's model has an API list price, // Cost at those prices (cache reads and writes at the vendor's own rates). // Routed is what magpie routed through the account in the window so far, // up to when the share was read, and Used that share. A call made with the