Commit Graph
83 Commits
Author SHA1 Message Date
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
yetone 3e5bc3d8fe gateway, usage: conversation text is kept only under a session the client named, and a client's "request-…" session counts like any other (#1355)
What changed: with recording on, a request that names no session used to
get a made-up "request-…" id and its text saved under it. Nothing listed
that id and GatewaySessionByID turned it away, so the text could never be
opened. magpie now makes up no id: such a request isn't recorded, and the
X-Magpie-Session reply header only echoes the client's own session.

With no made-up ids left, the "request-" prefix checks in appendUsage,
OTel, Usage's sessions, Routing's vias and the gateway Sessions projection
only dropped sessions clients named themselves (appendUsage wiped them from
the ledger). They are gone. The tests that held the old rule now say the
new one, and gateway-sessions.md says it.

Run: TestGatewayConversationNeedsTheClientsSession and
TestGatewayConversationClientRequestPrefixedSession fail on the PR's code
(a made-up id is returned; the ledger keeps 0 of 2 calls) and pass here;
putting appendUsage's prefix check back turns the second red again.
gofmt -l clean; go vet; GOOS=linux and GOOS=windows go vet -tags nogui on
gateway, gui, sessions, settings, usage; go test -race -timeout 900s on
those five: ok (gateway's TestCORSKeyThroughTheServer rerun after its fix).
GUI: gateway-conversations, gateway-mode and all sessions-* tests, 216
cases in Chromium and WebKit: pass.
2026-10-10 04:24:18 +08:00
木子不是木子狸 c9b8263378 sessions, gateway: Sessions lists gateway sessions, and can keep their text on this computer when turned on (#1355, mu-zi-lee)
What changed: the Sessions page lists sessions seen only through the
gateway (from the usage ledger, read-only, a native session of the same id
wins), and shows in gateway mode. A Sessions switch, off by default and
confirmed before it turns on, records each gateway exchange's text under
the config dir (scrubbed, at most 7 days and 256 MiB, cleaned hourly).
Settings sync and restore can't turn it on; POST /api/sessions/recording
turns it on or off and can clear what was kept.

Why: users of magpie as a gateway (gateway mode, LAN clients) had no way
to see their conversations; the owner chose this design on the PR.

Squashed from PR head 6a343ba1 onto origin/main. Conflicts: gui-shell.md
(kept main's placeMenu text, took the PR's Sessions in gateway mode) and
settings_keep_test.go (main's fields plus GatewayConversations).

Run: go build ./..., go vet on gateway, gui, sessions, settings, usage;
go test -race -timeout 900s on those five packages: all ok.
2026-10-10 04:24:18 +08:00
yetone ed31293c0e usage, gui: a reply its vendor let go in a burst over a couple of hundred milliseconds tells no speed, not 2,237 tok/s (John on Discord)
John's Kimi Code rows after v0.1.1119 (OpenCode, group/k3-glm, api.kimi.ai,
Chat, k3-256k): 550 tokens, 22 of them reasoning, in 16 s with the first
content at 5.2 s read 2,237 tok/s, and 395 tokens in 19 s 2,012. 528 answer
tokens at 2,237 tok/s is 236 ms: the burst the vendor let go at the end.
de5455b8 measured how long the content took to come (flow) and took the
window as no longer than it, so a burst sent in one write (flow ~1 ms) fell
under the 100 ms floor and told none, but a burst let go over 236 ms of
many events read its tokens over those 236 ms, under the 10,000 tok/s
ceiling. The time a burst takes to come is not the time it took to write.

usage.DecodeOf now tells no speed for a reply held back and let go at its
end, both ways the burst can show:
- its content came in under a quarter of its window (flow*4 < window):
  the text came early, the tool call it wrote over the rest of the time
  came at the end (window 10.6 s, flow 236 ms);
- it reasoned, and its answer came over 20 times faster than its
  reasoning came between its first content and its first text: the text
  came with the burst, so the window from it is the burst itself (22
  reasoning tokens over 10.5 s, then 528 in 236 ms). Hidden reasoning
  (OpenAI's, Claude's omitted) comes before the first content and leaves
  that time short; streamed reasoning comes at its answer's pace.
Between the two the window is the whole window again, not the flow.
routing.js's decodeOf and app.js's ledDecode do the same; docs/reference.md
says it.

Tests: TestKimiHeldBurstTellsNoSpeed, a fake Kimi Code (Chat: four
reasoning_content deltas, then text and a tool call whose arguments come
as 40 writes 6 ms apart over the last 236 ms; usage 538/550/22), through
the real gateway for a Chat, a Responses and an Anthropic agent, with the
wait shortened (first content 1.3 s, end 4 s): the held call and the held
answer tell none (before: 2,112 to 2,237 tok/s on all three), a steady
50 tok/s answer after the same reasoning keeps ~50. TestKimiHeldBurstAtJohnsTimes
feeds firstToken the same streams at John's times (5.2 s, 16 s): before,
2,138 and 2,237 tok/s. TestJohnsRowsTellNoSpeed: his rows as records
(before: 2,237, 2,237, 2,015). routing-burst-speed and usage-speed gain
his rows and a steady 50 tok/s one; they fail on the old routing.js and
app.js ("2237 tok/s", "2,237 tok/s") and pass now in Chromium and WebKit,
en and zh, with reasoning-speed, routing-request-metrics,
usage-ledger-detail, click-scroll, gui-ja, gui-de and i18n-keys.

Run: go test -tags nogui ./internal/... (golang:1.26.8 in Docker, as a
non-root user: as root, internal/agent's TestAside* write-refusal tests
fail because root ignores the file modes they rely on, unrelated to this);
-race -count=5 of the new and the burst tests; go vet (linux, windows,
nogui) on internal/gateway and internal/usage. Not tried against the real
Kimi Code API: the owner's Kimi Code key answers 403 (subscription has no
access), so how Kimi Code lets the reply go is inferred from John's
numbers; which of the two shapes his rows were is not known, and both are
covered.
2026-10-09 00:10:23 +08:00
yetone de5455b8fe gateway, usage, gui: a reply whose vendor sent its first words and held the rest to send in one burst tells no speed, not 1,367 tok/s (John on Discord)
John's request (OpenCode, a group served by Kimi Code at api.kimi.ai,
Chat) showed 1,367 token/s: its tokens counted over the time from its
first token to its end, though nothing came in between and the rest came
at once. The 100 ms / 10,000 tok/s bounds catch a burst only when the
first content comes with it.

firstToken now reads on past the first text and marks when each content
event's bytes came (one mark a millisecond, up to 65,536 marks and the
8 MB it reads), and flowMs is how long the content took to come from
where the speed is counted: the span from a tenth of its bytes to nine
tenths, scaled to the whole. A steady stream gets about its whole window;
one let go in a burst about 1 ms. It is kept as Call/Try/Route .flow and
usage.Record.flow_ms (and the Requests page's packed rows), and
usage.DecodeOf, routing.js's decodeOf and app.js's ledDecode count no
longer a window than it. A record without it reads as before.

Verified: TestBurstTellsNoSpeed, a fake Chat vendor that sends a word,
waits 600 ms, then 199 words and the end in one write (1,000 tokens), for
a Chat and a Responses agent: no speed; before, 1636 and 1655 tok/s. Its
steady case (a word every 60 ms) keeps 200 tokens over most of its
window. TestCodexBackendBurstTellsNoSpeed is the same through Codex's own
ChatGPT backend (before: 1,000 tokens in 601 ms). TestFirstTokenKinds now
expects the stream read past its first text. Go tests ran on Linux
(golang:1.26 in Docker; this Mac's syspolicyd held new test binaries at
launch). GUI: routing-burst-speed (a route with John's 5.1 s first token,
6.7 s and a 2 ms flow: was "1367 tok/s", now none) and usage-speed (a row
with flow_ms 2 shows "—") fail without the JS change and pass with it,
with reasoning-speed, routing-request-metrics and usage-ledger-detail, in
Chromium and WebKit (en/zh, ja/de where the tests have them); no strings
changed. Not reproduced with Kimi Code itself: whether it holds the
stream so is inferred from the numbers.
2026-10-08 20:11:05 +08:00
forever e961836fb0 usage, gateway, gui, provider, cli: the tests pass when a run crosses midnight, and a usage answer reads the clock once (#1046)
* usage: the usage tests pass at any time of day, midnight included

The usage tests stamped their calls with the machine's time and then
asked for today, 7 or 30 days, or a cached answer, which the code
worked out from its own time.Now a moment later. A minute after
midnight a call made "a minute ago" was yesterday's, and when midnight
fell between the test's read and the code's, the call and the period
were of two days. magpie usage, the TUI's Usage page, the two Codex
cache-write tests and the computers' shared days failed in the first
minutes after midnight (the TUI's after midnight UTC, the zone its
package's tests run in since 1caea638), and 28 more failed when
midnight fell inside them.

usage.Clock is now the time every period is read by: the start of
today, 7 days and 30 days (LedgerOf, Summarize, Direct, QueryPage), the
hours or days of the chart (LedgerSeries, QueryPage), the day a cached
summary or page is for, the time Append gives a call that has none,
the days davsync shares and the date in an exported CSV's name. It is
time.Now, as before, and a variable for the tests, like LogCalls. Each
test that built its calls from the time now holds Clock at noon on
2026-09-30 (holdClock; holdUsageClock in gui and the CLI; three lines
in tui and davsync) and stamps its calls from that instant, among them
TestReasoningReplyTimedByItsAnswer, whose timeline rows 117b6c7f made
at time.Now. TestPeriodsReadTheClock checks that every one of these
reads goes through Clock. TestQueryPageSourceAndIdentityInvalidation is
held too; that it fails when run alone is fixed apart from this, in
#1045.

Seven held tests could not fail at midnight before, and are held so
that the tests read one clock: TestUsageSameSizeAndMtimeRewrite (All's
totals), TestDirectCountsOnlySessionFileCalls (30 days around its own
noon), TestQueryPageIOOutsideCacheLock (a file two days old), gui's
TestUsageLedgerDayRoutes (7 days hold its calls from either day),
TestLedgerSingleSnapshotAndLocalSession and
TestLedgerNamesModelAtProvider (their calls are stamped after the code
reads the time), and TestUsageRawAndPricedChunksShareBudget, which
fails only when the midnight in it starts a new week of All's chart, on
a Sunday night; at.sh sets the time of day and not the weekday, so that
one was not shown.

Verified with at.sh, a scratch script that runs a test binary under a
zone made with zic, so that the local time of day is the one asked for
as the run starts (HOME in a sandbox, Go's caches pinned). The runs were
first made on c5a54bc7, and those marked (698da36f) again on 698da36f,
with the same results. The tui package runs in UTC since 1caea638, a
zone at.sh doesn't move, so its runs on 698da36f used copies of both
trees whose TestMain keeps the zone TZ sets.

Before, at 00:00:30, 00:01:30 and 12:00:00 (698da36f):
  TestUsageShowsCallsNotThroughMagpie, 00:00:30:
    usage_cli_test.go:95: no calls today · route an agent through
    magpie and its usage shows up here
  00:01:30: "5 tokens today · 1 call · no price", without the calls
  not through magpie; TestUsagePageShowsCallsNotThroughMagpie (tui)
  fails the same two ways at usage_test.go:138
  --- FAIL: TestCodexCacheWriteNotInInput (00:00:30)
    codex_cache_write_test.go:104: rows []
  --- FAIL: TestCodexCacheWriteMatchesGatewayCall (00:01:30)
    codex_cache_write_test.go:73: filter {...}: 0 rows, 0 calls, want
    the gateway's 2: []
  --- FAIL: TestUsageSharedBetweenComputers (00:01:30)
    usage_share_test.go:134: a's days on the server:
    [...-2026-10-05 ...-2026-10-06 ...-2026-10-07]
  12:00:00: PASS

Midnight inside a test, in scratch copies of the head. Started at
23:59:59.3 with the code's first period read held 1.5s, so that it
reads after midnight what the test stamped before it, 16 usage tests,
3 gui tests and TestUsageCSV FAIL, among them
  ledger_test.go:257: today: 0
  review_test.go:69: chart counted 0
  incremental_log_test.go:202: concurrent append lost
  TestCachedSummaryRemainsCallerOwned: panic: runtime error: index out
  of range [0] with length 0
  usage_test.go:121: second page: {... Period:today Rows:[] ...
  Total:0 ...}
  usage_test.go:311: "": magpie-requests-7d-2026-10-06
Started at 23:59:55 with the test waiting past midnight between two of
its reads, 7 more FAIL:
  request_day_test.go:45: selecting a day changed the chart or its
  legend
  cache_bounds_test.go:84: uncached today summary stale
  growing_rewrite_test.go:71: today summary stale
  cache_bounds_test.go:153: page key changed instead of exercising the
  same cache
  priced_blocks_test.go:55, caller_provider_test.go:129 and :172: page
  differs
TestReasoningReplyTimedByItsAnswer, with a scratch 1.5s sleep before
its LedgerSeries, started at 23:59:59.3 (698da36f):
  usage_test.go:255: part: {Calls:0 Tokens:0 Cost:0 Timed:0 TTFT:0
  DecodeMs:0 DecodeOut:0}

After: the same at.sh runs PASS at 00:00:30, 00:01:30 and 12:00:00
(698da36f); the same scratch copies made of this change PASS, each
test taking 1.5s or 5.2s, so midnight did fall inside it (698da36f for
TestReasoningReplyTimedByItsAnswer's); and every changed test PASS at
23:59:59.9, 00:00:30 and 12:00:00 (698da36f).

Without the change (698da36f): with the reads put back on time.Now, 21
usage tests, 6 gui, 2 CLI, the tui and the davsync test fail, among
them
  --- FAIL: TestPeriodsReadTheClock
    clock_test.go:55: Direct(Today): 0 calls since 2026-10-06 00:00:00
    -0700 PDT, want 1 since 2026-09-30 00:00:00 -0700 PDT
    clock_test.go:63: Summarize(Today) the next day: 1 calls, want 0
  --- FAIL: TestReasoningReplyTimedByItsAnswer
    usage_test.go:255: part: {Calls:0 Tokens:0 ...}
Each of the eleven reads put back alone fails a test:
TestPeriodsReadTheClock for the nine in usage (LedgerSeries:
"clock_test.go:52: LedgerSeries(Today): 0 calls, want 2"; the page's
cache key: "clock_test.go:66: QueryPage(Today) the next day: 1 rows,
want 0"), TestCSVStamp for the CSV's name (usage_test.go:325: "":
magpie-requests-7d-2026-10-06) and TestUsageSharedBetweenComputers for
davsync (usage_share_test.go:224: all computers: 4 rows, 707 in; want
5, 737).

On this commit: go test -tags nogui -count=1 . ./internal/usage
./internal/tui ./internal/davsync ./internal/gui ok; -race -count=20
over the changed tests of each of these packages ok; gofmt -l prints
nothing, and go vet -tags nogui on the five packages finds nothing.

* usage: pages, CSVs and magpie usage asked at midnight show one day

An answer about usage read the time more than once. The Requests page
read it for the day it is kept for, for the period its log and session
files are read over, for the period of its rows and for its chart's
hours; the page from the ledger (QueryPage's path when LogCalls is
set, as in the tests) for its rows and for its chart; Direct for its
period and for its rows; a CSV for its rows and for its name;
magpie usage and the TUI's Usage page for Summarize and then for
Direct. Most of these reads have the log and the session files read
between them, seconds on a large log, and when midnight fell between
two of them the answer was of two days: yesterday's calls listed over
today's empty chart, Direct starting yesterday and counting none of
yesterday's calls, the calls not through magpie left out of magpie
usage and the Usage page (they were the new day's, none yet), and
yesterday's calls saved as magpie-requests-today-<the new day>.csv.

Each answer now reads Clock once and passes that moment down. queryPage
reads it for its key, its sources, its rows and its chart
(buildRequestBlocks takes it); the page from the ledger reads its rows
and its chart at it (LedgerOfAt, ledgerSeriesAt); Direct reads the
ledger at the moment of its period. usage.Summaries(p) is Summarize(p)
and Direct(p) at one moment, and magpie usage and the TUI's Usage page,
when a period is picked and when it is read again, ask for it: one
exported name, the clock left inside usage and one line changed at
each caller, where SummarizeAt and DirectAt would be two names and
each caller would read the clock itself. The CSV download and export
read their rows with the new usage.LedgerOfAt at the moment their file
is named for, which csvStamp now takes; the rows and the name are read
in two packages, so LedgerOfAt is exported. LedgerOf, LedgerSeries,
Summarize, Direct and QueryPage keep their signatures, each reading
Clock once.

The new tests set Clock to read a tenth of a second before midnight
the first time and a tenth of a second after it from then on, set
again for each answer. The midnight is the one that starts 2026-10-01,
local time: a past instant, at midnight because that is what is
tested, and the day before it is the 2026-09-30 the held tests use.
TestAnswerReadsTheClockOnce asks QueryPage(Today) from the indexed log
and from the ledger: its 3 rows, one from a session file written that
day at 23:00, are under that day's chart, and asked again after
midnight the page is the next day's, not the one kept for the day
before; Direct(Today) counts the call and starts that day.
TestUsageAskedAtMidnight (magpie usage today), TestUsagePageAtMidnight
(the TUI's Usage page, today picked and read again) and
TestUsageCSVAtMidnight (download and export) check that the calls
through magpie and those not through it, or the rows and the file's
name, are of the day asked on. TestCSVStamp passes its time.

Verified on the previous commit, at.sh as there. The runs were first
made on c5a54bc7, when the tui package's tests still ran in the local
zone, and those marked (698da36f) again on 698da36f, with the same
results.

Before: the new tests on the previous commit, at any time of day
(at.sh at 12:00:00 too) (698da36f):
  --- FAIL: TestAnswerReadsTheClockOnce
    clock_test.go:131: QueryPage(Today): 0 rows, 0 in a chart from
    2026-10-01 00:00:00 -0700 PDT; want 3 under one from 2026-09-30
    00:00:00 -0700 PDT
    clock_test.go:141: QueryPage(Today): 3 rows, 0 in a chart from
    2026-10-01 ...; want 3 under one from 2026-09-30 ...
    clock_test.go:145: Direct(Today): 0 calls since 2026-09-30
    00:00:00 -0700 PDT, want 1 since 2026-09-30 00:00:00 -0700 PDT
  --- FAIL: TestUsageAskedAtMidnight
    usage_cli_test.go:154: 5 tokens today · 1 call · no price ...,
    with no part for the calls not through magpie
  --- FAIL: TestUsagePageAtMidnight
    usage_test.go:184: today picked: ... (the same)
    usage_test.go:187: read again: ...
  --- FAIL: TestUsageCSVAtMidnight
    usage_test.go:367: download: 200, attachment;
    filename="magpie-requests-today-2026-10-01.csv" with 2 rows
    (<nil>), want magpie-requests-today-2026-09-30.csv with 2
    usage_test.go:378: export: 200
    {"path":"~/Downloads/magpie-requests-today-2026-10-01.csv",
    "rows":1}, want magpie-requests-today-2026-09-30.csv with 1 row

With the real clock, in scratch copies of both trees: scratch tests
held one of Clock's reads 1.5s after it was made, as reading a large
log does (the first; for one of them the page's third, its chart's),
and at.sh started each at 23:59:59.3. Before, all 9 FAIL, among them
  asked 23:59:59.564, answered 00:00:01.068
  Direct(Today): 0 calls since 2026-10-05 00:00:00 -0940 MID, want 1
  since 2026-10-05 00:00:00 -0940 MID
  QueryPage(Today): 2 rows, 0 in a chart from 2026-10-06 ...; want 2
  under one from 2026-10-05 ...
  download: attachment; filename="magpie-requests-today-2026-10-06.csv"
  with a call of 2026-10-05 23:59
After, all 9 PASS, answered at 00:00:00.9 to 00:00:01.0, so midnight
fell inside each, except the chart's: its held read is gone with the
change. A scratch sleep before the chart shows that one: before "2
rows, 0 in a chart from 2026-10-06", after PASS, asked 23:59:59.344
and answered 00:00:00.941. At 12:00:00 all of them PASS in both trees.

After: every changed test PASS with at.sh at 23:59:59.9, 00:00:30 and
12:00:00 (698da36f).

Without the change (698da36f): with the production put back to the
previous commit's (gui/usage.go only so far that TestCSVStamp compiles:
csvStamp takes the time, read apart from the rows as before), go test
-count=1 . ./internal/usage ./internal/tui ./internal/gui fails the four
new tests and no other, with the lines above. Each of the 16 places put
back alone fails one of them: the page's key (clock_test.go:134: "3
rows, 3 in a chart from 2026-09-30 ...; want 0 under one from 2026-10-01
..."), its sources (:131: "2 rows"), its rows (:131: "0 rows"), its
chart (:131), the ledger page's rows and chart (:141), LedgerOfAt (:141,
:145), ledgerSeriesAt (:141), Direct (:145); Summaries, indexedSummary
and magpie usage (usage_cli_test.go:154); Summaries and the TUI's period
key and reload (usage_test.go:184, :187); the CSV's download and export
(usage_test.go:367, :378).

On this commit: go test -tags nogui -count=1 . ./internal/usage
./internal/gui ./internal/tui ./internal/davsync ./internal/gateway ok;
-race -count=20 over the changed tests of each package ok; gofmt -l
prints nothing, and go vet -tags nogui finds nothing.

* gateway: the key-limit tests pass when a run crosses local midnight

A go test run that crossed local midnight could fail the gateway's
key-limit tests. keyLimited and the /v1/magpie/limit endpoint each read
time.Now() when they check a key, and access.Window turns that into a
calendar window (a day from midnight, a week from Monday, a month from
the 1st). The tests seed "yesterday" from their own time.Now() and then
make several calls, so a run that crossed midnight saw its calls split
over two windows: the second call of a 350-token day was let in, or a
restart counted nothing.

The gateway's key-limit path now reads limitClock, a variable for the
tests like ruleClock and idClock, and production behaviour is unchanged
(it is time.Now). TestKeyLimitRefusesBeforeUpstream,
TestKeyLimitHoldsParallelRequests and TestKeyLimitWindowResets pin it
at 2026-09-30 12:00 local and seed "yesterday" from that instant. Calls
are still recorded at the real time, after the pinned one, and a window
counts every call from its start, so they all count in the pinned
window; the "tomorrow's window" check in TestKeyLimitWindowResets stays
on the real now, the first window with none of those calls in it. No
other test sets a key limit with records in its window (the gateway-key
CLI test and the GUI caller-key tests count 0 calls or have no limit).

TestKeyLimitRefusesBeforeUpstream now also checks that the 429's
Retry-After and X-Magpie-Limit-Reset name the next midnight after the
check, and that the limit endpoint's week starts on the pinned
Monday.

Verified with at.sh, a scratch script that runs the test binary under
a zone made with zic, so that the local time of day is the one asked
for as the run starts:
- before, at.sh at 23:59:59 with COUNT=500/300 and FRAC 0.3/0.6/0.8:
  3 of 6 runs of each test failed with
  key_limit_test.go:217: spent key let in
  key_limit_test.go:117: a restart forgot what the key used 200
  key_limit_test.go:121: status &{Period:day Start:2026-10-06 ...
  Calls:0 Tokens:0 ...}
- after, the same 6 runs (COUNT=500, both tests) print PASS, and so do
  ^TestKeyLimit at 12:00:00 and 00:00:00 with COUNT=20.
- go test -tags nogui -count=1 ./internal/gateway: ok (79.5s);
  -race -count=20 -run '^TestKeyLimit' ./internal/gateway: ok.
- gofmt -l prints nothing; go vet -tags nogui ./internal/gateway is
  clean.

The month boundary (TestKeyLimitHoldsParallelRequests) and Monday can't
be reproduced by changing the time of day; the pinned clock covers them
the same way.

Fails without the change (tests pinned, keyLimited back on time.Now):
--- FAIL: TestKeyLimitRefusesBeforeUpstream
    key_limit_test.go:107: headers map[... Retry-After:[80228]
    X-Magpie-Limit-Reset:[2026-10-07T00:00:00-07:00] ...]
and with only the limit endpoint back on time.Now:
--- FAIL: TestKeyLimitRefusesBeforeUpstream
    key_limit_test.go:159: limit endpoint {... "period":"week",
    "start":"2026-10-05T00:00:00-07:00" ...}

* gateway: the routing history tests pass when a run crosses midnight

TestHistoryKeepsDaysAndDropsOld and TestRemoteMagpieGroupHistory took
now := time.Now() and saved routes at now and now+1s. saveRoute files a
route by its own day (r.Time.Local()), so a test started at 23:59:59 put
the +1s route in tomorrow's file and History(today) found one route
less. TestHistoryKeepsSessionAndTokenTiers raced the other clock:
saveRoute prunes by time.Now(), so when the day turned between the
test's time.Now() and the first saveRoute, the prune gzipped "today"
after the first route, the second went to a new .jsonl, and the test's
own pruneHistory gzipped that over the first .gz, losing route 1.

saveRoute now prunes by historyClock (time.Now outside the tests). The
three tests take historyNoon(t), which holds that clock at
2026-09-30 12:00 local and returns it as their now, restored with
t.Cleanup. Every route, day file and prune is then on that one past day.
The fixture can't be a fixed past day without the clock: pruning by
the real today gzips that day's file at once (and, a month on, drops
it as too old).

The other history tests keep the real clock:
TestHistoryRouteOutsideDayLimit writes its day files itself from one
now and the code under test reads no clock, and
TestHistoryRouteDayAndNoLock already uses a fixed day.

Verified with at.sh, a scratch script that sets the local time of day
through a zone made with zic as the run starts:
- before, at.sh ./internal/gateway at 23:59:59:
  --- FAIL: TestHistoryKeepsDaysAndDropsOld
      history_test.go:50: days [{2026-10-06 1} {2026-10-05 1} {2026-10-04 1}]
  --- FAIL: TestRemoteMagpieGroupHistory
      remote_group_served_test.go:144: routes [... only ID 1 ...]
  and, with a 2s sleep after now := time.Now() standing in for the turn
  of the day, --- FAIL: TestHistoryKeepsSessionAndTokenTiers
      history_test.go:22: compressed history lost accounting: [only ID 2]
  12:00:00 control: PASS.
- after: the three tests PASS at 23:59:59, 23:59:59.9 (FRAC=0.9),
  12:00:00, and 23:59:59 with the same 2s sleep; all TestHistory* and
  TestRemoteMagpieGroupHistory PASS at 23:59:59 with -test.count=3.
- with saveRoute pruning by time.Now() again (the fixtures still pinned),
  at any time of day:
  --- FAIL: TestHistoryKeepsSessionAndTokenTiers
      history_test.go:32: compressed history lost accounting: [only ID 2]
- go test -tags nogui -count=1 ./internal/gateway: ok;
  -race -count=20 on the three tests: ok; gofmt -l and
  go vet -tags nogui ./internal/gateway print nothing.

* gateway, davsync: the request archive tests pass when a run crosses UTC midnight

The archive names a call "<date>/<id>" from the call's own start, in
UTC (archiving in archive.go). TestArchiveOn read time.Now().UTC()
before posting and TestRequestArchiveToS3 read it before post(), and
each expected that read's date. A run where UTC midnight (17:00 PDT)
fell between the test's read and the request's start expected the day
before the one the archive used, and failed.

Both tests now take the date from the Time the call carries
(s.Recent()[0].Time, the same start the archive's name is made from),
in UTC, so nothing is read from the clock a second time. No production
code changes. The other archive tests already go by the call's Archive
name, and internal/gui's archive test uses a fixed name; no other test
in internal/gateway, internal/davsync or internal/gui predicts an
archive key or a UTC-dated name from its own clock.

Verified: at.sh only moves the local time of day, and this is a UTC
crossing (UTC midnight was ~16h away), so it was shown in a scratch
copy whose serve starts each request 0.2s after the next UTC midnight,
as a request does when the test read the clock just before it. There
the old tests fail:
  archive_test.go:115: call archive "2026-10-07/000000-f4690de23ee8a859",
  want "2026-10-06/000000-f4690de23ee8a859"
  archive_test.go:93: nothing at
  "team x+y/magpie/archive/2026-10-06/000000-0e74a87816ef6a56.json"
and the new ones pass. Unshifted, under at.sh at local 23:59:59,
00:00:00 and 12:00:00, both pass, as the old ones do at 23:59:59 and
00:00:00 (local time doesn't enter the name). With archiving naming by
start.Format (local) instead of start.UTC().Format, both new tests fail
under at.sh at local 23:00:00, where the local date is a day behind
UTC's:
  --- FAIL: TestArchiveOn ... archive_test.go:116: call archive
  "2026-10-05/082500-7322712bd89f71da", want
  "2026-10-06/082500-7322712bd89f71da"
  --- FAIL: TestRequestArchiveToS3 ... archive_test.go:95: nothing at
  "team x+y/magpie/archive/2026-10-06/082500-3587ab4192da2cd5.json"
and pass at 12:00:00. go test -tags nogui -count=1 ./internal/gateway
./internal/davsync passes in a sandbox HOME; -race -count=20 -run
'^(TestArchiveOn|TestRequestArchiveToS3)$' passes; gofmt -l and go vet
-tags nogui on both packages are clean.

* gui: TestWhatsNewTodayRoute passes when the run crosses local midnight

TestWhatsNewTodayRoute posts {"on":true} to /api/whatsnew/today, which
writes today() to whatsnew-quiet-day, then checks quietToday(), which
compares the file with a second today(). A run that crossed local
midnight between the two read different days and failed with
"on: 204 false". The neighbouring TestWhatsNewQuietAfterRestartToUpdate
already pins today; this test didn't.

The test now pins today to 2026-09-30 (restored with t.Cleanup), so the
post and the check read the same day. The other What's new tests start
from an empty folder, so quietToday finds no file and never reads
today().

Verified: with a temporary 1s sleep between the post and the check, the
unpinned test under at.sh (local time of day set by a zone) started at
local 23:59:59.5 failed with "whatsnew_test.go:237: on: 204 false" and
passed at 12:00:00; pinned, it passes at 23:59:59.5 (same sleep), and,
without the sleep, at 23:59:59, 00:00:00 and 12:00:00. With
setQuietToday writing time.Now().Format("2006-01-02") instead of
today(), the test fails: "--- FAIL: TestWhatsNewTodayRoute ...
whatsnew_test.go:239: on: 204 false". go test -tags nogui -count=1
./internal/gui passes in a sandbox HOME; -race -count=20 -run
'^TestWhatsNewTodayRoute$' passes; gofmt -l and go vet -tags nogui
./internal/gui are clean.

* provider: TestZCodeStartSentAsTheApp passes when the run crosses midnight

A ZCode Start Plan request opens with a context prefix that says
"Today's date is <day>" (zcodeDateReminder), the day zcodeStartRequest
took from its own time.Now(). TestZCodeStartSentAsTheApp sent the
request, then built the expected prefix from a second time.Now(). A run
that crossed midnight between the two failed on "the context prefix",
the request holding the day before.

zcodeStartRequest now takes the time from zcodeClock (a package
variable, time.Now outside tests, as gateway's ruleClock), and the test
pins it to 2026-09-30 12:00 local, restored with t.Cleanup, and expects
"Today's date is 2026-09-30." The test sets TZ=Asia/Shanghai, which
moves time.Local only when nothing has read it yet; a mid-day instant in
time.Local formats to the same day either way. The other calls to
zcodeStartBody in the test check shaping only, not the day.

No other provider test builds a day string from a second clock: the
WorkBuddy credits, daily warm-up and check-in tests pass fixed times to
code that takes now as an argument, and TestQoderCheckinOnTheCard's day
is only carried, not compared.

Verified with at.sh (local time of day set by a zone, run as
-run '^(TestDailyCredits|TestZCodeStartSentAsTheApp)$' so that
time.Local is read before the test's t.Setenv("TZ"), as in a full run;
alone, Local becomes Asia/Shanghai): with a temporary 1s sleep after the
request, the unpinned test started at local 23:59:59.5 failed with
"zcode_client_test.go:195: the context prefix: ... Today's date is
2026-10-05." and passed at 12:00:00; pinned, it passes at 23:59:59.5
(same sleep) and, without the sleep, at 23:59:59, 00:00:00 and 12:00:00.
With zcodeStartRequest back on time.Now(), the pinned test fails:
"--- FAIL: TestZCodeStartSentAsTheApp ... zcode_client_test.go:196: the
context prefix: ... Today's date is 2026-10-06." go test -tags nogui
-count=1 ./internal/provider passes in a sandbox HOME; -race -count=20
-run '^TestZCodeStartSentAsTheApp$' passes; gofmt -l and go vet -tags
nogui ./internal/provider are clean.

* accounts, quota: a window's reset reads against one time per listing; TestQuotaCell passes across midnight

quotaCell, a window in `magpie accounts` and `magpie quota`, read the
clock three times: whether the reset had passed, how long until it, and
ResetClock's label, which names the calendar day ("tomorrow 02:13" or
"02:13"). TestQuotaCell set the reset 2h13m30s from time.Now() and
built the expected label from yet another time.Now(); a run that crossed
local midnight between quotaCell's read and the test's got "tomorrow
02:13" from one and "02:13" from the other and failed.

quotaCell now takes now. accountsCmd and quotaCmd take one time.Now()
just before printing and pass it to every window's cell, so a listing's
windows agree on what "today" is. The test passes a fixed 2026-09-30
12:00 local and expects "↻2h13m 14:13", and for a reset the next day
"↻14h13m tomorrow 02:13"; no zone in tzdata 2026c changes its clock
between those instants, so both read the same in any TZ. resetsCell's
label, quotaReadingCell's expired check and quotaResetCmd's prompt
still read time.Now(); no test compares them against a second clock.
internal/tui's quotaCell and quotaLines already take now, and their
tests pass a fixed one.

Verified with at.sh (local time of day set by a zone): with a temporary
1s sleep between quotaCell and the check, the old test started at local
23:59:59.5 failed with "accounts_cli_test.go:128: \"5h 42% ↻2h13m
tomorrow 02:13\"" and passed at 12:00:00; the new one passes at
23:59:59.5 (same sleep) and, without the sleep, at 23:59:59, 00:00:00
and 12:00:00. Putting any of quotaCell's three reads back on the wall
clock fails the test ("--- FAIL: TestQuotaCell"). ResetClock's now
alone fails the next-day case: "accounts_cli_test.go:134: tomorrow:
\"7d 42% ↻14h13m 02:13\"". The passed check alone, or all three:
"accounts_cli_test.go:129: \"5h 42% · reset time passed Sep 30
14:13\"". untilShort alone: "accounts_cli_test.go:129: \"5h 42% ↻now
14:13\"". go test -tags nogui -count=1 . passes in a sandbox HOME;
-race -count=20 -run '^TestQuotaCell$' passes; gofmt -l and go vet
-tags nogui . are clean.
2026-10-07 02:14:29 +08:00
yetone e6dd5d20bb usage, gateway, gui: a reply that reasoned is timed by its answer, from its first text, not by all its output from its first token (tony on Discord #general: Usage › Requests read "gpt-6.1-sol 163 token/秒 · 8,036 个请求 · 首字 14 秒" and asked whether subagents were added up) — speed was every output token over the time after the first content (text, reasoning or a tool call). Output counts the reasoning, and a model whose reasoning is hidden (OpenAI's encrypted reasoning, a summary sent when it is done, Claude's omitted thinking) writes it before the stream shows anything, inside the TTFT; so a 2,000-token think and a 200-token answer over the 1.5 s after the first token read 2,200 in 1.5 s, 1,467 tok/s. Concurrency was not the cause: the aggregate is Σ tokens over Σ per-request windows, so subagents running at once never add up. In the owner's own usage.jsonl codex/gpt-6-luna turns read up to 600 tok/s (out 496, reasoning 224, 11,055 ms, ttft 10,228) and its aggregate 133; it is 80 now. usage.DecodeOf is the one rule: a reply with reasoning counts out − reasoning over ms − firstText, one that reasoned and wrote only tool calls tells no speed, one without reasoning is timed from its TTFT as before; DecodeWindow's burst cut (#731) still applies. Record.Decode feeds summarize, the ledger's Totals and its timeline Parts; a route keeps its reply's reasoning (Route.Reasoning, from gateway.go and codex_backend.go), and routing.js's decodeOf/speedOf times its rows, the story and a session's average by it (an older route takes its served usage's reasoning); app.js's ledDecode does the Usage page's rows, whose tooltip says the reasoning left out, and the Output speed help says the rule, in en, zh, ja and de. History is read the same way, as it keeps the reasoning and the first text. Routing never ranks by speed. TestReasoningReplyTimedByItsAnswer (the 2200/2000 turn, a summary 10 ms before the text, a concurrent subagent, tool calls only, reasoning over output, no reasoning, not streamed: 1,200 tokens in 11 s through summarize, addRow, LedgerSeries and Decode) fails without the change and passes -race -count=10; TestUsageKeepsTimeToFirstToken now has its paced replies report reasoning and checks the route keeps it. reasoning-speed.test.cjs (Routing rows 133, 100, none and 100, the story never 1,467, the session 105; the Usage rows, tooltip and KPI the same; no sideways scroll) passes on Chromium and WebKit in en, zh, ja and de, and fails against the old assets (1467 tok/s); routing-request-metrics, routing-burst-speed, usage-speed, usage-ledger-detail, i18n-keys, gui-ja, gui-de, ledger-hscroll and click-scroll pass on both. go test -race -tags nogui ./internal/... under a temp HOME passes but internal/proc's TestUserPath ("the login shell's PATH never came"), which failed under the full run's load, passes 3/3 alone and is not touched here; go vet, gofmt -l, linux and windows (nogui) builds pass. Not tried with tony's data. docs/reference.md says how output speed is counted. 2026-10-06 19:47:56 +08:00
yetone c5b57b9077 gateway, usage, gui: a relay's reply of tool calls ended "end_turn" or "tool_calls" goes on to the calls, a tool_use whose start carries its input keeps it, an Anthropic stream that just stops is an error, and every request says its protocol and the upstream's stop reason (蓝猫 on Discord)
蓝猫's custom Anthropic-protocol provider in front of Grok ended the agent's
turn a few words in with no error, where Alma on the same endpoint ran on.
Replayed from a fake upstream, three ways an Anthropic-shaped relay's
stream was read wrong when magpie translated it for an agent of another
protocol:

- a reply of tool calls whose stop_reason said end_turn, stop or OpenAI's
  tool_calls was handed on as finish_reason "stop": the agent ended its
  turn instead of running the calls. stopFromAnthropic takes tool_calls,
  function_call, length and content_filter; collector.finish makes a
  "stop" beside tool calls "tool".
- a tool_use block whose content_block_start carries its whole input,
  with no input_json_delta after, lost the input (the call went with {}).
  anthropicDecoder emits it, and skips deltas for that block after.
- a stream that ended cleanly with no stop_reason and no message_stop was
  finished as a whole reply. streamTranslated now takes it as cut: asked
  to go on where it can, else ended with "the reply ended before it was
  complete", as the passthrough already did.

Each request now keeps the upstream's own stop reason (Usage.Stop /
usage.Record.stop: stop_reason, finish_reason, a Responses status), from
the passthrough's sniffer and the translated stream, shown as "Upstream
stop reason" in a request's details on Usage › Requests. Each row there
is tagged with the protocol it was sent upstream in, "Chat → Anthropic"
when translated, told from its endpoint, so older rows have it too; the
details say Protocol. en/zh/ja/de, no left border, no select, a click
moves nothing.

relay_stop_test.go's four tests fail without the change (finish_reason
"stop" for tool calls under end_turn/tool_calls/stop, arguments "" for a
whole-input start, a cut stream finished "stop", no stop recorded) and pass
with it; the passthrough case sends "data:" without a space and CRLF.
ledger-protocol.test.cjs passes in Chromium and WebKit, en and zh.
go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test
-tags nogui ./... under a temp HOME pass.
2026-10-05 22:47:21 +08:00
yetone 71d2da1f42 catalog, usage, gateway, gui: a price can have a long-context tier and a 1-hour cache write, and the price boxes take decimals (PAMI on Discord)
OpenAI bills gpt-6-astra, gpt-6.1-sol and gpt-6-luna over 272K input at 2× input and cache and 1.5× output, for the whole request. A price now has tiers: `magpie model price <m> 10,50,1,12.5 --tier 272k 20,75,2,25` (--tier can repeat). A tier applies when input + cache reads + cache writes is over its size, so 272,000 is not over and 272,001 is. The built-in prices take tiers only where models.dev lists one (cost.tiers of type "context"), and it does list one for those three. The ledger, each request and OTLP are costed at the tier the call reached. Session and day totals sum many calls, so they stay at the base price.

Anthropic bills a cache write kept for an hour at 2× input and one kept for 5 minutes at 1.25×. Its usage reports which is which in cache_creation.ephemeral_5m/1h_input_tokens. The gateway (API and Claude subscription) and Claude Code's transcripts now keep that split. A price's fifth part is the 1-hour write. When it isn't given, it is 2× input: that is Anthropic's rule, and only Anthropic reports 1-hour writes. Claude list prices carry the 2× too. cache_write_tokens is still the total, and the usage CSV adds cache_write_5m_tokens and cache_write_1h_tokens at the end. The app shows the split on a request's Cache and on the usage tooltips. Old prices and old records, which have no 1-hour part, read as before. The sessions cache (18) and the call cache (calls-v8) are re-read once.

In the GUI, the price boxes were number inputs and dropped what they didn't parse ("0,25"). They are now decimal text boxes that take both "0.25" and "0,25". A model's price row has a 1-hour box (empty means 2× input) and a quiet Long-context price row. That row shows the list's tier greyed in, or sits behind a link when the list has none. A bad size is refused by name. en/zh/ja/de.

Tests:
- New: TestPriceTiers, TestCostSplit, TestPriceJSON, TestModelPriceTiers, TestModelPriceTierCmd, TestAnthropicCacheWriteSplit and TestClaudeCacheWriteSplit. The ledger CSV test expects the new columns.
- model-price-tiers.test.cjs is new; model-price-edit and provider-price-rate are updated. All of them fail against the old assets and pass in WebKit. Chromium couldn't be launched here.
- go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
2026-10-05 21:56:59 +08:00
yetone e5981040dc gateway, gui: a request an aggregator passed on says which provider answered it behind it, "Upstream: DeepInfra" (leslie_luo on Discord: 像 CPA 那样指出实际供应商) — through OpenRouter a request was only "OpenRouter · deepseek/deepseek-chat", with no word of the provider (DeepInfra, StreamLake, Novita…) OpenRouter had sent it on to. OpenRouter names it in its replies, as tried with the owner's real key: Chat's body and every chunk of its stream have a top-level "provider", Messages' body has one and its stream's message_start a message.provider; its Responses replies and every reply's headers name none. The gateway now reads it (upstreamOf) from a body relayed as it came and from each event of one it translated, Chat, Messages or Responses, streamed or not, and keeps it on the request's try and route (upstream) and in the usage ledger (Record.Upstream; the CSV export's last column, searched as the rest). The Routing page's Requests list says Upstream: DeepInfra beside where it went, giving way after the provider's name when short of room, with its story saying the aggregator passed it on; a request's details on the Usage page have Upstream provider. A reply naming none says nothing. zh, ja, de strings. ClinePass and Cline weren't tried (no account); Vercel's gateway documents no such field in its replies, and a vendor whose reply has a top-level "provider" string is read the same way. In a sandbox magpie with the owner's real OpenRouter key: Chat, Messages and Responses (translated to Chat), streamed and not, all six said StreamLake in the trace, the ledger and on the Routing page. TestUpstreamRecorded (6 paths × streamed or not: the route, its try, Recent and the ledger) fails on the old code, TestUpstreamOf; routing-upstream.test.cjs (Chromium and WebKit, en and zh: the tag inside its row, the story, the Usage details, a click moves nothing, no left-border accent) fails on the old assets. ledger-hscroll, request-archive-usage, usage-ledger and usage-ledger-detail pass on WebKit; routing-served fails the same on origin/main (its swap wording). go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass but for TestTranslatedStreamKeepsClientAlive, which passes alone 5 times here and on origin/main. 2026-10-05 14:08:08 +08:00