Commit Graph
341 Commits
Author SHA1 Message Date
yetone c2fd48782b Put back what 1f05c311d took out of main by mistake
1f05c311d was committed with its worktree's older tree on top of a
fresh origin/main (git reset --soft), so beside the memory fix it
undid every file 610ae1f54..c1312ac15 changed (45 files: key balance,
import links, project subagents, uninstall, site, LESSONS.md and
more). This commit restores each of them to c1312ac15 byte for byte;
the tree is now c1312ac15 plus the memory fix alone
(git diff --stat c1312ac15 HEAD: the 4 files of the fix).
2026-11-13 12:18:23 +08:00
yetone 1f05c311d9 library: an open memory holds still while the Memory tab polls (Nietzsche_Li on X)
"资源库-记忆中,被展开的记忆的表单会定时抖动". While search by meaning
still has memories to read (read < of, which can last up to a minute
between memembed.Keep's reads) or a learn-from-conversations run goes,
the Memory tab reads its row again every 2s, and each read drew the
whole page anew. The open editor was a new .lib-detail each time and
played its content-in entrance (opacity .5, 2px slide) every 2s.

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

TestPrefetchEachMakeIsAReadersOwn counts four readers' makes now.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Not tried / not changed:
- No real Cursor call; the owner's ledger copy has only auto rows.
- Cursor's own auto and composer-2.5, and its own spellings (glm-5p3,
  deepseek-v41-flash-1017) and gemini-3.1-pro have no catalog price and
  stay unpriced; the plugin would have to give them a cost.
- Not ./... and no GUI suite: the change is in provider's price lookup
  only.
2026-11-04 22:45:40 +08:00