Commit Graph
63 Commits
Author SHA1 Message Date
yetone e4e9eb0928 usage: a ZCode call to a provider added by hand at magpie's address is not a local session's (jiangshangmuyun on X)
The Usage page listed one ZCode call as "new-provider · 本地会话" among the
gateway's own rows for the same Trae CN DeepSeek calls. The reporter has one
ZCode window and routes everything through magpie.

Cause: the user added magpie to ZCode by hand as a provider of their own
("new-provider", base URL magpie's gateway), not through magpie's connect,
which writes the id "magpie". ZCode records that id beside each reply, and
readZCodeCalls left out only "magpie"/"dial" (ocGatewayProvider). Its calls
were read from ZCode's database as well as logged by the gateway, and only
hidden again where pairing by session, tokens and end time matched; a call
whose counts didn't agree was listed twice as a "local session".

Fix: zcodeGateway also takes any provider whose base URL, in ZCode's
config.json or provider_config.json, is this machine (loopback, localhost,
0.0.0.0, one of its own addresses) on the gateway's port (MAGPIE_ADDR or the
saved port). Such calls are left out before pairing, as "magpie" ones are.
zcode's call parse version is 4, so cached shards are read again. Like
workbuddyGateway it reads the configuration as it is now. The label itself
is unchanged: a call that did go straight to a vendor is still a local
session's.

Siblings filed, not changed: OpenCode/MiMo (ocGatewayProvider), Pi
(piGateway) and dsh still match the gateway by provider name only (#7193).

Go run on mote at this change on base 9bf5848c1, rebased onto e2e8ea253
(no internal/sessions, usage or GUI file changed between): go test -count=1 ./internal/sessions
./internal/usage ./internal/usageapi (ok); GOOS=darwin/linux/windows go vet of
those packages (clean); gofmt -l clean. Broken by hand: with ocGatewayProvider
back in readZCodeCalls, TestZCodeHandAddedGatewayProvider is red ("a call to a
provider at the gateway's address was read as a local session's").
GUI (no GUI file changed, so as a check of the Usage page that shows these
rows): every usage-*, session-identity and i18n-* file, chromium and webkit,
each language they cover, on mote under load ~40: 1670 of 1777 pass. The 107
reds are in 12 usage files (usage-agents-hide, usage-chart-line,
usage-speed-all-models, usage-upload, usage-ledger and 7 more) and fail the
same at origin/main e2e8ea253 without this change (107 of 308 in those files,
same tests). Filed: #2276, #5834, #6003, #6743, #6790, #6975.
Not tried: the reporter's real ZCode database and config (this computer has
no ZCode); why that one call's tokens didn't pair (no data); the full Go suite.
2026-11-19 17:39:35 +08:00
yetone de58a3879b sessions: a cold read packs idle Claude sessions' calls into one file
shangyuan0818 on X: on Windows, Usage -> Sessions took 18 to 25 s with
long Claude Code sessions. The cause: a cold read wrote a calls-v15 .gob
shard and a .rev for every Claude session, about 21k files for 12k
sessions, and Windows Defender scans each file as it is closed.

Sessions not changed within the hour are now written into one
calls-v15/*.pack per pass (MPCALLS1 magic, the frames, a gob index of
path/offset/count, length, CRC32, magic). It is written to a temp file
and renamed, and flushed at the end of a pass, at checkpoints, in Saved
and every 32 MB. A session's own shard is read before the pack, so a
session that grows gets its own shard and its lines are appended there
as before. A bad pack means the source is read again. The hourly prune
sweeps packs no session points at. Working sessions keep a shard and a
.rev as before.

Measured on xiaomi-gpu (Windows 11, Defender on), fixture of 12,016
Claude session files, no magpie cache, first /api/sessions reply, the
runs alternating old and new:
  origin/main build: 31.67 s, 25.26 s, 20.74 s
  this change:        5.92 s,  5.85 s,  5.65 s
  restart with the pack written: 1.97 s and 2.16 s; then 0.25 to 0.31 s.
  The cache held 1 .pack and 4 .gob.

Tests (call_pack_test.go): TestColdSessionsReadWritesOnePack,
TestPackedCallsServeRequests, TestPackedSessionGrows. With the pack
branch turned off by hand the first fails (.gob:63 .rev:62) and the
second finds 0 packs.

Run at 4ace48feb (this change on origin/main 2ab2f6913):
- gofmt -l: clean.
- go test ./... -timeout 45m -count=1 on mote: 101 packages ok
  (internal/sessions 154 s), 3 red, none in code this touches, each
  filed: internal/cli TestHealthcheckFindsTheRunningGatewayWithoutMagpieAddr,
  TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr and
  TestUpdateFindsAMagpieThatWroteNoRecord (#6223: another session's ssh
  forward listened on mote's 127.0.0.1:3425); internal/gateway
  TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117) and
  TestLaneLimitRoutes (#5150); internal/gui
  TestAppReplacesItsOlderGatewayOnceIdle (#6297) and
  TestSettingsSaveKeepsWhatItDoesNotSend (#7127, red since f6a538ece).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go
  build: clean.
- internal/gui/tests/sessions-*.test.cjs (46 files): 322 of 322 in
  chromium, 322 of 322 in webkit.
- wsl-run go test ./internal/sessions: ok (25.3 s), at the base before
  the rebase.
- win-run go test ./internal/sessions: 4 reds, the same on origin/main
  07d19510f and filed as #6071 (TestAgySessions, TestAgyRowOnly,
  TestAntigravityAppFolder, TestCCListingKeepsItsNames). go vet clean.

Rebased onto fcbc1a2d0 (three gateway commits, none in
internal/sessions or its doc). At the pushed head: go test
./internal/sessions ok (209 s); go vet of it on darwin, linux (nogui)
and windows clean; go build clean.

Not tried: a real user's profile; the timings use a generated fixture
the size of the report.
2026-11-19 01:22:40 +08:00
yetone 1549ccf743 sessions: agy's and Antigravity's own calls carry their first-token time and duration (guyng35955 on X)
Usage → Requests showed agy's own calls with no time to the first
token, no duration and so no speed. Those calls don't go through the
gateway, which is where other calls are timed, and the readers of agy's
and the Antigravity app's conversations never read the step's times.

Each step's metadata row (exa.cortex_pb.CortexStepMetadata) has them:
1 created_at, 6 viewable_at, 7 finished_generating_at. A model step is
created as its request goes out, so 6 less 1 is the time to the first
token and 7 less 1 the call's duration (stepTimesOf). A response that
two steps share is timed from the first step's start to the last's end.
A step with no end, or times out of order, has none (unknown, not 0).
agy and antigravity call-cache versions go to 2 so cached shards are
read again.

Checked with real agy 1.5.9 in a sandbox HOME against a fake Gemini
endpoint that held its first chunk 2.01s and ended at 4.03s: the row
said 2014ms and 4032ms. That row and transcript are the new fixture
(testdata/agy-times).

Run:
- TestAgyCallsCarryTheirTimes, TestAntigravityAppCallTimes,
  TestAntigravityAppOneResponseTimedWhole, TestStepTimesUnknown: red
  on the old readers (all 0ms), green on these (mote).
- go vet ./internal/sessions ./internal/usage, GOOS=linux and
  GOOS=windows go vet ./internal/sessions, gofmt -l: clean (mote).
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage:
  ok (mote, at 31dcfcc33).

Not run here: the full suite (running after the push) and the GUI suite
(no GUI change). Not tried: a real agy call to Google (the local
account is refused), so the times rest on the fake endpoint's run.
Seven other agents' own calls have the same gap: #6940.
2026-11-17 15:39:43 +08:00
yetone 90d54a2675 usage: Factory Droid's own sessions count under Not through magpie (_meouwu on X)
Droid's sessions were on the Sessions page, but Usage's "Not through
magpie" read no Droid calls, so what Droid spent straight at Factory or
a BYOK provider never added up.

Droid writes no tokens into a transcript: a message line has its time,
the message and a reply's modelId. Read from droid 0.231.0's binary
(its session schema) and the real runs in testdata/droid-skills, what a
session spent is only in <id>.settings.json: tokenUsage, its own running
total (input less the cache, output with thinking, cache read and
written), and lastCallTokenUsage, the latest call alone. So each session
is one call of its total, at its last message (the day Sessions already
counts the same total on), under its settings' model; a subagent's is
under the session that called it, a fork's starts at none.

- sessions: calls_droid.go reads a session with its settings whole
  (wholeCallReaders "droid"); droidFiles joins callSources, behind
  Reads("droid") and allowed() like the rest. WSL is not read: the
  Sessions page doesn't list Droid in a distro either.
- No double count: a session whose settings or any reply names magpie's
  own entry (custom:magpie/...) or a custom model whose baseUrl is the
  gateway's port on loopback is left out whole; the gateway counted those
  calls, and a total can't be split by model. A session is judged when
  read, again once it or its settings change.

Tests: TestDroidCalls (the 4 real droid 0.231.0 sessions: tokens, time,
model; custom:mh on localhost:11434 counted, on the gateway's port left
out; Reads off counts none), TestDroidCallsOfSessions (subagent, fork,
no settings, magpie's entry, Factory's own model), and
TestDirectDroidSessionTotals in usage. Both sessions tests are red on
origin/main (0 calls); with the gateway check broken by hand both go red
on the gateway cases.

Run (mote): go test ./internal/sessions
./internal/usage ok; go vet + GOOS=linux/windows go vet of both ok;
gofmt clean; go test ./internal/gui ./internal/agent ok.
Not tried: a real Droid session against Factory's own models (no Factory
account here); no GUI change.
2026-11-16 18:56:32 +08:00
yetone 91b3af8470 usage: Qoder's own calls are under Not through magpie, by the credits they cost (eating_dream on X)
Qoder's and Qoder CN's sessions were on the Sessions page and nowhere in
Usage: callSources never listed their files. They are Claude Code's
lines, and are now read for calls as Claude Code's are (ccCallAgent:
claudeCallLine, the call cache, continuations and revisions).

Qoder writes a reply on its own models ("auto" among them) with every
token count 0 unless QODER_EXPOSE_TOKEN_USAGE is set: the transcript
writer (vUl in qodercli, the same in Qoder.app's worker, qoder-agent-sdk)
zeroes them unless the model is a custom one, from qodercli 1.1.0 on. It
keeps the reply's credits. So such a call carries Credits (new on
sessions.Call, passed to the ledger's Record), counted with no tokens
and no price; "auto" names no model, so nothing is priced for it. A
model of the user's own, whose counts are written, is read and priced
as before. The GUI's direct section already shows credits (ledCredits).

Fixture: testdata/qoder-1.1.89 is lines as qodercli 1.1.89's writer
lays them out (key order, zeroed usage, credits/original_credits/
billable, a reply with no usage), read from its npm bundle; the ids are
made up. The older invented qoder fixtures got message ids of their own
(Calls counts a message id once across agents, and they shared
WorkBuddy's m1/m2).

Run (on mica, at f07e3e067's tree, rebased on 269e54de5):
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage
  ./internal/gui: ok
- GOOS=linux and GOOS=windows go vet of both packages: ok; gofmt -l clean
- red on the old code (origin/main's calls.go, call_cache.go,
  call_continuation.go, call_revisions.go, ledger.go with the new tests):
  TestQoderCalls got 0 calls, TestDirectQoderCallsByCredits Credits 0
  Credited 0

Not tried: no real Qoder transcript was captured (qodercli needs a
signed-in account here); the format comes from the bundle's writer. No
GUI change, so no GUI suite. A reply Qoder writes with no usage at all
is not counted. The tokens of Qoder's own models can't be shown: Qoder
doesn't write them.
2026-11-16 16:51:51 +08:00
yetone ab4b1cf38f sessions: a long Codex rollout is read on after a restart, not read again whole
shangyuan0818 on X: on Windows, Usage > Sessions took over ten seconds to
open with one very long session (tens to 100 MB), though there were only
a few sessions.

Cause: a Codex rollout's summary window (state.Codex) and its calls'
window (cxRun) lived in memory only. After a restart, or once the window
had been dropped, the first line a live rollout gained made parseRead,
prepareCalls and readsWhole read the rollout again from its first line:
once for the summary and once for the calls. Claude Code sessions were
already read on through their kept windows (#3493).

Fix: the window of a rollout being written (changed within the hour, the
same files memory keeps windows for) is now kept on disk with the parser
version, a window version, and the size, offset and content hash of the
read that made it. The summary's goes in codex-windows/<hash>.gob next
to sessions.json. It is written with sessions.json, and it is removed
once the cache drops that window. The calls' window goes in the shard's
.rev file next to Claude's. Each is used only when all of those match,
so a window from another read, or from an older layout, is never used;
the file is read whole instead, as before.

Measured (100 MB rollout built from testdata/codex-native-paginated.jsonl,
plus a 100 MB Claude Code session, GET /api/sessions in a sandbox HOME):
  mote (M5), before: after one line appended following a restart, 2.51 s
    (Codex alone 2.25 s). After: 9.7 ms (Codex alone 6.3 ms).
  Windows (xiaomi-gpu), before: 2.61 s. After: 22.8 ms.
  The first read with nothing kept is unchanged: 2.6 s on mote, 2.8 s on
    Windows. Warm and plain-restart opens were already 10 to 30 ms. stats
    and overview stayed at a few ms throughout.
  A real 32 MB rollout: 24 ms after an append, with 2 KB and 4 KB windows.
    A 100 MB rollout with a unique response id per turn: 11 ms, with
    623 KB and 834 KB windows.

Tests: TestCodexSessionReadOnAfterRestart reads a rollout, restarts, then
appends a replayed token_count and a new turn. It checks that neither
reader starts at offset 0, and that calls and the session's tokens,
models and cost match a read from scratch. TestCodexWindowLeavesWithItsSession
covers writing, reading back, refusing another read's window and
removal. TestPlainRolloutReadOnceForSessionsAndCalls (#4369) expected
both readers to start from 0 after a restart; it now expects them to
read on.

Broken by hand, each red: the summary window not read (starts [319830 0]);
the calls window not read ([0 319830]); a summary window emptied of what
it had seen (it panicked in codexUsageState.count, which is why the
version guard was added); a calls window emptied (62 calls vs 61).

Run: gofmt -l clean. GOOS=linux and GOOS=windows go vet -tags nogui ./...
on mote. Full go test -tags nogui -timeout 45m ./... on Linux (wsl-run,
magpie-desktop) at this change on 70bd270ae: every package ok but
internal/usage, whose TestRequestStateKeptAcrossACatalogFetchedAgain is
red the same way alone on origin/main 7b50e1f2c (11 of 20; a same-size
catalog write in one mtime tick, filed as #6572). mote's suite.lock had
five runs queued ahead, so its run of this change is still waiting.
Rebased onto 7b50e1f2c (7 files in internal/provider and internal/usage,
none under internal/sessions); provider, usage and sessions run again
there on Linux: all ok (#6572 passed this time). win-run ./internal/sessions/: only TestAgySessions,
TestAgyRowOnly, TestAntigravityAppFolder and TestCCListingKeepsItsNames
fail, and they fail the same way on origin/main ea9f2639b (#6071).
win-run -run 'Session|Usage|Calls' ./internal/gui/: only
TestGatewayModeStatsNameTheGatewaySessions fails, the same on ea9f2639b
(#6068).

Old data: right after updating, every user's live rollout is read whole
once more on its next change, since no window has been kept yet. From
then on it is read on. Nothing else changes for files not written within
the hour.

Not changed: WorkBuddy, WorkBuddy AI and CodeBuddy calls are still read
whole on every line (556 ms per 100 MB on mote), filed as #6565. Not
tried: the reporter's own machine and files.
2026-11-14 03:28:08 +08:00
yetone f798b4eb7a sessions: keeping a file's calls trims the revision windows only when it holds one
keepCalls and keepCallContinuation trimmed every kept window after each
keep, under callsMu: a sort of the candidates and a map, twice a file.
A request-index build reads ~11.5k session files through four workers,
and the files it reads are disk shards that hold no window (weight 0),
so each trim changed nothing while the workers queued on callsMu for it.
A block and mutex profile of a real-account rebuild showed ~55k
contentions on callsMu (about 5 a file), ~3.5 s of lock handoffs and
~4.3 s in pthread_cond_signal.

Now keepCalls trims only after keeping a file with a window, and
keepCallContinuation only after it adds an entry (its early returns add
none). Every window added is still trimmed at once, so the budgets hold
as before; a window aging out waits for the next keep that adds one.

Run: go test ./internal/sessions ./internal/usage ./internal/gui (ok, on
mica), go vet, GOOS=linux and GOOS=windows go vet ./internal/sessions,
gofmt -l. Real account on mote (75G sandbox HOME, network blocked): a
request-index rebuild forced by a new Anthropic price each run, CPU of
the process 30 s after start, alternating: v0.1.4052 21.25 / 17.68 /
15.95 s, this change 14.81 / 14.14 / 13.43 s (mean 18.3 -> 14.1 s).
Not tried: a test that counts trims; the change is a cost, and every
kept window is still trimmed by the same code.
2026-11-13 21:34:15 +08:00
yetone f5553d7103 sessions: a Pi subagent's calls are its lead session's, on its own model (nzvzbmz78932 on X)
nzvzbmz78932 on X: "在pi子代理中使用了deepseek 但是不显示用量". pi-subagents
(npm 0.88.1) runs each subagent as a Pi of its own, its session in
<lead file's folder>/<run id>/run-<n>/session.jsonl (async and parallel
runs a level deeper), or under extensions/subagent/config.json's
defaultSessionDir, its header's parentSession naming the lead's file.
magpie read only sessions/*/*.jsonl, so those files were never read. The
lead's `subagent` tool result carries the subagents' usage summed, and
piParse counted it on the lead's model and provider: a lead on magpie's
entry made it the gateway's (piGateway), so DeepSeek's calls were on no
page, Usage or Sessions.

- piFilesIn reads every session file under a lead's folder as the
  lead's (non-main, like omp's), and the defaultSessionDir ones through
  their headers' parentSession, up to 8 levels.
- piSubagentsRead: a tool result whose every sessionFile is one of those
  counts nothing, in piParse and piCall; one naming a file not read
  still counts as before.
- The scout's header id is in Session.Subs (pi is idInFile), so a
  subagent on magpie's entry is the lead's row to the gateway too.
- state.codexPath is parsePath, the file read, for piLeadID: a new field
  took state past its 416-byte class (TestStateFitsItsSizeClass).
- parseVersions and callParseVersions pi/raft/cindy raised.

The fixture is a real run: Pi 1.4.0 with pi-subagents 0.88.1 in a
sandbox PI_CODING_AGENT_DIR, a lead and one scout on a relay's
deepseek/deepseek-flash; system prompts dropped, paths rewritten.

Run (mica, at this head):
- go test ./internal/sessions: ok (119s)
- GOOS=linux and GOOS=windows go vet ./internal/sessions: ok; gofmt clean.
- Linux (wsl-run, magpie-desktop): TestPi*, TestOmp*, TestCodex*,
  TestStateFits*: ok
TestPiSubagentCalls: beside the lead and in defaultSessionDir, each with
the lead on the relay and on magpie's entry (the reporter's case).
Broken by hand: without the walk, 3 of 5 calls and 0 of 2 with the lead
on magpie (red); without the tool-result skip, 6 calls, the sum counted
again (red); the Subs check was red while it named the run id.
Not tried: the reporter's own files; a subagent nesting subagents; a
subagent run on magpie's entry against a live gateway.

With f0fb22c6b and 5bc816c1a below it, at this head (mica): go test
./internal/sessions ./internal/agent ./internal/claudecode ok,
./internal/gateway -run TestClaude ok, GOOS=linux and windows go vet of
the four ok, gofmt clean.
2026-11-13 19:07:34 +08:00
yetone 6bcdc6468d sessions: agy's own calls name the model its conversation database names (DvnT662 on X)
Usage → Requests showed every call read from a local agy-cli session with
no model (v0.1.3996). The calls reader read only agy's transcript,
brain/<id>/.system_generated/logs/transcript_full.jsonl, which carries
tokens but no model. agy keeps the model in conversations/<id>.db, the
Antigravity app's layout: gen_metadata field 1.19 is the served model,
and a step's metadata field 20.3 names its generator (0 when left out, as
antigravityRead reads it). A generator's "last_step_index" n in 1.20 names
step n+1 for steps the steps table doesn't hold.

- calls_agy.go: agyStepModels reads the db read-only and gives each
  transcript step its model (through agAppModel, so -n deployment
  suffixes go as on the app's rows). The call file's stat folds in the
  db and its -wal, so a model written after the step is read again.
- agy.go: the Sessions page counts each step's tokens under that model
  (still "agy" when the db names none), and its rev folds in the db too.
- parseVersions / callParseVersions "agy": 1, so cached parses are redone.

Fixture: gen 0 is parkavenue9639's real agy 1.5.6 gen_metadata row from
#3147 (matching its transcript step 1, 11519 in / 781 out); steps.tsv is
the real steps.metadata agy 1.5.7 wrote on this Mac. Generator 1 is made
in the test.

Run (mote): go test -count=1 ./internal/sessions ./internal/usage ok;
go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok; gofmt -l clean.

Broken by hand, each red: calls given no model; no last_step_index
fallback; Sessions not moving counted tokens to the model; call files
ignoring the db's stat; Sessions rev ignoring the db.

Not tried: a live successful agy turn (this Mac's only agy account is
refused, so its db has no answered step); agy in WSL; conversations with
a db and no transcript still count nothing (#5432); tok/s and stripping
-trial (#4805).

Refs #3147, #4805, #5432
2026-11-13 13:53:05 +08:00
yetone e630c003cd usage: Devin CLI's own calls are read from its sessions (aohan0905 on X)
Usage counted none of Devin CLI's requests. Devin's CLI (3000.11.234,
run for real in a sandbox HOME) keeps its sessions in
<data>/devin/cli: sessions.db (SQLite: sessions, and message_nodes with
each chat_message), or with DEVIN_SESSION_STORE=files a folder per
session (log.jsonl + meta.json), whose first run copies the database's
sessions in and leaves the database. Each assistant message names its
call: request_id, generation_model (swe-2-high, effort and all),
created_at and metrics (input/output/cache read/cache write tokens,
ttft_ms, total_time_ms), written as two nodes per reply.

- sessions: calls_devin.go lists both stores (a session in both once,
  from the store written last), reads each session whole, one call per
  request_id (Msg devin:<id>), with the cwd. Registered in callSources
  and wholeCallReaders; Found lists "devin" for the consent page.
- provider: DevinModelEffort splits a variant id into model and effort
  (claude-haiku-5-5-low -> claude-haiku-5-5, low), so the catalog prices
  it. swe-2 has no catalog price and shows as unpriced.
- agentenv clears DEVIN_SESSIONS_DIR in test sandboxes.

Fixtures are the real runs' files: 3 sessions in sessions.sql (schema
verbatim, triggers dropped, assistant and user rows only), one session
only in the folder store and one in both, project folder renamed.

Run (mica): go test ./internal/sessions ./internal/provider
./internal/agentenv ./internal/usage ./internal/usageapi ./internal/cli
./internal/gui ok; go vet darwin, linux -tags nogui, windows on the
touched packages ok; gofmt clean. win-run: the Devin tests ok. A built
binary's `magpie usage all` / `--csv all` in a sandbox HOME holding the
real Devin data: 5 calls under Devin, the two claude-haiku-5-5 calls
priced from the catalog ($0.000277, $0.000986), swe-2 unpriced.

Broken by hand: devinCallFiles out of callSources (TestDevinCalls and
TestDevinDBReadAgain red, 0 calls); a session in both stores listed
twice (TestDevinSessionListedOnce red, 9 calls); the per-request dedupe
off (red, a request counted twice); DevinModelEffort returning the id
whole (TestDevinCalls and TestDevinModelEffort red).

Not tried: Devin's folder on Windows (taken as %APPDATA%\devin\cli, as
its credentials.toml; not seen on a real Windows install); a long real
session or subagents; DEVIN_SESSIONS_DIR set (read from the CLI's
behaviour in the sandbox, not from a GUI-started magpie's environment).
2026-11-13 12:26:43 +08:00
yetone c14fa0ce93 Bring back 919780414 and 88d2962e0, which 698ed4adb undid
698ed4adb (a busy port names its holder) was committed from a tree made
before 919780414 and 88d2962e0 landed (09:38, eight minutes before it),
and took both out with no word in its body: quotatable.js, the Usage
Cards / Table switch and its test, and sessions' 16-byte head and
prefix hashes (digest.go) were gone from main from v0.1.3823. This puts
both back as they were, on top of 698ed4adb's own change, which is kept.

Run at this tree, on mote (cherry-pick of both onto origin/main
db0c1b039, no conflicts):
- gofmt -l internal/sessions: clean.
- go vet ./internal/sessions ./internal/gui; GOOS=windows and
  GOOS=linux -tags nogui go vet ./internal/sessions: ok.
- go test -count=1 ./internal/sessions: ok 83.6s.
- go test -run 'Budget|Lazy|I18n' ./internal/gui: ok (the core script
  budget holds with both changes).
- GUI, chromium and webkit: usage-quota-table, gateway-port-holder,
  i18n-keys, i18n-en-no-cjk, old-webkit: 44 of 46. The two reds are
  old-webkit's "compat.js is the first" (headerpresets.js, #6030) and
  "the styles hold up in Safari 15.0" (#5919), red the same on an
  origin/main db0c1b039 copy.
Not run: the full Go and GUI suites.
2026-11-12 09:57:52 +08:00
yetone 698ed4adb5 gateway: a busy port names the program holding it, and Tailscale's serve gets its fix (pluoki on X)
The Gateway page, `magpie serve` and the app log said only "port N is held by another program". pluoki's was `tailscale serve` on the same port number.

proc.PortHolder reads the holder (lsof on the Mac, /proc on Linux, Get-NetTCPConnection on Windows). Tailscale's daemon is root's and often unreadable, so `tailscale serve status --json` is the fallback for the port. gateway.NoteHeld / PortHeld.Sentence say who holds it, and for Tailscale give `tailscale serve --https=<other> http://127.0.0.1:<port>`. Shown in the `magpie serve` standby line and bind error, the app log, `gatewayHeld` in /api/state (Gateway page) and Start's "taken" answer, in en, zh, zh-TW, ja, de. A holder that can't be read says nothing; the old wording stands. Nothing is killed or touched.

Run: gofmt clean; go vet darwin, linux nogui, windows (mica); go test ./internal/proc ok; targeted holder/gateway tests on macOS (mica), Windows (win-run) and Linux (wsl-run); parser tests with real lsof output; GUI gateway-port-holder, gateway-takeover, gateway-older, gateway-skew, gateway-port, i18n-keys, i18n-en-no-cjk in chromium and webkit. Real run on WSL: a holder named tailscaled on the LAN address with magpie on 0.0.0.0 gives the Tailscale sentence at the bind error; a Python holder on loopback gives "held by python3.12 (pid N)".
Broken by hand: each fix reverted in turn, its test went red.
gateway-card.test.cjs is red on origin/main too (#6029). internal/gateway, gui and cli package runs were still going at push; the full suite follows the tag.
Not tried: a real `tailscale serve` (changes live config), a real Windows holder end to end, the bind-error path on macOS (a wildcard bind coexists with a specific one there).
2026-11-12 09:46:34 +08:00
yetone 88d2962e0c sessions: a file's head and prefix hashes are kept as 16 bytes, not hex (#2278)
Each kept file's state held its head hash as 64 hex characters and its
sampled prefix hash as "sample-v1:" and 64 more, two allocations of 64
and 80 bytes beside the state. They are only compared, so they are now
a digest: the first 16 bytes of the same SHA-256, inline in the state's
own 16 bytes where each string header was. The state's size class is
unchanged (416), and the 144 bytes a file are gone.

A cache written before reads as the same files: digest reads the old
hex (with or without "sample-v1:") as its first 32 characters, which
are what headDigest and prefixHash give now, so the first start after
the update reads nothing again. The call shards' gob keeps its string
fields, written and read through the digest, so a shard written before
restores the same too. File names still use hashHead's full hex.

Run, on a sandbox HOME holding the owner's real account history (18,346
session files), the same sessions.json before each run, web mode, at
120 s:
- w14 (main): live heap 88.8 MB, footprint 129 MB, 127 MB after GC,
  CPU 2.35 s
- w15 (this): live heap 86.1 MB, footprint 124 MB, 121 MB after GC,
  CPU 2.48 s; at 30 s 2.31 s of CPU against 2.15 s, so no file was read
  again from the old cache
Broken by hand: digest no longer stripping "sample-v1:" turns
TestDigestReadsTheHashesWrittenBefore and
TestPrefixHashUnchangedAndUnbuffered red.
At the pushed head (rebased on 848269fcf): gofmt clean, go vet for darwin,
windows and linux (nogui) ok, go test ./internal/sessions/ ./internal/usage/
ok on mica. The full suite runs after the push (both test boxes were
loaded).
2026-11-12 09:41:52 +08:00
yetone 4b1f3eca4a usage: a ZCode call magpie routed is not counted again as a local session's (nori_tsukiji on X)
With ZCode on the same computer as magpie, the Usage page's local session
calls came out equal to the calls magpie had routed: each was counted twice.

Cause: a ZCode request names its session without the sess_ prefix ZCode's
database gives it (zcodeBareID; GatewayKeys, Titles and the Sessions list
already knew). The Usage page pairs a gateway record with a session file's
call by session, tokens and end time (matchedBlocks), and the calls read
from ZCode's database kept sess_<id> / sess_subagent_agent_<id>, so they
never shared a session with the gateway's records and were never paired.
Leaving out calls whose providerID is "magpie" (ocGatewayProvider) only
helps when ZCode writes that id beside a reply; with any other id the call
was listed twice.

Fix: readZCodeCalls gives each call the bare session id; zcode's call parse
version is 3, so cached shards are read again. Claude Code, Codex, Pi,
OpenCode, Kimi, dsh, grok, minimax, agy and WorkBuddy name their sessions as
their requests do (raft.go's requestIDs has ZCode alone); not changed.

Run on mote: go test ./internal/usage ./internal/sessions (ok; the zcode
fork test's expected session ids are now the bare ones), gui and cli with
-run 'ZCode|Zcode|Usage|Session' (ok), go vet darwin/linux/windows (clean),
gofmt -l clean. TestZCodeCallsPairWithTheGatewaysRecords (a session, a
provider id of ZCode's own, a subagent) was red on the old code: 4 rows for
2 routed calls, the local ones Session sess_7c1f against the gateway's 7c1f.
Not tried: a real ZCode database (this computer has none, only the app's
tasks index) and the full suite.
2026-11-12 00:42:50 +08:00
yetone 2f660ca86b sessions, usage: Antigravity's gemini-4-argon-d is gemini-4-argon, not a second unpriced model
oioio's Antigravity database names gemini-4-argon's generator
"gemini-4-argon-d". agAppModel took only "-n" off a gemini-* id (Google's
gemini-3.8-flash-n, b2432754e), so the Usage panel showed gemini-4-argon
twice and the -d one had no price. usage.GeminiServing had the same
"-n"-only rule, so the gateway's log would call gemini-4-argon answered
as gemini-4-argon-d a swap.

Both now ask sessions.GeminiDeployment: a gemini-* id with one lowercase
letter after its last hyphen is that model's deployment. Google's own
ids never end in a lone letter (-lite, -nano, -pro, -001, -exp), and
other makers' ids (gpt-5-d, claude-sonnet-4-5-n) stay as written. The
rule is by shape, not by the catalog: a catalog lookup at parse time
would freeze a "-d" into the kept parses whenever models.json wasn't
there yet. antigravity's parseVersions and callParseVersions go to 1,
so parses and call shards kept with gemini-4-argon-d are read again on
update; nothing else is reread.

Run (mote, at this tree):
- go test -tags nogui ./internal/sessions ./internal/usage: ok.
- go vet, GOOS=windows go vet, GOOS=linux go vet -tags nogui on both
  packages; gofmt -l prints nothing.
- Broken by hand: GeminiDeployment put back to the old -n-only rule.
  TestAntigravityAppDeploymentName failed ("gemini-4-argon-d":
  "gemini-4-argon-d", want "gemini-4-argon", fields 19, 21, 22) and
  TestSwappedGeminiServingName failed ("gemini-4-argon answered as
  gemini-4-argon-d is the model asked for"); both pass with the change.
- Full suite runs after the push (go test -tags nogui -timeout 45m ./...).

Not tried: oioio's own database (only the model name was posted), and
a real gateway request that Google answers as gemini-4-argon-d.

Reported-by: oioio (Discord)
2026-11-07 00:22:13 +08:00
yetone 8c97edc802 sessions: a calls write goes to its file a frame at a time, its patch list made once
writeCalls held a whole write in one bytes.Buffer, grown by doublings,
before any of it went to the file, and the frame's patch list grew by
append from empty whenever a collection had emptied its pool, as it does
all through a first start. In a 120s cold start on mote over real
history copies (#2278 recipe), the list's growth was 148 MB and the
buffer's 150 MB of writeCalls' 556 MB.

Now each frame is encoded into one pooled buffer and written to the file
at once, so a write holds at most one frame (~1 MB, where a 52k-call
session held 8 MB), and the list is grown once to the first frame's size.
A write that fails after its first frame leaves frames ending in More,
which loadCalls already reads as a write cut off: the file is read again.

Measured, rc4 (303a31dd6's tree) against rc5 (this change), 120s cold on
mote: the list's line is gone from the profile, bytes.growSlice 150 ->
70 MB while rc5 did 1.39x the writes (gob's encoder buffers 240 -> 334
MB); writeCalls 556 -> 583 MB for that 1.39x, ~25% less a write. What is
left is each frame's gob encoder's own buffer, which a frame decoded on
its own needs.

TestCallsWriteAfterACollection writes 10240 calls after two collections:
4.9 MB, bar 6 MB. By hand: the list not grown at once 7.4 MB red, the
whole write held 6.8 MB red; the old code 9.3 MB. It reads the file back
call for call.

Run at the rebased head on mote: gofmt; go vet ./internal/sessions for
darwin, linux and windows; go test -count=1 ./internal/sessions ok.
Not run: the full suite (last at v0.1.3152's change, 85 packages ok).
2026-11-06 19:28:44 +08:00
yetone 81d6a3294b sessions: a first start's read of Claude Code history makes 39% less garbage (#2278)
A first start (or one after the session caches are gone) reads every
Claude Code transcript to count calls. On a real 21 GB history this
allocated 14.6 GB and ran 460 GCs. Three things made most of what was
thrown away right after:

- ccWithoutContent made a new copy of each reply line with its content
  set to null (82 MB), and gjson.GetBytes copied the content to find it
  (27 MB). ccDecode now builds the stripped line in a pooled buffer and
  finds the content through an unsafe.String view, with no copy.
- ccStr.UnmarshalJSON went through json.Unmarshal for each string, which
  made a decoder for each one (29 MB). A string with no escapes and valid
  UTF-8 is now taken as its bytes. Anything else still goes to
  json.Unmarshal, which writes U+FFFD for bad bytes.
- writeCalls made a new Patches list for each frame (1 GB). It now reuses
  one list from a pool and clears it before putting it back, so the pool
  keeps no reference to the call state.

Measured on mote with the real 21 GB history copied into a sandbox HOME,
with the session caches deleted before each run, over 120s:
  v0.1.3118: 14.6 GB allocated, 460 GCs, CPU 3:17, footprint peak 195 MB
  this:       8.96 GB allocated, 277 GCs, CPU 3:19, footprint peak 197 MB
The footprint peak is what is live (the caches), so it does not change.

Tests:
- TestCCDecodeAsUnmarshal holds ccDecode to json.Unmarshal of the whole
  line. Its cases are escaped content, non-UTF-8 bytes, content first,
  an error line, not JSON, and an empty line.
- TestCCDecodeAllocations allows at most 1300 bytes for a 41 KB reply
  line.
- TestCallsWriteKeepsNoPatchListPerFrame allows at most 6 MB for a
  6144-call write.
Both allocation tests turn GC off while they measure, because a GC
empties the pool; they passed 5 of 5. Broken by hand: with the line
pool removed, the decode test made 1984 bytes and went red. With the
Patches list made per frame again, the write test made 13056 KB and
went red.

Full suite on mote at 3f53fa1f3 plus this change: gofmt clean, go vet ok (darwin, linux nogui, windows), go test -timeout 45m ./...: 86 packages ok; internal/gui red only in TestMainWindowCorners/macOS_26_SDK, the known #3949 (macOS 27 corners), not touched here.
2026-11-06 14:58:40 +08:00
yetoneandyygutn 783537e810 sessions: the Antigravity app's own conversations count on Usage and Sessions (#2190)
xxooioo (Discord) asked for the Antigravity desktop app's calls made
without magpie's gateway on Usage and Sessions. The app keeps each
conversation as a SQLite database, ~/.gemini/antigravity/conversations/
<id>.db (WAL). Messages are encrypted, but steps.metadata is plain
protobuf: 1 the step's start, 9 the call's usage (2 input, 3 output,
4 cache write, 5 cache read, 11 response id), 20.3 the gen_metadata idx
of its generator, whose message names the model (field 19, else 21/22).

The reader opens the database read only, in one read transaction; a
response id seen twice is one call at its last step. Each conversation is
a read-only session under agent "antigravity", gated by Reads like every
other agent and added to Found. A call the app sent through magpie is
matched to the gateway's record by tokens and time the way agy's steps
are (agyLocal now covers "antigravity"), so it is counted once.
"gemini-3.8-flash-n", the model the rows name, is counted as
gemini-3.8-flash (b2432754e).

Fixture: the four steps.metadata rows yygutn posted on #2190, byte for
byte (testdata/antigravity/steps.tsv), under the schema he posted; the
decoded tokens and times match his figures. The gen_metadata rows wrap
the posted field-19 bytes in a field-1 message, since the rest of that
row was not posted.

Run on mote: go test -count=1 ./internal/sessions/ ./internal/usage/
./internal/agent/ ok; ./internal/gui/ ok but TestMainWindowCorners
(#3949, macOS 27, untouched); gofmt -l clean; GOOS=linux and
GOOS=windows go vet of sessions and usage clean (./... for linux stops in
Wails' cgo files, as without this change). skillsCounted says why the
app's skills aren't counted (step payloads are encrypted).
Broken by hand: agyLocal back to "agy" only fails
TestAntigravityAppCallThroughMagpieCountedOnce; the wholeCallReaders key
renamed fails TestAntigravityAppCalls (0 calls).
Not tried: a real app database (the app isn't installed on any test
machine); whether a call through the gateway records the same tokens;
conversation titles (not read; agyhub_summaries_proto.pb unknown).

Co-authored-by: yygutn <yygutn@gmail.com>
2026-11-06 10:07:06 +08:00
yetoneandSKYhuangjing 2741b749f9 sessions: a codex fork's rollout-<n> turn does not end the copied head (#5090)
ownTurn ended a Codex fork's copied head at the first turn id the parent's
file didn't hold (fb1f4856a). codex-rs names a turn that has no id of its
own "rollout-<n>" (the rollout canonicalizer's implicit turns; the
thread-history builder), and a copied head can carry one the parent's file
lacks. It was taken for the fork's first own turn, so every copied
checkpoint after it was booked as the fork's call: July and August usage
that was the parent's history over again. Reporter: SKYhuangjing, whose
fork branch codex-fork-head-marker (acb034645) this ports.

ownTurn now leaves a "rollout-" turn id alone. callParseVersions and
parseVersions raise codex to 3, so kept shards and call caches are read
again once (the same one-time re-read the codex 2 raise cost).

Changed from the patch: the code comment and the subsystem page
(docs/subsystems/gateway-sessions.md) say what codex-rs does, not what
the reporter's corpus showed; the test comment names #5090.

Checked, not changed: ZCode's fork path (zcDB.copied) matches copies by
the original message id and never reads a turn id; ownTurn has one
caller (codexUsageState.context).

Run (mote-run, at this tree on origin/main + this commit):
- TestCodexForkHeadMarkerDoesNotEndTheCopies red with ownTurn as on
  origin/main (4 calls on the fork, want 1), green with the fix.
- go test -count=1 ./internal/sessions ./internal/usage ok; gofmt -l clean.
- GOOS=windows and GOOS=linux go vet ./internal/sessions clean.
Not tried: the reporter's real database (we have no copy of their
corpus). Not confirmed: codex-rs main has no writer that puts a
turn_context with "rollout-<n>" into a forked file from
record_initial_history, as the issue says; the prefix is confirmed from
the two codex-rs writers above, but which one produced the reporter's
files is unknown. Not handled: a fork whose own first turn is itself a
"rollout-<n>" (a legacy rollout migrated with no ids) still doesn't end
the copies by turn id; checkpoints still match it as before.

Full suite: run after the push, result on #5090.

Co-authored-by: SKYhuangjing <13705011+SKYhuangjing@users.noreply.github.com>
2026-11-04 09:10:52 +08:00
yetone fb1f4856a8 sessions: a fork's own calls are counted; only its copies are the parent's (ZCode, Codex)
Sky (skyhuang1994) on Discord, on their real ZCode database after
v0.1.2847 (1d0fc2bb0): September's message table holds 57,787 rows,
13.552B tokens; 5,204 rows (1.537B) carry a forkOrigin and are copies,
and ZCode's cloud usage says 12.057B. The new version took 5.094B out,
3.6B of it real. The biggest was the "msc" session: forked at the end of
August, then 11,409 calls of its own in September (3.489B), none with a
forkOrigin, a custom-UUID provider. The Usage page had 0 of them.

Cause (ZCode): readZCodeCalls marked copies in a map keyed by m.ID. A
row's id is in the message table's id column, not in its data (OpenCode
writes data without id; checked on this machine's real opencode.db: 2 of 2
rows have no $.id), so every message decodes with ID "". One copy in a
session set copies[""], and every assistant message of that session was
left out: a fork that went on working lost all of its own calls. The test
fixtures had "id" inside data, so they never saw it. The Sessions page
(parseOpenCode) asks zcDB.copied per message and was right.
Fix: copies are marked by row index. Only a message whose forkOrigin
names a messageId still in the database is skipped.

Codex: a fork's checkpoint was a copy whenever its {total, last} was one
the parent's rollout holds, anywhere in the fork. A fork goes on working,
and its first own call can carry exactly the numbers of the parent's
next call after the fork (same history, same next prompt). The copies
are now the head of the fork only: the fork's first turn_id the parent
never had (turn_context or task_started) ends them (ownTurn,
CopiedTurns, read with the parent's checkpoints). A rollout with no turn
ids is matched as before; its running total keeps later calls apart.

callParseVersions codex 2, zcode 2 and parseVersions codex 2, so the
parses kept by v0.1.2847 are read again once. ZCode's Sessions parse
didn't change and stays at 1.

Tests (fixtures follow Sky's case: a parent of 08-30, a fork with
forkOrigin copies of its replies, ZCode's fork notice, then 40 replies of
its own in September with no forkOrigin, no id in data, provider a UUID):
- TestZCodeForkThatWentOnWorkingKeepsItsOwnCalls: red on origin/main
  7d022bdb6 ("the fork's calls: 0 {...}, want its 40 own"), as Sky saw.
- TestCodexForkThatWentOnWorkingKeepsItsOwnCalls: red on main and with
  ownTurn turned off by hand (1 call on the fork, want its 2 own).

docs/subsystems/gateway-sessions.md says this.

Run on mote (mote-run) at this change on origin/main 7d022bdb6; rebased
on 08d7bfaaa (gui, redact, gateway-key only), go build ./... and
internal/sessions run again: ok.
- gofmt -l internal: empty
- GOOS=linux go vet -tags nogui ./... ; GOOS=windows go vet ./... : ok
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage
  ./internal/tune ./internal/otlp ./internal/davsync ./internal/tui : ok
- go test -run 'Session|Usage|Calls|Ledger|Stats|ZCode|Codex|Fork'
  ./internal/gui ./internal/cli : ok

Broken by hand:
- the copies keyed by message id again (origin/main): the ZCode test red,
  0 calls on the fork.
- ownTurn's call in context() off: the Codex test red, 1 call on the fork.

Not tried:
- Sky's real ZCode database; there is none on this machine and no ZCode
  source to read its writer. That ZCode's data has no id, as OpenCode's,
  rests on the symptom (every row of the fork gone) and OpenCode's real
  rows here.
- a real forked Codex rollout that went on working; the turn ids of a
  real 0.117 fork were read from the fixtures' shape, not a real file.
- the whole gui and gateway suites, and a full go test ./...: other
  sessions' suites were running on mote.
2026-11-03 20:21:17 +08:00
yetone 1d0fc2bb08 sessions: a fork's copies of its parent's calls are counted once (Codex, ZCode)
Sky (skyhuang1994) on Discord: on ZCode, 10-31 showed ~0.70B GLM-5.3
tokens where ZCode's own model_usage had ~0.28B. A selection side chat
opened on 11-02 from a 10-31 session holds a copy of its 860 assistant
messages, with the 10-31 times and the same 421,041,276 tokens, and made
no calls. On Codex, a week of 2026-03 read 5,136,041,178 gpt-5.4 tokens,
where the machine had spent ~0.27B.

ZCode: ZCode 3.17's CLI copies a session's messages (gce, for a side
chat, a fork and a checkpoint restored) with a new id and session, the
original's time, model and tokens, and metadata.forkOrigin
{sessionId, messageId}. zcDB.copied says a message is a copy of one still
in the database, and readZCodeCalls and parseOpenCode (for ZCode) leave
it out. A copy of a copy names the copy it came from, so of each chain
one is counted. A copy whose original is gone is counted. ZCode's own
fork notices carry a forkOrigin with no messageId, and are not copies.

Codex: a fork (/fork, spawn_agent with the parent's context) writes every
line of the parent's rollout into its own first, token_count events too,
stamped at the fork's time (codex-rs 0.117 record_initial_history,
InitialHistory::Forked). Each copied checkpoint was booked as a call on
the fork's day. The fork's session_meta has forked_from_id. The parent's
rollout is found in the same Codex home: the UUIDv7 day of its id ±1
day, then every day, then archived_sessions. Its checkpoints, {total,
last}, are read once (8 parents kept), and a fork's checkpoint found among
them only advances the running total, on Usage (calls) and Sessions
(stats) both. A parent not found leaves the fork read as before.

callParseVersions and parseVersions raise codex and zcode to 1, so their
kept parses are read again once. The version tests (call_versions,
parse_versions, cache_decode) now hold the versions at none raised: they
test the mechanism, not the current numbers.

docs/subsystems/gateway-sessions.md says all of this. Filed #5072:
OpenCode's fork copies the same way and names no original, so it is
still counted twice.

Run at this head on mote (mote-run):
- gofmt -l internal: empty
- GOOS=linux go vet -tags nogui ./... ; GOOS=windows go vet ./... : ok
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage
  ./internal/tune ./internal/otlp ./internal/davsync ./internal/tui : ok
- go test -run 'Session|Usage|Calls|Ledger|Stats|ZCode|Codex'
  ./internal/gui ./internal/cli : ok

Broken by hand:
- zcDB.copied returning false: TestZCodeCopiesCountedOnce red. msg_c1 and
  msg_d1 were counted as calls, and the Sessions page's 10-31 read
  {1200 300 1800} for {400 100 600}.
- the copied() check in count() off: TestCodexForkCountsOnlyItsOwnCalls
  red. 4 calls on the fork, {87984 5950 268416} for {45744 3550 179584}.

Not tried:
- a real ZCode database or side chat. There is none on this machine.
  The copy shape was read from ZCode 3.17.2's zcode.cjs (gce).
- a real forked Codex rollout or one from 2026-03. ~/.codex/sessions here
  spans 2026-07 to 11 and has no forks. The fixtures follow codex-rs
  0.117's writer. Whether Sky's 5.1B week is all fork copies is not
  known; a cumulative count read as per-turn in an older format was not
  found in that source.
- newer rollouts' token_usage_record copies in a fork, and a parent in
  another Codex home (WSL, CODEX_HOME).
- the whole gui and gateway suites. Another session's suite was running
  on mote; gui and cli ran only the tests above.
2026-11-03 19:13:00 +08:00
yetone 78cd4e6dd4 sessions: a call through magpie in Cindy is counted once, as the gateway's (jealousy03888)
jealousy03888 on Discord: "cindy里用Zcode订阅 同一个请求两个记录是特性吗".
Their Routing list had one ZCode GLM-5.3 request twice: the gateway's row
(ZCode · api.z.ai, 135/37/84,736 tokens, ~$0.026) and five seconds later
a "local session" row on the provider "magpie-beedee1a" with the same
tokens and cost, so Usage and the Requests totals counted it twice too.

Cause: Cindy's import parser gives a custom provider the link's id plus
eight hex digits of a new UUID (`${id.slice(0,24)}-${randomUUID()
.slice(0,8)}`, read in Cindy 0.1.94's app.asar), so magpie's link (id
"magpie") becomes "magpie-<8 hex>", and Cindy's Pi writes that id on
every reply. The Pi reader left out only "magpie"/"dial", so Cindy's
calls through magpie were read as Cindy's own beside the gateway's.

Now piGateway(agent, provider) also takes "magpie-" + eight lowercase
hex digits as magpie's entry, in Cindy's files only (Pi's own and omp's
providers are named by the user; magpie writes "magpie" there). A
provider the user adds by hand in Cindy under the name Magpie gets the
slug "magpie" or "magpie-2", never this shape. callParseVersions raises
cindy to 1, so Cindy's call shards written before are read again once
on update and the duplicates already shown go away (usage's request and
heat caches key on CallCacheVersion, so they are rebuilt too); no other
agent's shards are re-read.

Every other agent's reader was checked for the same gap (an id the app
chooses rather than magpie): OpenCode and ZCode ("magpie", written by
magpie), dsh (magpie's three route names), MiniMax Code
(custom_provider:magpie), Kimi ("magpie/" model prefix), WorkBuddy and
CodeBuddy (models.json vendor magpie), Grok Build (its config.toml
tables), Pi, omp and Raft (models.json "magpie"), Claude Code, Codex
and Antigravity (paired with the gateway's rows by session, response id
or tokens and time). Cindy is the only one whose provider id is made by
the app; Lody and AionUi also import a link but their sessions aren't
read.

TestCindyGatewayCallsCountedOnce puts a Cindy Pi session shaped like
the report (provider magpie-beedee1a, zcode/GLM-5.3, 135/37/84,736,
durationMs 5292) and a reply on a user's own "magpie-relay" into
Cindy's session folder; the first must not be a call, the second must
be one. TestCallParseVersionRaiseReadsThatAgentAlone now restores the
real versions after it.

Run (on mote): gofmt -l internal/sessions (nothing); go vet;
GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; go build
./... all ok. go test -tags nogui -timeout 45m ./... at 40a287b21+this:
86 packages ok, internal/cli red on two filed reds outside this change:
TestEveryRouteHasACommandOrIsNamed (GET /api/context/reply, #5026,
red alone too) and TestLibraryMCPHub (#4140, passes alone). Rebased on
c3593dc49 (no sessions or usage change between) and run again at the
pushed head: internal/sessions ok, internal/usage ok.

Broken by hand: piGateway's Cindy branch replaced by `return false`:
TestCindyGatewayCallsCountedOnce FAIL ("a call through magpie's link in
Cindy counted as Cindy's own: ... Upstream:magpie-beedee1a ...").

Not tried: a real Cindy session through magpie (none on this machine;
the shape is from Cindy's source and the reporter's screenshot); the
Sessions overview's session count for Cindy, which counts sessions,
not calls, and was not changed.
2026-11-03 18:15:07 +08:00
yetone 6a6e4fefac sessions: WorkBuddy AI's own sessions are listed under its name (maxleebeta)
maxleebeta (Discord #general) is signed in to both WorkBuddy builds, the
China one and the international one, and the international one was
missing from an agent list. The provider side lists both: provider.All()
and CatalogFor have workbuddy/* and workbuddy-ai/* models under "WorkBuddy"
and "WorkBuddy AI". The sessions package, though, read only ~/.workbuddy.
WorkBuddy AI keeps the same files in ~/.workbuddy-ai (its product.json
dataFolderName, as internal/agent wires it), and nothing read them. So
WorkBuddy AI was missing from the Sessions page's agent picker, from
Usage > Sessions' agent strip, from the reading consent's folders and
from the usage ledger.

Changed:
- WorkBuddyAIDir and workbuddyAIFiles read ~/.workbuddy-ai/projects as
  agent workbuddy-ai with WorkBuddy's parser, in allFiles, Dirs,
  callSources (wholeCallReaders), Deletable and Found.
- buddyDir picks WorkBuddy AI's own models.json for the
  call-through-magpie skip.
- A ~/.workbuddy-ai that is a link to ~/.workbuddy is read once, as
  WorkBuddy's.
- skillsCounted names workbuddy-ai (WorkBuddy's parser counts no skills).
- docs/subsystems/gateway-sessions.md has a line for it.

Tests:
- TestWorkBuddyAI checks sessions, cwd, title, tokens, Deletable, Found,
  calls, the skip of magpie's gateway, and the link.
- TestWorkBuddyAIGatewayIsItsOwn: one model id that WorkBuddy's
  models.json gives to magpie and WorkBuddy AI's gives to the user's own
  provider.
- TestWorkBuddyAISessionsListedUnderTheirName checks /api/sessions,
  /api/sessions/manage and /api/sessions/stats: name "WorkBuddy AI",
  icon workbuddy-color, deletable.

Broken by hand (each went red): allFiles, parserFor, Deletable, Found,
the call sources, the wholeCallReaders entry, buddyDir.

Run on mote at this head (base origin/main c86fa2a34):
- gofmt -l and go vet for darwin, GOOS=linux and GOOS=windows -tags nogui
  (internal/sessions, internal/gui): clean.
- go test -tags nogui -timeout 45m over sessions and every package that
  imports it: ok for sessions (after the skillsCounted line), agent, cli,
  davsync, gui, otlp, tui, tune and usage.
- internal/gateway failed only TestCodexPoolSaysTheClientsVersion, which
  is #4807 (red in a full package run on mote, another test's Codex
  identity reaches it). Nothing here touches it.

Not tried:
- The reporter's screenshots, which we couldn't download, so their list
  may be another one.
- A real WorkBuddy AI install.
- The Agents page's detection of a newer, renamed WorkBuddy AI bundle
  (5.9.3).
- Windows.
- WORKBUDDY_CONFIG_DIR set: both apps then use that folder, and its
  sessions are listed as WorkBuddy's.
- No GUI JS changed (the page reads the agents from the API), so no
  Playwright files were run.
2026-11-03 08:54:40 +08:00
yetoneandggbdpq d76c4b23a4 sessions: Grok Build's own calls reach Usage, its turns through magpie left to the gateway (#4423)
liubing0806: with Local session selected, Usage lists Kimi's, Claude's,
Codex's and DeepSeek Harness's models and no Grok Build one, while Usage
→ Sessions shows the same sessions' grok-4.7-build tokens. Grok Build
had no call reader.

From ggbdpq's patch (via gua2100): calls_grok.go reads the updates.jsonl
the Sessions page reads, as parseGrok counts it. Each turn_completed is
a call per model in its modelUsage (input without what the cache held),
at the line's time; an empty modelUsage falls back to the session's
model. A subagent's folder is its own session; a fork counts lines from
its created_at on. It is a line source (lineCallReaders): a grown file is
read on from where the last read stopped, its carry kept in the disk
shard as Pi's is.

Added here: the patch left a turn asked through magpie's gateway to
gatewayMatches, and said such a turn may land in both ledgers. It does:
a turn_completed sums every request of the turn per model (modelCalls 7
and 17 in liubing0806's report) under the model the reply named
(moonshotai/Kimi-K3 for magpie's group/auto-kimi-k3), so no gateway row
matches it one to one. The model a turn was asked on is in its prompt's
user_message_chunk (_meta.modelId), and a turn asked on one of the
[model."magpie/…"] tables magpie writes in Grok Build's config.toml (by
table name, its model, or the magpie/ prefix) is the gateway's and left
out here. With no prompt line read, the session's model decides. The
carry keeps the asked model (Asked) across reads.

Run at this tree on mote: go test ./internal/sessions ./internal/usage
./internal/otlp ./internal/tune ./internal/davsync -count=1: ok;
go test ./internal/sessions -run Grok -race: ok; gofmt clean; go vet
GOOS=linux and GOOS=windows ./internal/sessions: ok.
Broken by hand: grokCallLine returning at once: TestGrokCalls,
TestGrokCallsForkKeepsItsOwnTurns, TestGrokCallsLeaveTheGatewaysTurnsOut
red; the gateway check off: TestGrokCallsLeaveTheGatewaysTurnsOut red (e
counted 26124 in).
Not tried: a live Grok Build session read by the GUI's Usage page; the
fixture lines are a real session's of each kind with the prompt cut.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-03 05:08:39 +08:00
yetone 2140f5b935 sessions: a plain Codex rollout read from its start has its calls read on the summary's pass (#4369)
A start parses every changed session file for Sessions (refresh ->
parseWith), then reads every changed file's calls for Requests
(ReadCallSource -> readCalls). callsAlong already let a packed rollout
and an unread Claude session be read once for both; a plain .jsonl
rollout was read twice. On copies of the owner's real ~/.codex and
~/.claude (1.7 GB), a cold start scanned 931 times, 3.49 GB, every large
rollout x2.

callsAlong now takes a plain rollout too, when both reads start at its
first line: the summary it goes on from has no Codex window (nothing
kept, or kept on disk, which holds none), and parseWith lets the ride go
when either read goes on from an offset (calls.st.Off as well as s.Off),
so a read on from where it was is two incremental reads, as before. A
summary that still has its window is passed in so such a file's calls
shard isn't loaded only to be let go.

keepCalls names the root when none is named yet. A ride keeps a
rollout's calls (Codex window and all) during the Sessions parse, before
any Requests read has called pruneCalls; pruneCalls took the empty root
for a moved one and dropped everything kept. The shard on disk has no
window, so the next line read the rollout whole again (in the same run,
seconds after the start). TestHistoricalClaudeFilesDoNotDisplaceActive
Windows went red on exactly that ("rebuilt active call shard" for its
Codex rollout) until this.

TestWarmReadsOnlyInItsSlots' calls phase found nothing left to read,
since the index phase now reads every file's calls along; it appends a
line to each source first, so the calls have reading of their own.

Tests' forget (in the new test, claude_ride_test.go and
codex_zst_warm_test.go) calls Reset before removing the cache file:
Reset writes a save still pending, which put back the file just removed,
and the next List then went on from disk states (no window), red 1 in
~40 under -race. TestHistoricalClaudeFilesDoNotDisplaceActiveWindows
waits for the save (saved()) before writing its marker onto a cached
state the save's goroutine was encoding (a DATA RACE under -race).

Run on mote (macOS 27.2):
- TestPlainRolloutReadOnceForSessionsAndCalls (new): 3 plain rollouts.
  Nothing kept: each scanned once, from 0. Read, kept on disk, the long
  one grown and Reset: that one scanned once, from 0. An append in the
  same run: no scan from 0 (with keepCalls' root line removed by hand:
  "an append: the long rollout read again from its first line:
  [213219 0]", and the Historical test red as above). Calls, List and StatsAt reflect.DeepEqual to
  a calls-first read without the ride in each case. With plain rollouts
  kept out of callsAlong by hand: "first read: ... scanned from [0 0],
  want once from 0" for all 3. Restored: ok. -race -count=80 with
  the Packed, ClaudeSessionReadOnce, CodexSessionReadOn, Historical and
  WarmReads tests: ok (108.8s)
- Real data (copies of 1.7 GB of the owner's sessions, probe run
  sessions.List(200), usage QueryPage Today and Week; probe not
  committed): cold 931 scans / 3.49 GB -> 718 / 2.10 GB, no rollout read
  twice; no change 0 / 0; the first line appended to the newest rollout
  after the cold read: read whole by both readers -> read whole once
  (1 scan, 10.8 MB; the before run's newest was a 21.5 MB one, read
  twice). It is read whole at all because it was last changed on 10-31,
  past any window's idle time: a session left that long is read whole
  once on its next line, now in one pass. Later lines: 2 scans, 0 MB.
- go test -timeout 45m ./internal/sessions ./internal/usage
  ./internal/gateway ./internal/gui: ok for sessions (11.3s, -race 56.2s, at this tree), usage (30.2s), gateway (575.6s); internal/gui: ok but TestMainWindowCorners/macOS_26_SDK, red on macOS 27 as #3949 records (same message), untouched here
- GOOS=windows and GOOS=linux go vet ./internal/sessions: ok. gofmt -l:
  clean.

Not tried: a packed rollout's path is unchanged (it rode before).
2026-11-02 06:11:06 +08:00
yetone 7da5b34aa4 sessions: Cindy's Pi sessions are read from its pi-agent-home (ldl123292 on X)
Cindy starts Pi with --session-dir <userData>/pi-agent-home/sessions
(resolvePiAgentHome in Cindy's app.asar), so its Pi sessions never
reached ~/.pi/agent and magpie showed none of them. They are read now from
the Cindy and CindyGlobal builds' folders and listed as Cindy's: list,
transcript, calls on Usage, Dirs, delete, and the gateway's own record of
a Cindy session merged with the file's.

Run (mote): go test ./internal/sessions ./internal/agent ./internal/usage
ok. go test ./internal/gui: two reds, both the same on origin/main
699ddf152: TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
TestMainWindowCorners (#3949). Linux (wsl-run): go test -run
'Cindy|Raft|TestPi' ./internal/sessions ok. gofmt clean.
Broken by hand: without cindyFiles() in the sessions list both Cindy tests
fail (0 Cindy sessions, want 4).
Not tried: a real Pi session run in Cindy (none on this Mac; the fixtures
are Pi 1.1.0's own files put where Cindy's Pi writes them), Windows, the
full suite. Cindy's Codex in <userData>/codex-home is not read yet: #4651.
2026-11-01 09:12:11 +08:00
yetone e4c7841779 sessions: a Claude session read from its start has its calls read on the parse's own pass (#2278)
A first start parsed every Claude session for the Sessions page
(parseWith, claudeLine) and then scanned each again for Requests' calls
(readCalls, claudeCallLine): on the 13 GB fixture HOME that second scan
was ~20 s of the start's CPU (scanThin under readCalls in the profile).

callsAlong, which already let a packed Codex rollout's calls ride along
its parse, now does the same for claude and claude-desktop files whose
calls are read from the start: nothing kept, or kept without their
revision window (prepareCalls would start over anyway). Each line is
shown to both heads and handed to claudeLine and claudeCallLine as each
asked, both thinned by thinClaude as on their own scans. finish keeps
what readCalls keeps for Claude: writeCalls, then withoutRevisions for a
file not being worked on when the kept calls had no window, then
writeCallRevisions. Calls kept with their window are read on from where
they were by readCalls, as before, and a summary read on from its own
offset drops the ride (parseWith) so neither reader misses a line.

The ride keeps its calls on disk only (the shard and the revision
window), so a Sessions read still loads no calls into memory
(TestCallsDoNotInflateSessionIndex); readCalls' fast path takes the
window back from disk for a shard it loads (withCallRevisions), as
prepareCalls did for a changed one. Only Claude files with no shard and
nothing kept ride: calls read before are read on or again by readCalls
exactly as they were.

Run on mote (M5 Pro) at the pushed tree:
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage: ok.
  ./internal/gui: ok but TestCoveredWindowStaysUp, killed at its 30s
  deadline alone too (an AppKit window on mote, #4125/#2645).
- go vet sessions; GOOS=linux and windows go vet sessions, usage: ok.
- New TestClaudeSessionReadOnceForSessionsAndCalls: each Claude file
  scanned once on sessions-then-calls, calls and sessions equal to a read
  of each on its own, and a grown file read on, not from its start.
- Broken by hand: the ride off for Claude turns the new test red
  (scanned 2 times); dropping the fast path's withCallRevisions turns
  TestEvictedClaudeRevisionsReleasedAndRebuilt,
  TestClaudeLargeWindowSurvivesIdleAndSmallFiles,
  TestClaudeWindowReservationsAndRemoval and
  TestLargeClaudeFileKeepsAppendContinuation red.
- Cold start on the fixture HOME (13 GB of Claude projects, 52 GB of
  Codex), 75 s each, alternating, load 12-19: previous head 3:27.98 and
  3:18.01 of CPU, this one 3:03.74 and 3:06.88. Footprint peak 328/334
  MB before, 339/333 MB after (unchanged). The heatmap, requests,
  sessions overview (0, 7, 30 days) and stats answers are byte-equal in
  both rounds.

Not tried: Claude Desktop's Code tab files on a real Desktop install
(they take the same path as claude, agent claude-desktop).
2026-10-31 16:54:37 +08:00
yetone 30f29564eb sessions: a change to one agent's calls reads that agent's files again, not every shard (#2278)
callCacheVersion named every shard, so raising it for a fix to one
agent's calls threw away every agent's calls and re-read the whole
history on the next start: on a real history of ~4,700 transcripts
that is minutes of CPU and the ~310MB peak, for a change to Claude
alone.

Each agent now has its own number in callParseVersions. A shard frame
records the number its agent had when it was written (callDiskState
.Parser), and loadCalls drops a frame whose number is not the current
one, so only that agent's files are read again. CallCacheVersion()
adds the raised numbers, so the usage caches built on calls
(requestDiskBinary, heat_disk) still start again when any agent's
calls change. callCacheVersion stays for a change to every agent or to
the shards' form.

Existing shards are kept: the map is empty, gob leaves a zero Parser
out, and CallCacheVersion() is still "calls-v15".

Run on mote (zone worktree at this head):
- go vet ./internal/sessions ./internal/usage for darwin, linux and
  windows: ok. go build ./...: ok.
- go test ./internal/sessions ./internal/usage: ok.
- go test -race -count=3 -run 'TestCallParseVersionRaise|Calls|Shard|Frame'
  ./internal/sessions: ok.
- TestCallParseVersionRaiseReadsThatAgentAlone: a Claude transcript and
  a Codex rollout; raising claude scans the Claude file alone, with the
  same calls, and the next start scans nothing.
- Broken by hand (the Parser check in loadCalls removed): red at
  call_versions_test.go:67, "scanned map[], want Claude's file alone".

Not changed: internal/gui's TestCoveredWindowStaysUp is killed at 30s
on mote, as in #4125.
2026-10-31 12:34:40 +08:00
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