Commit Graph
92 Commits
Author SHA1 Message Date
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 640825b09a usage: the Requests card's traffic line reads whole, and a row says how many images went by file
matrix0487 on Discord:
- The Requests card's line "↑ 13 GB · ↓ 13 MB · 图片文件省下 44…" was cut
  with an ellipsis. It was one nowrap span.
- A row's details say "图片文件省下 10 MB" and should say "10 MB(3 张)".

The card line is now made of whole parts (usageParts, the pattern the
token line has since #2378). A card too narrow for all three puts the
saving on a line of its own. A part that is wider than the card by
itself (German at 420 wide) wraps inside itself; it is never cut.

The count:
- withDeepSeekFiles counts the image blocks it puts a file id in place
  of, on each try, and upBytes keeps the most of any one try (a retry
  sends the same images again, as the saved bytes are counted).
- It goes into usage.Record as `image_files` (omitempty) beside
  image_files_saved.
- packedRow keeps Tries and ImageFiles in int16 each (clamped to
  MaxInt16), so the row stays 152 bytes. request_snapshot carries the
  new field, and heat_disk hashes Tries as before.
- The detail row says "{size} ({n} image|images)": zh "10 MB(3 张)",
  zh-TW 張, ja 枚, de "Bild/Bilder", en "image/images".
- A row from before the count was kept has no image_files and shows
  the size alone, with no parentheses. The card's period total gets no
  count.

Run on mote, at this tree:
- gofmt -l (clean), go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build ./...: ok.
- go test -run 'TestRowImageFilesKept|TestRowBytesKept|TestRowsOfOneSession|
  TestDeepSeek|Snapshot|Heat' ./internal/usage ./internal/gateway: ok.
  - TestRowImageFilesKept: the count survives pack/unpack beside Tries,
    100000 clamps to 32767, an old row reads 0, the JSON has
    "image_files":3 and leaves out 0, and packedRow is 152 bytes.
  - TestDeepSeekImageFilesCountedInRow: two images in one message and
    one again in a later message make 3 in the stored row, twice, and a
    request with no image makes 0.
- GUI, BROWSER=chromium and webkit: usage-ledger-bytes runs every
  language at 1180 and 420. The 3-image and 1-image rows read in each
  language's unit, singular in en and de, and the old row stays bare.
  The reporter's period (13 GB, 13 MB, 44 MB) at 1180, 760 and 420 has
  every part whole and inside its card.
- The 79 usage-*/led* GUI files (concurrency 2): 641 of 659 pass in
  chromium and 637 of 654 in webkit. Every red is filed and red on
  origin/main d2c29abe7 too (run alone there in chromium, the same 17
  subtests): usage-agents-hide (#2276, #3414), usage-fold (#3415, #2163;
  in webkit also a timeout in "several accounts"), usage-ledger's
  return-to-live (#4078, #5048) and usage-overview-fold (#3947).
- Broken by hand, each red:
  - The count left out of packedRow: TestRowImageFilesKept.
  - The count not kept in withDeepSeekFiles:
    TestDeepSeekImageFilesCountedInRow ("0 images by file, want 3").
  - The detail's count dropped: usage-ledger-bytes in every language
    ("expected '10 MB(3 张)', actual '10 MB'").
  - The in-part wrap dropped: "de big 420" ("cut: 0,0,0,11").

Not tried: a real DeepSeek account (the count rides the same path as the
saved bytes, which were tried for #5407), and Linux WebKitGTK.

Reported-by: matrix0487
2026-11-06 11:46:25 +08:00
yetone 8b70b7d976 usage: a request's bytes up and down, and what DeepSeek's image files saved, in Requests
Suggested by @faithleysath (matrix0487 on Discord): the usage ledger now
keeps what each request received back (down_bytes) beside what it sent up
(up_bytes, #4456), and what DeepSeek's image files (#5407) kept out of the
upload (image_files_saved).

Shown in Usage → Requests:
- a row's details: "Sent upstream", "Received" and "Saved by image files",
  each only when it is above 0. A row from before has none of them, not 0;
- under the Requests card, the period's "↑ up · ↓ down", with
  "{n} saved by image files" when there is a saving. Its title gives the
  exact bytes. A period with no counted bytes shows no line.

What is counted:
- Down bytes are counted as the reply body is read, after Go's transport
  has undone gzip, so a gzipped reply counts its plain size, not wire
  bytes. A plugin's row counts the local hop to the plugin host. A 101
  body is not wrapped. Every try counts, so a refused try plus the
  answering one add up (TestLedgerKeepsDownBytes).
- Image files saved, per try: the body before the swap minus the body
  sent, minus the upload bytes this request itself paid (len(b64)/4*3).
  It can be negative on the turn that uploads; the GUI shows only a
  saving above 0. Gaps: an upload that finishes after the wait timeout or
  ctx-done is not subtracted (as with up_bytes); a joined upload flight is
  paid by the request that started it; multipart overhead is approximate.
- packedRow grows by three int32 (152 bytes, still within the test's
  bound), clamped to the int32 range. Totals sum all three.
- settledCountVersion goes 1 → 2, because Totals now count bytes. The
  settled page, heat and effort caches recount once, on the first start
  after the update. The heat key hash includes the new fields.

Run on mote at 84ad780b6 (origin/main, fetched):
- go test ./internal/usage: ok.
- go test ./internal/gateway -run 'TestLedgerKeepsDownBytes|TestDeepSeek|
  TestCodexOwnTurnKeepsUpBytes|TestLedgerKeepsUpBytes|
  TestLedgerCountsATrysSecondAsk': ok.
- go test ./internal/gui: only TestMainWindowCorners/macOS_26_SDK fails,
  as on main (#3949).
- gofmt -l clean; go vet of usage and gateway for darwin, linux (nogui)
  and windows; go build ./...
- New GUI test usage-ledger-bytes.test.cjs: 30 of 30 in Chromium and
  WebKit, en/zh/zh-TW/ja/de, at 1180 and 420 wide. It is red on the old
  page.js.
- usage-*, ledger-*, i18n-* and nav-timeout GUI files: 1231 of 1267.
  Every red is red on a clean 84ad780b6 too: usage-agents-hide (#3414),
  usage-fold (#3415), usage-ledger's "newest live route" (#5048),
  usage-overview-fold, which flakes in other languages on each run
  (#3947), i18n-keys (#5332, and #5426 filed now for "No session ID"),
  and nav-timeout (#5425, filed now).

Broken by hand:
- gotDown not wrapping the body: red, "down 0; the vendors answered
  141/265 bytes" and "the backend answered 105 bytes".
- the saved += removed: red, "saved 0".
- the settled guard red with the bytes fixture until the version raise.

Not tried: a real DeepSeek or other vendor account through a built app,
and a screenshot of the real app. The CSV export does not have the new
columns yet.
2026-11-06 09:17:10 +08:00
yetone 69167bc299 usage: a reply let go under a second after a wait four times longer tells no speed
pluviophile714 on Discord: a gpt-6.1-sol row on Routing read 1,539
tok/s (input 21,617, output 392, first token 8.2 s, total 8.3 s), where
another monitor measures ~70. The reply came whole about 255 ms after an
8.2 s wait. Its content was spread over that short window (flow 230 ms),
so the HeldShare flow check passed, and so did the 100 ms floor, and
392/0.255 s read as 1,539 tok/s.

New rule, usage.HeldWindowMs: a window under 1,000 ms whose start
(first token, first text or first reasoning) is more than HeldShare (4)
times the window tells no speed. One rule in every place that computes
one:
- usage.DecodeOf: the Usage page's speed and totals, the CLI, the GUI's
  model speeds, and the gateway's Speed first pacing (noteTrySpeed);
- routing/client.js decodeOf: the Routing row's speed and its story line;
- usage/page.js ledDecode, plus a ledNoSpeed_ reason for the dash's
  tooltip, in en, zh, zh-TW, ja and de.
docs/reference.md and docs/subsystems/gateway-sessions.md say so.

On the owner's usage.jsonl (read only), 103 of the 106 rows over 600
tok/s were such windows (e.g. 448 tokens in 107 ms after 8.1 s) and are
dropped. The 3 that stay have windows of 2 to 5 s. The overall speed
goes from 103.8 to 97.9 tok/s.

What it costs: a short reply that really streamed after a long wait
tells no speed either. The live visible-reasoning fixture (76 tokens
over 731 ms after 6.8 s, ~104 tok/s) and #2637's grok record (307 tokens
403 ms after a 4.6 s first token, 531 tok/s) now read "—". Their tests
keep their guarantees with the same timings after a short wait, and also
check the long-wait case.

Tests:
- New: internal/usage TestShortWindowAfterLongWaitTellsNoSpeed (the
  reporter's numbers, a reasoned row from the ledger, the boundary, a
  second after a long wait, Totals) and internal/gateway
  TestShortWindowAfterLongWaitNotesNoPace.
- GUI: usage-speed-every-row has the reporter's row (dash, and the
  tooltip in all five languages); routing-burst-speed has it (first
  token 8.2 s, no tok/s).
- Updated to the new rule: TestVisibleReasoningSpeed's decode-minimum
  and max-speed cases (short wait now), TestCodexTurnMeasured...'s
  gateway/Claude rows, TestLiveVisibleReasoningFixture and
  TestUsageIngestTellsSpeed.

Run on mote at this tree (rebased on e41ef6288):
- go test -timeout 45m: internal/usage ok, internal/tui ok.
- internal/gateway: red only in TestCompactionOverByteCapEveryTime
  (#4862, full package run; passes 3 of 3 alone).
- internal/gui: red only in TestMainWindowCorners (#3949, macOS 27).
- internal/cli: red only in TestEveryRouteHasACommandOrIsNamed (#5026,
  red on main since 0872bc2a0).
- The two speed fixtures that failed in the gateway run pass on rerun.
- GUI, chromium and webkit: 36 files (every speed, ledger, i18n,
  routing-request and burst file), 609 tests, 603 pass. The 6 reds are
  usage-ledger's "newest live route needs no return-to-live button"
  (#5048, #4078, #3104 on main).
- Rebased on 1af868a15 (f0e0385a0 changed routing/client.js), then
  run again at the pushed head: internal/usage ok; the gateway speed
  tests (-run ...Speed|Pace|Decode|TTFT...) ok; 8 GUI files (both
  speed files, routing-request-metrics/-model, routing-speed-first,
  i18n-keys, reasoning-speed, usage-speed-tip) 94 of 94 in both engines.
- gofmt -l clean. GOOS=windows go vet of usage, gateway, gui and cli ok.
  GOOS=linux go vet of usage and gateway ok; gui and cli need cgo/GTK
  for Linux, the same on main.

Broken by hand: with the check off in usage.go, client.js and page.js,
the new Go tests, TestCodexTurnMeasured..., TestLiveVisibleReasoningFixture,
TestUsageIngestTellsSpeed and both GUI files (1537 tok/s shown) go red.

Not tried:
- the reporter's own request;
- a real GPT stream, to confirm that a 255 ms window after 8.2 s is a
  held reply from this vendor;
- the whole GUI suite (no new API call or layout change);
- the Linux and Windows app.
2026-11-03 17:01:51 +08:00
yetone e41ef6288c providers: a spend cap on an API key, per day, month or in all (sparkling_lemur_62868)
sparkling_lemur_62868 on Discord: a team's OpenAI key holds granted
credits that other docker services spend from too, and they want magpie
to stop at a share of it. Their workaround was two magpies behind a
gateway-key limit.

What changed
- provider: KeySpendCaps on a provider, keyed by the key's fingerprint
  (key_spend.go): USD over a local calendar day, a local calendar month,
  or in all since it was set. Since is kept while the cap stays one in
  all. SetKeySpendCap and ParseSpendCap refuse an amount outside
  0 < usd <= 1,000,000 and an unknown period, and leave the saved cap
  as it was. Subscriptions are refused, since an account has its own
  usage-window cap.
- usage: KeySpent(keyID, start) is what magpie's own calls on the key
  cost at the Usage page's prices. Turned-away calls and app-reported
  ones are left out. It reads usage.jsonl once per key and start, keeps
  the sum for 5 minutes, and Append counts each new call into it
  (spentNew). A read that a write races is read again.
- gateway: perKeyEvery bars a key at its cap (spendHeld) as a usage cap
  holds an account. The next key serves, then the fallbacks. With none,
  the reply is 429 "spend cap reached: ..." naming each key, what it
  spent of which cap, and how to go on. Retry-After is when the soonest
  period renews; a cap in all gives none. A spend hold is not a usage
  cap: Stop at the caps and strictKeep don't end at it (capHeldOnly).
  The trace's barred row carries the cap, the spend and the period.
- GUI: a pill on each key's row in the provider editor, for example
  "$7.50 of $20.00 today". It opens the app's menu (No spend cap,
  Per day..., Per month..., In all...) and then takes the amount in
  place, as the lane-limit pill does. A key at its cap gets a line
  under its row: "At its spend cap · back in ...". Every string is in
  all five languages. The pill and the line are in keyspend.js, which
  app.js imports when it draws a key's row, so the core's script
  budget is not raised. /api/providers' keyList carries spend, and
  POST provider/keyspendcap sets it.
- CLI: magpie provider spend-cap <id> [key [usd [day|month|total]|off]]
  lists each key's spend and sets or removes a cap.
- docs: providers-accounts.md and gateway-routing.md.

Caveats, also in the tooltips:
- What counts is magpie's priced usage, not OpenAI's bill.
- A model with no known price counts $0.
- Requests already under way when the cap is reached still finish, so
  a key can go a little past it.

Run on mote at the pre-rebase head (3e3196222 + this change):
- go test -count=1 -timeout 45m for internal/provider, usage, cli, gui
  and gateway: provider, usage and gateway ok. Three reds, none from
  this change:
  - cli TestEveryRouteHasACommandOrIsNamed: GET /api/context/reply,
    red on main, #5026.
  - gui TestMainWindowCorners/macOS_26_SDK: macOS 27, #3949.
  - gui TestCoreScriptBudget: from this change. Fixed by moving the
    pill into keyspend.js, then ok on a rerun.
- go vet: plain, GOOS=linux -tags nogui and GOOS=windows -tags nogui,
  all clean. gofmt -l is clean.
- GUI, both engines: key-spend-cap.test.cjs passed 20 of 20 before
  the keyspend.js move, and all of its tests passed again after it.
  It covers en, zh, zh-TW, ja and de at 900 and 400px, a refused
  amount, the set, change and remove posts, and checks for no native
  select, no border stripe and no sideways scroll.
- Also run in both engines: i18n-keys, old-webkit, lane-limit,
  account-cap, key-row-chips-fit, key-weight-fit, key-nourl,
  provider-many-keys, key-switch, key-plan and key-rest-date.
  - key-replace's webkit 420px is red at base 3e3196222 too
    (#4126; base failed 2 of 3 en runs, this change 3 of 3).
  - key-rest-date's webkit zh-TW, ja and de tests time out at
    --test-concurrency=4 with three other files beside it, at base
    too (base 5 reds, this change 7). Run alone at concurrency 2, it
    passes 10 of 10 at base and with this change (#4691).

After the rebase onto 9c51f7fdb, at the pushed head:
- go build ./... and go vet on the five packages: clean.
- go test of the spend tests, TestCoreScriptBudget and the gui
  package's word tests: ok.
- i18n-keys and key-spend-cap in both engines: 24 of 24.

Broken by hand, each red and then restored:
- spentNew taken out of Append: TestKeySpentCountsTheKeysCalls red
  ("after a new call key a spent 3, want 7").
- spendHeld never barring: TestKeySpendCapPassesTheKeyOver red (the
  capped key reached the upstream).
- capHeldOnly keeping spend holds: TestKeySpendCapPassesTheKeyOver red
  (Stop at the caps answered 429 instead of using the fallback).

Not tried:
- a real OpenAI key or real spend;
- the real app window;
- Windows and Linux test runs (vet only);
- the whole GUI suite: mote was running two other sessions' full GUI
  suites at load 250 to 400.
2026-11-03 15:30:44 +08:00
yetoneandggbdpq 4bac5eed26 usage: a request's row says what went up to the vendor, tries summed (#4456)
RunMintOn asked how much a long session sends upstream: a proxy counted
~900 MB up in 45 minutes, and no ledger row said what a request sent.

A row now has up_bytes, the bytes that went on the wire, every try and
every second ask summed (zstd's size for a ChatGPT turn), and
plain_bytes, the last try's body before compression. They are summed
in the request's context on its own goroutine, set in serve and, for
Codex's own turns that come from the mux and not through serve, in
codexUpstreamOn. Handed-on rows carry neither; rows from before carry
neither.

From ggbdpq's patch (via gua2100), two changes:
- the patch counted in codexUpstreamOn but set the context only in
  serve, so a Codex turn on its ChatGPT sign-in, the zstd case the
  issue is about, wrote 0 and 0 (TestCodexOwnTurnKeepsUpBytes);
- a second request inside one try (RetryOneAuth, RetryZhipuCoding,
  RetryOpenCodeFreeOnZen) went up uncounted; it counts now
  (TestLedgerCountsATrysSecondAsk).
Request bodies to other vendors stay as their client sent them; zstd
stays Codex's (the owner's call, on the issue).

Run at this tree on mote: go test ./internal/gateway -run
'UpBytes|TrysSecondAsk|OneAuth|Codex|Draw|Relay' -count=1: ok;
go test ./internal/usage ./internal/redact -count=1: ok. gofmt clean.
Broken by hand: no context in serve: TestLedgerKeepsUpBytes and
TestLedgerCountsATrysSecondAsk red; none in codexUpstreamOn:
TestCodexOwnTurnKeepsUpBytes red (row 0/0, backend got 79 of 8444);
the second ask not counted: TestLedgerCountsATrysSecondAsk red.
Not tried: a real session's numbers against a proxy's; the GUI shows
neither field yet.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-03 05:08:39 +08:00
yetone 344a59f9db gui: an unchanged Sessions poll answers Same without making the rows
The Sessions tab asks for every session each 15 s. When nothing had
changed, the handler still copied the kept listing, made a row of each
session, merged the gateway's sessions, read Codex's effort and the
vias, encoded every row and hashed them, only to answer X-Magpie-Same.
Over ~17k real sessions (69 GB of Claude Code and Codex history) that
was ~140 ms of CPU and ~24 MB of garbage per poll.

Now the handler keeps, per ?limit, what the last list it sent was made
from: the sessions listing (sessions.ListUnless's number, which changes
whenever the listing is made again, and at least once a minute), the
usage log's version (usage.LogVersion), the user's usage aliases, and
the agents' names and icons with the folders. An ask whose
X-Magpie-Had is that list's tag, while all of these stand, gets
X-Magpie-Same before any row is made or the listing copied. Anything
else a row shows (a Codex thread's effort, a gateway title) follows
within the minute the kept listing stands. writeJSONRows returns the
tag it sent.

Measured on the real history (a sandbox HOME with APFS clones of
~/.claude/projects and ~/.codex/sessions, 17,140 files), 30 polls of
/api/sessions + stats + overview, the same script for both builds:
  before (d614f2172): 4.19 s CPU, /api/sessions median 64 ms, 711 MB
    allocated
  after:              2.67 s CPU, median 47 ms, 298 MB allocated
What is left is the listing's own look at every file (getattrlistbulk,
~43% of the samples) and its GC.

Tests: TestSessionsSameWithoutRows: an unchanged poll is Same without
rows, and a gateway call, an alias and a new session file each make the
rows again. Broken by hand on mote: never taking the shortcut fails it
("rows made 1 times"), and leaving the log version out of the key fails
it ("after a gateway call: same true"). go vet and go test of
internal/gui, internal/sessions and internal/usage on mote (macOS):
sessions and usage ok; gui's reds were TestMainWindowCorners (red on
origin/main b646a9127 too, #3949) and the BusyLoad guard (#4739, fixed
by b646a9127; passes after the rebase onto 403323af7). GOOS=linux go
vet of sessions and usage, GOOS=windows of all three.

Not run: the full ./... suite, a Linux vet of internal/gui (cgo), the GUI suite (the page's api() and its
X-Magpie-Had handling are unchanged), Windows and Linux.
2026-11-01 15:27:49 +08:00
yetone 9551fadcb4 gateway: reasoning streamed with no count in its usage is marked unknown, not read as none (#4545)
A reply whose stream carried reasoning (reasoning_content, Anthropic
thinking deltas) while its usage counted no reasoning tokens was
recorded Reasoning 0, ReasoningHidden false: the same record as a reply
that never reasoned, and a tool-only one was timed with its reasoning
counted as answer. hidesReasoning now takes the usage's reasoning count
and marks such a reply ReasoningHidden, the record's existing "the
stream doesn't tell how much it reasoned". Reasoning stays the vendor's
0; nothing is estimated, so no new field or Flags bit (rowReasoningHidden
512 is the one it already uses).

Who does this, from real bytes and docs: Anthropic's Messages usage has
no thinking count at all (output_tokens includes it), so every visible
Anthropic-protocol thinking reply was this case. The fixture
testdata/reasoning-uncounted-deepseek-anthropic.sse is DeepSeek's
Anthropic endpoint as it came on 2026-10-31 (deepseek-v4-pro, thinking
on): 33 thinking deltas, "391", usage output_tokens 35 and nothing else.
The owner's usage.jsonl has 12 kiro claude-haiku-4.5 rows with paced
first_reasoning_ms and reasoning 0, the same case through a plugin.
DeepSeek's Chat endpoint does count (completion_tokens_details), and
those rows are unchanged. No captured Chat vendor omits the count; the
Chat subtests are built from the shape, not a capture.

Siblings: Responses, Gemini and Code Assist were already marked hidden
whenever reasoning streamed (summaries). The Codex backend's two calls
pass its count too (no change for Responses; its call record now reads
the count after the sniffed usage is added). The Claude subscription
bridge counts thinking from the CLI and is unchanged.

What changes for a reader: Decode already leaves a hidden reply with no
text untimed, so a thinking + tool-call reply with no count tells no
speed now; one with text is timed as before (whole output from first
content). The GUI's decodeOf/ledDecode read the same flag; no GUI code
changed.

Run on mote at base d0a61b856, then again after rebasing onto
origin/main f1d0c0bfd (gateway and usage packages, gofmt, vet). Pushed on 5174c0970,
which changes only GUI files after that run:
- go test -tags nogui -timeout 45m -count=1 ./internal/gateway/...
  ./internal/usage/...: ok gateway 612s, ok usage 41s; at the
  rebased tree ok gateway 593s, ok usage 42s
- TestStreamedReasoningWithoutCount with the counted check taken out of
  hidesReasoning by hand: red in 4 of 6 subtests (anthropic, chat from
  anthropic, chat tool uncounted, anthropic from chat tool uncounted);
  green restored. "responses from anthropic" was already hidden on the
  old code (the translated Responses stream carries encrypted_content).
- gofmt -l internal/gateway internal/usage: clean; go vet for darwin,
  GOOS=linux and GOOS=windows on both packages: ok.
- node --test reasoning-speed.test.cjs usage-speed-every-row.test.cjs
  (Chromium and WebKit, five languages) on the Linux VM (wsl-run): 16
  pass, 0 fail. On mote the same run had 8 TimeoutErrors at load ~25,
  beside four other sessions' whole GUI suites running 18 to 30 hours;
  no GUI code changes here.

Not tried: a real Claude API key (Anthropic's own endpoint) and Zhipu,
vLLM or Ollama Chat streams; no full go test ./...; no Windows or Linux
run of the tests.
2026-10-31 17:46:51 +08:00
yetone 2eac916170 gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue
xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.

A gateway key can now expire (Key.Expires) and can be issued under
another key (Key.Issuer). It lives from 1m to 30d. It can be held to a
set of models, a set of accounts, tokens or cost over its whole life
(one "hours" limit as long as its life), and read-only.

- POST /v1/magpie/keys {"ttl":"1h"|3600, name, models, accounts, tokens,
  cost, readOnly} answers 201 with the secret once, no-store. GET lists
  the caller's keys, masked. DELETE /v1/magpie/keys/{id} revokes one.
- magpie gateway-key issue --ttl 1h [--name] [--models] [--accounts]
  [--tokens] [--cost] [--read-only] [--from <id>] [--json] prints the key
  alone. gateway-key issuer <id> on|off lets a key issue keys. list shows
  until/expired/issued by.

Who may issue:
- a key the user let issue (Issues), from wherever that key is let in,
  so a container or CI can;
- with no key, a request that profileRefused passes: loopback, no
  forwarding header, no Origin/Sec-Fetch/Mozilla marks, a loopback Host.
  Such a request can already use every model with no key and run the CLI,
  so it gains nothing.
Never: a page, another computer without such a key, a key not let issue,
an issued or expiring key, or a read-only key (readOnlyGuard).

An issued key never outlives or exceeds its issuer. IssueKey clamps its
expiry and refuses models and accounts the issuer can't use. On every
authentication (access.Check, under Authenticate and On), identityOf
folds the key into its issuer as the issuer is now: models, accounts,
read-only, quotas and expiry. An issuer that is off, removed or expired
refuses its keys. Spend counts against the issuer too: the new usage
field callerIssuerId, budget.read/Append counting both keys, and Reserve
reserving on both. /v1/magpie/limit answers expires and issuerLimits.

An expired or refused key gets 401 with why ("… expired at …: ask for a
new one") on every route, from loopback too. Otherwise a held sandbox
whose key ran out would be let in as no key. Expired keys are pruned
after an hour (every 10 minutes while serving, and on each issue).
rowText packs CallerIssuerID: without it, usage.Visit returned the field
empty and the issuer's limit counted none of its keys' calls.

Docs: gateway-routing.md has "Short-lived gateway keys" and the
/v1/magpie stats API table. site/public/docs remote has "Short-lived
keys" and "Stats API" in en, zh and ja. GitHub OIDC is filed as #4531.

Run at base 07a3312c5 (origin/main, fetched just before):
- mote: go test -count=1 -timeout 45m on access, budget, gwbudget,
  usage, cli, gateway, davsync, agent: ok.
- mote: internal/gui fails TestCoreScriptBudget (#4526),
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and ten AppKit window
  tests killed at their deadline (#4125, #2645). The first three fail the
  same at origin/main 07a3312c5 on mote. This change touches no GUI file.
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; node --test site/*.test.mjs (49
  pass).
- win-run: access and budget ok. usage fails TestDesktopSessionAccountMetadata
  the same at origin/main (#1356). cli's TestLibraryMCPHub failed once on
  TempDir cleanup (#4140) and passed alone.
- Real binary on mote, sandbox HOME, port 47811: issued a 1m key with
  curl, read its limit, listed it, saw `gateway-key list` show "until",
  had a page's Origin refused 403, and after 62s /v1/models answered 401
  "the gateway key "sandbox-1" expired at …".

Broken by hand, each restored:
- no expiry check in Check: TestIssuedKeyExpires and
  TestIssuedKeyExpiresOnEveryRoute go red.
- no 401 for a refused key on loopback: TestIssuedKeyExpiresOnEveryRoute
  goes red (the expired key let in as no key).
- budget not counting CallerIssuerID: TestIssuedKeysSpendTheirIssuersLimit
  goes red (5 calls reached the upstream).

Not tried: a Responses WebSocket open across the expiry. The GUI shows
no expiry or issuer yet (issued keys look like plain keys until pruned).
A held issuer's /v1/magpie/usage shows its own rows, not its keys'. The
refused-key 401 doesn't count toward tooManyAuthFails. Issued keys sync
through davsync like other keys, with their expiry.
2026-10-31 13:44:29 +08:00
yetone 6d154ef1e1 context: scripts (curl, Bun, python-httpx…) are one Scripts card, not an agent each
A request whose User-Agent names only an HTTP library or an SDK (curl,
Bun, node-fetch, undici, python-httpx, requests, aiohttp, Go-http-client,
okhttp, the OpenAI/Anthropic SDKs, …) or nothing at all got a Context
scorecard of its own, as if it were an agent (theforeveriris on X: "Bun",
"curl", "python-httpx" cards). usage.IsLibrary names those clients;
contextOfRecs folds them and "other" into one "Scripts" card at read
time, so older history reads the same way, and the card's meta line and
tooltip list the libraries by count. The cached day records are not
changed. No setting: it works as is. The Usage page's Agents list still
shows each library by name, with its Hide and Count-as-agent controls.
i18n for zh, zh-TW, ja, de. Existing context.js comments were condensed
so TestCoreScriptBudget holds without a raise (core scripts -28 bytes).

Run, at this head (rebased on 40af66027):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  (mote) for usage and gui; earlier the whole tree on all three, exit 0.
- mote: go test -count=1 -tags nogui -timeout 45m ./internal/usage
  ./internal/gui: ok, ok.
- Windows box: context-scripts + i18n-keys 26/26 (chromium, webkit,
  5 languages, 360 and 1100px). Before the rebase, every reachable file
  (context-*, compact-one-value, group-context, routing-context-fold,
  routing-ctx-fold, routing-ctx-still, i18n-keys, gui-de/ja/zh-tw,
  header-relang): 333/349; the 16 reds are routing-ctx-still, red the
  same on origin/main 40af66027 on that box, listed in #4124.
Broken by hand: IsLibrary false and no fold -> TestIsLibrary and
TestContextScriptsAreOneCard red (cards python-httpx, claude, Bun, ...);
the JS label/clients removed -> context-scripts.test.cjs 0/22.
Not tried: a real app run with real curl/Bun traffic; Linux WebKitGTK;
GUI files on mote (its browsers were busy with another suite).
2026-10-30 16:05:58 +08:00
yetone 643b525469 usage: a DeepSeek call at peak hours costs double its off-peak list price
treeMan on Discord: DeepSeek bills off-peak at half the peak rate, and the
Usage page didn't follow it. The catalog's list prices for these models
are already the off-peak ones: models.dev's DeepSeek, Command Code and
OpenCode Go entries give the off-peak rate as the price and a factor-2
multiplier for peak hours, and api.json leaves the multiplier out
(deepseek-flash: $0.15/$0.60/$0.003, DeepSeek's page says $0.30/$1.20/
$0.006 at peak). So every peak call was counted at half its cost. Now a
call made from 01:00 to 04:00 or 06:00 to 10:00 UTC, Monday to Friday,
costs twice the list price. The call's own timestamp decides.

Which providers (provider.PeakOf, by base URL, or by preset/id only for a
provider with no URL, such as a plugin's or a removed one):
- DeepSeek's API (api.deepseek.com), every model, except on Chinese
  public holidays (catalog.PeakDeepSeek);
- Command Code (api.commandcode.ai, the commandcode preset and the
  commandcode-plan plugin): deepseek-v4.1-flash, -v4.1-flash-fast,
  -v4-flash, -v4-flash-vision-exp and -v4-pro, every weekday, since its
  docs name no holiday. deepseek-v4-flash-fast is one price at every hour;
- OpenCode Go (opencode.ai/zen/go): deepseek-v4.1-flash and
  deepseek-v4-pro, every weekday.
Unchanged: OpenCode Zen (a flat $0.30/$1.20), ZenMux, Cline Pass,
OrcaRouter and every other relay, a price the user set (ModelPrices
returns before a Peak is set), a "same as" price and every other model.
The provider's price rate still applies.

Holidays: catalog.cnHolidays has 2026 from the State Council's notice
(2025-11-04). TestCNHolidaysCoverThisYear fails on 2027-01-01 unless that
year's notice, due in November, is added. A year missing from the table
counts no holidays.

Where the hour is applied (catalog.Price.In): Record.CostAt (Usage's
totals and groups), the packed gateway blocks (priceBlock), OTLP's
exported cost and budget's estimate (now). The Sessions page sums per
model without per-call times and stays at the list price. The model
editor's price box says when a list price counts double (four languages;
app.js kept under its budget by shortening, not by a raise).

Run at the tree pushed (parent 32f5c3369), on mote:
- gofmt -l clean
- go vet on the six packages
- go test of catalog, usage and otlp whole, and provider and gui -run
  Peak|PriceIn|CNHolidays|Price|TestCoreScriptBudget, with TZ=UTC and
  with TZ=Asia/Shanghai: all ok
At 76b18f68d (the same change before the last two rebases), on mote:
- go vet ./internal/..., GOOS=linux -tags nogui and GOOS=windows vet of
  ./..., and the darwin, linux nogui and windows builds: ok
- catalog, provider, usage and otlp whole, in both zones: ok
- internal/gui: TestCoreScriptBudget was red (app.js 108 bytes over),
  fixed by shortening the hint. Ten AppKit window tests were killed at
  their 30s bar at load ~130 (TestDockJoinLeadsCommandTab,
  TestMainWindowCorners and others); this change doesn't touch them.
GUI:
- model-price-edit (now checks both peak hints and none on a plain list
  price), model-price-tiers, provider-price-rate and i18n-keys: Chromium
  ok on mote.
- WebKit on mote couldn't launch at all (browserType.launch timed out at
  180s, 69 WebKit processes from other runs), so the three price files ran
  in WebKit on Linux (wsl-run): 8 of 8 ok.
- The whole GUI suite (both engines) at ff23724f3 was still running at
  load 110 to 150 when this was pushed, 119 red of ~7200. Every file
  checked so far is a timeout under load or in #4304 / #3476.
  model-chip-steady is red the same way on origin/main 0911a65e7.

Broken by hand, each red:
- CostAt without .In(r.Time): TestCostAtTheCallsHour (0.753 at peak,
  want 1.506)
- priceBlock without .In(p.Time): its block half
- Peak.At ignoring holidays: TestPeakHours on 2026-10-05
- priceOf never setting Peak: TestPriceOfPeak
- OpenCode Go's model list dropped: TestPeakOf (kimi-k3 "weekdays")

Not tried: a real call to DeepSeek, Command Code or OpenCode Go at peak
and off-peak to compare against their bills; a full go test ./...; the
holiday rule's handling of the swapped working weekends (DeepSeek says
Monday to Friday, so a worked Saturday stays off-peak here); ZenMux,
whose own docs give no schedule.
2026-10-30 15:22:55 +08:00
yetone 442897f414 gateway: masking time is kept when magpie's own time is unknown
A masked request's "Masking" part on the Routing page comes from
Route.Masking, which maskingMs capped at Own, magpie's own time before
the request went out. Own is known only when magpie's client wrote the
request and a first token came back, so a request that was masked but
went through a plugin, through Claude Code for a Claude subscription,
failed, or had no first token had its masking time dropped to 0, and
the page showed nothing for it (Discord, lute: some requests show the
masking and model time and some don't). The Codex backend path never
set it at all.

maskingMs now keeps all of the masking time when Own is unknown, and
still caps it at Own when Own is known. The Codex backend path sets it
on its route and its usage record. The usage page still shows Masking
only beside a known Own, as before.

Run (mote, go1.26.8):
- TestMaskingTimeKeptWhenOwnIsUnknown (a masked request the vendor
  refuses): red on the old redact_phase.go ("masking 0 ms, held
  120ms"), green with it.
- TestCodexOwnSignInKeepsItsMaskingTime: red without the codex
  backend lines ("route's masking 0 ms, held 120ms"), green with them.
- TestMaskingIsAPhaseWithItsTime, TestNoMaskingNoMaskingTime: ok.
- go test ./internal/gateway ./internal/usage -count=1 -timeout 45m with
  this and the next commit: ok (gateway 502s, usage 16s).
- go vet ./internal/gateway ./internal/usage for darwin, linux
  (-tags nogui), windows: ok. gofmt -l: clean.
2026-10-30 01:54:40 +08:00
yetone 2be04305fd usage: a session's model lists count only the log's blocks since the last
The whole log's model lists (cachedVias) were counted again from every
call in the log whenever it grew, which with calls coming in is every
poll: buildVias was ~3% of CPU on the #2278 bench. They are now counted
on from what the log's full blocks counted, which never change, and only
the blocks after are counted again. A session's counts are copied from
the prefix before they are added to, so the prefix is never written.
Rows are counted in the log's order either way.

The prefix is kept for the same clients and renames key as the lists,
and is dropped when the log is read afresh (its blocks differ). Window
lists (a since) are built as before.

TestViasCountedOnAreCountedAfresh DeepEquals the lists counted on with
buildVias afresh, after appends over a block's edge, a new session and
model, and the log written over, and checks that lists were counted on.
Broken by hand (a prefix session's list cut in half): red at "first".

Run at the next commit's tree (this one plus the gateway projection's
fold, in other files): go test ./internal/usage/... ./internal/usageapi/...
./internal/tui/... ok; ./internal/gui/ red only on TestMainWindowCorners
(#3949); GOOS=linux,windows,darwin go vet -tags nogui ./internal/usage/...
./internal/gui/ ok. Bench numbers are in the next commit.

Refs #2278
2026-10-29 06:21:46 +08:00
yetone 28c89afcef usage: a period's summary counts only the log's blocks since the last
Each call the gateway logged changed the log's version, and every
/api/usage ask for Week or Month counted the whole period again: on
the #2278 bench (a busy gateway, 4 calls a second, the GUI's polls every
5 s) topSummary was 11% of CPU, beside GC at ~30%.

A period's summary now keeps what it counted over the log's full blocks
(512 rows each, never written again once full) and counts only the
blocks since, then the last block. It counts afresh when anything a
count depends on changed: a block it counted was replaced, a rewrite,
prices or names (meta), cleared calls, the period's bounds or series, or
the keying (hosts, accounts, keyed providers) changed. In the last case
an account that newly answers for a provider splits that provider's
earlier calls too. Rows are counted in the same order as before, so
every float comes out bit-identical. The group maps are copy-on-write
over the kept prefix, and only what was touched is copied.

Run at this tree, 213a31b4d before this message (the parent is origin/main 7795f5573, no rebase):
- New TestSummaryCountedOnIsCountedAfresh. Over 3*512+100 rows, for
  Today, Week, Month and All, it DeepEquals the folded summary against
  summarizeFrom: after appends across a block edge, a new host, an
  account newly answering for openai, another block, and a log written
  over. It also checks that at least one summary per period was counted
  on from a prefix.
- Broken by hand twice. With the keying check skipped, red at "an
  account". With one block left uncounted, red at "first". Restored
  after each.
- On mote: go test ./internal/usage ./internal/usageapi ./internal/tui
  all ok (usage 17.2s); GOOS=linux/windows/darwin go vet -tags nogui
  ok; gofmt clean. Before the last comment-only edit: go test
  ./internal/gui is red only on TestMainWindowCorners/macOS_26_SDK,
  the known #3949 on mote's macOS 27.
- A/B on mote, v0.1.1963 against this, 240 s each, under the same
  polls and feed, with another session's GUI suite also running (load
  ~35):
  - topSummary: 3.24 s to 0.93 s of a 60 s CPU profile.
  - Polls, mean seconds:
    - /api/usage?period=7d: 0.16 to 0.13
    - /api/usage?period=30d: 0.27 to 0.14
    - all polls: 0.65 to 0.63
  - Steady RSS after 130 s: 892 to 920 MiB.
  - The cold-start peak at 30 s, before any calls were fed: 1000 to
    1219 MiB (ps); footprint peak 755 to 781 MB. The cold-start peak
    swings between runs; the RSS peak is the next work.

Not tried: rolling windows ("last:") and picked ranges are still
counted afresh on every ask, as before.

Refs #2278
2026-10-29 06:04:22 +08:00
yetone 012c584cc1 usage: clear a model's usage, or all of it, from the Usage page
CrazyMouse_TT on X asked for a way to clear usage, all of it or one
model's, to measure a local model fresh after deploying it.

The Usage page's Models list has a "…" on each row (and a right-click
menu) with "Clear usage…", and "Clear all usage…" sits under the lists
below the "Counted from…" note. Each asks first, in a confirmation that
says what is deleted, that it can't be undone, and that key spending
limits and allowances still count the calls.

A clear is a mark in settings (usageCleared: provider, model, unix ms),
read at read time; usage.jsonl is never rewritten. The Overview hides
calls up to the mark in summarizeFrom; the Requests page, heatmap and
ledger/CSV hide them in Filter.keepsRow, their one choke point, and the
request index's meta carries the marks so its cache is dropped. Key
budgets, window holds and Codex reads go through usage.Visit and the raw
log, so a clear never resets a key's spending limit or a quota. A later
clear of the same model or of everything takes the place of an earlier
one. The marks ride the settings part of a sync (sync-backup.md) and a
save of the Settings page keeps them (api.go's keep list; the guard
test TestSettingsSaveKeepsWhatItDoesNotSend caught it missing).
gateway-sessions.md and sync-backup.md say so.

Run on mote (mote-run) at this tree, rebased on origin/main c26b2992e
(the Go packages and usage-clear.test.cjs; vet and the 68 GUI files
ran at the earlier base f835bd713, four commits behind):
- go test -tags nogui -timeout 45m ./internal/usage ./internal/settings
  ./internal/usageapi ./internal/gui: all ok after the
  keep-list fix (before it, TestSettingsSaveKeepsWhatItDoesNotSend red).
- gofmt -l: clean. GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: exit 0. (Linux vet without nogui fails in
  wails' cgo, as on main.)
- usage-clear.test.cjs: 32/32 in Chromium and WebKit, en/zh/zh-TW/ja/de,
  at 1200, 560 and 390 (web). With the old page.js/client.js/i18n.js it
  fails (TimeoutError).
- 68 GUI files the change can reach (every usage-*, gui-de/ja/zh-tw,
  i18n-keys, click-scroll, idle-ticks, mobile-web, panel-usage,
  sessions-purge): 941/980. The reds are filed and red on main
  (usage-ledger run alone at origin/main 84a6a2c42 too): i18n-keys "masking…" (#4053), mobile-web
  (#3952), usage-agents-hide (#2276, #3414), usage-ledger "newest live
  route needs no return-to-live button" (#3104, run alone at main too).
  i18n-keys first also named "Clear usage…" in Go comments of this
  change; reworded.
Broken by hand, each red: hides() always false (usage and gui tests),
keepsRow's clear check removed ("Requests after the clear: 5 rows"),
clearedKey out of the request meta ("after clearing everything: 3"),
the api.go keep line removed (UsageCleared [] after a save).

Not tried: the full go ./... suite and the whole GUI suite (mote was
busy with other sessions' full suites), the real app, a sync between
two computers. usage.jsonl doesn't shrink, and the Sessions tab's
figures are not cleared.
2026-10-28 21:13:09 +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 28f3c4d7fd codex: the Codex app's first 100 models hold the ones used, hidden ones last
@ZhenLuoTTAWDTT on X: with Codex on magpie the model list stops short,
and the models past it can't be chosen.

Cause, from the clients' own code: the Codex app (ChatGPT.app
26.1013.40934, app-initial-90eb42395b7d.js) and the VS Code extension
(openai.chatgpt 26.51021.22027, model-queries-667cf4bd657d.js) both ask
their app-server for model/list with includeHidden, cursor null and
limit 100 (e?.limit??100) and never ask for nextCursor. codex-rs's
list_models pages the list sorted by priority, hidden entries counted,
so anything past the 100th is in no picker there. The CLI's /model
(tui model_popups.rs) lists every preset in a scrolling popup and has no
cap. magpie truncated nothing; its models are numbered after the
account's own, so a user with many models lost everything past ~100 in
the app, while hidden entries (codex-auto-review and the like) took
slots at the top.

Fix: codexcat.Fit ranks the list last of all, on every route magpie
hands Codex a list (/backend-api/codex/models after the user's own
order, /v1/codex/models before its 1 MiB cut, and the
model_catalog_json file via CatalogUsed): hidden entries go after every
listed one, and with more than 100 listed, the models Codex used in the
last 30 days (usage.CodexUsed, most recent first, at most 100; on
/v1/codex/models only the asking key's, CodexUsedBy) are brought into
the first 100 in the order they stood. The rest keep their order. The
list's ETag and X-Models-Etag carry a tag of the used set
(codexcat.UsedTag), so Codex asks again when it uses a model it hadn't;
CodexUsed is read at most once a minute, or at once when Append writes a
Codex call to a model it doesn't hold. Documented in
docs/subsystems/gateway-routing.md.

Tests (each red on the old code, broken by hand: Fit a no-op, the gateway
calls and the used tag removed, Append's codexUsedNew removed):
TestFitKeepsUsedModelsWhereTheCodexAppReads, TestFitLeavesAShortListsOrder,
TestCatalogUsedFits, TestUsedTagIsTheSet (codexcat), TestCodexUsed
(usage), TestCodexModelListKeepsUsedModelsInTheAppsHundred and
TestCodexCatalogKeepsTheKeysUsedModelsFirst (gateway).

Real run: codex-cli 0.162.1's app-server in a sandbox CODEX_HOME (never
~/.codex) with a model_catalog_json of 3 hidden entries at priority 1-3
and 150 listed models, driven over stdio with the app's own request
(model/list includeHidden, limit 100). Before: page 1 held 100 of 153,
3 of them hidden, the last many/model-096, nextCursor "100". The same
catalog put through Fit with many/model-140 used: page 1 has no hidden
entry and ends with many/model-140. The TUI's /model scrolled to all
150 (tmux).

Run with this change on e4ca47b0f: gofmt -l clean; go vet
-tags nogui with GOOS=linux and GOOS=windows on codexcat, usage, gateway
and agent clean. go test -count=1 -timeout 45m: codexcat ok, usage ok;
-run 'Codex|Fit|Used|ModelList|Catalog' on gateway, usage and agent ok
(122s, 11s, 80s). The whole gateway and agent packages ran too, but the
machine's disk was full under other sessions' runs (209M to 2.5G free),
and 959 lines of that log are "no space left on device". Of the reds,
three are not that: TestFolderVarsAreListed is #3884 (CARGO_HOME, red on
main since e4552cca9); TestHistoryKeepsDaysAndDropsOld (gateway) and
TestSuffixModesReachAgentFiles (agent) failed beside half-written
settings files and pass alone 3 of 3 at this commit. Not run: the full
./... suite (no room on the disk); the Codex app and VS Code extension
themselves against a magpie with this change (their request was read
from their bundles and replayed against a real app-server).

Rebased on ca8a6f346 (agent rename and Codex app route, claude_runs in
gateway) and run again: GOOS=windows go vet on agent
and gateway clean; -run 'Codex|Fit|Used|ModelList|Catalog' ok on
codexcat, usage and gateway (75s), and with |Rename ok on agent (68s).
Then rebased on 94c2aaecb (usage rename) and usage run whole again: ok
(88s).
2026-10-27 18:37:16 +08:00
yetone 8fba65d0bc gateway: what masking took a request is kept, and shown as Masking in its time
fremontdango on Discord asked, after the request that sat as "routing…"
while it was masked, how long masking took. Now each request keeps it.

noteRedacting adds up the time from the first masking at once to the
last's end (redaction.spent); maskingMs gives it in ms, at least 1 when
there was any, never more than Own, magpie's own time before the request
went out (splitSent), since masking happens inside it. It goes on the
route (Route.Masking, /api/gateway/trace) and in the usage record
(Record.Masking, masking_ms; packedRow's int32 fits in its padding, so
TestRowsOfOneSessionShareAShape's 216 bytes are unchanged, and the
process-private snapshot carries it). It is a duration, no text.

The Routing page shows it as magpie's "Masking" part, first in where the
first try's time went (timeParts, renderSteps); the Usage page's detail
splits it out of "In magpie" (page.js). Both use the core "Masking"
string every language already has (脱敏, 脫敏, マスク, Maskierung).

Why masking can be slow, measured on this machine (go1.27, M-series):
the rules are linear, ~0.25 ms/KB. redact.MaskJSON over a Claude Code
shaped body: 283 KB 35 ms (secrets) / 63 ms (+ personal data); 511 KB
70 / 122 ms; a dense 402 KB with 7,821 hits 173 ms with personal data,
144 ms with the user's words too. Through the gateway (redactedHits,
secrets + personal, 402 KB dense) 145 ms the first time, 123 ms again;
noteMasked ~2.6 ms. Doubling the body doubles the time; nothing
quadratic or repeated per hit. So a request held "routing…" for 15 s or
more (unroutedShow) while masked is the local model (Settings → Privacy
→ Find with a local model, internal/pii): it reads each text it hasn't
seen (a new turn's tool results are the misses), one model turn at a
time, so requests queue behind each other (#3682: 480 KB took 90 s on an
RX 470/580). No change to masking's speed here; the phase and the time
now say which it was.

Run at this head, on origin/main 9ae791221 (Go, M-series macOS):
- go test -timeout 45m ./internal/gateway ./internal/gui ./internal/redact
  ./internal/usage: ok (gateway 425s, gui 99s); ./internal/masking and
  ./internal/pii ok at the pre-rebase head 3a4a13d04
- gofmt -l internal: clean; go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean; go build: ok
- go test -race -count=3 TestMaskingIsAPhaseWithItsTime,
  TestNoMaskingNoMaskingTime: ok
- GUI, chromium and webkit: routing-masking (every language) 10/10,
  usage-ledger-detail 6/6, i18n-keys and routing-levels green. The whole
  routing-*, panel-routing*, usage-ledger* and i18n-keys set: 1,824
  tests, 96 red at load ~47, in 15 files. The first run's i18n-keys red
  was this change's (a Go comment quoting the core word), fixed in the
  commit before. The other 14 files, rerun two at a time at this head
  and at origin/main 9ae791221: the same files red on both (89 here, 86
  there; routing-rule-remove alone 5 red here, 7 on main). Each has an
  issue: #2115, #3410, #3411, #1905, #3593, #3408, #3096, #3094, #3001,
  #3104, #3786.

Broken by hand, each red: spent not added (route and record Masking 0),
no t.Masking on the route, no Masking in the usage record, the snapshot's
put/take of Masking (TestRowsOfOneSessionShareAShape), timeParts without
Masking or renderSteps without the first try's masking
(routing-masking), the Usage page without the Masking line
(usage-ledger-detail, 3 red).

Not tried: a real local model (Settings → Privacy → Find with a local
model) on the reporter's Windows box or any GPU, so a long masking was
only held by a fake masker; the Codex backend's usage record has no
Masking yet; the Windows test box wasn't used.

Reported by fremontdango on Discord.
2026-10-27 08:08:23 +08:00
yetone 39526c0690 usage: Append keeps the log open between calls, not an open and a close for each request (#3725)
Every request the gateway serves appends a line to usage.jsonl, and
Append opened and closed the file each time. In a CPU profile of the
request path (BenchmarkZZIO, a local benchmark not committed) Append was
0.51s of the handler's 1.36s, 0.35s of it in os.OpenFile and 0.07s in
Close.

Now the handle is held, under the same mu. Before each write the held
file's identity is checked against what Path names now (fstat and stat,
os.SameFile), so a log another program moves, removes or replaces, or a
Path that changes with HOME, is opened again. A failed write drops the
handle. Windows still closes after each write, since a file held open
there can't be removed or renamed.

Measured (local microbenchmark, open+fstat+write+fstat+close against a
held file with stat+fstat+write+fstat, 600-byte lines, 20000 runs, load
~80): 55 to 116µs per call before, 11 to 24µs held. On the whole
request (BenchmarkZZIO) the difference is inside the noise at this load,
so no request-time figure is claimed.

TestAppendHeldLogFollowsThePath appends twice and checks the second call
used the same handle (and that Windows holds none), then replaces the log
by rename, removes it, and moves HOME, checking each time that the next
call is counted in the file Path names. Broken by hand (identity check
skipped) it is red: after a replacement the call went to the old file and
Summarize counted 0 calls.

Windows box (test binary run outside the source tree): internal/usage,
mine and origin/main 92cf0b68d, both fail the same three tests:
TestDesktopSessionAccountMetadata (#1356), and TestKimiCodeCost and
TestRequestDiskNamesItsSource, which read testdata and source files that
aren't beside the binary there. TestUsageReadAfterAppendHashesNothingOnAFineClock
was red once in my first full run (#3511, the whole-second case); it
passed 30 of 30 alone with this change and in the next full run.

Run at this tree (fcbf618eb plus this change): gofmt -l internal/usage
clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage
ok; go test -count=1 -timeout 45m ./internal/usage ./internal/usageapi
./internal/gateway ok (16.161s, 6.655s, 448.476s).
2026-10-27 02:25:45 +08:00
yetone e1709ab42e usage: Append makes the log's folder only when it is missing (#3725)
Every request appends one line to usage.jsonl, and Append ran
os.MkdirAll on the folder first each time: a stat, and on its error
path a walk up the tree. Now the file is opened first, and the folder is
made (then the open tried again) only when that open says it doesn't
exist.

Measured with a scratch benchmark (not committed) at 1360689ef, Append into an
existing folder, -count 5: 3070 B and 25 allocs per call before, 2445 B
and 20 allocs after. Wall time is the write itself, ~45-60µs, and at
machine load ~160 the run-to-run noise was bigger than the saved stat,
so no time saving is claimed. A scratch test with XDG_CONFIG_HOME under
two missing folders checked the first Append still creates them and the
file.

Run at 1360689ef plus this change: gofmt -l clean; GOOS=linux and GOOS=windows
go vet -tags nogui ./internal/usage ok; go test -count=1 -timeout 45m
./internal/usage ok.
2026-10-27 01:58:09 +08:00
yetone 42976f9a08 usage: a renamed provider is shown once, by the id it has now
cybercaius on Discord (#help, 10-25): "已经更改供应商 id 的也没有变更过来反而
分开显示了". Reproduced in a sandbox HOME (magpie web on 3582, fake upstream
on 3583): after renaming myrelay to newrelay in the editor, the Requests
page's provider list had both myrelay and newrelay, each named "myrelay",
because the model-list probe row was still under myrelay. The summary was
already folded; the probe chunk, the Sessions tab's vias and the gateway's
loggedAnswers (lead-first routing) were not renamed at all.

What changed
- provider.Renames (UsageRenames): Of(id, time) is the id a call recorded
  under id at that time belongs to now. Every usage reader goes through it:
  summarizeFrom (and its historical-key set), ledgerMatched, NewPricer,
  NewCoster, the Requests page's gateway blocks, probe rows and other
  computers' days, window holds and their history, buildVias, and
  gateway loggedAnswers. Visit stays as recorded so Of is taken once.
  The summary, Requests and vias caches key on Renames.Key.
- An id reused by another provider no longer pulls the new one's calls
  into the old one. Rename onto, or Save of a new provider under, an id in
  another's Was moves it into that one's Gave with the time (giveID):
  calls before then stay the old provider's. freeID treats Was ids as
  taken, so adding the vendor again gets "-2". Renamed() (refs) skips ids
  a provider or subscription holds now.
- A providers.json that can't be read keeps the last renames read instead
  of none (a failed read is unknown), so usage doesn't split meanwhile.
- History: nothing in usage.jsonl is rewritten. Calls from before this
  release under a renamed id show under the new id at once. An id that was
  reused before this release has no hand-over time, so its calls show under
  whoever holds the id now, as before.

Siblings checked: budget keys by caller key; per-key limits, RPM and
concurrency count live requests by the current id; tray totals go through
QueryPage; codex_memory reads Requested refs. None needed a change.

Run at the tree before the rebase; rebased onto 894603bcd (GUI-only,
none of these files) and provider, usage, usageapi, the build and the
Rename/Answer/Lead tests of gateway and gui run again there: ok.
- TestRenamesByWhenTheIDWasTaken (provider), TestRenamedProviderShownOnce
  (usage), TestRenamedProviderAnsweredItsLead (gateway): each red with its
  piece broken by hand (Save's giveID, freeID's Was, the last-good renames,
  probe rename, vias rename, block pricer's timed path, summarize's time,
  loggedAnswers' rename), green with it.
- go test -timeout 45m provider usage usageapi budget middleware cli agent
  gui gateway sessions profile tui: all ok.
- gofmt -l, go vet ./internal/..., GOOS=linux/windows -tags nogui vet of
  provider/usage/gateway and build of the binary: clean.
- Sandbox: rebuilt binary on the same HOME; /api/usage/requests lists only
  newrelay, the probe row included.

Not tried: the GUI suite (no JS or asset changed; /api/providers gains an
omitempty "gave"), Windows tests run on the Windows box, a real account,
and the full ./... suite (other sessions' suites were running).
2026-10-25 10:53:45 +08:00
yetone ffe493773c usage: magpie's own Test, Detect APIs and model list requests are rows of the request log, counted nowhere
neiko and gys619 on Discord: a provider's Test or Detect APIs left no
trace in Usage > Requests, so a failing test couldn't be read back.

The provider package marks the context of the editor's Test, Detect APIs
(and per-model detection) and a model list's refresh with a kind
(internal/probelog). Each request sent under the mark is written once:
by the provider's Do, or by probelog.Transport under http.DefaultClient
(netproxy.Install), whichever sends it first; the Claude Code run and
the gateway's translated test write theirs from their result. A row
keeps time, provider, account, model, host, path (no query, no
user:password), method, status, ms and the first 500 bytes of the error.

The row is usage.SourceProbe, agent "magpie", Kind provider_test /
api_detect / model_list ("Test", "Detect APIs", "Model list" in Called
for; purposes.js regenerated). The log index keeps probes apart
(logSnapshot.probes), so Visit, Load, Summarize, budgets, Vias, heatmap,
shared days, LastSeen and observers never meet one. The request page
lists them (probeChunk) and counts none: Row.IsProbe, since a packed row
keeps the row's Source and not its record's. The page shows a muted
badge "magpie's own · not counted in any total" (en, zh, zh-TW, ja, de);
no new control, no layout change.

Tests, each red on the old code:
- usage TestProbeRowsListedNotCounted: listed, clipped, and absent from
  Sum, Through, every By group, Summarize, Load, LastSeen, OwnDays and
  the observer; a provider filter lists it and sums 0.
- provider TestTestWritesItsRequestsDown / TestDetectWritesItsRequestsDown:
  every request the fake server saw is exactly one row, with the right
  kind, model and 401 text; an unmarked Do writes nothing.
- probelog TestNoteKeepsNoSecret, TestTransportOnce.
- GUI usage-ledger-probe: badge per language, both engines, 1180/420,
  light and dark, no left border, no sideways scroll.
- gui TestProviderDetectDraft now expects the log line (source probe,
  kind api_detect, no key) and leaves usage.jsonl out of the unchanged
  config comparison.

Broken by hand, each went red: request_page's uncounted check,
log_index's probe skip, Append's observer skip, Do's Taken (6 rows for
4 requests), Test's and Detect's marks, probelog's query strip,
page.js's badge (11 GUI fails).

Run at this head (on origin/main 22a7f86c9): gofmt -l clean; go vet
./..., GOOS=linux -tags nogui and GOOS=windows clean; go test -count=1
usage, probelog, netproxy, usageapi, provider and gui packages ok (the
rebase over 22a7f86c9 applied cleanly; upstream's 8b460833e chunk
cache leaves probeChunk, built per query, alone).

Run one rebase earlier (on origin/main 0b72ccbef; request_page.go
merged by hand onto 7d67910f7/66b6d6ade's per-row Totals, with
uncounted rows skipping the caller and account groups too):
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, log tee'd:
  every package ok (gateway 640s, agent 514s, provider 278s, usage 77s)
  but internal/gui's TestRestartHandsTheGatewayOver (7 of 8 requests
  answered during the restart), 3 of 3 green alone after (#3451).
- gofmt -l clean; go vet ./..., GOOS=linux -tags nogui and GOOS=windows
  go vet ./... clean.
- GUI usage-ledger-probe, usage-ledger-reported, i18n-keys,
  purpose-filter, quota-pool-model: 72/72. usage-ledger's "newest live
  route needs no return-to-live button" is red on origin/main 0b72ccbef
  alone too (#3104).
- Whole GUI suite, both engines, at the pre-rebase base 761904b5a:
  1313 tests; reds, each also red on origin/main 7b1faf99f alone:
  account-discovery "agents' sign-ins read" (#3497), builtins
  "Plugins > Built-in" (Masking page in the list, #3518 filed), and
  context-map "two tiles overlap" chromium ja 420 (#3488; 1 of 2 red on
  main alone, 3 of 3 green on this branch alone). Earlier package run:
  TestRestartHandsTheGatewayOver red under load, passes alone (#3451).
- No size budget raised.

Not tried: no real vendor account (fake servers only); a plugin's model
list, fetched in the JS plugin host, isn't written down; the real GUI
app wasn't launched (Playwright only).
2026-10-25 04:12:06 +08:00
yetone 3a47e377e0 usage: a call whose vendor counts no cache is left out of every hit rate (#3464)
#3464 (zeewell on X): Kiro caches on its side, but its replies give only
credits and a context share, never cache tokens. Every hit rate outside
the Routing page read those calls' CacheRead of 0 as a miss. A Kiro-heavy
day showed "hit rate 6%" when the counted calls hit 90%.

The plugin already says so (opencode-kiro-auth 0.1.16 sends
usage.magpie_cache_unknown), and the gateway already kept it as
RouteUsage.CacheUnknown for Routing. This carries it the rest of the way:

- gateway: Usage.cacheNotCounted() (the vendor said so and no try
  reported a cache token) goes into usage.Record.CacheUnknown on every
  path that records a call: the gateway's own record, the OTel attempt
  path in observe.go, and trace's routeUsage.
- usage: Record.CacheUnknown is kept as ledger row flag 8192
  (rowCacheUnknown; grepped, no other flag uses that bit). Totals sums
  such calls' prompt into cache_unknown and counts them in
  cache_unknown_calls. Totals.HitRate leaves that prompt out of its
  denominator, and gives no rate when nothing is left.
- Old records: calls kept before the plugin said so carry no flag. A
  Kiro call (provider kiro or kiro-plugin) with no cache counted is read
  as uncounted (usage.CountsNoCache): in the ledger's row read, in
  Totals, and for Routing's history in internal/gui/trace.go
  (cacheCounted). The rule is scoped to Kiro's two ids, so another
  vendor's 0 stays a miss (tested).
- GUI: cacheHitOf in app.js drives the tray panel's card, the Usage
  page's agent rows and cache tile, the requests' Cache hit rate card and
  each ranking row. When only uncounted calls are left it shows "—" or
  nothing instead of 0%. Otherwise it says "{n} requests left out: their
  vendor doesn't count the cache". A request row's cache cells show "—",
  and its details say the vendor doesn't count the cache. The Context
  page (context.go, context.js) shows no cache for such a call and doesn't
  score it as a miss.
- No budget raised. This adds 625 bytes to app.js (1,320,224 to
  1,320,849, under its 1,321,336); d08b6118b had already moved the
  masking page's maskWho, maskProv and stillMotion out to
  plugins/redact, which an earlier version of this change did too.
- Strings in zh, zh-TW, ja and de. docs/subsystems/provider-plugins.md
  now describes the ledger side and what is not covered.

Not covered, filed: hit rates read from the agents' own session files
(the TUI and CLI session lists, the Sessions tab's totals) still count
Kiro's 0 as a miss (#3470). Found on the way: System One's calls are
recorded without their cache tokens (#3471).

Run at this tree (on origin/main e57e78563, fetched just before; the
54-file GUI run was at a84d2ec80, and the 14 files that main's
redact page change since could reach were run again here):
- gofmt -l . prints nothing. go build ./... ok. go vet ./... ok,
  GOOS=linux go vet -tags nogui ./... ok, GOOS=windows go vet ./... ok.
- go test -count=1 -timeout 45m ./internal/usage ./internal/gui
  ./internal/gateway: all ok (gateway 388s), TestCoreScriptBudget
  included.
- GUI, 54 files (ledger-*, panel-*, i18n-*, context-*, request*,
  usage-card*, usage-ledger and the masking/redact files),
  concurrency 2: WebKit 439/452, Chromium 444/457. The new
  ledger-cache-unknown test passed in both. Again here (ledger-*,
  masking-*, redact-*, mask-*, usage-ledger): WebKit 104/117,
  Chromium 109/122, the same reds. The reds, both already
  red alone on main before this change:
  - redact-words-any-case, 10/10 in each engine (#3500)
  - usage-ledger "newest live route needs no return-to-live button",
    en and zh in each engine (#3104)
- At earlier bases, with the same change: usage-agents-hide (#3414),
  usage-checkin's WebKit Qoder tab (#3091), usage-fold (#3415),
  usage-focus-steady (#3501) were red, each red alone on main too;
  usage-card-refresh read a row before it was laid out, under load
  (#3509); context-picks (#3483) and
  context-map's tile overlap (#3488) in Chromium. Filed while doing
  this: TestUsageReadAfterAppendHashesNothingOnAFineClock goes red
  about 1 in 20 on main aa3112f4e (#3511); it passed in this run.
- Red on the old code: the new Go tests in usage, gateway and gui, and
  ledger-cache-unknown.test.cjs (the old page shows "hit rate 6%"
  where this shows 90%). Each changed piece was broken by hand and
  turned a test red. The exception is the OTel attempt path in
  observe.go, which no test reaches.

Not tried: a real Kiro account through the GUI.
2026-10-25 01:23:42 +08:00
yetone ea9454d2d8 usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)
A vendor names one model two ways (deepseek-v4.1-flash and deepseek-flash),
and Usage, Usage > Sessions and `magpie usage` showed two rows. Now:

  magpie model alias deepseek-v4.1-flash deepseek-flash
  magpie model alias deepseek-v4.1-flash            (what it is counted as)
  magpie model alias deepseek-v4.1-flash --reset
  magpie model aliases

kept as settings.json "usageAliases" {from: to}. Off until one is written.
Ids match as routing groups match them (provider.sameModel: vendor/ prefix,
case, "_", snapshot date), at every provider; a chain is followed to its
end; an alias to itself, a loop, or a flag as an id is refused. A loop
written into the file by hand counts each model under its own id.

Display only: requests, agents' model lists, /v1/models, routing groups,
Same as and prices never read it. Each call is priced by the id it was
made under and only then counted under the alias; the alias's own price
is never put on the other id's calls, and a merged row is priced only
when every id in it is. Applied in usage summarize/direct (Models
groups), the gateway sessions projection (alias read before
gatewayCache's lock; the cache key hashes usageAliases), and
sessions.List/Get/Find/Stats (read before storeMu/mu, merged into new
slices so the memo is untouched; ModelEffort rows merged too). A failed
settings.json read keeps the last aliases read, and SetUsageAlias refuses
to write over an unreadable file (EditUsageAliases under fileMu). The GUI
settings save carries usageAliases. No GUI control.

Not aliased: the Requests ledger's per-request model and its model
filter, which show each call's own id.

Run (worktree at f4640c0ae, rebased onto 2b4c0664e with no overlap):
- gofmt -l: clean. go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- go test -count=1 -timeout 45m (sandbox HOME) internal/usage,
  sessions, provider, cli, settings, gui, tui: all ok.
- Real binary in a sandbox HOME: two usage.jsonl calls priced $2 and
  $100 per M: `magpie usage` showed two model rows ($2.00, $100), and
  after `magpie model alias` one row, 2.0M, 2 calls, $102; the session
  row too. alias/aliases/--reset/loop/self output checked by hand.

Broken by hand, each red then restored:
- no alias in summarizeFrom: TestUsageAlias* red
- nil alias into the gateway projection: TestUsageAlias* red
- statsIn without aliasStats / List without aliasSession:
  TestSessionsCountAliasedModelsAsOne red
- merged usage row keeps Priced true: TestAliasStatsLeavesItsInputAlone red
- loop check off / self check by == / last-good read off / flag check off:
  TestUsageAliasRefusesSelfAndLoops, TestUsageAliasUnreadSettings,
  TestModelAliasCmd red
- GUI save drops UsageAliases: TestSettingsSaveKeepsWhatItDoesNotSend red

Not tried: the GUI pages in a browser (no app.js change; the Usage and
Sessions pages read the same rows), the full go test ./... before push,
Windows box.
2026-10-24 02:48:50 +08:00
yetone 2fcd4b33c4 usage: one Vias index answers every since, instead of a rebuild from the whole log whenever the since changes (#2776)
Vias kept the lists for one since. The Sessions list asks from its
oldest listed session's start, each agent's manage page from that
agent's oldest, and a session's detail from that session's start, so
an open page's polls almost never asked the kept since, and each ask
read and grouped the whole log again. Idle with an open Sessions page
on the 720k-call sandbox, buildVias allocated 9.1 GB in 8 minutes,
78% of everything allocated, which is most of why the idle process
churned its heap and grew.

The cache now keeps one index from the whole log and each session's
first call. A session whose calls all came at or after the since is
answered from it. A session with calls before its since is answered
from one kept window for that since, built only when such a session
is read. Len counts the sessions with a call since the index's time.
Both are kept per log version and agent list, as before.

TestViasAnswerEverySinceFromOneIndex writes 20,001 sessions and asks
from three sinces in turn, as the three pages do: 2,677 bytes an ask.
On the old cache: red, 11,580,100 bytes an ask. It also checks that a
session with a call on each side of a since counts only the one after
it, and what Len says for a window and for every session.
TestGatewaySessionsCachePricesWindowsAndRewrite's window check and
TestUsageViasSkipsOldHistory stay green.

720k-call sandbox, idle with an open page's polls every 15 s (the
Sessions list, stats, Claude's manage page, Requests, state), before
and after side by side for 12 minutes, load ~170-250. Allocated from
minute 4 to minute 12: buildVias 9,100 MB before, 0 after (built once,
before minute 4). The faster answers let the poll loop run about twice
as often, so the totals (11.6 GB and 10.5 GB) aren't per poll. The
live heap ran 352-641 MB before and 514-724 MB after, and RSS 730-962
and 555-1217 MB; both swing with where a poll is when the snapshot is
taken and the machine's load, and neither shows a trend in 12 minutes.

Run: go test -p 4 -count=1 ./internal/usage/ -run
'Vias|KeptStrings|GatewaySessionsCachePrices|Incremental|Review': ok.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:19 +08:00
yetone 6359b2c27c usage: Vias hands every caller the one copy it keeps, and a session's list is copied only when read (#2776)
Vias cloned every session's list for each ask, from a cache built for
exactly this. The Sessions list, the manage pages and a session's
detail each asked, and read the lists of the sessions they show, or of
one. Over ~720k calls one ask was ~66 MB.

Vias now answers a ViaIndex over the kept map. Of(key) is a session's
list as a copy of its own, so a caller still can't change the kept
one; Len is how many sessions have one. The three GUI callers and the
tests read through Of.

TestViasHandOutTheKeptCopy writes 20,000 sessions and asks 20 times,
reading one list each: 2,590 bytes an ask. With the clone of every
list put back by hand (under ViaIndex): red, 3,817,492 bytes an ask.
It also changes a list read through Of and checks the next ask still
says 1 call.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone db61143fe7 usage: the Sessions and Routing caches copy out the strings they keep, so they no longer pin every decoded block
An unpacked block's strings are cut from one allocation (unpackInto). The
gateway-sessions projection (gatewayCache) and the vias cache kept a
session id, model, agent, provider or effort from nearly every block, and
each such substring held the block's whole decoded text: request and
response ids and errors included. keptStrings clones each kept value once
and interns it, so a cache holds only what it uses.

TestSessionCachesHoldNoDecodedBlocks writes 16 blocks x 512 rows with a
1 KB error each, reads GatewaySessions and Vias, drops the snapshot and
compares the live heap with and without the caches. Without the fix
(both call sites reverted) it is red: "the caches hold 16651 KB for 16
sessions: the decoded text of their blocks (8192 KB)". With it, green
-count=3.

Measured (macOS, sandbox HOME seeded with 600k gateway calls, the fixed
build vs ccb2eea15, the same Usage/Sessions/Routing views opened by
Playwright, after GC via /v1/magpie/heap; footprint from `footprint`):
- after the views: live heap 618 MB -> 466 MB, footprint 801 -> 670 MB
- after warm-up only: live heap 467 -> 390 MB
- CPU over the same 9m40s: ~22.4 s both
Go is the process that holds memory: on a live v0.1.1208 app the Go
process's footprint was 1045 MB, the Bun plugin host 51 MB, the two
WebKit WebContent processes 70 and 83 MB.

No single commit in v0.1.1225..HEAD is the cause: the shared-slab decode
(99fcddeeb) and both caches (c9b826337, 60f896031) predate v0.1.1225.
Idle with no page open, HEAD used 1.04 s CPU per 5 min against
v0.1.1225's 0.56 s.

Not fixed here: the gateway projection is kept once per window (up to
4), the startup heap peaks ~1.5 GB from GOGC doubling the warm-up's live
heap, and a synthetic 11k-session history did not reproduce the 1 GB
reported.

Run at this change on ccb2eea15 (load average ~275-500 from other
sessions):
- go test ./... -timeout 45m, sandbox HOME: 61 packages ok;
  internal/agent timed out at 45m; 4 reds in gateway
  (TestClaudeAccountsSpentFallBackToCodex,
  TestCodexServedNamesTheAccountThatSigned) and gui
  (TestPluginPageReadsWhatItDeclared,
  TestSetAnswersWhileDevinAndProvidersHang).
- Those 4 alone: gateway ok 40.8s, gui ok 13.7s.
- internal/agent alone (-timeout 45m): timed out again at 2732s under
  load ~500; the stacks left include a netproxy.Bridge accept loop.
  internal/agent never calls GatewaySessions or Vias, the only code
  changed. Not filed from here: the run kept only its last 25 lines,
  so the test that hung is not named.
- internal/usage: ok 123s.
- gofmt -l: clean. go vet ./internal/usage/ for darwin, linux
  (nogui) and windows: clean.
2026-10-19 03:01:38 +08:00
yetone 7170b5d8bd usage: the plan credits a reply says it cost are summed by model, agent and session (#2512)
wwcraft_ on Discord asked for the WorkBuddy credits spent on the Usage
page, by model, agent and session. WorkBuddy's chat stream ends with
usage.credit, the per-request figure its own app shows as "Credits
Consumed". The built-in and the moved plugin both hand that chunk to the
gateway's chat decoder (the plugin's renamed()/kept() pass usage on as it
came), so cUsage reads `credit` into Usage.Credits and the three record
sites keep it on the row. A reply that says nothing has no credits, not 0.

- usage: Record.Credits; Totals/Via sum Credits and count Credited; the
  packed row keeps it under its own flag bit (4096, in TestRowFlagsApart);
  the ledger CSV gains a trailing "credits" column.
- GUI: the Usage ranking's line says "0.7 credits" (积分, 積分,
  クレジット, Credits) beside the cost, its title how many requests said
  it; the Sessions page's Routed line says it per route. TUI usage page
  and `magpie usage` tables say it muted on the same line. No new layout.

Real replies on workbuddy-ai, 10-16: gemini-3.5-flash "credit":0.01;
deepseek-v4.1-flash, minimax-m3, kimi-k2.6 "credit":0; glm-5.3-flash
refused (14003). The tests use those bytes.

Run (at b07b518e7 on origin/main 63be47717, with #2511's commit):
- gofmt -l clean; go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean; go build: ok.
- go test -timeout 45m ./... with pipefail, sandbox HOME: 63 packages ok,
  usage (200s), cli, tui, gui among them; agent, gateway and library timed
  out at load ~270 (see the #2511 commit); library ok alone, agent and
  gateway ok with -timeout 150m: agent ok (5529s); gateway red only in TestIntentClassifierGroup (#1813), TestMaxRPMWaitsForRoomInTheMinute (#1791) and TestMaxRPMGroupPrefersMemberWithRoom (#2520), known timing reds under load, each passing alone here -count=3 (19s).
- New: TestPlanCreditsReachTheLedger (chat stream, whole reply,
  translated /v1/messages, free 0, none), TestPlanCreditsSummed,
  TestPlanCreditsPacked, TestFormatCredits, TestUsageSaysCredits, and
  plan-credits.test.cjs (en, zh, zh-TW, ja, de; Chromium and WebKit;
  420px fit) 12/12.
- Broken by hand: dropping Credits at the record site turns the gateway
  test red; skipping it in unpack turns the usage tests red; dropping the
  ranking's ledCredits turns plan-credits red in every language.
- GUI reds elsewhere: see the #2511 commit (#2536, #2552, a
  provider-detect-draft load timeout that passes 3/3 alone).
- Rebased onto origin/main ba132d68b (13 commits; chat.go, gateway.go, app.js, i18n.js among theirs): gofmt and go vet ./internal/... clean; Credits/DeepSeek/Balance/Ledger/RowFlags tests in usage, gateway, provider, cli, tui ok; plan-credits 12/12, balance-parts 4/4, i18n-keys 3/3 in both engines.
2026-10-16 20:11:34 +08:00
yetone 9916a94608 gateway, usage, plugins: OTel export is the first plugin on the gateway's observer point (P3)
P3 of docs/subsystems/plugin-runtime.md opens the gateway to plugins. The
observer point is first: it only reads, so it carries the least risk.
With plugins/otel off, the gateway exports nothing and does no observing
work. It keeps no reply whole and adds no request context.

- usage.Observer:
  - Methods: Serve, Bodies, Begin(Request) Watch and Ledger(Record). Watch
    has Attempt and End.
  - Observe(o) registers an observer until its remove is called.
  - ServeObservers is counted, and only Server.ListenAndServe calls it.
  - ObservedBodies takes the most any observer wants.
  - Record.SkipOTel becomes Watched, set by appendUsage for a request an
    observer watched.
- The gateway's otel.go becomes observe.go:
  - observeRequest asks each observer through Begin.
  - attempt and end call each Watch. Bodies are added only when an
    observer asks for them, and the whole reply only for WholeBodies.
- internal/otlp: the exporter (otel*.go) moves out of internal/usage, and
  the gateway's per-request span state moves into request.go. otlp.New()
  is an Exporter, a usage.Observer. What it sends is unchanged.
- plugins/otel:
  - Apply registers otlp.New() and disposes of it when turned off.
  - InUse is 1 while settings.OTelExport says to send. A user who exports
    only through MAGPIE_OTEL_* keeps the plugin on under Essentials.
- pluginrt.KeepFresh: the process serving the gateway refreshes every 2s
  when plugins.yml or settings.json changes. A switch made in the window or
  the CLI reaches a running gateway, or a headless serve, without a restart.
- docs: plugin-runtime.md gets a P3 section, a gateway runtime path and an
  updated failure section; reference.md says the export is the otel plugin.

Run at this tree on origin/main 82f48f093 (rebased onto 52ee84761 after,
which touches only the Linux tray icon):
- gofmt -l is clean. go vet passes on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -count=1 -timeout 25m ./...: ok, 55 packages, none failed.
- New tests:
  - usage: TestObserverServesWithTheGateway and TestObserverLedgerAndBodies.
  - gateway: TestObserverPoint, covering unwatched, no bodies, captured,
    whole and whole streamed.
  - plugins/otel: TestOnExportsOffSendsNothing (on, off, on, with a real
    collector) and TestInUseByEnvironment.
  - pluginrt: TestKeepFreshFollowsPluginsYml.
  - The OTel tests moved with their code to internal/otlp.

Broken by hand, each red, then restored:
- Apply without Observe, and without its dispose.
- KeepFresh refreshing only once.
- InUse reading settings.json only.
- Ledger keeping Watched rows: 3 gateway OTel tests red.
- ObservedBodies taking the last observer's answer.
- Observe not serving a late registration.
- appendUsage not setting Watched.
- Whole bodies never kept.
- Bodies always on with no observer asking.
2026-10-15 05:39:01 +08:00
Hogee 3c4b4dc973 sessions, usage: a Codex subagent with no title takes its parent's spawn_agent task_name, its nickname shows apart, and Usage requests say which calls were compactions (#1591, Hogeexxl)
Hogeexxl's change (his fork branch codex/codex-session-details, f7c176c9),
cherry-picked with his authorship:

- A Codex child thread whose title is still empty after the existing
  precedence takes the task_name of the parent's spawn_agent call, linked by
  the call id and the SubAgentActivity "started" item that names the child's
  agent_thread_id. Conflicting links leave the title empty.
- session_meta.agent_nickname is exposed as `nickname` on the list, one,
  manage and overview responses, beside the title, not in place of it.
- GET /api/usage/requests and /v1/magpie/usage/requests carry `compaction`
  (true/false) for Codex calls with native evidence, and leave it out
  otherwise. A gateway row matched by a unique response_id takes the marker
  and keeps its own model, usage, cost and kind.
- Flags bits 1024 (rowCompactionKnown) and 2048 (rowCompaction) are new.
  TestRowFlagsApart covers them, and they don't overlap 1..512. The sessions
  cache goes to version 21 and the calls cache to calls-v15.

Review:
- Rollout format checked against Codex's source (openai/codex 669449b):
  - v2 spawn_agent args carry task_name.
  - A paginated rollout persists item_completed with a SubAgentActivity
    item: kind "started", id = the call id, agent_thread_id.
  - SessionMeta has a top-level agent_nickname, which Codex's own list.rs
    and metadata.rs read too.
  - compaction_response_id lives in token_usage_record.
  Gaps in legacy rollouts and in calls without a response_id are fixed in
  the next two commits.
- Privacy: only a title string the user's own Codex wrote and a boolean
  are added to local API responses. Nothing new goes to a vendor or to
  telemetry. The ingest POST parses fields one by one, so it is unchanged.
- No .github, dependency or network changes.

What was run:
- His tests pass: go test -tags nogui ./internal/sessions ./internal/usage,
  and the two new internal/gui API tests.
- Broken by hand, each caught by his tests:
  - the nickname read removed;
  - the conflict checks removed;
  - mergeCodexCompactions broken;
  - the gateway pair's setCodexCompaction removed;
  - the flag read forced to true.
- Not caught:
  - the parent check on the title link (covered by a test in the next
    commit);
  - `copy.codexCompactions = nil` in cloneCodexChunks removed. That line is
    defensive only: the shared chunks never hold the map.
- The gofmt, vet and full-suite record for the three commits is in the
  last one.
2026-10-15 04:21:31 +08:00
yetone eb7199e120 gui: Routing is a plugin's page, its script, style and words in plugins/routing (P2)
P2 of docs/subsystems/plugin-runtime.md, the third page after Sessions
and Library.

- routing.js and routing.css move to assets/plugins/routing/ (client.js,
  routing.css). Its part's html is the page's head and boxes that were
  index.html's <main id="view-routing">; the rest is drawn by
  routingPage, run at mount since it builds on app.js. It keeps itself
  after that as it did (its own hidden, the language, focus), so its
  hooks are dirty and discard, a routing group being edited, which
  show() and the window's close ask through magpie.call:
  window.routingDirty and discardRouting are gone.
- plugins/routing: Essential, Requires window and gateway, in use while
  the user has a routing group (not Auto, not Hidden), since the page is
  where it is edited. The gateway routes the same with it off.
- With it off, what leads to the page goes too: the nav and panel tabs
  and the panel's section (data-feature="routing"), the guide's Open
  Routing, Providers' "Make a routing group of …", the Usage list's
  View routing and its time as a link, the context card's Latest
  request. A panel left on its Routing tab shows Agents.
- What other pages use of it stays on window: openRoute (context.js),
  kindName, swapWhy, routedWhy (Usage's Requests), newGroupWith
  (Providers), panelRoutingShown (the panel).
- The 505 strings only Routing says move from i18n.js to
  plugins/routing/i18n.js (4 languages); i18n.js 17048 → 15032 lines.
  The plugin's own name and line stay in i18n.js: the Plugins page
  says them with the plugin off (TestBuiltinsTranslated).
- Tests and comments that named routing.js name the new path (gateway's
  antigravity_rest and loop_guard, codeassist.go, usage.go,
  web_compress, group_member_info, assets_revalidate, font-cascade,
  win-fonts, three routing-*.test.cjs). builtins.test.cjs and
  builtins_test.go count seven built-ins and switch Routing off: its
  tabs go, the page shown stays.
- docs: plugin-runtime.md, gui-shell.md, gateway-routing.md.

Run, first on origin/main 3ec45e715, then after rebasing onto af27b70b4
(main's routing.js, css, app.js and i18n.js changes since were carried
into the moved files; its new Routing words, as the rules' conditions,
are in the plugin's i18n.js):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 ./internal/gui ./internal/gateway ./internal/usage
  ./internal/pluginrt ./plugins/...: ok (gateway 1800s under load,
  -timeout 45m; gui with -skip TestMainWindowCorners, #1936).
- All 193 GUI test files, 3 at a time at load ~250, Chromium and WebKit,
  at the Usage commit on 743fcc035: 185 and 186 green. Every red run
  alone here and on a just-fetched origin/main c524bc018:
  - the same on main: routing-model-rest (#2115), routing-wb-restricted
    (#1905), usage-agents-hide (11 of 16 in both, #2211), usage-fold
    (#2163: 12 of 14 here, 9 of 14 on main over 7 runs, the same 4px),
    quota-count-wrap and quota-name-translated in WebKit (#2228);
  - red only under load, green alone on both: routing-flood (#2215),
    routing-log-icons, usage-ledger (#2211), and three plugin-* files
    whose tree was rebased under them mid-run.
- days-fit, failed-open, side-calls and burst-speed, red on main after
  cf455ebd5, are fixed before this commit (#2134, d692b2548).
2026-10-15 01:32:12 +08:00
yetone 60f896031e usage: a client the user counts as an agent is counted as it on Usage and Sessions (#1958, NorethSea)
NorethSea's bridge (hermes-codex-thread-bridge) starts Codex's
app-server under a User-Agent of its own, so its calls were a row
apart from Codex on Usage, and its threads weren't Codex's in Sessions.
Rather than learn one bridge's name, the user says which agent a client
counts as.

- settings: clientAgents, client name (lowercased) -> agent id.
  ClientAgentsNow reads just that field through filememo, so a pass over
  the ledger costs a stat.
- usage: ReportedAs(ua) is AgentOf, then the user's mapping. It is used
  for what is reported only: the summary, the agents list and filters,
  request rows and pages, priced blocks, direct, Vias and gateway
  sessions. The gateway's routing, keys and caps still go by AgentOf,
  the client's own name. The mapping is read once per ledger pass
  (readLogSnapshot) and is part of the keys of the summary price cache,
  the vias cache and the request page cache, so a change redraws the
  history already counted. A request row keeps the client's own name in
  a new "client" field, shown as "Client" in its details.
- gui: POST /api/usage/arrange takes {count:{client,as}}. It refuses a
  client magpie already knows as an agent, "other" or magpie's own, and
  an "as" that isn't a known agent or is magpie. as "" counts it on its
  own again. /api/settings keeps the mapping it doesn't send. On the
  Usage page an unknown client's "…" offers "Count as an agent…" (a
  picker of the known agents), the agent's row says "with <client>",
  and the agent's "…" offers "Count <client> on its own". Strings are
  in all 5 languages.

Run:
- go test -count=1 ./internal/usage ./internal/settings ./internal/gui: ok.
- TestClientCountedAsAgent goes red with reportedAs broken, and with the
  mapping left out of the vias key or the request page key. With the
  summary key alone left out it stays green, because the settings stat
  already moves it.
- TestUsageArrangeCountClient and TestSettingsSaveKeepsWhatItDoesNotSend
  (ClientAgents added) pass.
- Playwright usage-count-client.test.cjs (new) and usage-agents-hide
  (its menu now has two items for an unknown client) pass in Chromium
  and WebKit, in all 5 languages, at 1100 and 420: 54/54. With
  countable() forced false, the new test goes red.
- gofmt -l is clean. go vet is clean for darwin, linux -tags nogui and
  windows.

Not tried: a real hermes bridge (the records' UA is from the issue), and
the Client line in a request's details has no GUI test.
2026-10-13 18:17:47 +08:00
yetone 30869e35a7 usage, gateway: each request's log row says the service tier asked, the one each try was sent at, and the one the vendor said it ran at (#1784, zhenghaowen0967)
What changed
- usage.Record has tier_asked, tier_sent and tier_served, and the CSV gets
  them as its last three columns.
  - tier_asked is the client body's service_tier (Claude's speed fast reads
    "fast").
  - tier_sent is the tier the try's last request actually went out at. It
    is noted in forwardOnce after every rewrite (a fast pick's priority,
    Ultrafast turned to priority on a plan without it, buildResponses
    dropping a tier the host can't take) onto the per-attempt wireAt. So a
    handed-on try's own row has its own tier.
  - tier_served is only what the reply said: service_tier at the top level,
    in response.service_tier, or in an Anthropic usage. It is read by the
    relay sniffer and by both translated readers, and is empty when the
    reply says nothing. It is never filled in from the ask.
- Codex's own relayed sign-in (codex_backend) records the same three.
- /v1/magpie/route: Route.tier (asked), and each Try has tier and
  tierServed. The session route has asked_tier, tier, tier_served and each
  try's tier and tier_served.
- docs/reference.md (CSV columns) and gateway-routing.md describe them.

Why
zhenghaowen0967 asked that a request whose Ultrafast was sent as priority
to an account without it show that in usage, per try, without calling
the served tier confirmed unless the reply says so.

What was run
- TestTierRecordedPerTry. With Pro out, the first try is recorded
  ultrafast, the second priority, and the final record has asked=ultrafast,
  sent=priority and served empty while the fake doesn't echo. With an
  echoing fake, served is what it said ("ultrafast", and "default" when
  none was asked). It also checks the CSV columns, and the Codex relay path
  with priority.
- TestUpstreamTierShapes covers the Chat chunk, Responses
  response.completed, a Responses body, an Anthropic message_start and
  message_delta usage, null, an over-long tier and non-JSON, as well as
  bodyTier per protocol.
- Broke it by hand:
  - with forwardOnce's noteWireTier removed, TestTierRecordedPerTry goes
    red (route tries' tier empty, TierSent empty);
  - with the sniffer's Tier line removed, TestUpstreamTierShapes goes red,
    and so does the Codex relay case of TestTierRecordedPerTry.
- go test -tags nogui ./internal/gateway ./internal/usage ./internal/cli;
  ledger_test's CSV expectations gain the three empty columns.
- gofmt -l; go vet on darwin; GOOS=linux and GOOS=windows go vet -tags
  nogui.

Not done
- The served-tier fixtures are built from the shapes OpenAI and Anthropic
  document, not from saved replies. Whether chatgpt.com's Codex backend
  echoes service_tier wasn't tried against a real account.
- Bridges that don't go through forwardOnce (the Claude subscription,
  Cursor's built-in) leave tier_sent empty.
- There is no price multiplier for priority/ultrafast and no GUI column.
2026-10-13 14:22:53 +08:00
yetoneandMonkeyLeeT dfbe001ff9 usage, gui: re-land def3a41e3, a Codex one-call turn timed only over a second and 100 tokens after its first token
2c30e5cee held def3a41e3 back "until Fallmonkey says what context it
missed". Fallmonkey answered on Discord: no objection, ship it. This
reverts the revert. app.js conflicted with aabdd6126 (larger sample
first); the resolution keeps aabdd6126's first_text_ms > 0 guard on the
reasoning check and adds back the Codex window check below it.

Run: go test -tags nogui ./internal/usage; usage-speed-count (52),
usage-speed, usage-ttft-rounding, i18n-keys green in chromium and
webkit; gofmt -l clean; go vet darwin, linux nogui, windows.

Reported-by: Fallmonkey (Discord)
Co-authored-by: MonkeyLeeT <MonkeyLeeT@users.noreply.github.com>
2026-10-13 09:10:14 +08:00
congee949 2d3b33bb78 usage: time tool-only replies only with visible reasoning evidence
Revises #1463 after the hidden-reasoning inflation review. Keep answers separate, retain evidence in routes and cached ledger rows, and exclude sealed or summary-only reasoning even without a token breakdown. Sync the backend and both GUI formulas.

Checked real WorkBuddy DeepSeek, Codex and Claude bridge responses in an isolated HOME; sanitized timings and failures are in docs/verification. Chromium/WebKit speed regressions pass (20 tests, five languages). New edge regressions and loop-order check pass under race repetition. Restoring the old formula or removing the hidden guard fails TestVisibleReasoningSpeed. macOS/Linux/Windows vet/build pass. Full-suite verification is recorded in the issue at this head; inherited proxy/Bun 1.3.14 failures are retained, with clean Bun 1.4.2 rerun in progress. No installed app replacement.

Rebased onto main by yetone (#1463). Conflicts with main's Own/Retried/
Queued/Tries row fields, HandedOn and the Codex speed floors were resolved
by keeping both. The packed row's ReasoningHidden bit was 64, which main
has since given to block_price.go's swapKnown, and main's rowHandedOn took
128, filling the uint8: Flags is now uint16 and ReasoningHidden is bit 512
(rowReasoningHidden; #1874's rowOwnCost took 256), read back in row(). The docs/verification notes and
their sample JSON are left out of the tree; they stay on the contributor's
branch and the issue. Run after the rebase: go test -tags nogui ./internal/usage/
and the gateway's reasoning/speed/TTFT tests, ok.
2026-10-13 06:43:50 +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 5ca9dc19db usage, gui: a model says how many of its replies were ended for looping (#1858)
#1858 asked for recovery across turns when a model loops. magpie is a
gateway and can't rewind the agent's session, so that is not planned now.
What it can do is let the reader see which model loops. Each reply the loop
guard ends (#1359) is logged with err_type "reply_loop", but Usage only
counted it among the failures.

usage.LoopErrType is now that type (the gateway's loopErrType is it), and
Totals.Loops counts, among the failed requests, those ended for looping. A
handed-on try is still no request. The Overview's model, agent, account
and key rows and the Requests ranking say "{n} looped" beside "{n}
failed", and the ranking's "Other" adds them up. Translated into zh,
zh-TW, ja and de.

Run: TestLoopsCountedPerModel (Overview groups, the ledger sum and
Breakdown; red with the increment removed). go test ./internal/usage
./internal/gateway ./internal/gui; gofmt -l; go vet on darwin, linux
-tags nogui and windows. The new usage-loops.test.cjs ran in chromium and
webkit, 5 languages at 360 and 1100px, 20 pass; it fails 10 of 10 on HEAD~
assets. usage-*, ledger-*, own-requests, i18n-keys and gui-zh-tw/ja/de in
both engines: 565 pass.
Not run: a real looping model through the gateway (the logging path is
unchanged from #1359).
2026-10-13 04:31:07 +08:00
yetone 2c30e5cee7 usage, gui: revert def3a41e3 until Fallmonkey says what context it missed
Fallmonkey asked on Discord (#feedback, 10-12 19:55) to hold the
single-call Codex threshold: "先别做?感觉你漏掉context了". It is not in a
release yet, so take it off main until the rule is agreed, rather than
ship a speed rule its own requester has paused.

This reverts commit def3a41e36.

Run: gofmt -l, go vet, go test ./internal/usage.
2026-10-13 04:07:30 +08:00
yetone def3a41e36 usage, gui: a Codex turn of one call is measured only over a second and 100 tokens after its first token, else told as the least it wrote over the whole turn (Fallmonkey on Discord)
Fallmonkey's repro: a Codex turn whose first token came at 6.8 s (the
model working) and the rest 0.2 s later in one network push read as
thousands of tok/s from its session file. The promised rule, now in:

- A Codex turn of one call read from its session file (source "log",
  turn TTFT known) tells a measured speed only when the window after its
  first token is 1 s or more and its body 100 tokens or more
  (usage.CodexWindowMs, CodexBodyTokens; Row.Decode, app.js ledDecode).
- The floor from e5b82cf38 for such a turn that reasoned (its answer over
  the time after the first token, "②") is held to the same threshold:
  827 ms after a 10.2 s first token no longer reads ≥329, as that window
  can be one push too.
- A turn that tells neither tells its output over the whole turn
  (Row.Floor, ledFloor_ "turn"), the wait in it, of any size: everything
  it wrote was written in that time, so it is a true floor. 380 tokens in
  6.8 + 0.2 s read ≥54 tok/s. Its tooltip says the whole turn was used and
  why, with the time after the first token (new string in en, zh, zh-TW,
  ja, de).

Gateway rows and other agents' rows keep DecodeOf as before; Codex calls
in turns of several keep the 1,000-token rule. The ledger's period sum
now adds each row after it is built (Totals.addFrom) so it uses
Row.Decode too. docs/reference.md says the rule.

Tests: TestCodexTurnMeasuredOnlyOverASecondAndAHundredTokens (new: 380
over 0.2 s after 6.8 s, 60 over 2 s, the 1 s/100 edges, gateway and
Claude rows unchanged, group, ledgerWith sum, Part) and
TestCodexRowsTellAFloor (updated cases) fail on the old ledger.go and
usage.go; the sum check fails with only the ledger closure reverted.
usage-speed-count.test.cjs: the 496/224 row now ≥45 with the whole-turn
tooltip, a 1,000-token answer over 10 s ≥100, Fallmonkey's row ≥54;
fails on the old app.js.

Ran: go test -tags nogui ./internal/usage ./internal/gui ./internal/cli;
gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
internal/usage and internal/gui; 50 GUI suites (usage-*, ledger-*,
reasoning-speed, routing-burst-speed, routing-request-metrics,
panel-usage, gui-de/ja/zh-tw, i18n-keys) in Chromium and WebKit: 506/507,
the one red usage-sum-whole chromium ja at 780px under load, reproduced
on origin/main 5c82e6880 and filed as #1864. On copies of the owner's
recent Codex rollouts (955 calls), 2 were turns of one call; one, 13
tokens 315 ms after a 4.3 s first token, moves from 41 tok/s to a floor.
Not tried with Fallmonkey's own sessions.
2026-10-13 03:51:38 +08:00
yetone 60808fd9cf usage, gateway, gui: magpie's own requests are told apart from the agent's, and a classifier on a subscription says it asks it every turn (#1839)
kensenzhao saw a subscription's allowance spent by requests the agent
didn't make: a routing group's classifier, set to a subscription's model,
asks it as every turn begins, and those calls looked like the agent's own.

What changed
- usage.Group has an own share (calls, tokens, cost) of the calls magpie
  made by itself, filled for models, keys and accounts. Record.ByMagpie
  is the test: agent "magpie", or one of its own User-Agents
  (magpie-router/1, magpie-search/1, magpie-vision/1) where the agents
  aren't loaded. The calls still count in the group's totals, as they
  went to the same key or account. A group with none sends no "own".
- The classifier's calls are Kind "routing": callKind marks RouterAgent's
  requests, and the decision model's record (Jev / System One) is written
  with it. A "Routing classifier" purpose names them in the ledger.
- Usage page: magpie's row among the agents and its ledger rows carry a
  "magpie's own" mark; an account's, key's or model's row adds "{n} by
  magpie itself"; an account's card says how many of the period's
  requests were magpie's own, drawn again once the summary arrives after
  the allowances.
- Routing page: /api/groups marks a model a subscription account serves
  (modelRef.Sub, servedRef). Beside a classifier on such a model, or a
  group whose first member is one, the editor says every turn starts
  with a request to that subscription, two when it picks both intent and
  effort in words. A classifier on a key or a free model says nothing.
- New strings in zh, zh-TW, ja and de. The mark is a muted chip with an
  even border all round (no left stripe).

Tests
- TestSummaryCountsMagpiesOwnCallsApart, TestByMagpie (usage).
- TestIntentRoutesATurn and TestJevPicksTheIntent (gateway) now check
  the classifier's records are Kind routing and magpie's own, and the
  agent's records are not.
- TestServedRefSaysASubscription (gui).
- own-requests.test.cjs: Chromium and WebKit, 1100 and 390 wide,
  en/zh/zh-TW/ja/de, the API faked; no click scroll, no sideways page.
- Broken by hand, each turned its test red: addOwn counting nothing;
  callKind's routing case removed; decide.go's Kind blanked; the ledger
  mark, the agents' mark, the "{n} by magpie itself" line, the card's
  line, its redraw after the summary, the Routing hint, its group case
  and modelRef.Sub each removed.

Run: gofmt -l; go vet on darwin, linux -tags nogui and windows; go test
for usage, access, catalog, gui (-tags nogui) and gateway in full; the
GUI tests above, the ledger, routing-intent and translation tests.
Not done: the warmups (warmClaude/askClaude) write no usage record at
all, so they can't be marked; that is left as it was. Not tried with a
real subscription classifier against a live account.
2026-10-13 01:41:50 +08:00
yetone 8653bead72 usage, gui: a usage record and a request's details carry its cache read and cache creation beside in and out (#1839)
kensenzhao asked for usage.jsonl and the Usage page's request details to
carry cache read and cache creation tokens beside input and output.

What changed
- usage.Record's cache_read and cache_write are written on every record,
  0 too (they were omitempty), so a prompt that missed the cache reads as
  that rather than as a record that kept no cache. A record from before
  has neither and reads as 0, as it did. Input still holds neither.
- Every route already filled them; this pins it per wire format:
  Anthropic messages, OpenAI Chat (prompt_tokens_details.cached_tokens and
  DeepSeek's prompt_cache_hit_tokens), Responses
  (input_tokens_details.cached_tokens) and Gemini
  (cachedContentTokenCount), relayed and translated, whole and streamed,
  a plugin's fetch, and the Claude subscription bridge. System One's
  decision calls report no cache and are left as they are.
- A request's details in the ledger have a Tokens row at every width:
  "{i} in · {o} out · {r} cache read · {w} cache creation", plus the
  5-minute/1-hour split when known. Before, the cache showed only as
  "{w} written · {r} read" when non-zero, so a missed cache said nothing.
  That string is gone; the new one is in zh, zh-TW, ja and de.

Prices and quotas: the JSON tag is the only change to the record, so the
cost math (CostAt -> CostSplit reads CacheRead/CacheWrite/CacheWrite1h),
Totals' cache sums, budget's CacheReads and access/limit's token windows
read the same values as before. Checked by reading each and by the usage,
access and catalog tests passing unchanged.

Tests
- TestRecordAlwaysCarriesCacheTokens (usage): 0s written, old records read.
- TestUsageRecordsCacheTokensOnEveryRoute, TestPluginUsageRecordsCacheTokens,
  TestClaudeSubscriptionUsageKeepsCacheTokens (gateway): each wire format,
  whole and streamed.
- ledger-cache-tokens.test.cjs: Chromium and WebKit, 1100 and 390 wide,
  en/zh/zh-TW/ja/de; usage-ledger-detail.test.cjs updated for the row.
- Broken by hand: putting omitempty back and dropping the Tokens row each
  turned its test red. The gateway route tests pin what the routes
  already did; they don't fail on the code before this commit.

Run: gofmt -l; go vet on darwin, linux -tags nogui and windows; go test
for usage, access, catalog, gui (-tags nogui) and gateway in full; the
GUI tests above plus the translation tests. Not run: a real vendor
request to see its cache figures land in usage.jsonl.
2026-10-13 01:41:50 +08:00
yetone 53abc8e283 gateway: a script Claude Code starts, naming a Claude id magpie doesn't serve, goes to Claude Code's tier (tbxark on X)
tbxark's request log: Claude Code's own requests went to its tier, while
Python-urllib asked /v1/messages for claude-sonnet-4-6 and claude-opus-5-5
and got 404 "unknown model" in 5 ms. A hook, the statusline or a plugin's
script that Claude Code starts inherits its ANTHROPIC_BASE_URL and token, so
it reaches magpie with the plain gateway token and its own User-Agent.
claudeTierStandIn mapped a Claude id to Claude Code's tier only for a
request magpie took for Claude Code, by its User-Agent, so the script's
ids went nowhere.

Now a request that came with the plain token (not a magpie-<agent> token
magpie gave an agent), whose User-Agent names no agent magpie knows
(usage.IsAgent; claude-desktop and cursor-local are known too), and that
names a Claude-family id magpie doesn't serve, gets Claude Code's stand-in
for it, on /v1/messages and on count_tokens (the one choke point both
use). Nothing changes when:
- the id is served (a Claude subscription or an Anthropic key in the
  catalog lists it): it goes where it is served, as before;
- the caller is an agent magpie knows, or uses an agent's own token;
- Claude Code isn't routed through this gateway (StandIn says nothing),
  so the 404 stays.

Run:
- TestClaudeTierForAScriptClaudeCodeStarted (new) fails on the old
  gateway.go (404 for urllib, "", anthropic-python; count_tokens counted 0
  without reaching the tier). Breaking the token check by hand or the
  served-id check by hand turns it red too. TestIsAgentByUserAgent (new,
  internal/agent) covers IsAgent with the real agent list.
- Sandbox HOME, a fake Anthropic upstream, `magpie serve` on 127.0.0.1:3561
  with Claude Code's settings.json routed there (sonnet/opus tiers set):
  python3 urllib POST /v1/messages claude-sonnet-4-6 with x-api-key magpie:
  old binary 404 "magpie knows no model", new binary 200, upstream got
  m-sonnet-tier; claude-opus-5-5 -> m-opus-tier; count_tokens reached the
  upstream on m-sonnet-tier. A codex_cli_rs User-Agent still gets 404.
- gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go test of every package (gateway with
  -timeout 25m).

A full ./... run on the loaded Mac timed the gateway package out at 10m
(#1654); run alone it passed in 330s.
2026-10-12 00:22:49 +08:00
yetone 8b799cc890 usage, gateway, gui: a request's "In magpie" is magpie's own time, not a try the vendor held before its 503 (#1532, nianlee-official)
The reporter's Codex -> OpenCode Go deepseek-flash request read "In magpie
104 s" with "Vendor's first token 37 s". Record.Sent is the ms from the
request to its answering try's body being written, and by design it
includes the tries that failed first and the pauses after them; the
request detail showed all of it as "In magpie". The reporter's own
routing screenshot shows OpenCode Go answering 503 Service Unavailable
after holding a try ~70-100 s (01:07:08: 3 tries, 222 s), and rows like
01:01:48 / 00:58:27 answered on a second try. Their ledger row showed no
"2 tries" only because that badge came in v0.1.1182.

Now each record also keeps, of Sent:
- own_ms: magpie's own work (before the first try, and in the answering
  try up to its request starting to go out, httptrace GetConn), floor 1;
- retried_ms: from the first try's start to the answering try's, i.e. the
  tries that failed first and their pauses;
- queued_ms: the answering try's wait for a MaxConcurrency / MaxRPM slot.
What's left (Sent - the three) is connecting and sending the body. The
Requests detail shows In magpie, Tries that failed first, Waiting for a
slot, Connecting and sending, Vendor's first token (en, zh, zh-TW, ja,
de). A record written before keeps showing Sent as In magpie. Sent and
Vendor's first token are unchanged. The packed in-memory request rows
carry the three fields (no on-disk format).

Measured: with an isolated gateway and a fake chat upstream, a
Codex-shaped Responses body of 1.79 MB (~330 turns of reasoning,
function_call and function_call_output, 18 tools, zstd encoded, sent
over real HTTP) took 0.64-1.36 s of magpie's own time alone and
0.8-0.95 s with 4 at once, at load average ~228; far from 100 s.

Run: TestSentTellsMagpieFromEarlierTries (upstream holds the first try
1.5 s and says 503, the second answers: Sent 1514, Own <500, Retried
>=1500) and TestSplitSent; on the old code the detail's value is the
whole 1.5 s (reproduced: sent 1514 ttft 1515), and both go red with
splitSent returning (sent, 0, 0). usage-ledger-detail.test.cjs (Chromium
and WebKit, en and zh) adds the reporter's row and fails on the old
app.js ("104 s" where "180 ms" is expected); i18n-keys, gui-ja, gui-de,
gui-zh-tw pass. go test -tags nogui ./internal/gateway ./internal/usage,
go vet (darwin, GOOS=linux, GOOS=windows) and gofmt -l pass.
2026-10-11 20:58:56 +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 e5b82cf38a usage, gui: Codex rows tell the least they wrote at: a call in a turn of several over its whole time, a turn of one call that reasoned by its answer after the first token (Fallmonkey on Discord)
Codex's session rows told no floor. A call in a turn of several could be
timed from inside itself; the commit before this one times it from what
asked for it, before its first output item, to its last, as Claude Code's
is. So Codex joins usage.FloorAgents and app.js's LED_FLOOR_AGENTS, and
such a call tells its output over its whole time, by the same 1,000-token
rule. On 622 stripped recent rollouts only 4 of 1,367 such calls have
1,000 tokens or more, so the floors will be few, but they are true.

A Codex turn of one call that reasoned has its first token (the turn's
time_to_first_token_ms) but not its first text, so DecodeOf tells no
speed. Fallmonkey asked for its whole output, reasoning too, over the
time after the first token. That reads high: OpenAI's reasoning is
written before the first content, so it isn't in that time. On a gateway
reply of 496 tokens, 224 of them reasoning, 827 ms after a 10.2 s first
token, that is 600 tok/s against a measured answer speed of 415 (the
bug e6dd5d20b fixed). Instead the answer, its output less the reasoning,
which all came after the first token, over that time: 329, a true floor
of the answer's speed. Any size tells one, as the wait isn't in it;
DecodeWindow's bounds still hold. The Requests row's tooltip says so, and
a group's floor tooltip now says the file doesn't say when the answer
began, true of both kinds, in en, zh, zh-TW, ja and de.

The 1,000-token rule stays (Fallmonkey asked for 5 s instead): it bounds
the share of the time the wait for the first token can be, which a
duration doesn't (a 5 s reply can be 4 s of wait). On the owner's
gateway rows, where both are known, a floor of 1,000 tokens or more read
0.40 of the measured speed (n=25), one of 5 s or more 0.18 (n=550). The
reason is in Row.Floor's comment and docs/reference.md.

Tests: TestCodexRowsTellAFloor (new) and TestGroupSpeedSaysHowManyRepliesItIsOf
(sol's 259 calls in turns of several now tell 259 floors at 50) fail on
the old ledger.go. usage-speed-count.test.cjs gains a turn-of-several row
(≥50) and the 496/224 row (≥329, its tooltip) and fails on the old app.js;
usage-session-speed.test.cjs's Codex row now tells its floor.

Ran: go test ./internal/usage ./internal/gui; usage-speed-count,
usage-session-speed, usage-ledger-detail, usage-speed, reasoning-speed,
usage-ledger-fit, usage-model-at-provider, routing-request-metrics,
gui-ja, gui-de, gui-zh-tw and i18n-keys in Chromium and WebKit, at 1400
and 560 px; gofmt -l; GOOS=linux/windows go vet.
2026-10-11 12:49:27 +08:00
yetone 3964ea656c usage, gui: a group's speed says how many replies it is of, "125 tok/s (1)", and one with only floors says "≥100 tok/s (30)" (Fallmonkey on Discord)
Fallmonkey: the Usage ranking and the Output speed card showed
gpt-6.1-sol's tok/s from the one reply of its 260 that used no tool (the
only Codex turn its session file times) beside "260 requests", while
Claude Code, whose Requests rows say "≥N tok/s" by the dozen since
0192edf1, showed none. Asked for one rule for every source: measured
replies give "N tok/s (k)", only floors give "≥N tok/s (k)", neither
gives nothing.

usage.Totals now counts DecodeN, the replies its DecodeMs/DecodeOut are
of (add and addRow), and FloorOut/FloorMs/FloorN, the floors of rows read
from Claude Code's and Claude Desktop's session files (Row.Floor, the
same rule as app.js's ledFloorSpeed: source "log", not failed, no
measured speed, 1,000+ tokens over 1 s+, under 10,000 tok/s). Floors are
never in Speed(); the Speed trend and `magpie usage` are unchanged.
app.js's ledGroupSpeed applies the rule to the ranking's rows (main page
and tray panel; the "Other" row sums the new fields), the Output speed
card and the overview's agent/model lists, with a tooltip saying which
it is and how many replies; a ranking by speed orders and bars a
floor-only group by its floor. Strings in en, zh, zh-TW, ja, de;
docs/reference.md says the rule.

Run: TestGroupSpeedSaysHowManyRepliesItIsOf (sol 260 calls, 1 measured
at 125 tok/s; Claude Code 42 calls, 30 floors at 100, a short, a failed
and a gateway row telling none; the page sums; summarize) fails to build
on the old code and goes red with the agent check taken out of
Row.Floor. usage-speed-count.test.cjs (overview, Requests rows, ranking
by tokens and by speed with order, titles and bars, the card for all and
for Claude Code's model alone, no clipping, no sideways scroll) passes in
Chromium and WebKit, en/zh/zh-TW/ja/de at 1400 and 560 px, and fails
against origin/main's assets. Related GUI suites (click-scroll, gui-de,
gui-ja, gui-zh-tw, i18n-keys, ledger-*, panel-usage, reasoning-speed,
routing-burst-speed, usage-*): 389/389 in both engines. go test -tags
nogui ./... (temp HOME) passes; gofmt -l clean; go vet nogui for darwin,
linux and windows on internal/usage and internal/gui. Not tried with
Fallmonkey's own data.
2026-10-11 10:04:15 +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
yetone 6d3bc9183d usage: the Usage and Requests pages count any days picked, from a Custom opt after All that opens a month to pick them on (#1492, nianlee-official)
The period bar had only Today, 7 days, 30 days and All. A Custom opt now
follows them. It opens the app's own menu (no native select): Yesterday,
This month, Last month and 90 days a click away, and a month of days to
pick the first day on, then the last. Days after today can't be picked;
arrows walk the days and Escape closes. Once picked, the opt names the
days ("Oct 1 – Oct 7"), and narrow windows show only its icon until then.

The backend takes the days as period "2026-10-01..2026-10-07", both
included, in the local time zone (usage.RangeOf, Period.Known/Until).
The summary, the Requests page (index and ledger fallback), Direct and the
CSV name count only calls from the first day's midnight up to the
midnight after the last. The chart is an hour each for one day, a day each
up to 60 days, and a week each from a Monday past that. A picked range is
summarised afresh each time, so ranges never pile up in the summary cache.
The credits-per-day card follows the days picked. New strings in zh,
zh-TW, ja and de.

Run:
- go test -tags nogui ./internal/usage ./internal/gui (sandbox HOME): ok.
- TestPickedDaysArePeriod with Until returning zero (no range end):
  FAIL, Summarize 5 calls / QueryPage 5 rows / LedgerOf 5 rows, want 3.
- usage-range.test.cjs, Chromium and WebKit, en and zh, at 390px: 4/4.
- Every GUI test touching period or the Usage view (87 files): Chromium
  388/388; WebKit 386/388, the two purpose-filter's Routing focus check
  (scrollTop off by 1px after a wheel), which then passed 52 of 56 lone
  runs here and 25 of 25 on origin/main; nothing in this change runs on
  the Routing page. gui-de, gui-ja, gui-zh-tw, i18n-keys: pass.
- gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui on both pkgs.
2026-10-10 19:15:12 +08:00
yetone cb406c8425 plugins: a plugin can add an agent magpie has no setup of its own for
Plugins could be subscription providers or gateway middleware. Now a third
kind: an agent plugin, so a user whose agent magpie doesn't ship can still
put it on magpie.

- internal/agentplug: a plugin's magpie.agent module (or a *.agent.js file)
  exports agent = {id, name, config, format?, model, prefix?, bin?, dir?,
  ua?, icon?, notice?} and an optional connect({gateway, model, models,
  agent}) returning the other keys to write. Compiled in moejs, reloaded
  when plugins.json or the file changes; why one didn't load is kept.
- internal/jsmod: module compiling (imports kept inside the plugin), moved
  out of middleware so both share it.
- internal/agent/plugged.go: each becomes an Agent (Plugin set) after
  magpie's own. JSON, YAML and env files are edited key by key, comments
  kept; what each key held is stashed typed under plugin:<id>:<path>, and
  its own model or Disconnect puts every key back. A built-in id is
  refused; a connect that throws writes nothing. Key magpie-<id>; usage
  names it by key or ua (usage.PluginAgents).
- GUI Plugins page: an Agent kind chip and glyph, a Discover "Agents"
  section (market kind "agent"), and an installed row line "Adds X to
  Agents" or why it didn't load. zh, zh-TW, ja, de strings.
- Docs: site Plugins page (en, zh, ja) "Agent plugins", reference.md,
  agent-wiring.md, gateway-middleware.md.

Run:
- go test ./... (all ok); gofmt -l clean; GOOS=linux go vet -tags nogui
  ./... and GOOS=windows go vet ./... clean.
- TestPluggedYAML, TestPluggedJSONUnwire, TestPluggedRefused.
- GUI: plugin-agent.test.cjs 22/22 (en, zh, zh-TW, ja, de; 980 and 420;
  chromium and webkit); all plugin-*.test.cjs, i18n-keys,
  deprecated-subscriptions, filter-ime: 315 pass, 0 fail.
- Real use, in a sandbox HOME: an Aider plugin (~/.aider.conf.yml, prefix
  openai/, connect writes openai-api-base/key) installed in a dev build;
  picking DeepSeek V4.1 Flash on the Agents page wired the file keeping the
  user's comment and keys; real aider 0.86.2 `--message` answered through
  magpie from the real DeepSeek account; usage.jsonl recorded agent aider,
  provider deepseek, 200; Disconnect restored the file byte for byte.
2026-10-10 18:39:47 +08:00