d3fc6f2bfada18e6ae7887b79ed1e4c650ca37e1
93
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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
|
||
|
|
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 |
||
|
|
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
|
||
|
|
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 |
||
|
|
69167bc299 |
usage: a reply let go under a second after a wait four times longer tells no speed
pluviophile714 on Discord: a gpt-6.1-sol row on Routing read 1,539 tok/s (input 21,617, output 392, first token 8.2 s, total 8.3 s), where another monitor measures ~70. The reply came whole about 255 ms after an 8.2 s wait. Its content was spread over that short window (flow 230 ms), so the HeldShare flow check passed, and so did the 100 ms floor, and 392/0.255 s read as 1,539 tok/s. New rule, usage.HeldWindowMs: a window under 1,000 ms whose start (first token, first text or first reasoning) is more than HeldShare (4) times the window tells no speed. One rule in every place that computes one: - usage.DecodeOf: the Usage page's speed and totals, the CLI, the GUI's model speeds, and the gateway's Speed first pacing (noteTrySpeed); - routing/client.js decodeOf: the Routing row's speed and its story line; - usage/page.js ledDecode, plus a ledNoSpeed_ reason for the dash's tooltip, in en, zh, zh-TW, ja and de. docs/reference.md and docs/subsystems/gateway-sessions.md say so. On the owner's usage.jsonl (read only), 103 of the 106 rows over 600 tok/s were such windows (e.g. 448 tokens in 107 ms after 8.1 s) and are dropped. The 3 that stay have windows of 2 to 5 s. The overall speed goes from 103.8 to 97.9 tok/s. What it costs: a short reply that really streamed after a long wait tells no speed either. The live visible-reasoning fixture (76 tokens over 731 ms after 6.8 s, ~104 tok/s) and #2637's grok record (307 tokens 403 ms after a 4.6 s first token, 531 tok/s) now read "—". Their tests keep their guarantees with the same timings after a short wait, and also check the long-wait case. Tests: - New: internal/usage TestShortWindowAfterLongWaitTellsNoSpeed (the reporter's numbers, a reasoned row from the ledger, the boundary, a second after a long wait, Totals) and internal/gateway TestShortWindowAfterLongWaitNotesNoPace. - GUI: usage-speed-every-row has the reporter's row (dash, and the tooltip in all five languages); routing-burst-speed has it (first token 8.2 s, no tok/s). - Updated to the new rule: TestVisibleReasoningSpeed's decode-minimum and max-speed cases (short wait now), TestCodexTurnMeasured...'s gateway/Claude rows, TestLiveVisibleReasoningFixture and TestUsageIngestTellsSpeed. Run on mote at this tree (rebased on |
||
|
|
e41ef6288c |
providers: a spend cap on an API key, per day, month or in all (sparkling_lemur_62868)
sparkling_lemur_62868 on Discord: a team's OpenAI key holds granted credits that other docker services spend from too, and they want magpie to stop at a share of it. Their workaround was two magpies behind a gateway-key limit. What changed - provider: KeySpendCaps on a provider, keyed by the key's fingerprint (key_spend.go): USD over a local calendar day, a local calendar month, or in all since it was set. Since is kept while the cap stays one in all. SetKeySpendCap and ParseSpendCap refuse an amount outside 0 < usd <= 1,000,000 and an unknown period, and leave the saved cap as it was. Subscriptions are refused, since an account has its own usage-window cap. - usage: KeySpent(keyID, start) is what magpie's own calls on the key cost at the Usage page's prices. Turned-away calls and app-reported ones are left out. It reads usage.jsonl once per key and start, keeps the sum for 5 minutes, and Append counts each new call into it (spentNew). A read that a write races is read again. - gateway: perKeyEvery bars a key at its cap (spendHeld) as a usage cap holds an account. The next key serves, then the fallbacks. With none, the reply is 429 "spend cap reached: ..." naming each key, what it spent of which cap, and how to go on. Retry-After is when the soonest period renews; a cap in all gives none. A spend hold is not a usage cap: Stop at the caps and strictKeep don't end at it (capHeldOnly). The trace's barred row carries the cap, the spend and the period. - GUI: a pill on each key's row in the provider editor, for example "$7.50 of $20.00 today". It opens the app's menu (No spend cap, Per day..., Per month..., In all...) and then takes the amount in place, as the lane-limit pill does. A key at its cap gets a line under its row: "At its spend cap · back in ...". Every string is in all five languages. The pill and the line are in keyspend.js, which app.js imports when it draws a key's row, so the core's script budget is not raised. /api/providers' keyList carries spend, and POST provider/keyspendcap sets it. - CLI: magpie provider spend-cap <id> [key [usd [day|month|total]|off]] lists each key's spend and sets or removes a cap. - docs: providers-accounts.md and gateway-routing.md. Caveats, also in the tooltips: - What counts is magpie's priced usage, not OpenAI's bill. - A model with no known price counts $0. - Requests already under way when the cap is reached still finish, so a key can go a little past it. Run on mote at the pre-rebase head ( |
||
|
|
4bac5eed26 |
usage: a request's row says what went up to the vendor, tries summed (#4456)
RunMintOn asked how much a long session sends upstream: a proxy counted ~900 MB up in 45 minutes, and no ledger row said what a request sent. A row now has up_bytes, the bytes that went on the wire, every try and every second ask summed (zstd's size for a ChatGPT turn), and plain_bytes, the last try's body before compression. They are summed in the request's context on its own goroutine, set in serve and, for Codex's own turns that come from the mux and not through serve, in codexUpstreamOn. Handed-on rows carry neither; rows from before carry neither. From ggbdpq's patch (via gua2100), two changes: - the patch counted in codexUpstreamOn but set the context only in serve, so a Codex turn on its ChatGPT sign-in, the zstd case the issue is about, wrote 0 and 0 (TestCodexOwnTurnKeepsUpBytes); - a second request inside one try (RetryOneAuth, RetryZhipuCoding, RetryOpenCodeFreeOnZen) went up uncounted; it counts now (TestLedgerCountsATrysSecondAsk). Request bodies to other vendors stay as their client sent them; zstd stays Codex's (the owner's call, on the issue). Run at this tree on mote: go test ./internal/gateway -run 'UpBytes|TrysSecondAsk|OneAuth|Codex|Draw|Relay' -count=1: ok; go test ./internal/usage ./internal/redact -count=1: ok. gofmt clean. Broken by hand: no context in serve: TestLedgerKeepsUpBytes and TestLedgerCountsATrysSecondAsk red; none in codexUpstreamOn: TestCodexOwnTurnKeepsUpBytes red (row 0/0, backend got 79 of 8444); the second ask not counted: TestLedgerCountsATrysSecondAsk red. Not tried: a real session's numbers against a proxy's; the GUI shows neither field yet. Co-authored-by: ggbdpq <ggbdpq@gmail.com> |
||
|
|
344a59f9db |
gui: an unchanged Sessions poll answers Same without making the rows
The Sessions tab asks for every session each 15 s. When nothing had changed, the handler still copied the kept listing, made a row of each session, merged the gateway's sessions, read Codex's effort and the vias, encoded every row and hashed them, only to answer X-Magpie-Same. Over ~17k real sessions (69 GB of Claude Code and Codex history) that was ~140 ms of CPU and ~24 MB of garbage per poll. Now the handler keeps, per ?limit, what the last list it sent was made from: the sessions listing (sessions.ListUnless's number, which changes whenever the listing is made again, and at least once a minute), the usage log's version (usage.LogVersion), the user's usage aliases, and the agents' names and icons with the folders. An ask whose X-Magpie-Had is that list's tag, while all of these stand, gets X-Magpie-Same before any row is made or the listing copied. Anything else a row shows (a Codex thread's effort, a gateway title) follows within the minute the kept listing stands. writeJSONRows returns the tag it sent. Measured on the real history (a sandbox HOME with APFS clones of ~/.claude/projects and ~/.codex/sessions, 17,140 files), 30 polls of /api/sessions + stats + overview, the same script for both builds: before ( |
||
|
|
9551fadcb4 |
gateway: reasoning streamed with no count in its usage is marked unknown, not read as none (#4545)
A reply whose stream carried reasoning (reasoning_content, Anthropic thinking deltas) while its usage counted no reasoning tokens was recorded Reasoning 0, ReasoningHidden false: the same record as a reply that never reasoned, and a tool-only one was timed with its reasoning counted as answer. hidesReasoning now takes the usage's reasoning count and marks such a reply ReasoningHidden, the record's existing "the stream doesn't tell how much it reasoned". Reasoning stays the vendor's 0; nothing is estimated, so no new field or Flags bit (rowReasoningHidden 512 is the one it already uses). Who does this, from real bytes and docs: Anthropic's Messages usage has no thinking count at all (output_tokens includes it), so every visible Anthropic-protocol thinking reply was this case. The fixture testdata/reasoning-uncounted-deepseek-anthropic.sse is DeepSeek's Anthropic endpoint as it came on 2026-10-31 (deepseek-v4-pro, thinking on): 33 thinking deltas, "391", usage output_tokens 35 and nothing else. The owner's usage.jsonl has 12 kiro claude-haiku-4.5 rows with paced first_reasoning_ms and reasoning 0, the same case through a plugin. DeepSeek's Chat endpoint does count (completion_tokens_details), and those rows are unchanged. No captured Chat vendor omits the count; the Chat subtests are built from the shape, not a capture. Siblings: Responses, Gemini and Code Assist were already marked hidden whenever reasoning streamed (summaries). The Codex backend's two calls pass its count too (no change for Responses; its call record now reads the count after the sniffed usage is added). The Claude subscription bridge counts thinking from the CLI and is unchanged. What changes for a reader: Decode already leaves a hidden reply with no text untimed, so a thinking + tool-call reply with no count tells no speed now; one with text is timed as before (whole output from first content). The GUI's decodeOf/ledDecode read the same flag; no GUI code changed. Run on mote at base |
||
|
|
2eac916170 |
gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue
xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.
A gateway key can now expire (Key.Expires) and can be issued under
another key (Key.Issuer). It lives from 1m to 30d. It can be held to a
set of models, a set of accounts, tokens or cost over its whole life
(one "hours" limit as long as its life), and read-only.
- POST /v1/magpie/keys {"ttl":"1h"|3600, name, models, accounts, tokens,
cost, readOnly} answers 201 with the secret once, no-store. GET lists
the caller's keys, masked. DELETE /v1/magpie/keys/{id} revokes one.
- magpie gateway-key issue --ttl 1h [--name] [--models] [--accounts]
[--tokens] [--cost] [--read-only] [--from <id>] [--json] prints the key
alone. gateway-key issuer <id> on|off lets a key issue keys. list shows
until/expired/issued by.
Who may issue:
- a key the user let issue (Issues), from wherever that key is let in,
so a container or CI can;
- with no key, a request that profileRefused passes: loopback, no
forwarding header, no Origin/Sec-Fetch/Mozilla marks, a loopback Host.
Such a request can already use every model with no key and run the CLI,
so it gains nothing.
Never: a page, another computer without such a key, a key not let issue,
an issued or expiring key, or a read-only key (readOnlyGuard).
An issued key never outlives or exceeds its issuer. IssueKey clamps its
expiry and refuses models and accounts the issuer can't use. On every
authentication (access.Check, under Authenticate and On), identityOf
folds the key into its issuer as the issuer is now: models, accounts,
read-only, quotas and expiry. An issuer that is off, removed or expired
refuses its keys. Spend counts against the issuer too: the new usage
field callerIssuerId, budget.read/Append counting both keys, and Reserve
reserving on both. /v1/magpie/limit answers expires and issuerLimits.
An expired or refused key gets 401 with why ("… expired at …: ask for a
new one") on every route, from loopback too. Otherwise a held sandbox
whose key ran out would be let in as no key. Expired keys are pruned
after an hour (every 10 minutes while serving, and on each issue).
rowText packs CallerIssuerID: without it, usage.Visit returned the field
empty and the issuer's limit counted none of its keys' calls.
Docs: gateway-routing.md has "Short-lived gateway keys" and the
/v1/magpie stats API table. site/public/docs remote has "Short-lived
keys" and "Stats API" in en, zh and ja. GitHub OIDC is filed as #4531.
Run at base
|
||
|
|
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.
|