Commit Graph
326 Commits
Author SHA1 Message Date
yetone 059d995d56 gateway keys: the list reads the ledger once for all keys, and a proxy's web page is said by its title (aiandcloud on X)
aiandcloud (2.98B tokens, 12,654 requests a day, server mode behind a
proxy) saw Gateway keys draw a Cloudflare 524 page as raw HTML.

Slow list: every poll of /api/caller-keys read up to a month of ledger
rows once per window per key. budget.AllOf now reads each distinct window
once for all keys, and keeps the settled blocks' sums with a cursor
(usage.VisitFrom), so a poll only reads what was appended since; the
unfinished tail block is always read again. A rewritten or shorter log
resets the cursor. All(k) is AllOf of one key.
Numbers (BenchmarkAll vs BenchmarkReadEach, 8 keys x day/week/month,
31 days x 12000 rows/day = 372k rows, warm): 211-228 ms before, 23.5 ms
after.

Raw HTML: fail() now turns an error string holding a web page (a remote
magpie's or a vendor's 524/502 page inside the JSON error) into a short
said/what pair, "A proxy in front of magpie answered, not magpie ({what})"
with the page's title, translated in all 5 languages (key already in
i18n.js). The browser already handled non-JSON bodies (notJSON, #2032).

Run (Windows box, mote ssh was down earlier): go test budget, usage, gui
(AllOf, Budget, FailSays, I18n, Keys); gateway-keys-proxy-page and
gateway-key-limit GUI files in chromium and webkit, 5 languages: 24/24;
gofmt; vet windows, linux nogui, darwin (mote, only a clang deprecation
warning). Broken by hand: with the old fail() TestFailSaysAProxyPageByItsTitle
is red; with VisitFrom's reset() removed TestAllOfIsWhatEachWindowRead is red.
Not tried: a user-scale cold ledger, a server behind a real Cloudflare,
the full suite before the tag (started after).
2026-11-11 13:00:54 +08:00
yetone 88c417392e usage: a sortable model speed ranking on the Requests tab (@flying_crp on X)
Usage's Requests tab gets a "Model speed" card: per model, the median output tokens/s, the median wait for the first token and the request count, over the selected range, sortable by every column (aria-sort header buttons, quiet table, no gradients). A request counts when it was answered (not rejected, handed on, failed or canceled), its first token was timed and it wrote 100 tokens or more (usage.MinRankTokens; the tooltip says so). Computed locally: each chunk keeps a 2% log-bin histogram per model beside its cells (speed_rank.go, chunkPart.speeds), a page merges the chunks' histograms, so there is no per-request sort and medians are within ~1%. The settled chunks' histograms are in the page file; its key salt is now page-v2, so the first load after upgrade recounts settled history once. /api/ledger sends speeds and speed_min.

Run (mote): gofmt clean; go vet darwin, linux nogui, windows for the touched packages and ./... earlier; go test internal/usage, internal/usageapi, internal/gui ok at this head; usage-model-speed.test.cjs 12 of 12 (chromium and webkit, en/zh/zh-TW/ja/de, 400px: order, sort by every column, aria-sort, focus kept, no horizontal overflow, ellipsis, hidden when empty); with i18n-keys and i18n-en-no-cjk 20 of 20; the whole GUI suite once on the branch before the rebase: every red is in a file unrelated to this change (account-arrange #6010, account-refresh-holds #5814, account-eye #5052, agent-switch-accounts #5925, bulk visibility and disconnect previews #5982 fixed in e430e2750, accounts-own-signin #6038), each red alone on origin/main 71a68639b or load-only.
Timing: 1M requests added to a chunk in ~185ms (TestModelSpeedRankAtTheLargestLedger).
Broken by hand: dropping the Failed/Canceled exclusion (gpt: 5 requests, 59.7 tok/s) and dropping the page's merge of chunk speeds (ranking empty) each turned the new tests red; restored.
Not tried: the real Linux app (WebKitGTK), a real ledger of hundreds of thousands of rows through the page-v2 file, a Windows run (win-run).
2026-11-11 10:12:23 +08:00
yetone d5f6159109 usage: a test that a failed stat keeps the log's last read (f2039c13f)
f2039c13f kept the usage ledger's last good read when the log's stat
failed but for absence (@simonzyzy on X), and shipped with no test.
TestUnreadableLogKeepsItsLastRead takes search permission off the log's
folder, so the stat fails with EACCES, and checks that the last read
stands. It also checks that a log removed for real drops it.

Run: on mote, the new test -race -count=3 ok, and ./internal/usage ok
(37.7s), go vet ok, gofmt clean. On Linux (wsl-run, magpie-desktop),
-v shows the test run and pass, not skipped.
Red on the old code: with f2039c13f^'s log_index.go, it fails with
"a failed stat replaced the last read" (an empty snapshot, info nil).
Not tried: Windows. The test is !windows because its stat goes through
CreateFile there, and folder permissions don't fail it the same way.
2026-11-11 09:32:03 +08:00
yetone f2039c13fc usage: a log that can't be read but for being absent keeps its last read (@simonzyzy on X) 2026-11-11 09:04:52 +08:00
yetoneandskygunner 28a79bc33a gui: the gateway-mode stats test holds its clock at a local 00:30 (#5690)
TestGatewayModeStatsNameTheGatewaySessions wrote its record at
time.Now()-1h, which in the first hour of a local day is yesterday, so
days=1 left it out: red on macOS and ubuntu CI at 4167419ab (00:31 UTC)
and on mote at 00:40 PST (#5690). The test now runs in a testing/synctest
bubble whose clock is moved to the next local 00:30, writes the record at
that moment, and checks the clock didn't move during the queries. A usage
test pins GatewaySessionWindow's edge: a local midnight is left out, one
nanosecond after it is in, on two consecutive days.

skygunner's patch (1554065a on their fork, posted on #5690 on 11-08),
applied as written on origin/main e12244aca; it waited three days unported.

Run on mote at this tree:
- The old fixture (-1h) inside the bubble: red at days=1 (TZ=UTC).
- -race -count=3 of both tests in UTC, America/Los_Angeles,
  Asia/Shanghai and Australia/Sydney: ok.
- go test -tags nogui ./internal/gui ./internal/usage: ok; go vet ok;
  gofmt -l clean.
Not run: the full suite (test-only change).

Co-authored-by: skygunner <skygunner@users.noreply.github.com>
2026-11-11 08:51:15 +08:00
yetone d02bb81788 usage: Codex's effort before the last few days goes when idle too
dropEffortPeriods let go of every period's kept CodexModelEffort answer,
but effortOlds (each period's effort before the cut, ~2.1 MB in the t60
idle heap with real accounts, under effortSplit) stayed for the life of
the process. It is in effort-v1.json and effortSplit reads it back from
there when the entry is missing, so it now goes with the rest, under
codexEffortBuilding (TryLock: a build under way keeps it).

Run on mote at this head: go test ./internal/usage ./internal/usageapi
./internal/gui ok; gofmt clean; GOOS=windows go vet and GOOS=linux go
vet -tags nogui ./internal/usage ok.
Broken by hand: without clear(effortOlds),
TestIdleCodexEffortLetGoAndBuiltAgain fails ("0 periods' answers and 1
periods' effort before the cut kept while idle").
Not tried: a fresh real-account heap at this head (next acrss run).
2026-11-11 06:56:39 +08:00
yetone 8d68b5f219 usage: Codex's model and effort answers go with the chunks' caches when idle
CodexModelEffort kept each period's answer (every Codex thread's
consumption by model and effort) for the life of the process. On a real
history it was ~6.9 MB of the idle heap after one visit to the Sessions
page (t59 measured on mote, heap at 10 idle minutes:
usage.keptCodexModelEffort).

Each ask now notes itself with derivedUsed, as the pairing and heatmap
reads do, and dropDerived lets go of every period's answer but one being
built. The page polls every 15 s while open, so it keeps them; the first
ask after derivedIdle (3 minutes) builds the answer again, waiting for it
as a first ask does.

Run on mote (go1.26.8):
- go test -count=1 ./internal/usage ./internal/usageapi ./internal/gui: ok
- gofmt -l, go vet, GOOS=windows go vet, GOOS=linux go vet -tags nogui
  for internal/usage: clean.
- Broken by hand: with dropEffortPeriods left out of dropDerived,
  TestIdleCodexEffortLetGoAndBuiltAgain fails ("1 periods' answers kept
  while idle").
2026-11-11 06:10:18 +08:00
yetone d401c25951 usage: the found-group names hold the catalog, so a usage ask no longer builds it again (#5978)
4921bf5a9 (#5892) put provider.UsageNamesKey into usagePriceCacheKey,
the check every GatewaySessions ask, summary and Codex model/effort read
makes before using its kept view. UsageNamesKey reads usageGroupNames,
which asked sharedGroups outside a catalog hold, so each ask built every
provider's entries and the found groups again. In the test sandbox that
was ~130 KB more per ask, enough to take TestGatewaySessionsHandOutTheKeptProjection
over its bar on macOS CI and Windows (547208 / 671560 > 552000). With
real providers it is a whole catalog build on every Sessions poll.

usageGroupNames now holds the catalog (provider.Hold), and so does
usagePriceCacheKey, so provider.All and the group names it reads share
one build. A held catalog is checked against the providers' and
settings' files at the first hold and dropped on any write, as for every
GUI request.

Found by bisect on mote over TotalAlloc per ask: 44732325e 407218,
4921bf5a9 537040.

Run at 9522288b1 plus this change:
- mote (macOS): go vet -tags nogui and go test -count=1 -tags nogui
  ./internal/provider ./internal/usage: ok. Before the rebase, the same
  plus ./internal/sessions ./internal/usageapi ./internal/gui: ok.
  An ask allocates 381834 bytes (was 547208); the Codex effort build
  271472 against 456152.
- xiaomi-gpu (Windows): both allocation tests pass, 399501 and 371480
  (were 699558 and 488640 at origin/main 87dfc0d0b, both red).
  The package run of ./internal/usage ./internal/provider is red on
  18 tests there; each one that also ran at origin/main 87dfc0d0b is red
  the same there (Codex keychain, TestDesktopSessionAccountMetadata,
  TestGitOnDisk*, TestResolveKeptAcrossRequests, TestSavedButSignedOut,
  TestPricerAllocatesNothingPerModel, TestLANNeighbours), and
  TestUsageReadAndReadAgain is #4796 (equal clock readings). Filed the
  two with no issue: #6024, #6025.
- gofmt -l: clean.

Broken by hand:
- both holds out (origin/main): 547208 on mote, red.
- only usagePriceCacheKey's hold out: 414295, green; it is the
  provider-side hold that fixes the class (UsageAlias and PublicRefs
  read usageGroupNames too).

Not tried: a real config with many providers (the saving there is a
catalog build per ask, not measured), and Linux.
2026-11-11 05:54:17 +08:00
yetone a54dddd967 usage: the request page's chunks go once it has gone unasked for 7 minutes
The 2-minute idle trim held the session files' chunks to requestIdleBytes
(24 MB). A real history's chunks (~11 MB on the owner's accounts, t54's
idle heap: readRequestBlocks 11.3 MB, readDiskEntry 9.2 MB flat) fit under
that bound, so they were kept for the life of the process after one visit
to the Usage page. Now a second timer, requestForget (5 min) after the
trim, lets them all go when nothing asked for the page since the trim. The
next page reads them back from the file of them (toDisk), decoded and not
parsed again; chunks not saved yet are parsed again, as with the trim.
`asks` counts the asks, so a forget armed before an ask lets nothing go.

Run (mote unreachable all evening, so on the Windows box and its Linux VM):
- wsl-run: go test -count=3 -race -run TestRequestChunks ./internal/usage ok;
  go test ./internal/usage ./internal/sessions ./internal/dirent ok;
  go vet ./internal/usage for linux, windows and darwin ok; gofmt clean.
- Broken by hand: with the forget's trim(0) taken out,
  TestRequestChunksForgottenLongIdle fails ("forgotten: 3 chunks kept").
- win-run: internal/gui and internal/usage. Every red there is the same at
  the base 6bac8f8a5 without this change: the two allocation bounds are
  #5978 (filed now), TestDesktopSessionAccountMetadata is #1356, and the gui
  reds are the box's own (%AppData% unset, Smart App Control).

- At the pushed head (rebased on 40fbec705): go test ./internal/usage
  ok on mote, go vet ./internal/usage for windows and linux ok.
- mote (macOS), when it came back: go test ./internal/usage ./internal/gui
  ./internal/sessions ok.
- Real accounts (a copy of the owner's, sandbox HOME on mote), `magpie web`
  idle 600s, runs ordered t54 (before), this, this, t54:
  - this change: the footprint drops at ~540s (132 → 121 MB, 107 → 103 MB)
    and RSS by ~70 MB; neither t54 run drops after 300s.
  - end heap, this change against t54: usage.QueryPage −11.5 MB
    (readRequestBlocks 1.5 MB, against 11.3 MB; readDiskEntry's 9.2 MB
    is gone).
  - These runs' totals are higher by ~14 MB of agent model lists kept past
    their minute (stampedLists), which this change doesn't touch; the next
    commit lets them go.
2026-11-11 01:26:08 +08:00
yetone 6b92824ff5 usage: a window's whole also at base rates, without long-context premiums (#5861, Norethcy on X)
A window's whole (WindowHolds) is priced at API list prices, which charge
GPT-6.1 Sol's input above 272K at a premium a subscription's own use
doesn't pay. A cycle with more long calls then reads as a larger
allowance: NorethSea's previous week came to $76.56, $53.52 without the
premium, against $56.99 for the current one.

Each priced call is now also costed at its model's base rates, the
long-context tiers left out and a peak hour's price kept (baseRates), and
the window's whole sent as BaseCost beside Cost, only when the two differ.
Past cycles get it too (HistoricalWindowHolds goes through windowHolds).
On the card the figure then says which it is ("≈ $76.56 API") and is a
button: a click switches every card, past cycles too, to the base figure
("≈ $53.52 base") and back, moves nothing, and is kept in the browser.
Its tooltip names both and says neither is an official dollar allowance
or a fixed quota. A window that paid no premium is drawn as before. The
ledger's and the API's real cost are unchanged. #4181 (auto-review calls
counted in the whole) is not part of this.

app.js and the core stay in their budgets with holdsLine's and holdsWhy's comments cut, no raise.

Run (mote's sshd reset every connection, so on the Linux box through
wsl-run; the package run at base 720200092, and the -run tests,
quota-holds and i18n-keys again at this head on 208b89422; rebased since onto 44732325e,
a gateway test only):
- go test -count=1 -tags nogui ./internal/gui ./internal/provider
  ./internal/sessions ./internal/usage ./internal/usageapi: ok (incl.
  TestCoreScriptBudget)
- go vet -tags nogui (linux), GOOS=darwin CGO_ENABLED=0 go vet, go vet on
  Windows (win-run): clean. gofmt -l: clean.
- GUI: quota-holds (new test: every language, 360 and 1000px), i18n-keys,
  i18n-en-no-cjk, quota-fit-batched, provider-fetch-holds in chromium and
  webkit: ok.

Broken by hand:
- baseRates keeping the tiers: TestWindowHoldsBaseCostLeavesOutLong-
  ContextPremiums red (base figure 0).
- the click updating only its own button: quota-holds' new test red in
  both engines ("the other card didn't switch").

Not tried: a macOS run (mote unreachable), the darwin gui package's vet,
and the reporter's own log; the test's prices are gpt-6.1-sol's shape.
2026-11-10 18:01:13 +08:00
yetoneandNorethSea 4921bf5a97 usage, sessions: one model option for a found routing group's two ids (#5892, Norethcy on X)
A found routing group is called by its public id (auto/<model>) and is
kept as group/auto-<slug>; calls recorded under either were counted as two
models, so Usage › Sessions' model filter listed the same group twice and
the ledger, summaries and session lists split its calls.

Ported from NorethSea's 30d6261cd on their fork: UsageAlias names a found
group by its public id before the user's alias (both spellings, old
session files too), sessions' lists, the ledger keyer, the summary cache's
key and Codex's model/effort read through it, and a cache keyed on the
group names (UsageNamesKey) is read again when a group is renamed. A user's
own provider named "auto" keeps auto/<model> (autoRefsOn).

Changed in review: the patch's ledger filter compared every record with
provider.SameRef, which reads the providers (customIDs, a stat of
providers.json) for each record a filter passes over. FilterOf, the one
place a Filter is made from a query, now canonicalizes the model once, and
keepsRecord asks the providers only for an auto/ record under a group/
filter (sameGroupModel).

Run (mote's sshd reset every connection all afternoon, so on the Linux box
through wsl-run; the package run at base 720200092, and the -run tests,
quota-holds and i18n-keys again at this head on 208b89422; rebased since onto 44732325e,
a gateway test only):
- go test -count=1 -tags nogui ./internal/gui ./internal/provider
  ./internal/sessions ./internal/usage ./internal/usageapi: ok
- go vet -tags nogui (linux), GOOS=darwin CGO_ENABLED=0 go vet (provider,
  usage, usageapi, sessions), and go vet on Windows (win-run, those and
  internal/gui): clean. gofmt -l: clean.
- GUI: usage-ledger-model-pick, usage-ledger, quota-fit-batched,
  i18n-keys in chromium and webkit. usage-ledger's "newest live route
  needs no return-to-live button" (and zh "request routing links") is red
  the same on origin/main 987eac0aa on that box: #3104, #4078.

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

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

Co-authored-by: NorethSea <963979204@qq.com>
2026-11-10 18:01:13 +08:00
yetone 3b261932e1 usage: what is kept of each chunk by its serial is let go after three idle minutes
Message keys, match hints, chunk first times and heat sums are kept by
chunk serial and pruned only by turns, so with no pairing or heatmap
while nobody looked they stayed for the life of the process (~4 MB of
message keys alone in a real history's idle heap). They are now let go
once none was read for three minutes, and read again from the chunk on
the next ask.

Test: TestDerivedLetGoWhenIdle (kept while read, let go when idle, same
answers after).

Run: go test ./internal/usage on mote at this head (ok, 36s) and on
the Linux box; go vet linux, windows, darwin. Broken by hand (the drop
skipped): red, "idle: 3 heat sums and 3 firsts kept". Real-account copy
on mote, 330s idle, both orders: hintsOf's 1.6 MB is gone from the end
heap; footprint moved with run order (+10-15 MB for whichever ran
second), so no footprint gain is claimed. Not tried: an idle after the
Requests page was paged, where message keys are kept.
2026-11-10 16:45:02 +08:00
yetone 662546e78d usage: a cache hit rate reads 100% only when all of the prompt was cached (ZhangXiaof48473 on X)
Routing's request list showed "缓存 100%" for Codex requests of 77.5K
tokens that read 77,200 of them from the cache (99.6%), beside rows at
99%, and the route line said "请求缓存命中率 99%". Every hit rate was
Math.round(100 * h) + "%", so anything from 99.5% up read 100%.

One formatter now says every hit rate: hitPct(h, d) in app.js, whole
percents (d decimals) unless rounding would say 100% or 0% of a prompt
not all or none cached, then one or two decimals (99.6%, 99.95%; never
past 99.99% or under 0.01%). Its callers: Routing's request rows, their
route line and a session's Avg. cache (plugins/routing/client.js); the
tray panel's Cache hit rate and the ranking rows' hit rate (app.js); the
Usage page's tiles, agent rows, Requests table, request detail and its
KPI strip, which keeps its one decimal (plugins/usage/page.js); the
context card's Prompt cache and the session traits Cache-friendly,
Cache misses and Cache hit (context.js). The TUI's and CLI's sessions
line, which floored the integer, use usage.HitPct, the same rule in Go;
it rounds now, so the TUI test's 67% (25.2K of 37.3K, 67.6%) reads 68%.
No new strings; app.js pays its bytes with six ledger comments cut, so
the core scripts are 15 bytes smaller than at its parent, no raise. Main
is over the core budget already (1,534,476 > 1,533,802 at the parent,
#5918); this commit doesn't add to it.

Run on mote:
- new internal/gui/tests/cache-hit-pct.test.cjs (Routing rows 99.6% /
  100% / 99%, the route line, hitPct at its edges) in chromium and
  webkit, en and zh: green; with the escalation line removed by hand,
  red (99.99% where 99.6% is wanted).
- cache-hit-pct, panel-usage, context-window, i18n-keys, usage-ledger,
  tray-totals, ctx-route, ledger-cache-hit, usage-hit-rate,
  routing-request-metrics (both engines; ledger-cache-unknown and
  ledger-cache-tokens in an earlier run): 186 pass, 6 red, all in
  usage-ledger's 'newest live route needs no return-to-live button',
  red the same on origin/main 00e8242e8 (#5048, #4078).
- go test ./internal/usage ./internal/cli ./internal/tui: ok, with
  TestHitPctNeverRoundsToAllOrNone and a 99.6% case in
  TestHitRateCountsCacheWrites (red on the old floor: 99%).
- go test ./internal/gui at the first base: TestCoreScriptBudget ok; one red,
  TestGatewayModeStatsNameTheGatewaySessions, run at 00:25 local (#5690,
  the first hour of a local day).
- gofmt; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
At the pushed head (rebased, comments cut): cache-hit-pct and
routing-request-metrics again, both engines, 8 of 8.
Not tried: the real app's window, or GUI files beyond those above (a
65-file run waited on mote's suite lock behind four full suites).
2026-11-10 16:28:04 +08:00
yetone e4197144a8 perf: every package's package-level regexps compile on first use
v0.1.3516 made gateway's and redact's patterns lazy. The other 299
package-level regexp.MustCompile calls, in 148 files across agent,
provider, gui, library, codexcat, sessions, usage, plugin and the rest,
now go through lazyre.New too, so a launch that never reaches them
(`magpie statusline`, run by Claude Code on every message) doesn't
compile them. Fields, maps and params that held them are *lazyre.RE.

Measured on mote (M5 Pro), sandbox HOME, v0.1.3516-equivalent build
(t42) against this one (t43):
- GODEBUG=inittrace=1 sum: 7.39 MB / 69,837 allocs -> 4.62 MB / 46,765
- `magpie statusline`, 3 runs each: instructions retired ~212M -> ~176M,
  peak memory footprint 19.2-19.4 MB -> 16.8-17.0 MB

Run: go vet ./... (darwin) ok; GOOS=windows go vet on each of the 30
changed packages ok; GOOS=linux go vet ok except ., internal/cli and
internal/gui, which stop in wails v3's cgo files when cross-compiled
(the same at main). New TestAllLazyPatternsCompile at the root compiles
all 574 registered patterns (ok), so a bad pattern fails a test rather
than a first use.
Not run before push: the changed packages' own test suites; they run
on mote after it.
2026-11-10 12:54:39 +08:00
yetone 84a6d6a813 usage: Cursor calls made outside magpie are counted on the Usage page (WaiooT on X)
WaiooT asked for Cursor's usage to be counted. The quota card was there
already (the plugin's auth.usage); what was missing was the calls the
account made in Cursor's own editor and cursor-agent, which never pass
magpie's gateway.

The Cursor plugin (0.2.44, magpie-community/plugins f73ba656) gains
auth.calls: it reads Cursor's own usage list,
DashboardService/GetFilteredUsageEvents (the call cursor.com's Usage
page makes), keeps the signed-in user's events (owningUser = GetMe's
userId), and leaves out the conversations it sent itself for magpie.

magpie side:
- host.js: a provider says `calls` when its plugin has auth.calls; a
  `calls` RPC normalises the reply (a call without an rid or time is
  dropped, cost only when a number >= 0).
- plugin.AccountCalls / plugin.OutsideCall.
- usage.ReadOutsideCalls, run by the gateway a minute after the start
  and every 10 minutes: each account's calls since its mark go in as
  reported calls (IngestReported, request id "cursor:<usageEventId>", so
  each is written once across restarts), by agent "cursor", provider
  cursor, with Cursor's own cost. The first reading goes 30 days back,
  but never before the gateway's last call to that provider, which older
  plugin versions couldn't tell apart. A failed reading keeps its mark;
  each later one starts 30 minutes back for events listed late.
  Marks are kept in plugin-calls.json beside usage.jsonl.
- Cursor's mover min 0.2.43 -> 0.2.44 (npm view --prefer-online: 0.2.44).
- docs/subsystems/provider-plugins.md: "Calls an account made outside
  magpie".

Run (mote, at this head):
- go vet for darwin, GOOS=linux -tags nogui and GOOS=windows on
  internal/usage, internal/plugin, internal/gateway, internal/provider: ok.
- gofmt -l: clean.
- go test -count=1 -timeout 45m ./internal/usage ./internal/plugin
  ./internal/provider ./internal/gateway: all ok (usage 36s, plugin 129s, provider 152s,
  gateway 937s), at 96d9b9ccd before the rebase onto origin/main (2
  commits, none touching these files).
- Plugin: the cursor package's whole suite (410 pass) and
  scripts/check.mjs on mote; a real-account auth.calls read returned 43
  calls with models, tokens and cents.

Broken by hand:
- lastThrough's start removed: TestOutsideCallsStartAfterTheGateway red.
- RequestID left empty: TestOutsideCallsCounted red (rows written again
  after a restart).
- host.js's rid/time filter removed: TestPluginOutsideCalls red ("4
  calls, want 2").
- Plugin: owningUser and own-conversation filters removed: calls.test.mjs
  red.

Not tried:
- A full magpie gateway with the plugin installed reading a real
  account end to end (the plugin read was real; the magpie side ran
  against the fake plugin and stand-ins).
- A team account (teamId), and the Cursor editor itself (none installed
  here); the editor's and cursor-agent's calls are one list, both shown
  as the Cursor agent.
- Two computers running magpie on one Cursor account each count the
  other's gateway calls as made outside magpie.
- No GUI change: the rows use the reported-row path the Usage page has.
2026-11-10 12:22:53 +08:00
yetone ca5e537ecb usage: traffic over time in Requests' chart, and how fast it flows now (songlairui on X)
songlairui on X asked for the gateway's bandwidth: many LLM calls, base64
images above all, weigh on the network. Each request's row already kept
its bytes up (UpBytes) and down (DownBytes), shown in its details and as
the period's "↑ · ↓" under the Requests card. What was missing was
bandwidth over time and right now.

- The Requests chart's metrics take Traffic: each hour's/day's bytes up and
  down, stacked by model, provider or agent. Its axis is in bytes ("4 MB"),
  its tooltip splits a column into "↑ up · ↓ down", and the ranking's
  values are bytes with the same split under each. A period with none
  says "No traffic counted in this period". A chart point's Part now
  carries up_bytes/down_bytes, from rows (Part.add) and from the request
  page's cells (Part.plus). The cells already kept Totals, so no cache
  version bump is needed.
- While requests are in flight, the Requests card says how fast traffic
  flows now: "↑ 1.0 MB/s · ↓ 40 KB/s", over the last ~3s, read from the
  new GET /api/usage/traffic a second apart. That route reports the
  gateway's running totals (Server.Traffic) and its requests in flight.
  The totals are atomics added where a row's bytes are added (sentUp,
  downCount.Read). So a stream counts as it arrives, nothing is buffered
  or scanned, and the totals and rows count the same bytes once. Polling
  runs only while Usage → Requests is shown and the window is visible.
  The line goes when nothing is in flight and nothing flowed. When another
  magpie serves the gateway, the route answers {} and the page shows no
  rate.

A Codex turn on the Responses WebSocket (7c1dc198d) is in the totals as
its row is: what the socket was written. The HTTP body sentUp counted is
taken back when the transport chooses the socket (toSocket) and given back
if the turn falls to HTTP after all (toHTTP), so the totals equal the sum
of the rows either way (TestTrafficCountsWhatTheSocketSent, kept and
refused).

Not counted, as before: Claude bridge turns (no HTTP to the vendor). A
plugin's row counts the local hop to the plugin host. An upload is counted
when its try is sent, so a large body shows as a burst in the live rate.
docs/subsystems/gateway-sessions.md has a Bandwidth section.

Run (mote; first at this change on da8480326, then again on 16a2dfac9):
- go test -count=1 -run 'Traffic|Socket|UpBytes|Ledger|Series'
  ./internal/gateway ./internal/usage ./internal/gui: ok.
- Broken by hand, each red, then restored: the down tally in downCount,
  the up tally in addUp, Part.plus's bytes, Part.add's bytes, the
  toSocket call (kept socket: traffic 151020, rows 50469) and the toHTTP
  call (refused: traffic 50360, rows 100551).
- gofmt -l clean; go vet -tags production ./..., GOOS=linux and
  GOOS=windows go vet ./...: ok; darwin, linux and windows builds: ok.
- GUI (mote, this tree): i18n-keys, i18n-en-no-cjk, usage-traffic and
  request-archive-usage, 54/54 in Chromium and WebKit (usage-traffic in
  en, zh, zh-TW, ja and de); usage-traffic red with the rate line broken
  by hand. "Traffic" is in i18n.js, not the Usage plugin's: Go says it
  too, and i18n-keys was red with it in the plugin's file.
- internal/cli TestEveryRouteHasACommandOrIsNamed: ok, with GET
  /api/usage/traffic named in notYet (the full run found it red).
- On 16a2dfac9 (the pushed base): gofmt -l internal clean; go test
  -count=1 -run 'Traffic|Socket|UpBytes|Ledger|Series|
  TestEveryRouteHasACommandOrIsNamed|Budget' ./internal/gateway
  ./internal/usage ./internal/gui ./internal/cli ok; i18n-keys and
  usage-traffic 40/40.
- Not finished at the tag, still running on mote: go test ./... -timeout
  45m and the whole GUI suite (under suite.lock), and the whole
  internal/gui, internal/usage and internal/gateway packages with every
  usage* GUI file. What they find is fixed in follow-ups.
2026-11-10 07:37:34 +08:00
yetone 68865032c3 usage: a gateway row keeps the address its request came from, on this computer only
geesehowardt7 on X asked to see a request's source IP. No usage row
kept it.

Record.ClientIP (json client_ip) is set in appendUsage from peerAddr:
the connection's own address, never a forwarding header (the gateway
trusts none), so behind a reverse proxy it is the proxy's. Loopback is
127.0.0.1/::1. Rows kept before this, reported calls and magpie's own
calls have none. rowText packs it, or the ledger cache gave it back
empty (the cache's file is keyed on this package's source, so it is
rebuilt once).

It stays here:
- sync's OwnDays blanks it, as it does Archive and Computer;
- GET /v1/magpie/usage/requests (other computers, Remote magpie, key
  holders) takes it out for every caller (withoutClientIPs);
- the CSV export, OTel and middleware points name their own columns
  and don't carry it; telemetry sends ids only.
The window's /api/usage/requests keeps it for the Usage page.

Run (mote, at base e3f1efdaa):
- go test -count=1 -timeout 45m ./internal/usage ./internal/usageapi: ok
- go test -run 'TestUsageRowsKeepTheClientsAddress|TestUsageOverGateway'
  ./internal/gateway: ok
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet on
  gateway and usage: ok; gofmt -l clean.
Broken by hand, each restored:
- no ClientIP in appendUsage: TestUsageRowsKeepTheClientsAddress red
  (addresses kept: map[:true]).
- no withoutClientIPs: the same test red (the API told 127.0.0.1:5000
  the address).
- OwnDays not blanking it: TestClientIPKeptHereNotShared red.
- before rowText packed it: TestClientIPKeptHereNotShared red (empty
  from the ledger).
The full suite runs with the GUI commit that shows it.
2026-11-10 04:44:07 +08:00
yetone 7c1dc198d1 usage: a turn over the Responses WebSocket counts what the socket was sent, and says so
A Codex turn kept on a Responses WebSocket sends only the new items as a
delta, but the row's ↑ was the whole HTTP body magpie built before the
transport ran, so a long conversation read as ~13MB up per turn
(matrix0487 on Discord). overSocket now records what each socket write
carried (wroteSocket) and, when the turn went out on the socket alone,
replaces the HTTP figure with those bytes (sentOnSocket); a turn that fell
back to HTTP keeps the HTTP body and adds any socket write made before the
fallback. errCodexSocketAgain's retry on a new socket counts both writes.

The row remembers that it went over the socket: Record.Socket (json "ws"),
packed as Flags bit 16384 (rowSocket, added to TestRowFlagsApart). The
Requests table's protocol badge says "Responses · WS" and the details'
Protocol line "Responses · WebSocket".

Run on mote at this commit (rebased on origin/main b4a0a2a1a): gofmt -l
clean; GOOS=linux and GOOS=windows go vet of internal/gateway and
internal/usage; go test ./internal/usage ./internal/gui ok; go test
./internal/gateway -run 'Codex|UpBytes|Ledger|Socket' ok; node --test of
every ledger-*, usage-ledger* GUI file and i18n-keys, 502 of 511, both
engines. The reds are filed and untouched by this change: ledger-swipe
webkit (#5223) and usage-ledger's "newest live route needs no
return-to-live button" (#3104, #4078, #4626, #5048).

Broken by hand: without the deferred sentOnSocket,
TestCodexSocketRowCountsWhatTheSocketSent reads 50,360 B for a 253 B
delta; without the Flags set, TestRowKeepsSocket's packed rows lose
Socket.

Not tried: a real Codex Pro account over the socket, and the full suite
(it runs after the tag). There is no "saved by the socket" figure yet,
since PlainBytes isn't packed.

Reported-by: matrix0487 (Discord)
2026-11-10 03:44:19 +08:00
yetone a8aeb2cad2 usage: picked days can start and end at a minute
blrbrzkj on Discord asked to see usage from one time to another, not
only whole days. The range menu has a start and an end time under its
month (empty is the whole day; 9:30, 0930 and 09:30 all read 09:30).
Picked with the days, the period is "2026-10-01T09:30..2026-10-01T18:00";
Enter applies new times to the days already picked. A time that isn't
one, or an end not after the start on one day, is marked and asks for
nothing. The opt says "Oct 1 09:30 – 18:00".

The backend reads either end as a date or a date with its minute
(usage.RangeOf, bounds); an untimed end is its next midnight. A timed
range of 48 hours or less is drawn by the hour from the first's hour.
CSV names drop the colons.

Run (mote): node --test usage-range-times (new, chromium + webkit, en +
zh), usage-range, i18n-keys, credit-days: 26/26 ok. go test
./internal/usage ./internal/gui ok (TestCoreScriptBudget fits, the
periodDays comment cut to pay for its regex); gofmt clean; go vet
native, GOOS=windows (usage, gui), GOOS=linux (usage) ok.
Broken by hand: a timed end read as its day's midnight turns
TestPickedMinutesArePeriod red. The page's own typedTime first clashed
with app.js's hhmm and stopped the Usage page mounting; the GUI run
caught it.
Not tried: the real app with a real ledger; ja/de/zh-TW screens.

Reported-by: blrbrzkj (Discord)
2026-11-10 02:01:37 +08:00
yetone 7e5cebb86c usage: a model list fetched again unchanged keeps the usage index
Each account's model list is fetched again on every start and every 45
minutes, and saveLive writes it again with only its "fetched" time moved.
Usage keyed the request index (and its file on disk, requests-v1.bin) and
the priced summaries on that file's mtime (statKey(catalog.LivePath)), so
each such save dropped every chunk: every start, and every refresh while
running, read the whole session history again, decoded every call shard
and rebuilt every row.

catalog.LiveKey names a saved list by a hash of its bytes without the
fetch time, made once per parse of the file (readLive's memo). A list
saved before Since was kept is dated by its fetch (LiveSince), so its
fetch time stays in its key. usage's liveListKey uses it for every
provider and Antigravity in readRequestState's meta and in
usagePriceCacheKey (the same mtime key, the sibling), and falls back to
the stat when the list can't be read.

Found by dumping both disk headers on mote: same binary, same sources,
and only the providers' hash differed, run to run.

Measured on mote, a copy of the owner's real accounts, GUI open, network
blocked, the Claude list rewritten as a start's fetch does. Restart of
the same build, t10 (main) against t11 (this):
  CPU in the first ~3 minutes   11.6s -> 2.5s
  allocated                     2.74GB -> 0.81GB
  sessions.loadCalls            771MB -> gone from the top
  footprint                     174MB -> 175MB
The first start after an upgrade that changes usage's code still builds
everything once (requestDiskBinary), as before.

Tests: TestRequestStateKeptAcrossAListFetchedAgain saves the same list
again an hour later and needs readRequestState's meta and
usagePriceCacheKey unchanged, and both changed for another list; on the
old usage code it is red on both. TestLiveKeyOnlyMovesWithTheList and
TestLiveKeyOfAnOldListKeepsItsFetch cover the key itself.

Run on mote at this tree: go test ./internal/catalog ./internal/usage
./internal/provider -count=1 ok; go vet ./... ok; GOOS darwin/linux/
windows go vet ./internal/catalog ./internal/usage ok (./... cross-OS
stops at wails' cgo files, as on main); gofmt clean.
Not run: the full ./... suite before the push (running after), GUI.
2026-11-10 00:36:16 +08:00
yetone fc9ce34d86 usage: hashRows reuses its scratch, within sizes its rows exactly
Startup on a copy of the owner's real accounts (mote, GUI, network
blocked, acgui.sh) allocated ~3.5GB, and two usage functions were near
the top of it:

- hashRows built a fresh 32KB byte buffer and shape map for every chunk
  it hashed: 510MB of the startup's allocations. It now takes them from
  a sync.Pool and clears the map before use. The digest is the same
  byte for byte (checked against the old code on the same chunks).
- rowChunk.within appended into a nil slice, growing it step by step
  (292MB flat). It now counts the rows in range first, returns nil when
  there are none, and makes the slice at that size.

Measured, same real-account copy, t9 (main) against t10 (this):
  startup CPU      13.81s -> 9.77s
  allocated (3m)   3483MB -> 2768MB (hashRows 510MB -> gone,
                   within 427MB -> 244MB cumulative)
  footprint        179MB  -> 175MB

Tests: TestHashRowsReusesItsScratch hashes a chunk again after a bigger
one and must get the same digest, and must allocate under 16KB a call
(min of 5 batches, so other goroutines' allocations don't count). Old
heat_disk.go: red at 32768 bytes a chunk; dropping clear(shapes): red.
TestWithinSizesItsRows needs len = cap = 600 (old code: cap 646).

Run on mote at this tree: go test ./internal/usage -count=1 ok, -race
ok, gofmt clean, go vet darwin/linux/windows ok, gui tests ok earlier.
An earlier usage run went red on a test whose name was lost (the log was
cut by tail); four full runs since are green, and the likely cause, the
first byte check counting other goroutines, is what the min-of-5 fixes.
2026-11-09 23:56:13 +08:00
yetone 3a5e4b62d0 usage: TestRowTokensAndZoneKept compares the zone by name and offset
The test compared got.Time.Location() with its own *time.Location by
pointer. rowZones keeps the first zone it sees for a name and offset, so
under -count=3 the second run got the first run's location back and the
test went red on unchanged code. It now checks the zone's name and
offset (IST, +5:30), which is what rowZones promises.

Run on mote: go test ./internal/usage -count=1 ok; -run
TestRowTokensAndZoneKept -count=3 ok (red on the old test). Broken by
hand: writing the row with an "XST" zone turns it red.
2026-11-09 23:56:13 +08:00
yetone e3f1efdaac usage: a message id's pairing key is 16 bytes, not 24
msgKeysOf keeps each chunk's message ids as hashes, with the row, for
every chunk a pairing reads. The key was two 64-bit hashes and an
int32, padded to 24 bytes. It is now a 64-bit and a 32-bit hash with
the row, 16 bytes: two of a long history's ~300k ids alike in all 96
bits is ~1e-18 likely.

Run on mote at this head:
- go test ./internal/usage: ok (28.8s)
- GOOS=darwin/linux/windows go vet ./internal/usage: ok
- gofmt -l: clean
- Broken by hand: with the second hash back at 64 bits,
  TestMsgKeySize is red (24 bytes).
- Real-account copy (~/r2278/acct), idle heap at 180s, v0.1.3404's
  tree vs this: appendMsgKeys 6.49 MB -> 3.69 MB, inuse 103.0 MB ->
  97.8 MB, Footprint 154 MB.
2026-11-09 19:58:17 +08:00
yetone a06872dec8 caps: a wallet window's spend is counted, so a cap holds it (#5770)
A window that tells only what is left (QuotaWindow.Balance: AStudio
0.2.0's 通用积分 and 星火积分, SuperMagic's points) read 0% used until
it was empty, so an account cap never tripped on it. 9won capped an
AStudio account at 4 and it spent over 1,000 credits past it.

magpie now counts what such a wallet spends (wallet_spend.go). Each
plugin reading's balance is set against the one before: a fall is
spent, a rise (top-up, daily grant) is not. The count runs over the
window's own period when it tells a reset, else the local day: a
wallet never renews, and a cap reached for good would switch the
account off with no time it comes back; the ask was "N a day". Spend
before a period's first reading, or across a gap between periods, is
unknown and not counted; spentSince says when counting began. The
counts are kept in wallet-spend.json beside providers.json, so a
restart doesn't lose them.

Every wallet window carries spent and spentSince. On an account with a
usage cap (WindowCaps.Holds) it also reads as amount spent of limit
(spent plus what is left), and used that share. A cap by share then
holds it in routing (allowanceOf takes the fields as they are) and on
the GUI row (capHeldOf reads used). So does 40cbdaa7e's amount cap,
which skipped a window with no total: 9won's "at most 300 a day" on a
wallet now holds (magpie provider account-cap ... --window 通用积分
--amount 300). An uncapped wallet is unchanged:
balance alone, routed by Allowance.Left. A cap just set is judged from
the next reading. holdsBounds leaves wallets out: there is no whole to
reckon "holds" from.

Tests, each red on the old code (broken by hand where they compile):
- TestPluginWalletCapHolds: real plugin host, fake plugin, wallet
  10,000 -> 9,500 on an account capped at 4. Used 5, CapHeld set, the
  uncapped account untouched. Red with the plugin_usage.go hook
  removed (Used 0, Spent nil).
- TestWalletSpendCounted: falls counted, top-ups not, a restart reads
  the count back, the next local day and a told reset start over
  (UTC+8 fixed zone), failed and share readings left alone.
- TestWalletCapHolds: account cap 4, the window's own cap 4, and an
  amount cap of 700 (not held at 650 spent, held at 750).
- TestWindowHoldsLeavesAWalletOut: red without the holdsBounds change
  (a wallet reckoned a 500-token whole).

Run on mote at this tree on f8186c691. Rebased under it after: 7000b23b8
(GUI files only) and 36ddd5761 (internal/sessions only) (lockf ~/suite.lock
mote-run):
- go test ./internal/provider -run 'Wallet|Cap|Amount' -count=1: ok
- go test ./internal/usage -run TestWindowHolds -count=1: ok
- gofmt -l .: clean
- go vet ./... for darwin and windows, and for linux with -tags nogui:
  ok
Pushed and tagged at once, per the owner's rule. The full go test ./...
-timeout 45m runs after the push and any red gets filed.

Not changed: the GUI. A wallet meter still shows "{n} left". A capped
one shows "At its cap" from used. The meter's Amount... item still
needs a total and a unit, so an uncapped wallet doesn't offer it yet
(follow-up). A Text window (a balance that isn't
a number) still can't be capped by share.

Reported-by: 9won (Discord)
2026-11-09 19:23:13 +08:00
yetone f8525323dd providers: a key with no balance URL takes a balance typed by hand, counted down by magpie's own usage
Some API-key providers tell no balance magpie can read (no Balance URL,
no relay query found), so their keys showed none. Now the user types what
the vendor's page says is left, on the key's row in the provider editor
(Set balance) or with `magpie provider key-balance <id> [key [usd|off]]`.
The key's card shows that less what magpie's usage priced the calls it
sent on the key since it was typed (usage.KeySpent, the spend caps'
count), marked as an estimate: "≈$12.50", the pill "≈$12.50 left", its
title saying what was typed, when, and what was counted since. Typing it
again counts from then; No balance takes it off.

A balance the vendor tells always wins: a provider with a Balance URL, a
plan source, Cline's or OpenCode Zen's card takes none typed, and a relay
whose query is found shows its own; when the probe finds none
(errNoBalance) the typed one is shown. A typed balance stays saved as the
user left it: the editor's save keeps it, a key's replaced value carries
it. An estimate is never kept in the balance history and tells routing
nothing (the routing allowances cache is left alone).

keybalance.js is loaded by keyspend.js (itself loaded when the editor
draws a key) for a provider that takes one, so app.js and the core's
script budget are unchanged. Words in zh, zh-TW, ja and de.

Run at this tree (mote):
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... at base 46b10af87; at this tree go vet of
  gui, provider, cli and usage;
- go test -tags nogui -count=1 ./internal/gui ./internal/provider
  ./internal/cli ./internal/usage: provider and usage ok; gui and cli
  red only on #5644 below; TestCoreScriptBudget ok (1,533,747, as main)
- the provider tests under -race -count=3;
- GUI: key-own-balance (new: Chromium and WebKit, en zh zh-TW ja de,
  900 and 400px, 20/20), key-spend-cap, old-webkit, i18n-keys, gui-de,
  gui-ja, gui-zh-tw, balance-found, key-balance-card, i18n-en-no-cjk:
  104 pass, 1 fail, i18n-keys "a plugin's words are its own", red the
  same on origin/main 7a2946caf (#5327, #5332, #5482, #5426).

Broken by hand, each went red:
- estimates kept in the balance history: TestTypedBalanceCountsDown;
- no fallback to the typed balance on errNoBalance:
  TestToldBalanceWinsOverTyped;
- the editor's save dropping KeyOwnBalances: TestKeyOwnBalanceRoutes.

Red on main, not this change: TestSettingsSaveKeepsWhatItDoesNotSend
and TestSettingsCLISetsWhatTheWindowSaves (groupSink, groupFirstToken,
groupPatience from 6b7ee4a98), filed as #5644.

Not tried: a real relay account with no balance URL (the cost counted is
magpie's own estimate, so a vendor pricing differently drifts until the
balance is typed again); the full Go and GUI suites before the push (run
after it, under the suite lock); the GUI in the real Windows and Linux
apps; routing does not use the estimate.

Reported-by: tenacious_eagle (Discord)
2026-11-08 02:54:25 +08:00
yetone d4712e1312 usage: a probe's chunk among the settled days no longer drops the heatmap's disk cache
heatSettledKey gave up whenever a settled chunk had no serial. A probe's
chunk (MCP and search calls) is made again for each query, so it never
has one. When a user had no tool call in the last two days, that chunk
fell among the settled days, the settled count was never kept on disk,
and every Usage refresh paired and counted every day again.

The loop below already names such a chunk by its rows (hashRows), the
same rows give the same key, and pairSerials already allows one unnamed
chunk. So the early return goes; the doc comment says what false means
now.

Ran (mote, at this head):
- TestHeatSettledKeyNamesAProbeChunk: green; red with the early return
  put back ("a probe's chunk left the settled days unnamed").
- go test -count=1 ./internal/usage ok; go vet for darwin, linux and
  windows ok; gofmt clean.
Not tried: timing a real Usage page with no recent tool calls.

Reported-by: gua2100 (Discord #feedback)
2026-11-08 00:12:29 +08:00
yetone 8373aaf14a usage: a settled session file touched keeps its settled days
The Requests page and the heatmap keep the days before the last two
counted (page-v1/heat-v1), under a key of the settled chunks. A session
file's chunk was keyed by its size and mtime, so a file touched without
a new call made a new key, and every poll of every period and filter
paired the whole history again (pageCold/heatCold). Agents do touch old
files: on this Mac a 15 min stat watch of ~/.claude/projects saw
settled files (last call 11-03/11-04) get their mtime moved exactly
+3600 s with the same size, and others get queue-operation, hook and
file-history lines that are no call. The key also hashed the chunks in
mtime order, so a touched file moved in it.

A session chunk is now keyed by its path and a digest of its rows
(hashRows, memoized per chunk serial, which names the file as read),
and each set is hashed in path order; a pairing breaks its ties by path
(timedRef.newer). A real change of rows still makes a new key
(TestPageSettledFromDisk). The key format changed, so the first start
after the upgrade counts the settled days once.

Measured on mote (M5 Pro), a sandbox HOME of 3000 Claude Code and 2000
Codex sessions (1.1 GB) and 300k gateway rows, the harness polling
requests+heatmap for today/7d/30d/all three times each, a line that is
no call appended to an old Claude Code file before each poll:
  before: heatmap 0.86-1.62 s every poll, requests all 1.34-1.43 s,
          30d 0.33-0.44 s
  after:  heatmap 0.13-0.42 s, requests all 0.15-0.44 s, 30d 0.07-0.69 s
          (the first poll of a period counts its recent days)
  first process, no caches: 17.4 s -> 10.8 s for the 14 calls; warm
  274 -> 278 ms. Sessions polls were 0.07-0.2 s in both.

Run on mote: go test ./internal/usage ./internal/sessions
./internal/usageapi ./internal/gui (ok); gofmt -l; go vet, GOOS=linux
-tags nogui and GOOS=windows go vet of ./internal/usage.
Broken by hand: TestSettledFileTouchedPairsRecentOnly is red on the old
heat_disk.go (paired 6 of 6); with the digest but not the path order it
is red too.
Not tried: GrayRabbit's own history (no sizes from them yet, #5618);
Windows or Linux timing; the GUI, which is unchanged.

Reported-by: GrayRabbit (Discord)
2026-11-07 21:47:58 +08:00
yetoneandmdwsk88 8de63c8b5a gateway, usage, gui, otlp: a request its agent canceled is no failure (#2398)
An agent that cancels its request before it is answered is logged 499
"the agent canceled the request": a person stops the reply, or sends the
next message while it is coming and Claude Desktop cancels it and asks
again, or Codex takes a subagent's report (#2398). The gateway already
says nobody failed (no rest, no reroute: TestCanceledRequestRestsNobody),
but Record.Failed is a status >= 400 or an error, so every page counted
it as a failure: the Requests card's "N failed" and success share, its
Failed filter, the CSV's error column, the Routing page's "errors your
agent saw", the Context page's error rate, the failed colour in the
Requests list, Routing and Recent calls, and the OTLP export's error
status. A Claude Desktop session on 2026-10-27 had four, each a message
sent mid-reply; #2398 had 91 of a day's 92 failures.

usage.CanceledBy tells the agent's cancel (499 with AgentCanceled) from
magpie's own limit on a request it asked of itself, logged 499 too and
still a failure (#2318). The cancel is logged with an error type of its
own, agent_canceled (usage.CanceledErrType, set in failedWith), so the
record says what it was and nothing guesses it from a 499, as #2398
asked. Record.Canceled reads the type, and a record logged before it by
its status and message, so the old log reads the same with nothing
migrated. A middleware's usage rows carry the type, so a module can tell
the cancel from magpie's own limit, which its rows (no error text)
couldn't.

Record.Failed leaves the cancel out; Totals counts it apart (Canceled, in
count and plus); RetriedRequest and the first-token and speed sums ask
Answered, so a canceled request is timed nowhere, as before; Codex's
memory of the last model still skips it. Routes and Recent calls say
canceled (set as a route is done and as a day's history is read, so old
days read the same); the Routing totals and the Context page's errors
leave it out. Ledger rows say canceled, and the pages show it muted, in neither the
failed nor the answered colour: the Requests list and its detail ("499 ·
canceled"), the Requests card ("N canceled", the success share of the requests not
canceled), the overview tile, the Routing page (a "gone" outcome, no
speed) and Recent calls (muted). New strings are in zh, zh-TW, ja and de.

The OTLP export: the records the gateway gives its observers for a
request and its try carry the type too (canceledAs), and a root span's
error.type follows Record.Failed, so a canceled request's span and its
try's go with status code 499, no error and no error.type.
TestOTelWaterfallFailureAndCancellation's canceled case held two failed
spans (the try the vendor refused as the agent left is recorded canceled,
as the request is); it now holds neither failed, both 499 and no
error.type. That change to the test is the point of this one.

mdwsk88's patch (aea0027fd) ran its tests at e056779a, a3768cdd,
c86fa2a3 and fcc0daa2, broke each check by hand (each red), and sent
real Claude Desktop cancels through a nogui build with a stand-in
upstream and OTLP collector. Its full record is on aea0027fd. Since
58541e5b (#4866) Codex's own-sign-in relay logs Codex gone mid-reply as
499 through canceled() too, so it counts as canceled
(TestCodexGoneMidReplyIsNoFailure). drawing_route.go still reads a
canceled request as not served when it decides whether a picture's
next request may stay on its provider: that is routing, not a count.

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

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

Co-authored-by: mdwsk88 <11055210+mdwsk88@users.noreply.github.com>
Reported-by: mdwsk88 (dawei on Discord)
2026-11-07 04:03:01 +08:00
yetone 2f660ca86b sessions, usage: Antigravity's gemini-4-argon-d is gemini-4-argon, not a second unpriced model
oioio's Antigravity database names gemini-4-argon's generator
"gemini-4-argon-d". agAppModel took only "-n" off a gemini-* id (Google's
gemini-3.8-flash-n, b2432754e), so the Usage panel showed gemini-4-argon
twice and the -d one had no price. usage.GeminiServing had the same
"-n"-only rule, so the gateway's log would call gemini-4-argon answered
as gemini-4-argon-d a swap.

Both now ask sessions.GeminiDeployment: a gemini-* id with one lowercase
letter after its last hyphen is that model's deployment. Google's own
ids never end in a lone letter (-lite, -nano, -pro, -001, -exp), and
other makers' ids (gpt-5-d, claude-sonnet-4-5-n) stay as written. The
rule is by shape, not by the catalog: a catalog lookup at parse time
would freeze a "-d" into the kept parses whenever models.json wasn't
there yet. antigravity's parseVersions and callParseVersions go to 1,
so parses and call shards kept with gemini-4-argon-d are read again on
update; nothing else is reread.

Run (mote, at this tree):
- go test -tags nogui ./internal/sessions ./internal/usage: ok.
- go vet, GOOS=windows go vet, GOOS=linux go vet -tags nogui on both
  packages; gofmt -l prints nothing.
- Broken by hand: GeminiDeployment put back to the old -n-only rule.
  TestAntigravityAppDeploymentName failed ("gemini-4-argon-d":
  "gemini-4-argon-d", want "gemini-4-argon", fields 19, 21, 22) and
  TestSwappedGeminiServingName failed ("gemini-4-argon answered as
  gemini-4-argon-d is the model asked for"); both pass with the change.
- Full suite runs after the push (go test -tags nogui -timeout 45m ./...).

Not tried: oioio's own database (only the model name was posted), and
a real gateway request that Google answers as gemini-4-argon-d.

Reported-by: oioio (Discord)
2026-11-07 00:22:13 +08:00
yetone 640825b09a usage: the Requests card's traffic line reads whole, and a row says how many images went by file
matrix0487 on Discord:
- The Requests card's line "↑ 13 GB · ↓ 13 MB · 图片文件省下 44…" was cut
  with an ellipsis. It was one nowrap span.
- A row's details say "图片文件省下 10 MB" and should say "10 MB(3 张)".

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

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

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

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

Reported-by: matrix0487
2026-11-06 11:46:25 +08:00
yetoneandyygutn 783537e810 sessions: the Antigravity app's own conversations count on Usage and Sessions (#2190)
xxooioo (Discord) asked for the Antigravity desktop app's calls made
without magpie's gateway on Usage and Sessions. The app keeps each
conversation as a SQLite database, ~/.gemini/antigravity/conversations/
<id>.db (WAL). Messages are encrypted, but steps.metadata is plain
protobuf: 1 the step's start, 9 the call's usage (2 input, 3 output,
4 cache write, 5 cache read, 11 response id), 20.3 the gen_metadata idx
of its generator, whose message names the model (field 19, else 21/22).

The reader opens the database read only, in one read transaction; a
response id seen twice is one call at its last step. Each conversation is
a read-only session under agent "antigravity", gated by Reads like every
other agent and added to Found. A call the app sent through magpie is
matched to the gateway's record by tokens and time the way agy's steps
are (agyLocal now covers "antigravity"), so it is counted once.
"gemini-3.8-flash-n", the model the rows name, is counted as
gemini-3.8-flash (b2432754e).

Fixture: the four steps.metadata rows yygutn posted on #2190, byte for
byte (testdata/antigravity/steps.tsv), under the schema he posted; the
decoded tokens and times match his figures. The gen_metadata rows wrap
the posted field-19 bytes in a field-1 message, since the rest of that
row was not posted.

Run on mote: go test -count=1 ./internal/sessions/ ./internal/usage/
./internal/agent/ ok; ./internal/gui/ ok but TestMainWindowCorners
(#3949, macOS 27, untouched); gofmt -l clean; GOOS=linux and
GOOS=windows go vet of sessions and usage clean (./... for linux stops in
Wails' cgo files, as without this change). skillsCounted says why the
app's skills aren't counted (step payloads are encrypted).
Broken by hand: agyLocal back to "agy" only fails
TestAntigravityAppCallThroughMagpieCountedOnce; the wholeCallReaders key
renamed fails TestAntigravityAppCalls (0 calls).
Not tried: a real app database (the app isn't installed on any test
machine); whether a call through the gateway records the same tokens;
conversation titles (not read; agyhub_summaries_proto.pb unknown).

Co-authored-by: yygutn <yygutn@gmail.com>
2026-11-06 10:07:06 +08:00
yetoneandggbdpq baf70992f6 usage: a call the vendor answered with another model is priced as the model that served it (#5340)
The ledger priced a call at the model asked for and fell back to the
model the reply named (Served) only when the asked-for one had no price
(#1498). That order is right for a relay that sells kimi-k3 as
moonshot-kimi-k3 and bills by the name it sold, but it also priced a
real substitution: claude-opus-5-5 asked, claude-opus-5 served. The
vendor bills for the model that ran. kaimo455's ledger had 836 such
rows, every one at the asked-for rate: $374.06 reported against
$493.28 at the served model's rate. gateway-key cost limits (KeySpent,
NewCoster) and budgets read the same pricer.

Pricer now prices a call the ledger marks swapped at the served model's
price. That covers a price the user set for the served model and every
other layer of BasePriceIn. A price the user set for the model asked for
still wins, 0 included (new provider.UserBasePriceIn is BasePriceIn's
user layer alone). When the served model has no price, the asked-for
one's stands. Renames, vendor aliases, serving names and region
deployments price as before, and rate windows still read each record's
own time. apiPricer, the API price behind a subscription window's whole,
follows the same rule: the served model's API price first, then the
asked-for one's.

Review changes on top of ggbdpq's patch:
- The swap is judged the way the ledger's Swapped column judges it: on
  the model id and on the name that went out (SentNameIn over the
  user's ModelWires). A model the user sends under the served one's name
  was answered as asked, so it keeps its own price. The patch judged the
  model id alone, so such a row was priced as swapped while the Requests
  page said it wasn't. The pricers' memo keys now include the effort,
  because the sent name depends on it.
- apiPricer (window holds) got the same rule. The patch left it on the
  old order.

Tests:
- TestLedgerPricesASwappedCallAsTheModelThatServed (patch, plus a
  ModelWires case) checks the ledger and the Requests page.
- TestLedgerPricesARenamedModelAsTheOneServed: the sol row (sol asked,
  kimi-k3 served, both priced) is a genuine swap, so it now prices at 3,
  not 2.
- TestHoldsPriceTheModelTheReplyNamed: claude-opus-4-7 answered by
  gpt-5.5 is priced at gpt-5.5's API price. Answered by an unpriced name,
  it keeps opus's.

Run on mote at this tree, on origin/main 4e7661adc:
- The three tests above: ok.
- Product files (ledger.go, window_holds.go, provider/models.go) put
  back to origin/main, tests kept: all three FAIL ("served luna:
  priced=true cost=10, want 33"; "sol: ... cost=2, want ... 3"; "a call
  answered by another model wasn't priced as that one: &{Input:5 ...}").
- servedInstead's sent-name check broken by hand (return true): the
  ModelWires case FAILs ("served luna: priced=true cost=33, want 10").
- go test -tags nogui -count=1 ./internal/usage/ ./internal/provider/
  ./internal/budget/ ./internal/otlp/ ./internal/middleware/: all ok
  (usage 44.9s, provider 158.3s).
- gofmt -l: clean. GOOS=linux go vet -tags nogui and GOOS=windows go vet
  of internal/usage and internal/provider: clean.

Not tried: a real ledger with Anthropic's refusal fallback. The rows in
the tests are built from the shape the reporter describes. The full
suite runs after the push.

#5340, kaimo455 (report, measurement and the proposed order)

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

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

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

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

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

Not tried: a real DeepSeek or other vendor account through a built app,
and a screenshot of the real app. The CSV export does not have the new
columns yet.
2026-11-06 09:17:10 +08:00
yetone 2df5d40ee3 usage: a ChatGPT API account's calls count in the same ChatGPT account's Codex window estimate (jctaoo on Discord)
A ChatGPT account signed in through Sign in with ChatGPT (chatgpt-api) and
to Codex draws on one plan's five hours and week. Only the Codex card reads
those windows, and its whole-window estimate (usage.windowHolds) keyed the
ledger's calls by provider + account, so the chatgpt-api calls were never
counted and the estimate came out low.

provider.SamePlanAccounts maps each chatgpt-api account to the Codex
account that is the same ChatGPT account, matched on the tokens'
chatgpt_account_id and chatgpt_user_id, both known and both equal, never
on a name: two Team seats of one email share the name and the user id,
not the account id. A token that names neither matches nothing, as
before. windowHolds (current and HistoricalWindowHolds) counts a matched
account's calls as the Codex account's, dry runs included. chatgpt-api
alone (no Codex account) is unchanged: its card reads no windows, so
there is nothing to estimate. Routing's caps and pace go by the vendor's
own reading of the windows and don't sum the ledger, so they are
unchanged; the per-provider account breakdown in the summary stays per
provider on purpose.

Run (mote, at this tree):
- go test ./internal/usage/ ./internal/provider/: ok.
  ./internal/gui/: TestMainWindowCorners/macOS_26_SDK red, the AppKit
  test filed as #3949 (macOS 27 on mote), untouched by this change;
  the rest ok.
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  internal/usage and internal/provider: ok. gofmt -l: nothing.
- quota-holds.test.cjs in Chromium and WebKit: 2/2 each (the GUI only
  renders the server's holds; no asset changed).
Broken by hand:
- remap removed in windowHolds: TestWindowHoldsCountsTheSameChatGPTAccount-
  ThroughTheAPI red, "whole 5 hours 2500 tokens, want 10000" and "the
  personal account holds 2500 tokens, want 10000".
- account id ignored (user id only) in SamePlanAccounts: red, "the Team
  seat holds 12500 tokens, want 5000" and "whole 5 hours 10000 tokens,
  want 2500" (token naming no account).
Not tried: a real chatgpt-api sign-in. No such account on this machine,
so whether OpenAI's Sign in with ChatGPT tokens carry chatgpt_account_id
and chatgpt_user_id (Codex's do, checked on the real Codex logins here)
is not verified; if they don't, nothing is matched and the estimate stays
as before. GUI suite in other languages not run (no strings changed).
2026-11-05 23:57:33 +08:00
yetone 7b5e773873 provider: a model at a window (claude-opus-5-5@300k) is priced as its model, so Cursor's sized ids have a cost
RyuJeXu on X (tweet 2117971061103100279), building an iOS board on magpie's
usage data: "cursor的用量好像不计费呀". Cursor calls showed no cost.

Cause: the Cursor plugin lists each model once per context size
(claude-opus-5-5@300k, @1m, gpt-5.5@272k, ...), lists them all at cost 0
(no price, pluginPrice), and its reply echoes the asked id, so usage rows
carry the sized id. pricedNames only took a window off grok- ids, so every
other sized id fell through the maker catalogs with no price. The plain ids
(claude-opus-5-5) were priced at the maker's list price all along.

Fix: pricedNames also tries the id with an "@<digits>k|m" window taken off
(modelWindow), for every provider. The window names the context size, not
a different model; long-context tiers still follow the call's own prompt
tokens through Price.At. Dated ids (claude-opus-4-5@20251101) and ids with
anything else after the @ are left alone. The regexp runs only for an id
with an @, since every listed model is priced on each Providers poll.

Tests:
- internal/provider/cursor_price_test.go: a moved Cursor provider prices
  @300k, @1m, upper case, a maker-prefixed id and gpt-5.5@272k/@1m as the
  plain model, through ListPrice, MakerPrice, PricedName(For), and its
  tier at 300K prompt tokens; a dated id, "@272", "@", "@272kb", an
  unknown model and auto stay as they were.
- internal/usage/cursor_window_cost_test.go: a Cursor row for
  claude-opus-5-5@300k costs what the plain id does ($6 each), auto stays
  unpriced, the page total is $12.
- grok_price_test.go: gpt-6-astra@500k under grok is now priced ($10/$50);
  grok-4.7-build@500k still isn't.

Run (all through mote-run, go1.26.8, base 823e7c250, the committed tree):
- gofmt -l internal/provider internal/usage: clean.
- go test -tags nogui -count=1 -timeout 45m ./internal/provider
  ./internal/usage ./internal/usageapi: ok 239s / 75s / 1s.
- GOOS=windows go vet and GOOS=linux go vet -tags nogui of provider,
  usage, usageapi: ok.
- Real catalog (a copy of the owner's models.json) before the change: every
  non-Grok sized Cursor id was unpriced; plain ids priced.

Broken by hand: with the old models.go put back, the two new tests fail on
every sized id (usage total 6 instead of 12) and TestGrokEffortListPrice
fails on gpt-6-astra@500k.

Not tried / not changed:
- No real Cursor call; the owner's ledger copy has only auto rows.
- Cursor's own auto and composer-2.5, and its own spellings (glm-5p3,
  deepseek-v41-flash-1017) and gemini-3.1-pro have no catalog price and
  stay unpriced; the plugin would have to give them a cost.
- Not ./... and no GUI suite: the change is in provider's price lookup
  only.
2026-11-04 22:45:40 +08:00
yetone 69167bc299 usage: a reply let go under a second after a wait four times longer tells no speed
pluviophile714 on Discord: a gpt-6.1-sol row on Routing read 1,539
tok/s (input 21,617, output 392, first token 8.2 s, total 8.3 s), where
another monitor measures ~70. The reply came whole about 255 ms after an
8.2 s wait. Its content was spread over that short window (flow 230 ms),
so the HeldShare flow check passed, and so did the 100 ms floor, and
392/0.255 s read as 1,539 tok/s.

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

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

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

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

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

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

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

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

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

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

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

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

Not tried:
- a real OpenAI key or real spend;
- the real app window;
- Windows and Linux test runs (vet only);
- the whole GUI suite: mote was running two other sessions' full GUI
  suites at load 250 to 400.
2026-11-03 15:30:44 +08:00
yetone dcc84dbc04 usage: the Overview says each account's credits, and the period's (lcyksp)
lcyksp (Discord #feedback) asked to see the WorkBuddy credits (积分) the
calls spent, per account too, not only tokens. The summary already summed
each reply's usage.credit into every group's Totals, and the Requests
page's ranking showed it, but the Overview's Accounts, Models and Agents
rows and its tiles never said it. Each row's line now says "{n} credits"
when a reply said any, and the calls tile says the period's sum. No tile
is added, so the four-tile grid is as it was; the text was translated
already.

Run on mote:
- go test ./internal/usage ./internal/usageapi: ok. TestPlanCreditsByAccount
  (new) checks each account's sum in the summary and the Requests page;
  with Totals.count not adding credits it is red (summary a@x: 0 of 0).
- GUI, every usage*, i18n*, ledger and credits file (both engines):
  1322 pass, 31 fail. plan-credits' new Overview test (5 languages, 420px)
  is red with page.js as before ("WorkBuddy · 70 calls"). The reds are
  usage-agents-hide (#2276, #3414), usage-fold "most on one screen"
  (#4790) and usage-ledger's return-to-live (#3104, #4078, #4626). Run
  alone at d8a34cbcf they fail the same way.
At the pushed head (on b328a7790): usage and usageapi ok; plan-credits,
usage-accounts and i18n-keys 32 pass, 0 fail.
Not tried: a real WorkBuddy account's Overview in the app. Calls from
before replies carried usage.credit say no credits.
2026-11-03 05:16:57 +08:00
yetoneandggbdpq 4bac5eed26 usage: a request's row says what went up to the vendor, tries summed (#4456)
RunMintOn asked how much a long session sends upstream: a proxy counted
~900 MB up in 45 minutes, and no ledger row said what a request sent.

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

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

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

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-03 05:08:39 +08:00
yetone e156fdd032 usage: a model's region deployment answered under its own name is not a swap (plugins#628)
WorkBuddy AI lists DeepSeek V4.1 Flash as deepseek-v4.1-flash-sg, its
paid id for the Singapore deployment. The plugin's product config names
it paidId to the free deepseek-v4.1-flash, with one window for both.
WorkBuddy answers under the model's own name, so the Routing page tagged
each request "请求 deepseek-v4.1-flash-sg · 实际 deepseek-v4.1-flash".
Old routes and kept usage rows kept the mark, so removing the model and
setting the provider up again didn't clear it (chansee97, plugins#628).

- RegionTail (internal/usage/served.go) covers a name that is the other
  with -sg, -us, -eu, -cn, -intl or -global after it. Such a pair is the
  same model, and Swapped excludes it.
- A region in both names, or a name that differs besides the region, is
  still a swap.
- Kept rows (request_page.go) and kept routes (gateway history.go's
  routedAgain) are judged again with it, so old marks go too.

Run on mote, at 5f0a84a00 plus this change:
- gofmt -l internal plugins: clean.
- go test -count=1 -timeout 45m on ./internal/usage, ./internal/usageapi,
  ./internal/budget, ./internal/davsync, ./internal/middleware,
  ./internal/otlp, ./internal/gui/..., ./internal/cli, ./internal/tui,
  ./internal/gateway/..., ./plugins/middleware/..., ./plugins/otel/... and
  ./internal/agent (every importer of internal/usage): all ok except four
  reds that are filed and don't touch swap marking:
  - internal/gui TestMainWindowCorners (#3949)
  - internal/cli TestEveryRouteHasACommandOrIsNamed (#4826)
  - internal/gateway TestCodexPoolSaysTheClientsVersion (#4807)
  - internal/gateway TestUnroutedRequestShownThenAnswered (#4200)
- GOOS=linux and GOOS=windows go vet ./internal/usage
  ./internal/gateway/...: ok.

After the rebase onto a32588528, which changed internal/usage's
request_page.go and match_chunks.go:
- ./internal/usage and ./internal/usageapi: ok.
- go test -run "RouteKept|Swap|Served|History" ./internal/gateway: ok.
- vet: ok.

Broken by hand, each red:
- RegionTail taken out of Swapped: TestSwappedRegionTail.
- The kept-row re-judge taken out: TestKeptRowRegionTailNotSwapped.
- The routedAgain re-judge taken out: TestRouteKeptRegionTailNotSwapped.

Not tried:
- A live WorkBuddy AI request to -sg, which would spend credits. That
  WorkBuddy answers -sg under the plain name rests on the report.
- The reporter's screen. This assumes the "实际" tag they saw is the
  Routing page's swap tag (or Usage's Served column, which is fixed by
  the same rule).
2026-11-02 19:26:26 +08:00
yetone 07dc0b4ec1 usage: an agy following the Antigravity app's gateway is counted once (Chamberlain_zyz on X)
An agy not connected on its own row follows the Antigravity app's
gateway, with the app's key (internal/agent/antigravity.go), so the
gateway records its calls as the app's ("antigravity"). Its transcript's
steps were matched only to records of agent "agy", so each one was
counted twice: Chamberlain_zyz's 17:00 hour showed Antigravity
39,104,506 and Antigravity CLI 38,562,861 tokens for the same calls.

agyGateway takes the app's session-less records too, at all three places
that matched agy's alone: the gateway side of the match key, the chunk
hints that pick which transcripts to open, and matchingRecords. The
match is still by exact tokens and time, so an app call of its own is
paired with an agy step only if both counted the same tokens within the
step's window. It is worked out when usage is read, so hours already
recorded are counted once too, for every user, with nothing to redo.

Run (mote, this tree):
- go test -count=1 -run Agy ./internal/usage: ok.
- Broken by hand (agyGateway back to "agy" alone):
  TestAgyStepThroughTheAppsGatewayCountedOnce and
  TestMatchOpensAgyChunksForTheApp fail; restored, ok.
- go test -count=1 ./internal/usage ./internal/sessions: both ok.
- go vet ./internal/usage, and with GOOS=linux and GOOS=windows: ok.
- The whole suite was not run: only these two packages are touched.

Not tried: a real agy through a real Antigravity app's gateway; the
reporter's case is taken from their screenshots and the app's wiring.
2026-11-02 19:08:59 +08:00
yetone 1829cd52ff sessions: a poll while a session grows makes only the rows it shows
VeryBTC on X (tweet 2117104179454091396) reported RSS that rises and
stays up while the window is open and a long-context session is active.
In that case every Sessions poll sees a changed file and rebuilds the
list. That rebuild copied every gateway-only session three times
(GatewaySessions, listedGateway, gatewayListed) and made each one a
Session row before EachMerged stopped at its 5000-row limit. It also
made every Claude Code file's path and key again.

- usage.EachGatewaySession walks the projection without copying it.
  gui's listedExternal stops at the list's limit and skips hidden
  sessions and sessions without an agent or id, as listedGateway did.
- sessions.EachMerged sorts indexes and makes a row only when the merge
  reaches it. The order is unchanged: newest first, stable on ties.
- listCCFiles reuses the last listing's path and key strings while a
  folder lists the same names. One file new or gone is stepped over.
  This holds ~32 B per file (~480 KB at 15k files), and the strings are
  shared with the listing it already held.
- page_memory.go's ~330 MB comment now has current numbers.
  gateway-sessions.md describes the lazy rows.

Per poll, on mote (go test probe through the real /api/sessions
handler, TotalAlloc):
  15k sessions x 10 turns, 400k ledger rows
    after a session file grows  150.6 MB, 201 ms -> 109.9 MB, 170 ms
    unchanged (warm)             17.2 MB         ->  12.0 MB
  3k sessions x 40 turns, 150k rows (no gateway-only rows past the cap)
    after a session file grows   31.3 MB         ->  29.6 MB
    unchanged (warm)              4.5 MB         ->   3.4 MB
  /api/usage is unchanged at 0.4 MB.

Tests:
- TestSessionsListMakesOnlyTheGatewayRowsItShows (gui) uses 3 natives,
  6000 gateway sessions in tied pairs, one hidden and one carrying a
  native's id. At limits 5, 40 and 6010, and with no limit, the rows
  equal the old pipeline's (listedGateway + gatewayListed +
  MergeExternal) after the JSON round trip. A grown native comes first
  with its new Last. The poll's allocation stays under 6000 rows' size.
- TestEachMergedMakesOnlyTheRowsItReaches (sessions): 15000 externals
  and 20 rows give MergeExternal's first 20, with allocation under a
  tenth of the rows.
- TestCCListingKeepsItsNames (sessions): a second listing of 3000 files
  is equal to the first, in at most 3n mallocs. A file added, files
  removed, and a folder gone with another new each list as a fresh
  listing does. Another agent's keys keep their own prefix.

Broken by hand, each red:
- EachMerged building every row first: 8.8 MB, the sessions test fails.
- The GUI handler back on the listedGateway(GatewaySessions) loop, with
  the lazy merge kept: 13.7 MB, the gui test fails.
- The gui test on origin/main's code: 23 MB, fails.
- The ccNames reuse turned off: 12197 mallocs, the listing test fails.

Run on mote (mote-run) at 73a1b8769, rebased on origin/main 07f4d46c5:
gofmt -l internal (empty), go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./... all clean. go test -count=1 -timeout
45m ./internal/sessions ./internal/usage ./internal/gui: sessions ok,
usage ok. gui is ok except TestMainWindowCorners/macOS_26_SDK, which is
#3949 (red on mote's macOS 27, an AppKit title bar test this change
doesn't reach). It was red the same way in the run before the rebase.

Not tried:
- A real app window with RSS measured over time. The numbers are
  allocation per poll from a probe.
- The rest of a changed poll: statsKept re-sums every session (~26 MB at
  15k), listing (~24 MB) and byKey (~9 MB). None was a cheap, safe
  change.
- Windows and Linux test runs (vet only).
- A gateway title store in the fixture. GatewayTitler's ReadDirs now run
  only for the rows shown.
2026-11-02 17:19:23 +08:00
yetone 276c806db2 plugins: a plugin's own requests are counted; a provider plugin's options get the editor (plugins#592)
zelong77 asked for two things once Devin 0.1.30's cache keep-alive
worked: its pings were invisible in magpie, and the interval and ping
count could only be edited in plugins.json. The owner decided pings are
shown as counted usage and the two numbers are edited in the GUI.

- host.js gives plugins input.magpie.usage(provider, call) and
  input.magpie.account(provider). usage validates the call (kind
  [a-z0-9_-]{1,40}, a model id, whole-number tokens from 0, status at
  most 999, error clipped to 500) and sends an unasked "usage" event;
  host.go hands it to plugin.OnUsage in the background.
- internal/usage/plugin_calls.go writes each one as a row of agent
  magpie on the plugin's provider (provider.PluginID) and account
  (provider.PluginAccountUser), with its kind. It is counted, priced
  and in every total, not a probe. Kind cache_keepalive is in the
  purpose catalog as "Cache keep-alive" (five languages), so the
  request log names and filters it. The ping itself still goes straight
  to Devin, never through the gateway, which would break the cache.
- /api/plugins reads every plugin's package options example, not only a
  middleware's or request hook's, and the Installed row offers the same
  Options JSON editor for a provider or agent plugin that suggests or
  has options (not while it is off). Clear's confirm no longer calls
  them a middleware's options.
- The Devin mover's min is 0.1.31, which reports each ping and gives
  its two settings' defaults (285 s, 6) to the editor. npm has 0.1.31
  (published 10:03Z); the plugins publish run is red only for
  think-tags' known E404 (plugins#180).
- docs: provider-plugins.md (the API, the options editor),
  gateway-sessions.md (the counted row beside probes).

Run at this tree (rebased on origin/main 85e37162e):
- mote (mote-run): go test -count=1 -timeout 45m ./internal/plugin
  ./internal/usage ./internal/gui ./internal/provider: plugin, usage,
  provider ok; gui red only in TestMainWindowCorners/macOS_26_SDK, the
  macOS 27 red already filed as #3949 (not this change's code).
- mote: GOOS=linux and GOOS=windows go vet of plugin, usage, provider ok;
  gofmt -l clean.
- mote: plugin-provider-options.test.cjs (new, 5 languages, 980/420px,
  Chromium + WebKit), plugin-gateway.test.cjs and i18n-keys.test.cjs:
  28 of 28 pass.
- The whole GUI suite (make test-ui) on WSL magpie-desktop (mote was at
  load ~100 with other sessions' suites, #4125), at the 8f804396f base:
  cut off after 498 test entries, when the session's background jobs
  were killed; 495 ok, 3 red, none on a page this change touches. Run
  again alone at origin/main 85e37162e, the same files are red there
  too: account-eye webkit (#4244), agent-expand-steady webkit 980px
  (#2935), add-button zh's 3000ms waitForFunction (filed #4792). The
  rest of the suite was not run.
Broken by hand (each red, then put back):
- host.go dropping the "usage" event: TestPluginReportsOwnUsage fails.
- plugins.go reading optionsExample for middleware/hooks only:
  TestProviderPluginOptionsExample fails.
- purpose.go without the Cache keep-alive kind:
  TestPluginKeepaliveIsCounted fails (purpose {}).
- plugins.js without ownOpts: plugin-provider-options.test.cjs times
  out waiting for the Options button in every language.
Not tried: a real Devin account's keep-alive ping reported into a real
magpie (needs a live Devin conversation idle for 285 s); a plugin can
report a row for any provider id, as magpie.load can.
2026-11-01 22:14:19 +08:00
yetone cbfbcb383b usage: a lead's answers are looked up in the blocks that name its conversation (#4370)
loggedAnswers, which leadFirst falls back to when affinity has lost a
Codex subagent's lead, read thirty days of the log into a Record a row
and kept the rows of one conversation. usage.VisitSessions reads only
those rows: a block whose Session and NativeSession strings don't name
the conversation is skipped, a row of another session is passed over by
its shape's string ids without becoming a Record, and a matched row's
strings are cloned out of the lent decode buffer. Each packed block's
sessions are kept once it is decoded (blockSessions, by weak pointer, so
no block the log let go is held), so a lookup decodes only the blocks the
conversation is in and the open tail. A page's copy with Codex
identities (which rewrite Session as a row is read) is read whole and
filtered on its records.

Run on mote (macOS 27.2), at load ~70:
- BenchmarkLeadLookup (40 blocks of 3000 rows, one conversation of 300):
  visit+filter 39-56ms and 2.9MB an op; VisitSessions 0.38-0.52ms and
  12KB.
- A copy of the owner's real usage.jsonl (8,853 rows, 1,270 sessions,
  18 blocks): every session looked up both ways gives the same records;
  6.9ms a lookup before, 3.4ms for the first and 0.39ms after, 14us for
  a conversation that isn't there.
- TestVisitSessionsIsVisitOfThoseSessions, red with the shape filter's
  session ids taken out; TestVisitSessionsRecordsKeepTheirStrings, red
  with the clone taken out; TestVisitSessionsSkipsBlocksOfOtherSessions,
  red with the known-sessions skip taken out.
- GOOS=windows go vet; GOOS=linux -tags nogui go vet: ok. gofmt -l: clean.
- go test -race of the new tests and the gateway tests of a lead's
  answers, in internal/usage and internal/gateway: ok (4.4s, 31.3s).
- go test ./internal/usage ./internal/gateway (whole packages) was
  still running on mote at load ~190 when this was pushed; its result
  goes on #4370.

Not tried: a real Codex subagent whose lead lost affinity; the lookup's
callers and filters are as they were, and the gateway's loggedAnswers
tests cover them.
2026-11-01 18:33:53 +08:00
yetone d7b42fcf23 usage: a chunk's one-byte numbers are read without Uvarint's loop, and a copying pass keeps its decode buffer (#4372)
A pass over packed chunks decodes every row's ~40 varints, and most are
under 128. binary.Uvarint was 42% of a lent pass's CPU on mote; take
now reads a one-byte number itself. A pass that copies its strings
(visitBlocks, rowsOf, within, the Codex pairs) decoded into a sync.Pool
buffer, which each collection empties, so after one it made the buffer
again and grew it to the largest block. It now decodes into its
rowBuffer's, as a lent pass does; unpackReusing takes the buffer and
whether its strings are lent apart.

Run on mote (M5 Pro), BenchmarkChunkRowsPass, 40 chunks of 3000 rows,
4 runs each, base 43d442700 and this change alternating twice (mote at
high load, so the lowest of each):
- lent: 16.3 ms at base, 13.0 ms here.
- copied: 55.7 and 55.1 ms; rowChunk.row's Record is most of it.
- copied after a collection: 3.34 MB and 45 allocs a pass at base,
  2.95 MB and 40 here.
- TestCopiedPassKeepsItsDecodeBuffer: red at base ("made 8
  allocations, want 4"), ok here.
- go test ./internal/usage: ok. go vet; GOOS=windows and GOOS=linux
  go vet ./internal/usage: ok. gofmt -l: clean.

Not done: a pass still decodes every chunk again; keeping them decoded
holds the history unpacked, which packing is there to avoid.
2026-11-01 18:19:53 +08:00
yetone 43d442700c usage: a row keeps its zone as an id, so the collector never scans rows (#4737)
A packedRow held its *time.Location, and that one pointer made every
[]packedRow a slice the GC scans word by word: the pages' rows of a
period, the kept decode buffers and every unpacked chunk, hundreds of
thousands of rows on each cycle. #4737's profile has gcDrain at 12% of
the CPU, scanObject 7.65% of it.

A row now keeps its zone as a uint16 into rowZones, a copy-on-write
list read with one atomic load. A zone is known by its String() and
offset, not its pointer: a time parsed with an offset, and a chunk read
from disk, has a new FixedZone each, and 30 parses of +05:30 are one
zone. time.Local is a zone as any other (a test sets it to UTC), so a
row keeps the zone it was written in, as before. Past 65535 zones a new
one's times are kept in UTC: the same instants. unpack looks a chunk's
Locations up once, not once a row. packedRow is 8 bytes smaller, so
TestPackedGatewayRetainsOversizedSnapshot's fixture has 180000 rows to
stay over its 32 MB.

Run on mote (M5 Pro):
- BenchmarkCollectWithRowsHeld, a runtime.GC() with 1M rows held:
  4.1-7.9 ms at origin/main 1fac66c06, 1.1-1.5 ms here (3 runs of 20).
- TestPackedRowsAreNotScanned: red with a *time.Location field put
  back ("packedRow.broke is a ptr"). TestRowZoneKeptThroughPack: times
  and zones (name, offset, String) the same through pack and unpack;
  red with the name-and-offset lookup taken out ("30 parses of +05:30
  added 31 zones").
- go test ./internal/usage: ok. go vet; GOOS=windows and GOOS=linux
  go vet ./internal/usage: ok. gofmt -l: clean.

Not tried: the GC share in a running magpie with a real history; the
benchmark is the scan this takes away, not the reporter's 12%.
2026-11-01 18:10:04 +08:00
yetone 1fac66c06d usage: a log snapshot read inside its stamp's tick is checked once, when it settles (#4368)
Each request the gateway writes wakes several readers at once: the menu
bar, the pages, the Sessions list. They all read inside the change
stamp's tick (100ms on a fine clock, 1s on a whole-second one). The read
that built the snapshot hashed the whole log after its parse, each later
reader in the tick hashed it again, and the first read once it settled
hashed it once more. That was four times the log for one request with
three readers, the recordHash 3.08s in KaranocaVe's profile.

Now a snapshot read inside the tick is not hashed after its parse, and a
reader still inside the tick takes it as it is. The first read once the
tick settles hashes it and makes it settled, as before, so nothing
settled is made of an unchecked read. A snapshot continued from one that
never settled still hashes its prefix first, since trusted needs the old
one settled. The disk copy is checked against the file when it is
loaded, as before.

What changes: a same-size rewrite by another program inside the tick
reaches readers when the tick settles, up to 100ms or 1s later, not
within it. A read a moment earlier would have had the old bytes anyway.
TestUsageSameTickRewriteIsNotCached's case with no append and no settle
now settles before it checks; its other seven cases are as they were.

Run:
- TestUsageReadersOfOneAppendHashTheLogOnce (new): an append, three
  readers in the tick, one after it settles. 1.00x the log hashed per
  append, 4.00x on the old code (red there).
- TestUsageAppendReadHashesNoPreReadScan: 0.80x per append + read,
  1.80x before.
- go test ./internal/usage: ok on mote (macOS 27.2, 44s) and in WSL
  magpie-desktop (Ubuntu 24.04, 32s).
- GOOS=windows and GOOS=linux go vet ./internal/usage: ok. gofmt: clean.

Not tried: the reporter's log size, and a filesystem with whole-second
stamps (where the tick is 1s, the same path).
2026-11-01 17:57:15 +08:00
yetone 344a59f9db gui: an unchanged Sessions poll answers Same without making the rows
The Sessions tab asks for every session each 15 s. When nothing had
changed, the handler still copied the kept listing, made a row of each
session, merged the gateway's sessions, read Codex's effort and the
vias, encoded every row and hashed them, only to answer X-Magpie-Same.
Over ~17k real sessions (69 GB of Claude Code and Codex history) that
was ~140 ms of CPU and ~24 MB of garbage per poll.

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

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

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

Not run: the full ./... suite, a Linux vet of internal/gui (cgo), the GUI suite (the page's api() and its
X-Magpie-Had handling are unchanged), Windows and Linux.
2026-11-01 15:27:49 +08:00
hlyx1 2b067434d7 provider: a Kimi Code membership's k3.1-pro and k3.1-pro-highspeed are priced at the Kimi API's (#4635)
hlyx1's fix (#4635, branch hlyx1/magpie kimi-code-k31-pro-price), asked
to be expedited by matrix0487 on Discord. Kimi Code's plans serve
k3.1-pro and k3.1-pro-highspeed, which models.dev's kimi-code-plan-*
catalogs list at the membership's $0. Neither id was in kimiCodeAPI, so
a membership's call on either was unpriced on Usage. They now map to
kimi-k3.1-pro and kimi-k3.1-pro-highspeed, like k3 to kimi-k3, and the
Requests list names that model (PricedNameFor).

Checked: Kimi Code's own /models answer (internal/catalog/testdata/
kimi-code-cn-models-2026-10-31.json) lists k3.1-pro "K3.1 Pro" and
k3.1-pro-highspeed "K3.1 Pro Highspeed". Kimi's pricing page
(platform.kimi.ai/docs/pricing/chat, read 2026-11-01) and models.dev's
live moonshotai entry both give kimi-k3.1-pro $2 in / $10 out / $0.20
cached / $2 5m write, and kimi-k3.1-pro-highspeed $4 / $20 / $0.20 / $4.
The fixture's new entries match models.dev's api.json in id, name, cost
and canonical_model_id.

The alias stays Kimi Code's (kimiCodePlans): the test's relay catalog
now lists a k3.1-pro of its own at $0.50/$1, which keeps that price, and
PricedNameFor(relay, k3.1-pro) stays k3.1-pro.

Docs: docs/reference.md, docs/subsystems/providers-accounts.md.

Run on mote (Go 1.26.8), at this change rebased on fb3942ee6 (the
pushed head adds only 784b66366, app.js and a GUI test): gofmt -l
clean; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
go vet ./... ok; go test -count=1 -timeout 45m for internal/provider,
usage, gateway, agent, cli, routes, sessions, usageapi: all ok.
TestKimiCodeListPrice and TestKimiCodeCost red with models.go at
origin/main (k3.1-pro {0 0 0 0} false; kimi-code-cn/k3.1-pro
priced=false cost=0, want true 3.264), green with it. Taking the
kimiCodeMember() check out by hand turns PricedNameFor(relay, k3.1-pro)
into kimi-k3.1-pro and the test red.
Full go test ./... at base da0005df8: every package ok but internal/gui,
red on TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
TestMainWindowCorners/macOS_26_SDK (#3949), both open on main and not
touched here.
Not tried: a real Kimi Code membership's k3.1-pro call through the GUI.
2026-11-01 11:19:26 +08:00
ggbdpq 96a37ee5e3 usage: the vendor's own alias for a model isn't a swap (#4593)
A request via Top-API for deepseek-v4.1-flash answered under
deepseek-flash was marked a swap. It isn't one: DeepSeek renamed its
V4.1 Flash deepseek-flash (api-docs.deepseek.com/updates, 2026-09-10:
"Change the model name to deepseek-flash to call the latest V4.1 Flash
model"), and every exemption Swapped knows is structural - a dated or
pinned tail, a Bedrock geography, a relay's word in front, a serving
name - none of which an official rename reads as.

VendorAlias reads a small table of rename pairs the vendor's own docs
state (deepseek-flash is V4.1 Flash), both ways, over squashed bare
names so case and separators don't matter; a bareModel'd name feeds it,
so the dated spellings either side writes hit it too. Only pairs the
docs state go in: a retired name routed elsewhere (deepseek-v4-flash)
is another model, and catalog's SameModel keeps deepseek-flash an id of
its own. The kept-row readers take the alias in beside the other
exemptions, so rows recorded before it are read back as not swapped.

Run (sandbox HOME, GOTOOLCHAIN=auto, -tags nogui):

  go test ./internal/usage -run 'TestSwappedVendorAlias|
  TestKeptRowVendorAliasNotSwapped'  ->  ok (base f811bf291: both FAIL,
  the seven alias pairs read as swaps)

  go test ./internal/usage -run 'TestSwapped|TestKeptRow|TestListed|
  TestRelay'  ->  ok

Reviewed and landed as one batch of 12 commits (gua's #4593, #3269,
#3881, #2887, #3289, #2718, #2855, Edward4226's #2718 key-path
sibling, and four review follow-ups). Run for the batch, whose last
commit's tree is 5d58a75f3:
- Full suite before the rebase (base d307aa648, wsl-run magpie-desktop,
  go test -tags nogui -count=1 -timeout 45m ./...): 81 packages ok. Reds,
  all with issues and none in code this batch touches: internal/agent
  TestInstalledVersion, TestGrokInstalled, TestOmpDetectedWithPiDir
  (#4033, #3548, #3141); gateway TestUnroutedHeldReportSaved (#4300);
  gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestColdTurnsTaken (#4510); provider
  TestClaudeAccountServesModelsListedSinceItsFetch (#3174). Run alone at
  origin/main 573b21f4b, TestGrokInstalled, TestOmpDetectedWithPiDir
  and TestSettingsSaveKeepsWhatItDoesNotSend are red there too. The
  other four pass there alone.
- After the rebase onto origin/main 573b21f4b, at this tree:
  internal/usage, update, gateway and provider ok. In internal/agent,
  the #4033/#3141 install-detection reds plus TestCopilotFolderFrom-
  AnIDEPluginIsNotTheCLI and TestZedAppPath. Those two are flaky the
  same way at origin/main (-count=10 alone: 4 and 5 of 10 red) and are
  already listed in #4033. The #3269 tests (TestCopilotLauncher*) pass
  5 of 5.
- Rebased onto origin/main ef63ef4a2. The #2855 commit met 0b9727ec9
  (#2974) in responses.go: the streamed item's done now takes both, the
  upstream's own id (thinkUp) and the made-over item; and in
  gateway-routing.md main's paragraph is kept with #2855's clause. That
  matches gua's latest head (range-diff: context only). At tree d7c76c6fa:
  internal/gateway, provider, usage, redact and update ok; vet
  GOOS=linux -tags nogui ./internal/..., darwin and GOOS=windows for
  gateway and provider.
- Rebased last onto origin/main d8f7d089f (5 commits: internal/agent
  and GUI files only). At tree 0d4bfd8c8, the pushed one: internal/agent's
  TestCopilotLauncher*, TestClaude*, TestOwn* and TestVSCode* ok, -count=3;
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI red once there, as it is at
  main (#4033). Vet of internal/agent: darwin, linux and windows.
- gofmt -l clean. On mote: go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- Broken by hand, each turning its guard red: the lift gate
  (TestReadingKeepsARefusalsRest, TestAutoVisionKeepsOffARefusedAccount);
  the named-time condition (TestNamedQuotaTimeReplacesAGuess); the
  filter-chain hop (WholeReply/glm-5.3-flash); Edward's aAt
  (TestKeyAllowanceElapsedResetStartsAgain); and the old
  magpieMadeReasoning, which panics in TestMadeReasoningSaysItsTextOnce/
  no_summary. Every new test of gua's is red at base d307aa648.
Not tried: real OpenAI, DeepSeek, GLM or ChatGPT accounts; a real VS Code
1.144 install on Windows; a GUI run (no GUI files are touched).

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 07:06:19 +08:00