Commit Graph
360 Commits
Author SHA1 Message Date
yetone 90d54a2675 usage: Factory Droid's own sessions count under Not through magpie (_meouwu on X)
Droid's sessions were on the Sessions page, but Usage's "Not through
magpie" read no Droid calls, so what Droid spent straight at Factory or
a BYOK provider never added up.

Droid writes no tokens into a transcript: a message line has its time,
the message and a reply's modelId. Read from droid 0.231.0's binary
(its session schema) and the real runs in testdata/droid-skills, what a
session spent is only in <id>.settings.json: tokenUsage, its own running
total (input less the cache, output with thinking, cache read and
written), and lastCallTokenUsage, the latest call alone. So each session
is one call of its total, at its last message (the day Sessions already
counts the same total on), under its settings' model; a subagent's is
under the session that called it, a fork's starts at none.

- sessions: calls_droid.go reads a session with its settings whole
  (wholeCallReaders "droid"); droidFiles joins callSources, behind
  Reads("droid") and allowed() like the rest. WSL is not read: the
  Sessions page doesn't list Droid in a distro either.
- No double count: a session whose settings or any reply names magpie's
  own entry (custom:magpie/...) or a custom model whose baseUrl is the
  gateway's port on loopback is left out whole; the gateway counted those
  calls, and a total can't be split by model. A session is judged when
  read, again once it or its settings change.

Tests: TestDroidCalls (the 4 real droid 0.231.0 sessions: tokens, time,
model; custom:mh on localhost:11434 counted, on the gateway's port left
out; Reads off counts none), TestDroidCallsOfSessions (subagent, fork,
no settings, magpie's entry, Factory's own model), and
TestDirectDroidSessionTotals in usage. Both sessions tests are red on
origin/main (0 calls); with the gateway check broken by hand both go red
on the gateway cases.

Run (mote): go test ./internal/sessions
./internal/usage ok; go vet + GOOS=linux/windows go vet of both ok;
gofmt clean; go test ./internal/gui ./internal/agent ok.
Not tried: a real Droid session against Factory's own models (no Factory
account here); no GUI change.
2026-11-16 18:56:32 +08:00
yetone 91b3af8470 usage: Qoder's own calls are under Not through magpie, by the credits they cost (eating_dream on X)
Qoder's and Qoder CN's sessions were on the Sessions page and nowhere in
Usage: callSources never listed their files. They are Claude Code's
lines, and are now read for calls as Claude Code's are (ccCallAgent:
claudeCallLine, the call cache, continuations and revisions).

Qoder writes a reply on its own models ("auto" among them) with every
token count 0 unless QODER_EXPOSE_TOKEN_USAGE is set: the transcript
writer (vUl in qodercli, the same in Qoder.app's worker, qoder-agent-sdk)
zeroes them unless the model is a custom one, from qodercli 1.1.0 on. It
keeps the reply's credits. So such a call carries Credits (new on
sessions.Call, passed to the ledger's Record), counted with no tokens
and no price; "auto" names no model, so nothing is priced for it. A
model of the user's own, whose counts are written, is read and priced
as before. The GUI's direct section already shows credits (ledCredits).

Fixture: testdata/qoder-1.1.89 is lines as qodercli 1.1.89's writer
lays them out (key order, zeroed usage, credits/original_credits/
billable, a reply with no usage), read from its npm bundle; the ids are
made up. The older invented qoder fixtures got message ids of their own
(Calls counts a message id once across agents, and they shared
WorkBuddy's m1/m2).

Run (on mica, at f07e3e067's tree, rebased on 269e54de5):
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage
  ./internal/gui: ok
- GOOS=linux and GOOS=windows go vet of both packages: ok; gofmt -l clean
- red on the old code (origin/main's calls.go, call_cache.go,
  call_continuation.go, call_revisions.go, ledger.go with the new tests):
  TestQoderCalls got 0 calls, TestDirectQoderCallsByCredits Credits 0
  Credited 0

Not tried: no real Qoder transcript was captured (qodercli needs a
signed-in account here); the format comes from the bundle's writer. No
GUI change, so no GUI suite. A reply Qoder writes with no usage at all
is not counted. The tokens of Qoder's own models can't be shown: Qoder
doesn't write them.
2026-11-16 16:51:51 +08:00
yetone 9bcdcfb7d1 provider: Antigravity's Orchestrator ids are priced as the Gemini model each is
guyng35955 on X: an Antigravity local session's calls under
gemini-pro-orchestrator-argon, gemini-pro-orchestrator-carbon and the
worker gemini-flash-worker-agy showed tokens and cache but cost "—". They
are Orchestrator mode's role ids, which no catalog prices.

pricedNamesTo now reads them as the model Antigravity's docs name
(https://antigravity.google/docs/models/): Orchestrator (Argon) plans with
Gemini 4 Argon, Orchestrator (Carbon) with Gemini 4 Carbon, and Gemini 4
Hydrogen does the implementation, so the worker is priced as
gemini-4-hydrogen. gemini-pro-orchestrator (Carbon's id before Argon came,
per the Antigravity Context Window Monitor extension 1.17.1's table) is
Carbon too. Only these four ids, under a route prefix or an effort suffix;
a name only like one stays unpriced. Every cost reads through this one
place: the Sessions list and overview (sessions.priceOf -> PricedName),
the usage ledger, its totals and per-agent view (Pricer -> ListPrice /
MakerPrice). Prices are taken as rows are read, so sessions recorded
before the update are priced once it is installed; nothing is re-parsed.

Google publishes no rate for the role ids themselves; they are priced at
the named model's models.dev list price.

Run (mote, at this tree):
- the three new tests red on origin/main's models.go (every role id
  unpriced), green with the fix; red again with argon mapped to carbon
  by hand
- go test -tags nogui ./internal/provider ./internal/sessions
  ./internal/usage: sessions and usage ok; provider ok but for
  TestRemoveListedAccountLeavesHiddenNamesake (ZCode account removal,
  not reached by this change), which passes alone -count=3 with and
  without this change; filed as #6764 with its output
- go vet, GOOS=linux and GOOS=windows go vet of those packages; gofmt -l
  clean
Not tried: the reporter's own Antigravity database, or a real Orchestrator
mode account (this Mac has no Antigravity app and the account isn't
offered Argon). No GUI change.

Reported-by: guyng35955 on X
2026-11-15 22:17:30 +08:00
yetone e99307fb86 usage: a file read anew forgets when the last one was written or pruned (#6760)
TestWholeKeptAcrossReset was red on main at -count=5 (4 of 5, "after a
restart: <nil>"), and TestFeedExpiresACursorOlderThanItsTombstones at
-count=3 (2 of 3, "must be refused, not skipped over: <nil>"). Both had
the same cause. A package-level "last done at" outlived the file it was
about:
- carryLoad reset the window-holds map and dirty bit for a new path,
  but not wroteAt. carrySave then waited 30s from the last file's write,
  or from a held clock later than this one, and wrote nothing.
- feedLoad reset everything but pruned, so a journal read anew wasn't
  pruned for an hour after another one was.
In the app it matters when the config dir changes (MAGPIE_CONFIG_DIR, a
sandbox HOME) without a restart, or when the clock moves back.

Each reset is now done where its sibling fields already were.

Run on mote at origin/main 30de93e9e plus this commit:
- red before, on the unchanged files: TestWholeKeptAcrossReset
  -count=5 FAIL ("after a restart: <nil>"), and
  TestFeedExpiresACursorOlderThanItsTombstones -count=3 FAIL;
- after: go test -count=3 ./internal/usage/ ok (126s);
- go vet ./internal/usage/, plus GOOS=linux -tags nogui and
  GOOS=windows: ok. gofmt clean.

Not run: the full suite. Both mote and mica were busy with other
sessions' full suites under suite.lock (mica at load 63). The change is
two field resets in internal/usage, and nothing outside the package
reads carry or feed.
2026-11-15 21:58:28 +08:00
yetone d50ae6fcb1 usage: an agent group says when its last call was
The Usage page will fold a small client idle for days into one Other
row (WJaunita45604 on X: dozens of randomly named test clients). It
needs each agent's newest call in the period, so Group gets Last
(json "last", omitted when zero), set for agents only by
summaryCounts.add and by direct().

Run: go test ./internal/usage -run 'AgentsSayTheirLastCall|LastCallMovesOn'
on mica, ok. Broken by hand: without the Last assignments both tests
go red.
2026-11-15 02:50:48 +08:00
yetone 80a315a70a gui: a closed or hidden page lets its Sessions and Usage caches go in 30 s
What a visit to the app's page read stayed until each cache's own idle
timer fired: the Sessions stats after 2 minutes, the Requests chunks
trimmed at 2 and forgotten 5 after that, each chunk's derived keys at 3.
On a real history (acctp, requests-v1.bin 71.5 MB) a web page open 70 s
and closed held 123 MB at the close, 108 MB a minute on, 74-76 MB three
to five minutes on, and was back to the tray's 52 MB only at ten.

The page now says it has gone from view (POST /api/page-away, sent from
the visibilitychange listener every window already has, when hidden: a
browser fires it as a tab closes, and the Mac window's orderOut
dispatches it too). 30 s later (pageAwayFor), unless a Sessions or Usage read
was in flight or ended since, the stats, overviews and tags go
(letGoStats, split out of forgetIdleStats), the Requests chunks and each
chunk's derived caches go (usage.ForgetPages: trim(0) + dropDerived,
idle timers stopped) and the pages go back to the system. A second tab
still polling, or a tab looked away from for under 30 s, keeps them. The
beacon writes nothing, so held's provider.Changed passes it by. The panel
sends it as well when it hides; it reads no Sessions or Usage page, so
there is nothing of its own to keep.

Tests: TestPageAwayLetsStatsGo (red with the forget skipped, and red
when a read after the beacon is ignored, both broken by hand) and
TestForgetPagesLetsChunksGoAtOnce.

The core script budget goes up 83 bytes, with the reason in its
comment: the beacon is folded into the existing listener and packed to
its shortest form (335 over as first written, with a pagehide listener
and a panel check).

Measured on mote (pageclose2.sh, the acctp history, a web page open
70 s and closed, footprint-overlay build like the release):
  before (w88): close 123 MB, +60 s 108, +180 s 76, +300 s 74, +600 s 52;
                peak 154
  after  (w89): close 123 MB, +45 s 92, +90 s 90, +180 s 54, +600 s 53;
                peak 149, 3.08 s CPU over 11 min
  final (w90, visibilitychange only): close 122 MB, +45 s 93, +90 s 90,
                +180 s 55, +600 s 52; peak 152

Run: go test ./internal/gui ./internal/usage on mote (ok);
GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./... (ok);
16 visibility GUI files + i18n-keys in chromium and webkit: red only in
routing-pin-away (the same subtest red alone at origin/main 4739ec92c,
2026-11-14 17:00:00 +08:00
yetone 925bc7188b usage: the Requests card's up arrow opens what the bytes sent upstream were made of
theforeveriris (X, 2121408745616162998) saw 8169 requests send 8.6 GB
up and 1.0 GB down and wanted to know why. About 1 MB a request is
normal: every request sends the whole conversation again, with the
system prompt and the tools' definitions. This shows it.

Gateway: promptOf, which already parses the body off the request path,
now also counts the bytes of the system prompt, the tool definitions
and images in the body it read. upParts scales those to the wire bytes
and puts them on Record.UpParts. Nothing new runs on the request path,
and a body that isn't parsed stays "Not measured".

Usage: a packed row keeps the mix in 255ths under flag rowUpParts
(32768); the row stays 152 bytes. Totals gain up_calls, up_measured,
up_system, up_tools and up_images, and Shares carry up_bytes and
up_calls by agent and by model. settledCountVersion goes 4 -> 5, so
settled days are counted again once on the next start.

GUI (Usage -> Requests): the "↑ 8.6 GB" on the Requests card is a
button that opens a "Sent upstream" card: the average per request, one
sentence on why, a bar and legend for Conversation / Tool definitions /
System prompt / Images / Not measured, and the top 8 agents and models
with bytes sent and per request. The open state is kept; × closes it.
A request's details get a "Made of" line. zh, zh-TW, ja, de strings.
Entrance is 200ms ease-out, no movement under reduced motion.

Run (mote, at this head on 27e43ed26):
- go test ./internal/usage ./internal/usageapi: ok
- go test -run 'Prompt|UpParts|UpBytes|DownBytes|Traffic|Ledger|
  CodexOwnTurn' ./internal/gateway: ok
- go test -run Budget ./internal/gui: ok (after the rebase)
- go vet -tags nogui for darwin, linux, windows on usage, gateway,
  usageapi, gui: ok; gofmt -l clean
- GUI: usage-upload.test.cjs 32/32 (chromium + webkit, 1180 and 420,
  en zh zh-TW ja de); with i18n-keys, i18n-en-no-cjk,
  usage-ledger-bytes, usage-traffic, usage-ledger-detail: 144 pass,
  0 fail
- GUI subset i18n*, usage*, ledger* at f1f34d624: the only reds are
  usage-agents-hide, usage-cards-hide, usage-fold,
  usage-hidden-way-back, usage-ledger, usage-range-times and
  usage-speed-all-models. They are red the same way on origin/main
  f1f34d624 without this change and are already filed (#3414, #3415,
  #6003, #6294, #6295, #6499, #5834).
- Screenshots of the card: chromium en 1180 light, webkit zh 1180
  dark, chromium zh 420 light.
- Benchmark: promptOf on a 1.17 MB body, 2.8-3.9 ms/op with counting
  vs 3.2-3.7 without, same allocations (noise).
- Broken by hand: without the b.again guard,
  TestPromptKnowsWhatItsBytesWere goes red.

Not run: the full go test ./... and the full GUI suite. mote and mica
were loaded, with a suite already queued under suite.lock.
2026-11-14 10:22:25 +08:00
yetone f53c4a1a14 usage: three tests hold the clock, so midnight never falls between a call and Today (#6486)
TestAliasCallsAreTheGatewaysNotDirect stamped its direct call 6 minutes
before time.Now() and asked Direct(Today), so in the six minutes after
local midnight the call was yesterday's: red on mote at 00:00 PST and on
macOS CI at 00:07 UTC (run 43523008440). TestLoopsCountedPerModel and
TestRequestsCountedOnceWithTheirRetries do the same with stamps up to 9 s
back (same class). All three now take their time from holdClock at a
fixed noon, as TestPeriodsReadTheClock does.

Run (mica, at 783b69b8c + this):
- the three tests -count=3 in TZ=UTC and TZ=Asia/Shanghai: ok
  (and in UTC, Asia/Shanghai, America/Los_Angeles on mote: ok)
- broken by hand: held at 00:00:03 instead of noon, all three red
  (gateway_alias_test.go:44 "0 calls", loop_count_test.go:55,
  retried_requests_test.go:55), so they read the held clock
- go test -count=1 ./internal/usage: ok 53s; go vet ./internal/usage: ok
Not run: the full suite (test-only change in one package).
Not changed: #6474 (TestWalletCapHolds, the 5 minutes before midnight)
is another package's sibling and stays open.
2026-11-14 08:31:52 +08:00
yetone 08f77528f4 usage: the serials sourceDigest met go when idle
sourceDigests.by and .last, the serials met this turn and the one
before, stayed for the life of the process: 577 KB of a real history's
idle heap. They only order which digests heat-digests.bin keeps first
when there are more than it holds (2*65536, against ~17k session
files). dropDerived, the 3-minute idle drop, now writes what was made
and lets them go; sourceDigest notes a read (derivedUsed) as the other
per-chunk caches do.

TestDigestTurnsGoWhenIdle: the turn's serials are nil after the idle
drop and the next key hashes nothing again. Red with the nil-ing taken
out by hand ("kept 1 and 0 serials when idle").

Run at this commit on mote (load 23.7, over its 18 cores; mica's disk
was full): go vet for darwin, linux and windows ok; go test
./internal/usage ok (52s), ./internal/gui ok (132s). Real Codex history
in a sandbox HOME (~/r2278), page open 30s then 8.5 min idle: liveHeap
13.13 MB against 13.68 MB before; the heap diff shows sourceDigest's
577 KB gone. Not run: the full suite.
2026-11-14 04:02:26 +08:00
yetone a532b646eb usage: the set of listed session paths is not kept on the index
readRequestBlocks makes a set of every session file's path (on), and
noteBuilt kept it on the index for save, the only reader, which it calls
right after. The set outlived the chunks' forget: 853 KB of a real Codex
history (pprof inuse_space at request_page.go:1214, the make of on) at
8 minutes idle. save takes it as an argument now; the field is gone.

Run at this commit on mote (load 24): go vet for darwin, linux and
windows ok; go test ./internal/usage ok (57s), ./internal/gui ok (158s).
Real Codex history in a sandbox HOME (~/r2278), page open 30s then 8.5
min idle: liveHeap 13.68 MB, against 17.07 MB for v0.1.4089; the heap
diff shows readRequestBlocks' 853 KB gone. One earlier capture read
22.3 MB with 5.2 MB under prefetchEach/sharedBuild; a goroutine dump of
the next run had no prefetchEach goroutine left, so that was a build in
flight when the heap was taken, not a stuck reader.
Not run: the full suite.
2026-11-14 03:46:32 +08:00
yetone 58629a0f8e usage: a trim that lets most chunks go gives back the map's table
The usage page's index of session-file chunks is let go when no page has
asked for it in requestIdle + requestForget (trim(0)). A Go map never
shrinks, so the emptied map kept its table: 853 KB of a real Codex
history's index (pprof inuse_space at request_page.go:1461, the map
assignment in keep) stayed for the life of the process, 8 minutes after
the page was last open. trim now copies what is left into a map of its
size when it dropped more than it kept.

TestRequestTrimGivesBackTheMap fills an index with 100k chunks, holds
the keys, and checks trim(0) gives back the table. Broken by hand (the
copy skipped): red, heap 9,054,088 -> 9,051,552. Fixed: 3 of 3 green.

Real Codex account sandbox (mote, acctp HOME, page open 30s then 8 min
idle, memprofilerate=1): liveHeap 18.00 MB -> 17.07 MB; nothing held
under requestIndex.keep (was 853 KB). One earlier run read 23.1 MB with
a usage build in flight at the capture (sharedBuild 5.2 MB); the rerun
had none.

mica: gofmt clean; go vet ./internal/usage for darwin, linux, windows;
go test ./internal/usage ./internal/gui ok.
Not run: the full suite.
2026-11-14 03:11:29 +08:00
yetone 82512bb640 usage: the probe chunk is let go when the pages rest and after warm-up
probeChunk memoised its last chunk for the polling page (#2278), and
nothing ever cleared it: ~5 MB of unpacked probe rows held for the
process's life on a real gateway's history, the largest single live
holder left in an idle heap profile (makeProbeChunk -> rowChunk.add).
ReleaseScratch (page rest) and ReleaseMatchScratch (after warm-up) now
drop it with the rest of the reads' scratch; the next page read makes it
again, and while a page polls the memo still answers.

Run (mica): go test -run 'TestProbe|TestAnswered' ./internal/usage/ ok.
Broken by hand: without the two releaseProbes() calls,
TestProbeChunkLetGoAtRest fails ("ReleaseScratch kept the probe chunk").

Measured on mote, real accounts in the sandbox HOME, idle after the page
was open 30 s and closed 60 s (memv.sh), base vs this, two runs each:
  heap profile in use: 52.5 MB (4.91 MB under makeProbeChunk, held from
    gui.warmStart) vs 46.9 MB (none under it)
  liveHeap: 40.0 / 45.7 MB vs 40.4 / 40.4 MB
  footprint: 94 / 117 MB vs 102 / 107 MB (noisy run to run)
go test ./internal/usage/ ./internal/gui/ on mica: ok.
2026-11-14 01:06:11 +08:00
yetone d5585933f1 usage: heat-digests.bin is read mapped, not copied into the heap
The heatmap's key names each session file's chunk by a digest kept on
disk by serial (#2278). The file holds up to 2*sourceDigestsKept digests
at 40 bytes each, 5MB on a long history, and every start read it whole
into the heap and kept it there for the process's life. After a save the
encoded bytes stayed instead, the same 5MB.

Where the system maps files (unix), the file is now mapped read-only,
as requests-v1.bin already is (mapDiskFile), and kept is read from the
mapping: its pages are clean file pages, not footprint, and a lookup is
a binary search that touches a few of them. After a save the file just
written is mapped in place of the encoded bytes, when it is still those
bytes. The file is only ever replaced by a rename, so a mapping stays
as it was read. Windows reads it into memory as before (mapsFiles).

Run (mica, go1.26.8):
- go test ./internal/usage/: ok (54s)
- go vet ./internal/usage/, GOOS=windows go vet ./internal/usage/: clean
- Broken by hand (no mapping on load, no keepMapped after save):
  TestSourceDigestsKeptAcrossStarts red, "after a save the digests are
  kept as encoded"; green again with the change.

Real account (mote, the owner's history in a sandbox HOME, magpie web
with the page open, 90s idle, footprint + Go MemStats):
- before (w63 = v0.1.4074's code): footprint 109MB, live heap 44.9MB
- after: footprint 101MB, live heap 39.6MB

- wsl-run and win-run: go test -run 'SourceDigest|Heat' ./internal/usage/
  ok on Linux (the mapped path) and Windows (read into memory).

Not run: the full ./... suite (only internal/usage is changed).
2026-11-14 00:40:00 +08:00
yetone b3395ffdaf usage: a models.dev change no call of the user's names keeps the request index
The request index's meta named the catalog by models.json's bytes
(catalog.CacheKey, v0.1.4037), so every real change models.dev made, most
of them to aggregators' lists (OpenRouter, NanoGPT, Kilo, Vercel) no call
names, dropped every chunk and read every session file again: ~15 s of
CPU on a long history, several times a day.

The meta now names catalogBase: the catalog the rows were made under,
kept while each question the rows asked of the catalog is answered the
same. The questions are Pricer's base price (basePriceIn, taken out of
Pricer whole) and ListedAs's listed name; each is noted with its answer
the first time it is asked (noteAsk). A new catalog file, or a catalog
read again (catalog.Resets: Sync writes the file before it resets), asks
them all again; one answered otherwise names the index anew, as any
change did before. A question answered otherwise than first, or more
than 50k of them, does the same. The asks are kept in
catalog-asks-v1.json, written before any file of rows under the meta
(toDisk, heat, page, effort, digests), so a restart holds the rows on
disk to them too. The price cache key (usagePriceCacheKey) is unchanged.

Run on mica at this tree: go test ./internal/usage ./internal/catalog
./internal/gateway ok (gateway 1038s); go vet, GOOS=linux and
GOOS=windows go vet of usage and catalog clean; gofmt clean. Broken by
hand, each red in TestRequestStateKeptAcrossACatalogChangeNoRowAsks:
answersSame always true, the meta back on catalog.CacheKey, and the
catalog.Resets check dropped (a check between Sync's write and its reset).
catalog_asks.go joins the row code's go:embed, so the index is built
once after this update.
Not tried yet: a real models.dev change on a real account (next, on mote).
2026-11-13 19:42:11 +08:00
yetone 2f1759c96c usage, catalog: the same catalog fetched again keeps the usage index
A Claude account's model list fetches models.dev again every 45
minutes (catalog.Asked), most often to the same bytes. Each fetch
rewrote models.json, so its mtime changed, and usage keyed its request
index, the index's file on disk (requests-v1.bin, heat, page, effort)
and its priced summaries on that mtime: the next usage query dropped
every chunk and read every session file again. On the acctp history
(15.7k session files) a start that rebuilds takes ~15 s of CPU in its
first 30 s, against ~2 s for one that keeps the index. Each fetch also
forgot the parsed catalog and told every agent to rewrite its list
(catalog.Changed), for nothing changed.

- catalog.CacheKey names models.json and labs.json by a hash of their
  bytes, kept by their stat so a key costs a stat until a file changes.
  Usage's request meta and price key use it in place of the mtime, as
  liveListKey already did for the providers' lists.
- Sync writes models.json and labs.json only when their bytes changed;
  the same bytes are dated now (Stale, Missing and Asked read the time),
  and Reset and Touched run only when either file changed.

Tests: TestSameCatalogFetchedAgainChangesNothing (catalog) and
TestRequestStateKeptAcrossACatalogFetchedAgain (usage). Broken by hand:
with keepFetched always writing, the catalog test is red (told the
agents on the same bytes); with usage keyed on statKey again, the usage
test is red (meta and price key changed).
2026-11-13 17:16:47 +08:00
yetone a95a7a1cd8 providers: each API key can bill at a price rate of its own (tnt12231 on X)
A relay sells keys in groups that bill at different rates against the
official price (0.5x on one, 1.2x on another) under one endpoint, and
magpie had only the provider's price rate. Now a key can have its own:

- provider.KeyPriceRates, keyed by key id like KeySpendCaps: cloned,
  normalized on save, carried when a key is replaced. A key without one
  bills at the provider's PriceRate. A price the user set for a model
  stands as set, as it does under the provider's rate.
- Usage prices each call at its key's rate (usage.Pricer memoizes per
  key id, BaseKeyPriceIn), so the Usage page, a key's spend cap and its
  typed balance follow it. PriceAt, used to route by price, takes the
  rate of the key the provider holds.
- GUI: the provider editor's Advanced has "Price rate per key" under
  Price rate, shown only with two or more keys, folded past 8 keys like
  the per-key proxies. An empty line shows the provider's rate as its
  placeholder. Save sends keyPriceRates ({} clears, left out keeps).
  The lines, the check and the placeholder live in keyrates.js,
  imported when a provider with two or more keys opens. The core's
  budget goes up 397 for what is left in app.js (the import, the
  draft's copy, Advanced opening for it, the save's line, proxyLines
  drawing another kind of line); app.js stays under its own.
- CLI: magpie provider key-rate <id> [key [rate|default]].
- docs/subsystems/providers-accounts.md: a Key price rates row.

Run, at this head (rebased on 287a1ffa2) through mote-run:
- go test ./internal/usage ./internal/cli ./internal/gui: ok.
  ./internal/provider: ok but TestHostBuildsNoList, red the same on
  origin/main 51b98b1a8 (3 of 3), filed as #6479 (likely 16b8c300f).
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build: ok.
- GUI: key-price-rate.test.cjs (chromium and webkit x en, zh, zh-TW,
  ja, de: own rates saved, provider rate as placeholder, bad values
  refused, comma decimals, {} on clear, a folded key keeps its rate,
  one key shows no lines and posts none), i18n-keys and
  provider-many-keys-proxy (it shares proxyLines): ok. old-webkit:
  keyrates.js added to its on-demand list; its two reds (compat.js
  first, Safari 15.0 styles) fail the same on origin/main 51b98b1a8
  (#5919 and the on-demand list's #6467 family).
- Earlier, at 92bce5c72: the GUI files that reach the provider editor
  (134 tests). The 6 provider-many-keys reds fail the same on that base
  (#6209); proxy-login-fields' chromium zh timeout passes 12/12 alone on
  base and branch (#6374).

Broken by hand: atKeyRate leaving PriceRate as the provider's made
TestKeyPriceRatePrices and TestPricerKeyPriceRates red; the save not
sending keyPriceRates made 20 of 30 key-price-rate GUI tests red, and
keyrates.js dropping each parsed rate made them red again after the
move.

Not tried: a real relay with several keys at different rates; the real
Linux WebKitGTK app. The budget estimate and the Sessions page's costs
still use the provider's rate.
2026-11-13 16:31:24 +08:00
yetone d370bef982 usage: Failed lists the requests a fallback answered, as Routing shows their tries failed (maohy915 on X)
maohy915 runs magpie on a NAS and uses it from another computer's magpie
through Remote magpie. The NAS's Routing page showed failed calls, but
Usage → Requests → Failed found none. Reproduced with two sandbox
instances on mote (B → remote-magpie → A, where A's provider `bad`
answers 429 and falls back to `good`). A's trace had 2 requests and 1
rerouted. Usage had 2 rows, Failed had 0 and Retried had 1. A try that
fails and is handed on writes no row when nothing is billed, and its
request's row is an answer on the second try. Failed kept only
LostRequest, the requests whose agent got the error, so the failed try
was nowhere under Failed. Plain failures, remote or not, were already
listed; only rerouted ones were missing.

Failed now keeps every request a try failed on (Record.FailedTry): the
requests the agent got an error for, the tries handed on, and the
requests a later try answered. Retried still keeps only the answered
ones. The counts are unchanged: each request is counted once, by how it
ended (小一's rule), so a Failed list reads "1 failed · 2 answered on a
retry". The Failed option and the card's "N failed" button now say so in
their tooltip, in every language. Filtered page cells are cached on disk
under the filter, so settledCountVersion goes to 4; the first start after
the upgrade pairs the history again once.

Run (mote):
- go test ./internal/usage ./internal/usageapi ./internal/gui: ok.
- New test TestFailedKeepsRequestsAFallbackAnswered; updated
  TestRequestsCountedOnceWithTheirRetries.
- GUI, both engines: ledger-retried (5 languages, 420/1100), i18n-keys,
  i18n-en-no-cjk, usage-ledger, api-key-usage, purpose-filter,
  usage-ledger-content, usage-phone-head, usage-loops, usage-request-page.
  All pass except known reds: i18n-keys "a plugin's words are its own"
  (#6422/#6423) and usage-ledger "newest live route needs no
  return-to-live button" (#4078/#3104/#4626).
- gofmt; go vet for darwin, linux -tags nogui, and windows.
- Real repro with a binary built from this tree: A's Failed went from 0
  rows to the rerouted request, both in the API and in the real page
  (Chromium).

Broken by hand:
- Filter back to LostRequest: both Go tests red.
- The Failed option's title dropped: ledger-retried red.

Not tried:
- Restoring settledCountVersion to 3 doesn't turn
  TestSettledCountedAsVersioned red: it counts only Filter{}. The bump is
  by reading.
- Not tried on a real NAS or in the desktop app's remote window; the
  page is the NAS's own web page.
2026-11-13 14:17:49 +08:00
yetone acced81418 usage: Codex effort read back shares its model and effort names (#2278)
effortDiskRead decoded every saved (model, effort) pair with its own copy
of both strings, so a few names were held thousands of times in the kept
Codex effort sums. The read now hands each entry the first copy of its
name.

Measured on mote, acctp real-account sandbox (17k chunks), pageheap.sh,
w53v (743001128) against w54v (this), alternating, two runs each:
- heap profile inuse_space cum: CodexModelEffort 4.60 MB -> 2.01 MB,
  effortDiskEntries 2.50 MB -> 1.00 MB
- liveHeap 78.38/77.86 MB -> 78.02/78.68 MB, Footprint 131/122 -> 126/130 MB:
  run-to-run noise (~1 MB) hides the 2.6 MB at this level
- CPU at mark unchanged (2.23-2.66 s both)

Run (mote, at this tree): go vet ./internal/usage; go test ./internal/usage
(ok, 59s). Broken by hand (intern removed): TestCodexEffortNamesReadOnce
red, "each entry has its own copy of a name".
Not tried: Windows/Linux (no OS-specific code).
2026-11-13 13:12:12 +08:00
yetone 743001128d usage: chunk digests in use are named by serial, read from the kept list (#2278)
sourceDigests held every chunk's 32-byte digest in a map (by, and last
for the turn before), beside heat-digests.bin's sorted list that already
holds them: ~2-3 MB of maps on a 17k-file history. by and last now hold
only the serials used, which decide what the kept file keeps first; a
digest is read from the kept list, or from made, the few hashed since
the last save. A save encodes the list and keeps what it wrote as the
list, so made is empty again after each heat key.

Measured on mote, real-account sandbox (17k chunks), pageheap.sh, page
open, w52v (v0.1.3983) against w53v (this), 3 runs each:
  liveHeap   79.34 / 79.57 / 79.63 MB -> 78.77 / 78.64 / 77.99 MB
  Footprint  133 / 134 / 133 MB       -> 130 / 132 / 126 MB
  heap profile, sourceDigest cum: 2.99 MB -> 0.90 MB (the list read)

Run: go vet ./internal/usage; go test -count=1 ./internal/usage ok (mote).
Broken by hand: not putting a hashed digest in made and not keeping the
written list made TestSourceDigestsKeptAcrossStarts red ("same run,
hashed 2 chunks"). New in the test: a second key in the same run hashes
nothing and leaves made empty; a used serial with no digest is left out.
Not tried: a history past 2*65536 chunks (the cap is unchanged).
2026-11-13 12:56:20 +08:00
yetone c2fd48782b Put back what 1f05c311d took out of main by mistake
1f05c311d was committed with its worktree's older tree on top of a
fresh origin/main (git reset --soft), so beside the memory fix it
undid every file 610ae1f54..c1312ac15 changed (45 files: key balance,
import links, project subagents, uninstall, site, LESSONS.md and
more). This commit restores each of them to c1312ac15 byte for byte;
the tree is now c1312ac15 plus the memory fix alone
(git diff --stat c1312ac15 HEAD: the 4 files of the fix).
2026-11-13 12:18:23 +08:00
yetone 1f05c311d9 library: an open memory holds still while the Memory tab polls (Nietzsche_Li on X)
"资源库-记忆中,被展开的记忆的表单会定时抖动". While search by meaning
still has memories to read (read < of, which can last up to a minute
between memembed.Keep's reads) or a learn-from-conversations run goes,
the Memory tab reads its row again every 2s, and each read drew the
whole page anew. The open editor was a new .lib-detail each time and
played its content-in entrance (opacity .5, 2px slide) every 2s.

- semWatch/distWatch draw nothing when the read changed nothing, and
  redraw only their own row (redrawRow) when it did; the whole tab only
  when the memories changed.
- render() marks a .lib-detail open before it (same data-detail) as kept,
  so it doesn't replay its entrance. This covers every render of an
  open editor in the Library: memories, instruction sets and agents'
  files (the siblings; no other Library tab polls into render()).
- A new memory's text no longer takes the focus back on every render.

Run (mote): library-memory-steady.test.cjs, all 5 languages, 980/420,
chromium + webkit: green 4 of 4 whole-file runs after the last change
(webkit alone 2 of 2 before it). Broken by hand: the same test against
origin/main's client.js and library.css: 22 of 22 red ("the editor
played its entrance again"). One webkit de 420 red was the test's own
first row click intercepted by the header at 420px while the page
settled; the test now opens rows with a DOM click.
Also run, both engines, every language, 980/420: library-memory, library-memory-select, library-memory-suggest, memory-icon, library-instr-busy, library-instr-sets, library-linked-set, library-follow-server: all green. No Go code changed, so no go test or vet.
Not tried: the real app on a real memory store mid-read.
2026-11-13 12:17:43 +08:00
yetone a095e40279 usage: a start doesn't hash every session file's rows again for the heatmap's key (#2278)
The heatmap's settled days are named by a digest of each session file's
chunk of rows (sourceDigest). The digests were kept in memory only, so
every start unpacked and hashed every chunk again: 0.14-0.16 s of CPU in
the first 40 s of a start on a real history (startpg profile, w50v).

A chunk's serial names its file as read under one root and meta
(sourceSerial: root, meta, path, size, mtime), the same in every run, so
the digests are now kept in heat-digests.bin next to heat-v1.json, by
serial, under requestDiskBinary()'s key of the code that makes the rows:
another build's rows are hashed again. A file that can't be read, was
cut short or names other code is nothing kept. It is written as
heat-v1.json is (temp file renamed over it), only when a digest was made,
with this run's digests first and then those kept it hasn't met, at most
two turns' worth (2 x 65536 x 40 bytes), sorted by serial. The file is
kept as read and searched in place: a map of its 17k entries beside
sourceDigests' own cost 1.4 MB of live heap in a first try (w51v).

Measured on mote with the real-account sandbox (acctp, 17k chunks), a
start with the page opened, second start of each build:
- CPU profile, first 40 s: 2.00 s (w50v, v0.1.3978) -> 1.54 s (w52v);
  sourceDigest/heatSettledKey 0.12-0.13 s -> gone
- pageheap at the mark: CPU 2.48 s -> 2.12 s, Footprint 134 -> 131 MB,
  liveHeap 79.1 -> 79.4 MB

Run (mote, Go 1.26.8):
- go test -count=1 -timeout 45m ./internal/usage: ok
- GOOS=windows and GOOS=linux go vet ./internal/usage: ok; gofmt clean
- TestSourceDigestsKeptAcrossStarts (new): a second start hashes 0 of 2
  chunks with the same key; a start of one file keeps the other's; a new
  file hashes 1; other row code hashes again; a cut file hashes again.
- Broken by hand (the disk lookup ignored): the new test goes red,
  "started again, hashed 2 chunks".
2026-11-13 11:57:46 +08:00
yetone 2ae8e61a4f usage: an upgrade reads session files again only when the code of their rows changed (#2278)
requests-v1.bin and log-v1.bin were keyed on a hash of every .go file in
internal/usage, so nearly every release that touched the package threw
both away. The first start after such an upgrade read all ~24k call
shards again: on the owner's real accounts (mote, acctp sandbox) that is
13.8s of CPU and ~3.4GB allocated before the page settles, against 2.4s
warm.

Each file now keys on the source its rows are made, written and read
through: rowSource (15 files) and logSource (23 files), embedded by name.
The row pricer and a file's chunk builder are lifted out of
readRequestBlocks (sessionRowPricer, sessionChunk) so they can be roots.
TestRequestDiskNamesTheCodeOfItsRows type-checks the package and walks
every declaration reached from those roots (uses, package vars assigned
elsewhere, interface calls, encoding/String/sort methods); it fails when
a reached file is not embedded or an embedded one is not reached.
Of the last six usage-changing releases, four (3962, 3958, 3941, 3908)
would have kept the cache.

Run:
- go test -count=1 ./internal/usage on mote: ok 51.9s.
- go vet ./internal/usage for darwin, windows, linux on mica: ok.
- Broken by hand: session_provider.go left out of rowSource's embed ->
  "rowSource: session_provider.go is reached but isn't in its go:embed",
  FAIL; restored.
- Real accounts on mote (pageheap.sh, page open, CPU at mark):
  w47v first start after an older binary 13.80s, numGC 217 (rebuild,
  expected); w47v again 2.45s; w48v (w47v plus a live init() in
  effort_split.go, a different binary) 2.59s, numGC 56; back to w47v
  2.43s. Before, the same swap cost ~14s.
Not tried: Windows or Linux real start.
2026-11-13 10:09:27 +08:00
yetone 6af6ae9885 usage: a log of MCP calls and probes keeps its blocks on disk too (#2278)
log-v1.bin was written only once a gateway block had filled. A log of
MCP tool calls and probes has none (the real-account sandbox's 8.3 MB
log is 25,223 MCP lines and 2,539 probes, 54 probe blocks, 0 gateway
blocks), so full.n stayed 0, the file was never written, and every
start parsed all 27k lines again: readLogSnapshot took 60 MB of the
start's allocations. The probes that were kept went as JSON and were
parsed back a record at a time.

A full point is now marked too when a probe block fills while no
gateway row stands after the full blocks, and it records how many probe
blocks were full there (logFull.probes). Those go to the file as binary
entries, as the gateway blocks do, read from its mapped pages; only the
probes after them, up to the full point, still go as records. The file
is written again when its full point reaches further (by offset, not
the gateway block count). The magic is magpie-log-v2, so a v1 file is
parsed over once.

Run:
- go vet ./internal/usage; go test ./internal/usage ./internal/gateway
  (mica, -timeout 45m): ok usage 31s, ok gateway 859s.
- TestStartReadsKeptProbeBlocks (new): an MCP-only log of 3 blocks + 100
  is kept, a start reads 3 blocks from the file, and reads as a whole
  parse. Broken by hand (no probe full point): red, "a log of probes
  wasn't kept".
- Real-account sandbox on mote (acctp, page open 2.5 min, version
  0.1.3961 builds): log-v1.bin written on the first start (645 KB);
  warm starts, w45v (v0.1.3961) against this:
    CPU at mark  3.21s, 3.00s  ->  2.50s, 2.39s
    allocated    701 MB        ->  646 MB, 629 MB
    readLogSnapshot cum 60 MB  ->  2.6 MB
    numGC        66            ->  56
  Footprint 128-133 MB -> 132-135 MB, liveHeap ~80 MB both: the same
  within noise.

Not tried: a log with both gateway and probe blocks across a v1 -> v2
start on a real account (the unit test's mixed log covers the format).
2026-11-13 08:51:24 +08:00
yetone a8b0e80f65 usage: the request page's probes are made into a chunk once per change
readRequestBlocks made probeChunk again on every poll of the Requests
and Usage pages: a rowChunk holding every probe since the period's
start minus a day, interned again each time. On the real-account
sandbox it was ~45 MB of 952 MB allocated in two and a half minutes
(rowChunk.add under probeChunk, #2278).

probeChunk now keeps the last chunk it made, with the probe blocks,
since, renames and hosts it was made from. A frozen block is never
written again (a new probe reopens the tail as a copy), UsageRenames
hands back the same maps while providers.json is unchanged
(Renames.Same compares them by identity), and hosts are compared by
content, so the same inputs make the same chunk, which no reader
writes. Any of them changing makes it again.

TestProbeChunkMadeOncePerChange: the same inputs give the same chunk;
a later since, a changed host and a new probe each make a new one.


Measured on mote with the real-account sandbox (pageheap.sh, the
request page polled to the mark): probeChunk allocated 43.81 MB at the
base (w42) and 24.54 / 24.10 MB with this (w43, two runs). It is not
zero there because the sandbox's network is blocked, so every probe
fails and logs a new row, which makes the chunk again.
Run on mote: go test ./internal/usage ok (33.9s); the test is red with
the memo turned off by hand.
2026-11-13 05:31:22 +08:00
yetone d85ee9e53f usage: the probes are kept in packed blocks, as the gateway rows are
The request log's probes (magpie's own tests, model lists, MCP tool calls
and searches) were a slice of whole Records, 952 B each, and every read
that continued the log appended to a copy of it. The owner's real log has
25,379 of them (25,223 MCP tool calls): ~24 MB of live heap in every
running app, the tray's included, for rows only the Requests page lists.

Now they are rowChunk blocks of logBlockRows, frozen (packed) when full,
the last one reopened as a copy for the next append (probeRows), the way
readLogSnapshot keeps gateway rows. probeChunk and log-v1.bin read them
back through chunkRows; a block whose Latest is before since is skipped
whole. log-v1.bin's format is unchanged.

Tests: TestProbeBlocksContinued (3 blocks + an appended block: the earlier
snapshot reads as before, the continued read equals a fresh parse, since
cuts at the right row). Broken by hand: dropping the continued snapshot's
probe blocks turns it red. TestStartReadsKeptLogBlocks covers the disk
round trip with probes.

Run at this head on mica: go vet ./internal/usage; go test ./internal/usage
./internal/gateway/... ./internal/gui, all ok (gateway 869s).

Real app on mote (sandbox HOME from the real-account sandbox, plus the
25,379 probe lines of the owner's real log), tray idle at 150s, cold:
  before (w36, v0.1.3938's code): footprint 105 MB, live heap 48.4 MB,
    readLogSnapshot 26.5 MB of it
  after  (w37): footprint 70 MB, live heap 16.0 MB, readLogSnapshot out
    of the top; warm start (log-v1.bin read back): live heap 15.6 MB
Requests page, web mode, same HOME: requests.csv byte for byte the same
on both builds; /api/usage/requests' 100 rows the same apart from the 4
probe rows the first run itself wrote (token refreshes through the dead
proxy).

Not tried: Windows and Linux (no OS-specific code here).
2026-11-13 02:35:15 +08:00
yetone 477bbb7a15 usage: GET /v1/magpie/usage/requests?cursor= reads requests as changes, with stable ids (rdsaltbo on X, #6060)
A program keeping a ledger of its own (a WakaToken plugin) can now read the
requests incrementally: cursor=start or cursor=now, then each next_cursor.
Rows carry a stable content-derived id (same after a restart), origin, and
original_ids (request_id, response_id, client_response_id, message_id,
session_id, native_session_id), each only when the source gave it. A call
read late, a corrected row (same id, higher seq) and a native row replaced by
the gateway's (deleted, with seq) all come through a persisted journal
(usage-feed.jsonl, appended and synced before answering). Cursors magpie
cannot resume from are refused: 400 cursor_invalid / cursor_filter_changed,
410 cursor_expired / cursor_reset. A held key sees only its own rows and
tombstones. Without cursor, offset/limit mode is unchanged.

Also: Record.MessageID (not persisted) from the agent file's message id, and
usageapi's row decoration moved into a namer shared by both modes.
Docs: reference.md, integrating.md, gateway-routing.md, gateway-sessions.md,
site remote.html (en/zh/ja), llms-full.txt.

Run (mote, this tree): go vet darwin, GOOS=windows, GOOS=linux -tags nogui on
usage, usageapi, gateway (gui on darwin); go test -count=1 for
internal/usage, usageapi, gui, gateway: all ok. New tests: resume gets exactly
the new rows, ids and cursors survive a restart, correction keeps the id,
gateway takeover retires the native row, refused cursors, expiry, now cursor,
identical records, and the feed over the gateway (held key, 401 without key,
offset mode). Broken by hand: an unconditional memo made the new-rows test
red (fixed to memo only the next page).
Not tried: real Claude Code/Codex session files, a huge (700k+) history,
Windows run of the tests, GUI browser suites (no GUI file touched).
2026-11-12 22:40:15 +08:00
yetone 10a27651f0 usage: a window's whole is kept across its reset until the new one tells its own (Musikrv77852 on X)
After Kimi Code's 7-day window reset with nothing used, the card lost its
"Whole ≈ N tokens" until the new week passed 5% used. The reckoning is
every provider's (usage.WithWindowHolds), so the fix is too: carryHolds
keeps the last whole told for each account's window (window-holds.json,
temp-and-rename) and, where the new window is under the floor or has none
routed yet, shows it with holds.prevAt set. The tooltip reuses the past
cycle's "Estimated from the window that began X, read Y" line; no new
label. The new window's own figure replaces it as soon as it can be told.

Run (mote): TestWholeKeptAcrossReset (reset with 0% and 2% used, restart
from disk, same-window under floor, other account, new window with data),
go test ./internal/usage ./internal/provider ./internal/gui (only
TestCoreScriptBudget red until its +10 here), quota-holds and quota-curve
GUI files in chromium and webkit (all 5 languages x 360/1000px for the new
case), gofmt, go vet darwin/linux/windows for usage and provider.
Broken by hand: carryHolds returning early reds the Go test and the GUI
case; dropping the prevAt branch in app.js reds the GUI case.
Not tried: a real Kimi account across a real weekly reset; a full
./... suite before the tag.
2026-11-12 21:48:04 +08:00
yetone 5241308212 settings: a day can start at 0 to 6 o'clock (ssharpcc on X)
Settings > Usage > "Day starts at" (dayStart, 0 to 6, default 0; also
magpie settings set dayStart 4). With 4, a call at 01:30 counts toward the
day before: the Usage page (summary, charts, heatmap, ledger day filter,
hour labels of Today) and the daily and monthly key caps (access.Window,
provider.SpendCap.Window).

internal/dayzone makes a time.Location whose midnight is the real day's
hour:00 (TZif built from the zone's own offsets, same DST instants), so
every place that cuts days by a Zone's midnight follows without edits;
usage.Zone returns it and the "now" reads use it too.

Run (mote): go test usage, settings, settingsapi, access, provider, gui,
dayzone, also with TZ=UTC and TZ=Pacific/Kiritimati; gofmt; go vet darwin,
linux nogui and windows; day-start, currency, number-units and i18n-keys
GUI files in chromium and webkit, en zh zh-TW ja de; TestCoreScriptBudget.
Broken by hand: TestDayStartsAfterMidnight red with 9 failures when the
hour is ignored. New tests: dayzone over 5 zones x hours 1/4/6 x two years
of days, usage, limit window, spend-cap window, day-start GUI.
Not tried: a real log history in a real window.
Not shifted, filed as #6314: the Sessions page, TUI sessions filter,
davsync shared per-day files, gateway_sessions day keys, credits_daily.
Rows are never stored in the shifted zone.
2026-11-12 18:31:50 +08:00
yetone ffc1d64e5e usage: a call recorded under magpie's alias id is the gateway's, not a direct one (CrazyJal on X)
Claude Desktop's Code tab, and Claude Code under it, write the id the gateway
listed the model by (magpie-<number>.anthropic.<Claude model>,
mythos-magpie-<n>, anthropic/magpie-<n>, claude-magpie-<n>) as each turn's
model. The gateway's log counts the turn under the model that served it, and
the agent's file counted it again under the alias: a row for a model that is
none, its cost on top of the real one.

Only the gateway knows those ids, so a call that names one went through it.
Such calls are now left out of what Direct, the ledger and the Requests
page's chunks take from session files, for every agent that records one.
Calls under a model of the agent's own are unchanged. usage.MagpieAlias
mirrors the gateway's alias forms; a gateway test fails when the two differ.

Run (mote, at the pushed head): TestAliasCallsAreTheGatewaysNotDirect, TestMagpieAliasForms and
the gateway's TestUsageKnowsEveryAliasForm pass; with ownCalls returning its
input the first fails (7 rows, four under aliases). go test internal/usage,
internal/gui, internal/sessions ok; vet darwin, linux nogui and windows of
usage and gateway clean; gofmt clean. Go-only change, so no GUI file was run.
Not tried: a real Claude Desktop 3p session (none on this machine; the model
forms come from the gateway's own alias code and its tests, not JSONL bytes).
Existing persisted request chunks rebuild with the new binary.
2026-11-12 13:14:43 +08:00
yetone e6bf4adf1f usage: Claude Code's helper requests are labelled, the largest cache write is one click away (recih on X, #6199)
Claude Code's AgentSummary and its auto mode classifier name themselves
nowhere in the request, so there is no client marker to read. The gateway
tells them by their content (inferredKind: a claude-cli/ request on the
Messages API; the classifier by autoModeClassifierAsk, the summary by its
last user text "Describe your ... in 3-5 words") and records them as
agent_summary_inferred and auto_mode_check_inferred. The purpose catalog
names them "Progress summary (inferred)" and "Auto mode check (inferred)"
and puts each with its plain kind's purpose, so the existing Purpose filter
lists both; nothing known and nothing inferred share a name. A tool that
printed the same words, a chat, and another agent's request stay unmarked.

A requests page now also holds BigWrite, the gateway-served row that wrote
the most to the cache (cells, page-v1.json and pageFromLedger all carry it;
rows from session files have no request to open). The Requests line shows
it as "109K largest write", a button that opens that request through
openUsageRoute. settledCountVersion is raised to 3, which keys the cached
pages.

Not done: the per-request branch recovery result asked for in #6199. No
structured field holds it.

Run on mote (load 21-24 of 18 cores, mica was higher): go test ./internal/usage
./internal/usageapi, the gateway and gui purpose tests, go vet for darwin,
linux (nogui) and windows, gofmt; the GUI files usage-big-write (new),
purpose-filter, routing-kind, i18n-keys and usage-ledger in chromium and
webkit. Broken by hand: inferredKind returning "" turns
TestClaudeHelperRequestsAreLabelled red; the larger-than test of BigWrite.add
turned round turns TestRequestPageBigWrite red on both paths; the jump off
turns usage-big-write red. Not tried: a real Claude Code session against a
live subscription, Linux WebKitGTK.
2026-11-12 02:01:31 +08:00
yetone 4b1f3eca4a usage: a ZCode call magpie routed is not counted again as a local session's (nori_tsukiji on X)
With ZCode on the same computer as magpie, the Usage page's local session
calls came out equal to the calls magpie had routed: each was counted twice.

Cause: a ZCode request names its session without the sess_ prefix ZCode's
database gives it (zcodeBareID; GatewayKeys, Titles and the Sessions list
already knew). The Usage page pairs a gateway record with a session file's
call by session, tokens and end time (matchedBlocks), and the calls read
from ZCode's database kept sess_<id> / sess_subagent_agent_<id>, so they
never shared a session with the gateway's records and were never paired.
Leaving out calls whose providerID is "magpie" (ocGatewayProvider) only
helps when ZCode writes that id beside a reply; with any other id the call
was listed twice.

Fix: readZCodeCalls gives each call the bare session id; zcode's call parse
version is 3, so cached shards are read again. Claude Code, Codex, Pi,
OpenCode, Kimi, dsh, grok, minimax, agy and WorkBuddy name their sessions as
their requests do (raft.go's requestIDs has ZCode alone); not changed.

Run on mote: go test ./internal/usage ./internal/sessions (ok; the zcode
fork test's expected session ids are now the bare ones), gui and cli with
-run 'ZCode|Zcode|Usage|Session' (ok), go vet darwin/linux/windows (clean),
gofmt -l clean. TestZCodeCallsPairWithTheGatewaysRecords (a session, a
provider id of ZCode's own, a subagent) was red on the old code: 4 rows for
2 routed calls, the local ones Session sess_7c1f against the gateway's 7c1f.
Not tried: a real ZCode database (this computer has none, only the app's
tasks index) and the full suite.
2026-11-12 00:42:50 +08:00
yetone ce0960b4ab usage: a first Requests build reads with four workers, not eight
A first build of the request rows runs on any upgrade that changes
internal/usage (the cache key hashes its source) and on a first install.
Each prefetchEach worker holds a whole file's calls while it reads, so
eight of them stacked up in the cold peak.

Measured on mote with a copy of the owner's real accounts and history
(HOME ~/r2278/acct, requests-v1.bin removed before each start), five
cold starts of each build alternated, physical footprint peak at 12s
(vmmap):
  eight workers: 248.3 259.1 252.1 257.5 276.1 MB (mean 258.6)
  four workers:  243.3 230.2 232.6 245.2 246.7 MB (mean 239.6)
Every four-worker run is below every eight-worker run. The build takes
the same time: the gctrace burst ends at 5.0/5.0/5.6/5.0/6.2s against
5.0/4.8/4.9/5.0/6.4s, and CPU in the first 12s is 6.7-7.6s for both.
The cache written is the same size (71,523,711 bytes) for both.

TestPrefetchEachMakeIsAReadersOwn counts four readers' makes now.

Run at this head (rebased on 8fe720453), on mote: gofmt -l clean,
go test ./internal/usage ok. go test ./internal/gui: red only in
TestCoreScriptBudget (#6116) and TestSettingsSaveKeepsWhatItDoesNotSend
(#6103), both red on main at 8fe720453 and filed; this change touches
no GUI file.
Not run: the full ./... suite.
2026-11-11 16:12:43 +08:00
Flandern1211 82f09e3248 sessions: Codex's leftover review threads are no rows, and its one-session folders are one group
Deleting a thread in Codex leaves its subagent rollouts behind: the
guardian's review threads, titled by the prompt it asks ("The following
is the Codex agent history whose request action you are assessing…"),
and the title threads it opens. magpie reads every rollout, so each was
a session of its own, and one whose thread was gone had nothing to hang
under. On this computer 642 Codex sessions held 422 subagent threads,
86 of them with their parent thread's file gone (and 2 more under one of
those): they filled folders of their own (Documents\Codex\2026-08-17\
shan, wang, wei…), and the bar counted 531 sessions made with another
provider, 371 of them review threads no one ever opened. Codex Desktop
also makes a folder for every chat started without a project
(~/Documents/Codex/<date>/<name>, its outputs/ and work/ in it, named
from the prompt): 36 of them here were 36 folders of one session each.

listAgentWith now drops a Codex subagent thread whose parent is not
listed, to a fixed point, so a chain of them goes too; the agent's tab
counts the rows it lists. The "Scratch sessions" group that commit
e373adddf gave ZCode's draft folders now holds Codex's own per-session
folders as well (that one, Documents\Codex\<date>, a probe in a temp
folder, worktrees, another app's hidden folder). The provider bar counts
Codex's own threads only (role main or unknown): 531 became 160 here.
And a gateway session no call of which was answered and which spent
nothing is no row either (usage.GatewaySession.SpentNothing): the three
empty rows under "Seen through the gateway" were Codex's failed
title calls (kind thread_title, 400/499, 0 tokens), their ids ones no
file of Codex's has.

Rows: 642 Codex sessions to 554 (88 review threads gone), 422 subagent
threads to 334; 36 folders (51 sessions) folded into Scratch sessions;
3 gateway rows to 0, so "Seen through the gateway" is empty here. Usage
still counts every one of those calls, and nothing was deleted.

Run:
- go test ./internal/sessions -run 'TestCodexSubagentWhoseParentIsGone|TestZCode' -count=1: ok.
- go test ./internal/gui -run 'Session|Gateway|Manage' -count=1: ok.
- go build ./...; go vet ./internal/gui ./internal/usage ./internal/sessions; gofmt -l; git diff --check; node --check client.js: clean.
- go test ./internal/sessions -count=1: the same failures as without this
  change (TestAgySessions, TestAgyRowOnly, TestAntigravityAppFolder,
  TestCCListingKeepsItsNames: path separators and allocation counts on
  this Windows box).
- go test ./internal/usage -count=1: TestDesktopSessionAccountMetadata
  fails without this change too.

Broken by hand:
- without keptSubagents the 86 rows come back
  (TestCodexSubagentWhoseParentIsGoneIsNoRow fails);
- hiding a gateway session on "spent nothing" alone breaks
  TestSessionsSameWithoutRows and TestGatewayConversationAPI: a call
  answered with no tokens is still a session, so SpentNothing also asks
  that none of its calls was answered;
- counting subagent threads in the provider bar says 531 here, 371 of
  them review threads.

Not changed: the review threads' calls are still counted by Usage and by
the Sessions page's stats; their rollouts stay on disk (Deleting the
parent does not delete them); the scratch grouping is worked out on the
page (client.js), so Usage's folder filter still lists those folders by
their paths.
2026-11-11 15:09:32 +08:00
yetone 059d995d56 gateway keys: the list reads the ledger once for all keys, and a proxy's web page is said by its title (aiandcloud on X)
aiandcloud (2.98B tokens, 12,654 requests a day, server mode behind a
proxy) saw Gateway keys draw a Cloudflare 524 page as raw HTML.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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