Commit Graph
22 Commits
Author SHA1 Message Date
yetone 2ace161020 usage: the model speed ranking by provider, with each provider's failed and swapped tries
skingstyle48487 on X runs more than ten relays and asked for a live view of
each one's speed and model performance. The ranking's key is now model plus
provider: each key counts its tries, the failed ones (failed or handed on)
and the swapped ones (the reply named another model, Row.Swapped). The
ledger sends them as provider_speeds; the model view merges them back as
before. settledCountVersion goes to 7 so settled pages are counted again
with the new fields.

Run (mote): go test ./internal/usage ./internal/usageapi, and the full
suite (see the last commit of this push).
Broken by hand: dropping m.Swapped++ or m.Failed++ turns
TestModelSpeedRankByProvider red.
2026-11-17 23:13:03 +08:00
yetone 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 7d5475769), mote: gofmt clean;
  TestCoreScriptBudget and TestLedgerSaysItsOneProvider ok;
  panel-currency-provider.test.cjs 20/20 (chromium + webkit x en, zh,
  zh-TW, ja, de; panel 440/320px, window 1100/420px, no sideways
  scroll, no page errors).
- At ff3ab573d (same change on 90932ed1f), mica, under suite.lock:
  go vet darwin, linux nogui, windows ok; builds for all three ok;
  go test -tags nogui -count=1 -timeout 45m ./... : 99 packages ok,
  exit 0. mote: go test usageapi, gui, usage ok.
- GUI suite, the 155 files the change can reach, mote: 2581 tests, 105
  failures in 13 files; the same 13 files give 104 at 90932ed1f. The
  one extra is tray-cell-click webkit en, flaky on both trees run
  alone (head green twice, base red once). Filed: grip-inset,
  key-balance-card, panel-fold, tray-cell-click, usage-* (#6293,
  #6294, #6295, #6499, #6003, #5872, #6414, #5869, #5796, #5215,
  #4790); panel-shortcut's 20 reds newly filed as #6606.

Broken by hand:
- panel-currency-provider on the old assets (MAGPIE_ASSETS): 20/20 red,
  with the reporter's symptom (DeepSeek $1.00, SiliconFlow $0.500
  under By provider).
- TestLedgerSaysItsOneProvider red with `out.Provider = f.Provider`
  removed.

Not tried: the real app's tray panel with real yuan and dollar
providers.
2026-11-14 12:42:46 +08:00
yetone 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).
2026-11-12 22:40:15 +08:00
yetone 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.
2026-11-12 02:01:31 +08:00
yetone 745d209dcf usage:day takes a from: a week, a month or all time in one read (HeheLi29136651 on X)
HeheLi29136651 asked for the Day card's weekly, monthly and total bill. The
read only answered one day, so the plugin had nothing to draw. usage:day
now takes {from: "YYYY-MM-DD" | "all"} beside date: the days from there to
date, with the same totals, agents, models and days list (usageapi.SpanOf;
DayOf is SpanOf with no from). "all" starts at the first day with calls:
the ledger keeps old calls in wider buckets that start before the first
call, so From is taken from the first day the heatmap lists. A from after
date, or a date after today, is an error. Answers carry `from`, which is how
a plugin tells a magpie that has spans from one that ignores the param.

Run, on mote:
- TestSpanOf (week, month, all, all up to an earlier date, day alone,
  bad inputs) with calls 300 days back, where the bucket starts before the
  first call: red when the From correction is removed (From 2026-01-12 for
  a first call on 01-15), green with it.
- TestPluginPageReadsADay gains from "2000-01-01", from "all" and a from
  after the day.
- go vet (darwin, windows, linux -tags nogui), usageapi and internal/plugin
  tests ok.
- The plugin side (page-day-card 0.3.0) reads it: seen in the sandbox web
  instance in chromium and webkit, empty ledger only.

Not tried: a ledger with real calls end to end in the page (the plugin's
test covers the card from a made-up read), and a magpie from before this
change opening the 0.3.0 page (the code path throws "usage:day from" when
there is no `from`, and says to update).
2026-11-11 17:38:42 +08:00
yetone 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 e430e2750, accounts-own-signin #6038), each red alone on origin/main 71a68639b or load-only.
Timing: 1M requests added to a chunk in ~185ms (TestModelSpeedRankAtTheLargestLedger).
Broken by hand: dropping the Failed/Canceled exclusion (gpt: 5 requests, 59.7 tok/s) and dropping the page's merge of chunk speeds (ranking empty) each turned the new tests red; restored.
Not tried: the real Linux app (WebKitGTK), a real ledger of hundreds of thousands of rows through the page-v2 file, a Windows run (win-run).
2026-11-11 10:12:23 +08:00
yetoneandNorethSea 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 720200092, and the -run tests,
quota-holds and i18n-keys again at this head on 208b89422; rebased since onto 44732325e,
a gateway test only):
- go test -count=1 -tags nogui ./internal/gui ./internal/provider
  ./internal/sessions ./internal/usage ./internal/usageapi: ok
- go vet -tags nogui (linux), GOOS=darwin CGO_ENABLED=0 go vet (provider,
  usage, usageapi, sessions), and go vet on Windows (win-run, those and
  internal/gui): clean. gofmt -l: clean.
- GUI: usage-ledger-model-pick, usage-ledger, quota-fit-batched,
  i18n-keys in chromium and webkit. usage-ledger's "newest live route
  needs no return-to-live button" (and zh "request routing links") is red
  the same on origin/main 987eac0aa on that box: #3104, #4078.

Broken by hand:
- keepsRecord back to r.Model != f.Model: TestUsageFoundGroupNames and
  TestLedgerFoundGroupNames red.
- usageGroupNames returning nothing: TestUsageFoundGroupNames (provider,
  usage), TestSessionsFoundGroupNames, TestCodexEffortFoundGroupNames,
  TestLedgerFoundGroupNames red.

Not tried: a macOS run (mote unreachable), the darwin gui package's vet,
and the reporter's own usage log.

Co-authored-by: NorethSea <963979204@qq.com>
2026-11-10 18:01:13 +08:00
yetone 623e797fde plugin pages: read a day's usage and share a picture they drew
A plugin's page can now read one day's usage and share an image it
drew. This is for the day card (JungleyYeh on X asked for a "daily AI
statement"); the card itself is an optional community plugin,
@magpie-community/page-day-card.

- A page that asks for the "usage:day" read gets that day as
  magpie.read("usage:day", {date, tz}): totals, each agent and its
  models, the streak and the average active day (usageapi/day.go,
  gui/pageday.go). The Plugins page names the read before it is granted.
- magpie.image.copy(png) and magpie.image.save(png, name) share a PNG
  of at most 16 MB. In the window they go through
  POST /api/plugin-pages/image (pageimage.go): copy puts the picture on
  the clipboard (clipimage.go: osascript PNGf on macOS, PowerShell
  PNG + Bitmap on Windows, wl-copy or xclip on Linux), and save writes
  it to Downloads under a name made safe. In magpie web, the browser
  saves or copies the picture itself.
- The window's side, pageshare.js, is imported the first time a page
  shares a picture. The core grows by its one call only, paid for by
  comments cut, so the budget is not raised.

Tests:
- New: TestDayOf, TestPluginPageReadsADay, TestPluginPageSharesAPicture,
  TestPageImageName and TestClipImageCommand. plugin-page.test.cjs
  covers the bridge, both engines and a refused SVG.

What was run (mote):
- gofmt, plus go vet on darwin, linux and windows: clean.
- Full go test ./... at the pre-rebase base: 369 packages ok, 3 FAILs.
  - TestEveryRouteHasACommandOrIsNamed and TestCoreScriptBudget were
    this change's own reds. The new route now has a parity entry, and
    the share code moved into lazy pageshare.js with no raise.
  - TestGatewayModeStatsNameTheGatewaySessions is #5690, the red in the
    first hour of the day (it ran at 00:32).
- GUI suite (affected and plugin files, both engines): 1160 of 1179
  passed. Every red is filed and none touches this change:
  - i18n-keys "a plugin's words are its own": #5332, #5426, #5482.
  - page-width-steady: #5013.
  - plugin-card-update in WebKit: #3079.
  - plugin-move-unserved "Try again": #4410.
- At this head, after the rebase on bc8b01d60:
  - gofmt clean; go vet ./internal/... on darwin, linux (nogui) and
    windows ok.
  - internal/usageapi, internal/plugin and internal/cli ok.
  - internal/gui: TestCoreScriptBudget, the TestPluginPage* tests and
    the TestPageImage/TestClipImage tests pass.
  - plugin-page and old-webkit (both engines): 12 of 12.

Real use:
- A sandbox HOME with a copy of real usage, through the real GUI
  server, in Chromium and WebKit, light and dark, en/zh/zh-TW/ja/de, at
  420 and 1100 px. The card showed 87.9M tokens, $9.85 and 4076 calls
  with a 22-day streak.
- Picking an earlier day and WebKit's Copy ("Copied") worked, with no
  page errors.
- Not tried at push: Chromium's Copy (its headless clipboard was
  denied) and magpie web's Save as a captured download. A second real
  run that grants both was still queued on mote's suite lock.
- Clipboard: checked live on macOS (osascript) and Windows
  (PowerShell). Not tried live on Linux: WSLg had no display.
2026-11-09 23:19:14 +08:00
yetoneandmdwsk88 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 e056779a, a3768cdd,
c86fa2a3 and fcc0daa2, broke each check by hand (each red), and sent
real Claude Desktop cancels through a nogui build with a stand-in
upstream and OTLP collector. Its full record is on aea0027fd. Since
58541e5b (#4866) Codex's own-sign-in relay logs Codex gone mid-reply as
499 through canceled() too, so it counts as canceled
(TestCodexGoneMidReplyIsNoFailure). drawing_route.go still reads a
canceled request as not served when it decides whether a picture's
next request may stay on its provider: that is routing, not a count.

Ported to origin/main 400b66ec3 on 2026-11-07, reviewed line by line.
Two siblings it left on the old rule, and a colour, now covered:
- usage.Row.Floor (the Claude Code speed floor) asked !Failed, so a
  canceled row, whose Failed is now false, told a floor: "3000 tokens
  in 4000 ms" for a reply no one waited for. It asks Answered now, as
  the speed and first-token sums do. TestAgentCanceledTellsNoFloor.
- The route-events feed (activityOf, #3387) told a canceled try and
  done route as failed. It leaves usage.CanceledBy out, and still
  counts magpie's own 499 limit. TestRouteEventsCanceledIsNoFailure.
- routing.css: a canceled Routing row ("rt-req gone") had the
  answered green dot. Its dot is muted now.
  routing-canceled-row.test.cjs checks the row, its dot and the errors
  stat in Chromium and WebKit, in en, zh, zh-TW, ja and de.

Run at this tree (mote-run, macOS):
- go test -count=1 internal/usage, usageapi, otlp, settings,
  settingsapi and cli: ok. internal/gateway: ok with -timeout 45m
  (847s; the default 10m ran out under load). internal/gui: ok but
  TestMainWindowCorners/macOS_26_SDK (#3949, mote is on macOS 27).
- Broken by hand: Floor on Failed again makes
  TestAgentCanceledTellsNoFloor fail ("a canceled row tells a speed
  floor: 3000 tokens in 4000 ms"). activityOf without CanceledBy makes
  TestRouteEventsCanceledIsNoFailure fail ("a done route its agent
  canceled is told failed"). Restored, both pass.
- GUI: node --test --test-concurrency=4 over routing-*, usage-*,
  ledger-*, panel-*, call-*, search-*, searcher-*, settings-*, i18n-*
  and gui-* (Chromium and WebKit; the files cover en, zh, zh-TW, ja
  and de), with #2398 and #5545 in one tree: 4961 of 5016 ok. The 55
  reds are in 12 files. i18n-keys' "a plugin's words are its own"
  names other files' strings (#5327, #5426, #5482). The other 11 files
  were run alone at dc49feca9 (this tree without either change) and at
  this tree: 52 and 51 reds, the same tests. The one apart is
  usage-focus-steady, which flakes (#3501). Each is filed: #5392,
  #3414, #5048, #3799, #3415, #3954, #4627, #4628, #5223, #1529.
  routing-canceled-row.test.cjs: 10 of 10. With the .rt-req.gone rule
  taken out, its dot is the answered green rgb(24, 154, 88) and it
  fails. Restored, it passes.
- Not tried: a real Claude Desktop cancel through this tree; Windows
  and Linux runs.

Co-authored-by: mdwsk88 <11055210+mdwsk88@users.noreply.github.com>
Reported-by: mdwsk88 (dawei on Discord)
2026-11-07 04:03:01 +08:00
yetone 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 14b451c11, then rebased on origin/main):
- gofmt -l clean; go vet (darwin) on access, cli, usageapi, gui;
  GOOS=linux -tags nogui and GOOS=windows go vet on access, cli,
  usageapi (mote).
- go test access, cli, usageapi: ok (mote). internal/gui: every test
  ok except the real-window AppKit tests #4125 lists
  (TestCoveredWindowStaysUp, TestPanelCloseHidesIt and 7 more), killed
  at their deadlines with pboard not running on mote.
- Broken by hand: with move-key removed, TestMoveKeyKeepsOrder,
  TestGatewayKeyCLIMove and TestLedgerKeyFilterInKeyOrder go red; with
  the mirror exclusion removed and the filter left unsorted,
  TestMoveKeyKeepsOrder ("the sharing key's mirror moved") and
  TestLedgerKeyFilterInKeyOrder go red.
- GUI (WSL): gateway-key-arrange 20/20 (chromium and webkit; en, zh,
  zh-TW, ja, de; 1100 and 420px). Red by hand: no arrange (20 red),
  grip always shown (chromium 10/10 red), drop commits nothing (webkit
  10/10 red).
- GUI (WSL), the 68 files the change can reach (every caller-keys
  fixture user, gateway-*, search-*, usage-ledger*, i18n-keys, gui-ja,
  gui-de, gui-zh-tw, key-page, phone-rows, api-key-*): 900/923. The
  reds were run again at origin/main 43966a53f and fail the same there
  (api-key-theme webkit, gateway-key-limit webkit, gateway-key-models
  webkit, search-first, usage-ledger-open-settled, usage-ledger-ttft,
  usage-ledger), each filed: #3307, #3523, #4081, #3795, #4262,
  #3104/#1876, and #4489 (usage-ledger-ttft, new). phone-rows,
  search-keys and connect-snippet-shell reds of the first run passed
  when run again at the head. usage-ledger's "zh: request routing
  links" went red once at the head (Usage view position on return) and
  passed in the first run.

At the rebased head (on 2ac423f4f): TestCoreScriptBudget and the
other Budget/I18n/Asset tests in internal/gui ok (mote);
gateway-key-arrange, i18n-keys and gateway-caller-keys 27/28 in WSL.
The red is gateway-caller-keys webkit en "wider than 560 right after
the resize" (#3797, red alone on main). A probe of that file, printing
the page width and any element past it, read 560/560 with nothing
wider in both engines, in two runs beside the arrange file.

Not tried: dragging in the real app (WebKitGTK, WKWebView, WebView2),
the full Go suite (started after the push).
2026-10-31 03:48:27 +08:00
yetone 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 2f5a3f1c0 + this change: all ok
  but internal/agent TestPiModelsAskedOnTheirNativeAPI (fixed on main
  by 7474a86f1, green there; this is rebased onto it),
  internal/update TestRelaunchOpenTriedAgain (#3881, green alone x3),
  and internal/gui's real-window AppKit tests (TestPanelCloseHidesIt,
  TestMainWindowCorners, TestTrayCellClickReleasedPanel red the same
  on origin/main 99ad38b7c; #2645, #4125, #1936).
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of the
  touched packages; gofmt -l clean.
- TestPluginAccountShownByItsUsageUser (new, real plugin host and fake
  plugin): id before a read, phone after, phone after a restart from
  quotas.json, phone kept over a failed read, own name wins, id when
  nothing is known. Red on the old code.
- GUI on the Linux box (mote's Chromium segfaults on these pages on
  origin/main too, #4125): account-plugin-user (new),
  routing-account-name (extended) and account-alias, Chromium and
  WebKit, every language, 34/34; the new checks red on the old code;
  the whole suite (make test-ui on the Linux box) was still running at
  push: 417 files in, 5 reds, none on a page this changes
  (account-models' row-moved check in WebKit, 81 vs 79px, and
  agent-models-all-hidden), not yet compared with origin/main; any
  that are new get an issue once it ends.
- At the rebased head (3bce283df): go test of provider, cli, tui,
  usageapi, plugin, agent -run TestPi, gui -run
  Budget|Provider|Quota|Account: all ok. Core scripts 1,535,513 of
  1,536,586.

Broken by hand: dropping the quotas.json fallback turns the test red
at "after a restart".

Not tried: a real Huawei CodeArts account (none here). A plugin whose
windows are all model pools isn't kept in quotas.json, so after a
restart it shows its id until its first read.
2026-10-31 01:01:49 +08:00
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