Commit Graph
17 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 2fd2cb60d4 usage: ZCode's calls leave the cache out of input, so the Requests page's hit rate reads 96.9%, not 49% (#1947, XcodeFish)
ZCode stores the AI SDK's counts: input includes cache reads and
writes. The session summary already took the cache out, but ocCall
passed ZCode's calls to the ledger as they were, so the Requests page,
which adds the cache to input for its hit rate, counted it twice
(the reporter's 275 calls: 49.2% instead of 96.9%).

ocCall subtracts cache read and write from input for agent "zcode";
callCacheVersion goes to calls-v12 so cached calls are parsed again.

Test: TestZCodeCallInputLeavesOutCache, with the reporter's rows; it
checks each call's tokens, the 96.9% rate, and that the session's
input equals its calls'. Fails on the old code. Ran: go test -tags
nogui ./internal/sessions/ (ok), go vet darwin/linux/windows, gofmt -l.
2026-10-13 16:17:06 +08:00
yetone 110b204313 sessions: Pi's and omp's own calls reach Usage, here and in WSL (#1951, Elenoxe)
Pi in WSL on a provider of its own never reached the Usage page: the
call ledger had no reader for Pi's or omp's session files, so only what
went through magpie's gateway was counted, and Sessions showed tokens
that Usage didn't.

calls_pi.go reads them whole, as call_cache's wholeCallReaders does for
Kimi, from piFiles, ompFiles and wslFiles("pi","omp"):
- each assistant message is a call on its own provider and model, with
  Pi's durationMs or omp's duration/ttft;
- "usage" / "model_usage" entries on the provider they name, and a
  compaction's, branch summary's or tool result's usage on the model in
  use, as Sessions counts them;
- a call through magpie's own entry (provider "magpie", "dial" before
  the rename) is left to the gateway, which logged it already;
- a failed call (no usage) is none;
- a fork's copies of its parent's entries (written before its header's
  time) are the parent's, and a call is keyed by entry id + time.

The fixtures are Pi 1.1.0's and omp 18.9.1's own files, written in a
sandbox HOME against a fake OpenAI-compatible relay (a run, a pi --fork
of it, a session whose calls failed before it went on through magpie);
the magpie lines are the owner's own Pi's, the reply text left out.

Run: go test -tags nogui -count=1 -timeout 45m ./internal/sessions
./internal/usage ./internal/cli ./internal/gui (green); gofmt -l; go vet
-tags nogui on darwin, GOOS=linux and GOOS=windows for internal/sessions.

Broken by hand: with the reader unregistered TestPiCalls finds 0 pi
calls and TestWSLSessionsListed says the distro's pi calls aren't
counted; without the magpie skip TestPiCalls/BesideReplies count the
gateway's calls; without the fork rule reading the fork's file alone
gives its parent's calls too.

Not tried: a real WSL distro (wslFiles is covered by the existing fake
distro), Windows paths at runtime, real "usage"/"model_usage"/
branch_summary entries beyond the fixtures. Grouping the Sessions
agent strip by WSL distro stays open in #1951.
2026-10-13 16:08:07 +08:00
yetone d3d1605c2c sessions: Kimi Code's own calls reach Usage, read from its wire files (#1607, infinitr0us)
Usage counts the gateway's calls and the calls the agents' own session
files record (sessions.Calls). Kimi Code had no reader, so its calls
straight to api.kimi.com on Kimi's own sign-in never showed (the
reporter's 47 k3 calls of one session on 2026-10-11).

The reader (calls_kimi.go) is built from the redacted real wire files
infinitr0us shared from two machines (protocols 1.0, 1.4, 1.5; text
replaced, every id, model and number kept) and their notes from Kimi
Code's source. It reads every agents/*/wire.jsonl under
$KIMI_CODE_HOME/sessions, else ~/.kimi-code/sessions (as agent.KimiDir
finds the new Kimi Code), main and subagents, ses_* folders included.
One call per usage.record: inputOther, inputCacheRead and
inputCacheCreation go to Input, CacheRead and CacheWrite, output as is,
the record's own model and time. Nothing is paired with step.end, since
1.4 and 1.5 write them in opposite orders and the June 1.4 build has no
messageId or llm.request. A model beginning "magpie/" (magpie's own
entry in Kimi's config) is skipped: the gateway counted it. kimi fork
copies the parent's records unchanged, so a call is keyed by agent
(agentId, else its agents/<id> folder), time, model and usage, and Calls
counts a key once. It is a whole-file call source (callSources,
wholeCallReaders) and the folder is watched (Dirs). The subsystem page
gets the list of call readers.

Fixtures (testdata/kimi-code) are the reporter's files cut to the lines
a call is read from, each line verbatim (50 KB; one of the July
session's eight agents kept).

Run: the reader over the reporter's whole, untrimmed files gives exactly
their README's totals (32/2,841,972/12,283; 151/7,025,587/122,782;
6/147,822/2,009; 10/338,328/2,176; 0 for the four others).
TestKimiCodeCalls (both homes), TestKimiCodeSkipsCallsThroughMagpie,
TestKimiCodeForkCountsOnce, TestKimiCodeBrokenFiles (cut mid-record,
empty, junk, null/negative/timeless usage) pass. Broken by hand, each
goes red: no magpie skip, no key, key without agent, no negative or
time guard, main only, KIMI_CODE_HOME ignored, cache read dropped.
go test -tags nogui ./internal/sessions ./internal/usage ./internal/cli
./internal/gui under a sandbox HOME, gofmt -l, go vet (darwin),
GOOS=linux go vet -tags nogui, GOOS=windows go vet.

Not tried: a live Kimi Code run (fixtures are the reporter's real
files, not a sandbox capture), a successful call through magpie (the
magpie-routed record in the test is the reporter's quoted 1.5 line with
a magpie/ model), a compaction record (usageScope "session", none in
the files), Kimi Code in WSL (not read), Windows paths at runtime. A
subagent's calls carry the session but no Subagent field.

Thanks to infinitr0us for the write-up from Kimi's source and the
redacted wire files.

Reported-by: infinitr0us
2026-10-13 06:59:17 +08:00
yetone a3f2097ede sessions: CodeBuddy Code's own calls reach Usage, read from its session files as WorkBuddy's are, and its calls through magpie's gateway are left to the gateway (#1779)
CodeBuddy Code was wired on the Agents page, but nothing read its session
files, so a call it made straight to its vendor never reached the usage
ledger. Only the calls it made through magpie's gateway showed, logged by
the gateway.

CodeBuddy Code writes its sessions the way WorkBuddy does:
projects/<cwd>/<id>.jsonl under $CODEBUDDY_CONFIG_DIR, else ~/.codebuddy.
A reply's usage sits in providerData.usage on its function_call or
assistant message line, keyed by providerData.messageId, and models.json
has the same format. So WorkBuddy's reader is now parameterized by agent:
- buddyFiles(agent, dir) lists the files.
- buddyGateway(dir, id) reads that agent's own models.json. Its stamp
  cache is kept per path.
- readWorkBuddyCalls takes the agent from the file.
"codebuddy" is registered in callSources and wholeCallReaders. A model
CodeBuddy asks for as custom-local:<id>, where models.json names <id> with
vendor "magpie", went to the gateway, and is skipped as WorkBuddy's are.

The fixtures in testdata/codebuddy are CodeBuddy Code 2.164.0's own files
(npm @tencent-ai/codebuddy-code), with only the cwd path shortened. They
come from two `codebuddy -p` runs in a sandbox HOME against a local OpenAI
fake: one on a model the user added for another vendor (counted: two
replies, 521 in + 26496 cache read, 115 out), and one on a vendor "magpie"
entry (skipped).

Run:
- TestCodeBuddyCalls goes red (0 calls) with codebuddyCallFiles taken out
  of callSources, and green with it in.
- TestCodeBuddyGatewayIsItsOwn checks that each agent's models.json is its
  own.
- go test ./internal/sessions passes.
- gofmt, go vet, Linux nogui vet and Windows vet are clean.
- Sandboxed go test ./... at the rebased head.

Not done:
- The Sessions page still doesn't list CodeBuddy Code's sessions. This
  commit is the Usage side only.
- Reasoning tokens (outputTokensDetails) aren't recorded, as for WorkBuddy.
- Not run against the reporter's China-edition session (47 calls). The
  line shapes match those in the issue.
2026-10-12 22:55:23 +08:00
yetone e044ea862f sessions: the warm-up at start reads with a quarter of the cores unless a page waits, and a long first read keeps what it read (#1665, laowangba233)
#1665: magpie pegs the CPU on every start (Windows Task Manager showed
95.8%). Three seconds after start, warmSessions indexes every Claude/Codex
session file and reads every file's calls for usage. refresh() ran
min(max(8, 2*NumCPU), 32) parsers at once and usage's prefetch 8 more, so the
background warm-up took every core while nobody was looking at the result.

Two goals, in one commit because they touch the same loop in refresh():

1. Quiet warm-up (quiet.go). gui's warmSessions runs inside
   sessions.Warm. While a warm-up runs and no request waits, every parse in
   refresh() and every readCalls takes one of max(1, NumCPU/4) slots. A
   request to /api/sessions* or /api/usage* (gui's held middleware) calls
   sessions.Ask(), which lifts the limit for as long as it runs, so a page
   the user opened isn't slowed down. A waiting reader re-checks every 50ms,
   so Ask takes effect mid-read.

2. Checkpoints. refresh() saved sessions.json only once all files were
   parsed. Quitting magpie before that (a slow machine, or the user closing
   it because the CPU is pegged) kept nothing, and the next start parsed
   every file again. Now every 5s (checkpointEvery) the files done so far
   are published and saved, if the cache generation still matches.

Measured on a Mac (14 cores) with a sandbox HOME holding 8.9 GB of real
sessions (copied read-only), sessions.json and calls-v11 removed, sampling
ps every 2s:
- cold start before: 41.2 CPU-s, peak 580-600%, done ~14s
- cold start after:  34.7 CPU-s, peak ~300-360%, done ~16s
- quit mid-index, before: quit at 6s (13.5 CPU-s spent) left no
  sessions.json and no calls files; the next start spent 41 CPU-s again.
- quit mid-index, after: quit at 12s left a 1.3 MB sessions.json (of
  3.0 MB); the next start spent 26.6 CPU-s instead of 34.7.

Tests (each red with its part undone, script-checked: refresh's slot
replaced by a no-op, readCalls' slot removed, the checkpoint block removed):
- TestWarmReadsOnlyInItsSlots: with every slot held, neither the index nor
  the calls read anything for 300ms; Ask() lets both finish.
- TestReadSlotOnlyWhileWarming: outside Warm, or while asked, reads don't
  wait.
- TestLongReadKeepsWhatItRead: a read held after its 3rd file has saved
  sessions.json with fewer files than it has to do.

Run: go test -tags nogui ./internal/sessions ./internal/gui
./internal/library ./internal/usage; gofmt -l; GOOS=linux and
GOOS=windows go vet of sessions, gui, library; full go test ./... before
push.
Not tried: the reporter's machine or data volume; a Windows re-measure.
2026-10-12 02:56:01 +08:00
yetone 5c9221899f sessions, agent: MiniMax Code's own calls reach Usage's split by agent, and its 0.6.8 User-Agent names it (#1605, LukeZ1988)
Usage's split by agent counts the gateway's calls and the calls the
agents' session files record (sessions.Calls). MiniMax Code had no
session reader at all, so a MiniMax Code on its own MiniMax sign-in or a
relay of the user's never showed in it.

What @minimax-ai/code 0.6.8 really writes, run in a sandbox HOME and
MINIMAX_DATA_DIR against a fake Anthropic upstream: each session is a
folder under <data dir>/v2/sessions/<yyyy>/<mm>/<dd>/, named
<time>-session_<base64 of its mvs_ id>, its messages in messages.jsonl.
An assistant line names the provider and model that answered, its usage
(input without the cache, output, cacheRead, cacheWrite, as pi's ai
package counts them) and the time in ms. The new reader
(calls_minimax.go) is a whole-file call source (callSources,
wholeCallReaders), and the folder is watched (Dirs). A call through
magpie's own entry (custom_provider:magpie) is skipped; the gateway
already counted it, with the account that answered. A reply is keyed by
its message_id, so one copied into another generation of the history
counts once.

Gateway side: magpie's entry sets User-Agent minimax-code, and the sandbox
run showed it reaching the upstream on /v1/messages and count_tokens.
0.6.8 without that header (a provider pointed at magpie by hand) sends
"MiniMaxCode", which now names minimax-code too. The class check:
StepCode, jcode, Prime Agent, Snow and every other built-in agent are
named by their own gateway key (TokenFor); TestEveryAgentNamedByItsKey
guards that for all of Clients(). Their direct, non-gateway calls are
not read yet, and neither are those of pi, Cline, Qoder, Grok, Droid,
omp, Cursor, Hermes and Alma, which the Sessions page reads (filed
as #1607).

Run: TestMiniMaxCodeCalls (the two real messages.jsonl files, verbatim:
three calls through magpie's entry and one on a relay; under ~/.minimax
and under MINIMAX_DATA_DIR) passes; dropping the gateway skip by hand
turns it red (4 calls). TestAgentOf (MiniMaxCode, minimax-code),
TestEveryAgentNamedByItsKey. go test ./internal/sessions
./internal/usage, the agent tests named above, gofmt -l, GOOS=linux and
GOOS=windows go vet. Not tried: MiniMax Code on Windows or in WSL (WSL
distros' MiniMax sessions are not read), a call on the MiniMax sign-in
itself (provider name taken from the file whatever it is), or a session
after compaction.
2026-10-11 20:09:15 +08:00
yetone 5d1d2f66dd sessions: a Codex call in a turn of several is timed from what asked for it to its last output, not from its own tool's output (Fallmonkey on Discord)
An older Codex rollout (no token_usage_record) writes a call's token_count
after the output of the tool that call ran. The call was timed from the
last thing the model was given, which by then was its own tool's output,
so its window was a millisecond or two: on 517 stripped copies of the
owner's Aug/Sep rollouts gpt-5.6-sol's multi-call calls read p50 65,500
and up to 1,844,000 tok/s. A count written seconds after its tool's
output gives the mid-range outliers (sol 972) Fallmonkey reported.

Now a call begins to answer at its first output item (reasoning, a tool
call, an assistant message). It is timed from what the model had last
been given at that moment, and, when its own tool's output came before
its usage line, it ends at its last output item rather than after the
tool ran. Newer rollouts, whose token_usage_record comes before the tool's
output, are timed as before: on 622 stripped recent rollouts every call
reads the same (sol p50 44, max 82). On the older ones sol now reads p50
34, p99 53, max 54. A long output line (a large patch) is read by its
head. The call cache goes to calls-v11 so cached calls are re-read.

TestCallsCodexTimedFromTheAsk is built on a real 2026-09-06 rollout's
shape with content stripped; on the old code it reads [15000 0 0 0]
instead of [15000 29000 8000 9000], and with the long-line branch taken
out it fails too.

Ran: go test ./internal/sessions, gofmt -l, GOOS=linux/windows go vet.
2026-10-11 12:49:27 +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 71d2da1f42 catalog, usage, gateway, gui: a price can have a long-context tier and a 1-hour cache write, and the price boxes take decimals (PAMI on Discord)
OpenAI bills gpt-6-astra, gpt-6.1-sol and gpt-6-luna over 272K input at 2× input and cache and 1.5× output, for the whole request. A price now has tiers: `magpie model price <m> 10,50,1,12.5 --tier 272k 20,75,2,25` (--tier can repeat). A tier applies when input + cache reads + cache writes is over its size, so 272,000 is not over and 272,001 is. The built-in prices take tiers only where models.dev lists one (cost.tiers of type "context"), and it does list one for those three. The ledger, each request and OTLP are costed at the tier the call reached. Session and day totals sum many calls, so they stay at the base price.

Anthropic bills a cache write kept for an hour at 2× input and one kept for 5 minutes at 1.25×. Its usage reports which is which in cache_creation.ephemeral_5m/1h_input_tokens. The gateway (API and Claude subscription) and Claude Code's transcripts now keep that split. A price's fifth part is the 1-hour write. When it isn't given, it is 2× input: that is Anthropic's rule, and only Anthropic reports 1-hour writes. Claude list prices carry the 2× too. cache_write_tokens is still the total, and the usage CSV adds cache_write_5m_tokens and cache_write_1h_tokens at the end. The app shows the split on a request's Cache and on the usage tooltips. Old prices and old records, which have no 1-hour part, read as before. The sessions cache (18) and the call cache (calls-v8) are re-read once.

In the GUI, the price boxes were number inputs and dropped what they didn't parse ("0,25"). They are now decimal text boxes that take both "0.25" and "0,25". A model's price row has a 1-hour box (empty means 2× input) and a quiet Long-context price row. That row shows the list's tier greyed in, or sits behind a link when the list has none. A bad size is refused by name. en/zh/ja/de.

Tests:
- New: TestPriceTiers, TestCostSplit, TestPriceJSON, TestModelPriceTiers, TestModelPriceTierCmd, TestAnthropicCacheWriteSplit and TestClaudeCacheWriteSplit. The ledger CSV test expects the new columns.
- model-price-tiers.test.cjs is new; model-price-edit and provider-price-rate are updated. All of them fail against the old assets and pass in WebKit. Chromium couldn't be launched here.
- go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
2026-10-05 21:56:59 +08:00
Fanbuz c21cd8c881 sessions: reconcile replayed Claude message usage without persisting message maps (#697)
* fix: 按消息修订校正 Claude 用量并限制缓存状态

* fix: 释放历史 Claude 索引并按字段读取请求标识

* fix: 保留大型 Claude 会话的增量读取窗口

* fix: 修正 Qoder 重计并按解析成本保留会话窗口

* fix: 避免历史会话窗口挤占活跃日志缓存
2026-10-04 10:01:52 +08:00
Fanbuz 67004a7e8f sessions: count Codex RECORD and compaction usage without a history parent (#695)
* fix: 按本地事件配对统计 Codex 响应与压缩用量

* fix: 限制用量索引内存并精简磁盘缓存

* fix: 淘汰解析索引后仍释放请求行缓存
2026-10-04 07:57:49 +08:00
yetone 643264c24f sessions: the Sessions page and local usage read the agents in WSL too, and resume one there through wsl.exe (lgtm on Discord: magpie can't detect the session lists of agents inside WSL?) — on Windows magpie already finds the WSL distros an agent is set up in (internal/agent's wslDistros, the distro user's home as \\wsl.localhost\<distro>\home\<user>), but the session reader only looked at this computer's own ~/.claude, ~/.codex and ~/.pi. Now internal/agent hands those homes to the sessions package (sessions.WSLHomes, set in init, no second discovery), and the sessions of Claude Code, Codex and Pi in each distro are listed beside this computer's, with Session.WSL naming the distro: a "WSL <distro>" badge on the Sessions page's rows and the management page, a WSL line in the details, " · WSL <distro>" in the API's name. Resume runs in the distro: wsl.exe -d '<distro>' --cd '<cwd>' -e sh -lc 'exec ${SHELL:-sh} -lic ''claude --resume <id>''' (the user's own shell, so the agent's PATH is there; no double quotes, which PowerShell 5.1 mangles). Their calls count in local usage (callFiles). Reading a distro over \\wsl.localhost is slow and opening a file in a stopped distro starts it, so the files are listed in the background, at most every 30 s, the listing kept in sessions-wsl.json; the page waits for it only the first time ever (up to 3 s); a stopped distro's sessions stay listed as last read and nothing in it is opened (the parse cache and call shards keep them). magpie doesn't delete a session in WSL: the checkbox and Delete are off for them, with a note to delete them there, and sessions.Delete refuses. OpenCode in WSL isn't read (its SQLite over \\wsl.localhost isn't reliable). zh strings added. TestWSLSessionsListed, TestWSLStoppedDistroKept and TestWSLNoneWithoutHomes (internal/sessions) and TestWSLSessionsOfTheDistro (internal/agent, FakeWSL: a Claude Code session in a fake Ubuntu is listed with its distro and the wsl.exe resume line) fail on the old code and pass. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. Not tried on a real WSL with agent sessions: the Windows test box's distros have no Claude Code, Codex or Pi sessions; the resume line wasn't run in PowerShell, and the pages weren't opened in a browser. 2026-10-03 23:55:18 +08:00
yetone d079dc6223 usage: an OpenCode session's row shows the effort and the model it asked for (#680, Sun1090: 数据不完整,推理强度是有的)
OpenCode rows read from its own data (opencode.db or storage/) had 请求模型 and 推理强度 as —. OpenCode keeps both on each reply (packages/schema/src/v1/session.ts, AssistantMessage): variant, the effort picked in its model menu for the prompt (high, max, low, xhigh, none, thinking … as the provider's variants name them; prompt.ts copies lastUser.model.variant onto every reply), and modelID, the model the reply was sent to. OpenCode 2 (session_message) keeps the variant in model.variant (Model.Ref). It records no model the response named, so modelID is what was asked for, as a Codex rollout's model is.

Now a call's Effort is the reply's variant ("default" or none is no effort picked); a compaction in OpenCode 2 takes the effort last replied with, as it takes the model. In the ledger an OpenCode call is told as a Codex one: requested = its model, served left empty rather than claimed. The call cache moves to calls-v5 so calls read before carry the effort.

TestOpenCodeCallsJSON/DB/V2 (fixtures with variant high, default, xhigh and none) and TestOpenCodeSessionCallIsWhatItAskedFor fail on the old code and pass. go vet ./internal/..., builds (nogui, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. Not tried against a real OpenCode database with variants (this machine's OpenCode data predates them).
2026-10-03 23:44:06 +08:00
yetone b8fdba5d64 usage: OpenCode's own calls are counted, as Claude Code's and Codex's are (#680, Sun1090: cc-switch 会统计 OpenCode 的用量,我这样不会被统计吗?) — OpenCode used on its own providers (OpenCode Zen/Go, its own keys), not through magpie's gateway, never reached the Usage page: the local calls were Claude Code's and Codex's session files only. Now each OpenCode assistant message is a call (agent opencode): its model, provider (as the session provider), input, output with the reasoning in it (reasoning kept apart too, as Codex's), cache read and write, its end time and how long it took, the session it ran under (a subagent's in its parent's), and a reply that failed with no tokens as a failed call (a stopped one is none). They are read where the Sessions page reads OpenCode: opencode.db — OpenCode 2's session_v2/session_message (a compaction on the reply before it) or the older session/message, the old ones not yet copied while OpenCode 2 migrates — else the JSON files under storage/. A reply through magpie's gateway (provider "magpie", or "dial") is left out: the gateway logged it already. Each session is a call source of its own, read again whole only when it changed (its size is the messages' count plus the sum of their time_updated, so an older message written again tells too) and kept in the call cache on disk as a file's calls are; the database listing is kept while opencode.db and its WAL are unchanged, and a read-only handle is shared between sources and closed after 10 s unused. The Sessions listing is unchanged (allFiles still takes callFiles; Calls and CallSources take callSources). ContentOf says no place for an OpenCode call. OpenCode's own cost isn't used: calls are priced at magpie's effective prices, as the others are. TestOpenCodeCallsJSON, TestOpenCodeCallsDB (cache kept unchanged and across a restart, an updated message read again, a failed and a stopped reply) and TestOpenCodeCallsV2 (compactions follow the reply before them, magpie's skipped) fail on the old code (no OpenCode calls). With a read-only copy of this computer's ~/.local/share/opencode (JSON storage, 3 OpenCode Zen kimi-k2.5-free replies): 3 calls, input 12281, output 235 (123 + 112 reasoning), cache read 24573 — the same as jq over the message files and as SQL SUM over an opencode.db built from them. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-03 21:27:17 +08:00
yetone f1ca6139b5 usage: a Codex call through the gateway that wrote to its upstream's cache is no longer listed a second time as a local session call (laowangba233 on #589: 用量中的统计是不是重复了 … 为啥会一个是提供商的一个是本地会话的) — the Usage page drops a Codex rollout's call when it matches a gateway record by session, end time within 2s and equal tokens. Codex reads input_tokens_details.cache_write_tokens from a Responses reply and keeps it as cache_write_input_tokens; the gateway's rUsage read only cached_tokens, so for a call whose upstream told a write the record had CacheWrite 0 and the rollout didn't, the tokens never matched, and the call stayed listed under Local session beside its provider's row. Calls without a write matched, so only some calls were counted twice (Maru Code 92 calls plus 22 "本地会话" in the report). Also, sessions' spent took only the cache read out of Codex's input_tokens, which holds the write too, so such a call's write was counted twice in its own input. Now: the gateway reads cache_write_tokens (input = input_tokens - cached - written) and tells it to Codex when it translates a reply; spent takes the write out of the input as well; and the matcher compares a call's input plus cache writes, its output and its cache reads, so a record and a rollout that split the write differently — an older Codex without the field, or records already in usage.jsonl from before this change — still match, and the duplicates already on a user's page go too. The session caches' versions go up (sessions.json 11, calls-v4) so kept parses are read again, and older calls-v* folders are removed. Under a provider filter the provider ranking still lists the other providers, as it is a picker; the duplicates were what made it read as double counting. TestCodexCacheWriteMatchesGatewayCall (a Codex rollout and gateway records for two calls, one with a 9000-token cache write; with the rollout naming the write and the record not, both naming it, and an older Codex without it: two rows, no Local session row, the provider ranking maru-code alone, unfiltered and filtered to the provider, by QueryPage and LedgerOf; fails without the change with a third row from the log), TestCodexCacheWriteNotInInput and TestResponsesUsageCacheWrite (parse and round trip through what Codex is told) are new and fail without the change; TestCallsCodex's call with a write now expects input 200 (2500 - 2000 read - 300 written). go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./internal/... under a temp HOME pass (TestFXInState's known TempDir-cleanup flake aside, which passes alone). 2026-10-03 00:47:33 +08:00
c0f3fa012a usage: combine gateway and local session requests with model charts and account labels (#239)
* usage: Requests lists the agents' own session-file calls, put to the vendor and account their files prove, charts them by provider, agent or model, shows what was said, and the tray panel gets a Usage tab

The Usage page's Requests tab now covers requests an agent sends with its own sign-in (Claude Desktop's Code tab and Cowork, Claude Code, Codex), which never pass the gateway, and shows more of every request: why it failed, what was said in it, who it was of.

Requests tab: a strip of four totals (tokens, requests, cost, cache hit rate); the trend of one metric — tokens, cost or requests — as columns by the hour, day or week, told apart by provider, agent or model (both remembered), beside a ranking of the same that is its legend and a way in (a click lists only that provider's or agent's requests; a provider picker sits beside the agent's). The ranking is as tall as the chart and scrolls in itself, with no scrollbar: a slim rail in the card's margin shows how much there is and where it is (its thumb dragged, the rail clicked), and the edge with more beyond it fades; under the chart (860px and narrower) it shows whole. A row opens to its details: the vendor's error type and words, request id, endpoint, and what was said in it (input and output, read from the agent's session file when opened, the call that ended nearest the request — nothing stored). A refresh period (off / 5 s / 10 s / 30 s / 1 min) and refresh-now. The Overview says it counts gateway calls only; Requests and the panel say they count both. The tray panel gets a Usage tab (today / 7 / 30 days, provider picker, four totals, a small chart, top five, "Open Usage"), and is as tall as its tallest tab (#124).

Provider and account of a session-file call: never magpie's "claude" or "codex" subscription. Anthropic's when Claude Desktop's session metadata (not Claude-3p) names the account and organization, with that account's email; OpenAI's when Codex's rollout names a provider that is OpenAI's in config.toml — the built-in "openai", or a named one at OpenAI's address or signed in with the ChatGPT account and no base_url (requires_openai_auth) — with the creator account's email when the file records it. Anything else is "Local session", its recorded provider id and session account kept (CSV: session_provider, session_account). The config read is today's: a file names the provider id only.

Gateway: a failed call keeps the vendor's error text and type, request id and endpoint; a Claude subscription's failure uses the status Claude Code reports (api_error_status). A request turned away before any vendor was asked is logged, marked rejected, listed in Requests and left out of every total. The client's own session header is kept as native_session beside X-Magpie-Session, and a session-file call is matched to a gateway record by request id, then by that session, equal tokens and an end within 2 s, only when unique both ways.

Reading: session-file calls live in the session index main keeps on disk, parsed incrementally and outside its lock (Claude Code, Cowork in both Claude folders, Codex); the usage log is read on from where it was; a page builds the ledger once. Days are counted on calendar dates (DST). CSV gains request_id, endpoint, error_message, error_type, source, session_provider, session_account. i18n: one "Endpoint" (终结点), which a second key had turned for Azure's field.

Tested: go vet ./..., go build (also GOOS=linux/windows, -tags nogui) and go test -tags nogui ./... pass. The whole GUI suite in Chromium and WebKit, en and zh (Playwright 1.62.1): all 393 tests pass. On this computer's files (7 days): 3,330 Claude Desktop calls resolve to Anthropic with the account, 1,991 Codex calls on a named ChatGPT-signed-in provider to OpenAI (620 with the account; older rollouts don't record it), 9 Claude Code CLI calls stay Local session.

Co-authored-by: yetone <yetoneful@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* usage: a session-file call of one of magpie's own Codex or Claude accounts is told as that provider, beside the gateway's calls on it — "OpenAI" and "Codex" (or "Anthropic" and "Claude Code") read as two vendors when they were one subscription

Codex: an official route (above) whose creator account and user are one of magpie's Codex sign-ins (the CLI's own or a saved one) is magpie's "codex", with that account's email as the gateway's rows have it. Claude Desktop (not Claude-3p): an account and organization that are one of magpie's Claude sign-ins is magpie's "claude". Only while magpie has that provider signed in; another account, a rollout with no account recorded, or an ambiguous workspace stays OpenAI or Anthropic, and a relay stays Local session.

Tested: TestSessionCallsOfMagpiesAccountsAreItsProviders (the account matched, another account, none recorded, magpie's account through a relay, Desktop in magpie's and another organization, Claude-3p, magpie signed out) and TestLedgerTellsCodexSessionCallsAsMagpiesCodex (a gateway Codex call and a session call of its account one provider of two calls, another account's OpenAI). On this computer (7 days): 3,439 Claude Desktop calls are magpie's Claude, 626 Codex calls its Codex, 1,322 older Codex rollouts with no account stay OpenAI. go test -tags nogui ./... and the usage GUI tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: 修复请求统计缓存膨胀与会话账号误归属 #239

调用明细改为按会话文件分片保存并限制内存缓存,汇总索引仅保留统计数据;网关日志按需读取。

严格匹配订阅账号与用户 ID,排除自定义渠道、非官方端点覆盖、外部 CODEX_HOME 及关闭的供应商。补齐零 token 失败去重、Codex 原始会话 ID、拒绝标记导出和面板显示修复。

通过全量 Go 测试、静态检查、受影响模块的并发检查、52 项浏览器测试及 macOS/Linux/Windows 构建;使用 35 万条合成调用验证索引体积与内存改善。

* fix: 降低请求统计刷新与写入开销并明确本地账号展示 #239

请求分片改为追加帧和字符串去重,分页复用未变化的紧凑快照,采用 LRU 并移出全局锁内的磁盘读取。缓存 Cowork 目录,补齐同前缀改写检测及崩溃临时文件清理。

本地记录仅显示匹配账号或本地会话,明确官方登录标记与请求路由的区别。默认今日与模型维度,Auto Review 复用共享目录定价并单独标注估价参考。

完整 Go 测试、vet、相关 race 和 52 项浏览器回归通过;提供 2000 文件及四个大会话连续追加的可复现性能对照。

* fix: 优化用量徽标与耗时分级并保护分页边界 #239

官方登录、API、订阅和本地会话采用独立颜色与柔和底色,兼容明暗主题。耗时按 10 秒及 30 秒阈值着色,保留估算标识与原始毫秒提示;无有效耗时显示短横线。

限制分页选取范围,避免超大偏移整数溢出及越界空页的无效堆构造。补充阈值、徽标对比度和极端分页参数回归。

* fix: 将账号与来源徽标分为两行展示 #239

* fix: 提高用量表格模型文字对比度 #239

发送模型和已知实际模型使用主题正文次级色,表头与时间同步加深。保留缺失值弱化、转发提示和本地日志来源说明。Chromium 与 WebKit 的中英文、浅深色主题 10 项界面检查通过。

---------

Co-authored-by: yetone <yetoneful@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:42:10 +08:00