aca0f0d8a1630923bf4e8a18b3a5a8ef508fc7bc
11
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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. |