Commit Graph
35 Commits
Author SHA1 Message Date
yetone 7037cd9801 sessions: the reads under a hold share one listing, and a pass's path set is reused (#2278)
A minute of the page's polls over a long history (52G Codex, 13G
Claude) allocated ~70 MB copying the held Codex listing for every
reader, ~35 MB on pruneCalls' and refresh's path maps, and ~40 MB more
on distinctOf's set and the Requests/effort listing made for each ask.
Allocation is what drives the collector's ~33% of CPU.

- heldFiles and the warm-up's listing hand every reader the same
  slice, clipped so an append is made elsewhere. Every caller only
  reads it or copies it (distinctOf, appends into their own); the one
  that sorted it, traceLineFiles, now concatenates into its own slice.
- distinctOf, pruneCalls and refresh take their path sets from a pool
  and clear them after the pass.
- CallSourcesAndCodexIdentities builds its listing in a pooled buffer
  given back once its sources are taken.

TestWarmUpListsRolloutsOnce checked that a caller could write over
the kept listing; it now checks the listing is shared and clipped.
TestHeldListingShared and TestListingPoolsGiveBackEmpty are new.

Run on mote at this tree, rebased onto e863f520c (gateway only) and
rerun after; then onto 7632e1be1 (internal/redact only):
- go vet -tags nogui ./internal/sessions/ ./internal/gui/
  ./internal/usage/ for linux, windows and darwin: clean.
- go test -race ./internal/sessions/ ./internal/usage/: ok.
  ./internal/gui/: ok but TestMainWindowCorners (#3949, known).
- Broken by hand: heldFiles' waiter returning slices.Clone again
  turns TestHeldListingShared red ("each read under the hold got a
  copy of the listing").
- The full-history bench (10 endpoints every 5s, heap profiles at 50s
  and 110s, alloc_space diff), two rounds each, v0.1.2121 against
  this:
  slices.Clone of the listing 69 / 30 MB -> gone;
  pruneCalls 36 / 25 MB -> 5 / 0.5 MB;
  distinctOf 122 / 81 MB -> 83 / 84 MB (its make and distinctInto).
  The totals per minute (1216 / 649 MB against 598 / 675 MB) swing
  with mote's load (~100 from other sessions) more than the change
  moves them, so they say nothing either way.

Not changed: the Codex listing itself (codexFilesIn, ~160-230 MB a
minute) is still made new for each hold, and readRequestState
(~310-390 MB) still reads every source per ask. Those are next.
2026-10-30 10:28:30 +08:00
yetone 9474eaf9cb sessions: Raft's Pi agents' sessions are listed as Raft's, with their prompts, calls and delete
Raft (slock's raft-computer) runs its agents on Pi and keeps each one's
Pi SDK session files in that agent's folder: <slock>/agents/<id>/
.pi-sessions/<ts>_<id>.jsonl, or .builtin-sessions/ for its built-in
runtime. <slock> is $SLOCK_HOME or ~/.slock (%USERPROFILE%\.slock on
Windows, the distro's ~/.slock under WSL). Read from raft-computer
1.0.14's PiDriver (buildPiSessionDir), BuiltInDriver and
resolveSlockHome, and a read-only listing of ~/.slock here.
runtime-sessions/ holds handoff notes, no sessions, and is not read.

- The Sessions page lists them as Raft's (agent "raft", in agent.Clients'
  others), titled and opened with their prompts as Pi's are.
- Their calls count on the Usage page as Raft's; calls through magpie
  stay the gateway's, as Pi's do.
- Raft's Pi uses the user's own ~/.pi/agent, so a request it sends
  through magpie reaches the gateway as Pi's under the same session id.
  sessions.GatewayKeys gives a Raft session both "raft|ID" and "pi|ID",
  so the gateway's copy is not listed twice nor counted twice (Merge,
  stats, NativeIDs, the GUI's Via).
- Delete and restore work as Pi's: the one file goes to the trash, and a
  folder beside it is left (the agent's workspace is not the session's).
  A session written in the last minutes is refused as active.
- No resume command, no carry and no trace export: Raft starts its own
  agents, and nothing outside it can resume one.
- SLOCK_HOME is passed through agentenv like the other agents' homes.

Run (at 958ad9f10 on e61e10535):
- mote (macOS): -run 'Raft|TestPi|TestDirs|TestVars|TestFolderVars' in
  sessions and agentenv: ok, and red for each break below. A full
  go test ./... was started there; at load ~300 from other sessions'
  suites it printed only magpie and internal/access (ok) before mote
  stopped answering (host down), so no full macOS record exists.
- mote (macOS), rebased on 5d24bc6cc: go test -count=1 ./internal/sessions/
  ./internal/agentenv/: ok (sessions 495s, agentenv 1.1s). agent and gui
  were not run in full on macOS.
- mote: GOOS=windows go vet of sessions, agent, agentenv, gui; GOOS=linux
  go vet of sessions, agent, agentenv: ok.
- Windows (win-run): agentenv ok; -run 'Raft|TestPi|TestDirs' in
  sessions ok. The full sessions package hit its 30m timeout after
  TestOneListing's red (#4114) and the Agy reds (#4115, #4177). agent
  and gui reds (Hermes, WorkBuddy, Lody, Qoder/Copilot plugin folders,
  Codex keychain, ClaudeDesktop language, Aside, InstallWithoutNode,
  DesktopExec, AionUi, ImportStatus, UpdateThatWontStart,
  GatewayHeldByAContainer, GatewaySessionHistoryAndCalendar): each run
  again at origin/main c1660481c on Windows and red there too, except
  TestHermesProfilesFollowMagpieModel which passed there alone; it is
  #1388's Hermes model rewrite, which this change does not reach.
- Linux (wsl-run): sessions ok, agentenv ok. agent's TestInstalledVersion,
  TestGrokInstalled, TestCursorFolderFromTheEditorIsNotTheCLI and
  TestOmpDetectedWithPiDir are red at origin/main c1660481c too (#4033,
  #3548). gui does not build there (no gtk4/webkitgtk-6.0 in the distro).

Broken by hand, each red, then restored: Raft's listing removed; the
"pi|ID" key dropped from GatewayKeys; the folder-beside check reverted to
Pi's absence; $SLOCK_HOME ignored; Raft's calls left out of piCallFiles;
NativeIDs without Raft; stats' native keys without "pi|ID".

Not tried: with real Raft. No agent on this machine has run on Pi, so
the fixtures are Pi 1.1.0's own files (testdata/pi-calls, testdata/pi)
placed in Raft's folders. The GUI was not run in a browser: no JS
changed, Raft's name and icon come from agent.Clients. Raft's icon is the
generic one.
2026-10-29 15:29:30 +08:00
yetone 50606d8c0b sessions: a live file's calls read back from its shard are read on from, not copied
Requests evicts a file's expanded calls after each read, so every change
of a live session loads its calls from the disk shard (loadKept) and
then prepareCalls cloned them whole to read on from. The loaded copy
has no other reader, so the clone was a second full copy of the
session's calls on every poll, held at once with the first while the
chunk was built. readCalls and callsAlong now say when the calls came
from disk, and prepareCalls then copies only the reading state
(cloneState: the Claude window, Codex's maps, which can be a kept
continuation's) and keeps the calls, Msgs and Began. Calls from the
cache are still copied.

Measured on real history (rss-home, owner's ~/.claude and ~/.codex,
read-only), ab5.sh, 90s warm-up then 8 GUI polls 15s apart, alloc
between the heaps:
  before (v0.1.1673 head): callFile.clone 160 MB, prepareCalls 201 MB;
    footprint 264-412 MB, Requests 287-722 ms
  after: clone gone from the profile; footprint 201-367 MB, Requests
    144-472 ms
The history is live, so loadCalls itself varied run to run (741 MB vs
172 MB); the clone's share is the part this change removes.

Run at this head (2e165fe9d + this change):
  go test -timeout 45m ./internal/sessions/  ok
  go test -timeout 45m ./internal/usage/ ./internal/usageapi/  ok
  GOOS=linux/windows go vet -tags nogui ./internal/sessions/  ok
  gofmt -l internal/sessions  clean
New TestCallsFromTheShardAreNotCopied (claude, codex): red with the
owned branch turned off by hand ("calls read from the shard were
copied to be read on from"), green with it.
Not tried: a GUI run (no GUI change).
2026-10-27 11:42:49 +08:00
yetone 67a137744f sessions: a call shard is written in frames of 2048 calls (#3493)
writeCalls wrote a shard's whole state as one frame, whatever its
size. The largest Codex session on the test copy (52,500 calls) was one
8MB gob frame, and decoding it allocated ~100MB and held ~70MB at once,
which is most of the gap between a cold warm-up's memory peak and a
warm one's.

A write now splits its patches into frames of framePatches (2048).
Every frame but the last has More set, and each carries Calls, the
file's call count after the write, so loadCalls sizes its slice once.
A file whose last frame has More was cut off mid-write and reads as
nil, the same as a bad CRC. A shard read from a frame over
framePatches (the old format) is written again in frames once, at its
first load (loadKept), so existing caches shrink their peak too.

Run at this tree (04439c859 + this change):
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/usage/:
  ok; go test -run 'Warm|Session' ./internal/gui/: ok.
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions/:
  ok; gofmt -l clean.
- TestCallsWrittenInFrames (frames 2048/2048/100, a file cut after the
  first frame reads nil, an old one-frame file loads and is rewritten)
  went red with each of: no More check, no rewrite, no Calls presize,
  no split.
- The real warm-up (gui warmSteps inside sessions.Warm) on a copy of
  the owner's ~/.claude and ~/.codex sessions, 15,719 shards / 118MB,
  alternating parent and change:
  - cold (requests-v1.bin removed): phys_footprint_peak 418/462/406/
    454MB before, 355/399/328MB after; allocated in step 2 ~1790MB
    before, ~1575MB after; step 2 2.2-4.9s before, 1.8-2.1s after.
  - the first run after the change, which rewrites the old shards:
    424MB peak, 2161MB allocated, 3.4s step 2 (once).
  - warm: peak 366/372MB before, 295/330MB after.

Not tried: Windows with real session data (the box has none).
2026-10-25 15:55:54 +08:00
yetone b686a8dfec sessions: a call shard's frames are read into a buffer kept between shards (#3493)
A cold Requests build (the first start after an update that changed the
usage package's source, so the request chunks are made again) reads
every call shard, ~15.7k on the real data copy. Each frame was read
into a new byte slice and decoded into a new callFrame, so gob made a
new Patches and Strings slice for every one. loadCalls now takes a
frameBuffer from a pool. gob decodes a slice that has room in place,
and leaves a field of the zero value as the field was, so each patch
and string of the last frame is cleared before the next is decoded in.
Nothing read out points into the buffer: gob copies strings and byte
slices, and a patch's call is copied into the file's calls.

Measured on the real data copy (sbpairs), warm-up harness TestZZWarm,
requests-v1.bin removed before each run so every run is a cold build,
three runs each:
  allocated through step 3   2139/2214/2182 MB -> 2001/2041/2044 MB
  loadCalls (cum, step 2)    781 MB -> 583 MB
  peak footprint             374-441 MB -> 371-419 MB, within noise
Warm starts unchanged (step 2 ~690 MB either way).

Run at this head: go test ./internal/sessions ./internal/usage ok;
-race -count=2 of the LoadedCalls, CallCache, Shard and Frame tests ok;
GOOS=linux and windows go vet -tags nogui ./internal/sessions ok; gofmt
clean. TestLoadedCallsKeepNothingOfTheLastShard reads a shard with
tokens, a session and a compaction, then one with none, three times;
broken by hand (the patches not cleared) it fails.

Not tried: Linux and Windows real-data runs.
2026-10-25 15:18:40 +08:00
yetone 42ab935516 usage: requests-v1.bin is of the code that makes rows, not of the binary
The file of the session files' chunks was named by the binary's own
stat key, so every upgrade, and magpie ships several a day, read every
session file again on its first Requests page: on a 15.6k-shard history
warm-up step 2 went from ~0.8-0.9s (read from the file) to 1.6-1.9s and
~1.3GB more allocation. It is named now by the call shards' version
(sessions.CallCacheVersion, which already decides whether a shard of the
calls is read) and a SHA-256 of this package's non-test source, which
the binary carries (go:embed *.go, ~750KB with the tests, which the name
leaves out). Of the last 99 releases, 17 changed that source; the other
82 keep the file. Prices, names and settings are in the file's meta as
before. When the embedded source can't be read the name is the binary's,
as it was.

Measured (real history, sbpairs): one test binary wrote the file, a
second binary at another path (the old key differs) read it: step 2
0.79s and 1001MB alloc, against 1.63s and 2285MB cold.

Run at this tree (89dc16476 + this change):
- go test -race -count=1 ./internal/usage: ok
- go test -count=1 ./internal/sessions ./internal/gui: ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage
  ./internal/sessions, and go build -tags nogui .: ok; gofmt -l clean
- TestRequestDiskNamesItsSource hashes the package's files from disk
  and wants the same name. Broken by hand (embed request_*.go only):
  red; restored: green.

Not tried: an upgrade of the real app from one release to the next.
2026-10-25 07:23:45 +08:00
yetone 432393217a sessions: a shard's gob definitions are compiled once, not once a shard (#3493)
Every call shard's frame is its own gob stream: callFrame's type
definitions, then the frame. loadCalls made a gob.Decoder for each, so
each of a start's ~15.6k shards compiled the same definitions again. A
cold Requests build (every upgrade, since requests-v1.bin is keyed on the
binary) spent ~400 MB of its allocation and most of its GC there.

decodeFrame keeps one Decoder in a pool along with the definition bytes
it has read, and hands it only the value message when a frame's
definitions are byte for byte those. A frame of other definitions gets a
new Decoder; a Decoder that failed is dropped; bytes left over after the
frame are an error, as before.

Measured on a copy of real data (15,656 shards, 117 MB), cold step 2 of
the GUI warm-up (QueryPage(All)): allocation 2190 -> 1968 MB, CPU
5.51 -> 3.92 s, maxrss 448 -> ~410 MB. Wall stays ~2.2-2.6 s: the
serial row building on the consumer goroutine is the limit, next.

Run at this head (94503901c + this, origin/main has only 402577c15 in
internal/gateway since):
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage: ok
- TestDecodeFrameAsAFreshDecoder: every frame equals a fresh Decoder's,
  a frame of other definitions in between, and cut, padded, empty and
  definitions-only frames are errors that leave the next frame reading.
- TestDecodeFrameKeepsDefinitions: 8 allocations a frame kept vs 478
  fresh.
- Broken by hand: always a fresh Decoder -> KeepsDefinitions red (479
  vs 478); reuse without comparing definitions -> AsAFreshDecoder red
  ("unknown type id or corrupted data" on the other writer's frame).
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/sessions ok.
2026-10-25 06:45:23 +08:00
yetone 500aa70965 sessions: listing the session files stats them on a few goroutines and sweeps the shard folder once a minute
Every Requests page lists every session file again
(CallSourcesAndCodexIdentities), and on a busy machine that listing was
most of a warm page after the pairing memo (#3493): ~130ms for 15.6k
Codex rollouts and the Claude Code transcripts, of which the lstat of
each rollout was half, stat()ing each Claude file a sixth, and
pruneCalls a sixth: it read the ~16k-shard cache folder and sha256'd
every path on each call.

- statFiles stats the files a walk found on up to 8 goroutines (from 512
  files), keeping the walk's order and leaving out what is gone or no
  regular file, as before. Codex's still take their info from the walk's
  entry (free on Windows), Claude Code's from os.Stat.
- pruneCalls still drops the in-memory entries of gone files each call,
  but looks over the shard folder (and hashes the paths for it) at most
  once a minute, and at once when the cache folder moved. Temps already
  waited an hour; an orphan shard waits up to a minute more.

Run at 4982ded8a (origin/main, fetched):
go test -timeout 45m of agent (363s), cli (77.7s), davsync (78.4s),
gateway (533s), gui (150s), otlp (20.4s), tui (33.6s), tune (2.9s), usage
(51.4s), usageapi (14.8s): ok. sessions was red at first:
TestRequestShardsAreBoundedAndIndependent found a removed session's shard
still there, since the sweep waited its minute. pruneCalls now sweeps at
once when a file it had read is gone; sessions ok (19.2s) after, and
usage (18.6s) and usageapi (4.6s) again. gofmt clean; GOOS=linux and
GOOS=windows go vet -tags nogui ./internal/sessions/ clean.

Real data (sandbox HOME with the live ~/.codex/sessions and
~/.claude/projects symlinked, read only): the old and new listings,
dumped as path, key, agent, size and mtime, are the same 15,601 sources
in the same order with the same 12,077 Codex identities. Mean of 20
listings after a first one, load ~160: old 142 / 132 ms, new 56 / 66 ms.

Tests: TestCodexFilesStatInOrder (new; 1500 rollouts with folders,
links and files of every size in one day, -race -count=3) is red when
statFiles keeps what failed to stat and when a worker skips half its
batch. TestCallShardsSweptOnceAMinute (new) is red with the gate taken
out. TestAbandonedCallTempsAndLRU now clears the gate before the call
that must sweep.
2026-10-25 05:42:59 +08:00
yetone 0e643b14e4 sessions: a screenshot's line is read thinned, not gathered whole (#3318)
A cold read of the sessions gathered every long line it read whole
(takeLong), to take a timestamp, a folder and a session id off it. In a
10GB Claude projects folder and a 50GB Codex sessions folder the lines
behind that were Claude Code tool results holding a screenshot twice
(message and toolUseResult), Claude Code's api-request-blob lines (up to
15MB) and 154 Codex prompts with screenshots (5 to 15MB a line). Spread
over the read's workers they held 130 to 154MB live at its peak.

scanThin hands such a line on thinned, a chunk at a time, never whole:
- Claude (summary and calls): a user line whose message is a tool result,
  or a line of Claude Code's own other than a title or summary (both read
  only for keys, timestamp, folder and session id), has every string cut
  to 4KB.
- Codex (summary): a line the head lets through has only its data: URLs
  cut; a prompt's text is kept whole.
Every byte outside a string is kept, an escape is kept whole or not at
all, and a cut never splits a rune, so the line stays JSON and a search
for a quoted key finds what it found before. Lines over maxLine are still
passed over.

Run:
- TestThinnerKeepsJSON: 200 rounds of random chunk splits (1 to 7 and up
  to 9000 bytes) over a line with escapes, \u surrogate pairs and CJK;
  red when escapes are ignored.
- TestThinToolResultReadsTheSame: claudeLine (main and not) and
  claudeCallLine give the same state thinned as whole over two 3MB tool
  results; a thinned read allocates under 3MB (red at 7.9 to 8.4MB with
  the thinning off).
- TestThinCodexKeepsPromptText: codexHead+codexBody give the same state
  with a 3MB image cut, the 21KB prompt kept whole; red when every
  string is cut.
- go test ./internal/sessions ./internal/gui ./internal/usage
  -timeout 45m: sessions and usage ok; gui red in
  TestRestartHandsTheGatewayOver (12 of 13 requests answered, a reset),
  which is #3451; alone -count=3 ok.
- GOOS=linux and windows go vet -tags nogui ./internal/sessions, gofmt.
- Real use: magpie web --gateway under a sandbox HOME whose
  .claude/projects and .codex/sessions are the owner's real ones (10GB
  and 50GB), caches cold, /api/sessions?limit=50 then the 7 and 30 day
  overview (load ~40 on the machine):
    before (e57e78563): takeLong 130 to 154MB live at +6 to +20s, heap
    in use 246 to 291MB, peak footprint 590MB, ps RSS 729MB, heapSys
    736MB
    after: takeLong gone from the heap, heap in use 118MB at +12s, peak
    footprint 483MB, ps RSS 636MB, heapSys 615MB
  A debug build printing each line gathered whole found the 154 Codex
  prompts and four api-request-blob lines; this commit covers both.

Not tried: Windows and Linux real reads; a Claude prompt (not a tool
result) with pasted images is still read whole, as claudeLine reads its
text.
2026-10-25 01:39:40 +08:00
yetone ff6f3188bd sessions: a grown Claude file is read on after a restart, with the window it had (#3493)
A Claude Code session's revision window lived in memory alone, so after
magpie started again (every update), or let a ninth live session's
window go, each Claude file that had grown was read again from its
first line. On the owner's real ~/.claude a live 2 GB session and a
372 MB one were read whole for the first Requests page: 2.4 GB, 7.4s.

The window is bounded (claudeRevisionEntries), so readCalls now keeps
it beside the file's shard (<hash>.rev, temp and rename, ~60 KB), with
the Off and ContentHash of the read that made it. A read whose old
state has no window takes it from there when both match, and reads on.
A file no longer being worked on drops its window as before, and its
.rev with it; pruneCalls takes away a .rev whose shard is gone.

Measured (internal/gui handler, sandbox HOME with the owner's real
~/.codex and ~/.claude, 15,553 sources): the first ledger week after a
restart 7.4s -> 1.7-2.4s across three restarts; 14 .rev files, 8-67 KB.

Run at this tree: go test -count=1 -timeout 45m ./internal/sessions
./internal/usage ./internal/usageapi ok; GOOS=linux and windows go vet
-tags nogui ./internal/sessions ok. TestClaudeFileReadOnAfterRestart is
red with withCallRevisions turned off ("read again from its start"),
and checks the calls read on equal a read from the start, a revised
recent message included.

The Sessions summary's own Claude window, in memory alone the same way,
is kept by the next commit.
2026-10-24 23:40:00 +08:00
yetone efd1b697e4 sessions: a cached file's calls are read into a slice made for them
loadCalls appended each decoded patch to a nil slice, so every cached
file's calls grew through append's steps. In a warm start's 30s
alloc_space profile (sandbox HOME, ~380k calls) that append was 509 MB,
the largest single site. Each frame now grows the slice once by its
patch count (slices.Grow), which a frame of new calls fills exactly.

TestLoadedCallsAreSizedOnce: 3000 cached calls came back in a slice of
3246 on the old code (red, run with the change stashed); 3006 now, the
allocator's size class. It also reads back a second appended frame.
go test -tags nogui ./internal/sessions/ ./internal/usage/: ok.

At 8b48dc5d6 (this commit and the two beside it, on 5c557c793):
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./...
clean; go test -race -tags nogui ./internal/usage/ ./internal/sessions/
ok; go test -tags nogui -timeout 45m ./... with pipefail: 68 packages
ok, no FAIL.
Warm start in a sandbox HOME, magpie serve --web (ps RSS / footprint /
heapSys at 30s): origin/main 650 / 213 / 649 MB, all three 606 / 208 /
598 MB. Allocated in the first 30s: 2557 MB before, 1878 MB after.
2026-10-21 09:41:29 +08:00
yetone 5466cc7604 sessions: a packed Codex rollout whose stamp changed is decompressed once at start, for both Sessions and Requests
The start's warm-up (gui warmSessions) parses every changed session file
for the Sessions page (statsFor -> refresh -> parse), then reads every
changed file's calls for Requests (usage.QueryPage -> prefetchSources ->
ReadCallSource -> readCalls). A packed rollout (.jsonl.zst) is decompressed
whole for each read, so when the Codex app repacked all 11,591 of them on
10-20 every one was decompressed and scanned twice (~48 GB of zstd read
twice; 75 GB of zstd allocation in 67 min, 37.8 GB on each path through
scanAt).

refresh's reader now takes a packed Codex rollout's calls along
(callsAlong) when their shard is stale too: one scanAt, each line shown to
both heads (codexHead, callHead) exactly as on a scan of its own, and
handed to codexBody and/or codexCallLine as each head asked. The calls
are then written and kept as readCalls would (writeCalls, keepCalls under
the generation check), so the Requests read that follows finds an
up-to-date shard. The ride holds the file's calls lock, taken before the
read slot as readCalls takes it, so a readCalls of the same file waits for
the ride rather than read it again, and no lock order is reversed. A scan
that fails leaves the calls to readCalls, as before. Plain rollouts, other
agents and a file whose calls are already current are read as before.

The warm-up already reads with a quarter of the cores (quiet.go: readSlot,
#1665) on both paths; this halves the work done under that cap, nothing
more is changed there.

Verified (sandbox HOME, Go caches pinned):
- TestPackedRolloutReadOnceForSessionsAndCalls (new): 3 packed rollouts
  (the two fixtures + a 40-call one). Calls-then-sessions scans each twice
  (the reference); sessions-then-calls with nothing kept, and again after
  every file's mtime changes, scans each once, and the calls, List and
  StatsAt are reflect.DeepEqual to the reference. With callsAlong replaced
  by nil in refresh it fails: "first read: ...zst scanned 2 times, want
  once" for all 3 files, and the same after repacking (6 errors). Restored:
  ok. -race -count=20: ok.
- Real rollouts: copies of 120 and of 180 of ~/.codex/sessions' packed
  rollouts (528 MB / 739 MB compressed), warm-up order (List, StatsAt, then
  ReadCallSource with 8 readers), with nothing kept ("cold") and after every
  mtime changed ("stamp"); old = callsAlong nil:
    120 files, full speed:  zst scans 240 -> 120; wall cold 0.84/0.90s ->
      0.52/0.48s, stamp 0.99/0.70s -> 0.43/0.52s; alloc 0.45-0.48 GB ->
      0.43-0.44 GB cold, 0.38-0.41 GB -> 0.38-0.39 GB stamp.
    180 files, inside sessions.Warm (3 readers of 14 cores): zst scans
      360 -> 180; wall cold 1.97/2.18s -> 1.48/1.59s, stamp 1.89/2.22s ->
      1.35/1.63s; alloc 0.57-0.63 GB both ways.
  Lists, stats and every source's calls, JSON-encoded, are byte-identical
  old vs new in all four phases (cmp).
  Allocation hardly moves: in a pprof of the 120-file run, 482 MB of ~800
  MB is scanAt gathering lines longer than its 1 MiB buffer (the packed
  rollouts' multi-MB session_meta lines), which only one of the two
  readers ever gathered, and zstd's own history buffers are 120-144 MB.
  What the change saves is the second decompression: CPU and disk reads.
- gofmt -l on the changed files: nothing. GOOS=linux go vet -tags nogui
  ./... ok; GOOS=windows go vet -tags nogui ./... ok.
- go test -timeout 45m ./internal/sessions/ ./internal/usage/
  ./internal/gui/: ok 13.8s / 17.1s / 81.7s. go test -race
  ./internal/sessions/: ok 44.5s after the next commit's test fix (red on
  origin/main a9304efe0 without it, TestManageReadsOnlyTheAgentsItShows).
Not run: the full ./... suite, the GUI Playwright suite (no GUI change),
a live magpie start against all 11,591 rollouts, Windows/Linux runs.
2026-10-20 23:50:02 +08:00
yetone ec396be60c sessions: a dsh session read for calls is read on, not whole
dsh's calls were read by a whole-file reader: each reply appended to a
session made Usage's ledger read the whole file again and, packed,
decompress every frame of it. parseDsh already reads on from the frame
it left off in (frames.go, 827c304d9); the call reader now does too.

readDshCalls is handed what the last read came to and reads on from its
tail (scanFrames for a packed file, scanAt for a plain one), carrying
dsh's header in dshCarry. It says how many of the calls it gives were
kept from before, so only the new ones are appended to the disk shard
(resumeCallReaders in call_cache.go). The carry is kept in the shard's
state as JSON (callDiskState.Dsh), since the in-memory read is let go
after packing. A fork's inherited end-seed met in a later read drops
what was counted before it and rewrites the shard whole, as the whole
read did by cutting at the last one. A file cut short or replaced
(tail.holds) is read whole. One change from before, as for parseDsh: a
last line not ended by a newline waits for it.

Measured (CPU, getrusage; 50 MB of events, ~3600 calls, a reply
appended between reads; packed: frames of 200 lines; the old reader
measured from a worktree at 432a2ba5e with the same harness; machine at
load ~500):
  plain  before: 91-109 ms CPU, 0.5-1.3 s wall per read after an append
  plain  after:  0.6-7.7 ms CPU, 2-129 ms wall
  packed before: 214-230 ms CPU, 3.5-4.8 s wall per read after an append
  packed after:  1.2-1.5 ms CPU, 13-46 ms wall
  first read unchanged (plain ~60-105 ms, packed ~195-215 ms CPU)

Tests: TestDshCallsReadOnlyWhatWasAppended (packed dsh-a) checks where
each read starts (scanHook) and its calls: a frame appended is read
alone; half a frame waits; a frame ending inside a line is read on from
that frame; after resetCalls() the read goes on from the disk shard;
cut short reads from 0. TestDshCallsEndSeedAcrossReads: dsh-c's
end-seed arriving in a later read drops the seeded call, its own is
read on, and the shard holds only that after resetCalls().
Broken by hand: no resume -> both red ("read from 0, want 654"); the
carry not written to the shard -> both red (same); the end-seed not
rewriting the shard -> red ("the fork's own ...: [50 100]").

Run: go test ./internal/sessions -run 'Dsh|Call|Usage|Pi' -count=1 ok;
gofmt -l and go vet ./internal/sessions clean. The full-suite record is
in the last commit of this series.
2026-10-19 11:30:48 +08:00
yetone da9fc17eb6 sessions: a Pi or omp session file read for calls is read on, not whole
Pi's and omp's calls (#1951) were read by a whole-file reader: every
time a session file grew by one line, Usage's ledger decoded the whole
file again, its header and every message, and rewrote its disk shard.
Pi and omp only append to a session file, a line an entry, as Kimi
Code's wire file is.

Pi and omp are now line readers (lineCallReaders): a file that only grew
is read on from the last whole line, and only the calls it adds are
appended to the shard. What a later line's call is read with is carried
in piCarry on the callFile: the header's cwd, a fork's start (what came
before it is its parent's), and the provider and model in use for a
compaction's or tool result's usage. That carry is kept in the shard's
state too, flat (callDiskState.Pi*), as the in-memory read is let go
after packing: a carry that lived only in memory made every append read
from 0 again. A shard written before has no carry (piCallsKept false)
and its file is read whole once more. Cut shorter, written over, or
grown at a changed head: read whole again (prepareCalls' head and
prefix hashes, as for Kimi).

Measured (CPU, getrusage; one 50 MB Pi session, ~3500 calls, a call
appended between reads; the old reader measured from a worktree at
432a2ba5e with the same harness; machine at load ~500):
  before: 112-153 ms CPU, 1.0-2.5 s wall per read after an append
  after:  1.1-3.1 ms CPU, 5-57 ms wall per read after an append;
          first read ~95 ms CPU, as before

Test: TestPiCallsReadOnlyWhatWasAppended (a fork, its model set once at
the top, compaction usage) checks where each read starts (scanHook) and
the calls it gives: an append with a half line after reads from the old
end and leaves the half line; finished, it is read; a line older than
the fork's start is left out after a resume as on a whole read; the
model, provider and cwd stay right on calls read on; after resetCalls()
the read resumes from the disk shard; cut shorter and written over read
from 0.
Broken by hand: piCallsKept always false -> red ("read from 0, want
686"); the carry not written to the shard -> red (same); begin run on
every read, the carry lost -> red ("calls [1 2], want [1 2 3]").

Run: go test ./internal/sessions -run 'Pi|Omp|OMP|Call|Usage' -count=1
ok; gofmt -l and go vet ./internal/sessions clean. The full-suite record
is in the last commit of this series.
2026-10-19 11:30:47 +08:00
yetone 11b42c0e2e sessions: a Kimi Code wire file read for calls is read on, not whole
Kimi Code's calls (#1607) were read by a whole-file reader: every poll of
Usage after a session's wire.jsonl grew decoded the whole file again for
the one or two records added. Kimi only appends to that file, a record a
line, so its calls now go through the line path Claude Code's and Codex's
take: lineCallReaders gives readCalls a begin (the session id) and a line
reader, and prepareCalls reads a grown file on from where the last read
left off, writing only the added calls to the disk shard. A half-written
last line waits for the rest; a file cut shorter, or written over, fails
the head and prefix checks and is read whole again.

That alone did not resume for any main session: Kimi's listing folds
state.json's size into the main wire file's, so the prefix hash, taken
over the listed size, ran past the end of the file and came back empty,
and an empty hash never matches. The hash is now taken over the bytes the
reader consumed (Off) rather than the listed size; for a Claude or Codex
file with no partial tail the two are the same, so their shards keep
their hashes. A title change in state.json still re-lists the file, and
now costs a resume, not a whole read.

TestKimiCodeForkCountsOnce wrote its subagent files without a final
newline, which a line reader keeps as an unfinished line; real wire files
end in one (all nine of the reporter's do), so the fixture now does too.

Measured (CPU, getrusage; one 50 MB wire.jsonl with a state.json beside
it, one record appended between reads, readCalls alone; machine loaded):
  before: 40-90 ms CPU, 240-980 ms wall per read after an append
  after:  0.9-1.1 ms CPU, 10-21 ms wall per read after an append;
          first read ~40-55 ms

Test: TestKimiCodeCallsReadOnlyWhatWasAppended (state.json present)
checks where each scan starts and what calls come back: appended with a
half line after, the half line finished, cut shorter, written over.
Broken by hand: no resume for kimi -> red ("read from 0, want 567");
resume without the size/prefix checks -> red ("cut shorter: read from
945, want 0"); the hash over the listed size again -> red ("read from 0,
want 567").

Run: go test ./internal/sessions -run 'Kimi|Call|Codex|Claude|Long|Grow|
Append|Resume|Prefix|Hash' -count=1 ok (359s); gofmt -l and go vet
./internal/sessions clean. The full-suite record is in the last commit
of this series.
2026-10-19 11:30:47 +08:00
Hogee 3c4b4dc973 sessions, usage: a Codex subagent with no title takes its parent's spawn_agent task_name, its nickname shows apart, and Usage requests say which calls were compactions (#1591, Hogeexxl)
Hogeexxl's change (his fork branch codex/codex-session-details, f7c176c9),
cherry-picked with his authorship:

- A Codex child thread whose title is still empty after the existing
  precedence takes the task_name of the parent's spawn_agent call, linked by
  the call id and the SubAgentActivity "started" item that names the child's
  agent_thread_id. Conflicting links leave the title empty.
- session_meta.agent_nickname is exposed as `nickname` on the list, one,
  manage and overview responses, beside the title, not in place of it.
- GET /api/usage/requests and /v1/magpie/usage/requests carry `compaction`
  (true/false) for Codex calls with native evidence, and leave it out
  otherwise. A gateway row matched by a unique response_id takes the marker
  and keeps its own model, usage, cost and kind.
- Flags bits 1024 (rowCompactionKnown) and 2048 (rowCompaction) are new.
  TestRowFlagsApart covers them, and they don't overlap 1..512. The sessions
  cache goes to version 21 and the calls cache to calls-v15.

Review:
- Rollout format checked against Codex's source (openai/codex 669449b):
  - v2 spawn_agent args carry task_name.
  - A paginated rollout persists item_completed with a SubAgentActivity
    item: kind "started", id = the call id, agent_thread_id.
  - SessionMeta has a top-level agent_nickname, which Codex's own list.rs
    and metadata.rs read too.
  - compaction_response_id lives in token_usage_record.
  Gaps in legacy rollouts and in calls without a response_id are fixed in
  the next two commits.
- Privacy: only a title string the user's own Codex wrote and a boolean
  are added to local API responses. Nothing new goes to a vendor or to
  telemetry. The ingest POST parses fields one by one, so it is unchanged.
- No .github, dependency or network changes.

What was run:
- His tests pass: go test -tags nogui ./internal/sessions ./internal/usage,
  and the two new internal/gui API tests.
- Broken by hand, each caught by his tests:
  - the nickname read removed;
  - the conflict checks removed;
  - mergeCodexCompactions broken;
  - the gateway pair's setCodexCompaction removed;
  - the flag read forced to true.
- Not caught:
  - the parent check on the title link (covered by a test in the next
    commit);
  - `copy.codexCompactions = nil` in cloneCodexChunks removed. That line is
    defensive only: the shared chunks never hold the map.
- The gofmt, vet and full-suite record for the three commits is in the
  last one.
2026-10-15 04:21:31 +08:00
Hogee 644f4316f9 sessions, usage, gui: separate Codex thread relationships and consumption (#1591)
Preserve native Codex thread IDs and explicit parent chains. Associate gateway
calls with their actual thread by unique response ID before legacy matching;
fold identical native history copies and keep ambiguous actors unknown.

Existing Sessions APIs expose optional Codex roles, parent/root relationships
and per-thread model/effort consumption. The overview uses its existing calendar
range. Usage request APIs expose query-time actor classification and reuse
session/subagent/parent_agent for Codex. Other agents, pricing, gateway routing,
UI assets, raw Usage logs and model-only aggregation retain their semantics.

Verified after rebasing onto main 331c27703a,
at commit 50baace0a52953263dddc49f4dc55f97a8457dd1, code tree
78743e334f8c841e2a188aafe26996c016a8fa4b. Only this message is amended afterward.
Go 1.26.8 darwin/arm64; tests used temporary HOME and pinned Go caches.

Passed (each exit 0):
- git diff --name-only origin/main...HEAD -- '*.go' | xargs gofmt -l (no output)
- go vet ./...
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go vet -tags nogui ./...
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go vet ./...
- go build -o /tmp/magpie-codex-session-identity-p4-darwin
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -tags nogui -o /tmp/magpie-codex-session-identity-p4-linux
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -o /tmp/magpie-codex-session-identity-p4-windows.exe
- go test -tags nogui ./...
- go test -race -tags nogui ./internal/sessions ./internal/usage ./internal/gui -run '^(TestCodexIdentityParentChainsAndSummaryCache|TestCodexIdentityParentMergeAcrossRolloutFiles|TestCodexCallThreadIDPriorityAndCache|TestCodexCompactionPromotesThreadID|TestCodexSourceNativeVariants|TestCodexIdentityFieldsOmitOtherAgents|TestCodexIdentityInvalidatesOldSummaryCache|TestCodexLedgerResponseIdentityAndOwnConsumption|TestCodexRequestPageFoldsCopiesBeforeResponseMatching|TestCodexExactResponsePairPreemptsLegacyMatchInLedgerAndDirect|TestCodexQueryPageExactResponsePairPreemptsLegacyMatch|TestCodexRejectedGatewayDoesNotPairWithNativeCall|TestCodexKnownSubagentWithUnknownRootKeepsOwnConsumption|TestCodexQueryPageRefreshesIdentityAndSharesJSONFields|TestCodexActorSurvivesPackedRequestChunk|TestPackedRequestPageCallerAndRouteIdentity|TestPackedGatewayRetainsOversizedSnapshot|TestCodexSessionAPIAddsOwnModelEffort)$' -count=1
- git diff --check

Behavior-break proof: removing identity/thread-ID promotion fails native identity,
upgrade/conflict and compaction assertions. Disabling exact-pair preemption loses
a neighboring main call. Removing API enrichment yields missing consumption;
using All for a 7-day overview yields 740/74 instead of 40/4. Restored code passed
its targeted tests and the final checks above.

Native checks had Clang enum/linker deployment-target warnings.
Linux/Windows runtime, real accounts/vendors and manual UI were not exercised.
No frontend suite was run because the change does not touch GUI assets.

Refs #1591 (Codex portion only).

Reviewed and applied by yetone (cherry-picked from Hogeexxl's fork, bf8c8c9e).
The one conflict was call_cache.go's version: main had taken calls-v13 for
compaction times (e1dcd1e1d), so this is calls-v14. Run with the follow-up
commit on top, at tree 122b933ba4c474e443f2b29c6d0a4163ae364f78 on origin/main e5cd125f0 (Go 1.26.8
darwin/arm64, sandbox HOME, private GOCACHE):
- gofmt -l on the changed files: none
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- the darwin, linux (nogui) and windows builds
- go test -tags nogui -timeout 40m ./...: all ok
- go test -race -tags nogui -run 'Codex|Packed|QueryPage|RequestPage'
  ./internal/sessions ./internal/usage ./internal/gui: ok
Broken by hand, each red: codexIdentityRow not setting Subagent (8 usage
tests), setting it for a main thread too (2), Session kept raw instead of
the root (7), thread_spawn's parent_thread_id not read (3 sessions tests),
response pairs not reserved before the old matching (6).
Not tried: a real Codex subagent rollout (none on this machine; every
recent rollout is a vscode main thread whose session_id equals its id),
and the GUI by hand. Claude Code's fields are unchanged.
2026-10-14 22:45:40 +08:00
yetone e1dcd1e1d7 tune: a compaction window advised never makes you wait longer on compactions, and says the wait (HirotaNagai on X)
Tuned for you advised the compaction window by tokens alone, so a smaller
window that compacts far more often could be advised however long each
compaction keeps the user waiting.

What changed
- sessions: a call now carries how long a compaction took (Call.Compact).
  Claude Code's compact_boundary line gives compactMetadata.durationMs,
  which goes on the first call after it that isn't an error. Codex compacts
  by a call of its own (the token_usage_record a compacted line names), and
  that call's own time is the compaction's. Older rollouts with no such
  record stay untimed. callCacheVersion is now calls-v13.
- tune: with 3 or more compactions timed for a model (minTimed), Facts.took
  is their median in seconds, and each window's Point.wait is its
  compactions x took. When compactions are timed, the advice never takes a
  window that compacts more often than the current one. Of the windows that
  don't, it takes the cheapest, and of those within 3% of that (sameCost)
  the one that compacts least. Tokens and seconds share no unit the files
  measure, so magpie doesn't trade one for the other at a guessed rate. The
  token-cheapest window is reported (cheapest, wait_cheapest) so the user
  can pick it. A model with fewer than 3 timed compactions is advised as
  before, with no wait shown.
- GUI (Usage > Context): when timed, the advice is labelled
  "Tokens + wait". The explanation says what a compaction took, the wait at
  the advice against the window now, and the cheaper window that would wait
  longer (if it saves 3% or more). The caveat says tokens and waiting only.
  The picker shows each window's wait, with "Fewest tokens" on the
  cheapest. Untimed rows are unchanged. The new strings are in zh, zh-TW,
  ja and de.
- docs/subsystems/agent-wiring.md describes the timing sources and the
  rule.

What was run
- go test -tags nogui ./internal/sessions ./internal/tune ./internal/gui
  ./internal/agent pass.
  - internal/agent ran before the rebase. It took 1416s under a load
    average of 120-300 and passed with -timeout 40m (the default 10m timed
    out mid-suite). Its Tune/Compact/CacheTTL tests pass on their own.
  - sessions, tune and gui ran again after rebasing on origin/main
    331c27703. fcd6f3519, the head this was pushed onto, touches none of
    these files.
  - internal/gui's TestProviderListReadsSettingsOnce failed 1 of 3 runs
    under load (7.0s against its 2s bar). It passed 6 of 6 on this branch
    and 9 of 9 on origin/main 4048ead7f, and it doesn't touch this code.
    Filed as #2185.
  - TestCallsClaudeCompactTook and TestCallsCodexCompactTook check the
    timings, also after Reset.
  - TestCompactTimedWaitsLeast checks the advice from 1M, 600K and 150K.
    With the timed rule disabled it fails ("advised 260000 makes 36
    compactions, more than 4 now").
  - TestCompactUntimedUnchanged checks that 2 timed compactions give the
    same advice as none, with no wait.
- GUI: context-tune, i18n-keys and context-window pass, 97/97 in Chromium
  and WebKit, in en/zh/zh-TW/ja/de at 360 and 1100 px. The new timed test
  fails against the old assets ("Fewest tokens" where "Tokens + wait" is
  expected).
- gofmt -l is clean. go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./... are clean.
- Real data, from copies of the owner's 4 Codex rollouts and 8 Claude
  transcripts in a sandbox HOME:
  - Compactions took 28-46s (opus-5-5), 85-139s (fable-5-1) and 52-121s
    (Codex gpt-5.6-sol).
  - gpt-5.6-sol keeps 230K. Before this change it was advised 70K: 44%
    fewer tokens, but about 3.5h of waiting against 30m.
  - opus-5 moves 200K to 190K, with 6% fewer tokens and the same wait.
  - Untimed models are unchanged.

Not tried: the live app with real accounts. The replay assumes a
compaction takes the same time at every window, since the files only time
compactions near the window the user ran with.
2026-10-14 20:03:53 +08:00
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