Commit Graph
124 Commits
Author SHA1 Message Date
yetone c8c3ce9a9a usage, sessions: Antigravity CLI's (agy's) own calls are counted, read from its transcripts, and a step it sent through magpie once (#2097, parkavenue9639)
agy wrote its calls nowhere magpie read. Each conversation's
brain/<id>/.system_generated/logs/transcript_full.jsonl has a line per step,
and a model step carries its own input_tokens, cache_read_tokens and
output_tokens. readAgyCalls reads those as agent agy, provider unknown
(session-unknown) and no model: the step names none, and settings.json's is
only the one picked now. A transcript an older agy wrote has the lines with
no token fields; they are left out, not counted as zero.

agy sends the gateway no session header, so its gateway records name no
session and the matcher, which pairs by session, would have counted a step
sent through magpie twice. matchedBlocks now pairs an agy step with a
session-less agy gateway record by tokens alone, and lets the record end up
to 30 minutes after the step's created_at, which is when the step began (to
the second), not when its call ended.

Tried for real: agy 1.2.16 under a sandbox HOME, with GEMINI_API_KEY and
GOOGLE_GEMINI_BASE_URL on a fake Gemini endpoint, three turns of one
conversation. It sent User-Agent google-genai-sdk/1.72.0, X-Goog-Api-Key and
no session header; its transcript's input_tokens is the prompt less the
cached tokens and output_tokens includes thoughtsTokenCount (8 + 40 = 48),
as the gateway counts a Gemini reply. A turn that failed to connect wrote
ERROR_MESSAGE steps with no tokens. That transcript is the fixture beside
the issue's quoted lines and an old one without tokens; the built binary's
`magpie usage --csv all` in that HOME lists the three steps as agy, log.

Run: TestAgyCalls and TestAgyStepThroughMagpieCountedOnce fail without the
change (0 agy calls; "the step the gateway logged is counted again"); gofmt
-l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on sessions and
usage; go build darwin, linux nogui, windows; go test -tags nogui of
internal/sessions, internal/usage, internal/usageapi, internal/cli in a
sandbox HOME, all ok.

Not tried: a step through a real magpie gateway and a real Google account
(the matcher's pairing is covered by the unit test with the gateway's
numbers from the fake run); agy on Windows or Linux; the full go test ./...
2026-10-14 14:35:23 +08:00
yetone 722abfbb0a usage, gui: a window whose whole can't be estimated says "not enough data", and why in its tooltip (#2045)
The Usage page's account cards told a window's whole ("Whole ≈ N tokens
· ≈ $X") only where it could be reckoned honestly, and said nothing
elsewhere, so a reader couldn't tell a window magpie can't reckon from
a fault (#2045 asked for "数据不足" there).

The server now says why on each window of an account's own card that
isn't reckoned (QuotaWindow.HoldsWhy):
- low: under 5% used (HoldsFloor);
- clock: no reset clock, so no known start;
- log: the window began before magpie's request log;
- none: magpie routed nothing the window counts in it;
- credits: a call in it may have been paid from credits or extra usage
  (#2010's dry runs).
Windows whose whole is never told (a pool, a family, money aside, an
error card, another magpie's) carry no reason and say nothing, as
before. WithWindowHolds now also fills reasons when no window at all can
be reckoned; the caller's cards are still left unwritten.

The GUI shows a muted "Whole: not enough data" on the reset's line, with
the reason in its tooltip, in all five languages. A reason it doesn't
know says nothing. History cards are unchanged.

Run:
- go test ./internal/usage ./internal/gui: pass. The window-holds tests
  check each reason, that reckoned windows carry none, and that the
  caller's cards stay unwritten. Not writing HoldsWhy turns 3 tests red.
- quota-holds.test.cjs in Chromium and WebKit, en/zh/zh-TW/ja/de, at
  360, 420, 440, 1000 and 1100: the line, its reason, muted, not cut,
  inside its card. Removing the GUI branch turns it red. Screenshots at
  420 in zh and de looked at.
- i18n-keys, quota-curve, keep-login, quota-name-translated in both
  engines: pass.
- gofmt -l clean; go vet darwin, linux (-tags nogui), windows; linux and
  windows builds.
Not tried: a real account's card in the running app.
2026-10-14 12:53:09 +08:00
youheyu 7bdd3904cd tests: the cache-fields record test starts from a log of its own (#1897)
TestRecordAlwaysCarriesCacheTokens 无自己的 config 目录,-count>1(race
job 的 -count=3 同样)第二次运行会读到上一次运行写的行,在行数断言失败。
给它自己的 XDG_CONFIG_HOME(包内兄弟测试同款),每次运行从空日志开始。

验证:-count=2 修复前 FAIL(lines 持 3+ 条),修复后 -count=3 与全包
-count=1 均通过。

Reviewed and run before landing: at origin/main the test alone with
-count=2 FAILs; with the fix -count=3 ok. Siblings: the whole
internal/usage package with -count=2, and with -count=2 -shuffle=1,2,3,
all ok, so no other test in the package reads a log another run left.
2026-10-14 05:43:47 +08:00
yetone e10b7f92a1 usage: a window whose calls may have been paid from credits shows no whole (#2010, NorethSea)
Once a Codex account's window read 100% used, ChatGPT kept answering its
calls from credits; once the credits ran out the card had no Balance, so
holdsBounds let the whole-window estimate back in and counted those calls
as the subscription's. The reporter's fixture (5 hours at 100%, week at
50%, a 100k subscription call and a 900k credits call) gave routed
1000000 / whole 2000000 for the week. Claude's extra usage after a dry
window is the same case.

dryRuns builds each account's dry runs from its kept quota history plus
the card's own reading: from the last reading with some left (unknown =
zero) through the first reading of none, to the first with some again.
A window that counted a call in a run is not reckoned when the vendor
answered a call after the run's first dry reading, or when no earlier
reading with some left is known. A run where everything after the dry
reading was turned away (no credits) leaves the estimate as it was, and
a run before the window began doesn't touch it.

Run: go test -tags nogui ./internal/usage ./internal/gui (HOME sandbox),
gofmt, GOOS=linux/windows go vet. TestWindowHoldsLeavesOutCallsPaidOtherwise
goes red with the exclusion disabled (prints the reporter's 1000000 /
2000000) and with the "answered after the dry reading" condition dropped.
Not tried against a real account that spent credits.
2026-10-14 04:32:01 +08:00
yetone 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.
2026-10-13 18:17:47 +08:00
yetone ea1ba22c32 gateway, gui: Codex's composer predictions go where Settings › General says, Off among them (#1970)
pluo's Usage view showed Codex calls of kind composer_predictions at
133k-231k tokens each with no cache read: ChatGPT.app's Codex guesses the
user's next message with a hidden turn on a fork of the thread, on the
thread's own model, reading the whole conversation again each time. It
asks only when the thread's provider is "openai", so through Codex's own
ChatGPT sign-in (and a custom table pointed at magpie). The app's bundle
(fge) asks for {suggestion: string|null} and uses b.suggestion||null.

What changed:
- settings.CodexPredictions: "" as Codex sends it, "off", or a model id
  (provider/model, group/<id>); anything else is refused on load.
- gateway: codexPredictionsTo + codexPrediction, wired beside the
  descriptions at both entrypoints (gateway.go and codex_backend.go).
  Off answers {"suggestion":null} from magpie and sends nothing (the
  title Off path made generic as sentNowhere). A model's answer goes back
  only as the object Codex asked for (predictionJSON: think tags and code
  fences stripped, suggestion trimmed, blank = null). Plain text is never
  taken as a suggestion, since Codex would put it in the user's composer
  as their next message; it gives null and is recorded as a failure
  ("prediction: ...").
- usage: purpose "Prediction" for composer_predictions (purposes.js
  regenerated).
- gui: POST /api/settings/codex-predictions, kept by the general save;
  Settings › General row "Codex composer predictions" (Codex's own / Off /
  magpie's models, the app's picker), hidden in gateway mode; Routing's
  story for the kind says Codex's own switch (Settings › General › Show
  predictions) and magpie's. i18n in zh, zh-TW, ja, de.
- docs: gateway-routing.md's Codex section, reference.md's gateway-mode
  list. site/ docs left for the owner.

What was run:
- go test -tags nogui ./internal/gateway/ (full, -timeout 40m),
  ./internal/gui/ ./internal/settings/ ./internal/usage/: pass.
  New: TestCodexPredictionsSetting (default to ChatGPT, off sent nowhere,
  model routed, plain turn untouched, ledger kinds), TestNoPrediction,
  TestCodexPredictionOnMagpie (/v1/responses and the backend path),
  TestPredictionJSON; gui TestCodexPredictionsSetting.
- Broken by hand, each went red: backend wiring removed; plain text
  accepted as a suggestion; the general save not keeping the setting;
  the Routing story's kind check.
- Playwright codex-predictions.test.cjs: chromium + webkit, 1100 and 420
  wide, en/zh/zh-TW/ja/de (20 pass). routing-kind (with the new kind),
  codex-descriptions, codex-titles, i18n-keys, gateway-mode,
  purpose-filter, routing-purpose-state, settings-general,
  settings-sections, settings-search: pass.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows.

Not tried: the real ChatGPT.app's predictions against magpie (the
feature is gated server-side by /wham/predictions/config and isn't on for
the owner's account); the reply shape is from the app's bundle.
2026-10-13 17:23:00 +08:00
yetone 5e30d58fe4 usage: a request's row says the upstream's own stop reason on the Requests page, in /v1/magpie/usage/requests and in the CSV (#1927, Gluxggg)
What changed: the gateway has recorded why the upstream said each reply
ended (Record.Stop: a Responses reply's "completed", Chat's "stop" or
"tool_calls", Anthropic's "end_turn") since c5b57b907, and the Requests
page has a line for it ("Upstream stop reason"). But the page, and
/v1/magpie/usage/requests, read their rows from the packed row cache
(rowChunk), whose list of a row's strings (rowText) never had Stop: every
row came back with it empty, so the line never showed and the API row had
no "stop". rowText now carries it (packedRow.Text grows; the cache is in
memory only, so nothing on disk changes shape). The CSV export gets it
too, as a last column, upstream_stop, after 30869e35a's tier columns.

The same gap, a sibling: 30869e35a (#1784) added TierAsked, TierSent
and TierServed to Record, also without rowText, so the API's rows had
them empty too. They are in rowText now, and TestRowTextHoldsEveryString
sets every string of a Record (but Computer, the chunk's; Source, the
row's own; and the unlogged bodies), packs and unpacks the row, and
names any that came back empty, so the next field added can't be lost
the same way.

Why: #1927 asks whether a /v1/responses reply that ended in
response.completed with no tool call was the upstream's own end or one
magpie made up. In a Responses-to-Responses relay magpie writes no
terminal event of its own (a stream with none ends in response.failed,
#370), and the row's stop reason is the field that shows what the upstream
said; it was recorded in usage.jsonl and lost on the way to every reader.

Run: TestRequestPageKeepsUpstreamStop (the reporter's row, through
Append and QueryPage twice, cached; the packed chunk round trip; the CSV
column) fails with rowText put back ("the upstream's stop reason was
dropped from the page's row") and with the CSV cell left empty ("CSV"),
passes with the change. TestRowTextHoldsEveryString fails with
TierServed left out ("Record.TierServed comes back from the packed row
as \"\""). TestLedger* updated for the new column. go test
-tags nogui ./internal/usage/ ./internal/cli/ ok. gofmt, vets and the
gateway suite: in the series' last push record below.
2026-10-13 16:34:59 +08:00
yetone 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.
2026-10-13 14:22:53 +08:00
yetone 087985c778 usage, gui: a Codex turn of one call too short to time tells its whole-turn floor only at 1,000 tokens or more, as Claude Code's does (Fallmonkey on Discord)
Fallmonkey's report: an 11-token gpt-6-astra answer in 2.75 s, too short
after its first token to be measured, showed "≥4 tok/s" from the
whole-turn fallback (def3a41e3), while an 815-token Claude Code reply,
told by the same formula (all output over the whole time, the wait for the
first token in it), showed nothing, because that floor needs 1,000 tokens.
The gate now follows the formula: a Codex turn of one call that is neither
measured nor tells its answer's floor (the answer over the time after the
first token, still held to 1 s and 100 tokens) tells its output over the
whole turn only when that is 1,000 tokens or more over a second or more,
the rule every other whole-time floor has (Row.Floor; app.js ledFloor_).
Under that, the wait is too much of the time to tell anything.

Changed: internal/usage/ledger.go (Row.Floor drops the Codex-only
any-size fallback and falls through to the shared 1,000-token rule),
internal/gui/assets/app.js (ledFloor_ the same), docs/reference.md.

Tests:
- TestCodexWholeTurnFloorNeedsAThousandTokens (new): Fallmonkey's 11
  tokens in 2.75 s tell no floor, as Claude Code's 815 in 18 s; 1,000 in
  12 s tell one for both. TestCodexRowsTellAFloor and
  TestCodexTurnMeasuredOnlyOverASecondAndAHundredTokens updated (380 in
  7 s, 496/224 in 11 s, 60, 99, 400 tokens now tell none; 1,200 and 1,300
  token one-push turns and a 1,000-token one at 999 ms still do).
  With the old ledger.go: FAIL, "astra's 11 tokens over 2.75 s: floor
  11/2750 ms, want none", and 8 more cases in the two older tests.
- usage-speed-count.test.cjs: the 496-token and 380-token rows and
  Fallmonkey's 11-token astra row show "—", a 1,200-token one-push turn
  "≥120 tok/s" with the whole-turn tooltip; in en, zh, zh-TW, ja, de at
  five widths. With the old app.js: FAIL "496 tokens over the whole turn
  tell nothing".

Ran: go test -tags nogui ./internal/usage; gofmt -l; go vet (darwin,
GOOS=linux -tags nogui, GOOS=windows) on internal/usage; GUI suites
usage-speed-count, reasoning-speed, usage-ledger-detail, usage-ledger-fit,
usage-ledger, usage-session-speed, usage-speed, usage-sum-whole,
panel-usage, i18n-keys in Chromium and WebKit. No strings changed. Not
tried on Fallmonkey's own session files.
2026-10-13 12:08:10 +08:00
congee949 b6831d83e1 gateway, gui: Codex's thread descriptions go to a model picked in Settings, apart from its titles (#1198, congee949)
Codex asks its own model, through its ChatGPT sign-in, for each thread's
description (thread_description), even while the conversation runs on
magpie's models. Settings › General gets "Codex thread descriptions"
beside "Codex thread titles". It defaults to Codex's own, which sends the
request as Codex sent it, or it can name one of magpie's models or a
routing group. The answer is wrapped as description-only JSON. The titles
setting is untouched. Usage and Routing show these requests under their
own Description purpose. The setting is kept across unrelated Settings
saves. There is no Off yet, because Codex's handling of an empty
description hasn't been checked. This is a first slice of #742.

Squashed from the PR and merged onto current main. Conflicts resolved:
- codex_backend.go: the description branch comes after the title branch,
  ahead of main's subagent pick.
- gateway.go: main's CC Switch #1301 comment above the compaction block is
  kept; the PR had shortened it.
- app.js: the gateway-mode list of hidden rows takes the new row.
- i18n.js and settings_keep_test.go: both sides kept.
- purposes.js: regenerated with go generate ./internal/usage.

Run on the merged tree:
- gofmt -l is clean.
- go vet passes on darwin, linux -tags nogui and windows; the builds on
  all three succeed.
- go test -tags nogui passes for ./internal/gateway, ./internal/gui,
  ./internal/settings and ./internal/usage.
- GUI, chromium and webkit: codex-titles, gateway-mode, purpose-filter,
  routing-purpose-state, gui-de, gui-ja, gui-zh-tw, i18n-keys,
  settings-general/-groups/-sections/-search and click-scroll: 118/118.

Broken by hand: with the description branch removed from codexBackend and
handle, TestCodexDescriptionsSetting, TestCodexDescriptionFallbackOnMagpie
and TestNoDescription fail.

Not tried: a real Codex thread_description request, and whether Codex's
sidebar takes the answer.
2026-10-13 10:13:15 +08:00
yetoneandMonkeyLeeT dfbe001ff9 usage, gui: re-land def3a41e3, a Codex one-call turn timed only over a second and 100 tokens after its first token
2c30e5cee held def3a41e3 back "until Fallmonkey says what context it
missed". Fallmonkey answered on Discord: no objection, ship it. This
reverts the revert. app.js conflicted with aabdd6126 (larger sample
first); the resolution keeps aabdd6126's first_text_ms > 0 guard on the
reasoning check and adds back the Codex window check below it.

Run: go test -tags nogui ./internal/usage; usage-speed-count (52),
usage-speed, usage-ttft-rounding, i18n-keys green in chromium and
webkit; gofmt -l clean; go vet darwin, linux nogui, windows.

Reported-by: Fallmonkey (Discord)
Co-authored-by: MonkeyLeeT <MonkeyLeeT@users.noreply.github.com>
2026-10-13 09:10:14 +08:00
yetoneandcongee949 8179ce768f usage: a test that a row's own cost and its hidden reasoning are read back apart (#1463, #1874)
#1874 (d4c2512d2) gave the packed row's Flags bit 256 to rowOwnCost
while the #1463 rebase gave the same bit to rowReasoningHidden; the
rebase onto it moved rowReasoningHidden to 512. With both on 256 a
reported call that said its cost read back as hidden reasoning (its
speed dropped) and every hidden-reasoning row as having said its own
cost. TestRowFlagsApart checks both rows raw, priced and packed, and
that no Flags bit is used twice.

Run: go test -tags nogui -count=1 ./... ok on macOS at this head
(rebased on d4c2512d2); gofmt and vet clean.
Broken by hand: rowReasoningHidden back to 256 turns both subtests
and the bit check red.

Co-authored-by: congee949 <c86474321@gmail.com>
2026-10-13 06:52:42 +08:00
yetoneandcongee949 296b63f8d6 usage, gateway: tests for the #1463 rebase: a priced row keeps its reasoning evidence, and a summary after an endpoint fallback stays hidden
Follow-up to congee949's rebased dfc24632
(#1463, streamed reasoning speed).

- TestPricedRowKeepsReasoningEvidence: the Requests page reads gateway rows
  through blockPricer, which sets swapKnown (64) on every row. The patch
  put ReasoningHidden on bit 64 too; on main that would have read every
  priced row as hidden, so a tool-only reply with no reasoning, and paced
  visible reasoning, lost their speed on the Requests tab. The rebase gave
  ReasoningHidden its own bit (256, Flags widened to uint16); this test
  prices visible, tool-only and hidden rows, raw and packed, and checks
  the flag and the speed read back.
- TestSummaryAfterEndpointFallbackStaysHidden: a Messages client, a model
  answered on /responses after /chat/completions said it isn't served
  there. call.To still reads Chat, so hidesReasoning(call.To) doesn't see
  the summary; only streamTranslated's summaryUpstream marking does. With
  no reasoning count the 1500 output tokens were otherwise timed from the
  first summary delta. Nothing covered that marking before.
- reasoning-speed.test.cjs: the "no reasoning: 500 in 5 s" comment had
  been joined onto the redacted row; put back on its own row.
- docs/subsystems/gui-shell.md: the flag bit, the fallback marking, the
  two tests.

Run: go test -tags nogui -count=1 ./internal/usage/ and the gateway's
reasoning tests; reasoning-speed.test.cjs in Chromium and WebKit (en, zh,
zh-TW, ja, de), 10/10.
Broken by hand: rowReasoningHidden = 64 turns TestPricedRowKeepsReasoningEvidence
red (visible and tool-only rows read hidden, 0 tok/s); summaryUpstream
forced false turns TestSummaryAfterEndpointFallbackStaysHidden red (1500
tokens in 314 ms).

Co-authored-by: congee949 <c86474321@gmail.com>
2026-10-13 06:43:50 +08:00
congee949 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.
2026-10-13 06:43:50 +08:00
yetone 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.
2026-10-13 06:32:03 +08:00
yetone 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).
2026-10-13 04:31:07 +08:00
yetone 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.

Run: gofmt -l, go vet, go test ./internal/usage.
2026-10-13 04:07:30 +08:00
yetone 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 e5b82cf38 for such a turn that reasoned (its answer over
  the time after the first token, "②") is held to the same threshold:
  827 ms after a 10.2 s first token no longer reads ≥329, as that window
  can be one push too.
- A turn that tells neither tells its output over the whole turn
  (Row.Floor, ledFloor_ "turn"), the wait in it, of any size: everything
  it wrote was written in that time, so it is a true floor. 380 tokens in
  6.8 + 0.2 s read ≥54 tok/s. Its tooltip says the whole turn was used and
  why, with the time after the first token (new string in en, zh, zh-TW,
  ja, de).

Gateway rows and other agents' rows keep DecodeOf as before; Codex calls
in turns of several keep the 1,000-token rule. The ledger's period sum
now adds each row after it is built (Totals.addFrom) so it uses
Row.Decode too. docs/reference.md says the rule.

Tests: TestCodexTurnMeasuredOnlyOverASecondAndAHundredTokens (new: 380
over 0.2 s after 6.8 s, 60 over 2 s, the 1 s/100 edges, gateway and
Claude rows unchanged, group, ledgerWith sum, Part) and
TestCodexRowsTellAFloor (updated cases) fail on the old ledger.go and
usage.go; the sum check fails with only the ledger closure reverted.
usage-speed-count.test.cjs: the 496/224 row now ≥45 with the whole-turn
tooltip, a 1,000-token answer over 10 s ≥100, Fallmonkey's row ≥54;
fails on the old app.js.

Ran: go test -tags nogui ./internal/usage ./internal/gui ./internal/cli;
gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
internal/usage and internal/gui; 50 GUI suites (usage-*, ledger-*,
reasoning-speed, routing-burst-speed, routing-request-metrics,
panel-usage, gui-de/ja/zh-tw, i18n-keys) in Chromium and WebKit: 506/507,
the one red usage-sum-whole chromium ja at 780px under load, reproduced
on origin/main 5c82e6880 and filed as #1864. On copies of the owner's
recent Codex rollouts (955 calls), 2 were turns of one call; one, 13
tokens 315 ms after a 4.3 s first token, moves from 41 tok/s to a floor.
Not tried with Fallmonkey's own sessions.
2026-10-13 03:51:38 +08:00
yetone 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.
2026-10-13 01:41:50 +08:00
yetone 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.
2026-10-13 01:41:50 +08:00
yetone ee20a1511b gateway: the package's tests wait ~42s less for queues and OTel exports (#1654)
internal/gateway hit go test's default 10m timeout under a full ./... on
a loaded Mac. go test -json timed its 1583 top-level tests at ~306s
summed (they run one after another); the slowest few waited on real
clocks for things the tests don't check.

- TestQueuedStreamFailureIsTheStreamsError (27s -> 0.3s): it queued for
  room in a 3s minute (MaxRPM 1), and each of the vendor's two retries
  waited a minute more, 9s a protocol. It now queues for a slot
  (MaxConcurrency 1, freed once the agent has heard a keepalive), which
  goes through the same keepQueued, queuedAlive and watch around the
  attempt, so its retries go at once. The assertions are unchanged.
- TestQueuedStreamKeptAliveOnceSentToItsVendor (15s -> 7.6s): the same
  slot instead of a 4s minute; keepHeldAfter 1.5s, keepalive 100ms and
  the vendor's 1s quiet stay. With the h.alive.sent clause in
  holdWriter.watch removed by hand it goes red on all three protocols
  ("wrote nothing ... between the vendor being asked and its answer").
- TestQueuedStreamKeptAliveForTheMinute keeps the MaxRPM queue.
- A shared holdSlot helper holds the slot; it frees itself after 5s and
  in cleanup, so a test that hears nothing fails instead of hanging.
- usage.OTelEvery / OTelSessionsEvery (5s / 2s, read once when StartOTel
  starts an exporter) replace the hard-coded tickers; the gateway's OTel
  tests set them to 200ms / 50ms through fastOTel.
  TestOTelClaudeMainAndChildDedupRetainsHelper 10s -> 4.5s (the rest is
  sessions' 2s settle before a Claude transcript counts as finished),
  TestOTelSessionDedupOnlyUnkeyedLoopback 2.25s -> 0.4s. Production
  intervals are unchanged.

Not cut: TestPluginStreamLargeReplies (22s, 24MB throttled at 3MB/s),
TestPluginStreamLongActiveReader (16s, sized to outlast a 10s stall
window the plugin host dropped in c38728145), TestLargeRequestEndpoints
(16s, a 64MB body the gateway parses many times over - product speed,
not test waits), and the many 1-3s tests.

Run: go test -count=3 -run 'TestQueued|TestOTel' ./internal/gateway (ok),
-race -count=2 of the same (ok), go test ./internal/usage (ok);
go test -count=1 -json ./internal/gateway: tests summed 305.9s before,
the changed ones ~41.6s less after; the whole run took 330.6s at load
average ~125 against 306.7s for the baseline, other tests slowing under
that load (e.g. TestWarmClaudeSaysWhyNot 0.26s -> 5.3s). gofmt -l clean;
GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway
./internal/usage clean.
2026-10-12 01:16:36 +08:00
yetone 11d1d5d208 usage: a model asked for at a window (grok-4.7@500k) and answered under its plain name is no longer marked swapped (#1645, ggbdpq)
magpie offers some models at a window beside their default, spelled as
<model>@<size>: grok-4.7@500k, and Cursor's grok-4.7@256k. The vendor
answers under the plain name. bareModel left the @500k in place, so
Swapped marked every such request as answered by another model.

What changed: bareModel now drops a trailing @<digits>[k|m], right after
the [1m] tail Claude Code writes, using the reporter's regexp. Another
version or variant answered for a windowed id is still a swap.

What was run:
- TestSwappedGrokWindowID uses the reporter's cases.
- It is red with the new line commented out (all five same-model cases
  fail) and green with it.
- go test -tags nogui ./internal/usage/ is green.
- gofmt -l and go vet are clean on darwin, linux and windows.

Not tried against real SuperGrok traffic.
2026-10-12 00:44:47 +08:00
yetone 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.
2026-10-12 00:22:49 +08:00
yetone 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.
2026-10-11 20:58:56 +08:00
yetone 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 de1ba9f12: all ok
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on ., the
  usage, usageapi, tui, gateway and gui packages: clean.
- Playwright ledger-retried.test.cjs, Chromium and WebKit, en zh zh-TW ja
  de, 420 and 1100 wide: 20/20 (German first failed on the cut-off line,
  fixed by letting the button lines wrap). usage-*, api-key-usage,
  purpose-filter (Failed is now the 2nd of 3 options), panel-usage,
  click-scroll, request-archive-usage, both engines: all green except
  purpose-filter's Routing case (1px focus scroll), which fails the same
  on 909d76747 and de1ba9f12, in Chromium too; it is #1291 (commented)
2026-10-11 12:58:03 +08:00
yetone 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 e6dd5d20b fixed). Instead the answer, its output less the reasoning,
which all came after the first token, over that time: 329, a true floor
of the answer's speed. Any size tells one, as the wait isn't in it;
DecodeWindow's bounds still hold. The Requests row's tooltip says so, and
a group's floor tooltip now says the file doesn't say when the answer
began, true of both kinds, in en, zh, zh-TW, ja and de.

The 1,000-token rule stays (Fallmonkey asked for 5 s instead): it bounds
the share of the time the wait for the first token can be, which a
duration doesn't (a 5 s reply can be 4 s of wait). On the owner's
gateway rows, where both are known, a floor of 1,000 tokens or more read
0.40 of the measured speed (n=25), one of 5 s or more 0.18 (n=550). The
reason is in Row.Floor's comment and docs/reference.md.

Tests: TestCodexRowsTellAFloor (new) and TestGroupSpeedSaysHowManyRepliesItIsOf
(sol's 259 calls in turns of several now tell 259 floors at 50) fail on
the old ledger.go. usage-speed-count.test.cjs gains a turn-of-several row
(≥50) and the 496/224 row (≥329, its tooltip) and fails on the old app.js;
usage-session-speed.test.cjs's Codex row now tells its floor.

Ran: go test ./internal/usage ./internal/gui; usage-speed-count,
usage-session-speed, usage-ledger-detail, usage-speed, reasoning-speed,
usage-ledger-fit, usage-model-at-provider, routing-request-metrics,
gui-ja, gui-de, gui-zh-tw and i18n-keys in Chromium and WebKit, at 1400
and 560 px; gofmt -l; GOOS=linux/windows go vet.
2026-10-11 12:49:27 +08:00
yetone 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
0192edf1, showed none. Asked for one rule for every source: measured
replies give "N tok/s (k)", only floors give "≥N tok/s (k)", neither
gives nothing.

usage.Totals now counts DecodeN, the replies its DecodeMs/DecodeOut are
of (add and addRow), and FloorOut/FloorMs/FloorN, the floors of rows read
from Claude Code's and Claude Desktop's session files (Row.Floor, the
same rule as app.js's ledFloorSpeed: source "log", not failed, no
measured speed, 1,000+ tokens over 1 s+, under 10,000 tok/s). Floors are
never in Speed(); the Speed trend and `magpie usage` are unchanged.
app.js's ledGroupSpeed applies the rule to the ranking's rows (main page
and tray panel; the "Other" row sums the new fields), the Output speed
card and the overview's agent/model lists, with a tooltip saying which
it is and how many replies; a ranking by speed orders and bars a
floor-only group by its floor. Strings in en, zh, zh-TW, ja, de;
docs/reference.md says the rule.

Run: TestGroupSpeedSaysHowManyRepliesItIsOf (sol 260 calls, 1 measured
at 125 tok/s; Claude Code 42 calls, 30 floors at 100, a short, a failed
and a gateway row telling none; the page sums; summarize) fails to build
on the old code and goes red with the agent check taken out of
Row.Floor. usage-speed-count.test.cjs (overview, Requests rows, ranking
by tokens and by speed with order, titles and bars, the card for all and
for Claude Code's model alone, no clipping, no sideways scroll) passes in
Chromium and WebKit, en/zh/zh-TW/ja/de at 1400 and 560 px, and fails
against origin/main's assets. Related GUI suites (click-scroll, gui-de,
gui-ja, gui-zh-tw, i18n-keys, ledger-*, panel-usage, reasoning-speed,
routing-burst-speed, usage-*): 389/389 in both engines. go test -tags
nogui ./... (temp HOME) passes; gofmt -l clean; go vet nogui for darwin,
linux and windows on internal/usage and internal/gui. Not tried with
Fallmonkey's own data.
2026-10-11 10:04:15 +08:00
yetone 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.
2026-10-11 04:44:13 +08:00
yetone d5bb1a2b13 catalog: a model its vendor lists under another id is priced by its canonical_model_id (#1520, liuweifeng)
workbuddy/deepseek-v4.1-flash had no price in `magpie model price`, the
Usage page or the ledger. models.dev's DeepSeek catalog has no
deepseek-v4.1-flash: it sells V4.1 Flash as deepseek-flash (and the
deprecated deepseek-v4-flash, deepseek-v4-flash-vision-exp), each with
canonical_model_id deepseek/deepseek-v4.1-flash. magpie never read that
field, and #1498's served fallback can't help since the reply names the
model as asked.

PricedBy, which every price path goes through (ListPrice, MakerPrice,
EffectivePrice and so the CLI, ledger, Usage page, routing cost, session
totals), now asks last, after every id spelling and before a relay's
rename: an entry whose canonical names the asked id. Scoped so nothing
priced today changes:
- only an entry whose canonical's maker is the catalog listing it
  (deepseek's own alias), never a reseller's: OpenCode's
  mimo-v2.6-flash-free ($0), Baseten's DeepSeek V4.1 Flash Fast (2x),
  Neuralwatt's -flex all name a model they are a variant of;
- never a $0 entry (NVIDIA's own nemotron-ultra-253b-v1);
- several entries under one canonical at different prices price none.

Run: against models.dev api.json of 2026-10-10, PricedBy over every
canonical id (448) for the maker list and each of the 150+ catalogs, old
vs new: no price changed or lost; 12 newly priced, all maker lists:
deepseek-v4.1-flash, deepseek-v4-pro-0813, gpt-5.6-cyber and three
ministral-3-*-instruct-2512. Built binary in a sandbox HOME with that
catalog: `model price <relay>/deepseek-v4.1-flash` "no price" -> $0.15/$0.6,
cache read $0.003; deepseek-v4-pro, claude-opus-4-6, openrouter's
unchanged; hy3 still unpriced (tencent is no maker preset).
Tests (fixtures are models.dev's literal bytes): TestPricedByCanonicalID
and TestLedgerPricesAModelListedUnderItsCanonicalID (the reporter's
record) fail on the old code; maker scope, $0 guard, two-price guard and
listed-before-canonical order each broken by hand turn a test red.
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on
internal/catalog, internal/usage; go test -tags nogui ./internal/catalog
./internal/usage pass; go test -tags nogui ./... green (47 packages)
after rebasing on cc2092a4b.
2026-10-11 00:35:29 +08:00
yetone 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.
2026-10-10 20:47:00 +08:00
yetone f3fa5a53ce usage: a relay's rename answered under the model's own name is not marked as another model swapped in (#1498, liuweifeng)
relay-a/moonshot-kimi-k3 answered as kimi-k3 was marked swapped in the
ledger, the CSV and the Routing trace, though it is the model asked for
under the relay's own name. The same held for #1383's
claude-deepseek-v4.1-flash answered as deepseek-v4.1-flash.

RelayRenamed: sent is served's own name (after bareModel, separators
squashed) with a relay's word and a hyphen in front; Swapped no longer
counts it, and a row kept marked swapped is read back as not swapped, as
SameSpelled rows are. What is left must have a digit and a letter, so a
bare word ("flash", "mini") is never taken for the model sent; another
version behind a relay's word (kimi-k2) is still a swap, and so is the
reverse (kimi-k3 answered as moonshot-kimi-k3).

Run: TestSwappedIgnoresARelaysRename, TestKeptRowRelayRenamedNotSwapped
(both red with RelayRenamed forced false), go test -tags nogui
./internal/usage, gateway tests. Sandbox magpie with the reporter's
record: `usage --csv` swapped false (true before). gofmt -l,
GOOS=linux/windows go vet clean.
2026-10-10 19:55:29 +08:00
yetone 34a6576cc4 usage: a relay-renamed model with no price is counted at the price of the model its reply said answered (#1498, liuweifeng)
A relay that sells kimi-k3 as moonshot-kimi-k3 answers as kimi-k3, and the
record keeps that as served, but the ledger priced only Record.Model, so
every such call showed "no price" and counted $0 although
relay-a/kimi-k3 has one ($3/$15, cache $0.3/$3 from models.dev).

pricer (which the ledger, the request page, sessions totals, OTel and
NewCoster all use) now falls back to EffectivePriceIn(provider, served)
when the model asked for has no price. The model asked for keeps its own
price whenever it has one, a zero set by the user included, so a ledger
that matched a vendor's bill still does; the served name is only used
where there was nothing. The cache key includes served. Documented
beside `magpie model price` in docs/reference.md.

Run: TestLedgerPricesARenamedModelAsTheOneServed (the reporter's record
byte for byte: priced at $0.0916398; a priced model keeps its own; a
user's 0 stays 0; a model priced by neither name stays unpriced), red on
the old pricer; go test -tags nogui ./internal/usage. Built magpie in a
sandbox HOME with the real models.dev cache and a relay-a custom
provider, the reporter's record in usage.jsonl: `magpie usage today`
shows "≈$0.092" where the old build shows "no price", and `usage --csv`
cost_usd 0.091640. gofmt -l, GOOS=linux/windows go vet clean.
2026-10-10 19:55:29 +08:00
yetone 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.
2026-10-10 19:15:12 +08:00
yetone cb406c8425 plugins: a plugin can add an agent magpie has no setup of its own for
Plugins could be subscription providers or gateway middleware. Now a third
kind: an agent plugin, so a user whose agent magpie doesn't ship can still
put it on magpie.

- internal/agentplug: a plugin's magpie.agent module (or a *.agent.js file)
  exports agent = {id, name, config, format?, model, prefix?, bin?, dir?,
  ua?, icon?, notice?} and an optional connect({gateway, model, models,
  agent}) returning the other keys to write. Compiled in moejs, reloaded
  when plugins.json or the file changes; why one didn't load is kept.
- internal/jsmod: module compiling (imports kept inside the plugin), moved
  out of middleware so both share it.
- internal/agent/plugged.go: each becomes an Agent (Plugin set) after
  magpie's own. JSON, YAML and env files are edited key by key, comments
  kept; what each key held is stashed typed under plugin:<id>:<path>, and
  its own model or Disconnect puts every key back. A built-in id is
  refused; a connect that throws writes nothing. Key magpie-<id>; usage
  names it by key or ua (usage.PluginAgents).
- GUI Plugins page: an Agent kind chip and glyph, a Discover "Agents"
  section (market kind "agent"), and an installed row line "Adds X to
  Agents" or why it didn't load. zh, zh-TW, ja, de strings.
- Docs: site Plugins page (en, zh, ja) "Agent plugins", reference.md,
  agent-wiring.md, gateway-middleware.md.

Run:
- go test ./... (all ok); gofmt -l clean; GOOS=linux go vet -tags nogui
  ./... and GOOS=windows go vet ./... clean.
- TestPluggedYAML, TestPluggedJSONUnwire, TestPluggedRefused.
- GUI: plugin-agent.test.cjs 22/22 (en, zh, zh-TW, ja, de; 980 and 420;
  chromium and webkit); all plugin-*.test.cjs, i18n-keys,
  deprecated-subscriptions, filter-ime: 315 pass, 0 fail.
- Real use, in a sandbox HOME: an Aider plugin (~/.aider.conf.yml, prefix
  openai/, connect writes openai-api-base/key) installed in a dev build;
  picking DeepSeek V4.1 Flash on the Agents page wired the file keeping the
  user's comment and keys; real aider 0.86.2 `--message` answered through
  magpie from the real DeepSeek account; usage.jsonl recorded agent aider,
  provider deepseek, 200; Disconnect restored the file byte for byte.
2026-10-10 18:39:47 +08:00
yetone 18d87fc51a usage: grok-4.7 answered as grok-4.7-build is the model asked for, not a swap (#1455, cybershape)
xAI answers a request for grok-4.7 with model grok-4.7-build (the
reporter's requests log; two relays' notes say the same for grok-4.6 ->
grok-4.6-build). Its own list (SuperGrok's, cached 2026-10-02) offers
grok-4.7 and grok-4.7-build-fast and no grok-4.7-build to ask for, so the
-build name is xAI's name for the build serving the model.

GrokServing reads past "-build" after a Grok model's version and joins
GeminiServing under ServingName, which Swapped, a kept requests-log row and
a kept route's try all use. Only names starting with grok count, and only
the same variant: grok-4.7 answered by grok-4.7-build-fast, grok-4.6-build
or grok-4.7-mini is still a swap, as is gpt-5 answered as gpt-5-build.

Run:
- TestSwappedGrokServingName, TestKeptRowGrokServingNameNotSwapped,
  TestRouteKeptGrokServingNameNotSwapped (new). With ServingName reduced to
  GeminiServing the usage tests fail ("grok-4.7 answered as grok-4.7-build
  is the model asked for", "serving name true, fast variant true").
- go test -tags nogui ./internal/agent ./internal/usage ./internal/gateway
  ok; gofmt -l clean; go vet for darwin, linux, windows clean.
- Not tried against xAI itself: no request was sent from the owner's Grok
  account; the served name is the reporter's.
2026-10-10 18:10:18 +08:00
yetoneandggbdpq 012be0fcbe usage: a Bedrock global. or us-gov. inference profile answered under its model's own id is no swap, so Claude on Bedrock's preset no longer shows as swapped (#1484, ggbdpq)
Bedrock's preset gives its Claude and GPT-6 models as global. inference
profiles (global.anthropic.claude-opus-5-5, global.openai.gpt-6-luna),
and a GovCloud account's are us-gov. ones. Bedrock's reply names the
model by its own id, as TestSwappedModel has it for us.anthropic.… .
bareModel stripped a profile's geography with vendorDot, which took two
to four letters only, so global. and us-gov. stayed on and Swapped
marked the route, its tries and the usage row as served by another
model. catalog's bedrockGeos already lists both.

vendorDot now takes global. and us-gov. too. Another model is still a
swap (global.anthropic.claude-opus-5-5 answered as claude-sonnet-5).
Rows and routes kept marked swapped before read as not swapped through
SameSpelled, which uses the same bareModel.

Run: TestBedrockProfileAnsweredByItsModelIsNoSwap fails on the old
served.go (Swapped true for four global./us-gov. pairs; route and usage
row marked swapped through the Bedrock preset to a fake runtime) and
passes with the change; go test -tags nogui ./internal/usage
./internal/gateway green under a temp HOME; gofmt -l clean; GOOS=linux
and GOOS=windows go vet -tags nogui on both packages. Not tried against
a real Bedrock account.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-10 17:58:07 +08:00
yetone 3e5bc3d8fe gateway, usage: conversation text is kept only under a session the client named, and a client's "request-…" session counts like any other (#1355)
What changed: with recording on, a request that names no session used to
get a made-up "request-…" id and its text saved under it. Nothing listed
that id and GatewaySessionByID turned it away, so the text could never be
opened. magpie now makes up no id: such a request isn't recorded, and the
X-Magpie-Session reply header only echoes the client's own session.

With no made-up ids left, the "request-" prefix checks in appendUsage,
OTel, Usage's sessions, Routing's vias and the gateway Sessions projection
only dropped sessions clients named themselves (appendUsage wiped them from
the ledger). They are gone. The tests that held the old rule now say the
new one, and gateway-sessions.md says it.

Run: TestGatewayConversationNeedsTheClientsSession and
TestGatewayConversationClientRequestPrefixedSession fail on the PR's code
(a made-up id is returned; the ledger keeps 0 of 2 calls) and pass here;
putting appendUsage's prefix check back turns the second red again.
gofmt -l clean; go vet; GOOS=linux and GOOS=windows go vet -tags nogui on
gateway, gui, sessions, settings, usage; go test -race -timeout 900s on
those five: ok (gateway's TestCORSKeyThroughTheServer rerun after its fix).
GUI: gateway-conversations, gateway-mode and all sessions-* tests, 216
cases in Chromium and WebKit: pass.
2026-10-10 04:24:18 +08:00
木子不是木子狸 c9b8263378 sessions, gateway: Sessions lists gateway sessions, and can keep their text on this computer when turned on (#1355, mu-zi-lee)
What changed: the Sessions page lists sessions seen only through the
gateway (from the usage ledger, read-only, a native session of the same id
wins), and shows in gateway mode. A Sessions switch, off by default and
confirmed before it turns on, records each gateway exchange's text under
the config dir (scrubbed, at most 7 days and 256 MiB, cleaned hourly).
Settings sync and restore can't turn it on; POST /api/sessions/recording
turns it on or off and can clear what was kept.

Why: users of magpie as a gateway (gateway mode, LAN clients) had no way
to see their conversations; the owner chose this design on the PR.

Squashed from PR head 6a343ba1 onto origin/main. Conflicts: gui-shell.md
(kept main's placeMenu text, took the PR's Sessions in gateway mode) and
settings_keep_test.go (main's fields plus GatewayConversations).

Run: go build ./..., go vet on gateway, gui, sessions, settings, usage;
go test -race -timeout 900s on those five packages: all ok.
2026-10-10 04:24:18 +08:00
yetone ee657c0969 usage: a Kimi Code membership's k3 is counted at Kimi's API price for kimi-k3, not ≈¥0.000, and kimi-for-coding is unpriced rather than free (#1370, maicent: Kimi Code 的模型计费都是 0)
Why it was 0: magpie already counts a subscription's calls at the API list
price (a Claude or Codex account at its maker's, cf6b82f7). A Kimi Code
provider is looked up in its own models.dev catalog first, and models.dev
lists every model of kimi-code-plan-global / kimi-code-plan-cn at $0 (what
the membership charges per token), so k3, k3-256k, kimi-for-coding and
kimi-for-coding-highspeed were all "priced" at $0. The same $0 catalogs
were also among the maker catalogs, so MakerPrice("k3") was $0 too.

What changed (internal/provider/models.go):
- membershipCatalogs (the two Kimi Code plan catalogs) are never read for a
  price: ListPrice, MakerPrice and PricedName skip them.
- A provider served at a Kimi Code catalog prices its model as the Kimi API
  model it is (kimiCodeAPI), per Kimi Code's docs
  (https://www.kimi.com/code/docs/en/, read 2026-10-09): k3 and k3-256k are
  K3 -> kimi-k3; kimi-for-coding-highspeed is K2.7 Code HighSpeed ->
  kimi-k2.7-code-highspeed. models.dev's canonical_model_id agrees. The
  prices come from moonshotai's catalog, which matches Kimi's pricing page
  (https://platform.kimi.ai/docs/pricing/chat: kimi-k3 $3 in, $15 out,
  $0.30 cached, $3 cache write; kimi-k2.7-code-highspeed $1.90/$8/$0.38).
- kimi-for-coding is K2.8 Preview, which the Kimi API doesn't sell: it has
  no API price, so it is now unpriced (the "—" / "no known price" the GUI
  already shows) instead of ¥0.000. The user can give it a price with
  `magpie model price kimi-code/kimi-for-coding …` or in Names & levels.
- The alias is scoped to Kimi Code providers: a relay's own "k3" keeps its
  own catalog price; Moonshot pay-as-you-go's kimi-k3, an OpenCode free
  model ($0) and Codex's maker price are unchanged.
- PricedNameFor(provider, model): the Requests list's "API price
  reference" names kimi-k3 for a Kimi Code k3 (internal/gui/usage.go).
Docs: reference.md (What a model costs) and providers-accounts.md.

Tests: TestKimiCodeListPrice (internal/provider; fixture
testdata/kimi_code_catalog.json is models.dev's own moonshotai and Kimi Code
plan entries) and TestKimiCodeCost (internal/usage; the reporter's k3 row,
240K in / 78.4K out / 10.0M cached, counted at $4.896 in the ledger and the
summary, kimi-for-coding unpriced, moonshot/kimi-k3 unchanged). Both fail on
the old models.go (every Kimi Code model priced at $0, MakerPrice(k3) $0,
k3 cost=0, unpriced 0); PricedNameFor's check fails with the alias turned
off ("k3-256k").

Run: gofmt -l (empty); go vet -tags nogui, GOOS=linux go vet -tags nogui,
GOOS=windows go vet -tags nogui on internal/provider, internal/usage,
internal/gui; go build, GOOS=linux go build -tags nogui, GOOS=windows go
build; go test -tags nogui -count=1 ./... under a temp HOME with pinned
caches: all ok; -race -count=3 on the new tests ok. No GUI asset changed,
so the Playwright suite wasn't run. Not tried with a real Kimi Code
account or the reporter's usage log.
2026-10-09 11:48:41 +08:00
yetone d1d4b7ed2a usage: a heatmap of the last 53 weeks on the Requests tab, by tokens, requests or cost (#1369, nianlee-official)
What changed: the Requests tab of the Usage page shows a heatmap card like
CC Switch's: a cell per day for the last 53 weeks, Monday on top, month
names over the weeks and weekday names at the edge, a Tokens / Requests /
Cost switch (kept in localStorage), a five-shade Less…More legend, and a
tip on each day with its date, tokens, requests and cost.

How: GET /api/usage/heatmap (usage.HeatmapOf) reads QueryPage's cached
request index over a hidden period, "heatmap", which starts on the Monday 52
weeks before this week's. Its rows are summed by local calendar day in both
the compact and the ledger path. So no raw log is scanned per render, and the
days count what the chart counts:
- the page's agent/provider/model/key filters, but not the period or day
  picked;
- the gateway's own rejections left out;
- cost of priced calls only, with an unpriced count.
The days are in the local time zone and the shades use theme tokens
(.l0–.l4, as in the sessions calendar). There are no left-border accents and
no native <select>. A click never scrolls the page. A narrow window scrolls
the card sideways inside itself, with the newest week in sight (kept there
as it's laid out or resized, until the reader scrolls back), and the weekday
names stay at the card's edge. The card is hidden when no day has calls. New
strings are in zh, zh-TW, ja and de.

Run:
- go test -tags nogui ./internal/usage ./internal/gui (new TestHeatmapDays,
  TestHeatmapOf, TestUsageHeatmapRoute); gofmt -l clean; go vet darwin,
  GOOS=linux and GOOS=windows go vet -tags nogui on both packages; go build
  for darwin, linux and windows.
- New internal/gui/tests/usage-heatmap.test.cjs in Chromium and WebKit, at
  420 and 1100, in en, zh, zh-TW, ja and de, plus dark and the empty case.
  It checks:
  - the cells, labels, legend and the busiest and quiet days;
  - the newest week in sight and only the card scrolling sideways;
  - the tip's text and that it stays inside the card;
  - that a metric click moves nothing and is kept;
  - that the filters, but no period or day, are sent.
- Breaking checks: with the keep-at-end guard reverted, 5 of its 11 subtests
  fail in WebKit; with the server's heatmap dropped, TestUsageHeatmapRoute
  fails.
- i18n-keys, click-scroll, gui-de, gui-ja, gui-zh-tw, sessions-usage-open
  and all usage-*.test.cjs GUI tests pass in both engines (161 each).
- A sandboxed `magpie web` (temp HOME, 2605 fake calls over 400 days, ports
  3671/3672): the card fills 369 days at 1280 and 420 wide, and the tip
  reads "2026年10月1日周四 / 2.6M token · 23 个请求 · ≈$1.05+".
2026-10-09 11:33:47 +08:00
yetone f368f709c3 test(usage): TestLogChangeTrustedAppendReuse counts the prefix it re-hashes, not an empty fingerprint (CI red on Windows since 439cfc4a)
What changed. TestLogChangeTrustedAppendReuse (Windows-only) took
`after.hash != ""` to mean "the read after a trusted append re-read the
historical prefix". Since #1357 (439cfc4a) the trusted, settled path keeps
a fingerprint without re-reading: the old snapshot's SHA-256 state is
continued over the appended lines. So the Windows "usage cache" CI step
failed with "trusted append scanned the historical prefix" while the
guarantee still held. The test now wraps logRecordHash, as
TestUsageAppendReadHashesNoPreReadScan does, and fails if the read after
the append hashes any bytes through it; it still checks the sealed blocks
are reused, and now also that the continued fingerprint equals a fresh
SHA-256 of the parsed bytes.

Verified rather than assumed: in log_index.go the trusted path skips the
prefix check (`trusted ||` short-circuits it) and the after-read check
(`!trusted || !settled`), and the parse seeks to old.off. Siblings: the
only build-tagged test in internal/usage is log_change_windows_test.go.
TestLogChangeSnapshotReuseWithoutFingerprint clears hash only to simulate
a cache hit with no fingerprint, which a change-time stamp alone still
serves; it doesn't use hash as a proxy for a re-read and passes.
incremental_log_test.go:147 asserts hash != "" on the unsettled path,
where the fingerprint is still required. Neither needed a change.

What was run. Windows 11 box (xiaomi-gpu; no Go there, so test binaries
were cross-compiled with go1.26.8 GOOS=windows and run in a scratch dir
with USERPROFILE/APPDATA/LOCALAPPDATA/TEMP redirected):
- origin/main's test, -count=5: FAIL x5 at :164 "trusted append scanned
  the historical prefix" (CI's failure reproduced).
- fixed test, -count=5: PASS x5.
- break A (continuation always re-verifies the prefix: `trusted ||`
  removed): FAIL x5 "re-hashed 143726 bytes of the 143726-byte
  historical prefix".
- break B (after-read check runs on the trusted path too): FAIL x5
  "re-hashed 143849 bytes of the 143726-byte historical prefix".
- CI's "Windows usage cache" -run set (no tags): all 11 PASS.
- whole package (-tags nogui): everything passes but
  TestDesktopSessionAccountMetadata, which fails identically with
  origin/main's binary; that is #1356, already filed, not touched here.
macOS: go test -tags nogui ./internal/usage/... ok (temp HOME, pinned
caches). gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet
-tags nogui ./internal/usage/ clean.
2026-10-09 07:20:48 +08:00
yetone 439cfc4ac4 usage: the parse is the log fingerprint, dropping the build's full re-read before it (#1357)
What changed. A usage-log snapshot's fingerprint is now produced by the
parse itself: each complete line read is fed into a SHA-256. When a build
continues the old snapshot's blocks, it continues the old snapshot's digest
too (crypto/sha256's state, kept on the snapshot as `digest`); otherwise the
digest starts fresh from byte 0 with the parse. The build's before-read
logRecordHash over the whole file is gone. The fingerprint covers the bytes
actually parsed (`off`), not info.Size(), so a half line another writer is
in the middle of appending is no longer counted as read; the unchanged
check, the prefix check and the after-read check all hash `off` bytes.

What stays, as #1328's tests require (ggbdpq's analysis on #1357): the
unsettled unchanged check, the prefix re-verification on a non-trusted
continuation, and the after-read check, which now compares the parse's own
digest against the file as it is after the read. A same-tick rewrite is
still caught at the build, not at a later read. On the trusted, settled
path nothing is re-read, as before; that snapshot now also carries a
fingerprint (the continued digest), so a later non-trusted append can
verify its prefix instead of rebuilding from byte 0.

Test changed: TestUsageRewriteBeforeFingerprintIsNotCached counted
logRecordHash calls and rewrote the file at call 1 (after the before-read
hash, before the parse) or call 2 (after the read). With the parse being
the fingerprint there is no call 1 any more, so the hash=2 case could no
longer fire. Its guarantee still holds and is still tested at both
boundaries: "before-read" rewrites at the build's first change-time look,
after its stat and before it opens and parses; "after-read" rewrites at the
after-read fingerprint check. Removing the after-read check makes
after-read fail. No other test changed.

New tests:
- TestUsageAppendReadHashesNoPreReadScan: 20,000-row settled log
  (2,760,615 bytes), 5 x Append + Summarize(Today), counts the bytes
  logRecordHash re-reads. origin/main: 7,728,984 bytes per cycle (2.80x the
  log), FAIL; this commit: 4,968,615 (1.80x), PASS. Wall time per cycle on
  an M-series Mac, 3 runs each: 3.43-3.52 ms before, 2.28-2.52 ms after
  (~32% less). The remaining two passes are the prefix check and the
  after-read check, which the same-tick guarantee needs.
- TestUsagePartialLineThenCompletion (settled and unsettled): another
  writer's half line, a read, then the line completed; the fingerprint
  covers the parsed bytes only and the completed record is counted. On
  origin/main it fails on the fingerprint check (it covered the half line).

Break checks: no after-read check -> RewriteBeforeFingerprint/after-read
fails; no prefix verification on a continuation -> SameSizeAndMtimeRewrite
append=true, SameTickRewrite append=true and LogGrowingRewriteThenAppend
fail; lines not fed into the digest -> SameTickRewrite fails.

Run: go test -tags nogui ./internal/usage/... ./internal/gateway/... (ok,
temp HOME, pinned caches, removed after); go test -race ./internal/usage/...
(ok); -race -count=10 on the rewrite/append tests (ok); gofmt -l (empty);
go vet, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage/
(ok). Not tried on Windows or Linux hardware; the change is
platform-independent hashing over the same read.
2026-10-09 06:54:28 +08:00
Ethereal49 3c629133c2 usage: refresh caches after same-tick log rewrites (#1328)
* usage: same-tick rewrites refresh cached totals and request pages

Trust change stamps only when they were settled at the snapshot read's
start. Fingerprint recent snapshots and append prefixes, and discard
fingerprint trust when the content changes during a read.

Fixes https://github.com/yetone/magpie/issues/1305

Verified: deterministic old-predicate FAIL/new PASS; usage tests with race;
nogui vet; Linux nogui and Windows builds; usage test cross-compilation for
Windows, Darwin and the unsupported-stamp fallback on FreeBSD.
Full nogui suite exposed the independent sessions TestList empty-session
limit failure. Native Linux GUI vet/build lack pkg-config and GTK/WebKit;
native Windows/NTFS execution was not run.

* usage: keep FILETIME stamp ages valid beyond UnixNano range

Convert whole seconds and the 100ns fraction separately. Checked the epoch, current dates with fractional ticks and year 2500; Windows build and usage test cross-compilation pass. Native Windows execution was not run.

* usage: keep history cached after an append settles

An unchanged log now validates a recent snapshot's nonempty fingerprint
before publishing a settled clone. Preserve its version and sealed blocks
so the summary and page caches stay warm without mutating readers' snapshots.

Follow-up to the review on https://github.com/yetone/magpie/pull/1328,
for https://github.com/yetone/magpie/issues/1305.

On e28e686, the real-clock append/read/settle/read tests fail with a
version bump and 32,428 additional allocations over 4,000 versus 10 rows.
With this change the targeted race run passes, with 165 extra allocations.
The existing performance test now measures this path on the real clock.

Verification uses Go 1.26.8, a temporary HOME and pinned Go caches.
Native Linux GUI checks require missing pkg-config/GTK/WebKit libraries;
native Windows/NTFS execution is not available. No GUI assets change.
Implementation and verification used AI assistance.

Final checks: usage race PASS (421 test results); nogui suite PASS (7,273
test results, 44 packages; 21 skipped tests, 3 packages without tests).
Nogui vet, Linux nogui build, Windows build, and usage test cross-compilation
for Windows amd64, Darwin arm64 and FreeBSD amd64 PASS. Native Linux GUI
vet/build were attempted and failed at the missing pkg-config executable.
2026-10-09 02:48:29 +08:00
yetone ed31293c0e usage, gui: a reply its vendor let go in a burst over a couple of hundred milliseconds tells no speed, not 2,237 tok/s (John on Discord)
John's Kimi Code rows after v0.1.1119 (OpenCode, group/k3-glm, api.kimi.ai,
Chat, k3-256k): 550 tokens, 22 of them reasoning, in 16 s with the first
content at 5.2 s read 2,237 tok/s, and 395 tokens in 19 s 2,012. 528 answer
tokens at 2,237 tok/s is 236 ms: the burst the vendor let go at the end.
de5455b8 measured how long the content took to come (flow) and took the
window as no longer than it, so a burst sent in one write (flow ~1 ms) fell
under the 100 ms floor and told none, but a burst let go over 236 ms of
many events read its tokens over those 236 ms, under the 10,000 tok/s
ceiling. The time a burst takes to come is not the time it took to write.

usage.DecodeOf now tells no speed for a reply held back and let go at its
end, both ways the burst can show:
- its content came in under a quarter of its window (flow*4 < window):
  the text came early, the tool call it wrote over the rest of the time
  came at the end (window 10.6 s, flow 236 ms);
- it reasoned, and its answer came over 20 times faster than its
  reasoning came between its first content and its first text: the text
  came with the burst, so the window from it is the burst itself (22
  reasoning tokens over 10.5 s, then 528 in 236 ms). Hidden reasoning
  (OpenAI's, Claude's omitted) comes before the first content and leaves
  that time short; streamed reasoning comes at its answer's pace.
Between the two the window is the whole window again, not the flow.
routing.js's decodeOf and app.js's ledDecode do the same; docs/reference.md
says it.

Tests: TestKimiHeldBurstTellsNoSpeed, a fake Kimi Code (Chat: four
reasoning_content deltas, then text and a tool call whose arguments come
as 40 writes 6 ms apart over the last 236 ms; usage 538/550/22), through
the real gateway for a Chat, a Responses and an Anthropic agent, with the
wait shortened (first content 1.3 s, end 4 s): the held call and the held
answer tell none (before: 2,112 to 2,237 tok/s on all three), a steady
50 tok/s answer after the same reasoning keeps ~50. TestKimiHeldBurstAtJohnsTimes
feeds firstToken the same streams at John's times (5.2 s, 16 s): before,
2,138 and 2,237 tok/s. TestJohnsRowsTellNoSpeed: his rows as records
(before: 2,237, 2,237, 2,015). routing-burst-speed and usage-speed gain
his rows and a steady 50 tok/s one; they fail on the old routing.js and
app.js ("2237 tok/s", "2,237 tok/s") and pass now in Chromium and WebKit,
en and zh, with reasoning-speed, routing-request-metrics,
usage-ledger-detail, click-scroll, gui-ja, gui-de and i18n-keys.

Run: go test -tags nogui ./internal/... (golang:1.26.8 in Docker, as a
non-root user: as root, internal/agent's TestAside* write-refusal tests
fail because root ignores the file modes they rely on, unrelated to this);
-race -count=5 of the new and the burst tests; go vet (linux, windows,
nogui) on internal/gateway and internal/usage. Not tried against the real
Kimi Code API: the owner's Kimi Code key answers 403 (subscription has no
access), so how Kimi Code lets the reply go is inferred from John's
numbers; which of the two shapes his rows were is not known, and both are
covered.
2026-10-09 00:10:23 +08:00
yetone de3b1c646a usage: a subscription card's window says what the whole window holds, "Whole ≈ N tokens · ≈ $X", reckoned from what magpie routed through the account since the window began over the share used, at API list prices (Chiao on Discord)
usage.WithWindowHolds fills QuotaWindow.Holds on GET /api/usage/quotas and its refresh, from usage.jsonl: the card's provider (by its id now, so a moved plugin's card and a renamed provider count), its account (ProviderAccount, or an older record's Host), calls to the models the window counts (Claude's Opus-only or Fable week), not turned away, from the window's start up to when the share was read. Priced by catalog.Price.CostSplit at the maker's list price, else the provider's own list, never the user's own subscription price: Anthropic's 5-minute and 1-hour cache writes at 1.25x and 2x input, OpenAI's cached input and no cache write price. A call with no API price leaves the window tokens-only. The caller's cards are not written to.

Not told where it wouldn't be honest: under 5% used, nothing routed in the window, magpie's log starting after the window did, no reset or no span (credits with no reset, Copilot's premium requests), Antigravity's per-model family and pool windows, Aside windows, a card with an error, a balance, or one read from another computer. The tooltip says how it was reckoned and that use of the account outside magpie makes it read low (the request said 偏高; such use raises the share without adding to what magpie saw, so the estimate is lower than the truth). en, zh, zh-TW, ja, de.

Run: go test -tags nogui ./... in Docker (golang:1.26.8): all pass but internal/agent's Aside* chmod tests, which fail only as root and pass with --user 1000. The new tests fail with the log-start check removed, the model scope removed, the caller's windows not cloned, and 1-hour cache writes at the 5-minute price. Against a read-only copy of the owner's usage.jsonl, quotas.json and models.json: Claude's week (71%) ≈ 46K tokens / $14.16 from 165 calls, its Fable week and 5 hours (12%) nothing, every other card nothing (under 5%, or no reset). New quota-holds.test.cjs passes in Chromium and WebKit at 360, 440 and 1000px in en, zh (万), zh-TW (萬), ja, de, and fails with the new CSS removed; click-scroll, gui-ja, gui-de, i18n-keys, quota-* and usage-* pass (304/304). go vet -tags nogui (darwin, GOOS=linux, GOOS=windows) and gofmt -l on the touched packages pass.
2026-10-08 20:53:03 +08:00
yetone de5455b8fe gateway, usage, gui: a reply whose vendor sent its first words and held the rest to send in one burst tells no speed, not 1,367 tok/s (John on Discord)
John's request (OpenCode, a group served by Kimi Code at api.kimi.ai,
Chat) showed 1,367 token/s: its tokens counted over the time from its
first token to its end, though nothing came in between and the rest came
at once. The 100 ms / 10,000 tok/s bounds catch a burst only when the
first content comes with it.

firstToken now reads on past the first text and marks when each content
event's bytes came (one mark a millisecond, up to 65,536 marks and the
8 MB it reads), and flowMs is how long the content took to come from
where the speed is counted: the span from a tenth of its bytes to nine
tenths, scaled to the whole. A steady stream gets about its whole window;
one let go in a burst about 1 ms. It is kept as Call/Try/Route .flow and
usage.Record.flow_ms (and the Requests page's packed rows), and
usage.DecodeOf, routing.js's decodeOf and app.js's ledDecode count no
longer a window than it. A record without it reads as before.

Verified: TestBurstTellsNoSpeed, a fake Chat vendor that sends a word,
waits 600 ms, then 199 words and the end in one write (1,000 tokens), for
a Chat and a Responses agent: no speed; before, 1636 and 1655 tok/s. Its
steady case (a word every 60 ms) keeps 200 tokens over most of its
window. TestCodexBackendBurstTellsNoSpeed is the same through Codex's own
ChatGPT backend (before: 1,000 tokens in 601 ms). TestFirstTokenKinds now
expects the stream read past its first text. Go tests ran on Linux
(golang:1.26 in Docker; this Mac's syspolicyd held new test binaries at
launch). GUI: routing-burst-speed (a route with John's 5.1 s first token,
6.7 s and a 2 ms flow: was "1367 tok/s", now none) and usage-speed (a row
with flow_ms 2 shows "—") fail without the JS change and pass with it,
with reasoning-speed, routing-request-metrics and usage-ledger-detail, in
Chromium and WebKit (en/zh, ja/de where the tests have them); no strings
changed. Not reproduced with Kimi Code itself: whether it holds the
stream so is inferred from the numbers.
2026-10-08 20:11:05 +08:00
yetone b2432754e5 usage, gateway: Antigravity's gemini-3.8-flash answered as gemini-3.8-flash-n is no longer marked as another model (dumplings on Discord)
Google's Code Assist backend names the deployment serving Gemini 3.8 Flash
"gemini-3.8-flash-n" in modelVersion, for every level it is asked at. On the
owner's real Antigravity account (daily-cloudcode-pa, 2026-10-08)
gemini-3.8-flash-low, -medium and -high all answered gemini-3.8-flash-n, with
or without a thinking level. gemini-3.8-flash-n itself is a 404 and
fetchAvailableModels doesn't list it. 3.7/3.6 Flash's levels answer the bare
family name, which #462 already allowed. So the requests log's amber "actual
model" and its "probably swapped" note were a false flag.

usage.GeminiServing accepts the sent Gemini model's own name plus "-n".
Swapped and the readers for kept rows and routes (request_page row(),
history routedAgain) all use it, so rows already logged read correctly
too. It covers Gemini only. gpt-5 -> gpt-5-mini, gpt-5 -> gpt-5-n,
claude-sonnet-4-5 -> -n, gemini-3.8-flash -> -lite, -> gemini-3.7-flash-n,
-> -nano and -high -> -low are still swaps.

Verified: TestSwappedGeminiServingName, TestLedgerGeminiServingNameIsNoSwap,
TestKeptRowGeminiServingNameNotSwapped and
TestRouteKeptGeminiServingNameNotSwapped fail on the old code ("gemini-3.8-flash
answered as gemini-3.8-flash-n is the model asked for", "still swapped") and
pass with it. Sandbox magpie on a copy of the real Antigravity login: before,
the routing log had swapped:true on every gemini-3.8-flash-n try. After, chat
completions at none/low/medium/high and /v1/responses are not swapped, and
the ledger reads the earlier rows as not swapped. go test -tags nogui ./...
passed under a temp HOME. go vet ran for darwin/linux/windows, and the
linux/windows builds passed.
2026-10-08 15:15:37 +08:00
wizzy-yangandwizzy-yang e95852e301 usage, gui: 用量页补上各 agent 会话文件里的用量,请求页按「经过 / 不经过 magpie」拆开 (#948)
* sessions: dsh、ZCode、WorkBuddy 的会话文件里有各自花掉的 token,用量台账从来不读

Sessions 页面一直都在读这些 agent 自己的会话文件,用量台账没有:用量页只显示网关本
身应答过的调用——也就是装上 magpie 之前的什么都没有,而一个直接指向厂商的 dsh 更
是什么都没有。本机上装 magpie 之前就已经在用这些 agent(用它们自带的模型),那段
用量一直对不上账。

  * 新增三类"整文件读取"的调用来源,走 wholeCallReaders(它们的调用不是一行一条,
    或者文件不能从中间接着读):dsh 的会话是 zstd 分帧追加的;ZCode 用的是 OpenCode
    那几张表;WorkBuddy 的同一句回复会在多行里重复同一个 messageId。三者的 token
    语义各自换算成 Call 的 Input/Output/CacheRead/CacheWrite,调用缓存跟着记一份(v9)。
  * 每个来源都跳过经由 magpie 网关发出的调用:网关自己记过那一本账,还带着真正应答
    的供应商和账号;dsh 发往网关的请求不带会话头,两边事后对不上(token 数每次不同、
    又没有可配对的 id),硬读就是同一通调用记两次。dsh 认它被配置去的那个 provider
    (dshGatewayProvider:magpie / dial),ZCode 和 OpenCode 认路由里写的 provider
    (ocGatewayProvider)。WorkBuddy 那部分见下一个提交。
  * WorkBuddy 的调用里,同一句回复的多行只记最后一次(它带这个回复的总量);而它从
    旧历史搬过来的回复一条 messageId 都没有,每一条都是独立的一通调用——会话汇总的
    读法(workbuddyLine)就是这么数的,这里照它来,否则台账会比 Sessions 页面少算,
    正是本次要消灭的那类"两页对不上",只是方向相反。
  * dsh 的一通调用保留它文件里记的两样东西:被配置去的供应商(Upstream,作为历史,
    从来不当成路由的证据),以及厂商真正应答的模型——回复的 replayState 里那个和
    请求模型不一致时,Model 记应答的、Requested 记被请求的,和 Claude Code 的文件
    一样的读法,好让请求表的若干列有东西可填。
  * 会话的 fork:dsh 的会话从另一个会话续起来时会带上对方已写入的事件(isSeeded /
    seedLength,session/end-seed 标记之后的不算),parser 跳过的这里同样跳过,否则
    同一通调用会在每个 fork 上再花一次。
  * WorkBuddy 的 subagents/ 子目录是父会话自己的调用来源(它带自己的消息 id,会话
    归到父会话名下);调用这条路不读 file.main,那个标记是 Sessions 页面给"会话自己的
    文件、不是子代理的"用的。

夹具:dsh 的三个会话(普通、带供应商与应答模型、以及一通经网关的),ZCode 的两条
(其中 ses_zcA 那条的 providerID 是 magpie,应被跳过),WorkBuddy 的既有会话(m1 的
usage 同时落在 assistant message 和它最后一个 function_call 上,只能记一次;旧历史
三条无 messageId 的回复各记一次)和一通经网关、一通走用户自建端点的会话。
调用缓存升到 v9:v8 里既没有 dsh 的供应商和应答模型,也没有"跳过网关调用"这件事,
旧缓存会继续把旧账 Serve 出来。

TestDshCalls、TestZCodeCalls、TestWorkBuddyCalls 是新的;把跳过网关调用那几行、以及
WorkBuddy 旧历史那条判据去掉,它们必挂、加上必过(都实际跑过反向验证)。

验证:go vet;go test ./internal/sessions(只余 TestCursor,Windows 路径前缀问题,
改动前同样失败);go build(windows)。

* usage: 请求页把"magpie 转的"和"它只读到的"分成两个数,GUI 跟着拆成两栏

用量页一直只显示网关自己应答过的调用,而现在它还要读 agent 自己会话文件里的调用:
两本账混在一行里,读者分不清哪一段是 magpie 转的、哪一段只是它从文件里读到的,
而总数事实上几乎全部来自后者(本机 30 天 847M token 里,网关只转了 2.4%)。Summary
里的两个来源卡片也加不出这个数来:它们只算 input 和 output,上面的 KPI 把缓存的
token 也算在内,于是"全部请求"读作 13.6M,而"Tokens"是 847M。

  * usage.RequestPage 和 usage.Filter 各多一样东西:前者在 Sum 之外带上 Through 和
    Direct(网关应答的,和从会话文件读到的),后者多一个 Through 维度。两种建页路径
    (流式的 queryPage 和治疗桌用的 pageFromLedger)都做同一个拆分,两边一致——
    TestCompactPageMatchesLedger 现在也覆盖两个来源筛选。
  * 每一行本来就是按 Source 区分这两类的("log" 是会话文件里的调用,其余走的网关),
    拆分就落在它上面;网关自己拒掉的调用两边都不算(页面在总数下面也这么说),所以
    SourceOf 对它返回 "",点哪一栏都同样把它排除,两栏自己的计数本来也不含它。
  * 两栏自己的数字是在"来源"这个挑选被清空的情况下数的,和各维度分组一样:三栏是读者
    来回切换的地方,各自得一直报着自己的数,否则点了其中一栏另一栏读作 0,且没有回
    到全部的路。
  * /api/usage/requests 支持 via=through|direct;GUI 那一侧的三个格子、计数单位、
    方块样式在下一个提交里。
  * Filter.Via 这个名字和 Record.Via(转发调用的那台电脑,#542)重了,改叫 Filter.Through。

Sessions 页列表长度那件事(sessionListLimit)拆到单独的 PR 里,不在这里。

验证:go vet;go test ./internal/usage(只余 TestOTelRetryAfterBound,计时的 ±30ms,
origin/main 同样失败);go build(windows)。

* gui: 请求页把来源拆成三栏,汇总那一排也改成方块

用途页的请求栏一直只有一本账(Sum),而现在它既显示网关应答的调用,也显示从各 agent
自己会话文件里读到的调用。三个格子画在上方汇总那一排方块里,样式一致:三张各自带
边框、彼此留缝的卡片,窄屏(≤620px)下竖排。

  * 每栏是一个 button:点一下就只列这一来源的请求,再点一下、或点"全部请求"回到
    全部;被选中的那一栏底下有一道本主题色的线。aria-pressed 标出当前选中的是哪一栏。
  * 计数后面跟单位("147 请求"),免得一个光秃秃的数字被读成下面的 token;token 是
    四项合计,和上面 KPI 的算法一致。
  * 三个格子在重绘之间是同一批元素、原地改(class / aria / 文本 / onclick),不是每次
    replaceChildren 重建——同一份 app.js 里 5810 行的规定就是这么写的("The switch is
    the same element across redraws, changed in place, so one being pressed or focused is
    never swapped out"),正在点的那个不该被换掉。
  * 汇总那一排本身(五张 KPI 卡)改成同样的方块:各自一张卡、有缝,边框写成
    var(--line) 而不是 --card-edge(那是面板用的变量,这些卡在独立窗口里也有)。
    ≤860px 两列排布时卡片之间的那几条线照旧:奇数位去掉左边框、第三张起加上边框,
    是 e0eaf5b4 带 #799 的老规则,这里只是跟着搬了位置,没有删。三张来源格是 button,
    不参与这套分隔线。
  * 供应商·账号 一栏:来自会话文件的行显示它文件里记的那个供应商 id(Codex 一向
    如此),有账号时仍是账号优先,什么都没有才说"本地会话"。"本地会话"角标的条件
    跟着放宽到账号或供应商任一存在,提示分两种说法:文件记了供应商的,说明这是它
    被配置去调用的那个记录、不是 magpie 看到的路由(不等于官方供应商);只认得出
    账号的,沿用原来那句"仅当本地元数据能明确识别时显示账号"。
  * 窗口参数支持 via,用后从地址栏清掉,和 tab/provider/agent 等一致。
  * 新增的串子在 en/zh/ja/de 四种语言里都有("{n} tokens" 上游已有,不重复加,
    i18n-keys 绿)。

验证:node --check(app.js、i18n.js);go vet;go build(windows)。
界面效果在本机用改动后的源码构建的二进制上过目:三栏的切换与计数、方块样式、
窄屏竖排、请求表新增的会话文件行(含供应商 id)。
浏览器套件(chromium 与 webkit、en/zh):session-identity、usage-ledger、
ledger-protocol、number-units、usage-ledger-chart、usage-ttft-rounding、
usage-chart-axis、usage-fold、web-page、usage-accounts、i18n-keys 全绿;
ledger-hscroll、usage-speed、click-scroll 全绿;gui-ja、gui-de 各一条失败、
usage-ledger-detail 六条失败,均在本机 origin/main 上同样失败,与本次改动无关。
usage-ledger-chart 新钉了 ≤620px 下 KPI 卡与来源格的分隔线(把 app.css 换回上游版本
它必挂,实测过)。

---------

Co-authored-by: wizzy-yang <wizzy-yang@users.noreply.github.com>
2026-10-07 19:43:01 +08:00
yetone 395c4bc51e tests: a test that sets time.Local does it through testenv.Zone, which first waits out the stand-ins' first runs — their os.Stat reads time.Local, and TestDsh -race alone raced it every run
testenv.StandIns (06420a71) starts each stand-in once in the background on
macOS and records it with os.Stat, which reads time.Local. internal/
sessions' inZone, internal/usage's TestDayFilterDST and the root package's
sessions CLI setup assigned time.Local while those runs could still be
under way. `go test -race -run '^TestDsh$' ./internal/sessions` reported
the race 6 of 6 runs on main (stats_test.go:14 against program.go:140).

testenv.Zone(t, loc) waits on the same WaitGroup RemovePrograms waits on,
sets time.Local and restores it in a Cleanup; the three helpers use it.
The root setup registers Zone before its own Cleanup, so the zone still
goes back after sessions.Reset's index write, as before.

After: the same command 0 races in 6 runs; -race -count=20 of
Dsh|DST over sessions and usage, -race -count=3 of the root Sessions
tests, -race of sessions/testenv/usage/root, go vet, gofmt pass. Tests only.
2026-10-07 06:17:56 +08:00
yetone 0bf9d77d3f agent tests: TestDriftBypassed's request reaching the gateway is kept to its run, so -count=2 passes
The test stood for a request with usage.Saw("codex"). Saw's record lasts
the process, which the gateway relies on (LastSeen answers from it before
a request is written to the log), so a second run started with a request
seconds old, newer than its prompt five minutes back, and found nothing
bypassed ("bypassed: <nil>", also on origin/main).

Drift reads LastSeen through a package variable the test replaces with its
own clock; production still reads usage.LastSeen. That Saw is LastSeen's
answer at once moves to usage's own TestSawIsLastSeen, which removes its
record afterwards.

-run 'TestDrift|TestSawIsLastSeen' -race -count=5 passes; before, -count=2
failed.
2026-10-07 03:03:06 +08:00