Commit Graph
11 Commits
Author SHA1 Message Date
yetone 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 d50f84c9f):
- go test -tags nogui -timeout 45m ./... : every package ok, exit 0.
- GOOS=linux and GOOS=windows go vet -tags nogui on usage, usageapi,
  provider, gui, gateway: ok. gofmt -l clean.
- New: TestDeletedProviderMergedIntoAnother (usage: cost 306 before and
  after the merge, 3 calls under main, coster/pricer price a relay call
  at its own price, a new "relay" keeps only its own call, rename and
  delete of the target, undo), TestDeletedProviderNamedAndMerged
  (usageapi), TestUsageDeletedProviderRoutes (gui).
- GUI: usage-ledger-deleted-merge.test.cjs, chromium and webkit, en zh
  zh-TW ja de at 1400 and 760px: ok. All 63 usage-*/ledger-* files and
  i18n-keys, both engines: 923 of 954 ok. The reds are red the same on
  origin/main c3b0484a9 run alone: usage-agents-hide (#3414),
  usage-fold (#3415), usage-ledger's "newest live route needs no
  return-to-live button" (#3104), and i18n-keys' "a plugin's words are
  its own" on library's "Runs as" (#3897).

After rebasing on origin/main 3e96197da (i18n.js merged with c3b0484a9's
balance keys): go build ./..., go test of internal/usage/...,
usageapi/..., provider/..., gui/... ok; the new GUI file in both
engines and every language ok; i18n-keys only #3897's red.

Broken by hand:
- Both returning (to, to): TestDeletedProviderMergedIntoAnother red,
  "cost 900, before 306".
- renamesOf not setting into: both Go tests red (relay still listed).
- ledProviderMore returning at once: the GUI test red (timeout waiting
  for the …), 5 of 5 subtests in chromium.
- On the old code the new tests don't compile (no MergeDeleted).

Not tried: the real app on a real providers.json with a deleted
provider; Linux/Windows GUI. gateway_sessions still prices by the raw
id, and a deleted provider's per-provider price stops applying once its
id is reused (both before this change, unchanged by it).
2026-10-28 11:15:57 +08:00
yetone 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.
2026-10-28 04:18:21 +08:00
yetone 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 e435b8867 + this change:
- gofmt -l and go vet on internal/usage, internal/usageapi and
  internal/gui: darwin, GOOS=linux -tags nogui, and GOOS=windows. The
  vet ran before the new _test files were added.
- go test ./internal/usage ./internal/usageapi and
  -tags nogui ./internal/gui: ok with TZ=UTC and with
  TZ=Asia/Shanghai.
- New tests:
  - TestUsageReadsTheViewersZone and TestZoneNames (internal/usage).
  - TestUsageRoutesReadTheViewersZone (internal/gui) asks the routes
    with ?tz= naming a zone other than the server's.
  - Each holds usage.Clock and checks the hour label, today's
    membership, the Day filter, the week chart's day label and the
    heatmap's days. With no ?tz=, the server's days are kept.

Broken by hand:
- Clock().In(zone) / Clock().In(f.loc()) back to Clock(): red in both
  zones (Summary, Requests, ledger, heatmap, /api/usage,
  /api/usage/requests, /api/usage/heatmap).
- The Day filter read in time.Local: red under TZ=UTC.
- The summary's and chart's bucketing in time.Local: the week-day label
  check goes red under TZ=UTC. Under TZ=Asia/Shanghai the chosen
  moment falls on one date in both zones, so it can't tell there.
Each was restored after.

Not tried:
- A Playwright GUI test with timezoneId in Chromium and WebKit was
  not written. The GUI suite and usage-stale-answer.test.cjs (which got
  a usageZoneQ stub) were not run: the disk was at ~350 MB free.
- TestCoreScriptBudget was not run again after the change. app.js is
  untouched, and page.js is a plugin page outside the core budget.
- A real remote `magpie web` from another zone, and the Windows box.
- Siblings left alone:
  - The Sessions tab buckets by the server's days and hours in its
    cached rollups, and its "By hour" card labels them with the
    browser's zone name.
  - The Routing history's day files are the server's days.
  These need issues of their own.
2026-10-23 10:54:27 +08:00
yetone 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 ca4a1cde0, head tree
539c84e92. Go 1.26.8, sandbox HOME, GOMODCACHE/GOCACHE pinned. The full Go
run and vet were at tree d6393dfc8, the same Go code as this head: only
app.js comments (cut under the core script budget) and one ja string
changed after it.
- gofmt -l: nothing. go build ./...; go vet ./... (darwin), GOOS=linux
  go vet -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test -timeout 45m ./..., through tee, one suite on the machine:
  68 packages ok. The one red was internal/gui's
  TestCoreScriptBudget: app.js 1,335,314 > 1,335,000, since main grew
  app.js under the stack. The autoscroll commit's own comments were cut
  (to 1,334,629) rather than the budget raised, and go test -count=1
  ./internal/gui is ok at this head (113s). Packages the run took from
  Go's test cache had the same inputs.
- GUI: the 18 files this stack touches or names, both engines,
  202 of 204 pass (tree 068acf128, this push less the last commit). The
  two reds: gui-ja, red on main since c2636b7b5 and fixed by this push's
  last commit (gui-ja and i18n-keys 6 of 6 there), and usage-fold's
  chromium "several accounts" (#2163, red on main the same way).
- Red on the old code: TestAccountNameOfAPluginAccount, with
  AccountNames put back to a.User, fails with "a gateway key's accounts
  read [fakeco/31****36@qq.com]". The new GUI test
  routing-account-name.test.cjs, with the old client.js, fails with
  "renamed, the account reads by its new name: Kiro example@gmail.com
  (foo) Pro".
- routing-account-name passes, en and zh, both engines. internal/provider,
  internal/usageapi, internal/cli and internal/gateway ok.
- The five usage files this change's first run found red: usage-agents-hide
  (#2276), usage-checkin (#3091), usage-fold (#2163) and usage-ledger
  (#3104) are red alone at the stack and on main the same way.
  usage-overview-fold now passes alone at both.
  The whole GUI suite ran at 1c1fc7183 (this stack's first 12 commits on
  0ddcf28a1): 11713 of 11769 pass. Each of the 21 red files was then run
  alone at the stack and at origin/main 8278fd9b0. Eight are red the same
  way on main: plugin-card-update (#3079), quota-count-wrap and
  quota-name-translated (#2228), s3-sync (#2448), usage-agents-hide
  (#2276), usage-checkin (#3091), usage-fold's chromium "several
  accounts" (#2163), usage-ledger (#3104). The other 13 pass alone on both
  and were red only under that run's load (50 to 335): currency #3101,
  plugin-github #3218, provider-fetch-again #3292, rest-try-now #2564,
  routing-auto-reset #3293, routing-keys-fold #1612, routing-steady #1804,
  routing-wb-restricted #1905, sessions-folder-delete #2218,
  sessions-manage #3294, switch-only #3295, text-size #1866, usage-pack
  #3296.

Not tried: a real Kiro account. The fixture is the reporter's case, with
their names.
2026-10-23 01:58:01 +08:00
yetone 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 df6bd3efe (head 48522d851):
    gofmt -l: nothing
    go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
      GOOS=windows go vet ./...: ok
    set -o pipefail; go test -timeout 45m ./...: ok, EXIT=0
      (68 ok, 19 with no test files; agent 528s, gateway 628s,
      library 482s)
    GUI, playwright 1.62.0, chromium and webkit, concurrency 3: the
      171 files near this change (routing*, panel-routing*,
      window-mask, privacy*, usage*, quota*, providers*): 2217 tests,
      2183 pass, 34 fail. Every red is also red alone on origin/main:
      quota-count-wrap and quota-name-translated (#2228),
      usage-agents-hide (#2276), usage-checkin (#3091), usage-fold
      (#2163), usage-ledger (#3104, red since df6bd3efe, green at its
      parent). window-mask: 20 of 20.
  At this stack on origin/main c922225f1 (head 91baa7adb), before
  df6bd3efe's routing trace change:
    set -o pipefail; go test -timeout 45m ./...: ok, EXIT=0
      (66 ok, 20 with no test files)
    the whole GUI suite (823 files, both engines, concurrency 3):
      11589 tests, 11554 pass, 35 fail. The 9 files red were run again
      alone at --test-concurrency=1 on the head and on origin/main
      a8ecf4020. The same 7 files were red on both: the five issues
      above plus s3-sync (#2448) and library-row-remove (#3099).
      nav-sub-unroll (#1950) and plugin-updates (#3103) were red only
      under the full run. codex-predictions (#2624) was 20 of 20.
2026-10-21 08:40:49 +08:00
yetone 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 d9b943555 (head 663db0ecf), with the #2517,
#2521 and #2522 changes, load ~240:
- gofmt -l clean; go vet -tags nogui for darwin, linux and windows: ok.
- go test -timeout 120m -count=1 ./... (pipefail): exit 0, every package
  ok (gateway 1416.8s, agent 1535.5s). Before the rebase, on 63be47717:
  - The 45m run had agent and gateway past 45m (#2544, #2108).
  - TestMainWindowCorners was killed at its deadline (#1936).
  - TestSkillRelinkKeepsUnreadableCopy failed (#2555; it passes alone).
  - gateway alone with 120m was ok.
- GUI, the 41 Requests/Usage files in serial, both engines, before the
  rebase: 493 pass, 3 fail. The 3 were usage-refresh "not yet 2 !== 1",
  the same on 63be47717 alone (1 of 3); seen again on #2184.
- Rebased, these all pass, 102/102: i18n-keys, usage-ledger-ttft,
  usage-ledger-key-split, usage-ledger, usage-speed, usage-ledger-detail,
  gui-ja, gui-de and gui-zh-tw.
- Rebased again onto 9b04c4e20, which touches ledger.go, request_page.go
  and gateway.go:
  - vet ×3: ok.
  - internal/usage, internal/usageapi and internal/cli: ok.
  - internal/gateway -run 'NativeCompaction|UsageOverGateway|Capped|Cap':
    ok.
  - usage-ledger-ttft, usage-ledger-key-split, usage-ledger and
    usage-speed: 86 pass. i18n-keys was red from main's own words (#2586,
    fixed in the next commit).
2026-10-16 21:59:33 +08:00
yetone 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.
2026-10-14 18:19:16 +08:00
yetone 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.
2026-10-13 06:32:03 +08:00
yetone 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 de1ba9f12: all ok
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on ., the
  usage, usageapi, tui, gateway and gui packages: clean.
- Playwright ledger-retried.test.cjs, Chromium and WebKit, en zh zh-TW ja
  de, 420 and 1100 wide: 20/20 (German first failed on the cut-off line,
  fixed by letting the button lines wrap). usage-*, api-key-usage,
  purpose-filter (Failed is now the 2nd of 3 options), panel-usage,
  click-scroll, request-archive-usage, both engines: all green except
  purpose-filter's Routing case (1px focus scroll), which fails the same
  on 909d76747 and de1ba9f12, in Chromium too; it is #1291 (commented)
2026-10-11 12:58:03 +08:00
yetone 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.
2026-10-11 04:44:13 +08:00
yetone 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.
2026-10-10 20:47:00 +08:00