f2eb56c6bbde1300dddc402861b59cd4e45e0215
83
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
6d154ef1e1 |
context: scripts (curl, Bun, python-httpx…) are one Scripts card, not an agent each
A request whose User-Agent names only an HTTP library or an SDK (curl, Bun, node-fetch, undici, python-httpx, requests, aiohttp, Go-http-client, okhttp, the OpenAI/Anthropic SDKs, …) or nothing at all got a Context scorecard of its own, as if it were an agent (theforeveriris on X: "Bun", "curl", "python-httpx" cards). usage.IsLibrary names those clients; contextOfRecs folds them and "other" into one "Scripts" card at read time, so older history reads the same way, and the card's meta line and tooltip list the libraries by count. The cached day records are not changed. No setting: it works as is. The Usage page's Agents list still shows each library by name, with its Hide and Count-as-agent controls. i18n for zh, zh-TW, ja, de. Existing context.js comments were condensed so TestCoreScriptBudget holds without a raise (core scripts -28 bytes). Run, at this head (rebased on |
||
|
|
643b525469 |
usage: a DeepSeek call at peak hours costs double its off-peak list price
treeMan on Discord: DeepSeek bills off-peak at half the peak rate, and the Usage page didn't follow it. The catalog's list prices for these models are already the off-peak ones: models.dev's DeepSeek, Command Code and OpenCode Go entries give the off-peak rate as the price and a factor-2 multiplier for peak hours, and api.json leaves the multiplier out (deepseek-flash: $0.15/$0.60/$0.003, DeepSeek's page says $0.30/$1.20/ $0.006 at peak). So every peak call was counted at half its cost. Now a call made from 01:00 to 04:00 or 06:00 to 10:00 UTC, Monday to Friday, costs twice the list price. The call's own timestamp decides. Which providers (provider.PeakOf, by base URL, or by preset/id only for a provider with no URL, such as a plugin's or a removed one): - DeepSeek's API (api.deepseek.com), every model, except on Chinese public holidays (catalog.PeakDeepSeek); - Command Code (api.commandcode.ai, the commandcode preset and the commandcode-plan plugin): deepseek-v4.1-flash, -v4.1-flash-fast, -v4-flash, -v4-flash-vision-exp and -v4-pro, every weekday, since its docs name no holiday. deepseek-v4-flash-fast is one price at every hour; - OpenCode Go (opencode.ai/zen/go): deepseek-v4.1-flash and deepseek-v4-pro, every weekday. Unchanged: OpenCode Zen (a flat $0.30/$1.20), ZenMux, Cline Pass, OrcaRouter and every other relay, a price the user set (ModelPrices returns before a Peak is set), a "same as" price and every other model. The provider's price rate still applies. Holidays: catalog.cnHolidays has 2026 from the State Council's notice (2025-11-04). TestCNHolidaysCoverThisYear fails on 2027-01-01 unless that year's notice, due in November, is added. A year missing from the table counts no holidays. Where the hour is applied (catalog.Price.In): Record.CostAt (Usage's totals and groups), the packed gateway blocks (priceBlock), OTLP's exported cost and budget's estimate (now). The Sessions page sums per model without per-call times and stays at the list price. The model editor's price box says when a list price counts double (four languages; app.js kept under its budget by shortening, not by a raise). Run at the tree pushed (parent |
||
|
|
442897f414 |
gateway: masking time is kept when magpie's own time is unknown
A masked request's "Masking" part on the Routing page comes from
Route.Masking, which maskingMs capped at Own, magpie's own time before
the request went out. Own is known only when magpie's client wrote the
request and a first token came back, so a request that was masked but
went through a plugin, through Claude Code for a Claude subscription,
failed, or had no first token had its masking time dropped to 0, and
the page showed nothing for it (Discord, lute: some requests show the
masking and model time and some don't). The Codex backend path never
set it at all.
maskingMs now keeps all of the masking time when Own is unknown, and
still caps it at Own when Own is known. The Codex backend path sets it
on its route and its usage record. The usage page still shows Masking
only beside a known Own, as before.
Run (mote, go1.26.8):
- TestMaskingTimeKeptWhenOwnIsUnknown (a masked request the vendor
refuses): red on the old redact_phase.go ("masking 0 ms, held
120ms"), green with it.
- TestCodexOwnSignInKeepsItsMaskingTime: red without the codex
backend lines ("route's masking 0 ms, held 120ms"), green with them.
- TestMaskingIsAPhaseWithItsTime, TestNoMaskingNoMaskingTime: ok.
- go test ./internal/gateway ./internal/usage -count=1 -timeout 45m with
this and the next commit: ok (gateway 502s, usage 16s).
- go vet ./internal/gateway ./internal/usage for darwin, linux
(-tags nogui), windows: ok. gofmt -l: clean.
|
||
|
|
2be04305fd |
usage: a session's model lists count only the log's blocks since the last
The whole log's model lists (cachedVias) were counted again from every call in the log whenever it grew, which with calls coming in is every poll: buildVias was ~3% of CPU on the #2278 bench. They are now counted on from what the log's full blocks counted, which never change, and only the blocks after are counted again. A session's counts are copied from the prefix before they are added to, so the prefix is never written. Rows are counted in the log's order either way. The prefix is kept for the same clients and renames key as the lists, and is dropped when the log is read afresh (its blocks differ). Window lists (a since) are built as before. TestViasCountedOnAreCountedAfresh DeepEquals the lists counted on with buildVias afresh, after appends over a block's edge, a new session and model, and the log written over, and checks that lists were counted on. Broken by hand (a prefix session's list cut in half): red at "first". Run at the next commit's tree (this one plus the gateway projection's fold, in other files): go test ./internal/usage/... ./internal/usageapi/... ./internal/tui/... ok; ./internal/gui/ red only on TestMainWindowCorners (#3949); GOOS=linux,windows,darwin go vet -tags nogui ./internal/usage/... ./internal/gui/ ok. Bench numbers are in the next commit. Refs #2278 |
||
|
|
28c89afcef |
usage: a period's summary counts only the log's blocks since the last
Each call the gateway logged changed the log's version, and every
/api/usage ask for Week or Month counted the whole period again: on
the #2278 bench (a busy gateway, 4 calls a second, the GUI's polls every
5 s) topSummary was 11% of CPU, beside GC at ~30%.
A period's summary now keeps what it counted over the log's full blocks
(512 rows each, never written again once full) and counts only the
blocks since, then the last block. It counts afresh when anything a
count depends on changed: a block it counted was replaced, a rewrite,
prices or names (meta), cleared calls, the period's bounds or series, or
the keying (hosts, accounts, keyed providers) changed. In the last case
an account that newly answers for a provider splits that provider's
earlier calls too. Rows are counted in the same order as before, so
every float comes out bit-identical. The group maps are copy-on-write
over the kept prefix, and only what was touched is copied.
Run at this tree, 213a31b4d before this message (the parent is origin/main
|
||
|
|
012c584cc1 |
usage: clear a model's usage, or all of it, from the Usage page
CrazyMouse_TT on X asked for a way to clear usage, all of it or one model's, to measure a local model fresh after deploying it. The Usage page's Models list has a "…" on each row (and a right-click menu) with "Clear usage…", and "Clear all usage…" sits under the lists below the "Counted from…" note. Each asks first, in a confirmation that says what is deleted, that it can't be undone, and that key spending limits and allowances still count the calls. A clear is a mark in settings (usageCleared: provider, model, unix ms), read at read time; usage.jsonl is never rewritten. The Overview hides calls up to the mark in summarizeFrom; the Requests page, heatmap and ledger/CSV hide them in Filter.keepsRow, their one choke point, and the request index's meta carries the marks so its cache is dropped. Key budgets, window holds and Codex reads go through usage.Visit and the raw log, so a clear never resets a key's spending limit or a quota. A later clear of the same model or of everything takes the place of an earlier one. The marks ride the settings part of a sync (sync-backup.md) and a save of the Settings page keeps them (api.go's keep list; the guard test TestSettingsSaveKeepsWhatItDoesNotSend caught it missing). gateway-sessions.md and sync-backup.md say so. Run on mote (mote-run) at this tree, rebased on origin/main |
||
|
|
396e0e4638 |
usage: a deleted provider's requests merged into another, or named, from the Requests filter
CyberCaius on Discord: a deleted provider's requests sat under its old id
("<date> 已删除"), and the only way to put them under a provider they
have was renaming that provider onto the old id. Now, with a deleted
provider picked in Usage › Requests' Provider filter, a "…" beside it
offers Merge into… (an app menu of the providers there are now) and
Rename… (the filter's button turns into a name field; Enter or leaving
it saves, Escape keeps it). With the merged-into provider picked, the
same "…" lists Separate <name> for each, the undo.
Nothing in the log is rewritten. Both live on the deletion's own record
in providers.json (Deleted.Into/MergedAt, Deleted.Label), so a provider
added later under the old id inherits neither: it is a different
provider, and its record of its own is what it has. Renaming the target
carries the merge (Rename rewrites Into); deleting the target ends it.
Renames.Both(id, time) gives the id a call is shown under and the one it
was made to (Own). Listing, filtering, the summary and vias go by the
shown id; pricing (Record.priceID, block_price's as), window holds and
the gateway's loggedAnswers go by the own one, so a merge moves no cost
or token, only whose name they sit under. The target's face lists what
was merged into it (Named.Merged). Routes: GET /api/usage/deleted/into,
POST /api/usage/deleted {id, into?, name?}; a field not sent stays.
Run (mote, at this tree on
|
||
|
|
28f3c4d7fd |
codex: the Codex app's first 100 models hold the ones used, hidden ones last
@ZhenLuoTTAWDTT on X: with Codex on magpie the model list stops short, and the models past it can't be chosen. Cause, from the clients' own code: the Codex app (ChatGPT.app 26.1013.40934, app-initial-90eb42395b7d.js) and the VS Code extension (openai.chatgpt 26.51021.22027, model-queries-667cf4bd657d.js) both ask their app-server for model/list with includeHidden, cursor null and limit 100 (e?.limit??100) and never ask for nextCursor. codex-rs's list_models pages the list sorted by priority, hidden entries counted, so anything past the 100th is in no picker there. The CLI's /model (tui model_popups.rs) lists every preset in a scrolling popup and has no cap. magpie truncated nothing; its models are numbered after the account's own, so a user with many models lost everything past ~100 in the app, while hidden entries (codex-auto-review and the like) took slots at the top. Fix: codexcat.Fit ranks the list last of all, on every route magpie hands Codex a list (/backend-api/codex/models after the user's own order, /v1/codex/models before its 1 MiB cut, and the model_catalog_json file via CatalogUsed): hidden entries go after every listed one, and with more than 100 listed, the models Codex used in the last 30 days (usage.CodexUsed, most recent first, at most 100; on /v1/codex/models only the asking key's, CodexUsedBy) are brought into the first 100 in the order they stood. The rest keep their order. The list's ETag and X-Models-Etag carry a tag of the used set (codexcat.UsedTag), so Codex asks again when it uses a model it hadn't; CodexUsed is read at most once a minute, or at once when Append writes a Codex call to a model it doesn't hold. Documented in docs/subsystems/gateway-routing.md. Tests (each red on the old code, broken by hand: Fit a no-op, the gateway calls and the used tag removed, Append's codexUsedNew removed): TestFitKeepsUsedModelsWhereTheCodexAppReads, TestFitLeavesAShortListsOrder, TestCatalogUsedFits, TestUsedTagIsTheSet (codexcat), TestCodexUsed (usage), TestCodexModelListKeepsUsedModelsInTheAppsHundred and TestCodexCatalogKeepsTheKeysUsedModelsFirst (gateway). Real run: codex-cli 0.162.1's app-server in a sandbox CODEX_HOME (never ~/.codex) with a model_catalog_json of 3 hidden entries at priority 1-3 and 150 listed models, driven over stdio with the app's own request (model/list includeHidden, limit 100). Before: page 1 held 100 of 153, 3 of them hidden, the last many/model-096, nextCursor "100". The same catalog put through Fit with many/model-140 used: page 1 has no hidden entry and ends with many/model-140. The TUI's /model scrolled to all 150 (tmux). Run with this change on |
||
|
|
8fba65d0bc |
gateway: what masking took a request is kept, and shown as Masking in its time
fremontdango on Discord asked, after the request that sat as "routing…" while it was masked, how long masking took. Now each request keeps it. noteRedacting adds up the time from the first masking at once to the last's end (redaction.spent); maskingMs gives it in ms, at least 1 when there was any, never more than Own, magpie's own time before the request went out (splitSent), since masking happens inside it. It goes on the route (Route.Masking, /api/gateway/trace) and in the usage record (Record.Masking, masking_ms; packedRow's int32 fits in its padding, so TestRowsOfOneSessionShareAShape's 216 bytes are unchanged, and the process-private snapshot carries it). It is a duration, no text. The Routing page shows it as magpie's "Masking" part, first in where the first try's time went (timeParts, renderSteps); the Usage page's detail splits it out of "In magpie" (page.js). Both use the core "Masking" string every language already has (脱敏, 脫敏, マスク, Maskierung). Why masking can be slow, measured on this machine (go1.27, M-series): the rules are linear, ~0.25 ms/KB. redact.MaskJSON over a Claude Code shaped body: 283 KB 35 ms (secrets) / 63 ms (+ personal data); 511 KB 70 / 122 ms; a dense 402 KB with 7,821 hits 173 ms with personal data, 144 ms with the user's words too. Through the gateway (redactedHits, secrets + personal, 402 KB dense) 145 ms the first time, 123 ms again; noteMasked ~2.6 ms. Doubling the body doubles the time; nothing quadratic or repeated per hit. So a request held "routing…" for 15 s or more (unroutedShow) while masked is the local model (Settings → Privacy → Find with a local model, internal/pii): it reads each text it hasn't seen (a new turn's tool results are the misses), one model turn at a time, so requests queue behind each other (#3682: 480 KB took 90 s on an RX 470/580). No change to masking's speed here; the phase and the time now say which it was. Run at this head, on origin/main |
||
|
|
39526c0690 |
usage: Append keeps the log open between calls, not an open and a close for each request (#3725)
Every request the gateway serves appends a line to usage.jsonl, and Append opened and closed the file each time. In a CPU profile of the request path (BenchmarkZZIO, a local benchmark not committed) Append was 0.51s of the handler's 1.36s, 0.35s of it in os.OpenFile and 0.07s in Close. Now the handle is held, under the same mu. Before each write the held file's identity is checked against what Path names now (fstat and stat, os.SameFile), so a log another program moves, removes or replaces, or a Path that changes with HOME, is opened again. A failed write drops the handle. Windows still closes after each write, since a file held open there can't be removed or renamed. Measured (local microbenchmark, open+fstat+write+fstat+close against a held file with stat+fstat+write+fstat, 600-byte lines, 20000 runs, load ~80): 55 to 116µs per call before, 11 to 24µs held. On the whole request (BenchmarkZZIO) the difference is inside the noise at this load, so no request-time figure is claimed. TestAppendHeldLogFollowsThePath appends twice and checks the second call used the same handle (and that Windows holds none), then replaces the log by rename, removes it, and moves HOME, checking each time that the next call is counted in the file Path names. Broken by hand (identity check skipped) it is red: after a replacement the call went to the old file and Summarize counted 0 calls. Windows box (test binary run outside the source tree): internal/usage, mine and origin/main |
||
|
|
e1709ab42e |
usage: Append makes the log's folder only when it is missing (#3725)
Every request appends one line to usage.jsonl, and Append ran os.MkdirAll on the folder first each time: a stat, and on its error path a walk up the tree. Now the file is opened first, and the folder is made (then the open tried again) only when that open says it doesn't exist. Measured with a scratch benchmark (not committed) at |
||
|
|
42976f9a08 |
usage: a renamed provider is shown once, by the id it has now
cybercaius on Discord (#help, 10-25): "已经更改供应商 id 的也没有变更过来反而
分开显示了". Reproduced in a sandbox HOME (magpie web on 3582, fake upstream
on 3583): after renaming myrelay to newrelay in the editor, the Requests
page's provider list had both myrelay and newrelay, each named "myrelay",
because the model-list probe row was still under myrelay. The summary was
already folded; the probe chunk, the Sessions tab's vias and the gateway's
loggedAnswers (lead-first routing) were not renamed at all.
What changed
- provider.Renames (UsageRenames): Of(id, time) is the id a call recorded
under id at that time belongs to now. Every usage reader goes through it:
summarizeFrom (and its historical-key set), ledgerMatched, NewPricer,
NewCoster, the Requests page's gateway blocks, probe rows and other
computers' days, window holds and their history, buildVias, and
gateway loggedAnswers. Visit stays as recorded so Of is taken once.
The summary, Requests and vias caches key on Renames.Key.
- An id reused by another provider no longer pulls the new one's calls
into the old one. Rename onto, or Save of a new provider under, an id in
another's Was moves it into that one's Gave with the time (giveID):
calls before then stay the old provider's. freeID treats Was ids as
taken, so adding the vendor again gets "-2". Renamed() (refs) skips ids
a provider or subscription holds now.
- A providers.json that can't be read keeps the last renames read instead
of none (a failed read is unknown), so usage doesn't split meanwhile.
- History: nothing in usage.jsonl is rewritten. Calls from before this
release under a renamed id show under the new id at once. An id that was
reused before this release has no hand-over time, so its calls show under
whoever holds the id now, as before.
Siblings checked: budget keys by caller key; per-key limits, RPM and
concurrency count live requests by the current id; tray totals go through
QueryPage; codex_memory reads Requested refs. None needed a change.
Run at the tree before the rebase; rebased onto
|
||
|
|
ffe493773c |
usage: magpie's own Test, Detect APIs and model list requests are rows of the request log, counted nowhere
neiko and gys619 on Discord: a provider's Test or Detect APIs left no
trace in Usage > Requests, so a failing test couldn't be read back.
The provider package marks the context of the editor's Test, Detect APIs
(and per-model detection) and a model list's refresh with a kind
(internal/probelog). Each request sent under the mark is written once:
by the provider's Do, or by probelog.Transport under http.DefaultClient
(netproxy.Install), whichever sends it first; the Claude Code run and
the gateway's translated test write theirs from their result. A row
keeps time, provider, account, model, host, path (no query, no
user:password), method, status, ms and the first 500 bytes of the error.
The row is usage.SourceProbe, agent "magpie", Kind provider_test /
api_detect / model_list ("Test", "Detect APIs", "Model list" in Called
for; purposes.js regenerated). The log index keeps probes apart
(logSnapshot.probes), so Visit, Load, Summarize, budgets, Vias, heatmap,
shared days, LastSeen and observers never meet one. The request page
lists them (probeChunk) and counts none: Row.IsProbe, since a packed row
keeps the row's Source and not its record's. The page shows a muted
badge "magpie's own · not counted in any total" (en, zh, zh-TW, ja, de);
no new control, no layout change.
Tests, each red on the old code:
- usage TestProbeRowsListedNotCounted: listed, clipped, and absent from
Sum, Through, every By group, Summarize, Load, LastSeen, OwnDays and
the observer; a provider filter lists it and sums 0.
- provider TestTestWritesItsRequestsDown / TestDetectWritesItsRequestsDown:
every request the fake server saw is exactly one row, with the right
kind, model and 401 text; an unmarked Do writes nothing.
- probelog TestNoteKeepsNoSecret, TestTransportOnce.
- GUI usage-ledger-probe: badge per language, both engines, 1180/420,
light and dark, no left border, no sideways scroll.
- gui TestProviderDetectDraft now expects the log line (source probe,
kind api_detect, no key) and leaves usage.jsonl out of the unchanged
config comparison.
Broken by hand, each went red: request_page's uncounted check,
log_index's probe skip, Append's observer skip, Do's Taken (6 rows for
4 requests), Test's and Detect's marks, probelog's query strip,
page.js's badge (11 GUI fails).
Run at this head (on origin/main
|
||
|
|
3a47e377e0 |
usage: a call whose vendor counts no cache is left out of every hit rate (#3464)
#3464 (zeewell on X): Kiro caches on its side, but its replies give only credits and a context share, never cache tokens. Every hit rate outside the Routing page read those calls' CacheRead of 0 as a miss. A Kiro-heavy day showed "hit rate 6%" when the counted calls hit 90%. The plugin already says so (opencode-kiro-auth 0.1.16 sends usage.magpie_cache_unknown), and the gateway already kept it as RouteUsage.CacheUnknown for Routing. This carries it the rest of the way: - gateway: Usage.cacheNotCounted() (the vendor said so and no try reported a cache token) goes into usage.Record.CacheUnknown on every path that records a call: the gateway's own record, the OTel attempt path in observe.go, and trace's routeUsage. - usage: Record.CacheUnknown is kept as ledger row flag 8192 (rowCacheUnknown; grepped, no other flag uses that bit). Totals sums such calls' prompt into cache_unknown and counts them in cache_unknown_calls. Totals.HitRate leaves that prompt out of its denominator, and gives no rate when nothing is left. - Old records: calls kept before the plugin said so carry no flag. A Kiro call (provider kiro or kiro-plugin) with no cache counted is read as uncounted (usage.CountsNoCache): in the ledger's row read, in Totals, and for Routing's history in internal/gui/trace.go (cacheCounted). The rule is scoped to Kiro's two ids, so another vendor's 0 stays a miss (tested). - GUI: cacheHitOf in app.js drives the tray panel's card, the Usage page's agent rows and cache tile, the requests' Cache hit rate card and each ranking row. When only uncounted calls are left it shows "—" or nothing instead of 0%. Otherwise it says "{n} requests left out: their vendor doesn't count the cache". A request row's cache cells show "—", and its details say the vendor doesn't count the cache. The Context page (context.go, context.js) shows no cache for such a call and doesn't score it as a miss. - No budget raised. This adds 625 bytes to app.js (1,320,224 to 1,320,849, under its 1,321,336); |
||
|
|
ea9454d2d8 |
usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)
A vendor names one model two ways (deepseek-v4.1-flash and deepseek-flash),
and Usage, Usage > Sessions and `magpie usage` showed two rows. Now:
magpie model alias deepseek-v4.1-flash deepseek-flash
magpie model alias deepseek-v4.1-flash (what it is counted as)
magpie model alias deepseek-v4.1-flash --reset
magpie model aliases
kept as settings.json "usageAliases" {from: to}. Off until one is written.
Ids match as routing groups match them (provider.sameModel: vendor/ prefix,
case, "_", snapshot date), at every provider; a chain is followed to its
end; an alias to itself, a loop, or a flag as an id is refused. A loop
written into the file by hand counts each model under its own id.
Display only: requests, agents' model lists, /v1/models, routing groups,
Same as and prices never read it. Each call is priced by the id it was
made under and only then counted under the alias; the alias's own price
is never put on the other id's calls, and a merged row is priced only
when every id in it is. Applied in usage summarize/direct (Models
groups), the gateway sessions projection (alias read before
gatewayCache's lock; the cache key hashes usageAliases), and
sessions.List/Get/Find/Stats (read before storeMu/mu, merged into new
slices so the memo is untouched; ModelEffort rows merged too). A failed
settings.json read keeps the last aliases read, and SetUsageAlias refuses
to write over an unreadable file (EditUsageAliases under fileMu). The GUI
settings save carries usageAliases. No GUI control.
Not aliased: the Requests ledger's per-request model and its model
filter, which show each call's own id.
Run (worktree at
|
||
|
|
2fcd4b33c4 |
usage: one Vias index answers every since, instead of a rebuild from the whole log whenever the since changes (#2776)
Vias kept the lists for one since. The Sessions list asks from its
oldest listed session's start, each agent's manage page from that
agent's oldest, and a session's detail from that session's start, so
an open page's polls almost never asked the kept since, and each ask
read and grouped the whole log again. Idle with an open Sessions page
on the 720k-call sandbox, buildVias allocated 9.1 GB in 8 minutes,
78% of everything allocated, which is most of why the idle process
churned its heap and grew.
The cache now keeps one index from the whole log and each session's
first call. A session whose calls all came at or after the since is
answered from it. A session with calls before its since is answered
from one kept window for that since, built only when such a session
is read. Len counts the sessions with a call since the index's time.
Both are kept per log version and agent list, as before.
TestViasAnswerEverySinceFromOneIndex writes 20,001 sessions and asks
from three sinces in turn, as the three pages do: 2,677 bytes an ask.
On the old cache: red, 11,580,100 bytes an ask. It also checks that a
session with a call on each side of a since counts only the one after
it, and what Len says for a window and for every session.
TestGatewaySessionsCachePricesWindowsAndRewrite's window check and
TestUsageViasSkipsOldHistory stay green.
720k-call sandbox, idle with an open page's polls every 15 s (the
Sessions list, stats, Claude's manage page, Requests, state), before
and after side by side for 12 minutes, load ~170-250. Allocated from
minute 4 to minute 12: buildVias 9,100 MB before, 0 after (built once,
before minute 4). The faster answers let the poll loop run about twice
as often, so the totals (11.6 GB and 10.5 GB) aren't per poll. The
live heap ran 352-641 MB before and 514-724 MB after, and RSS 730-962
and 555-1217 MB; both swing with where a poll is when the snapshot is
taken and the machine's load, and neither shows a trend in 12 minutes.
Run: go test -p 4 -count=1 ./internal/usage/ -run
'Vias|KeptStrings|GatewaySessionsCachePrices|Incremental|Review': ok.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
6359b2c27c |
usage: Vias hands every caller the one copy it keeps, and a session's list is copied only when read (#2776)
Vias cloned every session's list for each ask, from a cache built for
exactly this. The Sessions list, the manage pages and a session's
detail each asked, and read the lists of the sessions they show, or of
one. Over ~720k calls one ask was ~66 MB.
Vias now answers a ViaIndex over the kept map. Of(key) is a session's
list as a copy of its own, so a caller still can't change the kept
one; Len is how many sessions have one. The three GUI callers and the
tests read through Of.
TestViasHandOutTheKeptCopy writes 20,000 sessions and asks 20 times,
reading one list each: 2,590 bytes an ask. With the clone of every
list put back by hand (under ViaIndex): red, 3,817,492 bytes an ask.
It also changes a list read through Of and checks the next ask still
says 1 call.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
db61143fe7 |
usage: the Sessions and Routing caches copy out the strings they keep, so they no longer pin every decoded block
An unpacked block's strings are cut from one allocation (unpackInto). The gateway-sessions projection (gatewayCache) and the vias cache kept a session id, model, agent, provider or effort from nearly every block, and each such substring held the block's whole decoded text: request and response ids and errors included. keptStrings clones each kept value once and interns it, so a cache holds only what it uses. TestSessionCachesHoldNoDecodedBlocks writes 16 blocks x 512 rows with a 1 KB error each, reads GatewaySessions and Vias, drops the snapshot and compares the live heap with and without the caches. Without the fix (both call sites reverted) it is red: "the caches hold 16651 KB for 16 sessions: the decoded text of their blocks (8192 KB)". With it, green -count=3. Measured (macOS, sandbox HOME seeded with 600k gateway calls, the fixed build vs |
||
|
|
7170b5d8bd |
usage: the plan credits a reply says it cost are summed by model, agent and session (#2512)
wwcraft_ on Discord asked for the WorkBuddy credits spent on the Usage page, by model, agent and session. WorkBuddy's chat stream ends with usage.credit, the per-request figure its own app shows as "Credits Consumed". The built-in and the moved plugin both hand that chunk to the gateway's chat decoder (the plugin's renamed()/kept() pass usage on as it came), so cUsage reads `credit` into Usage.Credits and the three record sites keep it on the row. A reply that says nothing has no credits, not 0. - usage: Record.Credits; Totals/Via sum Credits and count Credited; the packed row keeps it under its own flag bit (4096, in TestRowFlagsApart); the ledger CSV gains a trailing "credits" column. - GUI: the Usage ranking's line says "0.7 credits" (积分, 積分, クレジット, Credits) beside the cost, its title how many requests said it; the Sessions page's Routed line says it per route. TUI usage page and `magpie usage` tables say it muted on the same line. No new layout. Real replies on workbuddy-ai, 10-16: gemini-3.5-flash "credit":0.01; deepseek-v4.1-flash, minimax-m3, kimi-k2.6 "credit":0; glm-5.3-flash refused (14003). The tests use those bytes. Run (at b07b518e7 on origin/main |
||
|
|
9916a94608 |
gateway, usage, plugins: OTel export is the first plugin on the gateway's observer point (P3)
P3 of docs/subsystems/plugin-runtime.md opens the gateway to plugins. The
observer point is first: it only reads, so it carries the least risk.
With plugins/otel off, the gateway exports nothing and does no observing
work. It keeps no reply whole and adds no request context.
- usage.Observer:
- Methods: Serve, Bodies, Begin(Request) Watch and Ledger(Record). Watch
has Attempt and End.
- Observe(o) registers an observer until its remove is called.
- ServeObservers is counted, and only Server.ListenAndServe calls it.
- ObservedBodies takes the most any observer wants.
- Record.SkipOTel becomes Watched, set by appendUsage for a request an
observer watched.
- The gateway's otel.go becomes observe.go:
- observeRequest asks each observer through Begin.
- attempt and end call each Watch. Bodies are added only when an
observer asks for them, and the whole reply only for WholeBodies.
- internal/otlp: the exporter (otel*.go) moves out of internal/usage, and
the gateway's per-request span state moves into request.go. otlp.New()
is an Exporter, a usage.Observer. What it sends is unchanged.
- plugins/otel:
- Apply registers otlp.New() and disposes of it when turned off.
- InUse is 1 while settings.OTelExport says to send. A user who exports
only through MAGPIE_OTEL_* keeps the plugin on under Essentials.
- pluginrt.KeepFresh: the process serving the gateway refreshes every 2s
when plugins.yml or settings.json changes. A switch made in the window or
the CLI reaches a running gateway, or a headless serve, without a restart.
- docs: plugin-runtime.md gets a P3 section, a gateway runtime path and an
updated failure section; reference.md says the export is the otel plugin.
Run at this tree on origin/main
|
||
|
|
3c4b4dc973 |
sessions, usage: a Codex subagent with no title takes its parent's spawn_agent task_name, its nickname shows apart, and Usage requests say which calls were compactions (#1591, Hogeexxl)
Hogeexxl's change (his fork branch codex/codex-session-details, f7c176c9),
cherry-picked with his authorship:
- A Codex child thread whose title is still empty after the existing
precedence takes the task_name of the parent's spawn_agent call, linked by
the call id and the SubAgentActivity "started" item that names the child's
agent_thread_id. Conflicting links leave the title empty.
- session_meta.agent_nickname is exposed as `nickname` on the list, one,
manage and overview responses, beside the title, not in place of it.
- GET /api/usage/requests and /v1/magpie/usage/requests carry `compaction`
(true/false) for Codex calls with native evidence, and leave it out
otherwise. A gateway row matched by a unique response_id takes the marker
and keeps its own model, usage, cost and kind.
- Flags bits 1024 (rowCompactionKnown) and 2048 (rowCompaction) are new.
TestRowFlagsApart covers them, and they don't overlap 1..512. The sessions
cache goes to version 21 and the calls cache to calls-v15.
Review:
- Rollout format checked against Codex's source (openai/codex 669449b):
- v2 spawn_agent args carry task_name.
- A paginated rollout persists item_completed with a SubAgentActivity
item: kind "started", id = the call id, agent_thread_id.
- SessionMeta has a top-level agent_nickname, which Codex's own list.rs
and metadata.rs read too.
- compaction_response_id lives in token_usage_record.
Gaps in legacy rollouts and in calls without a response_id are fixed in
the next two commits.
- Privacy: only a title string the user's own Codex wrote and a boolean
are added to local API responses. Nothing new goes to a vendor or to
telemetry. The ingest POST parses fields one by one, so it is unchanged.
- No .github, dependency or network changes.
What was run:
- His tests pass: go test -tags nogui ./internal/sessions ./internal/usage,
and the two new internal/gui API tests.
- Broken by hand, each caught by his tests:
- the nickname read removed;
- the conflict checks removed;
- mergeCodexCompactions broken;
- the gateway pair's setCodexCompaction removed;
- the flag read forced to true.
- Not caught:
- the parent check on the title link (covered by a test in the next
commit);
- `copy.codexCompactions = nil` in cloneCodexChunks removed. That line is
defensive only: the shared chunks never hold the map.
- The gofmt, vet and full-suite record for the three commits is in the
last one.
|
||
|
|
eb7199e120 |
gui: Routing is a plugin's page, its script, style and words in plugins/routing (P2)
P2 of docs/subsystems/plugin-runtime.md, the third page after Sessions and Library. - routing.js and routing.css move to assets/plugins/routing/ (client.js, routing.css). Its part's html is the page's head and boxes that were index.html's <main id="view-routing">; the rest is drawn by routingPage, run at mount since it builds on app.js. It keeps itself after that as it did (its own hidden, the language, focus), so its hooks are dirty and discard, a routing group being edited, which show() and the window's close ask through magpie.call: window.routingDirty and discardRouting are gone. - plugins/routing: Essential, Requires window and gateway, in use while the user has a routing group (not Auto, not Hidden), since the page is where it is edited. The gateway routes the same with it off. - With it off, what leads to the page goes too: the nav and panel tabs and the panel's section (data-feature="routing"), the guide's Open Routing, Providers' "Make a routing group of …", the Usage list's View routing and its time as a link, the context card's Latest request. A panel left on its Routing tab shows Agents. - What other pages use of it stays on window: openRoute (context.js), kindName, swapWhy, routedWhy (Usage's Requests), newGroupWith (Providers), panelRoutingShown (the panel). - The 505 strings only Routing says move from i18n.js to plugins/routing/i18n.js (4 languages); i18n.js 17048 → 15032 lines. The plugin's own name and line stay in i18n.js: the Plugins page says them with the plugin off (TestBuiltinsTranslated). - Tests and comments that named routing.js name the new path (gateway's antigravity_rest and loop_guard, codeassist.go, usage.go, web_compress, group_member_info, assets_revalidate, font-cascade, win-fonts, three routing-*.test.cjs). builtins.test.cjs and builtins_test.go count seven built-ins and switch Routing off: its tabs go, the page shown stays. - docs: plugin-runtime.md, gui-shell.md, gateway-routing.md. Run, first on origin/main |
||
|
|
60f896031e |
usage: a client the user counts as an agent is counted as it on Usage and Sessions (#1958, NorethSea)
NorethSea's bridge (hermes-codex-thread-bridge) starts Codex's
app-server under a User-Agent of its own, so its calls were a row
apart from Codex on Usage, and its threads weren't Codex's in Sessions.
Rather than learn one bridge's name, the user says which agent a client
counts as.
- settings: clientAgents, client name (lowercased) -> agent id.
ClientAgentsNow reads just that field through filememo, so a pass over
the ledger costs a stat.
- usage: ReportedAs(ua) is AgentOf, then the user's mapping. It is used
for what is reported only: the summary, the agents list and filters,
request rows and pages, priced blocks, direct, Vias and gateway
sessions. The gateway's routing, keys and caps still go by AgentOf,
the client's own name. The mapping is read once per ledger pass
(readLogSnapshot) and is part of the keys of the summary price cache,
the vias cache and the request page cache, so a change redraws the
history already counted. A request row keeps the client's own name in
a new "client" field, shown as "Client" in its details.
- gui: POST /api/usage/arrange takes {count:{client,as}}. It refuses a
client magpie already knows as an agent, "other" or magpie's own, and
an "as" that isn't a known agent or is magpie. as "" counts it on its
own again. /api/settings keeps the mapping it doesn't send. On the
Usage page an unknown client's "…" offers "Count as an agent…" (a
picker of the known agents), the agent's row says "with <client>",
and the agent's "…" offers "Count <client> on its own". Strings are
in all 5 languages.
Run:
- go test -count=1 ./internal/usage ./internal/settings ./internal/gui: ok.
- TestClientCountedAsAgent goes red with reportedAs broken, and with the
mapping left out of the vias key or the request page key. With the
summary key alone left out it stays green, because the settings stat
already moves it.
- TestUsageArrangeCountClient and TestSettingsSaveKeepsWhatItDoesNotSend
(ClientAgents added) pass.
- Playwright usage-count-client.test.cjs (new) and usage-agents-hide
(its menu now has two items for an unknown client) pass in Chromium
and WebKit, in all 5 languages, at 1100 and 420: 54/54. With
countable() forced false, the new test goes red.
- gofmt -l is clean. go vet is clean for darwin, linux -tags nogui and
windows.
Not tried: a real hermes bridge (the records' UA is from the issue), and
the Client line in a request's details has no GUI test.
|
||
|
|
30869e35a7 |
usage, gateway: each request's log row says the service tier asked, the one each try was sent at, and the one the vendor said it ran at (#1784, zhenghaowen0967)
What changed
- usage.Record has tier_asked, tier_sent and tier_served, and the CSV gets
them as its last three columns.
- tier_asked is the client body's service_tier (Claude's speed fast reads
"fast").
- tier_sent is the tier the try's last request actually went out at. It
is noted in forwardOnce after every rewrite (a fast pick's priority,
Ultrafast turned to priority on a plan without it, buildResponses
dropping a tier the host can't take) onto the per-attempt wireAt. So a
handed-on try's own row has its own tier.
- tier_served is only what the reply said: service_tier at the top level,
in response.service_tier, or in an Anthropic usage. It is read by the
relay sniffer and by both translated readers, and is empty when the
reply says nothing. It is never filled in from the ask.
- Codex's own relayed sign-in (codex_backend) records the same three.
- /v1/magpie/route: Route.tier (asked), and each Try has tier and
tierServed. The session route has asked_tier, tier, tier_served and each
try's tier and tier_served.
- docs/reference.md (CSV columns) and gateway-routing.md describe them.
Why
zhenghaowen0967 asked that a request whose Ultrafast was sent as priority
to an account without it show that in usage, per try, without calling
the served tier confirmed unless the reply says so.
What was run
- TestTierRecordedPerTry. With Pro out, the first try is recorded
ultrafast, the second priority, and the final record has asked=ultrafast,
sent=priority and served empty while the fake doesn't echo. With an
echoing fake, served is what it said ("ultrafast", and "default" when
none was asked). It also checks the CSV columns, and the Codex relay path
with priority.
- TestUpstreamTierShapes covers the Chat chunk, Responses
response.completed, a Responses body, an Anthropic message_start and
message_delta usage, null, an over-long tier and non-JSON, as well as
bodyTier per protocol.
- Broke it by hand:
- with forwardOnce's noteWireTier removed, TestTierRecordedPerTry goes
red (route tries' tier empty, TierSent empty);
- with the sniffer's Tier line removed, TestUpstreamTierShapes goes red,
and so does the Codex relay case of TestTierRecordedPerTry.
- go test -tags nogui ./internal/gateway ./internal/usage ./internal/cli;
ledger_test's CSV expectations gain the three empty columns.
- gofmt -l; go vet on darwin; GOOS=linux and GOOS=windows go vet -tags
nogui.
Not done
- The served-tier fixtures are built from the shapes OpenAI and Anthropic
document, not from saved replies. Whether chatgpt.com's Codex backend
echoes service_tier wasn't tried against a real account.
- Bridges that don't go through forwardOnce (the Claude subscription,
Cursor's built-in) leave tier_sent empty.
- There is no price multiplier for priority/ultrafast and no GUI column.
|
||
|
|
dfbe001ff9 |
usage, gui: re-land def3a41e3, a Codex one-call turn timed only over a second and 100 tokens after its first token
|
||
|
|
2d3b33bb78 |
usage: time tool-only replies only with visible reasoning evidence
Revises #1463 after the hidden-reasoning inflation review. Keep answers separate, retain evidence in routes and cached ledger rows, and exclude sealed or summary-only reasoning even without a token breakdown. Sync the backend and both GUI formulas. Checked real WorkBuddy DeepSeek, Codex and Claude bridge responses in an isolated HOME; sanitized timings and failures are in docs/verification. Chromium/WebKit speed regressions pass (20 tests, five languages). New edge regressions and loop-order check pass under race repetition. Restoring the old formula or removing the hidden guard fails TestVisibleReasoningSpeed. macOS/Linux/Windows vet/build pass. Full-suite verification is recorded in the issue at this head; inherited proxy/Bun 1.3.14 failures are retained, with clean Bun 1.4.2 rerun in progress. No installed app replacement. Rebased onto main by yetone (#1463). Conflicts with main's Own/Retried/ Queued/Tries row fields, HandedOn and the Codex speed floors were resolved by keeping both. The packed row's ReasoningHidden bit was 64, which main has since given to block_price.go's swapKnown, and main's rowHandedOn took 128, filling the uint8: Flags is now uint16 and ReasoningHidden is bit 512 (rowReasoningHidden; #1874's rowOwnCost took 256), read back in row(). The docs/verification notes and their sample JSON are left out of the tree; they stay on the contributor's branch and the issue. Run after the rebase: go test -tags nogui ./internal/usage/ and the gateway's reasoning/speed/TTFT tests, ok. |
||
|
|
d4c2512d2d |
usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)
What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
one record or an array, in usage.jsonl's shape:
- the post may carry up to 5000 records and 32 MiB;
- t, agent, provider, model and rid are required.
Each field is checked: unknown fields, quoted numbers, negative or absurd
counts, a status outside 100-599, a cost over 10000 USD, and a t more
than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
whole post with a 400 that names error.index and error.param, and nothing
is written. A past t is otherwise taken as given, so history can be
backfilled. The reply gives accepted and skipped counts and each
record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
shared, behind the Host check). A browser page also needs a key, since
corsGuard lets localhost pages and Origin null through. A held key is
refused.
- usage.IngestReported writes under usage.mu to the same file as
usage.Append. Rows carry source "reported" and no caller key. A rid
already reported is skipped, as is one repeated in the post. The set of
reported rids is read back from the log: one scan after a restart (lines
without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
flag; packed flags widened to uint16). Otherwise it is priced at
magpie's prices.
- Display:
- SourceReported is a source of its own: RequestPage.Reported,
?via=reported, and Ledger now honours via.
- The Requests tab gains a fourth cell "reported by apps", shown once
there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
- a key's budget/spend limit (budget.counts);
- window holds, and the log start that decides whether a window can be
reckoned (logSnapshot.firstOwn);
- gateway sessions and Vias;
- Codex's sealed answers and remembered model.
There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
site integrate.html (en, zh).
Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.
Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
- usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
languages, 1180 and 420 wide, light and dark);
- usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
- 40 posts of 5000 took 0.40 s (worst batch 18 ms);
- the first post after a restart took 0.45 s (rid rescan), a later one
1.6 ms;
- the cold index build took 2.1 s (as for gateway rows);
- page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
- summary all took 215 ms, 30d 20 ms.
Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
cost; the block pricer overwriting own cost; the Reported split;
fromBrowser's key rule; skipping bad records instead of refusing; the
max-records and body limits; the ingest lock (race); both locks;
firstOwn -> first; the IsReported guards in windowHolds,
buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.
Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.
|
||
|
|
5ca9dc19db |
usage, gui: a model says how many of its replies were ended for looping (#1858)
#1858 asked for recovery across turns when a model loops. magpie is a gateway and can't rewind the agent's session, so that is not planned now. What it can do is let the reader see which model loops. Each reply the loop guard ends (#1359) is logged with err_type "reply_loop", but Usage only counted it among the failures. usage.LoopErrType is now that type (the gateway's loopErrType is it), and Totals.Loops counts, among the failed requests, those ended for looping. A handed-on try is still no request. The Overview's model, agent, account and key rows and the Requests ranking say "{n} looped" beside "{n} failed", and the ranking's "Other" adds them up. Translated into zh, zh-TW, ja and de. Run: TestLoopsCountedPerModel (Overview groups, the ledger sum and Breakdown; red with the increment removed). go test ./internal/usage ./internal/gateway ./internal/gui; gofmt -l; go vet on darwin, linux -tags nogui and windows. The new usage-loops.test.cjs ran in chromium and webkit, 5 languages at 360 and 1100px, 20 pass; it fails 10 of 10 on HEAD~ assets. usage-*, ledger-*, own-requests, i18n-keys and gui-zh-tw/ja/de in both engines: 565 pass. Not run: a real looping model through the gateway (the logging path is unchanged from #1359). |
||
|
|
2c30e5cee7 |
usage, gui: revert def3a41e3 until Fallmonkey says what context it missed
Fallmonkey asked on Discord (#feedback, 10-12 19:55) to hold the
single-call Codex threshold: "先别做?感觉你漏掉context了". It is not in a
release yet, so take it off main until the rule is agreed, rather than
ship a speed rule its own requester has paused.
This reverts commit
|
||
|
|
def3a41e36 |
usage, gui: a Codex turn of one call is measured only over a second and 100 tokens after its first token, else told as the least it wrote over the whole turn (Fallmonkey on Discord)
Fallmonkey's repro: a Codex turn whose first token came at 6.8 s (the model working) and the rest 0.2 s later in one network push read as thousands of tok/s from its session file. The promised rule, now in: - A Codex turn of one call read from its session file (source "log", turn TTFT known) tells a measured speed only when the window after its first token is 1 s or more and its body 100 tokens or more (usage.CodexWindowMs, CodexBodyTokens; Row.Decode, app.js ledDecode). - The floor from |
||
|
|
60808fd9cf |
usage, gateway, gui: magpie's own requests are told apart from the agent's, and a classifier on a subscription says it asks it every turn (#1839)
kensenzhao saw a subscription's allowance spent by requests the agent
didn't make: a routing group's classifier, set to a subscription's model,
asks it as every turn begins, and those calls looked like the agent's own.
What changed
- usage.Group has an own share (calls, tokens, cost) of the calls magpie
made by itself, filled for models, keys and accounts. Record.ByMagpie
is the test: agent "magpie", or one of its own User-Agents
(magpie-router/1, magpie-search/1, magpie-vision/1) where the agents
aren't loaded. The calls still count in the group's totals, as they
went to the same key or account. A group with none sends no "own".
- The classifier's calls are Kind "routing": callKind marks RouterAgent's
requests, and the decision model's record (Jev / System One) is written
with it. A "Routing classifier" purpose names them in the ledger.
- Usage page: magpie's row among the agents and its ledger rows carry a
"magpie's own" mark; an account's, key's or model's row adds "{n} by
magpie itself"; an account's card says how many of the period's
requests were magpie's own, drawn again once the summary arrives after
the allowances.
- Routing page: /api/groups marks a model a subscription account serves
(modelRef.Sub, servedRef). Beside a classifier on such a model, or a
group whose first member is one, the editor says every turn starts
with a request to that subscription, two when it picks both intent and
effort in words. A classifier on a key or a free model says nothing.
- New strings in zh, zh-TW, ja and de. The mark is a muted chip with an
even border all round (no left stripe).
Tests
- TestSummaryCountsMagpiesOwnCallsApart, TestByMagpie (usage).
- TestIntentRoutesATurn and TestJevPicksTheIntent (gateway) now check
the classifier's records are Kind routing and magpie's own, and the
agent's records are not.
- TestServedRefSaysASubscription (gui).
- own-requests.test.cjs: Chromium and WebKit, 1100 and 390 wide,
en/zh/zh-TW/ja/de, the API faked; no click scroll, no sideways page.
- Broken by hand, each turned its test red: addOwn counting nothing;
callKind's routing case removed; decide.go's Kind blanked; the ledger
mark, the agents' mark, the "{n} by magpie itself" line, the card's
line, its redraw after the summary, the Routing hint, its group case
and modelRef.Sub each removed.
Run: gofmt -l; go vet on darwin, linux -tags nogui and windows; go test
for usage, access, catalog, gui (-tags nogui) and gateway in full; the
GUI tests above, the ledger, routing-intent and translation tests.
Not done: the warmups (warmClaude/askClaude) write no usage record at
all, so they can't be marked; that is left as it was. Not tried with a
real subscription classifier against a live account.
|
||
|
|
8653bead72 |
usage, gui: a usage record and a request's details carry its cache read and cache creation beside in and out (#1839)
kensenzhao asked for usage.jsonl and the Usage page's request details to
carry cache read and cache creation tokens beside input and output.
What changed
- usage.Record's cache_read and cache_write are written on every record,
0 too (they were omitempty), so a prompt that missed the cache reads as
that rather than as a record that kept no cache. A record from before
has neither and reads as 0, as it did. Input still holds neither.
- Every route already filled them; this pins it per wire format:
Anthropic messages, OpenAI Chat (prompt_tokens_details.cached_tokens and
DeepSeek's prompt_cache_hit_tokens), Responses
(input_tokens_details.cached_tokens) and Gemini
(cachedContentTokenCount), relayed and translated, whole and streamed,
a plugin's fetch, and the Claude subscription bridge. System One's
decision calls report no cache and are left as they are.
- A request's details in the ledger have a Tokens row at every width:
"{i} in · {o} out · {r} cache read · {w} cache creation", plus the
5-minute/1-hour split when known. Before, the cache showed only as
"{w} written · {r} read" when non-zero, so a missed cache said nothing.
That string is gone; the new one is in zh, zh-TW, ja and de.
Prices and quotas: the JSON tag is the only change to the record, so the
cost math (CostAt -> CostSplit reads CacheRead/CacheWrite/CacheWrite1h),
Totals' cache sums, budget's CacheReads and access/limit's token windows
read the same values as before. Checked by reading each and by the usage,
access and catalog tests passing unchanged.
Tests
- TestRecordAlwaysCarriesCacheTokens (usage): 0s written, old records read.
- TestUsageRecordsCacheTokensOnEveryRoute, TestPluginUsageRecordsCacheTokens,
TestClaudeSubscriptionUsageKeepsCacheTokens (gateway): each wire format,
whole and streamed.
- ledger-cache-tokens.test.cjs: Chromium and WebKit, 1100 and 390 wide,
en/zh/zh-TW/ja/de; usage-ledger-detail.test.cjs updated for the row.
- Broken by hand: putting omitempty back and dropping the Tokens row each
turned its test red. The gateway route tests pin what the routes
already did; they don't fail on the code before this commit.
Run: gofmt -l; go vet on darwin, linux -tags nogui and windows; go test
for usage, access, catalog, gui (-tags nogui) and gateway in full; the
GUI tests above plus the translation tests. Not run: a real vendor
request to see its cache figures land in usage.jsonl.
|
||
|
|
53abc8e283 |
gateway: a script Claude Code starts, naming a Claude id magpie doesn't serve, goes to Claude Code's tier (tbxark on X)
tbxark's request log: Claude Code's own requests went to its tier, while Python-urllib asked /v1/messages for claude-sonnet-4-6 and claude-opus-5-5 and got 404 "unknown model" in 5 ms. A hook, the statusline or a plugin's script that Claude Code starts inherits its ANTHROPIC_BASE_URL and token, so it reaches magpie with the plain gateway token and its own User-Agent. claudeTierStandIn mapped a Claude id to Claude Code's tier only for a request magpie took for Claude Code, by its User-Agent, so the script's ids went nowhere. Now a request that came with the plain token (not a magpie-<agent> token magpie gave an agent), whose User-Agent names no agent magpie knows (usage.IsAgent; claude-desktop and cursor-local are known too), and that names a Claude-family id magpie doesn't serve, gets Claude Code's stand-in for it, on /v1/messages and on count_tokens (the one choke point both use). Nothing changes when: - the id is served (a Claude subscription or an Anthropic key in the catalog lists it): it goes where it is served, as before; - the caller is an agent magpie knows, or uses an agent's own token; - Claude Code isn't routed through this gateway (StandIn says nothing), so the 404 stays. Run: - TestClaudeTierForAScriptClaudeCodeStarted (new) fails on the old gateway.go (404 for urllib, "", anthropic-python; count_tokens counted 0 without reaching the tier). Breaking the token check by hand or the served-id check by hand turns it red too. TestIsAgentByUserAgent (new, internal/agent) covers IsAgent with the real agent list. - Sandbox HOME, a fake Anthropic upstream, `magpie serve` on 127.0.0.1:3561 with Claude Code's settings.json routed there (sonnet/opus tiers set): python3 urllib POST /v1/messages claude-sonnet-4-6 with x-api-key magpie: old binary 404 "magpie knows no model", new binary 200, upstream got m-sonnet-tier; claude-opus-5-5 -> m-opus-tier; count_tokens reached the upstream on m-sonnet-tier. A codex_cli_rs User-Agent still gets 404. - gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; go test of every package (gateway with -timeout 25m). A full ./... run on the loaded Mac timed the gateway package out at 10m (#1654); run alone it passed in 330s. |
||
|
|
8b799cc890 |
usage, gateway, gui: a request's "In magpie" is magpie's own time, not a try the vendor held before its 503 (#1532, nianlee-official)
The reporter's Codex -> OpenCode Go deepseek-flash request read "In magpie
104 s" with "Vendor's first token 37 s". Record.Sent is the ms from the
request to its answering try's body being written, and by design it
includes the tries that failed first and the pauses after them; the
request detail showed all of it as "In magpie". The reporter's own
routing screenshot shows OpenCode Go answering 503 Service Unavailable
after holding a try ~70-100 s (01:07:08: 3 tries, 222 s), and rows like
01:01:48 / 00:58:27 answered on a second try. Their ledger row showed no
"2 tries" only because that badge came in v0.1.1182.
Now each record also keeps, of Sent:
- own_ms: magpie's own work (before the first try, and in the answering
try up to its request starting to go out, httptrace GetConn), floor 1;
- retried_ms: from the first try's start to the answering try's, i.e. the
tries that failed first and their pauses;
- queued_ms: the answering try's wait for a MaxConcurrency / MaxRPM slot.
What's left (Sent - the three) is connecting and sending the body. The
Requests detail shows In magpie, Tries that failed first, Waiting for a
slot, Connecting and sending, Vendor's first token (en, zh, zh-TW, ja,
de). A record written before keeps showing Sent as In magpie. Sent and
Vendor's first token are unchanged. The packed in-memory request rows
carry the three fields (no on-disk format).
Measured: with an isolated gateway and a fake chat upstream, a
Codex-shaped Responses body of 1.79 MB (~330 turns of reasoning,
function_call and function_call_output, 18 tools, zstd encoded, sent
over real HTTP) took 0.64-1.36 s of magpie's own time alone and
0.8-0.95 s with 4 at once, at load average ~228; far from 100 s.
Run: TestSentTellsMagpieFromEarlierTries (upstream holds the first try
1.5 s and says 503, the second answers: Sent 1514, Own <500, Retried
>=1500) and TestSplitSent; on the old code the detail's value is the
whole 1.5 s (reproduced: sent 1514 ttft 1515), and both go red with
splitSent returning (sent, 0, 0). usage-ledger-detail.test.cjs (Chromium
and WebKit, en and zh) adds the reporter's row and fails on the old
app.js ("104 s" where "180 ms" is expected); i18n-keys, gui-ja, gui-de,
gui-zh-tw pass. go test -tags nogui ./internal/gateway ./internal/usage,
go vet (darwin, GOOS=linux, GOOS=windows) and gofmt -l pass.
|
||
|
|
47269f448f |
usage, gateway, gui: the Requests card counts requests once, a try handed on to the next isn't a failure, and says how many were answered on a retry (小一 on Discord)
小一's Codex-on-credits ledger read "5,482 · 1,094 failed" while many rows said "2 tries/3 tries" and had been answered. "Failed" counted usage rows, not requests: besides each request's final row, the gateway writes a row for every try a vendor refused or turned away (hw.refused/hw.turnedAway), and each of those was counted as a call and a failure even when a later member answered. (Ordinary failovers write no row; 499 cancels and the agent's own client-side retries are separate requests.) In the owner's own usage.jsonl, 24 of the 71 "failed" rows were such refusals a later member answered. Now a request counts once, by how it ended: - usage.Record gains `tries` (final row, when the route took more than one) and `handed_on` (the row of a try that failed and handed the request on). Totals.count skips handed-on rows; a failure is a request whose agent got an error (LostRequest); one answered after a failed try is Totals.Retried (RetriedRequest), with a `retried=1` filter. - Logs written before this are read the same way: the log index marks a failed, non-rejected row followed by another of the same route id as handed on and raises the later row's tries (routeRows); the packed row and its snapshot carry both. - Panel card, Usage overview tile, ledger card, rankings and group rows, `magpie usage` and the TUI say "N answered on a retry"; the CSV adds `tries` and `handed_on` at the end. A row says "· handed on" (with why in its title) or "· N tries". - On the ledger's Requests card "N failed" and "N answered on a retry" are buttons that switch the list to the Failed / new Retried filter, and back when pressed again. The lines wrap rather than cut a button off (German). zh, zh-TW, ja, de strings added. - Docs: reference.md (counting, filter, CSV columns), gateway-routing.md. Run: - go test -tags nogui ./internal/usage ./internal/usageapi ./internal/tui ./internal/gateway . : ok. New TestRequestsCountedOnceWithTheirRetries (JSONL fixture: legacy refused row + 200, handed_on + 200 tries 3, 502 tries 2, plain 200, routeless 429 → 5 calls, 2 failed, 2 retried, across Ledger, QueryPage, Summarize, heatmap, filters, CSV) and TestRetriedRequestCountsOnce (group a refuses, b 500s, c answers → 1 call, 0 errors, 1 retried; a lone 400 → 1 error). - Broke each by hand (count without the HandedOn skip, gateway without HandedOn, log index without routeRows): each test went red; restored. - go test -tags nogui -timeout 40m ./... under the gotest lock, rebased on origin/main |
||
|
|
e5b82cf38a |
usage, gui: Codex rows tell the least they wrote at: a call in a turn of several over its whole time, a turn of one call that reasoned by its answer after the first token (Fallmonkey on Discord)
Codex's session rows told no floor. A call in a turn of several could be
timed from inside itself; the commit before this one times it from what
asked for it, before its first output item, to its last, as Claude Code's
is. So Codex joins usage.FloorAgents and app.js's LED_FLOOR_AGENTS, and
such a call tells its output over its whole time, by the same 1,000-token
rule. On 622 stripped recent rollouts only 4 of 1,367 such calls have
1,000 tokens or more, so the floors will be few, but they are true.
A Codex turn of one call that reasoned has its first token (the turn's
time_to_first_token_ms) but not its first text, so DecodeOf tells no
speed. Fallmonkey asked for its whole output, reasoning too, over the
time after the first token. That reads high: OpenAI's reasoning is
written before the first content, so it isn't in that time. On a gateway
reply of 496 tokens, 224 of them reasoning, 827 ms after a 10.2 s first
token, that is 600 tok/s against a measured answer speed of 415 (the
bug
|
||
|
|
3964ea656c |
usage, gui: a group's speed says how many replies it is of, "125 tok/s (1)", and one with only floors says "≥100 tok/s (30)" (Fallmonkey on Discord)
Fallmonkey: the Usage ranking and the Output speed card showed
gpt-6.1-sol's tok/s from the one reply of its 260 that used no tool (the
only Codex turn its session file times) beside "260 requests", while
Claude Code, whose Requests rows say "≥N tok/s" by the dozen since
|
||
|
|
99fcddeeba |
usage: the Requests tab, its filters and refresh, the charts, the TUI and magpie usage answer at once over a long history (Vantiboo1ean)
Vantiboo1ean (Discord, macOS M2, v0.1.1157) has ~750,000 requests in usage.jsonl. On Usage > Requests every filter, model pick and refresh spun forever and the page never updated. Reproduced in a sandbox HOME with 750k generated records in the real format (400 MB usage.jsonl, ~84k sessions), on magpie web and in process. The cause: the #563 budget dropped the index's blocks once they passed 24 MB (60 MB here), so every read, of any period, parsed the whole file again (6 s CPU) and priced every call again; All took 12 s of CPU, the heatmap 13 s, and the page read both at once. What changed: - log_index: the gateway's blocks are always kept (about 80 bytes a call, S2-compressed instead of flate); the file is parsed once, then only what was appended. - block_price: the gateway's blocks are priced per query, once per set of provider/model/served/effort names rather than per call, into pooled buffers; range loops go by pointer (a packed row is 264 bytes). - request_page: pages are always cached (16 at most), session-file chunks stay in the budget, and a page asked again while it is worked out (the refresh button, the timer) waits for that one instead of starting a second scan. - Siblings that read the same history: - The heatmap names each day once. - A day filter no longer allocates per call. - The ledger behind the TUI, magpie usage, the CSV export and sync (LedgerOf, OwnDays) reads the gateway's calls from the index instead of Load parsing the whole file. - Direct/Summaries matches the session files' calls against the index's blocks without pricing all 750k gateway calls. - A summary of more than 1024 sessions is now cached with its top 1024 (it was not cached at all). The Usage page's /api/usage gets the top 100 (it was sent all 84k, 19 MB, which it never draws) plus a new sessionCount. /v1/magpie/usage still lists every session, and magpie usage says "top 10 of <sessionCount>". Timings, CPU (the box was at load 130-190 on 14 cores, so wall is inflated; min of repeated runs), before -> after: Requests today 6.0 s -> 20 ms Requests 7d 5.8 s -> 93 ms Requests 30d ~6 s -> 362 ms Requests all 12.4 s -> 2.4 s first, ~8 ms again all, model filter 12.3 s -> 1.5 s all, agent filter 11.3 s -> 1.8 s 30d, search "opus" 6.7 s -> 353 ms day filter 6.0 s -> ~0.1 s heatmap 13.7 s -> ~2.3 s first summary today / all 6.0 / 9.2 s -> 25 ms / 1.6 s first, <1 ms again /api/usage?period=all 1.6 s + 19 MB JSON each time -> <1 ms, 53 KB TUI Summaries(all) ~8.5 s (Load + ledger) -> 1.1 s first, <1 ms again TUI Summaries(today) ~6 s -> 29 ms Visit 7d (budget, codex) 5.9 s -> 10 ms The first read of the file after start costs ~5 s of CPU, once. Tests (each seen red with its guarantee broken by hand): - TestUsageOverBudgetHistoryIsReadOnce - TestUsageSessionChunksStayInBudget - TestUsageOverBudgetPageIsCached - TestUsagePageAskedTwiceIsWorkedOutOnce - TestUsageLedgerReadsTheIndexNotTheFile - TestUsageLargeSummaryIsCompleteAndKeptTrimmed (was ...ButNotCached) - TestDirectCountsOnlySessionFileCalls, now with a request-id match, checks that Direct/Summaries equal the ledger's. Run: go test -tags nogui ./... (temp HOME), gofmt -l, GOOS=linux and GOOS=windows go vet on the touched packages. |
||
|
|
b6a263b9fd |
gateway, usage: the Usage page's numbers are read over the gateway, and a Claude Code subagent's call says which subagent and which started it (HoGee_xxl on X)
HoGee_xxl wants their own usage app to read magpie over the gateway, which had no /api/usage counterpart, and asked for subagents' parent ids. - GET /v1/magpie/usage (the /api/usage summary, ?period=) and GET /v1/magpie/usage/requests (the /api/usage/requests ledger page, same filters, offset/limit) on the gateway. The builders moved out of gui into internal/usageapi so both serve the same JSON; gui keeps aliases and sets usageapi.Clients for agent names (gateway can't import agent). Guard as /v1/magpie/quotas: this machine, or another with an enabled gateway key, behind the same Host check. A key held to a budget, models or accounts is refused the summary (403) and gets the ledger filtered to its own CallerKey, with callerKeys/agents/providers/accounts cut to its own rows (usageapi.OwnPage): those facets are drawn from every call in the period. `path` is left out for another machine. - usage.Record gains subagent and parent_agent; session stays the parent conversation. Gateway rows take them from x-claude-code-agent-id and x-claude-code-parent-agent-id; session-file rows from the file name (<session>/subagents[/workflows/<run>]/agent-<id>.jsonl, no cache version bump) and the parentAgentId of the agent-<id>.meta.json beside it. Both packed into the request page's text columns (now 29, msg at 29). Codex sub-threads: only kind, as before; no spawned thread on disk to take a parent shape from. Run: real Claude Code 2.1.296 under a sandbox CLAUDE_CONFIG_DIR against a local fake Anthropic endpoint that made it spawn a subagent from a subagent: the nested request carried X-Claude-Code-Agent-Id=a143287ac46b82a96 and X-Claude-Code-Parent-Agent-Id=a99ca20c03d1813d8, the first-level one the agent id only, Session-Id the parent's throughout; the nested meta.json had parentAgentId. Tests use those bytes. TestUsageOverGateway goes red with OwnPage, the CallerKey pin, or the header read removed (each tried). gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; set -o pipefail; go test ./... green. |
||
|
|
6d3bc9183d |
usage: the Usage and Requests pages count any days picked, from a Custom opt after All that opens a month to pick them on (#1492, nianlee-official)
The period bar had only Today, 7 days, 30 days and All. A Custom opt now
follows them. It opens the app's own menu (no native select): Yesterday,
This month, Last month and 90 days a click away, and a month of days to
pick the first day on, then the last. Days after today can't be picked;
arrows walk the days and Escape closes. Once picked, the opt names the
days ("Oct 1 – Oct 7"), and narrow windows show only its icon until then.
The backend takes the days as period "2026-10-01..2026-10-07", both
included, in the local time zone (usage.RangeOf, Period.Known/Until).
The summary, the Requests page (index and ledger fallback), Direct and the
CSV name count only calls from the first day's midnight up to the
midnight after the last. The chart is an hour each for one day, a day each
up to 60 days, and a week each from a Monday past that. A picked range is
summarised afresh each time, so ranges never pile up in the summary cache.
The credits-per-day card follows the days picked. New strings in zh,
zh-TW, ja and de.
Run:
- go test -tags nogui ./internal/usage ./internal/gui (sandbox HOME): ok.
- TestPickedDaysArePeriod with Until returning zero (no range end):
FAIL, Summarize 5 calls / QueryPage 5 rows / LedgerOf 5 rows, want 3.
- usage-range.test.cjs, Chromium and WebKit, en and zh, at 390px: 4/4.
- Every GUI test touching period or the Usage view (87 files): Chromium
388/388; WebKit 386/388, the two purpose-filter's Routing focus check
(scrollTop off by 1px after a wheel), which then passed 52 of 56 lone
runs here and 25 of 25 on origin/main; nothing in this change runs on
the Routing page. gui-de, gui-ja, gui-zh-tw, i18n-keys: pass.
- gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui on both pkgs.
|
||
|
|
cb406c8425 |
plugins: a plugin can add an agent magpie has no setup of its own for
Plugins could be subscription providers or gateway middleware. Now a third
kind: an agent plugin, so a user whose agent magpie doesn't ship can still
put it on magpie.
- internal/agentplug: a plugin's magpie.agent module (or a *.agent.js file)
exports agent = {id, name, config, format?, model, prefix?, bin?, dir?,
ua?, icon?, notice?} and an optional connect({gateway, model, models,
agent}) returning the other keys to write. Compiled in moejs, reloaded
when plugins.json or the file changes; why one didn't load is kept.
- internal/jsmod: module compiling (imports kept inside the plugin), moved
out of middleware so both share it.
- internal/agent/plugged.go: each becomes an Agent (Plugin set) after
magpie's own. JSON, YAML and env files are edited key by key, comments
kept; what each key held is stashed typed under plugin:<id>:<path>, and
its own model or Disconnect puts every key back. A built-in id is
refused; a connect that throws writes nothing. Key magpie-<id>; usage
names it by key or ua (usage.PluginAgents).
- GUI Plugins page: an Agent kind chip and glyph, a Discover "Agents"
section (market kind "agent"), and an installed row line "Adds X to
Agents" or why it didn't load. zh, zh-TW, ja, de strings.
- Docs: site Plugins page (en, zh, ja) "Agent plugins", reference.md,
agent-wiring.md, gateway-middleware.md.
Run:
- go test ./... (all ok); gofmt -l clean; GOOS=linux go vet -tags nogui
./... and GOOS=windows go vet ./... clean.
- TestPluggedYAML, TestPluggedJSONUnwire, TestPluggedRefused.
- GUI: plugin-agent.test.cjs 22/22 (en, zh, zh-TW, ja, de; 980 and 420;
chromium and webkit); all plugin-*.test.cjs, i18n-keys,
deprecated-subscriptions, filter-ime: 315 pass, 0 fail.
- Real use, in a sandbox HOME: an Aider plugin (~/.aider.conf.yml, prefix
openai/, connect writes openai-api-base/key) installed in a dev build;
picking DeepSeek V4.1 Flash on the Agents page wired the file keeping the
user's comment and keys; real aider 0.86.2 `--message` answered through
magpie from the real DeepSeek account; usage.jsonl recorded agent aider,
provider deepseek, 200; Disconnect restored the file byte for byte.
|
||
|
|
3e5bc3d8fe |
gateway, usage: conversation text is kept only under a session the client named, and a client's "request-…" session counts like any other (#1355)
What changed: with recording on, a request that names no session used to get a made-up "request-…" id and its text saved under it. Nothing listed that id and GatewaySessionByID turned it away, so the text could never be opened. magpie now makes up no id: such a request isn't recorded, and the X-Magpie-Session reply header only echoes the client's own session. With no made-up ids left, the "request-" prefix checks in appendUsage, OTel, Usage's sessions, Routing's vias and the gateway Sessions projection only dropped sessions clients named themselves (appendUsage wiped them from the ledger). They are gone. The tests that held the old rule now say the new one, and gateway-sessions.md says it. Run: TestGatewayConversationNeedsTheClientsSession and TestGatewayConversationClientRequestPrefixedSession fail on the PR's code (a made-up id is returned; the ledger keeps 0 of 2 calls) and pass here; putting appendUsage's prefix check back turns the second red again. gofmt -l clean; go vet; GOOS=linux and GOOS=windows go vet -tags nogui on gateway, gui, sessions, settings, usage; go test -race -timeout 900s on those five: ok (gateway's TestCORSKeyThroughTheServer rerun after its fix). GUI: gateway-conversations, gateway-mode and all sessions-* tests, 216 cases in Chromium and WebKit: pass. |
||
|
|
c9b8263378 |
sessions, gateway: Sessions lists gateway sessions, and can keep their text on this computer when turned on (#1355, mu-zi-lee)
What changed: the Sessions page lists sessions seen only through the gateway (from the usage ledger, read-only, a native session of the same id wins), and shows in gateway mode. A Sessions switch, off by default and confirmed before it turns on, records each gateway exchange's text under the config dir (scrubbed, at most 7 days and 256 MiB, cleaned hourly). Settings sync and restore can't turn it on; POST /api/sessions/recording turns it on or off and can clear what was kept. Why: users of magpie as a gateway (gateway mode, LAN clients) had no way to see their conversations; the owner chose this design on the PR. Squashed from PR head 6a343ba1 onto origin/main. Conflicts: gui-shell.md (kept main's placeMenu text, took the PR's Sessions in gateway mode) and settings_keep_test.go (main's fields plus GatewayConversations). Run: go build ./..., go vet on gateway, gui, sessions, settings, usage; go test -race -timeout 900s on those five packages: all ok. |
||
|
|
ed31293c0e |
usage, gui: a reply its vendor let go in a burst over a couple of hundred milliseconds tells no speed, not 2,237 tok/s (John on Discord)
John's Kimi Code rows after v0.1.1119 (OpenCode, group/k3-glm, api.kimi.ai,
Chat, k3-256k): 550 tokens, 22 of them reasoning, in 16 s with the first
content at 5.2 s read 2,237 tok/s, and 395 tokens in 19 s 2,012. 528 answer
tokens at 2,237 tok/s is 236 ms: the burst the vendor let go at the end.
|
||
|
|
de5455b8fe |
gateway, usage, gui: a reply whose vendor sent its first words and held the rest to send in one burst tells no speed, not 1,367 tok/s (John on Discord)
John's request (OpenCode, a group served by Kimi Code at api.kimi.ai, Chat) showed 1,367 token/s: its tokens counted over the time from its first token to its end, though nothing came in between and the rest came at once. The 100 ms / 10,000 tok/s bounds catch a burst only when the first content comes with it. firstToken now reads on past the first text and marks when each content event's bytes came (one mark a millisecond, up to 65,536 marks and the 8 MB it reads), and flowMs is how long the content took to come from where the speed is counted: the span from a tenth of its bytes to nine tenths, scaled to the whole. A steady stream gets about its whole window; one let go in a burst about 1 ms. It is kept as Call/Try/Route .flow and usage.Record.flow_ms (and the Requests page's packed rows), and usage.DecodeOf, routing.js's decodeOf and app.js's ledDecode count no longer a window than it. A record without it reads as before. Verified: TestBurstTellsNoSpeed, a fake Chat vendor that sends a word, waits 600 ms, then 199 words and the end in one write (1,000 tokens), for a Chat and a Responses agent: no speed; before, 1636 and 1655 tok/s. Its steady case (a word every 60 ms) keeps 200 tokens over most of its window. TestCodexBackendBurstTellsNoSpeed is the same through Codex's own ChatGPT backend (before: 1,000 tokens in 601 ms). TestFirstTokenKinds now expects the stream read past its first text. Go tests ran on Linux (golang:1.26 in Docker; this Mac's syspolicyd held new test binaries at launch). GUI: routing-burst-speed (a route with John's 5.1 s first token, 6.7 s and a 2 ms flow: was "1367 tok/s", now none) and usage-speed (a row with flow_ms 2 shows "—") fail without the JS change and pass with it, with reasoning-speed, routing-request-metrics and usage-ledger-detail, in Chromium and WebKit (en/zh, ja/de where the tests have them); no strings changed. Not reproduced with Kimi Code itself: whether it holds the stream so is inferred from the numbers. |
||
|
|
e961836fb0 |
usage, gateway, gui, provider, cli: the tests pass when a run crosses midnight, and a usage answer reads the clock once (#1046)
* usage: the usage tests pass at any time of day, midnight included The usage tests stamped their calls with the machine's time and then asked for today, 7 or 30 days, or a cached answer, which the code worked out from its own time.Now a moment later. A minute after midnight a call made "a minute ago" was yesterday's, and when midnight fell between the test's read and the code's, the call and the period were of two days. magpie usage, the TUI's Usage page, the two Codex cache-write tests and the computers' shared days failed in the first minutes after midnight (the TUI's after midnight UTC, the zone its package's tests run in since |
||
|
|
e6dd5d20bb | usage, gateway, gui: a reply that reasoned is timed by its answer, from its first text, not by all its output from its first token (tony on Discord #general: Usage › Requests read "gpt-6.1-sol 163 token/秒 · 8,036 个请求 · 首字 14 秒" and asked whether subagents were added up) — speed was every output token over the time after the first content (text, reasoning or a tool call). Output counts the reasoning, and a model whose reasoning is hidden (OpenAI's encrypted reasoning, a summary sent when it is done, Claude's omitted thinking) writes it before the stream shows anything, inside the TTFT; so a 2,000-token think and a 200-token answer over the 1.5 s after the first token read 2,200 in 1.5 s, 1,467 tok/s. Concurrency was not the cause: the aggregate is Σ tokens over Σ per-request windows, so subagents running at once never add up. In the owner's own usage.jsonl codex/gpt-6-luna turns read up to 600 tok/s (out 496, reasoning 224, 11,055 ms, ttft 10,228) and its aggregate 133; it is 80 now. usage.DecodeOf is the one rule: a reply with reasoning counts out − reasoning over ms − firstText, one that reasoned and wrote only tool calls tells no speed, one without reasoning is timed from its TTFT as before; DecodeWindow's burst cut (#731) still applies. Record.Decode feeds summarize, the ledger's Totals and its timeline Parts; a route keeps its reply's reasoning (Route.Reasoning, from gateway.go and codex_backend.go), and routing.js's decodeOf/speedOf times its rows, the story and a session's average by it (an older route takes its served usage's reasoning); app.js's ledDecode does the Usage page's rows, whose tooltip says the reasoning left out, and the Output speed help says the rule, in en, zh, ja and de. History is read the same way, as it keeps the reasoning and the first text. Routing never ranks by speed. TestReasoningReplyTimedByItsAnswer (the 2200/2000 turn, a summary 10 ms before the text, a concurrent subagent, tool calls only, reasoning over output, no reasoning, not streamed: 1,200 tokens in 11 s through summarize, addRow, LedgerSeries and Decode) fails without the change and passes -race -count=10; TestUsageKeepsTimeToFirstToken now has its paced replies report reasoning and checks the route keeps it. reasoning-speed.test.cjs (Routing rows 133, 100, none and 100, the story never 1,467, the session 105; the Usage rows, tooltip and KPI the same; no sideways scroll) passes on Chromium and WebKit in en, zh, ja and de, and fails against the old assets (1467 tok/s); routing-request-metrics, routing-burst-speed, usage-speed, usage-ledger-detail, i18n-keys, gui-ja, gui-de, ledger-hscroll and click-scroll pass on both. go test -race -tags nogui ./internal/... under a temp HOME passes but internal/proc's TestUserPath ("the login shell's PATH never came"), which failed under the full run's load, passes 3/3 alone and is not touched here; go vet, gofmt -l, linux and windows (nogui) builds pass. Not tried with tony's data. docs/reference.md says how output speed is counted. | ||
|
|
c5b57b9077 |
gateway, usage, gui: a relay's reply of tool calls ended "end_turn" or "tool_calls" goes on to the calls, a tool_use whose start carries its input keeps it, an Anthropic stream that just stops is an error, and every request says its protocol and the upstream's stop reason (蓝猫 on Discord)
蓝猫's custom Anthropic-protocol provider in front of Grok ended the agent's
turn a few words in with no error, where Alma on the same endpoint ran on.
Replayed from a fake upstream, three ways an Anthropic-shaped relay's
stream was read wrong when magpie translated it for an agent of another
protocol:
- a reply of tool calls whose stop_reason said end_turn, stop or OpenAI's
tool_calls was handed on as finish_reason "stop": the agent ended its
turn instead of running the calls. stopFromAnthropic takes tool_calls,
function_call, length and content_filter; collector.finish makes a
"stop" beside tool calls "tool".
- a tool_use block whose content_block_start carries its whole input,
with no input_json_delta after, lost the input (the call went with {}).
anthropicDecoder emits it, and skips deltas for that block after.
- a stream that ended cleanly with no stop_reason and no message_stop was
finished as a whole reply. streamTranslated now takes it as cut: asked
to go on where it can, else ended with "the reply ended before it was
complete", as the passthrough already did.
Each request now keeps the upstream's own stop reason (Usage.Stop /
usage.Record.stop: stop_reason, finish_reason, a Responses status), from
the passthrough's sniffer and the translated stream, shown as "Upstream
stop reason" in a request's details on Usage › Requests. Each row there
is tagged with the protocol it was sent upstream in, "Chat → Anthropic"
when translated, told from its endpoint, so older rows have it too; the
details say Protocol. en/zh/ja/de, no left border, no select, a click
moves nothing.
relay_stop_test.go's four tests fail without the change (finish_reason
"stop" for tool calls under end_turn/tool_calls/stop, arguments "" for a
whole-input start, a cut stream finished "stop", no stop recorded) and pass
with it; the passthrough case sends "data:" without a space and CRLF.
ledger-protocol.test.cjs passes in Chromium and WebKit, en and zh.
go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test
-tags nogui ./... under a temp HOME pass.
|
||
|
|
71d2da1f42 |
catalog, usage, gateway, gui: a price can have a long-context tier and a 1-hour cache write, and the price boxes take decimals (PAMI on Discord)
OpenAI bills gpt-6-astra, gpt-6.1-sol and gpt-6-luna over 272K input at 2× input and cache and 1.5× output, for the whole request. A price now has tiers: `magpie model price <m> 10,50,1,12.5 --tier 272k 20,75,2,25` (--tier can repeat). A tier applies when input + cache reads + cache writes is over its size, so 272,000 is not over and 272,001 is. The built-in prices take tiers only where models.dev lists one (cost.tiers of type "context"), and it does list one for those three. The ledger, each request and OTLP are costed at the tier the call reached. Session and day totals sum many calls, so they stay at the base price.
Anthropic bills a cache write kept for an hour at 2× input and one kept for 5 minutes at 1.25×. Its usage reports which is which in cache_creation.ephemeral_5m/1h_input_tokens. The gateway (API and Claude subscription) and Claude Code's transcripts now keep that split. A price's fifth part is the 1-hour write. When it isn't given, it is 2× input: that is Anthropic's rule, and only Anthropic reports 1-hour writes. Claude list prices carry the 2× too. cache_write_tokens is still the total, and the usage CSV adds cache_write_5m_tokens and cache_write_1h_tokens at the end. The app shows the split on a request's Cache and on the usage tooltips. Old prices and old records, which have no 1-hour part, read as before. The sessions cache (18) and the call cache (calls-v8) are re-read once.
In the GUI, the price boxes were number inputs and dropped what they didn't parse ("0,25"). They are now decimal text boxes that take both "0.25" and "0,25". A model's price row has a 1-hour box (empty means 2× input) and a quiet Long-context price row. That row shows the list's tier greyed in, or sits behind a link when the list has none. A bad size is refused by name. en/zh/ja/de.
Tests:
- New: TestPriceTiers, TestCostSplit, TestPriceJSON, TestModelPriceTiers, TestModelPriceTierCmd, TestAnthropicCacheWriteSplit and TestClaudeCacheWriteSplit. The ledger CSV test expects the new columns.
- model-price-tiers.test.cjs is new; model-price-edit and provider-price-rate are updated. All of them fail against the old assets and pass in WebKit. Chromium couldn't be launched here.
- go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
|
||
|
|
e5981040dc | gateway, gui: a request an aggregator passed on says which provider answered it behind it, "Upstream: DeepInfra" (leslie_luo on Discord: 像 CPA 那样指出实际供应商) — through OpenRouter a request was only "OpenRouter · deepseek/deepseek-chat", with no word of the provider (DeepInfra, StreamLake, Novita…) OpenRouter had sent it on to. OpenRouter names it in its replies, as tried with the owner's real key: Chat's body and every chunk of its stream have a top-level "provider", Messages' body has one and its stream's message_start a message.provider; its Responses replies and every reply's headers name none. The gateway now reads it (upstreamOf) from a body relayed as it came and from each event of one it translated, Chat, Messages or Responses, streamed or not, and keeps it on the request's try and route (upstream) and in the usage ledger (Record.Upstream; the CSV export's last column, searched as the rest). The Routing page's Requests list says Upstream: DeepInfra beside where it went, giving way after the provider's name when short of room, with its story saying the aggregator passed it on; a request's details on the Usage page have Upstream provider. A reply naming none says nothing. zh, ja, de strings. ClinePass and Cline weren't tried (no account); Vercel's gateway documents no such field in its replies, and a vendor whose reply has a top-level "provider" string is read the same way. In a sandbox magpie with the owner's real OpenRouter key: Chat, Messages and Responses (translated to Chat), streamed and not, all six said StreamLake in the trace, the ledger and on the Routing page. TestUpstreamRecorded (6 paths × streamed or not: the route, its try, Recent and the ledger) fails on the old code, TestUpstreamOf; routing-upstream.test.cjs (Chromium and WebKit, en and zh: the tag inside its row, the story, the Usage details, a click moves nothing, no left-border accent) fails on the old assets. ledger-hscroll, request-archive-usage, usage-ledger and usage-ledger-detail pass on WebKit; routing-served fails the same on origin/main (its swap wording). go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass but for TestTranslatedStreamKeepsClientAlive, which passes alone 5 times here and on origin/main. |