4794de398ea8337d223a91e207181c56fcf4ad76
42
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
99fcddeeba |
usage: the Requests tab, its filters and refresh, the charts, the TUI and magpie usage answer at once over a long history (Vantiboo1ean)
Vantiboo1ean (Discord, macOS M2, v0.1.1157) has ~750,000 requests in usage.jsonl. On Usage > Requests every filter, model pick and refresh spun forever and the page never updated. Reproduced in a sandbox HOME with 750k generated records in the real format (400 MB usage.jsonl, ~84k sessions), on magpie web and in process. The cause: the #563 budget dropped the index's blocks once they passed 24 MB (60 MB here), so every read, of any period, parsed the whole file again (6 s CPU) and priced every call again; All took 12 s of CPU, the heatmap 13 s, and the page read both at once. What changed: - log_index: the gateway's blocks are always kept (about 80 bytes a call, S2-compressed instead of flate); the file is parsed once, then only what was appended. - block_price: the gateway's blocks are priced per query, once per set of provider/model/served/effort names rather than per call, into pooled buffers; range loops go by pointer (a packed row is 264 bytes). - request_page: pages are always cached (16 at most), session-file chunks stay in the budget, and a page asked again while it is worked out (the refresh button, the timer) waits for that one instead of starting a second scan. - Siblings that read the same history: - The heatmap names each day once. - A day filter no longer allocates per call. - The ledger behind the TUI, magpie usage, the CSV export and sync (LedgerOf, OwnDays) reads the gateway's calls from the index instead of Load parsing the whole file. - Direct/Summaries matches the session files' calls against the index's blocks without pricing all 750k gateway calls. - A summary of more than 1024 sessions is now cached with its top 1024 (it was not cached at all). The Usage page's /api/usage gets the top 100 (it was sent all 84k, 19 MB, which it never draws) plus a new sessionCount. /v1/magpie/usage still lists every session, and magpie usage says "top 10 of <sessionCount>". Timings, CPU (the box was at load 130-190 on 14 cores, so wall is inflated; min of repeated runs), before -> after: Requests today 6.0 s -> 20 ms Requests 7d 5.8 s -> 93 ms Requests 30d ~6 s -> 362 ms Requests all 12.4 s -> 2.4 s first, ~8 ms again all, model filter 12.3 s -> 1.5 s all, agent filter 11.3 s -> 1.8 s 30d, search "opus" 6.7 s -> 353 ms day filter 6.0 s -> ~0.1 s heatmap 13.7 s -> ~2.3 s first summary today / all 6.0 / 9.2 s -> 25 ms / 1.6 s first, <1 ms again /api/usage?period=all 1.6 s + 19 MB JSON each time -> <1 ms, 53 KB TUI Summaries(all) ~8.5 s (Load + ledger) -> 1.1 s first, <1 ms again TUI Summaries(today) ~6 s -> 29 ms Visit 7d (budget, codex) 5.9 s -> 10 ms The first read of the file after start costs ~5 s of CPU, once. Tests (each seen red with its guarantee broken by hand): - TestUsageOverBudgetHistoryIsReadOnce - TestUsageSessionChunksStayInBudget - TestUsageOverBudgetPageIsCached - TestUsagePageAskedTwiceIsWorkedOutOnce - TestUsageLedgerReadsTheIndexNotTheFile - TestUsageLargeSummaryIsCompleteAndKeptTrimmed (was ...ButNotCached) - TestDirectCountsOnlySessionFileCalls, now with a request-id match, checks that Direct/Summaries equal the ledger's. Run: go test -tags nogui ./... (temp HOME), gofmt -l, GOOS=linux and GOOS=windows go vet on the touched packages. |
||
|
|
e9221e96dd |
provider, netproxy, gui: allowances can be read only when asked, and a system proxy set after start is taken within seconds (#1518, RooobinYe)
The reporter starts magpie at login with the proxy on "follow system
proxy". magpie comes up before the proxy app. With no system proxy set
yet, netproxy.For gives none, so magpie's own allowance reads went out
direct, from the user's real IP. That reading was then kept for up to
15s. A system proxy that is set but not listening fails the request
("proxyconnect ... connection refused"); it never falls back to direct.
Proxy freshness:
- netproxy.System re-reads a "none" reading after 2s (noneKeep) instead
of 15s (systemKeep, unchanged for a set proxy).
- The plugin host looks again every 2s while it has no proxy
(proxyLookNone), so a host started before the proxy app takes it soon.
- Catalog sync, the update check, plugin updates and token refresh all go
through netproxy.Func / Dispatch, so they use the current proxy too.
Settings -> Allowances -> "Allowance reads": Automatic (default, as
before) or When I ask (settings.QuotaReads = "asked",
POST /api/settings/quota-reads):
- These count as asking (provider.Asked): the Usage page opened or
refreshed (?asked=1), a card's refresh (RefreshUsage), magpie quota,
magpie accounts, magpie quota wait and the TUI's quotas.
- Every other read (quotaReading -> holdUnasked) carries netproxy.Hold.
netproxy.Func, Dispatch's choice proxies and the plugin host's calls
refuse a held request before it leaves.
- The readers return the last reading, dated (AsOf), or "not read yet".
That covers routing's Allowances / AwaitAllowance, the used-up switch,
the menu bar, alerts, Quotas/KeyBalances/PlanQuotas, Codex/Claude/
Cursor/Grok/Kiro usage and KeyAllowance.
- An account refused for its quota (StaleAllowance) or a key refused
(StaleKeyAllowance) is still read, once.
- Warm-up and check-in are unchanged.
- Strings are added in zh, zh-TW, ja and de. The docs are updated:
providers-accounts (Allowance row), provider-plugins (host proxy).
Run:
- go test -tags nogui ./... (sandbox HOME), gofmt -l, and go vet -tags
nogui on GOOS=linux/windows/darwin for ., netproxy, plugin, settings,
provider, gui and tui.
- New tests, each seen red by breaking the change by hand:
- TestSystemProxySetAfterStartIsTakenSoon and TestHeldRequestNeverLeaves
(netproxy).
- TestHostWithNoProxyLooksAgainSoon (plugin; red with 15s).
- TestAllowancesReadOnlyWhenAsked (red without the hold and without
markStaleRead), TestAllowancesReadByThemselvesByDefault and
TestKeyReadsOnlyWhenAsked (red without holdUnasked and without
unheld for a refused key).
- GUI quota-reads.test.cjs in Chromium and WebKit, at 900 and 360px, in
en/zh/zh-TW/ja/de.
- i18n-keys, gui-ja, gui-de, settings-sections, settings-groups,
currency, number-units and tray-bird.
|
||
|
|
b6a263b9fd |
gateway, usage: the Usage page's numbers are read over the gateway, and a Claude Code subagent's call says which subagent and which started it (HoGee_xxl on X)
HoGee_xxl wants their own usage app to read magpie over the gateway, which had no /api/usage counterpart, and asked for subagents' parent ids. - GET /v1/magpie/usage (the /api/usage summary, ?period=) and GET /v1/magpie/usage/requests (the /api/usage/requests ledger page, same filters, offset/limit) on the gateway. The builders moved out of gui into internal/usageapi so both serve the same JSON; gui keeps aliases and sets usageapi.Clients for agent names (gateway can't import agent). Guard as /v1/magpie/quotas: this machine, or another with an enabled gateway key, behind the same Host check. A key held to a budget, models or accounts is refused the summary (403) and gets the ledger filtered to its own CallerKey, with callerKeys/agents/providers/accounts cut to its own rows (usageapi.OwnPage): those facets are drawn from every call in the period. `path` is left out for another machine. - usage.Record gains subagent and parent_agent; session stays the parent conversation. Gateway rows take them from x-claude-code-agent-id and x-claude-code-parent-agent-id; session-file rows from the file name (<session>/subagents[/workflows/<run>]/agent-<id>.jsonl, no cache version bump) and the parentAgentId of the agent-<id>.meta.json beside it. Both packed into the request page's text columns (now 29, msg at 29). Codex sub-threads: only kind, as before; no spawned thread on disk to take a parent shape from. Run: real Claude Code 2.1.296 under a sandbox CLAUDE_CONFIG_DIR against a local fake Anthropic endpoint that made it spawn a subagent from a subagent: the nested request carried X-Claude-Code-Agent-Id=a143287ac46b82a96 and X-Claude-Code-Parent-Agent-Id=a99ca20c03d1813d8, the first-level one the agent id only, Session-Id the parent's throughout; the nested meta.json had parentAgentId. Tests use those bytes. TestUsageOverGateway goes red with OwnPage, the CallerKey pin, or the header read removed (each tried). gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; set -o pipefail; go test ./... green. |
||
|
|
690bc352f2 |
gui, provider: a Codex reset spent on Usage shows at once in the Providers editor and in routing (#1491, isdou)
isdou spent a reset on the Usage page: Usage showed the windows at 100%
left and 2 resets, while the Providers editor still said the week was
used up with 3 resets, and Routing said the account's allowance was
unknown and sent requests on to the next account.
Two reasons, one per page:
- The Providers editor reads each account's windows itself
(loginUsageOf, /api/login/usage) and keeps the reading a minute in
the page. askReset reloaded Usage's quotas only. It now drops the
editor's Codex reading too, and re-renders an open editor.
- UseCodexReset forgets the account's allowance (renewedNow), so until
the next background reading routing had no windows for it: weighed as
not known, behind the others, and a reading already out, begun before
the reset, is dropped for it too. The codex-reset handler now waits
(up to 10s) for provider.AwaitAllowance, which has the accounts read
again and asks once more when a reading begun before the reset lands,
so by the time the page hears "reset", routing knows the windows
started again, and /api/login/usage has the new reading cached.
Tests:
- provider TestResetAllowanceKnownAtOnce: a fake reader, the reset
spent with no reading out and with one out (held in the fake until
after renewedNow). Red with AwaitAllowance a no-op (not known), and
red with it asking one reading only (the in-flight case).
- reset-providers.test.cjs: Providers editor opened (3 resets), reset
on Usage, editor opened again: says 2. Red on origin/main's app.js
("still says 3 resets", login/usage not asked again) in all four;
passes in Chromium and WebKit, en and zh, 420 and 1000px.
Run: go test -tags nogui ./internal/provider/ ./internal/gui/ (ok),
-race -count=20 on the new provider test, gofmt -l clean.
|
||
|
|
6d3bc9183d |
usage: the Usage and Requests pages count any days picked, from a Custom opt after All that opens a month to pick them on (#1492, nianlee-official)
The period bar had only Today, 7 days, 30 days and All. A Custom opt now
follows them. It opens the app's own menu (no native select): Yesterday,
This month, Last month and 90 days a click away, and a month of days to
pick the first day on, then the last. Days after today can't be picked;
arrows walk the days and Escape closes. Once picked, the opt names the
days ("Oct 1 – Oct 7"), and narrow windows show only its icon until then.
The backend takes the days as period "2026-10-01..2026-10-07", both
included, in the local time zone (usage.RangeOf, Period.Known/Until).
The summary, the Requests page (index and ledger fallback), Direct and the
CSV name count only calls from the first day's midnight up to the
midnight after the last. The chart is an hour each for one day, a day each
up to 60 days, and a week each from a Monday past that. A picked range is
summarised afresh each time, so ranges never pile up in the summary cache.
The credits-per-day card follows the days picked. New strings in zh,
zh-TW, ja and de.
Run:
- go test -tags nogui ./internal/usage ./internal/gui (sandbox HOME): ok.
- TestPickedDaysArePeriod with Until returning zero (no range end):
FAIL, Summarize 5 calls / QueryPage 5 rows / LedgerOf 5 rows, want 3.
- usage-range.test.cjs, Chromium and WebKit, en and zh, at 390px: 4/4.
- Every GUI test touching period or the Usage view (87 files): Chromium
388/388; WebKit 386/388, the two purpose-filter's Routing focus check
(scrollTop off by 1px after a wheel), which then passed 52 of 56 lone
runs here and 25 of 25 on origin/main; nothing in this change runs on
the Routing page. gui-de, gui-ja, gui-zh-tw, i18n-keys: pass.
- gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui on both pkgs.
|
||
|
|
ee657c0969 |
usage: a Kimi Code membership's k3 is counted at Kimi's API price for kimi-k3, not ≈¥0.000, and kimi-for-coding is unpriced rather than free (#1370, maicent: Kimi Code 的模型计费都是 0)
Why it was 0: magpie already counts a subscription's calls at the API list
price (a Claude or Codex account at its maker's,
|
||
|
|
d1d4b7ed2a |
usage: a heatmap of the last 53 weeks on the Requests tab, by tokens, requests or cost (#1369, nianlee-official)
What changed: the Requests tab of the Usage page shows a heatmap card like CC Switch's: a cell per day for the last 53 weeks, Monday on top, month names over the weeks and weekday names at the edge, a Tokens / Requests / Cost switch (kept in localStorage), a five-shade Less…More legend, and a tip on each day with its date, tokens, requests and cost. How: GET /api/usage/heatmap (usage.HeatmapOf) reads QueryPage's cached request index over a hidden period, "heatmap", which starts on the Monday 52 weeks before this week's. Its rows are summed by local calendar day in both the compact and the ledger path. So no raw log is scanned per render, and the days count what the chart counts: - the page's agent/provider/model/key filters, but not the period or day picked; - the gateway's own rejections left out; - cost of priced calls only, with an unpriced count. The days are in the local time zone and the shades use theme tokens (.l0–.l4, as in the sessions calendar). There are no left-border accents and no native <select>. A click never scrolls the page. A narrow window scrolls the card sideways inside itself, with the newest week in sight (kept there as it's laid out or resized, until the reader scrolls back), and the weekday names stay at the card's edge. The card is hidden when no day has calls. New strings are in zh, zh-TW, ja and de. Run: - go test -tags nogui ./internal/usage ./internal/gui (new TestHeatmapDays, TestHeatmapOf, TestUsageHeatmapRoute); gofmt -l clean; go vet darwin, GOOS=linux and GOOS=windows go vet -tags nogui on both packages; go build for darwin, linux and windows. - New internal/gui/tests/usage-heatmap.test.cjs in Chromium and WebKit, at 420 and 1100, in en, zh, zh-TW, ja and de, plus dark and the empty case. It checks: - the cells, labels, legend and the busiest and quiet days; - the newest week in sight and only the card scrolling sideways; - the tip's text and that it stays inside the card; - that a metric click moves nothing and is kept; - that the filters, but no period or day, are sent. - Breaking checks: with the keep-at-end guard reverted, 5 of its 11 subtests fail in WebKit; with the server's heatmap dropped, TestUsageHeatmapRoute fails. - i18n-keys, click-scroll, gui-de, gui-ja, gui-zh-tw, sessions-usage-open and all usage-*.test.cjs GUI tests pass in both engines (161 each). - A sandboxed `magpie web` (temp HOME, 2605 fake calls over 400 days, ports 3671/3672): the card fills 369 days at 1280 and 420 wide, and the tip reads "2026年10月1日周四 / 2.6M token · 23 个请求 · ≈$1.05+". |
||
|
|
de3b1c646a |
usage: a subscription card's window says what the whole window holds, "Whole ≈ N tokens · ≈ $X", reckoned from what magpie routed through the account since the window began over the share used, at API list prices (Chiao on Discord)
usage.WithWindowHolds fills QuotaWindow.Holds on GET /api/usage/quotas and its refresh, from usage.jsonl: the card's provider (by its id now, so a moved plugin's card and a renamed provider count), its account (ProviderAccount, or an older record's Host), calls to the models the window counts (Claude's Opus-only or Fable week), not turned away, from the window's start up to when the share was read. Priced by catalog.Price.CostSplit at the maker's list price, else the provider's own list, never the user's own subscription price: Anthropic's 5-minute and 1-hour cache writes at 1.25x and 2x input, OpenAI's cached input and no cache write price. A call with no API price leaves the window tokens-only. The caller's cards are not written to. Not told where it wouldn't be honest: under 5% used, nothing routed in the window, magpie's log starting after the window did, no reset or no span (credits with no reset, Copilot's premium requests), Antigravity's per-model family and pool windows, Aside windows, a card with an error, a balance, or one read from another computer. The tooltip says how it was reckoned and that use of the account outside magpie makes it read low (the request said 偏高; such use raises the share without adding to what magpie saw, so the estimate is lower than the truth). en, zh, zh-TW, ja, de. Run: go test -tags nogui ./... in Docker (golang:1.26.8): all pass but internal/agent's Aside* chmod tests, which fail only as root and pass with --user 1000. The new tests fail with the log-start check removed, the model scope removed, the caller's windows not cloned, and 1-hour cache writes at the 5-minute price. Against a read-only copy of the owner's usage.jsonl, quotas.json and models.json: Claude's week (71%) ≈ 46K tokens / $14.16 from 165 calls, its Fable week and 5 hours (12%) nothing, every other card nothing (under 5%, or no reset). New quota-holds.test.cjs passes in Chromium and WebKit at 360, 440 and 1000px in en, zh (万), zh-TW (萬), ja, de, and fails with the new CSS removed; click-scroll, gui-ja, gui-de, i18n-keys, quota-* and usage-* pass (304/304). go vet -tags nogui (darwin, GOOS=linux, GOOS=windows) and gofmt -l on the touched packages pass. |
||
|
|
e95852e301 |
usage, gui: 用量页补上各 agent 会话文件里的用量,请求页按「经过 / 不经过 magpie」拆开 (#948)
* sessions: dsh、ZCode、WorkBuddy 的会话文件里有各自花掉的 token,用量台账从来不读
Sessions 页面一直都在读这些 agent 自己的会话文件,用量台账没有:用量页只显示网关本
身应答过的调用——也就是装上 magpie 之前的什么都没有,而一个直接指向厂商的 dsh 更
是什么都没有。本机上装 magpie 之前就已经在用这些 agent(用它们自带的模型),那段
用量一直对不上账。
* 新增三类"整文件读取"的调用来源,走 wholeCallReaders(它们的调用不是一行一条,
或者文件不能从中间接着读):dsh 的会话是 zstd 分帧追加的;ZCode 用的是 OpenCode
那几张表;WorkBuddy 的同一句回复会在多行里重复同一个 messageId。三者的 token
语义各自换算成 Call 的 Input/Output/CacheRead/CacheWrite,调用缓存跟着记一份(v9)。
* 每个来源都跳过经由 magpie 网关发出的调用:网关自己记过那一本账,还带着真正应答
的供应商和账号;dsh 发往网关的请求不带会话头,两边事后对不上(token 数每次不同、
又没有可配对的 id),硬读就是同一通调用记两次。dsh 认它被配置去的那个 provider
(dshGatewayProvider:magpie / dial),ZCode 和 OpenCode 认路由里写的 provider
(ocGatewayProvider)。WorkBuddy 那部分见下一个提交。
* WorkBuddy 的调用里,同一句回复的多行只记最后一次(它带这个回复的总量);而它从
旧历史搬过来的回复一条 messageId 都没有,每一条都是独立的一通调用——会话汇总的
读法(workbuddyLine)就是这么数的,这里照它来,否则台账会比 Sessions 页面少算,
正是本次要消灭的那类"两页对不上",只是方向相反。
* dsh 的一通调用保留它文件里记的两样东西:被配置去的供应商(Upstream,作为历史,
从来不当成路由的证据),以及厂商真正应答的模型——回复的 replayState 里那个和
请求模型不一致时,Model 记应答的、Requested 记被请求的,和 Claude Code 的文件
一样的读法,好让请求表的若干列有东西可填。
* 会话的 fork:dsh 的会话从另一个会话续起来时会带上对方已写入的事件(isSeeded /
seedLength,session/end-seed 标记之后的不算),parser 跳过的这里同样跳过,否则
同一通调用会在每个 fork 上再花一次。
* WorkBuddy 的 subagents/ 子目录是父会话自己的调用来源(它带自己的消息 id,会话
归到父会话名下);调用这条路不读 file.main,那个标记是 Sessions 页面给"会话自己的
文件、不是子代理的"用的。
夹具:dsh 的三个会话(普通、带供应商与应答模型、以及一通经网关的),ZCode 的两条
(其中 ses_zcA 那条的 providerID 是 magpie,应被跳过),WorkBuddy 的既有会话(m1 的
usage 同时落在 assistant message 和它最后一个 function_call 上,只能记一次;旧历史
三条无 messageId 的回复各记一次)和一通经网关、一通走用户自建端点的会话。
调用缓存升到 v9:v8 里既没有 dsh 的供应商和应答模型,也没有"跳过网关调用"这件事,
旧缓存会继续把旧账 Serve 出来。
TestDshCalls、TestZCodeCalls、TestWorkBuddyCalls 是新的;把跳过网关调用那几行、以及
WorkBuddy 旧历史那条判据去掉,它们必挂、加上必过(都实际跑过反向验证)。
验证:go vet;go test ./internal/sessions(只余 TestCursor,Windows 路径前缀问题,
改动前同样失败);go build(windows)。
* usage: 请求页把"magpie 转的"和"它只读到的"分成两个数,GUI 跟着拆成两栏
用量页一直只显示网关自己应答过的调用,而现在它还要读 agent 自己会话文件里的调用:
两本账混在一行里,读者分不清哪一段是 magpie 转的、哪一段只是它从文件里读到的,
而总数事实上几乎全部来自后者(本机 30 天 847M token 里,网关只转了 2.4%)。Summary
里的两个来源卡片也加不出这个数来:它们只算 input 和 output,上面的 KPI 把缓存的
token 也算在内,于是"全部请求"读作 13.6M,而"Tokens"是 847M。
* usage.RequestPage 和 usage.Filter 各多一样东西:前者在 Sum 之外带上 Through 和
Direct(网关应答的,和从会话文件读到的),后者多一个 Through 维度。两种建页路径
(流式的 queryPage 和治疗桌用的 pageFromLedger)都做同一个拆分,两边一致——
TestCompactPageMatchesLedger 现在也覆盖两个来源筛选。
* 每一行本来就是按 Source 区分这两类的("log" 是会话文件里的调用,其余走的网关),
拆分就落在它上面;网关自己拒掉的调用两边都不算(页面在总数下面也这么说),所以
SourceOf 对它返回 "",点哪一栏都同样把它排除,两栏自己的计数本来也不含它。
* 两栏自己的数字是在"来源"这个挑选被清空的情况下数的,和各维度分组一样:三栏是读者
来回切换的地方,各自得一直报着自己的数,否则点了其中一栏另一栏读作 0,且没有回
到全部的路。
* /api/usage/requests 支持 via=through|direct;GUI 那一侧的三个格子、计数单位、
方块样式在下一个提交里。
* Filter.Via 这个名字和 Record.Via(转发调用的那台电脑,#542)重了,改叫 Filter.Through。
Sessions 页列表长度那件事(sessionListLimit)拆到单独的 PR 里,不在这里。
验证:go vet;go test ./internal/usage(只余 TestOTelRetryAfterBound,计时的 ±30ms,
origin/main 同样失败);go build(windows)。
* gui: 请求页把来源拆成三栏,汇总那一排也改成方块
用途页的请求栏一直只有一本账(Sum),而现在它既显示网关应答的调用,也显示从各 agent
自己会话文件里读到的调用。三个格子画在上方汇总那一排方块里,样式一致:三张各自带
边框、彼此留缝的卡片,窄屏(≤620px)下竖排。
* 每栏是一个 button:点一下就只列这一来源的请求,再点一下、或点"全部请求"回到
全部;被选中的那一栏底下有一道本主题色的线。aria-pressed 标出当前选中的是哪一栏。
* 计数后面跟单位("147 请求"),免得一个光秃秃的数字被读成下面的 token;token 是
四项合计,和上面 KPI 的算法一致。
* 三个格子在重绘之间是同一批元素、原地改(class / aria / 文本 / onclick),不是每次
replaceChildren 重建——同一份 app.js 里 5810 行的规定就是这么写的("The switch is
the same element across redraws, changed in place, so one being pressed or focused is
never swapped out"),正在点的那个不该被换掉。
* 汇总那一排本身(五张 KPI 卡)改成同样的方块:各自一张卡、有缝,边框写成
var(--line) 而不是 --card-edge(那是面板用的变量,这些卡在独立窗口里也有)。
≤860px 两列排布时卡片之间的那几条线照旧:奇数位去掉左边框、第三张起加上边框,
是 e0eaf5b4 带 #799 的老规则,这里只是跟着搬了位置,没有删。三张来源格是 button,
不参与这套分隔线。
* 供应商·账号 一栏:来自会话文件的行显示它文件里记的那个供应商 id(Codex 一向
如此),有账号时仍是账号优先,什么都没有才说"本地会话"。"本地会话"角标的条件
跟着放宽到账号或供应商任一存在,提示分两种说法:文件记了供应商的,说明这是它
被配置去调用的那个记录、不是 magpie 看到的路由(不等于官方供应商);只认得出
账号的,沿用原来那句"仅当本地元数据能明确识别时显示账号"。
* 窗口参数支持 via,用后从地址栏清掉,和 tab/provider/agent 等一致。
* 新增的串子在 en/zh/ja/de 四种语言里都有("{n} tokens" 上游已有,不重复加,
i18n-keys 绿)。
验证:node --check(app.js、i18n.js);go vet;go build(windows)。
界面效果在本机用改动后的源码构建的二进制上过目:三栏的切换与计数、方块样式、
窄屏竖排、请求表新增的会话文件行(含供应商 id)。
浏览器套件(chromium 与 webkit、en/zh):session-identity、usage-ledger、
ledger-protocol、number-units、usage-ledger-chart、usage-ttft-rounding、
usage-chart-axis、usage-fold、web-page、usage-accounts、i18n-keys 全绿;
ledger-hscroll、usage-speed、click-scroll 全绿;gui-ja、gui-de 各一条失败、
usage-ledger-detail 六条失败,均在本机 origin/main 上同样失败,与本次改动无关。
usage-ledger-chart 新钉了 ≤620px 下 KPI 卡与来源格的分隔线(把 app.css 换回上游版本
它必挂,实测过)。
---------
Co-authored-by: wizzy-yang <wizzy-yang@users.noreply.github.com>
|
||
|
|
e961836fb0 |
usage, gateway, gui, provider, cli: the tests pass when a run crosses midnight, and a usage answer reads the clock once (#1046)
* usage: the usage tests pass at any time of day, midnight included The usage tests stamped their calls with the machine's time and then asked for today, 7 or 30 days, or a cached answer, which the code worked out from its own time.Now a moment later. A minute after midnight a call made "a minute ago" was yesterday's, and when midnight fell between the test's read and the code's, the call and the period were of two days. magpie usage, the TUI's Usage page, the two Codex cache-write tests and the computers' shared days failed in the first minutes after midnight (the TUI's after midnight UTC, the zone its package's tests run in since |
||
|
|
87487c5ef0 | plugin, provider: a plugin can press its vendor's daily check-in itself (auth.checkin), and magpie runs it as its own check-ins (Lemon on Discord #feedback: provider 每日签到的方法能放到插件里面去做吗; ARNO earlier asked for Qoder's) — the check-ins magpie had (WorkBuddy, Trae CN, MiniMax Code, Qoder) are each written in magpie against the vendor's endpoint, even for a subscription that moved to its plugin, so a plugin author had no way to give their provider one. A plugin's auth hook may now have checkin(getAuth, provider) beside usage: the host lists the provider with checkin: true (plugin.Provider.Checkin) and answers checkin({provider, account}) (plugin.AccountCheckin), refreshing the account as usage does, with {outcome, credit, streak, message}; outcome is claimed, done, ineligible, inactive, captcha or failed, and a throw or an outcome outside these is failed with the reason. internal/provider/plugin_checkin.go runs these through checkin.go's checkiner, as the built-ins are: each signed-in account in use once a Beijing day (first look 2 minutes after start, then every 30), a failure asked again after wbCheckinRetry, every other outcome settled for the day, results kept in plugin-checkin.json by provider|account; a failure is recorded as failed and resets nothing. captcha is new (CheckinCaptcha): the vendor wants a captcha, which magpie never solves, so it is said as "check in in its own app", not as a failure, and not asked again that day. The results mark the account's Usage card (checkinBy "plugin:<provider>", WithCheckins), so the card's check-in row, its Auto check-in and Check in now work for it (POST /api/settings/plugin-checkin {provider, on}, POST /api/usage/plugin-checkin {provider}); Settings → Usage gains a Plugins tab, shown while such a plugin is signed in, a Daily check-in row per provider with Off/On and how each account went; magpie accounts checkin and c on the TUI's Usage page include them (the TUI's "no account" line names check-in plugins). The switch (settings.PluginCheckins, by provider) is off by default; for WorkBuddy, Trae CN, MiniMax Code and Qoder it follows that vendor's existing switch until set on its own, and magpie's own check-in through the plugin's fetch leaves a provider whose plugin checks in to it (pluginChecksIn), so no account is checked in twice. The Settings page's save carries PluginCheckins over (TestSettingsSaveKeepsWhatItDoesNotSend's fixture names it). No plugin declares the hook yet; Qoder's check-in stays magpie's own here. TestPluginCheckinRunsAsTheBuiltinsDo (the fake plugin with FAKE_CHECKIN, five accounts answering claimed, done, captcha, a throw and an unknown outcome: off presses nothing; on, each outcome kept with its vendor; a minute on nothing pressed again; past the retry only the two failures; the next day all five; PluginCheckins and the cards marked; another provider's press asks none) and TestPluginCheckinTakesOverTheVendors (a qoder plugin without the hook leaves magpie's Qoder check-in its account, with it none; PluginCheckinOn's fallbacks) pass -race -count=10, and the latter fails with pluginChecksIn stubbed false; TestTUIChecksPluginsIn passes -race -count=20. plugin-checkin.test.cjs (the card's row with the captcha said, Auto check-in posting {provider, on}, no page move; the Settings Plugins tab at 440px with the row fitting, no sideways scroll, On posting) passes on Chromium and WebKit in en, zh, ja and de; usage-checkin, i18n-keys, gui-ja, gui-de and settings-* pass. go test -tags nogui ./internal/..., go vet, gofmt -l, linux (nogui) and windows builds pass. Not tried with a real plugin or account: no published plugin has the hook yet. docs/subsystems/provider-plugins.md (the hook's contract) and docs/reference.md say it. | ||
|
|
8c71cd27f9 |
quotas: a computer using another's magpie (remote-magpie) shows that magpie's quota cards (莫 on Discord: the second computer had the models and groups but /v1/magpie/quotas was empty, so Usage, the menu bar and magpie quota showed nothing) — each named with the remote ("Codex · Office", id office/codex, from: Office) and kept in its kind (subscription, plan, balance), on the Usage page, the tray, the TUI and magpie quota (which matches by the remote's id or name); their history comes with the local one. Only the computer holding the sign-ins asks vendors: it answers the new GET /v1/magpie/quotas/cards from what it has kept (CachedCards, never a read, whatever the age), asked here at most once in 30s; a card's refresh here POSTs /v1/magpie/quotas/refresh (that card, or every card from the remote's own card), which the remote does at most once in 30s per card. A remote keeps showing its last cards when it can't be reached; with none its one card says why (nothing read there yet, or a magpie too old to share — "update magpie there", zh/ja/de added). Cards from a third magpie aren't passed on, and the refresh path refuses them (400); a Codex reset or check-in isn't offered on a remote card. Same auth as /v1/magpie/quotas (loopback, or LAN with the key).
Verified: provider tests (fake remote: names/kinds, buttons stripped, third-magpie cards dropped, one ask per 30s, refresh paths, unreachable keeps last cards, 404 → update card, cache-only CachedCards, histories) and the gateway test (an in-process gateway with a fake balance vendor counting hits, asked through a remote-magpie provider: nothing read until a refresh, 5 card asks read nothing, two refreshes of a card read once, a remote card's refresh 400, another machine without the key refused) pass with -race -count=20; go test provider/gateway/gui/tui/root, vet, linux and windows builds pass. Two sandbox gateways (3481 with a fake balance vendor, 3482 with it as remote-magpie): magpie quota on the second showed the "nothing read" card with 0 vendor hits, then office/bal "Bal · Office" $12.00 after one refresh (1 hit), 10 more asks 0 hits, two card refreshes 1 hit. usage-remote-cards (names, translated remote errors, refresh ids) passes in Chromium and WebKit, en/zh/ja/de and fails without the app.js change; i18n-keys, gui-ja, gui-de, usage-card-refresh, usage-refresh, quota-reading-again pass. Not tried with a real second computer. |
||
|
|
8b52c521fa | qoder: daily check-in for Qoder and Qoder CN (ARNO on Discord) — while Settings › Daily check-in › Qoder (or the card's Auto check-in) is on, the gateway claims each plugin account's claimable daily credits (campaigns with actionType CLAIM_BENEFIT on openapi.qoder.sh / openapi.qoder.com.cn, as wallechfox/qoder-checkin claims them) once a Beijing day, through the plugin's fetch on its device token (@magpie-community/opencode-qoder-auth 0.2.7, now the mover's min). One claimed already is done, none listed is no event, an expired sign-in or an old plugin says so. Kept in qoder-checkin.json by site and uid; shown on the usage card, in the TUI's and CLI's check-in. Built-in (unmoved) accounts aren't checked in. Not tried with a real Qoder account. qoder_checkin_test (fake campaigns, both sites; -race -count=3) and usage-checkin (Chromium and WebKit, en and zh, fails without the GUI change) pass; go test provider/gui/tui/settings/gateway, vet, linux/windows/nogui builds pass. | ||
|
|
0c2dd5915e | gui: an answer read while the accounts are read again is followed by the new one (#959) — usage/quotas answers at once with the kept copy and reads the accounts again behind it, so the tray panel, opened, showed the old usage (40%) while the window's next timed read had the new (used up), until refreshed by hand (Magixyne). Such an answer now says so (X-Magpie-Reading: 1, provider.SubscriptionUsageReading), and loadQuotas asks again every 1.5s, twenty times at most, until it has landed; an answer the same as the last isn't drawn again. quota-reading-again (panel and window, en and zh, Chromium and WebKit; a read that never lands stops after twenty) passes and fails without the fix; TestSubscriptionUsageReadingWhileStale passes with -race -count=5. claude-usage-asked, panel-usage, tray-usages, usage-card-refresh, usage-stale-answer, quota-curve and usage-fold pass; go test ./internal/provider/ ./internal/gui/ and vet pass. | ||
|
|
f506d08d28 | usage, gui: the Requests tab ranks one model at each provider it went to (inaction on Discord) — the trend's ranking already gave each model its speed, first token and requests, but "Model" put a model's requests at every provider together, so glm-5.3 at Zhipu and at ZCode couldn't be told apart. The split has "Model · provider" now: a "modelAt" dimension (provider/model) whose rows are named by both with the provider's icon, each with its own tokens/s, first token and requests, ranked by any metric (Speed: the fastest first). A click lists that provider's requests of that model, again all of them; the others stay ranked. The trend's bar wraps at the narrowest window, "Split by" with its choices. The key of each provider and model is built once per page (TestRequestPageAppendDoesNotRepriceHistory's allocations). TestRequestPageRanksModelAtEachProvider, TestLedgerNamesModelAtProvider and usage-model-at-provider (WebKit, en and zh) fail without the change. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass (TestProvidersAnswerWhileListsComeIn and TestUserPath failed under load and pass alone). | ||
|
|
37f2a2851f | gui: a Usage card has a refresh of its own, left of its "Updated" time, that reads that card alone (Hu9956, #840: 在更新时间左侧加一个刷新按钮,鼠标悬停在套餐卡片上时显示,可以单独刷新某个套餐的用量,不用刷新全部) — only the page's Refresh read the allowances again, every card at once. Each card now has a ↻ that opens left of "Updated 3 min ago" (or of a failed reading's reason, or under a balance) as the card is hovered; at rest the line starts where the card's others do. A click POSTs /api/usage/quotas/refresh?provider=&user=: provider.RefreshUsage reads that subscription account, plan key or balance key again (a Claude account by running Claude Code's own /usage, as the page's Refresh does) and puts it in place in the caches, the other cards not asked and kept as they were read; the button turns while it reads. zh, ja, de strings. TestRefreshOneCard (two keys of one relay and another provider: a refresh asks that key alone, the others keep their figures) and the plugin case in TestPluginUsage (one account of three read) fail on the old code; usage-card-refresh.test.cjs (WebKit, en and zh: aligned at rest, left of the time when hovered, a click reads that card alone, turns meanwhile, doesn't scroll; a failed card's own button) fails on the old code. usage-quota-head, usage-checkin, click-scroll, quota-read-at, balance-parts, claude-usage-asked, gui-ja and gui-de pass on WebKit. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. | ||
|
|
c377754c8f | provider, gui: MiniMax Code's daily check-in (Hu9956, #811) — magpie claims each MiniMax Code (China) account's daily check-in credits once a Beijing day, as MiniMax Code's page does, the same way it does WorkBuddy's and Trae CN's. It asks GET agent.minimax.cn/minimax-cloud/api/v1/signin/status?timezone_id=Asia/Shanghai and, only while today's day is claimable (status 2), POST /claim with {}. Both go through the minimax-code plugin's fetch, which signs them in as the account. The page's x-timestamp and x-signature (md5 of ts + salt + body) go with them, though MiniMax doesn't check these now. Day status 3 (claimed) and claim_result 2 count as done; status 4 is not eligible; base_resp's code and message are the failure's reason, and an expired sign-in says sign in again. The streak is the week's day_no. Results are kept in minimax-checkin.json. The international site's check-in isn't known, so minimax-code-global accounts are left alone. The switch is in Settings › Usage › warm-up and check-in › MiniMax Code (minimaxCheckin, off by default) and on the usage card (Auto check-in, Check in now: POST /api/settings/minimax-checkin, /api/usage/minimax-checkin); the card row's vendor strings are now a table (CHECKINS). magpie checkin and the TUI also check it in. zh, ja and de strings. No real MiniMax account was at hand: TestMiniMaxCheckin and TestMiniMaxClaimAlready run against an httptest fake built from Hu9956's captured answers. The fake checks timezone_id, the signature, the GET without a body and {} on the claim. It covers claim, no second ask the same day, in already, disabled, a refusal with its reason, and expiry. They pass with -race. usage-checkin.test.cjs adds the MiniMax card (its own switch and press, Trae's untouched) and the Settings tab (WebKit, en and zh, 8/8). settings-sections, gui-ja, gui-de, click-scroll and usage-quota-head pass on WebKit. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. | ||
|
|
57e80efbf4 | feat: filter usage and routing requests by purpose (#771) | ||
|
|
0c7e6d834d | provider: Trae CN's daily check-in (每日签到) is pressed once a Beijing day for each Trae CN account, as WorkBuddy's is (#694, Hu9956: TRAE cn也有每天签到送100积分活动,这个会考虑支持吗) — Trae CN is served only by its community plugin (trae-cn, no built-in, no mover), so magpie asks Trae through the plugin's fetch, which from trae 0.1.4 (magpie-community/plugins, branch trae-checkin) sends api.trae.cn's /trae/api/ pages as the account (Cloud-IDE-JWT renewed when near its end, its device id): POST /trae/api/v2/ug/checkin_credits/status with {}, and /claim with {} only while enable is set and checked_in isn't. These are the endpoints autumnsentiment/Trae2api-cn (the relay the plugin's protocol came from) and qilimixingkong/trae-checkin both call; an unauthenticated POST to /status answers 200 {code:1001, enable:false, checked_in:false} and a made-up sibling path 404s. Answers: not enabled → inactive, checked_in → done with its credits, a claim → claimed +credits(+extra_credits), 9095 (this device is in today) → not eligible for the day (no other device id is sent to get round it, as qilimixingkong's does), 1001 or the plugin's X-Magpie-Sign-In: expired → failed, sign in again; 9074 and anything else → failed and tried again; a plugin before 0.1.4 (400, not JSON) → failed, update it. The day loop and its file are WorkBuddy's, made generic: checkin.go's checkiner (accounts as checkinAcct{key, do}) holds checkinNow, which wbCheckiner now wraps; keepCheckedIn and wbCheckinLoop.tick take a checkinRunner and a log label; withCheckins goes through markCheckins over checkinCards. Trae's is kept in trae-checkin.json by trae-cn|uid; settings.TraeCheckin (traeCheckin) is its own switch; the gateway runs KeepTraeCheckedIn beside KeepWorkBuddyCheckedIn; WithCheckins marks Trae CN cards too, with SubscriptionQuota.CheckinBy and WorkBuddyCheckin.By "trae" (never kept), so the Usage card's row uses POST /api/settings/trae-checkin and /api/usage/trae-checkin and its first Trae card holds Trae's own Auto check-in and Check in now; Settings' Usage part gains a Trae CN tab (traeList) shown while an account is signed in or the switch is on; magpie accounts checkin and the TUI's c check Trae CN accounts in too (the footer says daily check-in). Tests: trae_checkin_test.go (once a day: status then claim, nothing sent again that day, done the next; inactive, 9095 held for the day, 9074 retried, expired, an old plugin; Trae cards marked, another plugin's not), TestTUIChecksTraeIn, usage-checkin.test.cjs's Trae CN card (its own switch and press, WorkBuddy's untouched) and settings-groups.test.cjs's Trae CN tab; the WorkBuddy check-in tests pass unchanged. go vet ./internal/..., builds (darwin, GOOS=linux -tags nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass; the GUI tests pass on WebKit (Playwright's Chromium here fails to start, icudtl.dat missing, for the old tests too). Not tried with a real Trae CN account: none is signed in to the owner's magpie (no trae-cn in plugin-auth.json), so the authenticated status and claim answers' fields are as both open-source clients read them, not seen here. | ||
|
|
8b8f91ba8f | usage: a WorkBuddy account's card says how its daily check-in went, and turns it on (#694, Dazzle-sys: 签到设置放到用量卡片上,卡片显示今日是否已经签到;要去设置里看才知道签没签是不对的) — the check-in ran and was kept (workbuddy-checkin.json) but only Settings' Daily check-in said anything of it. It runs in magpie for a moved account too (through the plugin's fetch, wbCheckinAccounts), so the card can say it for both. GET /api/usage/quotas now adds, uncached, to each WorkBuddy (China) account checked in each day (provider.WithCheckins, matched by user name, an unnamed card only when there is one account) checkins and its last record; each such account's meters end in a line with a dot: Checked in today +credit · N-day streak (green), Not eligible for the daily check-in, No check-in event now, Check-in failed; magpie tries again later (red, the vendor's message in its tooltip), or Not checked in yet today (amber) / Auto check-in is off, with · last checked in {day}. The card's first such line has Auto check-in, the same setting as Settings' Daily check-in, which stays (POST /api/settings/workbuddy-checkin, written as Codex's auto reset is), and Check in now while an account isn't in today (POST /api/usage/workbuddy-checkin, CheckInWorkBuddy, then the cards are read again). Another vendor's card has none of it; no native select, no left stripe, the page doesn't move. zh strings added. usage-checkin.test.cjs (webkit, en/zh: three accounts' lines and states, none on Codex, the switch once and off, turned on with no scroll and the line turning amber, Check in now posted and the cards re-read) fails on the old code and passes; TestWorkBuddyCheckinOnTheCard covers the matching and that the cache isn't changed. credit-days, codex-auto-reset, quota-*, usage-arrange/fold/alert, settings-sections, tray-usages, balance-parts, click-scroll, add-sheet, removed-forget/hide and plugin-two-subs still pass. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. Not tried with a real WorkBuddy account. | ||
|
|
39ec205faa |
fix: refine usage day selection and CSV filenames (#689)
* fix: refine usage day selection and CSV export * fix: suppress default outline on usage day bars |
||
|
|
48d524d65a | feat: select a day in usage charts (#683) | ||
|
|
9ccabdfbd8 |
usage: quota cards draw what was left over time, against an even burn, and the tray card its cycle's line (#651, songlairui) — each reading magpie makes anyway of a subscription's windows (and of a plan bought with a key) is kept as a point in quota-history.json beside the config: provider, account, window, when read, percent left, the window's start and reset — no token, no prompt. A failed reading, one kept from before (As of), an unlimited window and a model family's aren't kept; Antigravity's pools are kept by pool. Within a cycle points are 5 minutes apart at least and a run of one figure is its two ends; a cycle ends where the window starts again (its reset passed, or moved further than the time between two readings, so a rolling window's isn't one). 45 days and 6000 points a window are kept. The Usage page's card has, under its meters, a line a window (several tiers of one account on one chart), broken at each reset, a dashed even burn from each window's start to its reset and an upright now line, with 2 days / Cycle (the account's longest current window, start to reset) in the app's segmented control, remembered, turning every card without moving the page. The tray's card has a thin line of its first window's current cycle. GET /v1/magpie/quotas/history (?days=, ?provider=, ?user=; local or LAN with the key, as /v1/magpie/quotas) and /api/usage/quotas/history serve it; /v1/magpie/quotas and magpie quota stay snapshots. Computers sharing usage (WebDAV/S3, Settings › Sync › usage) put their history beside their days, sealed, as <id>.magpie-quotas, and merge the others': the union by account, window and time, two points within 30 s the newer, nothing twice however often they sync; an older magpie never reads the file. TestQuotaHistoryRecords, TestQuotaHistoryCycles, TestMergeQuotaHistory, TestQuotasHistory and TestQuotaHistorySharedBetweenComputers cover recording, cycles, pruning, merge, the API and two computers on one WebDAV folder; quota-curve.test.cjs (WebKit, en/zh, light and dark) the curves, the toggle, no curve without readings, and the tray's line (Chromium doesn't start in this sandbox). go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. Not tried with real accounts; pay-as-you-go balances aren't drawn.
|
||
|
|
5332c0c638 | usage: each subscription account's tokens and cost, by the account that answered (#557: 希望用量账本能按订阅账号统计,每个 Codex / Claude 账号各用了多少 token、多少钱) — a call's record named the upstream key it went out on (ProviderKeyID/Name, #500) but never the subscription account, so with two Codex accounts signed in, or a Claude account that took over after a failover, the ledger could say what Codex cost and not what each account did. A record now carries providerAccount, the account that answered as the Routing trace names it (Account.User: its email or login, never a token), set by the gateway at the try that went out (the candidate loop's last try, so a failover's answer is the account that took over and the refused try stays the first account's; an X-Magpie-Account pin is the pinned one), and on the decide, draw and video paths too. Record.Account() gives it, or for a record written before the field the account its host named (Where() has long written "chatgpt.com as dee@example.com" for an account), and otherwise "" — shown as "account not recorded", never inferred from today's sign-in. The summary groups calls by provider and account (Summary.Accounts, the same email on Codex and on Claude being two accounts), priced as every other group; the ledger's Filter has Account, the search finds a call by its account, the CSV has a provider_account column beside provider_key_name (the provider's identity columns together, the caller's still last), and the Requests page's packed rows keep it and offer the period's accounts. magpie usage prints an accounts table after the provider keys, and magpie usage --csv --account <name> keeps one account's calls. The app's Usage page lists Accounts on the Overview (tokens and cost per account, the provider under its name, an unrecorded one in the faint colour, no stripe down a row's side) and has an Account filter on Requests, each account noting the providers it answered for, which asks for and exports that account's calls without moving the page. OTLP export is an allowlist and does not carry the account. TestUsageNamesPinnedAccount (both pinned accounts on magpie's endpoint and on Codex's own, the trace's Who and the record agreeing, no token in usage.jsonl) and TestUsageNamesAccountThatTookOver (Ordered routing, the first account refusing: the answer recorded as the spare, the refusal as the first) fail without the gateway change; TestSummaryByAccount, TestLedgerByAccount and TestRequestPageByAccount cover the grouping, the host fallback, "not recorded", keyed providers kept out, the filter, the search, the CSV column and the packed rows; TestLedger and TestLedgerWithSessionLogCalls take the new column. usage-accounts.test.cjs (WebKit and Chromium, en and zh: the Overview's accounts and costs, the Account picker's notes, its request and export, All accounts clearing it, scrollTop unchanged) fails without the asset change; api-key-usage, click-scroll, panel-usage, request-archive-usage, tray-usages, claude-usage-asked and every usage-* test pass in WebKit. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass (TestFXInState failed once on its TempDir cleanup, passes alone). | ||
|
|
da834411b5 |
usage: with WebDAV or S3 sync, each computer shares its usage and sees the others', the total and each computer's part (#542) — sync carried keys, agents and the library, and each computer's Usage page counted only the calls made on it. Sync now has a Usage tick (off unless picked, usage=yes in magpie webdav/magpie s3): a computer with it on puts its own calls up as one file a day, magpie/usage/<id>-<day>.magpie-usage beside the bundle (under the prefix's usage/ on S3), each a gzipped list of times, agents, providers, models, tokens, costs and statuses, sealed with the sync passphrase (backup.SealData, the key cached per passphrase so a sync derives it once); no request body, session, archive name or key goes, a call another computer passed on over the LAN (Via) isn't put up again, and an error is cut to 300 characters. The id is a random one kept in usage-computer.json, which no backup carries, with the host name beside it. A computer only ever writes and deletes its own names, so none overwrites another's; the files are not in the bundle and its hash, so sharing usage never makes a sync or a conflict of the bundle; the first sync puts up the last 90 days, after that only yesterday and today, at most every 15 minutes (a Save or Sync now at once), and a day past 90 is deleted by the computer it is of. The others' files, listed (PROPFIND Depth 1; ListObjectsV2) and fetched only when changed, are kept in usage-others and read with the ledger, as Record.Computer; a failure is said in the sync row ("Couldn't share usage") and never fails the sync. The Requests page and the panel's Usage tab get a Computer pick (this computer, other computers when more than one, each by name) sending computer=this|others|<id>; a row from another computer says "· on <name>" beside its agent, and its details name the computer and say what was said stays there, nothing asked of this computer's session files for it. With no other computer's usage there is no pick and nothing new on either page, and an older magpie never lists or reads usage/. TestUsageSharedBetweenComputers (computers a and b over a fake WebDAV under httptest: each sees 4 calls, the totals and its own and the other's part, nothing counted twice over repeated syncs, the bundle not put again for usage, a new call reaching the other, a day past the window deleted), TestUsageSharedThroughS3 (the same through a fake S3, signed list and delete, a prefix with a space and a plus) and TestUsageOffAsksNothing are new and don't build without the change; usage-computers.test.cjs (WebKit, en and zh: no pick without other computers, the pick and computer=this, another computer's row and details with no /content asked, the panel's pick, the sync form's tick posting usage: true, no click moving the page) fails without it on all but the no-other-computers case. s3-sync, sync-other-kind, panel-usage, request-archive-usage, click-scroll and usage-ledger-chart pass in WebKit. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass (TestFXInState failed once on its TempDir cleanup, passes alone). Turning the Usage tick off, or sync off, lets the other computers' usage kept here go (DropAllShared), so the Usage page counts this computer's alone again: TestUsageSharedBetweenComputers checks both, and fails without it.
|
||
|
|
bb1aa3acbd |
feat(gateway): named gateway keys with per-client usage (#344)
* feat(gui): show and filter usage for each API key * feat(gateway): issue per-user caller keys and attribute usage * feat(gui): manage gateway users and filter caller-key usage * test: verify caller-key failover and document user management * refactor(gateway): use named caller keys without user accounts * feat(gui): manage named caller keys with existing account styles * fix: remove user breakdown from CLI and leftover gateway styling * fix(usage): drop stale user field from request response * feat(gateway): authenticate LAN calls with named caller keys * fix(gateway): preserve LAN key rotation in the named caller store * fix(gui): retain native LAN key copy and rotation controls * fix(gui): inherit the global theme for API key inputs * fix(usage): show client API keys using the existing terminology * fix(gateway): rotate named keys without changing usage identity * fix(gui): unify gateway keys and selectable connection examples Keep sharing controls in Settings and manage credentials only in Gateway. Refresh the named-key list on navigation, ignore stale reads after key actions, and generate all API examples from the selected address and enabled key. * fix(gui): keep caller key names literal in connection menus * fix(access): use Magpie as default key and drop user migration * refactor(gui): name caller key source and tests consistently * refactor(usage): split provider-key accounting out of caller-key PR * fix(gateway): preserve LAN compatibility and add headless key management * fix(gui): clarify gateway keys and confirm destructive actions * test(gateway): guard caller attribution under 120 concurrent requests * fix(gateway): keep open access, tolerate migration errors and revoke legacy keys * fix(backup): preserve named gateway keys and honor no-keys restores * fix(gui): keep local API-key semantics and disambiguate shared credentials * docs(gateway): keep review scope focused and append browser test documentation * fix(backup): retain existing default keys when old backups lack their store * fix(gateway): attribute video creation usage to the caller key * fix(access): explain default key revocation blocked by read-only settings * test(usage): preserve provider and caller identities after rebase * test(gui): reconcile caller key fixtures with merged main * docs(usage): clarify caller coverage and independent provider accounting * fix(gui): initialize fast members for model-shortcut groups Latest main introduced fast-member arrays but omitted the model shortcut's draft. The existing unlisted-models browser regression fails unchanged on main. Initialize fast to an empty list and assert a standard-speed group is saved, without relaxing existing assertions. * fix(access): retain legacy LAN access when the key store cannot be created Allow only the configured legacy credential before either migration marker exists. Refuse revoked mirrors, disabled matches and unreadable stores; keep the fallback's caller identity stable when migration later succeeds. Cover read-only configuration directories, remote credential transports and revocation. * fix(backup): save settings before replacing gateway credentials Leave the key store untouched when settings validation or writes fail. Restore the previous settings association when the key store refuses its write, and report a rollback failure separately. Cover invalid settings and read-only settings/store failures. * fix(gui): reset missing caller filters and focus key controls without scrolling * test(provider): synchronize Zhipu quota fixture observations |
||
|
|
c0f3fa012a |
usage: combine gateway and local session requests with model charts and account labels (#239)
* usage: Requests lists the agents' own session-file calls, put to the vendor and account their files prove, charts them by provider, agent or model, shows what was said, and the tray panel gets a Usage tab The Usage page's Requests tab now covers requests an agent sends with its own sign-in (Claude Desktop's Code tab and Cowork, Claude Code, Codex), which never pass the gateway, and shows more of every request: why it failed, what was said in it, who it was of. Requests tab: a strip of four totals (tokens, requests, cost, cache hit rate); the trend of one metric — tokens, cost or requests — as columns by the hour, day or week, told apart by provider, agent or model (both remembered), beside a ranking of the same that is its legend and a way in (a click lists only that provider's or agent's requests; a provider picker sits beside the agent's). The ranking is as tall as the chart and scrolls in itself, with no scrollbar: a slim rail in the card's margin shows how much there is and where it is (its thumb dragged, the rail clicked), and the edge with more beyond it fades; under the chart (860px and narrower) it shows whole. A row opens to its details: the vendor's error type and words, request id, endpoint, and what was said in it (input and output, read from the agent's session file when opened, the call that ended nearest the request — nothing stored). A refresh period (off / 5 s / 10 s / 30 s / 1 min) and refresh-now. The Overview says it counts gateway calls only; Requests and the panel say they count both. The tray panel gets a Usage tab (today / 7 / 30 days, provider picker, four totals, a small chart, top five, "Open Usage"), and is as tall as its tallest tab (#124). Provider and account of a session-file call: never magpie's "claude" or "codex" subscription. Anthropic's when Claude Desktop's session metadata (not Claude-3p) names the account and organization, with that account's email; OpenAI's when Codex's rollout names a provider that is OpenAI's in config.toml — the built-in "openai", or a named one at OpenAI's address or signed in with the ChatGPT account and no base_url (requires_openai_auth) — with the creator account's email when the file records it. Anything else is "Local session", its recorded provider id and session account kept (CSV: session_provider, session_account). The config read is today's: a file names the provider id only. Gateway: a failed call keeps the vendor's error text and type, request id and endpoint; a Claude subscription's failure uses the status Claude Code reports (api_error_status). A request turned away before any vendor was asked is logged, marked rejected, listed in Requests and left out of every total. The client's own session header is kept as native_session beside X-Magpie-Session, and a session-file call is matched to a gateway record by request id, then by that session, equal tokens and an end within 2 s, only when unique both ways. Reading: session-file calls live in the session index main keeps on disk, parsed incrementally and outside its lock (Claude Code, Cowork in both Claude folders, Codex); the usage log is read on from where it was; a page builds the ledger once. Days are counted on calendar dates (DST). CSV gains request_id, endpoint, error_message, error_type, source, session_provider, session_account. i18n: one "Endpoint" (终结点), which a second key had turned for Azure's field. Tested: go vet ./..., go build (also GOOS=linux/windows, -tags nogui) and go test -tags nogui ./... pass. The whole GUI suite in Chromium and WebKit, en and zh (Playwright 1.62.1): all 393 tests pass. On this computer's files (7 days): 3,330 Claude Desktop calls resolve to Anthropic with the account, 1,991 Codex calls on a named ChatGPT-signed-in provider to OpenAI (620 with the account; older rollouts don't record it), 9 Claude Code CLI calls stay Local session. Co-authored-by: yetone <yetoneful@gmail.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * usage: a session-file call of one of magpie's own Codex or Claude accounts is told as that provider, beside the gateway's calls on it — "OpenAI" and "Codex" (or "Anthropic" and "Claude Code") read as two vendors when they were one subscription Codex: an official route (above) whose creator account and user are one of magpie's Codex sign-ins (the CLI's own or a saved one) is magpie's "codex", with that account's email as the gateway's rows have it. Claude Desktop (not Claude-3p): an account and organization that are one of magpie's Claude sign-ins is magpie's "claude". Only while magpie has that provider signed in; another account, a rollout with no account recorded, or an ambiguous workspace stays OpenAI or Anthropic, and a relay stays Local session. Tested: TestSessionCallsOfMagpiesAccountsAreItsProviders (the account matched, another account, none recorded, magpie's account through a relay, Desktop in magpie's and another organization, Claude-3p, magpie signed out) and TestLedgerTellsCodexSessionCallsAsMagpiesCodex (a gateway Codex call and a session call of its account one provider of two calls, another account's OpenAI). On this computer (7 days): 3,439 Claude Desktop calls are magpie's Claude, 626 Codex calls its Codex, 1,322 older Codex rollouts with no account stay OpenAI. go test -tags nogui ./... and the usage GUI tests pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: 修复请求统计缓存膨胀与会话账号误归属 #239 调用明细改为按会话文件分片保存并限制内存缓存,汇总索引仅保留统计数据;网关日志按需读取。 严格匹配订阅账号与用户 ID,排除自定义渠道、非官方端点覆盖、外部 CODEX_HOME 及关闭的供应商。补齐零 token 失败去重、Codex 原始会话 ID、拒绝标记导出和面板显示修复。 通过全量 Go 测试、静态检查、受影响模块的并发检查、52 项浏览器测试及 macOS/Linux/Windows 构建;使用 35 万条合成调用验证索引体积与内存改善。 * fix: 降低请求统计刷新与写入开销并明确本地账号展示 #239 请求分片改为追加帧和字符串去重,分页复用未变化的紧凑快照,采用 LRU 并移出全局锁内的磁盘读取。缓存 Cowork 目录,补齐同前缀改写检测及崩溃临时文件清理。 本地记录仅显示匹配账号或本地会话,明确官方登录标记与请求路由的区别。默认今日与模型维度,Auto Review 复用共享目录定价并单独标注估价参考。 完整 Go 测试、vet、相关 race 和 52 项浏览器回归通过;提供 2000 文件及四个大会话连续追加的可复现性能对照。 * fix: 优化用量徽标与耗时分级并保护分页边界 #239 官方登录、API、订阅和本地会话采用独立颜色与柔和底色,兼容明暗主题。耗时按 10 秒及 30 秒阈值着色,保留估算标识与原始毫秒提示;无有效耗时显示短横线。 限制分页选取范围,避免超大偏移整数溢出及越界空页的无效堆构造。补充阈值、徽标对比度和极端分页参数回归。 * fix: 将账号与来源徽标分为两行展示 #239 * fix: 提高用量表格模型文字对比度 #239 发送模型和已知实际模型使用主题正文次级色,表头与时间同步加深。保留缺失值弱化、转发提示和本地日志来源说明。Chromium 与 WebKit 的中英文、浅深色主题 10 项界面检查通过。 --------- Co-authored-by: yetone <yetoneful@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
02d501894b |
usage: link request accounting to routing history (#361)
Co-authored-by: raper <raper@raperdeMacBook-Air.local> |
||
|
|
41a5ad6513 | claude: an account's usage keeps itself up to date again, every ten minutes, through Claude Code (the user: 既然 Magpie 不再发任何的 Claude 请求了,轮询可以再加上,只是别那么频繁) — since v0.1.558 the usage was only read when Usage was opened or Refresh pressed, so the figures left open, in the menu bar and for routing went stale. The account Claude Code is signed in to now has its /usage run again by itself once its last reading is ten minutes old (an ask still reads at once, no more than once in 30s); magpie still never asks Anthropic, and a saved account is still never read. A failed run says why until the next one rather than "not read yet". TestClaudeWindowsAsked fails without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; claude-usage-asked, tray-usages, click-scroll, old-webkit pass. | ||
|
|
9bf6d43527 |
claude: magpie no longer asks Anthropic for a Claude account's usage, and adding a Claude account warns of a ban (the user: 不要伪造任何的 Claude 请求,能否通过 claude cli 获取 / 我害怕被封; 添加账号时要像其他的 Subscription Provider 一样显示风险提示) — the usage was read by magpie itself calling Anthropic's /api/oauth/usage with the account's token, on a timer, for every saved account, and Claude's usage-limit resets (cedar_ember) were listed, spent and auto-spent the same way. Now the usage is what Claude Code's own /usage prints (claude -p /usage, a command Claude Code answers itself without asking a model), run only when Usage is opened or Refresh pressed (GUI, magpie quota, accounts, TUI), for the account Claude Code is signed in to, at most once in 30s; a saved account shows only what Claude Code reported while using it, or the last reading kept. The Claude resets, Auto-use and their settings are gone (Codex's stay). Session jsonl files hold no usage figures, so they aren't read. Starting a Claude sign-in or import (GUI and CLI) first says Anthropic may suspend or ban the account and that it is at the user's own risk. TestClaudeWindowsAsked, TestParseClaudeUsage, TestClaudeUsageRunsClaudeCode, claude-usage-asked.test.cjs and claude-risk.test.cjs fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; routing-auto-reset, codex-auto-reset, quota-families, tray-usages, click-scroll, old-webkit, plugin-signin, usage-alert, usage-ledger pass.
|
||
|
|
a9ff84fd80 | accounts: a Claude account's usage-limit resets show on its card, and can be used, by hand or by themselves (StringKe on Discord: claude-code usage 里有 reset) — magpie read Claude usage without the resets. It now asks as Claude Code does (/api/oauth/usage?cedar_ember=1&skip_spend=1) and shows ↺ N resets · until … on the card and panel. "Use a reset" spends the grant Anthropic names next through POST /api/organizations/{org}/reset_rate_limits, as Claude Code's /limit-reset does, the organization read from /api/oauth/profile; Auto-use (off by default, per account) spends one only when the account's whole week is used up, every other candidate is resting and the grant clears seven_day, at most one a week. The routing page labels an automatic one. Checked against fake servers with the user's JSON, never against Anthropic. TestClaudeGrants, TestClaudeResetsOnCard, TestUseClaudeReset, TestAutoUseClaudeReset, TestClaudeAutoReset and claude-resets.test.cjs (Chromium, WebKit, en/zh) fail without the change; codex-auto-reset, routing-auto-reset, click-scroll, old-webkit pass. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass. | ||
|
|
1e9f3a46cb | usage: a Requests tab lists every request of the period, one row each, and exports them as CSV, from the window and from magpie usage --csv (Discord 范不着: a per-request ledger as sub2api keeps, to set beside the upstream's own bill) — the Usage page summed calls by agent and model, and the log did not keep the model the agent asked for or the one the reply said answered, so a single request could not be checked against a vendor's bill. usage.Record now keeps Requested (req, the model id the client sent, a magpie alias or group as it came) and Served (served, the model the vendor's reply named, only when it named one); every usage.Append in the gateway fills them (the relayed and translated paths, Codex's backend, image draws, decide), and records written before load as they did, without them. The swap test the Routing page uses (a dated or pinned name is the same model) moved to usage.Swapped so the ledger marks the same rows. usage.Ledger gives the period's records newest first with each one's list-price cost, the agent it is counted under and whether the model was swapped, filtered by agent, failures alone and a search over the models, provider, account, session and effort; usage.WriteCSV writes them (time, agent, requested_model, provider, host, model, served_model, swapped, effort, input, output, cache write, cache read and reasoning tokens, cost_usd, duration_ms, ttft_ms, status, error, session, kind). The Usage page gets a third tab, Requests (请求), between Overview and Sessions, under the same period picker: an agent filter, All/Failed, a search field and Export CSV over a table of time, agent, requested model, provider · account, model sent, served model (amber with the Routing page's sentence when another model answered, plain on a dated name, a dash when the reply named none), effort, in, out, cache write, cache read, cost, duration and status, a failure's row marked by a red dot and bold code; the totals over it and 100 rows a page with Newer and Older. GET /api/usage/requests serves a page, POST /api/usage/requests/export saves all the filtered rows to Downloads (never over an earlier file) and opens the folder, GET /api/usage/requests.csv hands a browser the file in magpie web. The table scrolls sideways in its own box; at the window's narrowest the words after the head's cost give way so the three tabs fit without the page scrolling sideways. No border stripe; clicks move nothing (the pager held where it was). en and zh strings together. Tested with TestLedger (order, cost, swap, a dated name, an old record without the fields, each filter, the CSV exactly), TestServedModelRecorded and TestServedModelUnnamed (a request through a fake upstream answering with another model records Requested fake/sol, Model sol and the served name; one naming none leaves Served empty), TestUsageCSV (magpie usage --csv, a period, a stray argument refused), TestUsageLedgerRoutes (paging, totals, filters, export to Downloads twice) and a new internal/gui/tests/usage-ledger.test.cjs in Chromium and WebKit, en and zh, light and dark: the tabs and columns, the swap tag on the swapped row only, the 429 row, Older and Newer over 130 requests with the pager left where it was, the agent, Failed, search and period filters asking the server from the first page, Export CSV posting the filters with no page and saying where the file went, at 560 wide no tab scrolling the page sideways and the cost uncut, no left border. go build -tags nogui (and GOOS=linux, GOOS=windows), go test -tags nogui ./... and the whole GUI suite (122 tests) pass. Not tried in the real window through Wails or against a live gateway's log. | ||
|
|
502246c563 | usage: a Codex account's rate-limit resets are on its card, so they don't go unused (可能把 resets card 在里边反应出来么?免得我们忘了用) — wham/usage's rate_limit_reset_credits count, and from /wham/rate-limit-reset-credits when the first of those left runs out, show as "↺ 2 resets · until Sat 22:30" under a hairline on the tray's Usage card, under the account's windows in the window's Usage view, and in magpie quota / accounts and the TUI (nothing when there are none, no date when none expire); "Use one…" asks first — which account, that its windows start again at once, that it can't be undone, and that there is nothing to start again when no window has been used — then spends one with a fresh redeem_request_id on that account (POST /api/usage/codex-reset, or magpie quota reset [<account>] [--yes]), says what came of it in words and reads the usage again; the account signed in now is found from Codex's own auth.json, not only the list magpie keeps. panel: a section's account count is a quiet rounded pill by its name, not a bare 2 at the far end (那个 2 是没有仔细打磨), the "N accounts" kept as its tooltip | ||
|
|
4790c06b02 | usage: each call keeps where it went — the provider's host, or the account it was — so a provider id later pointed somewhere else no longer puts the earlier place's tokens and cost under the new one: a model's usage is told apart by host (provider/model @ host) when its provider went to more than one place in the period, or to somewhere other than where it goes now. Asked on Discord | ||
|
|
7b69b22a76 | quota: what is left of every subscription, plan and key balance, for scripts and agents — magpie quota [<provider>] [--json] prints each window's use and remaining percent and when it starts again, and each key's balance; the gateway answers the same at GET /v1/magpie/quotas (only to this machine, as it names the accounts), so an agent can pick where to send its work (#85) | ||
|
|
f1fba8d7eb | usage: a GLM Coding Plan's allowance and OpenCode Go's show on the Usage page — Zhipu's (open.bigmodel.cn) and Z.ai's 5-hour and weekly windows and the month's MCP calls, with the plan's level, and OpenCode Go's 5-hour, weekly and monthly ones, each asked of the vendor with the provider's key, a card for each key when it has several; a pay-as-you-go GLM key, which has no windows, shows none (#68) | ||
|
|
293c45677c | agent + gui: magpie and curl are clients the gateway knows by name, with their logos, beside the agents — the Usage and Routing views both draw a request's client from the one list, every agent in it whether it is set up here or not, where Routing only knew those found on this machine | ||
|
|
2b1e9e8619 |
usage: the Usage page shows what is left on an API key beside the subscriptions' allowances — DeepSeek, Kimi, OpenRouter and SiliconFlow are asked by their hosts, and any custom provider can name its balance endpoint and where the amount sits in the reply (Balance URL / field in the editor, balance= / balance.path= in the CLI), each key it has on asked with itself; magpie provider <id> prints it too (#40)
|
||
|
|
2a90ed1030 | usage: the page no longer waits on subscription quotas — they load on their own, in parallel, stale-while-revalidate (#6) | ||
|
|
702477525a |
Claude subscription as a provider; model lists fetched, never compiled in
A signed-in Claude Code is now offered as a provider (claude/…) like Codex and Copilot. Anthropic classifies another agent's system prompt as third-party traffic even over Claude Code's OAuth, so magpie drives the real local claude binary for every generation: the caller's tools are bridged in over MCP (magpie claude-mcp-helper), and tool results resume the same Claude Code turn. Token counting is estimated locally so the OAuth token takes no side path. No model list is compiled in any more. The built-in catalog, preset defaults and Claude Code's alias list are gone; the picker shows the models.dev catalog (refreshed in the background when stale) layered with each vendor's own /models answer, and signed-in accounts fetch theirs at start-up. Whether a model rejects temperature/top_p now comes from models.dev rather than a name prefix. The gateway retries a Chat request on the Responses endpoint when the model is Responses-only, and remembers that. Recent calls keep the first 256 KB of request and response bodies, viewable in the call list. The Usage tab shows subscription allowances (Claude, Codex, Copilot) as the vendors report them. |
||
|
|
402a96c39d |
Rename dial to magpie, with a magpie for a logo
The product, module path (github.com/yetone/magpie), binaries, env vars (MAGPIE_ADDR, MAGPIE_DEV_UI, MAGPIE_THEME, MAGPIE_DEBUG), config and cache folders (~/.config/magpie, ~/.cache/magpie), bundle id (com.yetone.magpie), gateway provider id and token, and every UI string now say magpie. On first run magpie copies ~/.config/dial and ~/.cache/dial to the new folders when they don't exist yet (copy, not move, so a still-running dial keeps working; the old folders can be deleted by hand later). The logo is a small round magpie in profile: one path for the header and the tray, and the app tile adds the white belly and the blue-green tail. The header mark is drawn in ink rather than the accent colour, which fought the text in light mode. |
||
|
|
30c489a000 |
usage: a token statistics page
The gateway now records every call's token counts (read from the provider's own usage block, in both the translated and the pass-through paths) with the calling agent taken from the client's User-Agent, into ~/.config/dial/usage.jsonl. A Usage tab sums them by period, agent and model, with a per-hour/day/week timeline and cost at models.dev list prices; dial usage does the same in the terminal. Also nudges the window header 1pt up so the brand sits level with the traffic lights, and lets ?view= open the window on a tab. |