Commit Graph
279 Commits
Author SHA1 Message Date
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
yetone 5bb252c8f3 usage: a poll's small pairing lets a whole history's scratch go (#2278)
The matcher, the response picks and visibleLocal's set of ids seen are
kept for the next pairing, and each pairing that puts one back holds it
scratchLinger more. A poll's pairing of its last few days put back the
scratch the cold start's pairing of the whole history made, sized for
every call, so ~140 MB of maps and slabs stayed while the window polled:
the heap profiles at 44, 50, 56, 62 and 68 s were alike to the MB, all
of it under codexEffortOfIndex, with no pairing of the history running.

Each scratch now records the rows of the largest call it served, and a
call over a quarter of that or less (and over 4096 rows' floor) makes its
own; the large one goes with the collection. A call alike in size takes
what is kept, as before, so the polls while an agent works still reuse
it. holdBigBuild counts its rows through the same rowsOfAll.

Run on mote at this head (parent 7d4a63148, rebased; usage ok 21.4s, usageapi ok 1.6s there):
- go vet ./internal/usage: ok
- go test ./internal/usage ./internal/usageapi: ok 18.0s, ok 0.8s
- TestSmallPairingLetsLargeScratchGo with scratchFits always true: red
  ("a small pairing kept the match scratch of a large one"); green with
  it back, beside TestPairScratchGoesWhenUnused, -KeepsNothingBetweenCalls
  and TestVisibleLocalSeenKeptEmpty.
- gofmt -l clean.

Real history (the owner's full ledger and session files, sandbox HOME,
caches deleted, the GUI's polls for 120 s), footprint every 5 s:
- this head: peak 532 and 539 MB; after the peak 367–374 MB while it
  polled; CPU 3:29 both.
- e31ccf230 in the same session: peak 556 MB (548–566 before); after the
  peak 416–419 MB; CPU 3:38.

The peak itself is the pairing of the whole history while it runs, beside
the Month page and the session stats; this change doesn't cut that.
Not tried: Windows and Linux runs.
2026-10-30 23:20:35 +08:00
yetone 18b63fe5f8 usage: a cold start's builds find the pairing the build before them made (#2278)
On a cold start the page of the month, the page of All, Codex's effort
and the heatmap read the history side by side and pair it in turn
(holdBigBuild). Each one missed the pairing the one before had kept
(pairMemo), and paired the whole history again beside it. On the real
history (469 gateway blocks, 16619 session chunks) every big build
missed; the warm All page's miss had a memo whose session serials all
differed (16619 of 16619).

Three things kept them apart:

- A session file's chunk got a serial from a counter each time a read
  built it. The builds read the same files together and share one build
  of each (sharedBuild), but each named its copy apart. A chunk's
  serial is now made from what it is made of: the file's path, size
  and mtime under the index's root and meta (sourceSerial), the same
  in a build and in a chunk read back from requests-v1.bin. The top
  bit keeps it apart from a counted serial (gateway blocks, other
  computers' days). The caches keyed by serial (cells, fold ids, match
  hints, message keys) hold what a chunk's rows give, so a chunk of
  the same file and meta reads the same from them.
- A build took the last pairing when it began, before waiting its
  turn. It now takes it once it has the turn (lastPairs).
- A build kept its pairing after it let the turn go, so the build
  that waited took its turn first and found none. It now keeps it
  while still holding the turn (keepPairsFor). The memo is kept
  though the build's index isn't: it stands only for chunks of its
  serials.

TestBigBuildsBegunTogetherPairOnce starts the page of All and the
heatmap together over a gateway log and eight session files, both
having read their rows before either pairs: two pairings, every row
once and the heatmap's recent days.

Broken by hand, the test is red (3 pairings) with any one of the three
undone: the counted serial back, the memo taken before the turn, the
memo not kept.

Run at this head, rebased on e31ccf230, on mote: go test -timeout 45m
./internal/usage/ (ok 16.3s; 52.9s at 2f65a33aa) and ./internal/usageapi/ (ok); gofmt -l
clean; GOOS=linux, windows and darwin go vet ./internal/usage/
./internal/usageapi/ ok. ./internal/gui/ was run at 2f65a33aa: the AppKit
real-window tests (TestMainWindowCorners, TestPanelCloseHidesIt, the
Dock and tray ones) hit their 20-80s deadlines on mote, which has no
window session for them (#4125, #2645); nothing in the GUI changed.
GOOS=linux go vet ./internal/gui/ stops in Wails' cgo files, as a cross
build without cgo does.

On mote, the real history, a true cold start (caches deleted), 240 s
polled as the Usage page polls: phys_footprint_peak 551, 553, 548 MB
against v0.1.2213's 607 (592-628 in earlier runs), CPU 3:50-4:08 against
3:40, under load ~27 from other sessions. An instrumented build logs
one pairing of All, then hits for the rest (30d, then All miss, All
hit, All hit). A restart with the caches kept: 317 MB against 341, CPU
10.5 s against 10.5 s. The peak left is Codex's effort pairing All
(~150 MB) while the page of the month, under bigBuildRows, pairs its
own beside it (~80 MB); not changed here.
2026-10-30 22:49:35 +08:00
yetone a6e7d40421 usage: the heatmap pairs its year through All's pairing, not a third time (#2278)
A cold start paired the whole history three times in turn: the page of
All, Codex's effort through All's memo, and the heatmap's 53 weeks on
their own. The year covers the same chunks as All for most histories,
and its pairing was the last and highest of the footprint's peaks
(fp 503 -> 565 -> 574 -> 582 -> 592 MB as each pairing ran, e18 on
the real history).

heatSplit's cold path now pairs through pairEvery: All's window and
All's memo (cache.pairs), visited from the heatmap's since on. Whichever
of the page of All, the effort and the heatmap comes first pairs every
row; the others take the memo. A call is paired to its session row as
the whole history pairs it, so a call early in the year can match a
session row from before it, as the page of All already counts it.
Only the heatmap's recent days are paired again for it.

On a cold start this alone moved no peak (597/619/595/611 MB against
e18's 592-628): every build missed the memo, for the reasons the next
commit fixes. With it, the effort, the page of All and the heatmap take
one pairing.

TestHeatmapPairsAsAllDoes counts the pairings with the page first and
with the heatmap first; both orders are red on the old code.

Run at this head, rebased on e31ccf230, on mote: go test -timeout 45m
./internal/usage/ (ok 16.3s; 52.9s at 2f65a33aa) and ./internal/usageapi/ (ok); gofmt -l
clean; GOOS=linux, windows and darwin go vet ./internal/usage/
./internal/usageapi/ ok. ./internal/gui/ was run at 2f65a33aa: the AppKit
real-window tests (TestMainWindowCorners, TestPanelCloseHidesIt, the
Dock and tray ones) hit their 20-80s deadlines on mote, which has no
window session for them (#4125, #2645); nothing in the GUI changed.
GOOS=linux go vet ./internal/gui/ stops in Wails' cgo files, as a cross
build without cgo does.
2026-10-30 22:49:35 +08:00
yetone fb3aef575b usage: settled days are kept across an upgrade that counts them the same (#2278)
The settled summaries (heat-v1.json, page-v1.json, effort-v1.json)
were keyed by requestDiskBinary, which hashes this package's source.
14 of the last 39 releases changed that source. After each of those
upgrades, every user's first start paired the whole history three
times (page, heatmap, Codex effort), and that is the cold start's
footprint peak.

heatSettledKey now names the counting by sessions.CallCacheVersion and
a new settledCountVersion constant. requests-v1.bin and the gateway
log's disk file still use requestDiskBinary, so a session file is
still read again after any source change. Only the pairing is kept.

TestSettledCountedAsVersioned is the guard. It runs a cold page,
heatmap and effort build over a fixed fixture in UTC: five Codex calls
with their gateway calls, cache reads, five efforts, an unmatched
Claude call with cache writes, and a 500. It hashes what the three
files keep, with keys and times stripped, and compares the hash with a
golden value. A change that counts a row differently fails it until
settledCountVersion and the golden are raised together. It guards only
what the fixture reaches.

Run on mote at this tree (rebased onto da3c5e0c0): gofmt clean; GOOS
linux, windows and darwin go vet of ./internal/usage/ and
./internal/usageapi/ ok; go test ./internal/usage/ ./internal/usageapi/
ok (17.2s, 0.8s); TestSettledCountedAsVersioned, *SettledFromDisk and
TestHeatSettledKeyNamesTheZone ok again under TZ=Pacific/Kiritimati.
TestSettledCountedAsVersioned also ok on Windows (win-run).

Broken by hand, each red: a page cell's n doubled in cellsBefore,
effort before the cut leaving out one row, and a heatmap day's tokens
leaving out CacheWrite. A doubled heatBefore tokens count stays green,
since it only goes into the key.

Real full history on mote (fullcold.sh, then a start with the caches
kept, by a binary whose internal/usage source differs by one comment
line):
  old key: cold peak 616 MB; upgraded start peak 591 MB, fp 377 MB at 240s
  new key: cold peak 626 MB; upgraded start peak 449 MB, fp 258 MB at 240s
One run each.

Not tried: an upgrade across a real release pair.
2026-10-30 20:46:59 +08:00
yetone da3c5e0c0f gateway: Claude Desktop's connection check is tagged as one on the Routing page (cybercaius on Discord)
Also: the check follows a Desktop model switch made after the last turn.

cybercaius (#help): with gpt-6.1-sol on AnyRouter chosen in the
conversation, the Routing page showed "Claude Desktop requested
deepseek/deepseek-flash" while the answer came from gpt-6.1-sol. The route
was right; the row was not explained.

Those rows are Desktop's own connection check ({"max_tokens":1, content
"."}, app.asar 2.7032 lWt/YT). Desktop names its model itself: the
shortest listed id with haiku, else sonnet, else opus, else the FIRST
listed model. magpie lists no Claude-named ids to it, so the check names
the first one (deepseek-flash), whatever the conversation is on, and
magpie sends it to the model chosen in Desktop's menu (desktopChosen).

- The check is recorded with kind connection_check (KindDesktopCheck,
  usage purposeKinds "Connection check", purposes.js regenerated). The
  Routing page tags the row "Connection check" next to the requested id
  and its story says the id is the one Desktop named from its list, not
  the conversation's model, and where magpie sent it. zh/zh-TW/ja/de.
  The requested id itself stays what Desktop sent.
- desktopChosen: a turn sent after cowork_account_settings.json was last
  written wins over the menus (newer of the two). Before, the last
  session's model came first whenever any menu still held it, so the Code
  tab switched off DeepSeek with Cowork left on it kept the check on
  DeepSeek. desktopPicked now carries when that turn was sent (the
  file's mtime once read).

The two 400s were AnyRouter's own (the reporter says so); not changed.

Run (at 0013f990c, this tree before its rebase on e0ad48641 and the
version stamp v0.1.2208 -> v0.1.2212 in comments/doc):
- mote: go test -tags nogui -timeout 45m -count=1 ./... : 81 ok, exit 0.
- mote: go vet ./internal/gateway ./internal/usage for darwin, linux
  (nogui) and windows: ok. gofmt clean. go generate ./internal/usage
  gives the same purposes.js as committed.
- GUI: routing-desktop-check (new; en, zh, zh-TW, ja, de), routing-kind,
  i18n-keys: chromium on mote ok; WebKit could not launch on mote (90+
  hung pw_run.sh launches from other sessions), so both engines ran on
  the Linux box (wsl-run): 14/14 ok.
- Whole GUI suite (wsl-run, concurrency 4) still running at push; reds
  so far are in account-arrange, account-models and agent-expand-steady,
  files this change does not reach. Checked against main after.
Broken by hand:
- call.Kind = KindDesktopCheck turned off: TestClaudeDesktopProbeAsksNoClassifier
  red ('recorded as kind "" (unmarked)').
- the connection_check story removed from client.js: routing-desktop-check red.
- old desktop.go: the new "Code tab switched off the last session's
  model" case red; the at.After check turned off: red too.
Not tried: a real Claude Desktop. Whether Desktop sends a check on each
model switch, and whether its composer switch writes the menu file, are
read from its bundle, not seen live. AnyRouter's 400s not looked into.
2026-10-30 20:32:25 +08:00
yetone 0606e03702 usage: a settled chunk's message keys are read for a pairing, not kept (#2278)
msgKeysOf kept every chunk's message keys by serial, for the next
pairing of the same chunks. A cold start pairs the whole history (the
warm-up's page of All, then the heatmap's year and Codex's effort when
page-v1, heat-v1 and effort-v1 miss), so it kept every session file's:
67 MB of the 460 MB live heap 30s after the footprint passed 400 MB
(heap profile of a cold start of the real history on mote), while
polls pair only the days since the split's cut.

A chunk whose rows end before settledBefore(now) is now left nil by
msgKeysOf, and visibleLocal reads its keys into one buffer as it
reaches it. Such a chunk is paired only when a split page's, the
heatmap's or the effort's kept cells are missed. What is left out is
the same: TestVisibleLocalSettledNotKept pairs a settled and a recent
chunk three times and checks the copy left out each time and that only
the recent chunk's keys are kept.

Cold start of the real history (fullcold.sh on mote, caches deleted):
phys_footprint_peak 613 and 603 MB with this change, against 638, 648,
654, 660, 663 and 682 MB before it.

Run at the rebased tree (on origin/main 387e8572a, on mote): gofmt -l clean;
go vet -tags nogui ./internal/usage/ for linux, windows and darwin ok;
go test ./internal/usage/ ok (34.5s), ./internal/usageapi/ ok;
-run 'VisibleLocal|Pair|PageSplit|Heat|Effort|QueryPage' ok.
Broken by hand (msgKeysOf keeping settled chunks again):
TestVisibleLocalSettledNotKept red, "settled chunk's keys kept true".
2026-10-30 20:21:52 +08:00
yetone 17c90b6f2f usage: pairFixture's chunks take serials of their own (#2278)
TestPairScratchKeepsNothingBetweenCalls was red after any test that
paired another pairFixture of other sizes first: both fixtures named
their chunks 100, 101, ..., so msgKeysOf, which keeps a chunk's message
keys by its serial, read the other fixture's ids for this one's chunks
and left 18 of 108 calls out as copies ("a first call matched 90 of
108"). It passed alone and in the package's full order, so it showed
only under a -run of the pairing tests.

Run at the rebased tree (on origin/main 387e8572a, on mote): gofmt -l clean;
go vet -tags nogui ./internal/usage/ for linux, windows and darwin ok;
go test ./internal/usage/ ok (34.5s), ./internal/usageapi/ ok;
-run 'VisibleLocal|Pair|PageSplit|Heat|Effort|QueryPage' ok.
Broken by hand (serials 1 and 100+f again): that -run is red,
TestPairScratchKeepsNothingBetweenCalls "a first call matched 90 of 108".
2026-10-30 20:21:52 +08:00
yetoneandYangHonghang 9e73f69af4 providers: rate windows bill a provider's hours at its own rate (#2463)
A provider can have up to 8 rate windows: days, a span that may cross
midnight (on this computer's clock), and a rate. Inside a window a call
costs the base price times the rate. The base is the user's model price
as set, or the list price times PriceRate with the vendor's own peak
(DeepSeek, Command Code, OpenCode Go) already in it. The author gave
this order as the spec: a 0.8 window on a shared DeepSeek key takes 0.8
off the peak price at peak. The editor's hint says not to set the
official peak hours again as a window, in every language.

Each call is priced at its own time on the Usage page and its CSV, in
the Requests tab's rows, and against a gateway key's cost limit. The
Sessions page, group templates and the model list written into an
agent's own config use the base price. /v1/models prices at now.

Ported from YangHonghang's 2c9d459ff (rate-windows-2463-v2). The Go
pricing, its tests and the translations are theirs. Changed here:
- No budget raised. Their commit raised appScriptBudget and
  coreScriptBudget; core_budget_test.go is main's again. The editor's
  window rows, time menus, validation and hint moved to ratewindows.js,
  which app.js imports when the field is drawn (as signsheets.js is).
  The sliding-thumb and modalDepth comments were cut down to make room.
  The core is 1,535,528 of 1,536,586 and app.js 1,312,242 of 1,315,316.
  Until the script has loaded, a save leaves rateWindows out, and the
  server keeps the saved ones.
- Their unrelated TestAssetsHaveNoConflictMarkers is dropped (one
  commit, one goal).
- The row badge shows only for a provider with windows. Before, every
  provider with a price rate alone got a new ×badge. Its title is
  shorter, and so are its translations.
- AgentPricer (agent model files: Pi, omp, OpenCode cost) uses the base
  price. Nothing rewrites those files when a window opens or closes, so
  a price taken at Sync stayed on outside the window.
- internal/budget gets a TestMain through testenv, so the new test
  runs in a home of its own.
- old-webkit's list of lazily loaded scripts names ratewindows.js.
- The draft keeps each window as a shallow copy, and a day chip
  replaces its days array, so the saved provider is never changed.
- The GUI test waits for the lazy script's hint, not a fixed 300ms.
  It also checks the peak note in each language.

Run first on 2f5a3f1c0, then again after rebasing on 70d9996c5,
8acb0d3a7 and d609729cf. The rebase onto 70d9996c5 met main's ruleedit.js in
old-webkit's list, and both are listed.
- gofmt -l internal: clean at 8acb0d3a7 (129578c3d gofmt'd main's
  pi_api_test.go).
- mote, on 8acb0d3a7: go vet on usage, provider and gui
  ok; GOOS=linux and GOOS=windows go vet -tags nogui ./... ok.
  go test -tags nogui for internal/usage, provider, gui, budget and
  sessions: ok. The five internal/agent tests that are red on WSL
  (below) pass on mote there. On d609729cf (a one-line mover min in
  internal/provider), internal/provider again: ok.
- On 2f5a3f1c0: internal/provider, usage, budget and sessions, and the
  gui RateNow|PriceRate|CoreScript|Budget tests, each under TZ=UTC,
  Asia/Shanghai and America/Los_Angeles: all ok.
- wsl-run (magpie-desktop, Playwright chromium and webkit) on
  70d9996c5: provider-rate-windows, old-webkit, i18n-keys,
  provider-price-rate, provider-advanced-fold, agent-hides-editor,
  key-box-once, provider-many-keys, nokey-editor and
  editor-short-window: 200/200. On 2f5a3f1c0 the first five and
  model-price-edit: 132/132. On mote the same files hit WebKit launch
  timeouts (180s) under another session's full GUI suite (load 30), and
  that run was stopped.
- Full suite, wsl-run (mote was running another session's full suite),
  go test -tags nogui -count=1 -timeout 45m ./... at 6e534f546 (this
  change on 70d9996c5): every package ok except internal/agent.
  internal/agent fails TestInstalledVersion, TestGrokInstalled,
  TestCursorFolderFromTheEditorIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath. This change doesn't touch internal/agent. At
  origin/main 8acb0d3a7 on the same box, TestInstalledVersion,
  TestGrokInstalled and TestOmpDetectedWithPiDir fail too: a fake CLI
  in /tmp exec'd with "Invalid argument". That is #4033 and #3548
  (WSL2 binfmt interop).
- Broken by hand, red each time:
  - Pricer without the window: TestPricerRateWindows,
    TestBlockRowsTakeTheirRateWindow, TestCostLimitCountsTheRateWindow.
  - Block rows without atWindow: TestBlockRowsTakeTheirRateWindow.
  - AgentPricer at now: TestAgentPricerLeavesTheRateWindowOut.
  - Badge for a price rate alone: TestRateNowOf.
  - Peak note removed: provider-rate-windows, 10 of 10 chromium
    layouts.
  - ratewindows.js not in old-webkit's list: old-webkit.

Not tried:
- A real relay billed by the hour.
- The real desktop app (WebKitGTK, WKWebView).
- The full GUI suite (mote was running another session's).
Known limits:
- No rate is stored per record, so changing the windows reprices
  history, as a changed PriceRate does.
- Windows follow this computer's zone, with no zone of their own.
- The Sessions page uses the base price.

Co-authored-by: YangHonghang <honghang.yang@qq.com>
2026-10-30 18:55:51 +08:00
yetone 3bce283df4 usage: visibleLocal keeps its set of ids seen for the next pairing, not made again each time (#2278)
visibleLocal made a map of every Claude message id (~400k on the bench
HOME) to size for every pairing: 212 MB of the ~2 GB 90 s of polls
allocated, the largest single site left after the decode buffers were
kept (70d9996c5).

The set is now kept empty between calls as the matcher's scratch is
(keptSeen, an atomic pointer): a call takes it, a cleared map keeps its
buckets, and it goes with the scratch on ReleaseScratch or scratchLinger
after the last pairing. A call while another has it makes its own.

Run on mote at this tree, rebased on origin/main:
- go test -count=1 ./internal/usage/ ./internal/usageapi/: ok, at df09470d0 on 99ad38b7c
- GOOS=linux|windows|darwin go vet -tags nogui ./internal/usage/
  ./internal/usageapi/ ./internal/gui/: ok
- TestVisibleLocalSeenKeptEmpty (new): the set is kept empty, a call on
  other chunks after leaves out what a first call does, ReleaseScratch
  drops it. Broken by hand, red each time: the set not cleared before
  it is kept; ReleaseScratch not dropping it.

Bench (hmw.sh, 90 s), second runs: visibleLocal 266 MB -> 71 MB
(msgKeysOf and the duplicates left), fp_peak 347 -> 348 MB. The run's
total (2030 -> 2702 MB) moved with the sessions list, which this run
built again (sessionRoutes +782 MB, QueryPage -277 MB); that list is
the next thing to look at.
2026-10-30 18:36:13 +08:00
yetone 70d9996c57 usage: a pass's decode buffer is kept past a collection, not grown again after every GC (#2278)
chunkRows decoded each chunk into a rowBuffer from a sync.Pool. A poll
while an agent works collects several times a second, and each
collection emptied the pool, so the next pass grew a buffer to the
largest session chunk again. In 90 s of polls on the 65 GB bench HOME,
unpackReusing allocated 779 MB (486 MB flat), 553 MB of it under
matchedBlocks.

The buffers are now kept as the matcher's scratch is: up to four in
keptRows (atomic pointers), taken by chunkRows.of and put back by
release, and let go with the scratch, on ReleaseScratch or scratchLinger
after the last pass.

Run on mote at this tree, rebased on origin/main:
- go test -count=1 ./internal/usage/ ./internal/usageapi/: ok, at ae906d4df on df31059d6
- GOOS=linux|windows|darwin go vet -tags nogui ./internal/usage/
  ./internal/usageapi/ ./internal/gui/: ok
- TestRowBufferKeptPastCollections (new): a buffer survives two
  runtime.GC() between passes, two passes at once get two and both are
  kept, ReleaseScratch drops them. Broken by hand, red each time: release
  not putting the buffer back; ReleaseScratch not calling releaseRows.

Bench (hmw.sh, 90 s, gateway calls appended every 3 s, 10 endpoints
polled), second runs, mote load ~32:
- v0.1.2193 (e11): 2742 MB allocated, unpackReusing 779 MB,
  matchedBlocks 553 MB, pairRowsIn 858 MB, late GCs 26, fp_peak 333 MB.
- this (e12): 2030 MB, unpackReusing 199 MB, matchedBlocks 48 MB,
  pairRowsIn 346 MB, late GCs 16, fp_peak 347 MB (within noise).

Not tried: a real session file growing during the bench (the bench only
appends gateway calls).
2026-10-30 18:27:57 +08:00
yetone 4023a2e999 usage: a page's newest rows are kept on each chunk's part, not decoded again for every page (#2278)
A Usage page read again after a call picked its newest rows by decoding
the few newest chunks again, then decoded them once more for the rows
themselves (rowsOf). Under an agent at work that is the long session's
own file among them (57k calls): in the writer bench (a call every 3s,
the GUI's 10 endpoints polled) pairedRows.newest was 392 MB of 90s.

newest now keeps what a chunk gave on the chunk's part: its newest rows
the filter keeps, up to take, each with its row (strings copied, as the
chunk is decoded lent), and whether that was all of them. The part is
the cell cache's: its chunk serial and pairing sig, under the page's
period and filter, dropped with the rest when the clears, names or
prices change (meta). A page that wants more rows than the chunk gave
reads it again. The page's rows come from newest, and rowsOf is not
called for them.

Run at the pushed head, on mote:
- TestNewestKeptOnPart: pages of take 2, 2, 1, 4, 4, 6 decode 1, 0, 0,
  2, 0, 0 chunks with the same refs and rows; new parts decode again;
  rows read stay as they were after the chunks are decoded again over
  the lent block. Broken by hand, red each way: the kept rows never
  used; the take check dropped; the lent strings not copied.
- go test ./internal/usage/ ./internal/usageapi/: ok
- go vet -tags nogui, GOOS linux, windows, darwin: ok
- Writer bench, second start of each binary, 90s, load ~25:
  newest 392 MB and rowsOf 88 MB (v0.1.2190) -> 6 MB and none.
  Everything allocated: 3698 MB with only the refs kept -> 2742 MB.
  fp_peak 312 -> 333 MB, late GCs 46 -> 26.
  Not changed: the decode buffers are a sync.Pool, emptied at each GC,
  so the big chunk's buffer is now grown by matchedBlocks (18 -> 553 MB)
  where newest and rowsOf grew it before. That is the next change.
2026-10-30 18:17:09 +08:00
yetone 819aad1bc1 usage: a chunk's Claude message ids are read once per serial, not on every pairing (#2278)
visibleLocal leaves out a Claude message written again in another file.
To do it, every pairing decoded every local chunk of the period and
hashed each row's message id. While an agent worked (a call appended
every 3s, the GUI's endpoints polled every 5s), that was 1.1 GB of the
4.5 GB allocated in 90s; 840 MB of it was decoding.

Each chunk's message keys (the two hashes and the row) are now kept by
the chunk's serial, as matchedBlocks' hints are, with the same pruning
(hintsKept turns). Only a chunk with no serial, or none kept, is
decoded. The keys are read in the order the chunks are passed, so what
is left out is the same as before.

Run at this head, on mote:
- go vet ./internal/usage/; GOOS=linux, windows, darwin go vet -tags
  nogui ./internal/usage/ ./internal/usageapi/: ok
- go test -count=1 ./internal/usage/ ./internal/usageapi/: ok
- TestVisibleLocalKeptBySerial: three chunks, two with serials. The
  calls decode 3, then 1, then 1 chunk, with the same rows left out each
  time, and in reverse order too.
- Broken by hand: ignoring the kept keys made it red (call 1 decoded 3
  chunks); shifting each kept row index made it and
  TestVisibleLocalLeavesOutRepeatedMessages red.
- Writer bench (hmw.sh: the real 109 MB usage.jsonl history, calls
  appended every 3s, 10 endpoints polled), at the second start, heap
  profile at 90s, against v0.1.2188's code:
  - visibleLocal: 1111 MB -> 259 MB (msgKeysOf 53 MB);
  - pairRowsIn: 1394 MB -> 331 MB;
  - total allocated: 4537 MB -> 3908 MB;
  - fp_peak: 544 MB -> 315 MB.
  mote was at load ~26 from other work, so the times are noisy.

Not changed: the seen map is still built on every pairing (206 MB of
the 259 MB left).
2026-10-30 17:57:52 +08:00
yetone 8974836679 usage: a chunk's rows before the heatmap's cut are counted once, not on every read (#2278)
heatBefore summed the recent chunks' rows before the cut for heatSplit,
pageSplit and effortSplit, unpacking every recent chunk whole each time.
A long-lived session file is recent for weeks (one of the owner's Claude
sessions holds 57k calls), so each recompute of the Usage page while an
agent works unpacked ~200k rows three times. A named chunk's sum is now
kept by its serial and the cut, and dropped after hintsKept reads that
didn't ask for it, as hintsOf keeps a chunk's hints.

Run on mote at this tree:
- go test ./internal/usage ./internal/usageapi: ok
- GOOS=linux|windows|darwin go vet -tags nogui ./internal/usage: ok
- TestHeatBeforeKeptBySerial: sums equal a count of every chunk, a named
  chunk is unpacked once per cut, an unnamed one every time.
  Broken by hand (a kept sum used whatever its cut): red; restored, green.
- A debug build on a copy of the real history logged each call: the
  first reads of a start (concurrent) unpacked 766 non-empty chunks
  (207k rows) each; the next read unpacked none of them.
- Cold start bench, 120s of polls: fp_peak 321MB vs 309MB before, 103 vs
  96 GCs: no change outside noise, since polls answered 304 recompute
  nothing. A bench appending a call every 3s was too noisy on mote
  (load ~20 from other work) to show a difference either way.

Not tried: the GUI suite (no GUI file changed).
2026-10-30 17:42:08 +08:00
yetone 8f0d21a009 usage: a start reads the gateway log's full blocks from log-v1.bin, not the whole log again (#2278)
Every start parsed the whole of usage.jsonl with json.Unmarshal a line at
a time. On the owner's real history (109 MB) that was 622 MB of the first
18s's 1765 MB allocated, and most of the GC work of a cold start.

The full blocks the log index freezes are now kept in log-v1.bin beside
the sessions cache, with where they end in the log (offset, line count),
the SHA-256 of the log up to there and the hasher's state, first/firstOwn,
the provider keys and hosts seen, and the probe rows before that offset.
A start reads them and parses only the lines after. They stand only
while the log's bytes up to the offset hash the same and the code that
reads them is the same (requestDiskBinary); otherwise the whole log is
parsed as before. The file is written through a temp file and a rename,
at most every 10 minutes and only when it gains blocks.

Run on mote at this tree, rebased on origin/main:
- go test ./internal/usage ./internal/usageapi: ok
- GOOS=linux|windows|darwin go vet -tags nogui ./internal/usage: ok
- TestStartReadsKeptLogBlocks: a second start loads the kept blocks, and
  rows, probes, keys, hosts and hash equal a whole parse; a log edited
  before the offset is parsed whole.
- Broken by hand: accepting the kept blocks without resumeLogHash turns
  TestStartReadsKeptLogBlocks red (hash differs); restored, green.
- Bench on a copy of the real history (~/r2278, 109 MB log), cold start
  polled 120s, second start of each binary (caches hit):
  v0.1.2184: peaklive 217MB fp_peak 307MB, 156 GCs
  this:      peaklive 210MB fp_peak 315MB,  98 GCs
  readLogSnapshot alloc_space 622MB -> 8.6MB; total 1765MB -> 1095MB.
  The first start writes log-v1.bin (7.4 MB).

Not tried: the GUI suite (no GUI file changed); Windows and Linux runs of
the package (vet only).
2026-10-30 17:10:26 +08:00
yetone f8088cb2d1 usage: a page whose settled days are kept leaves the gateway's older blocks unpriced (#2278)
Every query of All priced and unpacked every gateway block of the history
before it looked at what it needed. With the page's cells, the heatmap's
days and Codex's effort kept from earlier days (page-v1, heat-v1,
effort-v1), a cache hit reads only the last days' rows. Pricing the rest
was still 53 MB of the 219 MB heap at 18s on the real history
(blockPricer.priceBlock: 38 MB of pooled rows, 14 MB of unpacking).

readRequestBlocks now leaves a packed, named block whose newest call is
before settledBefore(now) (the splits' edge) as a stub: its serial, count
and latest time, the raw block and the pricer. priceStubs prices stubs in
place, and every pairing calls it first (pairRowsIn, pairRowsMemo,
heatBefore). So a miss, a page of older rows, or a period the splits don't
cover prices them as before. rowsIn counts a stub by its raw block.
heatSettledKey names a gateway block by its raw rows, which requestState's
meta prices, so a priced block and a stub get one key. That changes the
keys once; this binary's own keys already change.

Run at 0414bbedd plus this change (origin/main fetched, no newer commits), on mote:
- go test -count=1 ./internal/usage ./internal/usageapi: ok
- go test ./internal/gui: the AppKit tests time out at 30s, the same set
  as #4125 (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
  TestMainWindowCorners and 7 more); nothing else red
- GOOS=linux/windows/darwin go vet -tags nogui on the three packages: ok
- Broken by hand: with the stub turned off,
  TestKeptPageLeavesSettledBlocksUnpriced fails with "started again, 2
  blocks priced"

Real history on mote (~/r2278, a copy of the real ~/.codex, ~/.claude and
gateway log), 120s with the GUI's polls:
- v0.1.2183 at a cache hit: fp_peak 368 MB (356-374 before), peaklive
  262 MB
- this change at a hit: fp_peak 301 and 308 MB, peaklive 226 and 219 MB
- the first start of a new binary misses as before: 510-512 MB
- the five pages (all, 7d, all at offset 0 limit 100, all for codex, 30d)
  are the same as v0.1.2183's apart from float rounding in the sums
  (largest relative difference 5e-14)

Not tried: Windows and Linux runs. The change is in the usage package,
which has no OS-specific code.
2026-10-30 16:45:53 +08:00
yetone 0414bbeddb usage: page-v1.json holds eight pages and moves one read near its end first, so a reader's filters don't drop the warm-up's (#2278)
page-v1.json held four pages, newest written first, and a page read
from it was never moved. The warm-up's All, the Usage page's period,
the tray's periods and a few filters a reader picks are more than four,
so the warm-up's was dropped and every start after paired the whole
history again (the 587 MB start). Seen on the real history: after five
pg.sh pages the next start missed. It holds eight now, and a page read
from the second half is written again first.

Real history on mote (~/r2278), with the previous commit: a start
after the five pages hit (fp_peak 356 MB, peaklive 266 MB).

Test: TestPageReadAgainStaysOnDisk (the warm-up's page last of eight,
read, then one more page written: the next start still reads it).
Broken by hand (no move): red, "read again, then another page written".

Run at this head, on mote:
  go test -count=1 ./internal/usage ./internal/usageapi: ok, ok
  GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage: ok
Not run: the full suite. internal/gui's AppKit tests time out on mote
(#4125); this change is internal/usage only.

Rebased on 6d154ef1e (with the commit before this); go test
./internal/usage ./internal/usageapi and the three vets ran again at this
head: ok.
2026-10-30 16:15:28 +08:00
yetone 4650e1e3c4 usage: this computer's zone is one page key, so the warm-up builds the page the Usage page reads (#2278)
The warm-up and the tray ask QueryPage with Filter{} (no zone); the
Usage page asks with Zone: time.Local (usageapi.FilterIn, usage.Zone("")
is time.Local). Both read their days in time.Local, but the pages cache,
the parts cache, pageOld and the page-v1.json/heat-v1.json keys took
them as two filters. So the warm-up's pairing of the whole history
warmed nothing the page read: the page built its own beside it, and
page-v1.json held two All pages. Found by logging the page key of every
start on the real history: the warm-up's key had zone "" and the page's
"Local", with everything else the same. queryPageOf now treats Zone ==
time.Local as no zone, before any key is made.

Real history on mote (~/r2278), 120s each, the build with this and the
next commit:
  new-binary miss  fp_peak 518 MB, peaklive 378 MB (v0.1.2180: 587/408)
  hit              fp_peak 374 MB / 356 MB, peaklive 271/266 MB
The hit after the five pg.sh pages (all, 7d, 30d, all with offset,
codex) started with the page cached on disk.

Test: TestLocalZoneIsTheWarmUpsPage (the page in time.Local after the
warm-up's pairs nothing more and is equal). Broken by hand (the
normalisation off): red, "the page in time.Local paired [6 6]".
TestPageSettledFromDisk's setup moved into pageHistory, which the new
test shares.

Run at this head, on mote:
  go test -count=1 ./internal/usage ./internal/usageapi: ok, ok
  GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage: ok
  go test ./internal/gui: 8 AppKit window tests time out at 30s
  (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestMainWindowCorners
  and others): mote's AppKit hang, #4125. This change is internal/usage only.
Not run: the full suite.
2026-10-30 16:14:45 +08:00
yetone 6d154ef1e1 context: scripts (curl, Bun, python-httpx…) are one Scripts card, not an agent each
A request whose User-Agent names only an HTTP library or an SDK (curl,
Bun, node-fetch, undici, python-httpx, requests, aiohttp, Go-http-client,
okhttp, the OpenAI/Anthropic SDKs, …) or nothing at all got a Context
scorecard of its own, as if it were an agent (theforeveriris on X: "Bun",
"curl", "python-httpx" cards). usage.IsLibrary names those clients;
contextOfRecs folds them and "other" into one "Scripts" card at read
time, so older history reads the same way, and the card's meta line and
tooltip list the libraries by count. The cached day records are not
changed. No setting: it works as is. The Usage page's Agents list still
shows each library by name, with its Hide and Count-as-agent controls.
i18n for zh, zh-TW, ja, de. Existing context.js comments were condensed
so TestCoreScriptBudget holds without a raise (core scripts -28 bytes).

Run, at this head (rebased on 40af66027):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  (mote) for usage and gui; earlier the whole tree on all three, exit 0.
- mote: go test -count=1 -tags nogui -timeout 45m ./internal/usage
  ./internal/gui: ok, ok.
- Windows box: context-scripts + i18n-keys 26/26 (chromium, webkit,
  5 languages, 360 and 1100px). Before the rebase, every reachable file
  (context-*, compact-one-value, group-context, routing-context-fold,
  routing-ctx-fold, routing-ctx-still, i18n-keys, gui-de/ja/zh-tw,
  header-relang): 333/349; the 16 reds are routing-ctx-still, red the
  same on origin/main 40af66027 on that box, listed in #4124.
Broken by hand: IsLibrary false and no fold -> TestIsLibrary and
TestContextScriptsAreOneCard red (cards python-httpx, claude, Bun, ...);
the JS label/clients removed -> context-scripts.test.cjs 0/22.
Not tried: a real app run with real curl/Bun traffic; Linux WebKitGTK;
GUI files on mote (its browsers were busy with another suite).
2026-10-30 16:05:58 +08:00
yetone c7171a2561 usage: a page's cells before its last days are kept in page-v1.json, so a start pairs only the recent chunks for All (#2278)
A start's first page of All (the warm-up's, and the Usage page's own)
paired the whole history for the page's cells, every gateway call with
its session row: ~85 MB of a ~316 MB heap at 18s after the heatmap's days
and Codex's effort were kept (v0.1.2172). The cells of the rows before
cut (local midnight two days back) are now kept as heatSplit keeps its
days, in memory and in page-v1.json beside the sessions cache, under a
key from heatSettledKey plus the page's until, names and hours. A start
pairs only the chunks since the edge. A page whose rows are older than
cut (an offset past the recent rows) falls back to the full pairing.

Real history on mote (~/r2278, a copy of the owner's), 120s each,
three starts in a row:
  v0.1.2165       fp_peak 451-471 MB, peaklive 326-364 MB
  this, miss      fp_peak 587 MB, peaklive 408 MB (a new binary's first start)
  this, hit       fp_peak 361/366 MB, peaklive 265 MB, gcs 150 (was ~150)
page-v1.json is ~240 KB.
The output is the same: /api/usage/requests for period all, 7d, 30d,
all with offset/limit and all filtered to codex, from a start that hit
page-v1.json and from a cold one (file moved away): 0 differences, each
float within 1e-6, on two hit runs.

Test: TestPageSettledFromDisk (first page pairs once and writes the file;
after a restart fewer chunks are paired and the page is equal; an older
offset falls back and equals the cold page; a changed settled file pairs
everything, then hits again). Broken by hand (pageSplit always false):
it goes red at "first page: pairings []".

Run at this head (rebased on ace8ee1e1), on mote:
  go test -count=1 ./internal/usage ./internal/usageapi: ok, ok
  GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage ./internal/usageapi: ok
Not run: the full suite. TestCoveredWindowStaysUp (internal/gui) is red
on mote even alone, "signal: killed", the AppKit hang under #4125; this
change touches internal/usage only.
2026-10-30 15:44:59 +08:00
yetone 643b525469 usage: a DeepSeek call at peak hours costs double its off-peak list price
treeMan on Discord: DeepSeek bills off-peak at half the peak rate, and the
Usage page didn't follow it. The catalog's list prices for these models
are already the off-peak ones: models.dev's DeepSeek, Command Code and
OpenCode Go entries give the off-peak rate as the price and a factor-2
multiplier for peak hours, and api.json leaves the multiplier out
(deepseek-flash: $0.15/$0.60/$0.003, DeepSeek's page says $0.30/$1.20/
$0.006 at peak). So every peak call was counted at half its cost. Now a
call made from 01:00 to 04:00 or 06:00 to 10:00 UTC, Monday to Friday,
costs twice the list price. The call's own timestamp decides.

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

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

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

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

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

Not tried: a real call to DeepSeek, Command Code or OpenCode Go at peak
and off-peak to compare against their bills; a full go test ./...; the
holiday rule's handling of the swapped working weekends (DeepSeek says
Monday to Friday, so a worked Saturday stays off-peak here); ZenMux,
whose own docs give no schedule.
2026-10-30 15:22:55 +08:00
yetone 32f5c33692 usage: a chunk without calls is read back from requests-v1.bin without a Latest, so a new version pairs its history on one start (#2278)
diskEntry wrote a chunk's Latest as c.Latest.UnixNano(). For a chunk
without calls Latest is the zero time, whose UnixNano is out of int64's
range and is written as another time; readDiskEntry read it back as a
call on 1969-12-31. heatSplit and effortSplit count a chunk with a zero
Latest as recent, but one read back so as settled, so the settled set
after a build (14426 chunks on the real history) differed from the one
after a read (15677). The key heat-v1.json and effort-v1.json were
written under on a new version's first start missed on its second, and
the whole history was paired again: two cold peaks, not one.

A zero Latest is now written as 0 and read back as the zero time.
Old data: requests-v1.bin is rewritten under the new binary (its key
holds requestDiskBinary()), so nothing old is read by the new reader.

Run:
- TestDiskEntryKeepsNoLatest round-trips a zero Latest and
  time.Unix(1790000100,5). Red on the old reader ("Latest 0001-01-01
  ... read back as 1969-12-31 16:00:00 -0800 PST"), green with the fix.
- Real history on mote (sandbox HOME, copy of the owner's sessions and
  requests): the first start wrote heat-v1.json and effort-v1.json, the
  second and third didn't rewrite them (both hit), and the heatmap's
  JSON had the same md5 on all three starts.
- Rebased onto 244d80e23; at the pushed tree on mote:
  go test -count=1 ./internal/usage ok (53.3s), gofmt clean,
  go vet -tags nogui ./internal/usage for windows ok (linux, darwin ok
  before the rebase, which touched no file of this commit).
Not tried: a full ./... suite.
2026-10-30 15:16:30 +08:00
yetone 1bbaded622 usage: an agent's call to magpie's own MCP tools is a row of Requests
ferock (Discord) asked to see calls to magpie's MCP tools, such as
magpie-image's generate_image, generate_video and generation_result, in
Routing > Requests.

Each tools/call to magpie's own MCP servers (image, vision, web search,
tools and the Library hub) is now a row of the request log. The row has
Source and Kind "mcp", the tool as its model, the server as its host,
how long the call took, and its error if it failed. The provider and
model it shows are those of the model requests the call made, collected
through the request's context in appendUsage. generation_result names
the model of the job it answers. The stdio Magpie Image server reports
each call it answered to the gateway as "magpie/toolCalled". That report
carries the tool, ms, model and error, never the prompt.

The arguments are never stored at all, so there is nothing to mask. The
rows go down the probe lane: they are listed, but no total, host list,
budget or key limit counts them. The model requests a call made are rows
of their own.

In the GUI the row reuses the Requests list. It gets a muted "MCP" badge
with a tooltip, the server beside the provider, and a Succeeded/Failed
status. The Purpose filter gains "MCP tool" in every language. There is
no new page, no <select> and no left border.

The core scripts went over their budget with the new purpose.
genpurposes now writes purposes.js as compact JSON, which makes the core
448 bytes smaller than main in all, and coreScriptBudget is lowered to
the new total, 1,538,975. No room is added.

Run on mote, at the rebased head:
- gofmt -l: clean. go vet -tags nogui ./... with GOOS darwin, linux
  and windows: ok.
- go test -tags nogui -timeout 45m: ./internal/usage, ./internal/imagemcp,
  ./internal/usageapi and ./internal/gui ok. internal/budget has no test
  files. ./internal/gateway (805s): every test ok except five Antigravity
  and Codex/Grok tests. They fail the same on a clean origin/main
  3bebc3839 and are filed as #4362.
- GUI, the usage-ledger*, routing-request*, purpose*, i18n* and
  gui-zh/ja/de files (25). On mote, Chromium: 32 of 32 ok; WebKit
  could not launch (10 other sessions' suites on mote). On Linux
  (wsl-run), both engines: 335 of 355 ok. The 20 reds are
  routing-request-model, usage-ledger, -ttft, -chart and
  -open-settled, which fail the same at the parent 1534474c8 (#4120).
  usage-ledger-mcp, purpose-filter and i18n-keys are ok in both.
  The whole GUI suite runs after the push, and each red it finds gets
  an issue.
- At the pushed head, rebased on 0804f2d97: ./internal/gui (the
  budget and purpose asset tests among them), ./internal/usage,
  ./internal/imagemcp and ./internal/usageapi ok, and ./internal/gateway
  -run "MCP|Purpose|Probe" ok.
- usage-ledger-mcp.test.cjs covers 5 languages, widths 1180 and 420,
  light and dark, with no sideways scroll.

Broken by hand. Each break went red:
- sawHost's MCP skip removed: TestMCPCallRowsListedNotCounted (the hosts
  list had magpie-image).
- Row/Record.IsProbe's MCP case removed: the same test (3 calls counted),
  and TestMCPCallCountsInNoKeyLimit (Calls: 1).
- The callMCPTool hook removed: TestMCPToolCallIsARequestRow and its
  siblings (no rows).
- The appendUsage hook removed: the row had no provider or model.
- imagemcp's report removed: TestToolCallsAreReported.
- The gateway's magpie/toolCalled case removed:
  TestMCPCalledFromStdioIsARow.
budget's in-memory counts() now skips these rows too. Breaking only that
stays green, because budget.Of reads the file through usage.Visit, which
already skips probes, and limits count tokens and cost.

Not tried:
- no real agent calling a real vendor's drawing;
- no test run on Windows or Linux;
- the page not checked in the real app or in WebKitGTK.
A generate call that answers while its drawing still runs has no model on
its row. The generation_result row that follows names it.
2026-10-30 15:00:16 +08:00
yetone cd5df81ecd usage: Codex's effort before the last days is kept on disk, so a start pairs only the recent chunks (#2278)
After the heatmap's settled days were kept (heat-v1.json, fixed in the
commit before), the cold start's largest part was codexEffortOfIndex:
a pairing of the whole history, every gateway call with its session
row, for the effort column, ~90 MB of a ~310 MB heap at 18 s on the
real history bench.

effortSplit does for it what heatSplit does for the heatmap: the effort
of rows before cut (local midnight two days back) comes from memory
while the settled chunks' serials match (10 min), else from
effort-v1.json under a key built by heatSettledKey (the settled chunks,
the recent chunks' rows before cut, the identities, the code, root and
meta); only the chunks since edge are paired again. When neither
stands, the full pairing is used as before and the part before cut is
kept. Old data: no file yet means one full pairing, as today, then the
file. A write that fails only means the next start pairs again.

Real history (mote ~/r2278/full, heap at 18 s, three starts of this
build): CodexModelEffort 14 MB, effortSplit 3.6 MB on the third start
(v0.1.2156: 91 MB); /api/usage/heatmap at 40 s byte-identical to
v0.1.2156's (md5 7e458920...) on all three. The first two starts of a
new binary write the files (the settled chunks differ once between a
fresh build and requests-v1.bin's read), the third reads them.

TestCodexEffortSettledFromDisk: a restart pairs fewer chunks with the
same sums; a changed settled file pairs all with the changed input; a
cold run without the file equals it. Red with effortDiskRead disabled
by hand ("started again, paired 6 of 6").

Run at this tree, on d05482bab + the commit before (mote): go test
-count=1 ./internal/usage ok (86.1s); rebased onto 70a0c387c (an agent
change) and ran again: ok (16.8s); gofmt -l clean; go vet -tags
nogui ./internal/usage ./internal/gui for linux, windows, darwin ok.

Not done here: queryPageOf, the warm-up's QueryPage(All) page 0, is now
the largest part (111 to 227 MB at 18 s), a full pairing for 50 rows.
2026-10-30 14:47:05 +08:00
yetone ceef9e9438 usage: the heatmap's settled-days key names the filter's zone, not its pointer (#2278)
8d4c07ffe (v0.1.2156) named the heatmap's settled days with %#v of the
Filter, and the page's filter carries Zone, a *time.Location: %#v
writes its address, another in each run. So heat-v1.json never matched
on a start and every start paired the whole history for the heatmap
again, the cost 8d4c07ffe was to take away. Its bench start matched by
chance.

The zone is now written by its name, the rest of the filter as before.

Found with a key-parts log on mote (~/r2278/full): two starts of one
binary wrote headers differing only in Zone:(*time.Location)(0x1089b81e0)
vs (0x105d8c1e0). After the fix three starts of a build with it: the
first (new binary) and second wrote heat-v1.json, the third read it,
and its heap at 18 s has no heatSplit (was 83 to 95 MB in each start
before).

TestHeatSettledKeyNamesTheZone: two FixedZone("Z", 3600) give one key,
nil or another zone a different one. Red at 8d4c07ffe's heat_disk.go
("one zone, two keys"), green here.

Run at this tree, cherry-picked onto d05482bab (mote; first
run on c28cc5c87 the same): go test -count=1 ./internal/usage ok (16.4s); gofmt -l clean; go vet -tags
nogui ./internal/usage for linux, windows, darwin ok.
2026-10-30 14:39:22 +08:00
yetone 8d4c07ffed usage: the heatmap's settled days are kept on disk, so a start pairs only the last days (#2278)
The heatmap's days before the cut (two days ago) came from heatOld, a
full pairing of the whole history kept in memory. A started magpie made
it again on its first heatmap, and again every heatOldFresh (10 min):
on the 52G Codex + 13G Claude bench history that was heatSplit's 88 MB
of the cold start's ~325 MB in-use heap at 18 s.

The days are now kept in heat-v1.json beside the sessions cache, under
a key (heatSettledKey) naming what they were counted of: the request
code and the index's root and meta (prices, names), the cut, since,
zone, filter, the recent chunks' rows before the cut, the Codex thread
identities, and each settled chunk (a session file's by path, size and
mtime, like requests-v1.bin; any other chunk by its rows). The file is
written through a temp file renamed over the last. A key that can't be
named (a chunk with no serial) pairs as before; after heatOldFresh a
same-named key keeps the days without pairing again.

Measured on mote, ~/r2278/full, cold start + the page's 10 endpoints
polled every 5 s:
- heap at 18 s: v0.1.2149 324.6 MB in use, heatSplit 88.3 MB,
  HeatmapOf 135.8 MB; this 310.1 MB, no heatSplit, HeatmapOf 44.1 MB.
- /api/usage/heatmap at 40 s: byte-for-byte the same as v0.1.2149's.
- gcpeak 120 s, 3 rounds each, alternated (mote under other load):
  live 360/393/414 vs 378/404/387 MB, gcs 148/174/168 vs 201/209/160.
  The peak moves to CodexModelEffort's own full pairing (91 MB), next.
- First start, no file yet: pairs as before and writes 7.9 KB.

Tests: TestHeatmapAfterACallPairsOnlyTheLastDays now removes the file
for its cold oracle, and past heatOldFresh with nothing changed pairs
less than all, then a new settled file pairs all and equals cold.
TestHeatmapSettledDaysFromDisk: restarted with memory cleared pairs
less than all and gives the same heatmap; another filter, a rewritten
settled file, and no file each pair all.

Run at this tree (mote): go test ./internal/usage ok (71s);
go test -tags nogui ./internal/gui -run 'Heat|Usage' ok, usageapi ok;
go vet -tags nogui ./internal/usage/... ./internal/gui/... on linux,
windows, darwin ok; gofmt -l clean. Rebased onto e8d42c02d, then cae785a37 (no
internal/usage change in either); at e8d42c02d go test ./internal/usage ok
(100s) and linux vet ok again. Not run: the full suite.
2026-10-30 14:19:41 +08:00
yetone fddd7ff08f usage: pairing keeps its rows as bits and its groups by sums, and lets its pairs go (#2278)
A cold start pairs the whole history, and pairing held its row sets as
map[rowRef]bool, ~40 bytes a row, several sets of most rows at once.
They are now refSet: a bitset a chunk, a bit a row. matchScratch's
groupOf was keyed by the whole matchKey (a session string and its
tokens); it is keyed by a 128-bit maphash sum of them now, and the
sessions map is filled when a group is made. pairedRows' pairs and
compactions maps were filled and never read; they are gone.

Measured on mote, a copy of the real full history (52G Codex, 13G
Claude), GODEBUG=gctrace=1, 120s of /api polls, 3 rounds each,
alternating, v0.1.2143 (807048470) against this change:
  peak live heap  459 -> 439 MB (512/426/440 vs 470/433/413)
  heap at GC      543 -> 517 MB
  footprint peak  677 -> 641 MB
The inuse profile at the peak shows groupOf 28.7 -> 11.8 MB and the
matched set gone from matchedBlocks. This is a small part of the peak;
the rest is the full re-pair itself, which is next.

Run at this tree (rebased onto dca3e2d71 from 807048470), on mote:
go vet ./internal/usage; GOOS=linux|windows|darwin go vet -tags nogui
./... all ok; go test -count=1 ./internal/usage ok (30.1s), with the
new TestRefSet and TestMatchKeySum (no allocation).
Not run: the full suite, the GUI suite.
2026-10-30 13:42:11 +08:00
yetone 807048470e usage: a row keeps its times in ms in 32 bits, 184 bytes where it was 216 (#2278)
A page holds every row of its period at once, and at a cold start over
the full history the rows held were most of what the footprint's peak
held: on mote's copy of the real history (52G Codex, 13G Claude Code),
the inuse heap 20s into a polled start had 48.5 MB of decoded session
rows (unpackReusing) and 42.9 MB of priced gateway rows (pricedRows),
both packedRow.

Millis, TTFT, FirstText, FirstReasoning, Sent, Flow, Own, Retried and
Queued are ms (Record's *_ms) and go in an int32, as Masking already
did. One past 24 days, which no call takes, is kept as the longest an
int32 holds (msOf), not wrapped. The snapshot's encoding is unchanged:
each is written as the int64 it was and read back through msOf.
unsafe.Sizeof(packedRow{}) goes from 216 to 184, 15% of every row held:
~14 MB of the 91 MB above.

Run at this head (rebased on 46aa7e6b8, which touches providers and
the GUI only), on mote:
- go build ./... ok
- go test -count=1 ./internal/usage ./internal/usageapi ok (and before
  the rebase, on eadeb89c4)
- GOOS=linux, windows, darwin go vet -tags nogui ./internal/usage ok;
  gofmt -l clean
- TestRowsOfOneSessionShareAShape now wants 184 bytes at most.

Broken by hand: msOf as a plain int32(ms) turns the new
TestRowTimesPastWhatARowKeeps red ("read back Millis -1702967296").

Not measured: a whole-app footprint A/B. Two rounds of peakheap.sh ran
at mote load ~220, with most polls timing out (3 to 12 of 80 answered)
and each run higher than the last whatever the binary (202, 248, 270,
318 MB), so they say nothing either way.
2026-10-30 12:41:24 +08:00