Commit Graph
306 Commits
Author SHA1 Message Date
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
yetoneandethereal49 0565c0bbac usage: a test's comment no longer says the Requests page's word Unmarked (#4524)
i18n-keys' "a plugin's words are its own" was red on main since
5787d758a: plugins/routing/i18n.js has "Unmarked", and a comment in
internal/usage/search_calls_test.go quoted it, so the word read as core's
too. The comment now says "the unmarked purpose". Ethereal49's patch
(739bc64 on their fork), taken as written.

Run on mote: i18n-keys.test.cjs, 0 fail (was the one red);
go test ./internal/usage -run TestSearchRowsListTheirPurpose.

Co-authored-by: ethereal49 <hongyeluo49@gmail.com>
2026-11-01 02:29:59 +08:00
ggbdpq d1b62f4604 usage: price a local session's call at the provider its file names
What changed

A call read from an agent's own session file (omp's model_usage, say) has
no billing provider of ours — its row reads session-unknown — so Pricer
priced it only through the maker lookups, which answer nothing for models
no vendor catalog lists as its own, even when the models.dev catalog
lists the model under the provider the file recorded (openrouter listing
typesafe/jev-1.14 at $0.042/M in, #4278). When the effective price is
unknown and the record is one of those, its session provider now prices
the call — but only what the catalog itself affirms: the very model id,
listed under that provider, with a price. A provider models.dev doesn't
know, a model it lists that provider without, and an entry with no price
stay unpriced, the CSV cost empty, rather than priced at another entry's
guess; the pricer's memo is keyed by the session provider too, so two
files naming different routes price apart.

Run

- go test -tags nogui -run 'TestUnknownProviderPricedBySessionProvider' ./internal/usage — red before (the named route stayed unpriced), green after
- go test -tags nogui ./internal/usage/... — ok
- gofmt -l internal/usage — clean

Generated-by: GLM-5.3-FlashX (ZCode)

Reviewed and applied from #4278 (ggbdpq, 645e80ab2). It differs from
the patch hashed on the issue only in its git-version trailer.

The reporter's own call stays unpriced for now. models.dev's default
api.json, which magpie fetches, does not list openrouter
typesafe/jev-1.14; only api.json?type=all does. #4278 stays open for
that. The Sessions page prices a session-unknown call through its own
priceOf, by model only: #4591.

Broken by hand: ledger.go back at main with the test kept, and
TestUnknownProviderPricedBySessionProvider fails.

Run (on mote, through mote-run):
- Full `go test -tags nogui -count=1 -timeout 45m ./...` with this stack
  on c30d3b7b6: 82 packages ok. internal/gui was red only on
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514, SearchAll from
  b09349d17) and TestColdTurnsTaken (#4510). Both are filed, and neither
  touches this stack.
- Rebased onto 29d0ab39f, which changed internal/gateway since then:
  gofmt -l, go vet (darwin, GOOS=linux -tags nogui, GOOS=windows) and
  go test -count=1 ./internal/gateway ./internal/usage ./internal/provider
  ./internal/sessions all ok at the pushed head. go build ./... ok for
  darwin, linux (nogui) and windows.
- go test -race of the gateway tests this stack adds or touches, on
  the stack at fb29cd30f: ok.
2026-10-31 23:35:27 +08:00
yetone e94fb18b8f usage: a page's cells and the heatmap's days read strings where they were decoded (#2278)
partsOf, cellsBefore and heatDaysOf read each chunk through a chunkRows
that copied the chunk's whole string section first. What they keep is
unique's handles (a cell), a date made by Format and numbers (a day), so
the copy was thrown away chunk by chunk. They now read through
lentRows(), as newest and the Codex readers already do.

Run on mote:
- go test ./internal/usage/ -count=1 -timeout 45m: ok (40s).
- -race -count=3 on TestPartsReadStringsWhereDecoded,
  TestRowBufferKeptPastCollections, TestRequestCells*, *Heat*, *PageSplit*: ok.
- TestPartsReadStringsWhereDecoded (new): 8 packed chunks, 1.1MB of
  strings. With the three sites put back to `var rows chunkRows` by sed
  it is red: partsOf 1,188,672 bytes, cellsBefore 1,197,568, heatDaysOf
  1,187,616. Green with the change; the cells' names and the days' counts
  are right after the buffer was decoded over again.
- Real history copy (66GB, ~12k session files), magpie web in a sandbox
  HOME, heap profile 40s after start, two rounds each:
  unpackReusing 183MB / 174MB before, 106MB / 113MB after;
  partsOf 76MB / 78MB before, 55MB / 56MB after.
  A warm poll of every page reads cached parts and is unchanged.

Not tried: the Windows and Linux boxes (no OS-specific code).
2026-10-31 20:48:05 +08:00
yetone 213d59f3b3 usage: a first start pairs the history once for the page and Codex's effort (#2278)
A first start, with no sums on disk, paired the whole history a few
days at a time (coldSpans) for the warm-up's page of All (pageCold),
then again for Codex's effort of the same period (effortCold), or the
other way round when the Sessions overview asked first. Both read the
same blocks and name the settled days by the same heatSettledKey, so
whichever runs first now counts both from its one pairing and writes
both files: pageCold counts the effort when its filter is empty and
effort-v1.json lacks it, effortCold counts the cells of the period's
unfiltered page when page-v1.json lacks them.

Run on mote (M5 Pro), at this tree (rebased on 7e0fe83d4):
- go test -count=1 ./internal/usage/: ok (25.5s).
- TestFirstBuildPairsOnceForPageAndEffort asks the page then the
  effort, and the effort then the page, each after a cold restart:
  the second pairs no span, and both answers equal a build alone.
  Broken by hand: pageCold given no effort key, red ("page first:
  effort … after N spans"); effortCold counting no cells, red
  ("effort first: page …").
- Real cold start on the 11,925-file fixture (8.5GB .zst + 17GB
  jsonl), `magpie web`, two runs each, alternated:
  before (v0.1.2368's tree) CPU 3:11.45 / 3:04.84, footprint peak
  332 / 335 MB; after CPU 2:54.02 / 2:57.12, peak 330 / 325 MB. The
  heatmap, requests, overview (0/7/30) and stats (0/30) answers are
  byte for byte the same. Load on mote 22-28 from other sessions.

Not changed: the footprint's peak barely moves; the two builds ran one
after the other already (coldTurns), so this saves their CPU, not a
peak.
2026-10-31 18:57:39 +08:00
yetone 9551fadcb4 gateway: reasoning streamed with no count in its usage is marked unknown, not read as none (#4545)
A reply whose stream carried reasoning (reasoning_content, Anthropic
thinking deltas) while its usage counted no reasoning tokens was
recorded Reasoning 0, ReasoningHidden false: the same record as a reply
that never reasoned, and a tool-only one was timed with its reasoning
counted as answer. hidesReasoning now takes the usage's reasoning count
and marks such a reply ReasoningHidden, the record's existing "the
stream doesn't tell how much it reasoned". Reasoning stays the vendor's
0; nothing is estimated, so no new field or Flags bit (rowReasoningHidden
512 is the one it already uses).

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

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

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

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

Not tried: a real Claude API key (Anthropic's own endpoint) and Zhipu,
vLLM or Ollama Chat streams; no full go test ./...; no Windows or Linux
run of the tests.
2026-10-31 17:46:51 +08:00
yetone f1d0c0bfdd usage: Codex's effort is kept on disk for each period, not one (#2278)
effort-v1.json held one entry. The Sessions list asks Codex's effort
for All and the overview for its own period (30d by default), and the
two wrote over each other, so every start, a warm one too, paired one
of them a few days at a time again (effortCold): ~100 MB of the warm
start's live heap at the moment and seconds of CPU. The file now holds
a list of up to four, the last written first, one per since; a file of
one entry, as earlier releases wrote it, is read as that one, so an
upgrade pairs nothing again.

Run on mote (M5 Pro), at this tree:
- go test -count=1 ./internal/usage/: ok (28.6s).
- GOOS=linux and GOOS=windows go vet ./internal/usage/: ok.
- Broken by hand: effortDiskPeriods = 1 turns
  TestCodexEffortPeriodsKeptApart red ("all started again, paired 6 of
  6"); 4 is green.
- Real start on the 11,925-file fixture (8.5GB .zst + 17GB jsonl),
  `magpie web` warm after a cold start, two runs each:
  before (e4c784177) CPU 10.34s / 10.99s, footprint peak 273 / 271 MB;
  after CPU 7.94s / 9.09s, peak 267 / 268 MB. The heatmap, requests,
  overview (0/7/30 days) and stats (0/30) answers are byte for byte the
  same. Heap profiles of the warm start before showed effortCold under
  the overview route at every sample; after, no effortCold is run. Load
  on mote was 28-37 from other sessions.

Not changed: heat-v1.json still holds one entry; a start asks the
heatmap for one filter only, and no warm-start profile showed it built
again.
2026-10-31 17:29:12 +08:00
yetone 7b09d2c951 provider: a model can be listed by an id of the user's at its provider, asked for by its own
zeewell on X (tweet 2116404121930432888): relays serve one model under
ids of their own (deepseek-v4.1-flash-1017, grok-4.6@500k). They want to
give each one their own id at the provider layer. magpie then lists,
routes, groups and finds groups by that id, and the upstream request
still carries the vendor's id.

Choice: a new per-model map, settings' ModelIDs
("<pid>/<local>": "<own id>"), served through the wire names that
already exist. ModelSameAs was not widened. It means "same as another
vendor's model": it lends specs and joins found groups. Making it rename
models everywhere would change every existing user's ids and refs.
ModelWires was not reinterpreted either, for the same reason. ModelIDs is
ModelWires turned round: a wire keeps magpie's id and changes the one
sent, and this keeps the one sent and changes magpie's. Settings.Wires()
merges each entry in as a wire name (wrapped by a "<pid>/*" wire). Every
place that sent a ModelWires name (gateway, usage ledger, request page,
UpstreamName, UpstreamNameAs) reads Wires(), so the upstream id needs no
new path. An explicit ModelWires entry for the same id wins.

- Listed by the local id: Available, liveIDs/liveByID, Serving and
  ListPrice translate through OwnModelID. /v1/models, agents' lists,
  Resolve, routing groups and found groups (auto/<local>, merged with
  every other provider serving that id) all see the local id.
- Only a provider of the user's own (Account == nil) takes one. An
  account's or a plugin's request is built from its list's id, which no
  wire reaches.
- Two variants of one provider given one id: the latest given it wins,
  and the earlier one is listed by its own id again. The CLI names it.
  The editor refuses two rows given one id in one save. A model of the
  provider's own id that a variant is listed by (plain grok-4.6 beside
  grok-4.6@500k) is not listed while the variant has it.
- The user's values are never overridden. SetModelID moves picks,
  contexts, fallbacks, groups' members/rules/fast/placed/off/weights/
  classifier/pick, the pickers' lists, every per-model setting
  (Settings.MoveModel) and gateway keys' models (provider.ModelMoved,
  set by access) to the new id, but only where nothing is under the new
  id yet. Agents' own files are not rewritten: an old provider/<own id>
  still resolves and is sent as it is. Group match patterns and key
  patterns stay as written.
- Key limits: a key held to either id passes for both (modelAllowed:
  the ref, OwnModelID, ListedModelID). Group members use the same check.
- Usage: model = the listed id, served = the vendor's id from its reply.
  The price is the own id's first.

CLI: magpie model id <provider/model> [<id>|--reset], magpie model ids.
GUI: Providers > a provider's editor > Names & levels > "Listed as",
beside Same as. It is staged with the editor's Save and taken back by
Restore default, in zh, zh-TW, ja and de. Accounts have no box.
Docs: providers-accounts.md, gateway-routing.md, and site start.html in
en, zh and ja.

Run (mote-run, at this tree rebased on 841326709):
- go test -tags nogui of internal/gateway, provider, settings, access,
  usage and cli: ok. internal/gui: ok but for
  TestSettingsSaveKeepsWhatItDoesNotSend's SearchAll, red on main since
  b09349d17 (#4514, yiqiui's patch); its ModelIDs case passes.
- TestAutoVisionDoesNotBuildListsAgain: 457 allocations with 4 models,
  458 with 400 (main 459), searcherModel within its 50. Reading
  Shared() per list cost 3041; SharedModelIDs parses only modelIDs once
  per file change, the settings path is built again only when what it is
  built from changes, and Serving looks up the own id only when a key is
  listed to some model.
- TestCoreScriptBudget: raised by 1,178 bytes for the Listed as box,
  with a note.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet ok.
- GUI: provider-listed-as (en, zh, zh-TW, ja, de), provider-same-as,
  provider-detect in Chromium on mote and WebKit on the Linux box (mote's
  WebKit launch hangs, #4125): 9 of 9.
Broken by hand, each red: the wire name (wires), the list (list), a key
held to the own id (keyown), the key move hook (hook), liveIDs, liveByID,
moving refs (moverefs) and moving per-model settings (movemodel).
Not tried: a red for ListPrice's or Serving's own-id lookup; a real relay
with variant ids; Match patterns are not rewritten to the new id. The
full Go suite and the whole GUI suite are still running and their reds
get their own issues.
2026-10-31 15:04:44 +08:00
yetone 19594cc1cb usage: a span's trimmed chunk keeps only the strings its rows name
A first start's page, heatmap and Codex effort build pair their history
in 4-day spans, and a session file that reaches past a span is trimmed
to it (within). The trimmed chunk cloned the file's whole Strings
table, whose strings all point into the one decoded block of the file:
every span it reached held the whole file's text. within now copies the
strings its kept rows name into one block of its own, renumbers them
("" stays id 0), and rebuilds Shapes through setTexts.

Run on mote, at 2eac91617 plus this change:
- go vet ./internal/usage; go test -count=1 ./internal/usage: ok.
- Broken by hand (every remapped id set to 0 in the mote copy):
  TestFirstBuildPairsSpans FAIL.
- A cold start on the owner's real history copy (~52 GB of Codex
  rollouts, 448k Claude calls) with the window's polls, two runs each,
  against v0.1.2331's build: heatmap, requests, overview 0/7/30 and
  stats 0/30 answers byte-identical. The most live heap in gctrace
  went from 250/253 MB to 245/241 MB. CPU 3:07/3:22 against 3:13/3:07
  (load 4-14). The footprint peak stayed at 329/334 MB against
  333/336 MB: within noise.

Not done: a 2-day or 1-day span took the most live heap to ~235 MB but
changed the last digit of the requests page's float sums and added GCs,
so the span stays 4 days.
2026-10-31 14:16:20 +08:00
yetone 2eac916170 gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue
xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.

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

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

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

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

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

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

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

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

Not tried: a Responses WebSocket open across the expiry. The GUI shows
no expiry or issuer yet (issued keys look like plain keys until pruned).
A held issuer's /v1/magpie/usage shows its own rows, not its keys'. The
refused-key 401 doesn't count toward tooManyAuthFails. Issued keys sync
through davsync like other keys, with their expiry.
2026-10-31 13:44:29 +08:00
yetone 30f29564eb sessions: a change to one agent's calls reads that agent's files again, not every shard (#2278)
callCacheVersion named every shard, so raising it for a fix to one
agent's calls threw away every agent's calls and re-read the whole
history on the next start: on a real history of ~4,700 transcripts
that is minutes of CPU and the ~310MB peak, for a change to Claude
alone.

Each agent now has its own number in callParseVersions. A shard frame
records the number its agent had when it was written (callDiskState
.Parser), and loadCalls drops a frame whose number is not the current
one, so only that agent's files are read again. CallCacheVersion()
adds the raised numbers, so the usage caches built on calls
(requestDiskBinary, heat_disk) still start again when any agent's
calls change. callCacheVersion stays for a change to every agent or to
the shards' form.

Existing shards are kept: the map is empty, gob leaves a zero Parser
out, and CallCacheVersion() is still "calls-v15".

Run on mote (zone worktree at this head):
- go vet ./internal/sessions ./internal/usage for darwin, linux and
  windows: ok. go build ./...: ok.
- go test ./internal/sessions ./internal/usage: ok.
- go test -race -count=3 -run 'TestCallParseVersionRaise|Calls|Shard|Frame'
  ./internal/sessions: ok.
- TestCallParseVersionRaiseReadsThatAgentAlone: a Claude transcript and
  a Codex rollout; raising claude scans the Claude file alone, with the
  same calls, and the next start scans nothing.
- Broken by hand (the Parser check in loadCalls removed): red at
  call_versions_test.go:67, "scanned map[], want Claude's file alone".

Not changed: internal/gui's TestCoveredWindowStaysUp is killed at 30s
on mote, as in #4125.
2026-10-31 12:34:40 +08:00
yetone 5787d758a7 usage: a search a provider's model runs with its own tool is a Web search row
cybercaius on Discord: with magpie's search APIs off, DeepSeek was asked
to search, and Usage › Requests showed nothing of it; its purpose list
had only All, Connection check and Unmarked.

DeepSeek searches by itself on its Anthropic and Responses APIs
(searchHosts): Claude Code's web_search_20250305 and Codex's web_search
are relayed as sent, and the reply carries server_tool_use and
web_search_tool_result blocks (#669), or web_search_call items. magpie
read only the reply's tokens. Its Chat API has no search tool, so a
Chat client's request there, with the searcher and the APIs off, gets no
search at all.

searchTally (search_native.go) counts what the reply shows: Anthropic's
server_tool_use blocks named web_search and
usage.server_tool_use.web_search_requests, the Responses API's
web_search_call items. What a stream named as it went (a block's start,
an item done, by id), what a whole reply or the stream's end listed, and
what the usage said are counted apart and the most is taken, so an item
named added, done and again in response.completed is one search. The
relay's usage sniffer and both translated readers feed it into an
unexported Usage.searches; after the request's own row,
logNativeSearches writes one row per search (at most 20): Source search,
Kind web_search, the request's agent, provider, host and model, status
200. No query is kept and nothing goes to telemetry: the rows ride the
probes' lane as the search API rows do (listed, counted nowhere, not
exported). An event is parsed for it only when it holds server_tool_use
or web_search_call.

The purpose filter needed no change: a search row's kind already gives
it Web search (TestSearchRowsListTheirPurpose guards that, and passes on
the old code too). The Requests tab shows the row with its model and
provider as it shows a plan's own search.

Run (mote, at this tree):
- go test -count=1 -timeout 45m ./internal/usage ./internal/gateway: ok
- go vet ./internal/gateway ./internal/usage, GOOS=windows and
  GOOS=linux go vet ./internal/gateway: ok; gofmt -l clean
Broken by hand:
- without this change TestOwnProviderSearchesAreLogged fails:
  "anthropic whole: 0 search rows, want 1"
- counting every streamed web_search_call event instead of the done
  ones by id: "responses stream: 4 search rows, want 2"
Not tried: a real DeepSeek account (the fixtures are #669's DeepSeek
reply and Anthropic's documented stream shape); the translated readers'
counting has no test of its own; no GUI file changed, so no GUI run.
2026-10-31 11:25:39 +08:00
yetone ef8dfaa463 usage: a span pairs a long session's rows within its reach alone (#2278)
A first build pairs four days at a time, but a chunk was taken whole
into each span it reached. A session file or ledger block written over
weeks was paired in every span: on the owner's history the late spans
paired ~257k rows each, near all of it, ~230k of them from ~180 such
chunks. coldSpans now takes a chunk reaching past a span's
[from-heatReach, to+heatReach) as its rows within that window, and its
rows of no time, as a chunk of its own (rowChunk.within). Rows past the
reach pair with nothing counted in the span. Lazy gateway blocks and
chunks with raw rows are taken as before.

Run (mote, at this head):
- go vet ./internal/usage; GOOS=linux and GOOS=windows go vet
  ./internal/usage: ok.
- go test -count=1 ./internal/usage ./internal/usageapi: ok.
- TestFirstBuildPairsSpans gains a Codex thread written over 20 days,
  each call with its gateway record; spans of 1, 4 and 14 days must
  match pairing at once (total 11).
- Broken by hand: within keeping no rows -> TestFirstBuildPairsSpans
  red (the long thread's effort 71 vs 141 at once). Not caught: a
  window narrowed by heatReach on each side stays green, since the
  fixture's call and its record are a second apart.
- Real history (owner's, sandbox HOME copy, cold start, 3 runs each,
  against v0.1.2310's change): phys_footprint_peak 313/318/317 MB vs
  324/318/325 MB (avg 316 vs 322). CPU 4:15/4:07/4:04 vs
  4:10/3:58/3:59 at load ~23 (within noise, maybe +2%). The span log
  shows the late spans' rows 256,871 -> 144,691. heatmap, sessions
  overview (0/7/30) and stats (0/30) JSON byte-identical in all three
  runs; requests equal to 1e-9 (summation order).

Not changed: the peak now sits on the requests page's first build
(~73MB) beside the sessions stats cache (~85MB retained) and Codex
effort (~28MB); those come next.
2026-10-31 11:00:40 +08:00
yetone a377ffde9e usage: a first build pairs four days of history at a time, not two weeks (#2278)
coldSpan was 14: each span of a first start's pairing held ~1000 to
4700 chunks' matched blocks, priced stubs and Codex pairs at once,
the largest part of the cold-start peak. Four days holds less of it
at the same CPU. The comments that said "a few weeks" say days, and
TestFirstBuildPairsSpans checks 1, 4 and 14 days a span against a
pairing of every chunk.

Run (mote, through mote-run): go build, go vet ./internal/usage,
go test ./internal/usage ./internal/usageapi: ok.

Real history copy on mote, cold starts:
  coldSpan 4   peak 319/322/328 MB (avg 323)  cpu 3:55/4:23/4:05
  coldSpan 14  peak 354/356/342 MB (avg 351)  cpu 4:20/4:08/4:05
  (an earlier pass: 14 → 353/372, 4 → 332/326, 2 → 325/323 with
  cpu 4:26/4:32; 2 days bought little more, so 4.)
heatmap, overview 0/7/30 and stats 0/30 JSON are byte-identical; the
request page differs in 10 floats by summation order only (<1e-9
relative), counts and every other value the same.

Rebased onto b09349d17 (probes.go, search_calls_test.go in usage); go vet
and go test ./internal/usage ./internal/usageapi again there: ok.
2026-10-31 10:35:47 +08:00
yetone c420559fdf usage: a search API's asks, and a plan's own searches, are rows of the request log (#3528)
cybercaius on Discord: "能记录代搜 API 的用量信息吗,在使用过程中看不到它用了哪些代搜 API".
Nothing recorded which search API answered a search, how often, or whether
it failed.

Each ask of a search API (askSearchAPIKeys) and each search sent to Kimi
Code's or WorkBuddy's own search service (ownSearch) is now a row of
Usage › Requests, source "search" (usage.SourceSearch, kind web_search):
the vendor or plan, the host asked, ok / found nothing / refused / the
error, and the time. The row is a probe: it is listed, never counted in a
total or a chart, and never exported. Telemetry reads no usage rows, so
nothing is added to it. The query is not written: an error's text is
scrubbed of it (url.Error reduced to op and host, and the plain,
QueryEscape and PathEscape forms replaced). The Usage page badges the row
"Search API", or "Web search" under a plan's provider, muted.

Run (rebased on 3e5aa1151):
- go test ./internal/gateway ./internal/usage ./internal/settings
  ./internal/budget on Linux (WSL magpie-desktop): ok. With -tags nogui
  there the root package is ok; internal/cli and internal/gui were still
  running at the push (owner: ship at once), any red they show is filed.
- TestSearchAPIAsksAreLogged, TestSearchAPIFailureKeepsNoURL,
  TestOwnSearchIsLogged, TestWorkBuddyPluginSearches,
  TestSearchAPIRowsListedNotCounted; TestCoreScriptBudget ok.
- go vet for darwin, linux and windows on gateway, usage, settings; gofmt.
- usage-ledger-search.test.cjs in Chromium and WebKit, en zh zh-TW ja de,
  wide and narrow; i18n-keys.
Broken by hand: without logSearch the gateway tests go red; with the
query left in an error's text TestSearchAPIFailureKeepsNoURL goes red;
with IsProbe not naming search, the totals test goes red; the old page.js
fails the GUI test.
Reds the same at base 3e5aa1151, filed: usage-ledger, -chart, -ttft,
-open-settled (#3104, #4078, #3001, #4263, #4489); internal/agent on Linux
(#4033).
Not tried: real Tavily, Kimi Code or WorkBuddy accounts; the Routing page
shows no search rows; the whole GUI suite.
2026-10-31 10:32:00 +08:00
yetone 64aaf421ac usage: a packed row holds its time as unix ns and a zone, its tokens in 32 bits (#2278)
A packedRow was 184 bytes; it is 152 now. Its time.Time (24 bytes) is
kept as unix nanoseconds and the *time.Location it was in, read back
with Time(); its six token counts are int32s, not int64s. No call
reads or writes 2^31 tokens; one past it is kept as the most an int32
holds (tokensOf), not wrapped. The archive's encoding is varints and
is unchanged.

Run (mote, through mote-run): go build, go vet, GOOS=linux and
GOOS=windows go vet ./internal/usage, go test ./internal/usage
./internal/usageapi: ok. TestRowTokensAndZoneKept (new) packs a row in
a +05:30 zone at 123ns with 3e9 and -3e9 tokens, and checks time,
zone and the saturated counts after a pack/unpack round trip.
Broken by hand: tokensOf as a plain int32(n) makes it red ("read back
Input -1294967296 ... want 2147483647").

Real history copy on mote (cold start, magpie-ext = v0.1.2296 change):
  cold peak  this 346/342/354 MB (avg 347)  before 373/349/359 (avg 360)
  warm peak  this 273/262 MB               before 297/276
heatmap, overview 0/7/30, stats 0/30 and the request page JSON are
byte-identical to before.
2026-10-31 10:24:23 +08:00
yetoneandggbdpq a808c31a75 usage: a plan key's window is reckoned from the calls routed on that key (#3747)
A plan bought with an API key (Kimi Code, a GLM Coding Plan, MiniMax's
and the rest of planquota) tells its windows to the key, and when a
provider holds several keys each card names its key: the card's user is
the key's name (PlanQuotas). The ledger names a key's call by the key
alone, ProviderKeyName with no account, since accountOf answers "" for a
key (#557). windowHolds looked a window's calls up by provider and
account, so a key card looked for calls answering as "new" or "old",
found none, and said "not enough data" at 87% used (davisjiahao).

A call now answers as the account it went out as or, when it names no
account, as its key. The key was in the ledger all along, so calls
logged before this fall in too and nothing is rewritten. The same key
also places the call in that card's dry runs, which were keyed by the
card's user already. Every planquota provider's named-key cards go
through this one predicate; the ledger's other Account() readers (the
accounts view, filters, CSV, requests page) keep their meaning.

Not covered, as before: a lone key's card names no user and is never
reckoned (holdsBounds), an unnamed key beside others gets a masked-key
card the ledger can't name, and calls made before a key was renamed
stay under the old name. The lone key is filed as #4507.

Ported from gua2100's branch hunt91-l3-3747-key-card (deb1c0ba0) as
written, reviewed line by line.

Run at this head (rebased on 5c637f17b), on mote:
- go test -tags nogui -count=1 ./internal/usage ok (20.4s).
- go vet -tags nogui ./internal/usage clean on darwin, GOOS=linux and
  GOOS=windows; gofmt -l clean.
- In review: -run TestWindowHolds ok with TZ=UTC and TZ=Asia/Shanghai.

Broken by hand: with window_holds.go put back to main's, the new
TestWindowHoldsReckonsAPlanKeysWindowByItsName fails with "new's 5
hours: <nil> (why "none"), want 2500 routed, whole 2874", the
reporter's symptom.

Not tried: a real Kimi Code key's card in the GUI; a full
go test ./....

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-31 09:07:36 +08:00
yetone 86e19b9b74 gui: a cold start's turn lets the matcher's scratch go when it ends (#2278)
Each turn of the warm-up and of a page's first ask (coldTurns) now ends
with usage.ReleaseMatchScratch: the request matcher's kept maps, picks
and row buffers, which sat for scratchLinger (30 s) under the next
turn's read of the history. The priced blocks stay, so the next turn's
queries don't price the history again.

On mote, a sandbox HOME with the real history (13k sessions, ~720k
gateway calls), 75 s with ten answers asked every 5 s, phys_footprint
peak:
- start with its caches: 260 and 263 MB, against 274 and 285 MB at
  v0.1.2284.
- first start, run alternately with v0.1.2284: 359, 359 and 361 MB
  against 360, 360 and 364. CPU 3:41-3:47 against 3:35-3:41. The
  slowest first answer was 31.5-32.4 s against 30.9-31.8 s.
- the heatmap and the requests answers are byte for byte the same.
Dropped: releasing the priced blocks too (ReleaseScratch). That gave
253-255 MB with caches, but 362-369 MB on a first start, which priced
the history again in each turn.

Run on mote at 03d21ab8e + this:
- go vet ./...: ok.
- go test ./internal/usage: ok.
- go test ./internal/gui: red only in ten real-window AppKit tests,
  killed at their deadlines under load. They are the same ten that fail
  on a clean a6951cc63 (#4125, #2645).
- TestMatchScratchGoesPricedBlocksStay goes red with
  ReleaseMatchScratch made a no-op, and red when it releases the priced
  blocks too.
- gofmt -l: clean.
Not run: Linux vet of internal/gui (no gtk4 on wsl-run). After this was
run, the rebase onto origin/main brought in 11fc687c0 (a GUI test's
wait), 06c2c35d1 (Claude's interactive start) and 6ba593de0 (the main
window's passing note). They touch none of these files.
2026-10-31 08:31:15 +08:00
yetone f2eb56c6bb usage: a first start pairs the history a few weeks at a time, not at once (#2278)
With no sums on disk (a first install, or a version that counts rows
otherwise), the page's cells, the heatmap's days and Codex's effort
before the cut were built from one pairing of the whole history. Every
gateway block was priced, every session row's message id went into one
set, and every call into one match map. On the owner's history that
was ~212 MB of the warm-up's 341 MB in use and the cold start's peak.

coldSpans builds them as a day's start advances them (pageAdvance),
14 days at a time. A span pairs the chunks with a row from heatReach
before it to heatReach after. Each chunk's oldest row is kept by its
serial. A gateway block not priced yet is priced by a pricer of the
span alone, and its rows go back to the pool after the span. The
recent days are then paired as on any kept start.

The page's cells come out in another order (by span, then chunk), so
TestSettledCountedAsVersioned now sorts them before it hashes. The
sorted hash is the same for a pairing at once and in spans, so
settledCountVersion stays. Tests that count a pairing of every chunk
use pairAtOnce (coldSpan 0).

Run on mote at the pushed head (rebased on b62fa332f): gofmt -l
clean; go vet ./internal/usage for darwin, linux and windows ok;
go test -count=1 ./internal/usage ok (20.0s); go build . ok.
Broken by hand: TestFirstBuildPairsSpans goes red when a span pairs
only its own days (lo, hi := from, to): the effort differs.
Bench, real history (a year), cold first start, against v0.1.2256,
two rounds each, on mote at load ~22:
  no GUI polls:  footprint peak 451, 407 MB (2256: 493, 484);
                 live heap max 318, 289 MB (2256: 367, 362)
  GUI polls:     footprint peak 483, 410 MB (2256: 534, 532);
                 live heap max 316, 290 MB (2256: 395, 406)
The heatmap's answers are byte-equal to 2256's. The request page's
differ only in float digits from the summation order (232 floats,
largest relative difference 6.5e-14); every other value is equal.
Not tried: a start on Windows or Linux.
2026-10-31 03:13:28 +08:00
yetone f45c3c96b6 usage: a day's first start advances the kept sums from the last cut, not a pairing of all history (#2278)
The page's cells, the heatmap's days and Codex's effort before the last
days are kept on disk (page-v1.json, heat-v1.json, effort-v1.json) under
a key that names the cut, today minus two days at midnight. The cut moves
each midnight, so each user's first start of a day found none of them,
and paired the whole history again three times. On the 240k-row bench
history that peak was 506-538 MB, against 235-325 MB for a start of the
same day.

Each file now also holds the cut and since its sums were counted at.
When the current key misses, the file's sums still stand if the key at
their own cut is the same: the chunks are split again at that cut, named
as heatSettledKey names them, and compared with the file's key. Then
only the chunks of the days since that cut are paired. The rows between
the two cuts are added to the kept sums, and the sum is written under
the current key. The heatmap also drops days before a since that moved
forward a week. A full pairing is left for a first install, a raised
version, or a settled chunk that changed.

settled_version_test blanks a page's cut and since, as it blanks its key
and at. They say when the cells were counted, not how, so
settledCountVersion stays at 1. Files written before this commit have no
cut, so the first day change after the upgrade still pairs everything
once.

Run at 9cd9cfed0 (rebased on cfb06e11c), on mote:
- go test -count=1 ./internal/usage: ok (16.8s)
- GOOS=linux and GOOS=windows go vet ./internal/usage: ok
- gofmt -l internal/usage: clean

New tests (cut_advance_test.go): TestHeatmapDaysAdvanceACut,
TestPageCellsAdvanceACut and TestCodexEffortAdvancesACut. Each holds the
clock at Sunday 2026-10-04, then at Monday, and checks that every
pairing on Monday is below all chunks and that the result equals a cold
pairing. The heatmap test includes a call 368 days back that leaves the
window when the week turns.

Broken by hand:
- With the days between the cuts left out (all three), all three tests
  are red.
- With the advance turned off (all three), all three tests are red on
  the pairing count.

Real history (mote, ~/r2278: 240k gateway rows and the full session
history, window endpoints polled every 5s, clock moved one day by a
temporary build-only env that is not in this commit, caches restored
with cp -Rp each run):
- day change, advance off: peak 506, 518 MB
- day change, this commit: peak 418, 398 MB
- the same day: peak 325 MB
- /api/usage/heatmap and /api/usage/requests were byte-identical with
  the advance on and off.

Not tried: a real overnight day change on a user's machine. The cold
first-install peak (~480-538 MB) is unchanged by this commit.
2026-10-31 01:48:43 +08:00
yetone 62a1dcdd79 usage: a start's log blocks are of log-v1.bin's pages, not the heap (#2278)
logDiskRead read log-v1.bin whole with os.ReadFile, and the kept blocks'
Archives were slices of that copy, so a 240k-call history held ~7 MB of
file bytes in the heap for good. GOGC then let the heap grow by about as
much again. Where the system maps the file, the blocks are now of its
pages, the same way requests-v1.bin's blocks already are (diskMapping,
readMapped, m.read()). Elsewhere it is read into the heap as before.

Run at the pushed head, on mote, through mote-run:
- go vet ./internal/usage: ok. GOOS=linux and GOOS=windows go vet
  ./internal/usage: ok.
- go test ./internal/usage: ok. go test ./internal/usageapi: ok.
- New TestLogDiskBlocksMapped: 2 full blocks plus a tail are written,
  the log is restarted and read again, and each full block's Archive
  must be inside the mapping. Broken by hand (c.mapped = m dropped): red,
  "block 0: read from the file into the heap". Green again restored.
- go test ./internal/gui: FAIL on the AppKit window tests only
  (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
  TestMainWindowCorners and 7 others), killed at their deadline on mote
  under load ~24. These are #4125 and #2645, and the same tests fail
  without this change.

Bench on mote, with the real 240k-row history: a warm restart while
the Sessions tab polls, and the heap profiled at 200 s.
- In use: 174.1 and 175.0 MB with this change, 187.6 MB without.
- Footprint at 200 s: 290 and 297 MB with it, 297 MB without. mote's
  load (~24) makes this ±20 MB, so the footprint gain is not resolved.

Not tried: Windows, where the file is still read into the heap.
2026-10-31 00:28:43 +08:00