73ecef0b36cd8a3467eb70fbdd9799ea98db9b7d
19
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
27c998aba0 |
usage: the tray panel's and Requests' costs follow each provider's currency
onkashiko on X: with Currency set to By provider, the menu bar panel still showed every cost in one currency; providers and models were not each in their own. drawLedColumns and drawLedRank (shared by the tray panel and the window's Requests tab) formatted every value with no provider, so fmtCost fell back to the Totals in currency. - usageapi.Ledger echoes the provider a page is filtered to (`provider`, omitempty). - app.js: ledProv(l, split, id) names the provider of a value: the ledger's filter, the row's provider (provider split), the provider part of a modelAt id, or for a model split the provider(s) that served it when they all share a currency. ledFormat/ledFormatLong take it, so the rank's values and sub-lines, the tooltip's rows and the axis (when one provider is picked) are in that provider's currency. Sums (the panel total, the tooltip total, a model served in two currencies) stay in the Totals in currency. - page.js: the Requests head and the cost head use the filter's provider; the heatmap tip too. Other fmtCost calls are sums or sessions with no provider and are unchanged. - core script budget +491 (1,269,040 -> 1,269,531): drawLedColumns and drawLedRank are drawn by the panel, so there is no lazy page to move this to; packed to the shortest form. - docs/subsystems/gui-shell.md says how By provider reaches the panel. Run: - At 065fb6a8b (rebased on |
||
|
|
477bbb7a15 |
usage: GET /v1/magpie/usage/requests?cursor= reads requests as changes, with stable ids (rdsaltbo on X, #6060)
A program keeping a ledger of its own (a WakaToken plugin) can now read the requests incrementally: cursor=start or cursor=now, then each next_cursor. Rows carry a stable content-derived id (same after a restart), origin, and original_ids (request_id, response_id, client_response_id, message_id, session_id, native_session_id), each only when the source gave it. A call read late, a corrected row (same id, higher seq) and a native row replaced by the gateway's (deleted, with seq) all come through a persisted journal (usage-feed.jsonl, appended and synced before answering). Cursors magpie cannot resume from are refused: 400 cursor_invalid / cursor_filter_changed, 410 cursor_expired / cursor_reset. A held key sees only its own rows and tombstones. Without cursor, offset/limit mode is unchanged. Also: Record.MessageID (not persisted) from the agent file's message id, and usageapi's row decoration moved into a namer shared by both modes. Docs: reference.md, integrating.md, gateway-routing.md, gateway-sessions.md, site remote.html (en/zh/ja), llms-full.txt. Run (mote, this tree): go vet darwin, GOOS=windows, GOOS=linux -tags nogui on usage, usageapi, gateway (gui on darwin); go test -count=1 for internal/usage, usageapi, gui, gateway: all ok. New tests: resume gets exactly the new rows, ids and cursors survive a restart, correction keeps the id, gateway takeover retires the native row, refused cursors, expiry, now cursor, identical records, and the feed over the gateway (held key, 401 without key, offset mode). Broken by hand: an unconditional memo made the new-rows test red (fixed to memo only the next page). Not tried: real Claude Code/Codex session files, a huge (700k+) history, Windows run of the tests, GUI browser suites (no GUI file touched). |
||
|
|
e6bf4adf1f |
usage: Claude Code's helper requests are labelled, the largest cache write is one click away (recih on X, #6199)
Claude Code's AgentSummary and its auto mode classifier name themselves nowhere in the request, so there is no client marker to read. The gateway tells them by their content (inferredKind: a claude-cli/ request on the Messages API; the classifier by autoModeClassifierAsk, the summary by its last user text "Describe your ... in 3-5 words") and records them as agent_summary_inferred and auto_mode_check_inferred. The purpose catalog names them "Progress summary (inferred)" and "Auto mode check (inferred)" and puts each with its plain kind's purpose, so the existing Purpose filter lists both; nothing known and nothing inferred share a name. A tool that printed the same words, a chat, and another agent's request stay unmarked. A requests page now also holds BigWrite, the gateway-served row that wrote the most to the cache (cells, page-v1.json and pageFromLedger all carry it; rows from session files have no request to open). The Requests line shows it as "109K largest write", a button that opens that request through openUsageRoute. settledCountVersion is raised to 3, which keys the cached pages. Not done: the per-request branch recovery result asked for in #6199. No structured field holds it. Run on mote (load 21-24 of 18 cores, mica was higher): go test ./internal/usage ./internal/usageapi, the gateway and gui purpose tests, go vet for darwin, linux (nogui) and windows, gofmt; the GUI files usage-big-write (new), purpose-filter, routing-kind, i18n-keys and usage-ledger in chromium and webkit. Broken by hand: inferredKind returning "" turns TestClaudeHelperRequestsAreLabelled red; the larger-than test of BigWrite.add turned round turns TestRequestPageBigWrite red on both paths; the jump off turns usage-big-write red. Not tried: a real Claude Code session against a live subscription, Linux WebKitGTK. |
||
|
|
88c417392e |
usage: a sortable model speed ranking on the Requests tab (@flying_crp on X)
Usage's Requests tab gets a "Model speed" card: per model, the median output tokens/s, the median wait for the first token and the request count, over the selected range, sortable by every column (aria-sort header buttons, quiet table, no gradients). A request counts when it was answered (not rejected, handed on, failed or canceled), its first token was timed and it wrote 100 tokens or more (usage.MinRankTokens; the tooltip says so). Computed locally: each chunk keeps a 2% log-bin histogram per model beside its cells (speed_rank.go, chunkPart.speeds), a page merges the chunks' histograms, so there is no per-request sort and medians are within ~1%. The settled chunks' histograms are in the page file; its key salt is now page-v2, so the first load after upgrade recounts settled history once. /api/ledger sends speeds and speed_min. Run (mote): gofmt clean; go vet darwin, linux nogui, windows for the touched packages and ./... earlier; go test internal/usage, internal/usageapi, internal/gui ok at this head; usage-model-speed.test.cjs 12 of 12 (chromium and webkit, en/zh/zh-TW/ja/de, 400px: order, sort by every column, aria-sort, focus kept, no horizontal overflow, ellipsis, hidden when empty); with i18n-keys and i18n-en-no-cjk 20 of 20; the whole GUI suite once on the branch before the rebase: every red is in a file unrelated to this change (account-arrange #6010, account-refresh-holds #5814, account-eye #5052, agent-switch-accounts #5925, bulk visibility and disconnect previews #5982 fixed in |
||
|
|
4921bf5a97 |
usage, sessions: one model option for a found routing group's two ids (#5892, Norethcy on X)
A found routing group is called by its public id (auto/<model>) and is kept as group/auto-<slug>; calls recorded under either were counted as two models, so Usage › Sessions' model filter listed the same group twice and the ledger, summaries and session lists split its calls. Ported from NorethSea's 30d6261cd on their fork: UsageAlias names a found group by its public id before the user's alias (both spellings, old session files too), sessions' lists, the ledger keyer, the summary cache's key and Codex's model/effort read through it, and a cache keyed on the group names (UsageNamesKey) is read again when a group is renamed. A user's own provider named "auto" keeps auto/<model> (autoRefsOn). Changed in review: the patch's ledger filter compared every record with provider.SameRef, which reads the providers (customIDs, a stat of providers.json) for each record a filter passes over. FilterOf, the one place a Filter is made from a query, now canonicalizes the model once, and keepsRecord asks the providers only for an auto/ record under a group/ filter (sameGroupModel). Run (mote's sshd reset every connection all afternoon, so on the Linux box through wsl-run; the package run at base |
||
|
|
8de63c8b5a |
gateway, usage, gui, otlp: a request its agent canceled is no failure (#2398)
An agent that cancels its request before it is answered is logged 499 "the agent canceled the request": a person stops the reply, or sends the next message while it is coming and Claude Desktop cancels it and asks again, or Codex takes a subagent's report (#2398). The gateway already says nobody failed (no rest, no reroute: TestCanceledRequestRestsNobody), but Record.Failed is a status >= 400 or an error, so every page counted it as a failure: the Requests card's "N failed" and success share, its Failed filter, the CSV's error column, the Routing page's "errors your agent saw", the Context page's error rate, the failed colour in the Requests list, Routing and Recent calls, and the OTLP export's error status. A Claude Desktop session on 2026-10-27 had four, each a message sent mid-reply; #2398 had 91 of a day's 92 failures. usage.CanceledBy tells the agent's cancel (499 with AgentCanceled) from magpie's own limit on a request it asked of itself, logged 499 too and still a failure (#2318). The cancel is logged with an error type of its own, agent_canceled (usage.CanceledErrType, set in failedWith), so the record says what it was and nothing guesses it from a 499, as #2398 asked. Record.Canceled reads the type, and a record logged before it by its status and message, so the old log reads the same with nothing migrated. A middleware's usage rows carry the type, so a module can tell the cancel from magpie's own limit, which its rows (no error text) couldn't. Record.Failed leaves the cancel out; Totals counts it apart (Canceled, in count and plus); RetriedRequest and the first-token and speed sums ask Answered, so a canceled request is timed nowhere, as before; Codex's memory of the last model still skips it. Routes and Recent calls say canceled (set as a route is done and as a day's history is read, so old days read the same); the Routing totals and the Context page's errors leave it out. Ledger rows say canceled, and the pages show it muted, in neither the failed nor the answered colour: the Requests list and its detail ("499 · canceled"), the Requests card ("N canceled", the success share of the requests not canceled), the overview tile, the Routing page (a "gone" outcome, no speed) and Recent calls (muted). New strings are in zh, zh-TW, ja and de. The OTLP export: the records the gateway gives its observers for a request and its try carry the type too (canceledAs), and a root span's error.type follows Record.Failed, so a canceled request's span and its try's go with status code 499, no error and no error.type. TestOTelWaterfallFailureAndCancellation's canceled case held two failed spans (the try the vendor refused as the agent left is recorded canceled, as the request is); it now holds neither failed, both 499 and no error.type. That change to the test is the point of this one. mdwsk88's patch (aea0027fd) ran its tests at |
||
|
|
333e7f573b |
gateway: gateway keys are dragged into the order you want, kept with the keys (alextjy on Discord)
alextjy asked on Discord whether gateway keys can be reordered. They could not: the Gateway page listed them in the order caller-keys.json held them, and nothing changed that order. - access: a "move-key" action puts one key at a place in the list, under the same file lock as every other key change. Nothing else about the key changes, and the sharing key's mirror in settings is left alone (its pointer would otherwise land on another key). - GUI: the Gateway page's key rows are dragged the way search APIs' rows are (shared dragRows, a grip shown on hover only, Alt+Up/Down, the existing "Drag to reorder" title). A refused move puts the list back from the server. New strings in zh, zh-TW, ja and de. - CLI: `magpie gateway-key move <id> <place>` (from 1); list already prints the stored order. - Usage > Requests: the key filter lists keys in the user's order, removed keys after. The Overview stays a ranking by use. Run (worktree at |
||
|
|
3b5dccd527 |
accounts: a plugin account goes by its usage's name, not its id (#4416)
A Huawei Cloud CodeArts account is kept by its accountId, an IAM id (iam::<domain>:user:<name>), and every list showed that id while its quota card showed the masked phone the plugin's usage() names it by. Display only: an account now reads as the name the user gave it, else the `user` its plugin's last usage read gave (PluginUserOf: the in-memory read, else quotas.json), else its id. The id stays the key everything is kept by; nothing stored changes or migrates. A read that fails keeps the last good name; nothing read yet is the id, never blank. One rule in provider (AccountShown, AccountShownOf, AccountLabelOf), used by every list: cards' Alias (Usage page, tray panel, /v1/magpie/quotas, magpie quota), magpie accounts, magpie providers, the TUI's Providers rows and quota titles, usageapi's Account filter, the quota alert. The GUI gets it as /api/providers' accountUsers (accountShownOf in app.js): the editor's account rows (the id in the tooltip), the per-account proxy lines, Routing's userShown, the Providers search, Hide accounts. app.js's account lookups share one helper, so the core stays in its budget (1,536,561 of 1,536,586), with no room added. Run: - go test ./... -timeout 45m on mote at |
||
|
|
396e0e4638 |
usage: a deleted provider's requests merged into another, or named, from the Requests filter
CyberCaius on Discord: a deleted provider's requests sat under its old id
("<date> 已删除"), and the only way to put them under a provider they
have was renaming that provider onto the old id. Now, with a deleted
provider picked in Usage › Requests' Provider filter, a "…" beside it
offers Merge into… (an app menu of the providers there are now) and
Rename… (the filter's button turns into a name field; Enter or leaving
it saves, Escape keeps it). With the merged-into provider picked, the
same "…" lists Separate <name> for each, the undo.
Nothing in the log is rewritten. Both live on the deletion's own record
in providers.json (Deleted.Into/MergedAt, Deleted.Label), so a provider
added later under the old id inherits neither: it is a different
provider, and its record of its own is what it has. Renaming the target
carries the merge (Rename rewrites Into); deleting the target ends it.
Renames.Both(id, time) gives the id a call is shown under and the one it
was made to (Own). Listing, filtering, the summary and vias go by the
shown id; pricing (Record.priceID, block_price's as), window holds and
the gateway's loggedAnswers go by the own one, so a merge moves no cost
or token, only whose name they sit under. The target's face lists what
was merged into it (Named.Merged). Routes: GET /api/usage/deleted/into,
POST /api/usage/deleted {id, into?, name?}; a field not sent stays.
Run (mote, at this tree on
|
||
|
|
3e22123c9c |
usage: a deleted provider's calls stay apart from a new one under its id
cybercaius (Discord): after deleting a provider and adding a new one
that took the same id, the old provider's usage showed under the new one.
Delete now records the provider in providers.json ("deleted": id, name,
icon, when, its Was and Gave). UsageRenames gives a deleted id to
<id>~<when> only once something reuses it (a live provider, a later
deleted record, or a later Was), so a deleted provider nobody replaced
keeps its raw id and the existing probe/usage tests stay as they were.
/api/usage's provider faces name a deleted id from its record and set
Named.deleted; the Usage provider picker notes "Deleted {date}" (zh, zh-TW,
ja, de translated). Old deletes, made before this, have no record and
stay merged: nothing tells their calls apart now.
Run (mote): go test -tags nogui -run 'Deleted|Rename|NotSetUp|Probe'
./internal/usage ./internal/usageapi ./internal/provider ok; gofmt -l
clean; go vet -tags nogui ok.
Broken by hand: dropping the f.Deleted append turns
TestDeletedProviderKeepsItsCallsFromOneAddedUnderItsID and
TestDeletedProviderListedApartAndMarked red; restored, green.
Not tried: a real delete-and-re-add in the GUI app.
|
||
|
|
e00fbdbbc7 |
usage: times and days follow the viewer's time zone, not the server's (Outvi V, Discord)
Outvi V reads a remote magpie through `magpie web`. The Usage page
bucketed calls by the server's days and hours, so a call at 9:00 in
UTC+8 showed under 1:00.
What changed:
- The Usage page (plugins/usage/page.js) names its browser's IANA zone
in ?tz= on /api/usage, /api/usage/requests, /api/usage/heatmap, the
CSV link and the export.
- usage.Zone turns the name into one cached *time.Location per name, so
a Filter holding it stays a comparable cache key. An empty or unknown
name, or a zone that keeps this computer's clock, is time.Local, so
the desktop page, the tray and the TUI see no change and share caches.
- Filter.Zone carries the zone. Today/7d/30d, the chart's hour and day
buckets and labels, the Day filter and the heatmap's days are all
read in it (Clock().In(zone)). The summary cache is keyed by period
and zone, and the request-page cache by the reader's date.
- Shared days from other computers are read with a 2-day margin, not
1, since two zones can be 26h apart.
- Limit and quota resets are unchanged. The gateway's
/v1/magpie/usage stays on the computer's zone.
Run at
|
||
|
|
4f6498f822 |
routing, usage: an account renamed in magpie reads by its new name (magpie-community/plugins#310, molvqingtai)
molvqingtai renamed a Kiro (plugin) account from "example@gmail.com (foo)" to "example@gmail.com (bar)", and the Routing page kept saying "(foo)" on every request made after. Cause: the Routing page never looked up the user's name at all. A trace's `who` is the vendor's account name (Weighed.Who), and plugins/routing/client.js showed it as it was. Usage records (ProviderAccount) keep the vendor's name the same way, and the Usage page's Accounts, the request log's Account filter, `magpie usage`, a gateway key's accounts (AccountNames, /api/caller-keys) and Routing's "Several accounts" pools (onOf) all showed it raw too. This affected built-in and plugin providers alike. Records still keep the vendor's name. It is the key the user's name is stored under (providers.json AccountNames, in lower case), so it stays the identity: Routing still groups and ranks by `who`. The name is looked up when it is shown: provider.AccountShown / AccountShownOf / AccountRef.Shown in Go, and userShown (accountNameOf over /api/providers' accountNames) on the Routing page. So requests from before the rename read by the current name too, and a cleared name goes back to the vendor's. A key's name and an unnamed account read as before. Already right before this change: quota cards and the menu bar (Alias), `magpie accounts`, and the editor's account row. Record for this push: 13 commits on origin/main |
||
|
|
0eb5cbe81a |
routing: the live view and Usage's Requested name a found group auto/<model>, not group/auto-<model> (未寒 on Discord)
Reported: 未寒 picked auto/claude-opus-5-5, and the Routing live view and
Usage's Requested column named it group/auto-claude-opus-5-5, an internal
id that agents never see.
Changed:
- internal/gateway/trace.go: GroupRef and SubGroup carry Ref
(Group.Ref(), the id agents pick the group by).
- internal/gui/trace.go: publicRoute rewrites a route's Model,
For.Model, Subagent.Asked/To and the group's and subs' Ref through
provider.PublicRef (memoised per answer). It copies the pointers
before writing, so the gateway's trace is left as it was.
- internal/gui/context.go: the Context page's model too.
- internal/usageapi/usageapi.go: the ledger page's Requested.
- routing/client.js: useName falls back to a sub's ref.
Test: TestRoutesNameFoundGroupsByTheirPublicID
(internal/gui/trace_publicref_test.go). Broken by hand, each one red:
- publicRoute made a no-op: red on model, group, subagent, For, Subs
and route.
- usageapi mapping removed: `the ledger's Requested:
["group/auto-claude-opus-5-5" "group/mine"]`.
- contextRoutes mapping removed: `the Context page's model:
"group/auto-claude-opus-5-5:high"`.
- Ref dropped from gateway/trace.go alone stays green, as expected:
publicRoute fills an empty Ref.
Not covered: the ledger's text search (usage.Filter.Query) still matches
the stored group/auto-… form, not the shown auto/… (package usage can't
import provider). client.js's ref fallback has no GUI test of its own.
Run, go1.26.8 darwin/arm64, sandbox HOME, private GOCACHE:
At this stack on origin/main
|
||
|
|
2c72563dd1 |
usage: Requests splits and filters by gateway key, with "No gateway key" for the calls none made (#2521)
MauriceCarlo asked for two things on Usage → Requests. 1. The gateway-key filter should show even when one key has calls. The picker hides itself under two options, and with one key it had one, so calls made with that key couldn't be told from calls made with no key. A "No gateway key" choice (callerKey=none) now sits beside the keys whenever the period has calls with no key, or it is the current pick. A single key's picker therefore shows and separates the two. The hidden condition itself is left to #2499, which another session has. 2. The trend chart and the ranking can split by gateway key. LED_SPLITS gains "Gateway key". It's offered only while the period has a key's calls, and it falls back to Model otherwise. A click on a rank row picks that key, or none, and a second click lets go, as the other splits do. Server: - usage.Dimensions gains "callerKey". A row's key is its CallerKeyID, or NoCallerKey ("none") when it has none, and the filter takes "none" as calls without a key. - Filter.Without(d) is the one place that clears a dimension's own pick, so the by-split lists every value. RequestPage's fast and slow paths both use it now; they each had their own switch. - usageapi names the split's shares from the key labels: "No gateway key" for none, the ID if a key was deleted. - OwnPage keeps a held key's view to its own share in by and in the chart's split, so one key never learns another's name or numbers. The series was already only its own rows. - docs/reference.md documents callerKey=none and by.callerKey. "No gateway key" goes into the core i18n.js. The gateway keys page says "No gateway keys yet", and i18n-keys' "a plugin's words are its own" matches on substrings. Tests: - TestCallerKeySplitAndNone runs the fast and the slow path over {}, one key, none, and none+an agent, and checks by.callerKey. Broken by hand, it goes red: once with the none clause in the filter removed, and once with Without's callerKey case removed. - TestUsageOverGateway: on loopback the split names both keys. A held key's by.callerKey is only its own. With the OwnPage scrub skipped, it goes red (another key's name leaked). - usage-ledger-key-split is new, in both engines, all five languages, and 1400 and 760 px. It checks: - the picker's options with the none choice; - filtering on none; - the split's rows, and a click picking and letting go; - no sideways scroll; - that a period with no key's calls shows neither the picker nor the pill. 32/32 pass. With the none option removed by hand, 11 go red. Run on origin/main |
||
|
|
6d19988416 |
usage: a provider the log names but that isn't set up now goes by its name, "Claude Code", not "claude" (@ByronVon1 on X)
The Requests page's Provider filter listed "claude" between named providers. The usage log keeps the id of every provider a call went to, and usageapi named those only from provider.All(). The Claude Code subscription is in that list only while its account is discovered, so after a sign-out, with account discovery off, or for a preset provider removed since, the bare id showed. This happened in the filter, each row's Provider column, the split-by-provider and model-at-provider legends, the Account filter's provider notes, and the summary's model and account subtitles (stateOf had its own copy of the same lookup). - provider.KnownFace(id): the name and icon magpie knows an id by while it isn't set up. It covers the built-in subscriptions' card faces (accountCard: Claude Code, Codex, Copilot, Gemini, Antigravity, moved ones) and then the presets. A custom provider removed since stays its id, since nothing else knows its name. - usageapi.providerFaces: one lookup for LedgerPage and stateOf, in order: the provider set up, "Local session" for session-unknown, then KnownFace, then the id. Run: - TestProvidersNotSetUpAreNamed (new, internal/usageapi). Fails on the old code with 13 errors across the filter, rows, both splits, the Account filter and the summary; passes with the fix. - gofmt -l: clean. go vet for usageapi, provider, gateway, gui on darwin, and usageapi, provider on GOOS=linux and windows: clean. - go test ./internal/usageapi ./internal/usage: ok. - go test ./internal/provider ./internal/gateway ran at load average ~300 with other sessions' suites. Three timing tests went red, and each passes 3/3 alone (-count=3 -run): TestCopilotSecretToolUsername (#1627, commented), TestOTelFastRequestTranscriptDiscovery (#1811), and TestTranslatedStreamKeepsClientAlive (filed as #2169). TestUsageOverGateway and the gateway's TestUsage* pass. - GUI: usage-ledger.test.cjs and usage-ledger-chart.test.cjs in chromium and webkit, 52/52 (playwright 1.62.0). app.js is unchanged, since the page already shows the name the API sends. Not tried: the real GUI with a signed-out Claude account. |
||
|
|
d4c2512d2d |
usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)
What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
one record or an array, in usage.jsonl's shape:
- the post may carry up to 5000 records and 32 MiB;
- t, agent, provider, model and rid are required.
Each field is checked: unknown fields, quoted numbers, negative or absurd
counts, a status outside 100-599, a cost over 10000 USD, and a t more
than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
whole post with a 400 that names error.index and error.param, and nothing
is written. A past t is otherwise taken as given, so history can be
backfilled. The reply gives accepted and skipped counts and each
record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
shared, behind the Host check). A browser page also needs a key, since
corsGuard lets localhost pages and Origin null through. A held key is
refused.
- usage.IngestReported writes under usage.mu to the same file as
usage.Append. Rows carry source "reported" and no caller key. A rid
already reported is skipped, as is one repeated in the post. The set of
reported rids is read back from the log: one scan after a restart (lines
without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
flag; packed flags widened to uint16). Otherwise it is priced at
magpie's prices.
- Display:
- SourceReported is a source of its own: RequestPage.Reported,
?via=reported, and Ledger now honours via.
- The Requests tab gains a fourth cell "reported by apps", shown once
there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
- a key's budget/spend limit (budget.counts);
- window holds, and the log start that decides whether a window can be
reckoned (logSnapshot.firstOwn);
- gateway sessions and Vias;
- Codex's sealed answers and remembered model.
There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
site integrate.html (en, zh).
Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.
Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
- usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
languages, 1180 and 420 wide, light and dark);
- usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
- 40 posts of 5000 took 0.40 s (worst batch 18 ms);
- the first post after a restart took 0.45 s (rid rescan), a later one
1.6 ms;
- the cold index build took 2.1 s (as for gateway rows);
- page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
- summary all took 215 ms, 30d 20 ms.
Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
cost; the block pricer overwriting own cost; the Reported split;
fromBrowser's key rule; skipping bad records instead of refusing; the
max-records and body limits; the ingest lock (race); both locks;
firstOwn -> first; the IsReported guards in windowHolds,
buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.
Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.
|
||
|
|
47269f448f |
usage, gateway, gui: the Requests card counts requests once, a try handed on to the next isn't a failure, and says how many were answered on a retry (小一 on Discord)
小一's Codex-on-credits ledger read "5,482 · 1,094 failed" while many rows said "2 tries/3 tries" and had been answered. "Failed" counted usage rows, not requests: besides each request's final row, the gateway writes a row for every try a vendor refused or turned away (hw.refused/hw.turnedAway), and each of those was counted as a call and a failure even when a later member answered. (Ordinary failovers write no row; 499 cancels and the agent's own client-side retries are separate requests.) In the owner's own usage.jsonl, 24 of the 71 "failed" rows were such refusals a later member answered. Now a request counts once, by how it ended: - usage.Record gains `tries` (final row, when the route took more than one) and `handed_on` (the row of a try that failed and handed the request on). Totals.count skips handed-on rows; a failure is a request whose agent got an error (LostRequest); one answered after a failed try is Totals.Retried (RetriedRequest), with a `retried=1` filter. - Logs written before this are read the same way: the log index marks a failed, non-rejected row followed by another of the same route id as handed on and raises the later row's tries (routeRows); the packed row and its snapshot carry both. - Panel card, Usage overview tile, ledger card, rankings and group rows, `magpie usage` and the TUI say "N answered on a retry"; the CSV adds `tries` and `handed_on` at the end. A row says "· handed on" (with why in its title) or "· N tries". - On the ledger's Requests card "N failed" and "N answered on a retry" are buttons that switch the list to the Failed / new Retried filter, and back when pressed again. The lines wrap rather than cut a button off (German). zh, zh-TW, ja, de strings added. - Docs: reference.md (counting, filter, CSV columns), gateway-routing.md. Run: - go test -tags nogui ./internal/usage ./internal/usageapi ./internal/tui ./internal/gateway . : ok. New TestRequestsCountedOnceWithTheirRetries (JSONL fixture: legacy refused row + 200, handed_on + 200 tries 3, 502 tries 2, plain 200, routeless 429 → 5 calls, 2 failed, 2 retried, across Ledger, QueryPage, Summarize, heatmap, filters, CSV) and TestRetriedRequestCountsOnce (group a refuses, b 500s, c answers → 1 call, 0 errors, 1 retried; a lone 400 → 1 error). - Broke each by hand (count without the HandedOn skip, gateway without HandedOn, log index without routeRows): each test went red; restored. - go test -tags nogui -timeout 40m ./... under the gotest lock, rebased on origin/main |
||
|
|
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. |
||
|
|
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. |