382c8c0bdfdcedadbfa35ce1df7bd34f583ec17b
338
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
2ae8e61a4f |
usage: an upgrade reads session files again only when the code of their rows changed (#2278)
requests-v1.bin and log-v1.bin were keyed on a hash of every .go file in internal/usage, so nearly every release that touched the package threw both away. The first start after such an upgrade read all ~24k call shards again: on the owner's real accounts (mote, acctp sandbox) that is 13.8s of CPU and ~3.4GB allocated before the page settles, against 2.4s warm. Each file now keys on the source its rows are made, written and read through: rowSource (15 files) and logSource (23 files), embedded by name. The row pricer and a file's chunk builder are lifted out of readRequestBlocks (sessionRowPricer, sessionChunk) so they can be roots. TestRequestDiskNamesTheCodeOfItsRows type-checks the package and walks every declaration reached from those roots (uses, package vars assigned elsewhere, interface calls, encoding/String/sort methods); it fails when a reached file is not embedded or an embedded one is not reached. Of the last six usage-changing releases, four (3962, 3958, 3941, 3908) would have kept the cache. Run: - go test -count=1 ./internal/usage on mote: ok 51.9s. - go vet ./internal/usage for darwin, windows, linux on mica: ok. - Broken by hand: session_provider.go left out of rowSource's embed -> "rowSource: session_provider.go is reached but isn't in its go:embed", FAIL; restored. - Real accounts on mote (pageheap.sh, page open, CPU at mark): w47v first start after an older binary 13.80s, numGC 217 (rebuild, expected); w47v again 2.45s; w48v (w47v plus a live init() in effort_split.go, a different binary) 2.59s, numGC 56; back to w47v 2.43s. Before, the same swap cost ~14s. Not tried: Windows or Linux real start. |
||
|
|
6af6ae9885 |
usage: a log of MCP calls and probes keeps its blocks on disk too (#2278)
log-v1.bin was written only once a gateway block had filled. A log of
MCP tool calls and probes has none (the real-account sandbox's 8.3 MB
log is 25,223 MCP lines and 2,539 probes, 54 probe blocks, 0 gateway
blocks), so full.n stayed 0, the file was never written, and every
start parsed all 27k lines again: readLogSnapshot took 60 MB of the
start's allocations. The probes that were kept went as JSON and were
parsed back a record at a time.
A full point is now marked too when a probe block fills while no
gateway row stands after the full blocks, and it records how many probe
blocks were full there (logFull.probes). Those go to the file as binary
entries, as the gateway blocks do, read from its mapped pages; only the
probes after them, up to the full point, still go as records. The file
is written again when its full point reaches further (by offset, not
the gateway block count). The magic is magpie-log-v2, so a v1 file is
parsed over once.
Run:
- go vet ./internal/usage; go test ./internal/usage ./internal/gateway
(mica, -timeout 45m): ok usage 31s, ok gateway 859s.
- TestStartReadsKeptProbeBlocks (new): an MCP-only log of 3 blocks + 100
is kept, a start reads 3 blocks from the file, and reads as a whole
parse. Broken by hand (no probe full point): red, "a log of probes
wasn't kept".
- Real-account sandbox on mote (acctp, page open 2.5 min, version
0.1.3961 builds): log-v1.bin written on the first start (645 KB);
warm starts, w45v (v0.1.3961) against this:
CPU at mark 3.21s, 3.00s -> 2.50s, 2.39s
allocated 701 MB -> 646 MB, 629 MB
readLogSnapshot cum 60 MB -> 2.6 MB
numGC 66 -> 56
Footprint 128-133 MB -> 132-135 MB, liveHeap ~80 MB both: the same
within noise.
Not tried: a log with both gateway and probe blocks across a v1 -> v2
start on a real account (the unit test's mixed log covers the format).
|
||
|
|
a8b0e80f65 |
usage: the request page's probes are made into a chunk once per change
readRequestBlocks made probeChunk again on every poll of the Requests and Usage pages: a rowChunk holding every probe since the period's start minus a day, interned again each time. On the real-account sandbox it was ~45 MB of 952 MB allocated in two and a half minutes (rowChunk.add under probeChunk, #2278). probeChunk now keeps the last chunk it made, with the probe blocks, since, renames and hosts it was made from. A frozen block is never written again (a new probe reopens the tail as a copy), UsageRenames hands back the same maps while providers.json is unchanged (Renames.Same compares them by identity), and hosts are compared by content, so the same inputs make the same chunk, which no reader writes. Any of them changing makes it again. TestProbeChunkMadeOncePerChange: the same inputs give the same chunk; a later since, a changed host and a new probe each make a new one. Measured on mote with the real-account sandbox (pageheap.sh, the request page polled to the mark): probeChunk allocated 43.81 MB at the base (w42) and 24.54 / 24.10 MB with this (w43, two runs). It is not zero there because the sandbox's network is blocked, so every probe fails and logs a new row, which makes the chunk again. Run on mote: go test ./internal/usage ok (33.9s); the test is red with the memo turned off by hand. |
||
|
|
d85ee9e53f |
usage: the probes are kept in packed blocks, as the gateway rows are
The request log's probes (magpie's own tests, model lists, MCP tool calls
and searches) were a slice of whole Records, 952 B each, and every read
that continued the log appended to a copy of it. The owner's real log has
25,379 of them (25,223 MCP tool calls): ~24 MB of live heap in every
running app, the tray's included, for rows only the Requests page lists.
Now they are rowChunk blocks of logBlockRows, frozen (packed) when full,
the last one reopened as a copy for the next append (probeRows), the way
readLogSnapshot keeps gateway rows. probeChunk and log-v1.bin read them
back through chunkRows; a block whose Latest is before since is skipped
whole. log-v1.bin's format is unchanged.
Tests: TestProbeBlocksContinued (3 blocks + an appended block: the earlier
snapshot reads as before, the continued read equals a fresh parse, since
cuts at the right row). Broken by hand: dropping the continued snapshot's
probe blocks turns it red. TestStartReadsKeptLogBlocks covers the disk
round trip with probes.
Run at this head on mica: go vet ./internal/usage; go test ./internal/usage
./internal/gateway/... ./internal/gui, all ok (gateway 869s).
Real app on mote (sandbox HOME from the real-account sandbox, plus the
25,379 probe lines of the owner's real log), tray idle at 150s, cold:
before (w36, v0.1.3938's code): footprint 105 MB, live heap 48.4 MB,
readLogSnapshot 26.5 MB of it
after (w37): footprint 70 MB, live heap 16.0 MB, readLogSnapshot out
of the top; warm start (log-v1.bin read back): live heap 15.6 MB
Requests page, web mode, same HOME: requests.csv byte for byte the same
on both builds; /api/usage/requests' 100 rows the same apart from the 4
probe rows the first run itself wrote (token refreshes through the dead
proxy).
Not tried: Windows and Linux (no OS-specific code here).
|
||
|
|
477bbb7a15 |
usage: GET /v1/magpie/usage/requests?cursor= reads requests as changes, with stable ids (rdsaltbo on X, #6060)
A program keeping a ledger of its own (a WakaToken plugin) can now read the requests incrementally: cursor=start or cursor=now, then each next_cursor. Rows carry a stable content-derived id (same after a restart), origin, and original_ids (request_id, response_id, client_response_id, message_id, session_id, native_session_id), each only when the source gave it. A call read late, a corrected row (same id, higher seq) and a native row replaced by the gateway's (deleted, with seq) all come through a persisted journal (usage-feed.jsonl, appended and synced before answering). Cursors magpie cannot resume from are refused: 400 cursor_invalid / cursor_filter_changed, 410 cursor_expired / cursor_reset. A held key sees only its own rows and tombstones. Without cursor, offset/limit mode is unchanged. Also: Record.MessageID (not persisted) from the agent file's message id, and usageapi's row decoration moved into a namer shared by both modes. Docs: reference.md, integrating.md, gateway-routing.md, gateway-sessions.md, site remote.html (en/zh/ja), llms-full.txt. Run (mote, this tree): go vet darwin, GOOS=windows, GOOS=linux -tags nogui on usage, usageapi, gateway (gui on darwin); go test -count=1 for internal/usage, usageapi, gui, gateway: all ok. New tests: resume gets exactly the new rows, ids and cursors survive a restart, correction keeps the id, gateway takeover retires the native row, refused cursors, expiry, now cursor, identical records, and the feed over the gateway (held key, 401 without key, offset mode). Broken by hand: an unconditional memo made the new-rows test red (fixed to memo only the next page). Not tried: real Claude Code/Codex session files, a huge (700k+) history, Windows run of the tests, GUI browser suites (no GUI file touched). |
||
|
|
10a27651f0 |
usage: a window's whole is kept across its reset until the new one tells its own (Musikrv77852 on X)
After Kimi Code's 7-day window reset with nothing used, the card lost its "Whole ≈ N tokens" until the new week passed 5% used. The reckoning is every provider's (usage.WithWindowHolds), so the fix is too: carryHolds keeps the last whole told for each account's window (window-holds.json, temp-and-rename) and, where the new window is under the floor or has none routed yet, shows it with holds.prevAt set. The tooltip reuses the past cycle's "Estimated from the window that began X, read Y" line; no new label. The new window's own figure replaces it as soon as it can be told. Run (mote): TestWholeKeptAcrossReset (reset with 0% and 2% used, restart from disk, same-window under floor, other account, new window with data), go test ./internal/usage ./internal/provider ./internal/gui (only TestCoreScriptBudget red until its +10 here), quota-holds and quota-curve GUI files in chromium and webkit (all 5 languages x 360/1000px for the new case), gofmt, go vet darwin/linux/windows for usage and provider. Broken by hand: carryHolds returning early reds the Go test and the GUI case; dropping the prevAt branch in app.js reds the GUI case. Not tried: a real Kimi account across a real weekly reset; a full ./... suite before the tag. |
||
|
|
5241308212 |
settings: a day can start at 0 to 6 o'clock (ssharpcc on X)
Settings > Usage > "Day starts at" (dayStart, 0 to 6, default 0; also magpie settings set dayStart 4). With 4, a call at 01:30 counts toward the day before: the Usage page (summary, charts, heatmap, ledger day filter, hour labels of Today) and the daily and monthly key caps (access.Window, provider.SpendCap.Window). internal/dayzone makes a time.Location whose midnight is the real day's hour:00 (TZif built from the zone's own offsets, same DST instants), so every place that cuts days by a Zone's midnight follows without edits; usage.Zone returns it and the "now" reads use it too. Run (mote): go test usage, settings, settingsapi, access, provider, gui, dayzone, also with TZ=UTC and TZ=Pacific/Kiritimati; gofmt; go vet darwin, linux nogui and windows; day-start, currency, number-units and i18n-keys GUI files in chromium and webkit, en zh zh-TW ja de; TestCoreScriptBudget. Broken by hand: TestDayStartsAfterMidnight red with 9 failures when the hour is ignored. New tests: dayzone over 5 zones x hours 1/4/6 x two years of days, usage, limit window, spend-cap window, day-start GUI. Not tried: a real log history in a real window. Not shifted, filed as #6314: the Sessions page, TUI sessions filter, davsync shared per-day files, gateway_sessions day keys, credits_daily. Rows are never stored in the shifted zone. |
||
|
|
ffc1d64e5e |
usage: a call recorded under magpie's alias id is the gateway's, not a direct one (CrazyJal on X)
Claude Desktop's Code tab, and Claude Code under it, write the id the gateway listed the model by (magpie-<number>.anthropic.<Claude model>, mythos-magpie-<n>, anthropic/magpie-<n>, claude-magpie-<n>) as each turn's model. The gateway's log counts the turn under the model that served it, and the agent's file counted it again under the alias: a row for a model that is none, its cost on top of the real one. Only the gateway knows those ids, so a call that names one went through it. Such calls are now left out of what Direct, the ledger and the Requests page's chunks take from session files, for every agent that records one. Calls under a model of the agent's own are unchanged. usage.MagpieAlias mirrors the gateway's alias forms; a gateway test fails when the two differ. Run (mote, at the pushed head): TestAliasCallsAreTheGatewaysNotDirect, TestMagpieAliasForms and the gateway's TestUsageKnowsEveryAliasForm pass; with ownCalls returning its input the first fails (7 rows, four under aliases). go test internal/usage, internal/gui, internal/sessions ok; vet darwin, linux nogui and windows of usage and gateway clean; gofmt clean. Go-only change, so no GUI file was run. Not tried: a real Claude Desktop 3p session (none on this machine; the model forms come from the gateway's own alias code and its tests, not JSONL bytes). Existing persisted request chunks rebuild with the new binary. |
||
|
|
e6bf4adf1f |
usage: Claude Code's helper requests are labelled, the largest cache write is one click away (recih on X, #6199)
Claude Code's AgentSummary and its auto mode classifier name themselves nowhere in the request, so there is no client marker to read. The gateway tells them by their content (inferredKind: a claude-cli/ request on the Messages API; the classifier by autoModeClassifierAsk, the summary by its last user text "Describe your ... in 3-5 words") and records them as agent_summary_inferred and auto_mode_check_inferred. The purpose catalog names them "Progress summary (inferred)" and "Auto mode check (inferred)" and puts each with its plain kind's purpose, so the existing Purpose filter lists both; nothing known and nothing inferred share a name. A tool that printed the same words, a chat, and another agent's request stay unmarked. A requests page now also holds BigWrite, the gateway-served row that wrote the most to the cache (cells, page-v1.json and pageFromLedger all carry it; rows from session files have no request to open). The Requests line shows it as "109K largest write", a button that opens that request through openUsageRoute. settledCountVersion is raised to 3, which keys the cached pages. Not done: the per-request branch recovery result asked for in #6199. No structured field holds it. Run on mote (load 21-24 of 18 cores, mica was higher): go test ./internal/usage ./internal/usageapi, the gateway and gui purpose tests, go vet for darwin, linux (nogui) and windows, gofmt; the GUI files usage-big-write (new), purpose-filter, routing-kind, i18n-keys and usage-ledger in chromium and webkit. Broken by hand: inferredKind returning "" turns TestClaudeHelperRequestsAreLabelled red; the larger-than test of BigWrite.add turned round turns TestRequestPageBigWrite red on both paths; the jump off turns usage-big-write red. Not tried: a real Claude Code session against a live subscription, Linux WebKitGTK. |
||
|
|
4b1f3eca4a |
usage: a ZCode call magpie routed is not counted again as a local session's (nori_tsukiji on X)
With ZCode on the same computer as magpie, the Usage page's local session calls came out equal to the calls magpie had routed: each was counted twice. Cause: a ZCode request names its session without the sess_ prefix ZCode's database gives it (zcodeBareID; GatewayKeys, Titles and the Sessions list already knew). The Usage page pairs a gateway record with a session file's call by session, tokens and end time (matchedBlocks), and the calls read from ZCode's database kept sess_<id> / sess_subagent_agent_<id>, so they never shared a session with the gateway's records and were never paired. Leaving out calls whose providerID is "magpie" (ocGatewayProvider) only helps when ZCode writes that id beside a reply; with any other id the call was listed twice. Fix: readZCodeCalls gives each call the bare session id; zcode's call parse version is 3, so cached shards are read again. Claude Code, Codex, Pi, OpenCode, Kimi, dsh, grok, minimax, agy and WorkBuddy name their sessions as their requests do (raft.go's requestIDs has ZCode alone); not changed. Run on mote: go test ./internal/usage ./internal/sessions (ok; the zcode fork test's expected session ids are now the bare ones), gui and cli with -run 'ZCode|Zcode|Usage|Session' (ok), go vet darwin/linux/windows (clean), gofmt -l clean. TestZCodeCallsPairWithTheGatewaysRecords (a session, a provider id of ZCode's own, a subagent) was red on the old code: 4 rows for 2 routed calls, the local ones Session sess_7c1f against the gateway's 7c1f. Not tried: a real ZCode database (this computer has none, only the app's tasks index) and the full suite. |
||
|
|
ce0960b4ab |
usage: a first Requests build reads with four workers, not eight
A first build of the request rows runs on any upgrade that changes internal/usage (the cache key hashes its source) and on a first install. Each prefetchEach worker holds a whole file's calls while it reads, so eight of them stacked up in the cold peak. Measured on mote with a copy of the owner's real accounts and history (HOME ~/r2278/acct, requests-v1.bin removed before each start), five cold starts of each build alternated, physical footprint peak at 12s (vmmap): eight workers: 248.3 259.1 252.1 257.5 276.1 MB (mean 258.6) four workers: 243.3 230.2 232.6 245.2 246.7 MB (mean 239.6) Every four-worker run is below every eight-worker run. The build takes the same time: the gctrace burst ends at 5.0/5.0/5.6/5.0/6.2s against 5.0/4.8/4.9/5.0/6.4s, and CPU in the first 12s is 6.7-7.6s for both. The cache written is the same size (71,523,711 bytes) for both. TestPrefetchEachMakeIsAReadersOwn counts four readers' makes now. Run at this head (rebased on |
||
|
|
82f09e3248 |
sessions: Codex's leftover review threads are no rows, and its one-session folders are one group
Deleting a thread in Codex leaves its subagent rollouts behind: the
guardian's review threads, titled by the prompt it asks ("The following
is the Codex agent history whose request action you are assessing…"),
and the title threads it opens. magpie reads every rollout, so each was
a session of its own, and one whose thread was gone had nothing to hang
under. On this computer 642 Codex sessions held 422 subagent threads,
86 of them with their parent thread's file gone (and 2 more under one of
those): they filled folders of their own (Documents\Codex\2026-08-17\
shan, wang, wei…), and the bar counted 531 sessions made with another
provider, 371 of them review threads no one ever opened. Codex Desktop
also makes a folder for every chat started without a project
(~/Documents/Codex/<date>/<name>, its outputs/ and work/ in it, named
from the prompt): 36 of them here were 36 folders of one session each.
listAgentWith now drops a Codex subagent thread whose parent is not
listed, to a fixed point, so a chain of them goes too; the agent's tab
counts the rows it lists. The "Scratch sessions" group that commit
e373adddf gave ZCode's draft folders now holds Codex's own per-session
folders as well (that one, Documents\Codex\<date>, a probe in a temp
folder, worktrees, another app's hidden folder). The provider bar counts
Codex's own threads only (role main or unknown): 531 became 160 here.
And a gateway session no call of which was answered and which spent
nothing is no row either (usage.GatewaySession.SpentNothing): the three
empty rows under "Seen through the gateway" were Codex's failed
title calls (kind thread_title, 400/499, 0 tokens), their ids ones no
file of Codex's has.
Rows: 642 Codex sessions to 554 (88 review threads gone), 422 subagent
threads to 334; 36 folders (51 sessions) folded into Scratch sessions;
3 gateway rows to 0, so "Seen through the gateway" is empty here. Usage
still counts every one of those calls, and nothing was deleted.
Run:
- go test ./internal/sessions -run 'TestCodexSubagentWhoseParentIsGone|TestZCode' -count=1: ok.
- go test ./internal/gui -run 'Session|Gateway|Manage' -count=1: ok.
- go build ./...; go vet ./internal/gui ./internal/usage ./internal/sessions; gofmt -l; git diff --check; node --check client.js: clean.
- go test ./internal/sessions -count=1: the same failures as without this
change (TestAgySessions, TestAgyRowOnly, TestAntigravityAppFolder,
TestCCListingKeepsItsNames: path separators and allocation counts on
this Windows box).
- go test ./internal/usage -count=1: TestDesktopSessionAccountMetadata
fails without this change too.
Broken by hand:
- without keptSubagents the 86 rows come back
(TestCodexSubagentWhoseParentIsGoneIsNoRow fails);
- hiding a gateway session on "spent nothing" alone breaks
TestSessionsSameWithoutRows and TestGatewayConversationAPI: a call
answered with no tokens is still a session, so SpentNothing also asks
that none of its calls was answered;
- counting subagent threads in the provider bar says 531 here, 371 of
them review threads.
Not changed: the review threads' calls are still counted by Usage and by
the Sessions page's stats; their rollouts stay on disk (Deleting the
parent does not delete them); the scratch grouping is worked out on the
page (client.js), so Usage's folder filter still lists those folders by
their paths.
|
||
|
|
059d995d56 |
gateway keys: the list reads the ledger once for all keys, and a proxy's web page is said by its title (aiandcloud on X)
aiandcloud (2.98B tokens, 12,654 requests a day, server mode behind a
proxy) saw Gateway keys draw a Cloudflare 524 page as raw HTML.
Slow list: every poll of /api/caller-keys read up to a month of ledger
rows once per window per key. budget.AllOf now reads each distinct window
once for all keys, and keeps the settled blocks' sums with a cursor
(usage.VisitFrom), so a poll only reads what was appended since; the
unfinished tail block is always read again. A rewritten or shorter log
resets the cursor. All(k) is AllOf of one key.
Numbers (BenchmarkAll vs BenchmarkReadEach, 8 keys x day/week/month,
31 days x 12000 rows/day = 372k rows, warm): 211-228 ms before, 23.5 ms
after.
Raw HTML: fail() now turns an error string holding a web page (a remote
magpie's or a vendor's 524/502 page inside the JSON error) into a short
said/what pair, "A proxy in front of magpie answered, not magpie ({what})"
with the page's title, translated in all 5 languages (key already in
i18n.js). The browser already handled non-JSON bodies (notJSON, #2032).
Run (Windows box, mote ssh was down earlier): go test budget, usage, gui
(AllOf, Budget, FailSays, I18n, Keys); gateway-keys-proxy-page and
gateway-key-limit GUI files in chromium and webkit, 5 languages: 24/24;
gofmt; vet windows, linux nogui, darwin (mote, only a clang deprecation
warning). Broken by hand: with the old fail() TestFailSaysAProxyPageByItsTitle
is red; with VisitFrom's reset() removed TestAllOfIsWhatEachWindowRead is red.
Not tried: a user-scale cold ledger, a server behind a real Cloudflare,
the full suite before the tag (started after).
|
||
|
|
88c417392e |
usage: a sortable model speed ranking on the Requests tab (@flying_crp on X)
Usage's Requests tab gets a "Model speed" card: per model, the median output tokens/s, the median wait for the first token and the request count, over the selected range, sortable by every column (aria-sort header buttons, quiet table, no gradients). A request counts when it was answered (not rejected, handed on, failed or canceled), its first token was timed and it wrote 100 tokens or more (usage.MinRankTokens; the tooltip says so). Computed locally: each chunk keeps a 2% log-bin histogram per model beside its cells (speed_rank.go, chunkPart.speeds), a page merges the chunks' histograms, so there is no per-request sort and medians are within ~1%. The settled chunks' histograms are in the page file; its key salt is now page-v2, so the first load after upgrade recounts settled history once. /api/ledger sends speeds and speed_min. Run (mote): gofmt clean; go vet darwin, linux nogui, windows for the touched packages and ./... earlier; go test internal/usage, internal/usageapi, internal/gui ok at this head; usage-model-speed.test.cjs 12 of 12 (chromium and webkit, en/zh/zh-TW/ja/de, 400px: order, sort by every column, aria-sort, focus kept, no horizontal overflow, ellipsis, hidden when empty); with i18n-keys and i18n-en-no-cjk 20 of 20; the whole GUI suite once on the branch before the rebase: every red is in a file unrelated to this change (account-arrange #6010, account-refresh-holds #5814, account-eye #5052, agent-switch-accounts #5925, bulk visibility and disconnect previews #5982 fixed in |
||
|
|
d5f6159109 |
usage: a test that a failed stat keeps the log's last read (f2039c13f)
|
||
|
|
f2039c13fc | usage: a log that can't be read but for being absent keeps its last read (@simonzyzy on X) | ||
|
|
28a79bc33a |
gui: the gateway-mode stats test holds its clock at a local 00:30 (#5690)
TestGatewayModeStatsNameTheGatewaySessions wrote its record at
time.Now()-1h, which in the first hour of a local day is yesterday, so
days=1 left it out: red on macOS and ubuntu CI at
|
||
|
|
d02bb81788 |
usage: Codex's effort before the last few days goes when idle too
dropEffortPeriods let go of every period's kept CodexModelEffort answer,
but effortOlds (each period's effort before the cut, ~2.1 MB in the t60
idle heap with real accounts, under effortSplit) stayed for the life of
the process. It is in effort-v1.json and effortSplit reads it back from
there when the entry is missing, so it now goes with the rest, under
codexEffortBuilding (TryLock: a build under way keeps it).
Run on mote at this head: go test ./internal/usage ./internal/usageapi
./internal/gui ok; gofmt clean; GOOS=windows go vet and GOOS=linux go
vet -tags nogui ./internal/usage ok.
Broken by hand: without clear(effortOlds),
TestIdleCodexEffortLetGoAndBuiltAgain fails ("0 periods' answers and 1
periods' effort before the cut kept while idle").
Not tried: a fresh real-account heap at this head (next acrss run).
|
||
|
|
8d68b5f219 |
usage: Codex's model and effort answers go with the chunks' caches when idle
CodexModelEffort kept each period's answer (every Codex thread's
consumption by model and effort) for the life of the process. On a real
history it was ~6.9 MB of the idle heap after one visit to the Sessions
page (t59 measured on mote, heap at 10 idle minutes:
usage.keptCodexModelEffort).
Each ask now notes itself with derivedUsed, as the pairing and heatmap
reads do, and dropDerived lets go of every period's answer but one being
built. The page polls every 15 s while open, so it keeps them; the first
ask after derivedIdle (3 minutes) builds the answer again, waiting for it
as a first ask does.
Run on mote (go1.26.8):
- go test -count=1 ./internal/usage ./internal/usageapi ./internal/gui: ok
- gofmt -l, go vet, GOOS=windows go vet, GOOS=linux go vet -tags nogui
for internal/usage: clean.
- Broken by hand: with dropEffortPeriods left out of dropDerived,
TestIdleCodexEffortLetGoAndBuiltAgain fails ("1 periods' answers kept
while idle").
|
||
|
|
d401c25951 |
usage: the found-group names hold the catalog, so a usage ask no longer builds it again (#5978)
|
||
|
|
a54dddd967 |
usage: the request page's chunks go once it has gone unasked for 7 minutes
The 2-minute idle trim held the session files' chunks to requestIdleBytes
(24 MB). A real history's chunks (~11 MB on the owner's accounts, t54's
idle heap: readRequestBlocks 11.3 MB, readDiskEntry 9.2 MB flat) fit under
that bound, so they were kept for the life of the process after one visit
to the Usage page. Now a second timer, requestForget (5 min) after the
trim, lets them all go when nothing asked for the page since the trim. The
next page reads them back from the file of them (toDisk), decoded and not
parsed again; chunks not saved yet are parsed again, as with the trim.
`asks` counts the asks, so a forget armed before an ask lets nothing go.
Run (mote unreachable all evening, so on the Windows box and its Linux VM):
- wsl-run: go test -count=3 -race -run TestRequestChunks ./internal/usage ok;
go test ./internal/usage ./internal/sessions ./internal/dirent ok;
go vet ./internal/usage for linux, windows and darwin ok; gofmt clean.
- Broken by hand: with the forget's trim(0) taken out,
TestRequestChunksForgottenLongIdle fails ("forgotten: 3 chunks kept").
- win-run: internal/gui and internal/usage. Every red there is the same at
the base
|
||
|
|
6b92824ff5 |
usage: a window's whole also at base rates, without long-context premiums (#5861, Norethcy on X)
A window's whole (WindowHolds) is priced at API list prices, which charge
GPT-6.1 Sol's input above 272K at a premium a subscription's own use
doesn't pay. A cycle with more long calls then reads as a larger
allowance: NorethSea's previous week came to $76.56, $53.52 without the
premium, against $56.99 for the current one.
Each priced call is now also costed at its model's base rates, the
long-context tiers left out and a peak hour's price kept (baseRates), and
the window's whole sent as BaseCost beside Cost, only when the two differ.
Past cycles get it too (HistoricalWindowHolds goes through windowHolds).
On the card the figure then says which it is ("≈ $76.56 API") and is a
button: a click switches every card, past cycles too, to the base figure
("≈ $53.52 base") and back, moves nothing, and is kept in the browser.
Its tooltip names both and says neither is an official dollar allowance
or a fixed quota. A window that paid no premium is drawn as before. The
ledger's and the API's real cost are unchanged. #4181 (auto-review calls
counted in the whole) is not part of this.
app.js and the core stay in their budgets with holdsLine's and holdsWhy's comments cut, no raise.
Run (mote's sshd reset every connection, so on the Linux box through
wsl-run; the package run at base
|
||
|
|
4921bf5a97 |
usage, sessions: one model option for a found routing group's two ids (#5892, Norethcy on X)
A found routing group is called by its public id (auto/<model>) and is kept as group/auto-<slug>; calls recorded under either were counted as two models, so Usage › Sessions' model filter listed the same group twice and the ledger, summaries and session lists split its calls. Ported from NorethSea's 30d6261cd on their fork: UsageAlias names a found group by its public id before the user's alias (both spellings, old session files too), sessions' lists, the ledger keyer, the summary cache's key and Codex's model/effort read through it, and a cache keyed on the group names (UsageNamesKey) is read again when a group is renamed. A user's own provider named "auto" keeps auto/<model> (autoRefsOn). Changed in review: the patch's ledger filter compared every record with provider.SameRef, which reads the providers (customIDs, a stat of providers.json) for each record a filter passes over. FilterOf, the one place a Filter is made from a query, now canonicalizes the model once, and keepsRecord asks the providers only for an auto/ record under a group/ filter (sameGroupModel). Run (mote's sshd reset every connection all afternoon, so on the Linux box through wsl-run; the package run at base |
||
|
|
3b261932e1 |
usage: what is kept of each chunk by its serial is let go after three idle minutes
Message keys, match hints, chunk first times and heat sums are kept by chunk serial and pruned only by turns, so with no pairing or heatmap while nobody looked they stayed for the life of the process (~4 MB of message keys alone in a real history's idle heap). They are now let go once none was read for three minutes, and read again from the chunk on the next ask. Test: TestDerivedLetGoWhenIdle (kept while read, let go when idle, same answers after). Run: go test ./internal/usage on mote at this head (ok, 36s) and on the Linux box; go vet linux, windows, darwin. Broken by hand (the drop skipped): red, "idle: 3 heat sums and 3 firsts kept". Real-account copy on mote, 330s idle, both orders: hintsOf's 1.6 MB is gone from the end heap; footprint moved with run order (+10-15 MB for whichever ran second), so no footprint gain is claimed. Not tried: an idle after the Requests page was paged, where message keys are kept. |
||
|
|
662546e78d |
usage: a cache hit rate reads 100% only when all of the prompt was cached (ZhangXiaof48473 on X)
Routing's request list showed "缓存 100%" for Codex requests of 77.5K
tokens that read 77,200 of them from the cache (99.6%), beside rows at
99%, and the route line said "请求缓存命中率 99%". Every hit rate was
Math.round(100 * h) + "%", so anything from 99.5% up read 100%.
One formatter now says every hit rate: hitPct(h, d) in app.js, whole
percents (d decimals) unless rounding would say 100% or 0% of a prompt
not all or none cached, then one or two decimals (99.6%, 99.95%; never
past 99.99% or under 0.01%). Its callers: Routing's request rows, their
route line and a session's Avg. cache (plugins/routing/client.js); the
tray panel's Cache hit rate and the ranking rows' hit rate (app.js); the
Usage page's tiles, agent rows, Requests table, request detail and its
KPI strip, which keeps its one decimal (plugins/usage/page.js); the
context card's Prompt cache and the session traits Cache-friendly,
Cache misses and Cache hit (context.js). The TUI's and CLI's sessions
line, which floored the integer, use usage.HitPct, the same rule in Go;
it rounds now, so the TUI test's 67% (25.2K of 37.3K, 67.6%) reads 68%.
No new strings; app.js pays its bytes with six ledger comments cut, so
the core scripts are 15 bytes smaller than at its parent, no raise. Main
is over the core budget already (1,534,476 > 1,533,802 at the parent,
#5918); this commit doesn't add to it.
Run on mote:
- new internal/gui/tests/cache-hit-pct.test.cjs (Routing rows 99.6% /
100% / 99%, the route line, hitPct at its edges) in chromium and
webkit, en and zh: green; with the escalation line removed by hand,
red (99.99% where 99.6% is wanted).
- cache-hit-pct, panel-usage, context-window, i18n-keys, usage-ledger,
tray-totals, ctx-route, ledger-cache-hit, usage-hit-rate,
routing-request-metrics (both engines; ledger-cache-unknown and
ledger-cache-tokens in an earlier run): 186 pass, 6 red, all in
usage-ledger's 'newest live route needs no return-to-live button',
red the same on origin/main
|
||
|
|
e4197144a8 |
perf: every package's package-level regexps compile on first use
v0.1.3516 made gateway's and redact's patterns lazy. The other 299 package-level regexp.MustCompile calls, in 148 files across agent, provider, gui, library, codexcat, sessions, usage, plugin and the rest, now go through lazyre.New too, so a launch that never reaches them (`magpie statusline`, run by Claude Code on every message) doesn't compile them. Fields, maps and params that held them are *lazyre.RE. Measured on mote (M5 Pro), sandbox HOME, v0.1.3516-equivalent build (t42) against this one (t43): - GODEBUG=inittrace=1 sum: 7.39 MB / 69,837 allocs -> 4.62 MB / 46,765 - `magpie statusline`, 3 runs each: instructions retired ~212M -> ~176M, peak memory footprint 19.2-19.4 MB -> 16.8-17.0 MB Run: go vet ./... (darwin) ok; GOOS=windows go vet on each of the 30 changed packages ok; GOOS=linux go vet ok except ., internal/cli and internal/gui, which stop in wails v3's cgo files when cross-compiled (the same at main). New TestAllLazyPatternsCompile at the root compiles all 574 registered patterns (ok), so a bad pattern fails a test rather than a first use. Not run before push: the changed packages' own test suites; they run on mote after it. |
||
|
|
84a6d6a813 |
usage: Cursor calls made outside magpie are counted on the Usage page (WaiooT on X)
WaiooT asked for Cursor's usage to be counted. The quota card was there
already (the plugin's auth.usage); what was missing was the calls the
account made in Cursor's own editor and cursor-agent, which never pass
magpie's gateway.
The Cursor plugin (0.2.44, magpie-community/plugins f73ba656) gains
auth.calls: it reads Cursor's own usage list,
DashboardService/GetFilteredUsageEvents (the call cursor.com's Usage
page makes), keeps the signed-in user's events (owningUser = GetMe's
userId), and leaves out the conversations it sent itself for magpie.
magpie side:
- host.js: a provider says `calls` when its plugin has auth.calls; a
`calls` RPC normalises the reply (a call without an rid or time is
dropped, cost only when a number >= 0).
- plugin.AccountCalls / plugin.OutsideCall.
- usage.ReadOutsideCalls, run by the gateway a minute after the start
and every 10 minutes: each account's calls since its mark go in as
reported calls (IngestReported, request id "cursor:<usageEventId>", so
each is written once across restarts), by agent "cursor", provider
cursor, with Cursor's own cost. The first reading goes 30 days back,
but never before the gateway's last call to that provider, which older
plugin versions couldn't tell apart. A failed reading keeps its mark;
each later one starts 30 minutes back for events listed late.
Marks are kept in plugin-calls.json beside usage.jsonl.
- Cursor's mover min 0.2.43 -> 0.2.44 (npm view --prefer-online: 0.2.44).
- docs/subsystems/provider-plugins.md: "Calls an account made outside
magpie".
Run (mote, at this head):
- go vet for darwin, GOOS=linux -tags nogui and GOOS=windows on
internal/usage, internal/plugin, internal/gateway, internal/provider: ok.
- gofmt -l: clean.
- go test -count=1 -timeout 45m ./internal/usage ./internal/plugin
./internal/provider ./internal/gateway: all ok (usage 36s, plugin 129s, provider 152s,
gateway 937s), at 96d9b9ccd before the rebase onto origin/main (2
commits, none touching these files).
- Plugin: the cursor package's whole suite (410 pass) and
scripts/check.mjs on mote; a real-account auth.calls read returned 43
calls with models, tokens and cents.
Broken by hand:
- lastThrough's start removed: TestOutsideCallsStartAfterTheGateway red.
- RequestID left empty: TestOutsideCallsCounted red (rows written again
after a restart).
- host.js's rid/time filter removed: TestPluginOutsideCalls red ("4
calls, want 2").
- Plugin: owningUser and own-conversation filters removed: calls.test.mjs
red.
Not tried:
- A full magpie gateway with the plugin installed reading a real
account end to end (the plugin read was real; the magpie side ran
against the fake plugin and stand-ins).
- A team account (teamId), and the Cursor editor itself (none installed
here); the editor's and cursor-agent's calls are one list, both shown
as the Cursor agent.
- Two computers running magpie on one Cursor account each count the
other's gateway calls as made outside magpie.
- No GUI change: the rows use the reported-row path the Usage page has.
|
||
|
|
ca5e537ecb |
usage: traffic over time in Requests' chart, and how fast it flows now (songlairui on X)
songlairui on X asked for the gateway's bandwidth: many LLM calls, base64
images above all, weigh on the network. Each request's row already kept
its bytes up (UpBytes) and down (DownBytes), shown in its details and as
the period's "↑ · ↓" under the Requests card. What was missing was
bandwidth over time and right now.
- The Requests chart's metrics take Traffic: each hour's/day's bytes up and
down, stacked by model, provider or agent. Its axis is in bytes ("4 MB"),
its tooltip splits a column into "↑ up · ↓ down", and the ranking's
values are bytes with the same split under each. A period with none
says "No traffic counted in this period". A chart point's Part now
carries up_bytes/down_bytes, from rows (Part.add) and from the request
page's cells (Part.plus). The cells already kept Totals, so no cache
version bump is needed.
- While requests are in flight, the Requests card says how fast traffic
flows now: "↑ 1.0 MB/s · ↓ 40 KB/s", over the last ~3s, read from the
new GET /api/usage/traffic a second apart. That route reports the
gateway's running totals (Server.Traffic) and its requests in flight.
The totals are atomics added where a row's bytes are added (sentUp,
downCount.Read). So a stream counts as it arrives, nothing is buffered
or scanned, and the totals and rows count the same bytes once. Polling
runs only while Usage → Requests is shown and the window is visible.
The line goes when nothing is in flight and nothing flowed. When another
magpie serves the gateway, the route answers {} and the page shows no
rate.
A Codex turn on the Responses WebSocket (
|
||
|
|
68865032c3 |
usage: a gateway row keeps the address its request came from, on this computer only
geesehowardt7 on X asked to see a request's source IP. No usage row
kept it.
Record.ClientIP (json client_ip) is set in appendUsage from peerAddr:
the connection's own address, never a forwarding header (the gateway
trusts none), so behind a reverse proxy it is the proxy's. Loopback is
127.0.0.1/::1. Rows kept before this, reported calls and magpie's own
calls have none. rowText packs it, or the ledger cache gave it back
empty (the cache's file is keyed on this package's source, so it is
rebuilt once).
It stays here:
- sync's OwnDays blanks it, as it does Archive and Computer;
- GET /v1/magpie/usage/requests (other computers, Remote magpie, key
holders) takes it out for every caller (withoutClientIPs);
- the CSV export, OTel and middleware points name their own columns
and don't carry it; telemetry sends ids only.
The window's /api/usage/requests keeps it for the Usage page.
Run (mote, at base
|
||
|
|
7c1dc198d1 |
usage: a turn over the Responses WebSocket counts what the socket was sent, and says so
A Codex turn kept on a Responses WebSocket sends only the new items as a
delta, but the row's ↑ was the whole HTTP body magpie built before the
transport ran, so a long conversation read as ~13MB up per turn
(matrix0487 on Discord). overSocket now records what each socket write
carried (wroteSocket) and, when the turn went out on the socket alone,
replaces the HTTP figure with those bytes (sentOnSocket); a turn that fell
back to HTTP keeps the HTTP body and adds any socket write made before the
fallback. errCodexSocketAgain's retry on a new socket counts both writes.
The row remembers that it went over the socket: Record.Socket (json "ws"),
packed as Flags bit 16384 (rowSocket, added to TestRowFlagsApart). The
Requests table's protocol badge says "Responses · WS" and the details'
Protocol line "Responses · WebSocket".
Run on mote at this commit (rebased on origin/main
|
||
|
|
a8aeb2cad2 |
usage: picked days can start and end at a minute
blrbrzkj on Discord asked to see usage from one time to another, not only whole days. The range menu has a start and an end time under its month (empty is the whole day; 9:30, 0930 and 09:30 all read 09:30). Picked with the days, the period is "2026-10-01T09:30..2026-10-01T18:00"; Enter applies new times to the days already picked. A time that isn't one, or an end not after the start on one day, is marked and asks for nothing. The opt says "Oct 1 09:30 – 18:00". The backend reads either end as a date or a date with its minute (usage.RangeOf, bounds); an untimed end is its next midnight. A timed range of 48 hours or less is drawn by the hour from the first's hour. CSV names drop the colons. Run (mote): node --test usage-range-times (new, chromium + webkit, en + zh), usage-range, i18n-keys, credit-days: 26/26 ok. go test ./internal/usage ./internal/gui ok (TestCoreScriptBudget fits, the periodDays comment cut to pay for its regex); gofmt clean; go vet native, GOOS=windows (usage, gui), GOOS=linux (usage) ok. Broken by hand: a timed end read as its day's midnight turns TestPickedMinutesArePeriod red. The page's own typedTime first clashed with app.js's hhmm and stopped the Usage page mounting; the GUI run caught it. Not tried: the real app with a real ledger; ja/de/zh-TW screens. Reported-by: blrbrzkj (Discord) |
||
|
|
7e5cebb86c |
usage: a model list fetched again unchanged keeps the usage index
Each account's model list is fetched again on every start and every 45 minutes, and saveLive writes it again with only its "fetched" time moved. Usage keyed the request index (and its file on disk, requests-v1.bin) and the priced summaries on that file's mtime (statKey(catalog.LivePath)), so each such save dropped every chunk: every start, and every refresh while running, read the whole session history again, decoded every call shard and rebuilt every row. catalog.LiveKey names a saved list by a hash of its bytes without the fetch time, made once per parse of the file (readLive's memo). A list saved before Since was kept is dated by its fetch (LiveSince), so its fetch time stays in its key. usage's liveListKey uses it for every provider and Antigravity in readRequestState's meta and in usagePriceCacheKey (the same mtime key, the sibling), and falls back to the stat when the list can't be read. Found by dumping both disk headers on mote: same binary, same sources, and only the providers' hash differed, run to run. Measured on mote, a copy of the owner's real accounts, GUI open, network blocked, the Claude list rewritten as a start's fetch does. Restart of the same build, t10 (main) against t11 (this): CPU in the first ~3 minutes 11.6s -> 2.5s allocated 2.74GB -> 0.81GB sessions.loadCalls 771MB -> gone from the top footprint 174MB -> 175MB The first start after an upgrade that changes usage's code still builds everything once (requestDiskBinary), as before. Tests: TestRequestStateKeptAcrossAListFetchedAgain saves the same list again an hour later and needs readRequestState's meta and usagePriceCacheKey unchanged, and both changed for another list; on the old usage code it is red on both. TestLiveKeyOnlyMovesWithTheList and TestLiveKeyOfAnOldListKeepsItsFetch cover the key itself. Run on mote at this tree: go test ./internal/catalog ./internal/usage ./internal/provider -count=1 ok; go vet ./... ok; GOOS darwin/linux/ windows go vet ./internal/catalog ./internal/usage ok (./... cross-OS stops at wails' cgo files, as on main); gofmt clean. Not run: the full ./... suite before the push (running after), GUI. |
||
|
|
fc9ce34d86 |
usage: hashRows reuses its scratch, within sizes its rows exactly
Startup on a copy of the owner's real accounts (mote, GUI, network
blocked, acgui.sh) allocated ~3.5GB, and two usage functions were near
the top of it:
- hashRows built a fresh 32KB byte buffer and shape map for every chunk
it hashed: 510MB of the startup's allocations. It now takes them from
a sync.Pool and clears the map before use. The digest is the same
byte for byte (checked against the old code on the same chunks).
- rowChunk.within appended into a nil slice, growing it step by step
(292MB flat). It now counts the rows in range first, returns nil when
there are none, and makes the slice at that size.
Measured, same real-account copy, t9 (main) against t10 (this):
startup CPU 13.81s -> 9.77s
allocated (3m) 3483MB -> 2768MB (hashRows 510MB -> gone,
within 427MB -> 244MB cumulative)
footprint 179MB -> 175MB
Tests: TestHashRowsReusesItsScratch hashes a chunk again after a bigger
one and must get the same digest, and must allocate under 16KB a call
(min of 5 batches, so other goroutines' allocations don't count). Old
heat_disk.go: red at 32768 bytes a chunk; dropping clear(shapes): red.
TestWithinSizesItsRows needs len = cap = 600 (old code: cap 646).
Run on mote at this tree: go test ./internal/usage -count=1 ok, -race
ok, gofmt clean, go vet darwin/linux/windows ok, gui tests ok earlier.
An earlier usage run went red on a test whose name was lost (the log was
cut by tail); four full runs since are green, and the likely cause, the
first byte check counting other goroutines, is what the min-of-5 fixes.
|
||
|
|
3a5e4b62d0 |
usage: TestRowTokensAndZoneKept compares the zone by name and offset
The test compared got.Time.Location() with its own *time.Location by pointer. rowZones keeps the first zone it sees for a name and offset, so under -count=3 the second run got the first run's location back and the test went red on unchanged code. It now checks the zone's name and offset (IST, +5:30), which is what rowZones promises. Run on mote: go test ./internal/usage -count=1 ok; -run TestRowTokensAndZoneKept -count=3 ok (red on the old test). Broken by hand: writing the row with an "XST" zone turns it red. |
||
|
|
e3f1efdaac |
usage: a message id's pairing key is 16 bytes, not 24
msgKeysOf keeps each chunk's message ids as hashes, with the row, for every chunk a pairing reads. The key was two 64-bit hashes and an int32, padded to 24 bytes. It is now a 64-bit and a 32-bit hash with the row, 16 bytes: two of a long history's ~300k ids alike in all 96 bits is ~1e-18 likely. Run on mote at this head: - go test ./internal/usage: ok (28.8s) - GOOS=darwin/linux/windows go vet ./internal/usage: ok - gofmt -l: clean - Broken by hand: with the second hash back at 64 bits, TestMsgKeySize is red (24 bytes). - Real-account copy (~/r2278/acct), idle heap at 180s, v0.1.3404's tree vs this: appendMsgKeys 6.49 MB -> 3.69 MB, inuse 103.0 MB -> 97.8 MB, Footprint 154 MB. |
||
|
|
a06872dec8 |
caps: a wallet window's spend is counted, so a cap holds it (#5770)
A window that tells only what is left (QuotaWindow.Balance: AStudio 0.2.0's 通用积分 and 星火积分, SuperMagic's points) read 0% used until it was empty, so an account cap never tripped on it. 9won capped an AStudio account at 4 and it spent over 1,000 credits past it. magpie now counts what such a wallet spends (wallet_spend.go). Each plugin reading's balance is set against the one before: a fall is spent, a rise (top-up, daily grant) is not. The count runs over the window's own period when it tells a reset, else the local day: a wallet never renews, and a cap reached for good would switch the account off with no time it comes back; the ask was "N a day". Spend before a period's first reading, or across a gap between periods, is unknown and not counted; spentSince says when counting began. The counts are kept in wallet-spend.json beside providers.json, so a restart doesn't lose them. Every wallet window carries spent and spentSince. On an account with a usage cap (WindowCaps.Holds) it also reads as amount spent of limit (spent plus what is left), and used that share. A cap by share then holds it in routing (allowanceOf takes the fields as they are) and on the GUI row (capHeldOf reads used). So does 40cbdaa7e's amount cap, which skipped a window with no total: 9won's "at most 300 a day" on a wallet now holds (magpie provider account-cap ... --window 通用积分 --amount 300). An uncapped wallet is unchanged: balance alone, routed by Allowance.Left. A cap just set is judged from the next reading. holdsBounds leaves wallets out: there is no whole to reckon "holds" from. Tests, each red on the old code (broken by hand where they compile): - TestPluginWalletCapHolds: real plugin host, fake plugin, wallet 10,000 -> 9,500 on an account capped at 4. Used 5, CapHeld set, the uncapped account untouched. Red with the plugin_usage.go hook removed (Used 0, Spent nil). - TestWalletSpendCounted: falls counted, top-ups not, a restart reads the count back, the next local day and a told reset start over (UTC+8 fixed zone), failed and share readings left alone. - TestWalletCapHolds: account cap 4, the window's own cap 4, and an amount cap of 700 (not held at 650 spent, held at 750). - TestWindowHoldsLeavesAWalletOut: red without the holdsBounds change (a wallet reckoned a 500-token whole). Run on mote at this tree on |
||
|
|
f8525323dd |
providers: a key with no balance URL takes a balance typed by hand, counted down by magpie's own usage
Some API-key providers tell no balance magpie can read (no Balance URL, no relay query found), so their keys showed none. Now the user types what the vendor's page says is left, on the key's row in the provider editor (Set balance) or with `magpie provider key-balance <id> [key [usd|off]]`. The key's card shows that less what magpie's usage priced the calls it sent on the key since it was typed (usage.KeySpent, the spend caps' count), marked as an estimate: "≈$12.50", the pill "≈$12.50 left", its title saying what was typed, when, and what was counted since. Typing it again counts from then; No balance takes it off. A balance the vendor tells always wins: a provider with a Balance URL, a plan source, Cline's or OpenCode Zen's card takes none typed, and a relay whose query is found shows its own; when the probe finds none (errNoBalance) the typed one is shown. A typed balance stays saved as the user left it: the editor's save keeps it, a key's replaced value carries it. An estimate is never kept in the balance history and tells routing nothing (the routing allowances cache is left alone). keybalance.js is loaded by keyspend.js (itself loaded when the editor draws a key) for a provider that takes one, so app.js and the core's script budget are unchanged. Words in zh, zh-TW, ja and de. Run at this tree (mote): - go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... at base 46b10af87; at this tree go vet of gui, provider, cli and usage; - go test -tags nogui -count=1 ./internal/gui ./internal/provider ./internal/cli ./internal/usage: provider and usage ok; gui and cli red only on #5644 below; TestCoreScriptBudget ok (1,533,747, as main) - the provider tests under -race -count=3; - GUI: key-own-balance (new: Chromium and WebKit, en zh zh-TW ja de, 900 and 400px, 20/20), key-spend-cap, old-webkit, i18n-keys, gui-de, gui-ja, gui-zh-tw, balance-found, key-balance-card, i18n-en-no-cjk: 104 pass, 1 fail, i18n-keys "a plugin's words are its own", red the same on origin/main |
||
|
|
d4712e1312 |
usage: a probe's chunk among the settled days no longer drops the heatmap's disk cache
heatSettledKey gave up whenever a settled chunk had no serial. A probe's
chunk (MCP and search calls) is made again for each query, so it never
has one. When a user had no tool call in the last two days, that chunk
fell among the settled days, the settled count was never kept on disk,
and every Usage refresh paired and counted every day again.
The loop below already names such a chunk by its rows (hashRows), the
same rows give the same key, and pairSerials already allows one unnamed
chunk. So the early return goes; the doc comment says what false means
now.
Ran (mote, at this head):
- TestHeatSettledKeyNamesAProbeChunk: green; red with the early return
put back ("a probe's chunk left the settled days unnamed").
- go test -count=1 ./internal/usage ok; go vet for darwin, linux and
windows ok; gofmt clean.
Not tried: timing a real Usage page with no recent tool calls.
Reported-by: gua2100 (Discord #feedback)
|
||
|
|
8373aaf14a |
usage: a settled session file touched keeps its settled days
The Requests page and the heatmap keep the days before the last two
counted (page-v1/heat-v1), under a key of the settled chunks. A session
file's chunk was keyed by its size and mtime, so a file touched without
a new call made a new key, and every poll of every period and filter
paired the whole history again (pageCold/heatCold). Agents do touch old
files: on this Mac a 15 min stat watch of ~/.claude/projects saw
settled files (last call 11-03/11-04) get their mtime moved exactly
+3600 s with the same size, and others get queue-operation, hook and
file-history lines that are no call. The key also hashed the chunks in
mtime order, so a touched file moved in it.
A session chunk is now keyed by its path and a digest of its rows
(hashRows, memoized per chunk serial, which names the file as read),
and each set is hashed in path order; a pairing breaks its ties by path
(timedRef.newer). A real change of rows still makes a new key
(TestPageSettledFromDisk). The key format changed, so the first start
after the upgrade counts the settled days once.
Measured on mote (M5 Pro), a sandbox HOME of 3000 Claude Code and 2000
Codex sessions (1.1 GB) and 300k gateway rows, the harness polling
requests+heatmap for today/7d/30d/all three times each, a line that is
no call appended to an old Claude Code file before each poll:
before: heatmap 0.86-1.62 s every poll, requests all 1.34-1.43 s,
30d 0.33-0.44 s
after: heatmap 0.13-0.42 s, requests all 0.15-0.44 s, 30d 0.07-0.69 s
(the first poll of a period counts its recent days)
first process, no caches: 17.4 s -> 10.8 s for the 14 calls; warm
274 -> 278 ms. Sessions polls were 0.07-0.2 s in both.
Run on mote: go test ./internal/usage ./internal/sessions
./internal/usageapi ./internal/gui (ok); gofmt -l; go vet, GOOS=linux
-tags nogui and GOOS=windows go vet of ./internal/usage.
Broken by hand: TestSettledFileTouchedPairsRecentOnly is red on the old
heat_disk.go (paired 6 of 6); with the digest but not the path order it
is red too.
Not tried: GrayRabbit's own history (no sizes from them yet, #5618);
Windows or Linux timing; the GUI, which is unchanged.
Reported-by: GrayRabbit (Discord)
|
||
|
|
8de63c8b5a |
gateway, usage, gui, otlp: a request its agent canceled is no failure (#2398)
An agent that cancels its request before it is answered is logged 499 "the agent canceled the request": a person stops the reply, or sends the next message while it is coming and Claude Desktop cancels it and asks again, or Codex takes a subagent's report (#2398). The gateway already says nobody failed (no rest, no reroute: TestCanceledRequestRestsNobody), but Record.Failed is a status >= 400 or an error, so every page counted it as a failure: the Requests card's "N failed" and success share, its Failed filter, the CSV's error column, the Routing page's "errors your agent saw", the Context page's error rate, the failed colour in the Requests list, Routing and Recent calls, and the OTLP export's error status. A Claude Desktop session on 2026-10-27 had four, each a message sent mid-reply; #2398 had 91 of a day's 92 failures. usage.CanceledBy tells the agent's cancel (499 with AgentCanceled) from magpie's own limit on a request it asked of itself, logged 499 too and still a failure (#2318). The cancel is logged with an error type of its own, agent_canceled (usage.CanceledErrType, set in failedWith), so the record says what it was and nothing guesses it from a 499, as #2398 asked. Record.Canceled reads the type, and a record logged before it by its status and message, so the old log reads the same with nothing migrated. A middleware's usage rows carry the type, so a module can tell the cancel from magpie's own limit, which its rows (no error text) couldn't. Record.Failed leaves the cancel out; Totals counts it apart (Canceled, in count and plus); RetriedRequest and the first-token and speed sums ask Answered, so a canceled request is timed nowhere, as before; Codex's memory of the last model still skips it. Routes and Recent calls say canceled (set as a route is done and as a day's history is read, so old days read the same); the Routing totals and the Context page's errors leave it out. Ledger rows say canceled, and the pages show it muted, in neither the failed nor the answered colour: the Requests list and its detail ("499 · canceled"), the Requests card ("N canceled", the success share of the requests not canceled), the overview tile, the Routing page (a "gone" outcome, no speed) and Recent calls (muted). New strings are in zh, zh-TW, ja and de. The OTLP export: the records the gateway gives its observers for a request and its try carry the type too (canceledAs), and a root span's error.type follows Record.Failed, so a canceled request's span and its try's go with status code 499, no error and no error.type. TestOTelWaterfallFailureAndCancellation's canceled case held two failed spans (the try the vendor refused as the agent left is recorded canceled, as the request is); it now holds neither failed, both 499 and no error.type. That change to the test is the point of this one. mdwsk88's patch (aea0027fd) ran its tests at |
||
|
|
2f660ca86b |
sessions, usage: Antigravity's gemini-4-argon-d is gemini-4-argon, not a second unpriced model
oioio's Antigravity database names gemini-4-argon's generator
"gemini-4-argon-d". agAppModel took only "-n" off a gemini-* id (Google's
gemini-3.8-flash-n,
|
||
|
|
640825b09a |
usage: the Requests card's traffic line reads whole, and a row says how many images went by file
matrix0487 on Discord:
- The Requests card's line "↑ 13 GB · ↓ 13 MB · 图片文件省下 44…" was cut
with an ellipsis. It was one nowrap span.
- A row's details say "图片文件省下 10 MB" and should say "10 MB(3 张)".
The card line is now made of whole parts (usageParts, the pattern the
token line has since #2378). A card too narrow for all three puts the
saving on a line of its own. A part that is wider than the card by
itself (German at 420 wide) wraps inside itself; it is never cut.
The count:
- withDeepSeekFiles counts the image blocks it puts a file id in place
of, on each try, and upBytes keeps the most of any one try (a retry
sends the same images again, as the saved bytes are counted).
- It goes into usage.Record as `image_files` (omitempty) beside
image_files_saved.
- packedRow keeps Tries and ImageFiles in int16 each (clamped to
MaxInt16), so the row stays 152 bytes. request_snapshot carries the
new field, and heat_disk hashes Tries as before.
- The detail row says "{size} ({n} image|images)": zh "10 MB(3 张)",
zh-TW 張, ja 枚, de "Bild/Bilder", en "image/images".
- A row from before the count was kept has no image_files and shows
the size alone, with no parentheses. The card's period total gets no
count.
Run on mote, at this tree:
- gofmt -l (clean), go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./..., go build ./...: ok.
- go test -run 'TestRowImageFilesKept|TestRowBytesKept|TestRowsOfOneSession|
TestDeepSeek|Snapshot|Heat' ./internal/usage ./internal/gateway: ok.
- TestRowImageFilesKept: the count survives pack/unpack beside Tries,
100000 clamps to 32767, an old row reads 0, the JSON has
"image_files":3 and leaves out 0, and packedRow is 152 bytes.
- TestDeepSeekImageFilesCountedInRow: two images in one message and
one again in a later message make 3 in the stored row, twice, and a
request with no image makes 0.
- GUI, BROWSER=chromium and webkit: usage-ledger-bytes runs every
language at 1180 and 420. The 3-image and 1-image rows read in each
language's unit, singular in en and de, and the old row stays bare.
The reporter's period (13 GB, 13 MB, 44 MB) at 1180, 760 and 420 has
every part whole and inside its card.
- The 79 usage-*/led* GUI files (concurrency 2): 641 of 659 pass in
chromium and 637 of 654 in webkit. Every red is filed and red on
origin/main
|
||
|
|
783537e810 |
sessions: the Antigravity app's own conversations count on Usage and Sessions (#2190)
xxooioo (Discord) asked for the Antigravity desktop app's calls made
without magpie's gateway on Usage and Sessions. The app keeps each
conversation as a SQLite database, ~/.gemini/antigravity/conversations/
<id>.db (WAL). Messages are encrypted, but steps.metadata is plain
protobuf: 1 the step's start, 9 the call's usage (2 input, 3 output,
4 cache write, 5 cache read, 11 response id), 20.3 the gen_metadata idx
of its generator, whose message names the model (field 19, else 21/22).
The reader opens the database read only, in one read transaction; a
response id seen twice is one call at its last step. Each conversation is
a read-only session under agent "antigravity", gated by Reads like every
other agent and added to Found. A call the app sent through magpie is
matched to the gateway's record by tokens and time the way agy's steps
are (agyLocal now covers "antigravity"), so it is counted once.
"gemini-3.8-flash-n", the model the rows name, is counted as
gemini-3.8-flash (
|
||
|
|
baf70992f6 |
usage: a call the vendor answered with another model is priced as the model that served it (#5340)
The ledger priced a call at the model asked for and fell back to the
model the reply named (Served) only when the asked-for one had no price
(#1498). That order is right for a relay that sells kimi-k3 as
moonshot-kimi-k3 and bills by the name it sold, but it also priced a
real substitution: claude-opus-5-5 asked, claude-opus-5 served. The
vendor bills for the model that ran. kaimo455's ledger had 836 such
rows, every one at the asked-for rate: $374.06 reported against
$493.28 at the served model's rate. gateway-key cost limits (KeySpent,
NewCoster) and budgets read the same pricer.
Pricer now prices a call the ledger marks swapped at the served model's
price. That covers a price the user set for the served model and every
other layer of BasePriceIn. A price the user set for the model asked for
still wins, 0 included (new provider.UserBasePriceIn is BasePriceIn's
user layer alone). When the served model has no price, the asked-for
one's stands. Renames, vendor aliases, serving names and region
deployments price as before, and rate windows still read each record's
own time. apiPricer, the API price behind a subscription window's whole,
follows the same rule: the served model's API price first, then the
asked-for one's.
Review changes on top of ggbdpq's patch:
- The swap is judged the way the ledger's Swapped column judges it: on
the model id and on the name that went out (SentNameIn over the
user's ModelWires). A model the user sends under the served one's name
was answered as asked, so it keeps its own price. The patch judged the
model id alone, so such a row was priced as swapped while the Requests
page said it wasn't. The pricers' memo keys now include the effort,
because the sent name depends on it.
- apiPricer (window holds) got the same rule. The patch left it on the
old order.
Tests:
- TestLedgerPricesASwappedCallAsTheModelThatServed (patch, plus a
ModelWires case) checks the ledger and the Requests page.
- TestLedgerPricesARenamedModelAsTheOneServed: the sol row (sol asked,
kimi-k3 served, both priced) is a genuine swap, so it now prices at 3,
not 2.
- TestHoldsPriceTheModelTheReplyNamed: claude-opus-4-7 answered by
gpt-5.5 is priced at gpt-5.5's API price. Answered by an unpriced name,
it keeps opus's.
Run on mote at this tree, on origin/main
|
||
|
|
8b70b7d976 |
usage: a request's bytes up and down, and what DeepSeek's image files saved, in Requests
Suggested by @faithleysath (matrix0487 on Discord): the usage ledger now keeps what each request received back (down_bytes) beside what it sent up (up_bytes, #4456), and what DeepSeek's image files (#5407) kept out of the upload (image_files_saved). Shown in Usage → Requests: - a row's details: "Sent upstream", "Received" and "Saved by image files", each only when it is above 0. A row from before has none of them, not 0; - under the Requests card, the period's "↑ up · ↓ down", with "{n} saved by image files" when there is a saving. Its title gives the exact bytes. A period with no counted bytes shows no line. What is counted: - Down bytes are counted as the reply body is read, after Go's transport has undone gzip, so a gzipped reply counts its plain size, not wire bytes. A plugin's row counts the local hop to the plugin host. A 101 body is not wrapped. Every try counts, so a refused try plus the answering one add up (TestLedgerKeepsDownBytes). - Image files saved, per try: the body before the swap minus the body sent, minus the upload bytes this request itself paid (len(b64)/4*3). It can be negative on the turn that uploads; the GUI shows only a saving above 0. Gaps: an upload that finishes after the wait timeout or ctx-done is not subtracted (as with up_bytes); a joined upload flight is paid by the request that started it; multipart overhead is approximate. - packedRow grows by three int32 (152 bytes, still within the test's bound), clamped to the int32 range. Totals sum all three. - settledCountVersion goes 1 → 2, because Totals now count bytes. The settled page, heat and effort caches recount once, on the first start after the update. The heat key hash includes the new fields. Run on mote at |
||
|
|
2df5d40ee3 |
usage: a ChatGPT API account's calls count in the same ChatGPT account's Codex window estimate (jctaoo on Discord)
A ChatGPT account signed in through Sign in with ChatGPT (chatgpt-api) and to Codex draws on one plan's five hours and week. Only the Codex card reads those windows, and its whole-window estimate (usage.windowHolds) keyed the ledger's calls by provider + account, so the chatgpt-api calls were never counted and the estimate came out low. provider.SamePlanAccounts maps each chatgpt-api account to the Codex account that is the same ChatGPT account, matched on the tokens' chatgpt_account_id and chatgpt_user_id, both known and both equal, never on a name: two Team seats of one email share the name and the user id, not the account id. A token that names neither matches nothing, as before. windowHolds (current and HistoricalWindowHolds) counts a matched account's calls as the Codex account's, dry runs included. chatgpt-api alone (no Codex account) is unchanged: its card reads no windows, so there is nothing to estimate. Routing's caps and pace go by the vendor's own reading of the windows and don't sum the ledger, so they are unchanged; the per-provider account breakdown in the summary stays per provider on purpose. Run (mote, at this tree): - go test ./internal/usage/ ./internal/provider/: ok. ./internal/gui/: TestMainWindowCorners/macOS_26_SDK red, the AppKit test filed as #3949 (macOS 27 on mote), untouched by this change; the rest ok. - go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of internal/usage and internal/provider: ok. gofmt -l: nothing. - quota-holds.test.cjs in Chromium and WebKit: 2/2 each (the GUI only renders the server's holds; no asset changed). Broken by hand: - remap removed in windowHolds: TestWindowHoldsCountsTheSameChatGPTAccount- ThroughTheAPI red, "whole 5 hours 2500 tokens, want 10000" and "the personal account holds 2500 tokens, want 10000". - account id ignored (user id only) in SamePlanAccounts: red, "the Team seat holds 12500 tokens, want 5000" and "whole 5 hours 10000 tokens, want 2500" (token naming no account). Not tried: a real chatgpt-api sign-in. No such account on this machine, so whether OpenAI's Sign in with ChatGPT tokens carry chatgpt_account_id and chatgpt_user_id (Codex's do, checked on the real Codex logins here) is not verified; if they don't, nothing is matched and the estimate stays as before. GUI suite in other languages not run (no strings changed). |
||
|
|
7b5e773873 |
provider: a model at a window (claude-opus-5-5@300k) is priced as its model, so Cursor's sized ids have a cost
RyuJeXu on X (tweet 2117971061103100279), building an iOS board on magpie's
usage data: "cursor的用量好像不计费呀". Cursor calls showed no cost.
Cause: the Cursor plugin lists each model once per context size
(claude-opus-5-5@300k, @1m, gpt-5.5@272k, ...), lists them all at cost 0
(no price, pluginPrice), and its reply echoes the asked id, so usage rows
carry the sized id. pricedNames only took a window off grok- ids, so every
other sized id fell through the maker catalogs with no price. The plain ids
(claude-opus-5-5) were priced at the maker's list price all along.
Fix: pricedNames also tries the id with an "@<digits>k|m" window taken off
(modelWindow), for every provider. The window names the context size, not
a different model; long-context tiers still follow the call's own prompt
tokens through Price.At. Dated ids (claude-opus-4-5@20251101) and ids with
anything else after the @ are left alone. The regexp runs only for an id
with an @, since every listed model is priced on each Providers poll.
Tests:
- internal/provider/cursor_price_test.go: a moved Cursor provider prices
@300k, @1m, upper case, a maker-prefixed id and gpt-5.5@272k/@1m as the
plain model, through ListPrice, MakerPrice, PricedName(For), and its
tier at 300K prompt tokens; a dated id, "@272", "@", "@272kb", an
unknown model and auto stay as they were.
- internal/usage/cursor_window_cost_test.go: a Cursor row for
claude-opus-5-5@300k costs what the plain id does ($6 each), auto stays
unpriced, the page total is $12.
- grok_price_test.go: gpt-6-astra@500k under grok is now priced ($10/$50);
grok-4.7-build@500k still isn't.
Run (all through mote-run, go1.26.8, base
|
||
|
|
69167bc299 |
usage: a reply let go under a second after a wait four times longer tells no speed
pluviophile714 on Discord: a gpt-6.1-sol row on Routing read 1,539 tok/s (input 21,617, output 392, first token 8.2 s, total 8.3 s), where another monitor measures ~70. The reply came whole about 255 ms after an 8.2 s wait. Its content was spread over that short window (flow 230 ms), so the HeldShare flow check passed, and so did the 100 ms floor, and 392/0.255 s read as 1,539 tok/s. New rule, usage.HeldWindowMs: a window under 1,000 ms whose start (first token, first text or first reasoning) is more than HeldShare (4) times the window tells no speed. One rule in every place that computes one: - usage.DecodeOf: the Usage page's speed and totals, the CLI, the GUI's model speeds, and the gateway's Speed first pacing (noteTrySpeed); - routing/client.js decodeOf: the Routing row's speed and its story line; - usage/page.js ledDecode, plus a ledNoSpeed_ reason for the dash's tooltip, in en, zh, zh-TW, ja and de. docs/reference.md and docs/subsystems/gateway-sessions.md say so. On the owner's usage.jsonl (read only), 103 of the 106 rows over 600 tok/s were such windows (e.g. 448 tokens in 107 ms after 8.1 s) and are dropped. The 3 that stay have windows of 2 to 5 s. The overall speed goes from 103.8 to 97.9 tok/s. What it costs: a short reply that really streamed after a long wait tells no speed either. The live visible-reasoning fixture (76 tokens over 731 ms after 6.8 s, ~104 tok/s) and #2637's grok record (307 tokens 403 ms after a 4.6 s first token, 531 tok/s) now read "—". Their tests keep their guarantees with the same timings after a short wait, and also check the long-wait case. Tests: - New: internal/usage TestShortWindowAfterLongWaitTellsNoSpeed (the reporter's numbers, a reasoned row from the ledger, the boundary, a second after a long wait, Totals) and internal/gateway TestShortWindowAfterLongWaitNotesNoPace. - GUI: usage-speed-every-row has the reporter's row (dash, and the tooltip in all five languages); routing-burst-speed has it (first token 8.2 s, no tok/s). - Updated to the new rule: TestVisibleReasoningSpeed's decode-minimum and max-speed cases (short wait now), TestCodexTurnMeasured...'s gateway/Claude rows, TestLiveVisibleReasoningFixture and TestUsageIngestTellsSpeed. Run on mote at this tree (rebased on |
||
|
|
e41ef6288c |
providers: a spend cap on an API key, per day, month or in all (sparkling_lemur_62868)
sparkling_lemur_62868 on Discord: a team's OpenAI key holds granted credits that other docker services spend from too, and they want magpie to stop at a share of it. Their workaround was two magpies behind a gateway-key limit. What changed - provider: KeySpendCaps on a provider, keyed by the key's fingerprint (key_spend.go): USD over a local calendar day, a local calendar month, or in all since it was set. Since is kept while the cap stays one in all. SetKeySpendCap and ParseSpendCap refuse an amount outside 0 < usd <= 1,000,000 and an unknown period, and leave the saved cap as it was. Subscriptions are refused, since an account has its own usage-window cap. - usage: KeySpent(keyID, start) is what magpie's own calls on the key cost at the Usage page's prices. Turned-away calls and app-reported ones are left out. It reads usage.jsonl once per key and start, keeps the sum for 5 minutes, and Append counts each new call into it (spentNew). A read that a write races is read again. - gateway: perKeyEvery bars a key at its cap (spendHeld) as a usage cap holds an account. The next key serves, then the fallbacks. With none, the reply is 429 "spend cap reached: ..." naming each key, what it spent of which cap, and how to go on. Retry-After is when the soonest period renews; a cap in all gives none. A spend hold is not a usage cap: Stop at the caps and strictKeep don't end at it (capHeldOnly). The trace's barred row carries the cap, the spend and the period. - GUI: a pill on each key's row in the provider editor, for example "$7.50 of $20.00 today". It opens the app's menu (No spend cap, Per day..., Per month..., In all...) and then takes the amount in place, as the lane-limit pill does. A key at its cap gets a line under its row: "At its spend cap · back in ...". Every string is in all five languages. The pill and the line are in keyspend.js, which app.js imports when it draws a key's row, so the core's script budget is not raised. /api/providers' keyList carries spend, and POST provider/keyspendcap sets it. - CLI: magpie provider spend-cap <id> [key [usd [day|month|total]|off]] lists each key's spend and sets or removes a cap. - docs: providers-accounts.md and gateway-routing.md. Caveats, also in the tooltips: - What counts is magpie's priced usage, not OpenAI's bill. - A model with no known price counts $0. - Requests already under way when the cap is reached still finish, so a key can go a little past it. Run on mote at the pre-rebase head ( |
||
|
|
dcc84dbc04 |
usage: the Overview says each account's credits, and the period's (lcyksp)
lcyksp (Discord #feedback) asked to see the WorkBuddy credits (积分) the
calls spent, per account too, not only tokens. The summary already summed
each reply's usage.credit into every group's Totals, and the Requests
page's ranking showed it, but the Overview's Accounts, Models and Agents
rows and its tiles never said it. Each row's line now says "{n} credits"
when a reply said any, and the calls tile says the period's sum. No tile
is added, so the four-tile grid is as it was; the text was translated
already.
Run on mote:
- go test ./internal/usage ./internal/usageapi: ok. TestPlanCreditsByAccount
(new) checks each account's sum in the summary and the Requests page;
with Totals.count not adding credits it is red (summary a@x: 0 of 0).
- GUI, every usage*, i18n*, ledger and credits file (both engines):
1322 pass, 31 fail. plan-credits' new Overview test (5 languages, 420px)
is red with page.js as before ("WorkBuddy · 70 calls"). The reds are
usage-agents-hide (#2276, #3414), usage-fold "most on one screen"
(#4790) and usage-ledger's return-to-live (#3104, #4078, #4626). Run
alone at
|