Commit Graph
3969 Commits
Author SHA1 Message Date
yetone 2a27fb8da8 gateway: a request's body is looked at for web search without a copy, and not parsed for a provider that searches by itself
attempt() asked searchAsked first, on every relayed request, and only
then whether the provider searches by itself. searchAsked looked for
three words with strings.Contains(string(body), …), each conversion a
copy of the whole body (a 211KB body: ~640KB and ms a request), and a
body offering web_search was then parsed whole: Codex offers it on
every turn, so each relayed Codex turn was parsed only to be told
"Codex searches by itself". searchedForIt now asks what is known of the
provider and model first, and searchAsked looks with bytes.Contains.
The same copy in the siblings that look at an error body
(fallback.passing, patience.busy, routing.failure's insufficient_quota)
goes too. lan.go's and the lower-cased look-ups in gateway.go need the
string they make and are left as they are.

Test: TestSearchAskedLooksCheaply. Broken by hand (string(body) and the
old order put back): red, "a 211KB body with no search in it: 3
allocations, want 0" and "a provider that searches by itself: 29
allocations, the body parsed".

BenchmarkSearchedForIt (211KB Responses body; load average ~450):
  codex-asks   old 2.55-5.02 ms/op  665KB/op  29-30 allocs/op
               new 0.1-1.9 us/op    0B/op     0 allocs/op
  other-plain  old 1.6-4.8 ms/op    663KB/op  3 allocs/op
               new 0.26-1.15 ms/op  0B/op     0 allocs/op

Run: go test ./internal/gateway -run
'TestSearchAskedLooksCheaply|TestWebSearchAskedOfEachAPI|Search|Busy|
Passing|Failure|Credit|Quota' -count 1: ok (140s).
2026-10-19 15:19:31 +08:00
yetone a1118187b5 gateway: who answered a conversation is written to affinity.json behind the answer, once in a while, not on every answer
answered() (and unanswered()) called saveSticks on every request
answered: up to 512 conversations sorted, marshalled, written to a temp
file and renamed, one answer after another under sticksSaving. Now the
stick is in memory at once (stickOf reads the map first) and the file
follows within sticksFlushAfter (2s): what is answered meanwhile goes in
one write. The gateway's drain (ListenAndServe) and magpie ending on a
signal (cli/signals.go, beside FlushServed) write what is waiting, so a
restart or the magpie handed over to reads every answer. A crash loses
the last 2s, as served.json does since 4f9e8331a. In a test binary the
wait is 0 and the file is written at once, as it was (no timer outlives
a test; 8215e8275 did the same for served.json). A write waiting for
another HOME's file (a test's) is dropped, not written into this one.

Test: TestSticksWrittenBehind (2s set by the test): 200 answers write
no file, the last is known in memory, flushSticks writes all 200, and a
short wait writes by itself. Broken by hand (noteSticks calling
saveSticks always): red, "affinity.json written on a request answered".

BenchmarkAnswered (512 sticks kept, 200x, 2 runs; load average ~450):
  old (saveSticks inline)  21.3 / 25.0 ms/op  506KB/op  2140 allocs/op
  new                      2.5 / 5.6 us/op    392-434B/op  8 allocs/op

Run: go test ./internal/gateway -run '^TestSticksWrittenBehind$' -count 1:
ok. go test ./internal/gateway -run 'TestSticksWrittenBehind|Affinity|
Sealed|Stick|Strict' -count 1: ok (57.8s).
2026-10-19 15:19:31 +08:00
yetone ed3a46d02b provider: what a request built of the catalog stays for the next request within a second, not built again for each
Hold dropped everything held when the last request let go, so one
request after another built the catalog again from every provider's
files and accounts (All, entries, the groups' entries, the settings):
a fifth to a third of a request's CPU with 30 providers. What is built
now stays until heldFor (1s) is past, as it already did for requests
that overlapped. It is built again at once when anything it was built
from may have moved:
- Changed() and a plugin change (dropHeld), as before;
- a write that only tells filememo (settings.Save, writePrivate, an
  agent's account file): held values carry filememo.Gen(), new here, and
  are dropped when it moved;
- providers.json or settings.json written by another process (the CLI's
  "magpie group add"): the first Hold of a request stats both and drops
  what is held when either changed, so the next request sees it, not a
  second later;
- the groups served or gated (GateGroups, ServeGroups): holdGate drops
  what is held on both changes (TestGroupsOnAndOff was red without it);
- another environment (a test's HOME), by a hash of os.Environ().
Other files another process writes (an agent's own sign-in file) are
seen within heldFor, as filememo already takes a file found unchanged.

Tests:
- TestHoldKeptForTheNextRequest: five requests one after another build
  once. Broken by hand (held.built = nil on the last release put back):
  red, "five requests one after another: built 5 times, want 1".
- TestHoldKeptUntilAWrite: each of filememo.Forget, providers.json and
  settings.json written behind magpie's back, and GateGroups, builds
  again once. Broken by hand, one at a time: the Gen check off, red
  "filememo told: built 0 times, want 1"; the stat off, red
  "providers.json written by another process: built 0 times, want 1";
  holdGate's dropHeld off, red "the groups gated: built 0 times, want 1".
- TestRequestBuildsProvidersOnce now wants 1, 0, then 1 after
  Changed() (a request later than 0.9s after the first may rightly
  build again on a loaded machine; the test allows it).

BenchmarkGroupOverhead (internal/gateway, 200KB Anthropic body,
stream=false, 100x, two rounds alternating; load average ~450, so the
cpu-ms/op it reports is the measure, not wall ns/op). base is 8215e8275:

  12x20 p0/m1  base  25.66 / 24.36 cpu-ms/op  16.8MB  41723-41827 allocs
               this  22.13 / 20.67 cpu-ms/op  13.4MB  33771-33969 allocs
  12x20 g4     base  30.59 / 30.68 cpu-ms/op  22.5MB  53213-53409 allocs
               this  25.91 / 25.60 cpu-ms/op  19.0MB  45213-45613 allocs
  30x60 p0/m1  base  54.95 / 53.26 cpu-ms/op  42.5MB  89466-90023 allocs
               this  30.80 / 29.27 cpu-ms/op  23.0MB  45853-46928 allocs
  30x60 g4     base  66.67 / 73.07 cpu-ms/op  68-70MB  112283-116845 allocs
               this  45.59 / 48.38 cpu-ms/op  49-52MB  68540-74905 allocs

Run: go test ./internal/provider -run 'Hold|Group|Changed|Served'
-count 1: ok (91s). go test ./internal/gateway -run
'^(TestGroupsOnAndOff|TestRequestBuildsProvidersOnce)$' -count 1: ok.
The full suite at the head of this series is in its last commit.
2026-10-19 15:19:31 +08:00
yetone ae019defed provider: in a test binary served.json is written as an answer is noted, so no write outlives its test
4f9e8331a wrote served.json 2s behind the answer. In a test binary that
timer outlived the test that answered, and wrote into its temp HOME as
testing removed it: BenchmarkGroupOverhead's first case failed 1 run in
6 with "TempDir RemoveAll cleanup: unlinkat …: directory not empty", and
TestOTelSessionDedupOnlyUnkeyedLoopback failed the same way in a package
run. servedFlushAfter is now 0 in a test binary (testing.Testing(), as
partners.go already does), and NoteServed writes at once, after it lets
go of servedAt, as it did before 4f9e8331a. TestNoteServedWritesBehind
sets the 2s itself.

Test: TestNoteServedInATestWritesAtOnce. Broken by hand (writeBehind
returning d in a test binary too): red, "not written as the answer was
noted: … served.json: no such file or directory".

Run: go test ./internal/provider -run 'TestNoteServed|LastServed'
-count 1: ok. BenchmarkGroupOverhead's 12x20 p0/m1 case, 6 runs of 100
requests before: 1 failed on the cleanup; see the next commits' records
for the runs after.
2026-10-19 15:19:31 +08:00
yetone 8fd74d15bf provider: retired.json is looked at on disk once a second, not on every request answered
Every answered request asks Unretire (the gateway's servedCandidate), and
each catalog built asks retiredNow; each was an os.Stat of retired.json
under retired's lock. Only retired.go writes the file (writeRetired, for
Retire and Unretire), and it keeps retired.at and the file's time current
itself, so this process's own retirements are told at once. The file is
now looked at again only after retiredLook (1s): another magpie's write
is seen within it. A config path of its own (another HOME) is read at
once, as before.

Numbers (Apple M4 Pro, loaded by other sessions):
  BenchmarkUnretire  before 98.8 us/op  640 B/op  5 allocs/op
                     after  0.46 us/op  320 B/op  3 allocs/op

Test: TestRetiredLooksOnceInAWhile: 200 Unretire+Retired calls look at
the disk at most twice; Retire and Unretire are told at once; a write
another magpie makes is seen once retiredLook passes; a new config path
is read at once. Broken by hand (the throttle disabled): red, "400 looks
at retired.json for 200 requests".

Run: go test ./internal/provider -run TestRetiredLooksOnceInAWhile;
./internal/gateway -run 'Retired|Zen': ok. The full suite run is in the
last commit of this series.
2026-10-19 15:19:31 +08:00
yetone e1ebd173e8 filememo: a file not there is, while a request holds what was read, not looked for again
A provider with no live model list fetched has no live-models file, and
each request asked after it for each of its models (Provider.Exposed ->
ListedAPIs -> catalog.LiveByID -> readLive), each time an os.Stat that
failed: in a CPU profile of a 30-provider, 60-model catalog, os.Stat was
32% of a request, nearly all of it this. A file found unchanged was
already taken as unchanged for heldFor (1s) within a hold; a file found
missing now is too, in the same generation of Forget. Forget (a write
magpie makes), Look(path) (another's write), the hold's end, a second
gone by, or a stat finding the file there drops it. Unheld, every read
still looks.

Numbers, BenchmarkGroupOverhead, 200KB body, stream=false, 100x each,
binaries alternated twice (Apple M4 Pro, loaded by other sessions):
                       before (cpu-ms/op, allocs)  after
  30x60  p0/m1         34.69 / 35.14   95126        32.87 / 31.84  89266
  30x60  group/g4      44.33 / 43.88  115303        40.77 / 40.77 109071
  12x20  p0/m1         15.75 / 16.30   42535        16.22 / 15.09  41645
  12x20  group/g4      18.15 / 18.50   54138        18.16 / 17.76  53118
(about 7-8% of a request's CPU on the larger catalog; within noise on
the small one, which has fewer missing files.)

Test: TestHoldMissing: 100 held reads of a missing file make one stat; a
file written meanwhile isn't seen until Forget, and is seen after Forget,
after Look and after the release; unheld, 3 reads make 3 stats. Broken by
hand (the missing check disabled): red, "100 looks at a file not there,
held".

Run: go test ./internal/filememo ./internal/catalog: ok. The full suite
run is in the last commit of this series.
2026-10-19 15:19:31 +08:00
yetone a20d86900d provider: what answered a request is written to served.json behind it, once in a while, not on every answer
NoteServed ran on every answered request (servedCandidate): it read
served.json, merged, and wrote it through steady.WriteFile (a synced temp
file renamed over it), all under servedAt's lock, so concurrent answers
queued behind each other's fsync.

Now NoteServed only notes in memory and arms one write for
servedFlushAfter (2s) later; everything noted meanwhile goes in that one
write, merged with what the file holds (another gateway's) and pruned past
servedKeep as before. The file's format is unchanged. This process's
LastServed has a note at once (it merges memory over the file, as it
did); the CLI, a process of its own, sees it within 2s. FlushServed writes
what is pending: the gateway calls it as Serve ends, and the CLI's signal
handler before it dies of the signal. A crash loses at most the last 2s
of notes. A note made under one config path (a test's HOME) is never
written into another's: a path change drops the pending write.

Numbers (Apple M4 Pro, machine loaded by other sessions):
  BenchmarkNoteServed  before 5.10-5.33 ms/op  7.8 KB/op  82 allocs/op
                       after  0.64 us/op       352 B/op    5 allocs/op

Test: TestNoteServedWritesBehind notes 200 answers and checks the file is
untouched, LastServed has the latest at once, FlushServed writes it once
(a second flush writes nothing), merged with another gateway's entry, and
that the timer writes it by itself. Broken by hand (origin/main's
served.go with stubs for the new names): red, "written on a request
answered", and the 200 notes took 1.04s.

Run: go test ./internal/provider -run 'TestNoteServedWritesBehind|TestQuotasLastServed|TestCardsLastServed';
./internal/gateway -run TestQuotasLastServedAt; ./internal/cli -run
'TestQuotaJSONLastServedAt|Signal'; ./internal/gui -run
TestServedMovedWakesTheMenuBar: ok. The full suite run is in the last
commit of this series.
2026-10-19 15:19:31 +08:00
yetone 865b618086 gui: a gateway session is listed without its days, which only the stats read (#2776)
gatewayExternal copied every gateway session's days into the
ExternalSession it hands the Sessions list, each agent's manage page
and a session's detail. MergeExternal, which all three go through,
never reads them; only MergeExternalStats does. The Sessions list asks
for every session, so each poll of an open page copied every gateway
session's days. After the Vias fix (the commit before this one), that copy was the
largest allocation an idle open page makes: 5.11 GB of 9.14 GB in 6
minutes on the 720k-call sandbox.

gatewayExternal now leaves the days out, and the stats add them
through gatewayDays. Each model list is made at its size.

TestGatewayListCopiesNoDays lists a session with 365 days: no days in
the listed copy, and gatewayDays has all of them. With the days copy
put back in gatewayExternal by hand: red, "a listed session copied 365
days". TestGatewaySessionHistoryAndCalendar still sees each day's
output in the stats.

720k-call sandbox, idle with an open page's polls every 15 s, this and
the build before it side by side for 10 minutes, load ~190-210, 12
poll rounds each. Allocated from minute 2 to minute 8: gatewayListed
5,440 MB before and 1,000 MB after, the Sessions list handler 5,820 MB
and 2,970 MB, the manage page 2,220 MB and 1,850 MB. The live heap at
the snapshots ran 393-857 MB before and 389-889 MB after, and RSS
406-1176 MB and 357-934 MB, with no trend in either over the 10
minutes.

Run: go test -p 4 -count=1 ./internal/gui/ ./internal/sessions/: ok.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:19 +08:00
yetone 2fcd4b33c4 usage: one Vias index answers every since, instead of a rebuild from the whole log whenever the since changes (#2776)
Vias kept the lists for one since. The Sessions list asks from its
oldest listed session's start, each agent's manage page from that
agent's oldest, and a session's detail from that session's start, so
an open page's polls almost never asked the kept since, and each ask
read and grouped the whole log again. Idle with an open Sessions page
on the 720k-call sandbox, buildVias allocated 9.1 GB in 8 minutes,
78% of everything allocated, which is most of why the idle process
churned its heap and grew.

The cache now keeps one index from the whole log and each session's
first call. A session whose calls all came at or after the since is
answered from it. A session with calls before its since is answered
from one kept window for that since, built only when such a session
is read. Len counts the sessions with a call since the index's time.
Both are kept per log version and agent list, as before.

TestViasAnswerEverySinceFromOneIndex writes 20,001 sessions and asks
from three sinces in turn, as the three pages do: 2,677 bytes an ask.
On the old cache: red, 11,580,100 bytes an ask. It also checks that a
session with a call on each side of a since counts only the one after
it, and what Len says for a window and for every session.
TestGatewaySessionsCachePricesWindowsAndRewrite's window check and
TestUsageViasSkipsOldHistory stay green.

720k-call sandbox, idle with an open page's polls every 15 s (the
Sessions list, stats, Claude's manage page, Requests, state), before
and after side by side for 12 minutes, load ~170-250. Allocated from
minute 4 to minute 12: buildVias 9,100 MB before, 0 after (built once,
before minute 4). The faster answers let the poll loop run about twice
as often, so the totals (11.6 GB and 10.5 GB) aren't per poll. The
live heap ran 352-641 MB before and 514-724 MB after, and RSS 730-962
and 555-1217 MB; both swing with where a poll is when the snapshot is
taken and the machine's load, and neither shows a trend in 12 minutes.

Run: go test -p 4 -count=1 ./internal/usage/ -run
'Vias|KeptStrings|GatewaySessionsCachePrices|Incremental|Review': ok.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:19 +08:00
yetone 34b1757843 usage: the kept gateway projection's days and models are lists of their own size (#2776)
buildGatewaySessions grew each session's Daily and Models an item at a
time from empty. The projection is kept for as long as the log is
unchanged, and so was the spare room append had left each list (five
days took eight). slices.Clip in gatewayProjection hides that room from
callers but doesn't free it. On the 720k-call sandbox, that append was
the largest single allocation of the build (319 MB of 1.14 GB), and the
lists are most of what the start keeps for the Sessions page.

Each list is now made at the size its map already counts.

TestGatewayProjectionKeepsNoSpareRoom builds 3000 sessions x 5 days
with one to five models each, and measures the heap the projection
keeps. The bound is its days and models x1.3, plus the sessions' list
and index. Fixed: 9,233,056 bytes, against a bound of 10,478,400. With
the two makes taken out by hand: red, 12,754,488 bytes.

720k-call sandbox, cold start, the four first asks together, the live
heap 20 s after them, back to back: 541 MB before, 479 MB after. The
machine's load was ~250-290 and the answers took ~140 s in both runs,
so their peak RSS (1395 and 1891 MB) measured the load, not this.

Run: go test -p 4 -count=1 ./internal/usage/: ok.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 43bd998b15 usage: GatewaySessions hands out the kept projection's lists instead of cloning every session's days for each ask (#2776)
GatewaySessions cloned every session's Models and Daily for each ask,
from the projection kept for exactly these asks. The start's first
asks (the Sessions list, each agent's manage page, the stats) each
cloned them all. In a heap snapshot at the 720k-call sandbox's peak,
cloneGatewaySession held ~447 MB live of the 1362 MB. Every caller
(gatewayExternal, listedGateway) only reads the lists, and copies them
again into its own ExternalSession anyway.

The lists are now the kept projection's, shared and read only, which
GatewaySessions' doc now says. This changes the old contract that a
caller owned its copy. The kept lists are clipped, so an append by a
caller makes a slice of its own and can't write into another's.
gatewaySessionFrom shares the days in a window the same way.
GatewaySessionByID still hands out a clone.

TestGatewaySessionsHandOutTheKeptProjection writes 2000 sessions x 10
days and asks 10 times: 435,215 bytes an ask, against the 368,000-byte
list itself. With the clone put back by hand: red, 3,669,150 bytes an
ask. TestGatewaySessionsCacheRefreshAndOwnership now checks that two
asks share the days, that two callers' appends don't alias each other
or the kept list, and that the kept data is unchanged after them. With
the clone put back it is red too ("each ask has a copy of the days of
its own").

Run: go test -p 4 -count=1 ./internal/usage/ ./internal/gui/: ok (load
~157).

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 6359b2c27c usage: Vias hands every caller the one copy it keeps, and a session's list is copied only when read (#2776)
Vias cloned every session's list for each ask, from a cache built for
exactly this. The Sessions list, the manage pages and a session's
detail each asked, and read the lists of the sessions they show, or of
one. Over ~720k calls one ask was ~66 MB.

Vias now answers a ViaIndex over the kept map. Of(key) is a session's
list as a copy of its own, so a caller still can't change the kept
one; Len is how many sessions have one. The three GUI callers and the
tests read through Of.

TestViasHandOutTheKeptCopy writes 20,000 sessions and asks 20 times,
reading one list each: 2,590 bytes an ask. With the clone of every
list put back by hand (under ViaIndex): red, 3,817,492 bytes an ask.
It also changes a list read through Of and checks the next ask still
says 1 call.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 227b864a45 usage: CodexModelEffort keeps only the gateway calls a Codex session file's call can be matched to (#2776)
CodexModelEffort built the whole ledger of the period and kept the rows
that carry a Codex thread. Every gateway call became a Record (in
gatewayRecords' slice), a packed row (gatewayMatchesDetails' chunk) and
a priced Row (ledgerMatched), all held at once, though only a gateway
call paired with a Codex session file's call by its response id can
carry a thread. On the 720k-call sandbox this build was 7.6 GB of the
start's 18 GB allocated and most of its peak.

codexEffortRows visits the log once and keeps only the gateway calls
with a response id, request id or session (native, else magpie's) that
one of the session files' calls has, or an agy call when one is agy's.
No other gateway call can change gatewayMatchesDetails' answer: the
request-id match looks up only the locals' ids, the fallback groups are
looked up only by the locals' sessions, and a response id's uniqueness
is counted over every call that has it, all of which are kept. Only the
paired calls are priced into rows, and the rows are the whole ledger's
thread rows in the same order, so the sums (floats included) are the
same.

TestCodexEffortRowsAreTheWholeLedgers compares the rows with the whole
ledger's for All, Today and 7d, with Codex's reader and every agent's:
a pair by response id, an ambiguous response id, a session-and-tokens
match, a call two days old, and unrelated calls around them. With the
session test dropped from matchingRecords by hand it is red (all,
every agent: the session-matched call shows as a row of its own).

TestCodexModelEffortLetsUnrelatedCallsGo builds over 3000 unrelated
gateway calls and allows a visit of the log and a half. With the old
build put back (LedgerOf): red, 18,347,128 bytes against a visit's
1,198,680. With the fix: 1,321,824 against 1,321,744.

720k-call sandbox, cold start, the four first asks together, back to
back (load 48.7 then 14.7, so the times are not comparable; the memory
is what this measures):
  before (beb9c40d5): peak RSS 4411 MB, heapSys 5513 MB, live 574 MB
  after:              peak RSS 2427 MB, heapSys 2413 MB, live 542 MB
  manage?agent=codex answered in 41.5 s before, 23.1 s after.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone baef679f29 sessions: every other reader of a session file sizes its buffer by what is left of it, as scanAt does (#2776)
d7e02ae08 sized scanAt's buffer by the rest of the file. The other line
readers of a session file still took 1 MiB per file read:
- readMiniMaxCalls, readAgyCalls and readWorkBuddyCalls (WorkBuddy and
  CodeBuddy Code), which read a changed file whole;
- scanFrames, dsh's packed (.zstd) sessions, read on from a frame;
- mayHold, a search's first look at each file.
(calls_pi, calls_kimi, calls_dsh and dsh.go no longer hold one since
the incremental readers before a77f6ae16.) Each now takes
scanBuffer(f, off): the rest of a plain file plus one byte, 16 KiB to
1 MiB. ReadBytes and readFrame read a line or frame longer than the
buffer whole, as before; a packed WorkBuddy file (a zstd stream, not
an *os.File) keeps 1 MiB.

TestReadersOfASmallFileTakeASmallBuffer reads a two-line file 50 times
through each of the five and allows 256 KiB per read. With the five
readers put back (the test kept): red in all five, 1,049,161 (minimax),
1,049,271 (agy), 1,049,256 (workbuddy), 1,068,296 (frames) and
1,056,984 (search) bytes per read.

Not measured on the 600k sandbox: it holds no MiniMax, agy, WorkBuddy or
dsh sessions, so the saving there is the test's: ~1 MiB per file each
time one of these is read again.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone c483feadfd usage: OpenCode Zen's card says OpenCode tells no key its balance, and Go at /inference/go gets its plan card (ttmrmx on X)
ttmrmx on X: "magpie 里 OpenCode Zen/Go 这个供应商的余额卡片不显示".

Cause, two parts:
- An OpenCode Zen key (opencode.ai/zen, /inference) had no balance source,
  so KeyBalances skipped it without a word and the Usage page drew no card.
  OpenCode has no balance a key can read. In sst/opencode,
  packages/console/app/src/lib/inference-proxy.ts serves only the model
  routes. /zen/v1/balance, /zen/v1/credits, /zen/v1/usage and
  /zen/v1/billing all 404, and billing.mdx shows the credits only in the
  console (Overview -> Credits, to owners and admins). No endpoint was
  invented.
- planQuotaSourceOf matched only /zen/go. models.dev now gives Go as
  opencode.ai/inference/go/openai/v1, so a Go provider saved there got no
  plan card at all. openCodeGateway() now tells go/zen/other (custom is
  the user's own) for both URL shapes, and Go at either one reads
  https://opencode.ai/zen/go/v1/usage.

What changed:
- A Zen key's card now carries errOpenCodeNoBalance and seeAt
  (https://opencode.ai/console). It reads "OpenCode doesn't tell an API key
  its balance — see Zen's credits in the OpenCode console, Overview →
  Credits", with an "Open the console ↗" button. That is one button with
  the needsAccessKey "Open settings" one (#1821), so the bytes stay small.
- A provider with its own BalanceURL is still asked that URL.
- Strings are in zh, zh-TW, ja and de.
- coreScriptBudget: rebased onto f76201a84, whose 1,469,000 already
  holds the card (~390 bytes; the tray panel draws it too); unchanged.
  TestCoreScriptBudget re-run after the rebase: ok.
- Plugins: there is no OpenCode built-in mover, and this is a
  key provider, so the change is all in magpie.

Run, all on this tree (HEAD 94919109c):
- Old code: TestOpenCodeZenSaysItTellsNoBalance (adapted), TestPlanQuotaSource,
  TestPlanQuotas and opencode-zen-balance.test.cjs all fail on a detached
  HEAD checkout; they pass here.
- Real use, in a sandbox (go build -tags dev, sandbox HOME, ports
  3486/3487, never the live config), with the owner's OpenCode key copied
  read-only:
  - /api/usage/quotas gives the Zen variant the new error and seeAt.
  - Both Go providers (/zen/go and /inference/go) request the usage URL and
    show the vendor's real 401 "This API key has expired". The owner's key
    is expired, so no live Go reading was seen. There's no Zen account with
    credit either, so the console page itself wasn't checked against a
    balance.
  - A Playwright screenshot shows the card. Clicking the button posted
    /api/open with the console URL.
- go test -p 4 ./... -timeout 45m: every package ok except these.
  - internal/agent timed out at 45m under load; alone it is ok in 1184s
    (#2723, #2544).
  - gateway TestClaudeAccountsSpentFallBackToCodex and
    TestMaxRPMWaitsForRoomInTheMinute pass alone -count=3 (#2858/#2859,
    #1791).
  - gui TestCoreScriptBudget was mine; fixed above.
- gofmt -l clean. go vet: darwin all; GOOS=windows provider and gui;
  GOOS=linux provider (gui needs cgo/wails for linux).
- GUI, chromium + webkit, en/zh/zh-TW/ja/de at 900 and 420px, 2 workers.
  The full suite was stopped at ~416 tests (load 160-500). Its reds were
  in agent-*/account-* files, which this doesn't touch (#1544, #1949).
  - The targeted set passed: quota-*, balance-*, key-balance-card,
    opencode-*, usage-access-key-card, gui-de/ja/zh-tw, i18n-keys,
    panel-usage, panel-balance-order, panel-quota-refresh, tray-usages,
    usage-quota-head, glm/plugin-quota-error, gateway-key-quotas,
    usage-remote-cards, usage-card-refresh and deprecated-subscriptions.
  - Exceptions: gateway-key-quotas (ja launch timeout) and panel-usage
    (zh) were red under load and pass alone.
  - quota-name-translated and quota-count-wrap (webkit) are red alone
    here and on origin/main f76201a84, with the same asserts. That is
    #2228, commented.
2026-10-19 13:42:21 +08:00
yetone f76201a84a plugins: a sign-in page the plugin's CLI opened isn't opened again, Grok's opened twice on macOS (andyfmyth on X)
"magpie里的grok 登录验证 在mac下 似乎每次都会弹两次验证, 在浏览器窗口里".
Grok's plugin signs in through `grok login --device-auth`, and Grok Build
(1.0.50, the webbrowser crate) opens the device page itself, through
NSWorkspace on macOS and ShellExecuteW on Windows. Neither reads $BROWSER;
the macOS binary has no "BROWSER" string. magpie then opened the same URL
from /api/plugin-signin (desktop), startPluginSignIn/followSignIn (a
browser tab) or `magpie plugin login`. Reproduced in a sandbox
HOME/GROK_HOME: grok's device-code tab appeared in Chrome with magpie not
involved, with and without SSH_CONNECTION. Built-in grok is retired
(2927a161e), so the plugin's path is the only one.

- The plugin's authorize result can say `opened: true` (not OpenCode's).
  host.js passes it on as Authorization.Opened, then SignInState.Opened,
  and the desktop handler, the CLI and app.js (both open points) open
  nothing then; the link is still shown.
- opencode-grok-auth 0.1.17 (magpie-community/plugins 47fbf63, on npm per
  `npm view --prefer-online`) says opened on darwin/win32, and elsewhere
  gives grok BROWSER=true, a no-op, so magpie stays the one opener there.
  The grok mover min is raised to 0.1.17.
- No other plugin's CLI opens a page: devin, cursor, kiro and qoder run
  status/refresh commands only.
- docs/subsystems/provider-plugins.md says so.

Tests:
- TestPluginSignInPageOpensOnce: the fake plugin signs in through
  /api/plugin-signin. "cli-opened" opens 0 pages; otherwise 1. Red with
  the old gui/plugins.go ("opened 1 more times").
- plugin-signin-opened.test.cjs: in a browser tab, right away and after
  an install, 5 languages, Chromium and WebKit. Every "opened" case is
  red on HEAD's app.js (23 fail); 42/42 with the change.

Run at the change (base origin/main 2ceff7370):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean.
- go test -p 4 -count=1 ./... -timeout 45m (load 150-380): every package
  ok except two.
  - gateway: TestVisionWaitIsntTheDescribersTime. It passes alone; filed
    as #2901.
  - gui: TestDockReopenKeepsTheWindowsSpace, TestMainWindowCorners,
    TestMainWindowRightToLeft, TestTrayCellClickReleasedPanel and
    TestCoveredWindowStaysUp, killed at their deadlines. All pass alone
    with TestPluginSignInPageOpensOnce; filed as #2645/#1936.
- GUI, both engines, at most 2 workers: plugin-signin-opened,
  plugin-signin, plugin-signin-no-url, plugin-moved-signin,
  signin-paste-plugin, signin-browser-down, signin-link,
  plugin-password-prompt and plugin-replaced. The run went 126 pass,
  10 fail, all launch or 5s timeouts at load ~380. Alone,
  plugin-signin-opened passes in both engines and password-prompt
  passes. signin-browser-down was red in one case per run, a different
  one each time. plugin-moved-signin (Chromium) is red alone at HEAD's
  app.js too. Both are filed as #2900.
- plugins: bun test packages/grok 49 pass; scripts/check.mjs ok. Its
  publish run is red only for middleware-think-tags's npm trust
  (plugins#180); grok 0.1.17 was published.
2026-10-19 12:42:48 +08:00
yetone e7114d3882 usage: one gateway session projection is kept, and a range of days is read out of it (#2776)
The gateway's sessions were projected and kept once per `since`, up to
four at once (all time, and each Sessions stats range: today, 7, 30
days...). With 600k calls the all-time projection alone is ~160 MB in
use (pprof inuse_space of buildGatewaySessions on the sandbox below),
and #2776 counted 148 MB for its copies.

Now only the all-time projection is kept. A range that starts at a
local midnight (every stats range does: combinedSessionStats parses
st.From in time.Local) is derived from it: each session's days from that
date on, with its tokens, models, cost and start/last summed from those
days. Each kept day now carries the first and last time of its requests
(unexported, two time.Time) so the derived start and last are exact.
Any other start is built from the log and not kept. The cache is keyed
on the zone too, since the days are local dates.

TestGatewayWindowsShareOneProjection: six days of calls over three
sessions, priced and unpriced models; the all-time read and five ranges
(0, 1, 2, 3 and 7 days back) build one projection between them, and each
range equals a direct build from its midnight (sessions, start, last,
tokens, models, cost within 1e-9, unpriced, days). Broken by hand:
- the midnight path turned off (a build per range, as before): red,
  "built 6 projections for one log and 5 ranges, want 1".
- the derived start taken from the whole session: red, codex|even's
  Start 2026-10-15 where the build says 2026-10-19.

Cost: the two times per kept day add ~13 MB to the one projection on the
sandbox below (158 -> 171 MB in use), against a whole second projection
(~160 MB) for each range a page asks for.

Measured: the sandbox runs (see the commits before) ask only the 30-day
range, so their heap shows one kept projection on both sides; the
saving is per extra range asked and is shown by the test's build count,
not by those runs.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
2026-10-19 11:33:00 +08:00
yetone cfbd321fc4 gui: the start's warm-up reads Codex's per-thread effort when there are Codex sessions (#2776)
The first Sessions page after a start that showed Codex rows read
usage.CodexModelEffort cold, from the whole ledger, while the page
waited. The warm-up now reads it as its last step, after the stats it
already warmed, and only when those stats hold a Codex session; every
later ask is answered from what CodexModelEffort keeps per period.

The steps move into warmSteps() so a test can run them.
TestWarmUpReadsCodexEffort: with Codex keys in the stats the step reads
the effort once, with none it reads nothing. With the step removed: red,
"read 0 times, want 1".

Measured on the same sandbox as the commit before (600k gateway calls,
~4,600 sessions), base 1a3b92688 against this branch, back to back, at a
load average of 350-480 (nine agents running suites):

  manage?agent=codex, asked 3.5s after the routes:
    base 226s / 190s / 232s (cold)   new 247s / 222s / 246s (cold)

It is not faster here: asked at 3.5s, the page arrives before the
warm-up reaches its last step, and both read the ledger at once; the
load makes every one of these numbers mostly CPU wait. The step helps a
first Codex page opened after the warm-up is done, which is the case in
#2776 (a page opened some time after a restart). Not measured at that
point under this load.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
2026-10-19 11:33:00 +08:00
yetone d7e02ae088 sessions: a scan's read buffer is the size of what is left of the file, 1 MiB at most (#2776)
scanAt gave every scan a 1 MiB bufio buffer. A start reads ~4,600
mostly small session files (and reads each again from where it was
left), so those buffers were the largest single allocation of a start:
9.4 GB of the 22.4 GB a warm start allocated on the sandbox below. The
buffer is now the rest of a plain file plus one byte, at least 16 KiB
and at most 1 MiB; a packed (zstd) file keeps 1 MiB. A line longer than
the buffer (a file grown since its size was read) is still read whole
through scanAt's long-line path.

Tests (internal/sessions/scan_buffer_test.go):
- TestScanOfASmallFileTakesASmallBuffer: 200 scans of a two-line file
  allocate under 64 KiB each. With the 1 MiB buffer back: red, "a scan
  of a two-line file allocated 1048871 bytes".
- TestScanReadsALineLongerThanItsBuffer: a line three buffers long, then
  a short one, are both handed over whole.

Measured on a sandbox instance (600k gateway calls, ~4,600 sessions),
base 1a3b92688 against this branch with every #2776 commit, back to back
at a load average of 340-450 (nine agents running suites), heap profile
after the four first API calls and 60s idle:

                       allocated   of it scan buffers   live heap
  warm  base            22.40 GB         9.40 GB          483 MB
  warm  new             15.86 GB         1.98 GB          498 MB
  cold  base            22.48 GB         9.31 GB          450 MB
  cold  new             15.76 GB         1.98 GB          498 MB

What is left in bufio.NewReaderSize is the other call readers' own
1 MiB buffers (calls_pi, calls_kimi, ...). Peak RSS did not drop at this
load (base 4.38/4.41 GB, new 4.59/4.54 GB): the peak comes from the four
first calls each materialising the 600k-call ledger at once
(gatewayRecords appends every Record, 2.56 GB allocated; ledgerOfAt
6.2 GB for CodexModelEffort), which this commit does not change.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
2026-10-19 11:32:59 +08:00
yetone c381e4cd1e sessions: a read is never held by another read's refresh, only by a change to the files (#2776)
A read of the sessions (List, Stats, Manage, the agents' lists, Codex's
threads) took dbReadMu, a plain mutex, for the whole call, parse
included. The start's warm-up reads every session file with a quarter of
the cores, so the first pages and API calls after a start waited for its
whole read before they could even look at the cache.

- dbReadMu becomes storeMu, an RWMutex: reads take it shared, and only
  the changes to the files (Delete, a Codex provider move, a Claude
  project relocation) take it alone.
- A file another refresh is reading now is in `parsing`, with a channel
  closed when its parse is in the cache. A second read serves the parse
  it already has of such a file, and waits only for one it has never
  read; it never reads the same file twice at once.
- Each parse is published as it finishes, not in checkpoint batches, so
  a waiting reader gets it at once.
- The shared store handles (OpenCode, Hermes, Alma, Cursor) closed at the
  end of every read; with reads overlapping, one could close a handle
  another still used. They now live as long as their last user
  (useDBs). get() and the titles path closed them without the lock at
  all before.

Tests (internal/sessions/refresh_shared_test.go), each broken by hand:
- TestReadNotHeldByAnotherRead: the warm-up's parse of 12 grown files is
  held; List and Manage answer within 10s from the kept parses, each file
  is parsed once in all, and a later List parses none. With storeMu.Lock
  in List: red, "List waited for another read of the same files to end".
- TestReadWaitsForAFirstReadUnderWay: a file never read is waited for,
  not served empty, and read once. Without the waits: red, "List answered
  without the files being read". Without the skip of a file being read:
  panic, close of nil channel.
- TestStoresLiveAsLongAsTheirLastUser: with the release always closing:
  red, "closed while a read still used it".
All three pass with -race.

Measured on a sandbox instance (600k gateway calls, ~4,600 Claude Code
and Codex sessions, 300 grown since the last start; 4 API calls asked
3.5s after the routes, when the warm-up starts), base 1a3b92688 against
this branch, back to back. The machine's load average was 350-480
(nine agents running suites), so these timings are mostly CPU wait and
vary by tens of seconds run to run:

  first answer (stats?days=30)  base 91s / 81s    new 50s / 79s
  manage?agent=claude           base 112s / 95s   new 83s / 96s

The pages no longer queue behind the warm-up's lock, but at this load the
answer is bound by the CPU its own parse gets, so no gain shows above the
noise in the second pair. On an idle machine the held reads are what
#2776 reports; the tests above show they are no longer held.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
- At this commit alone (2ceff7370 + this change): ./internal/sessions
  ok (82s), and its three new tests with -race ok.
2026-10-19 11:32:59 +08:00
yetone a77f6ae168 sessions: a WorkBuddy reply whose first line spent nothing is one call
Found in the reader audit, not a speed fix. readWorkBuddyCalls replaced
the call before a line whenever the line's messageId was the one the
line before it carried. A zero-token line makes no call but still set
that id. So a reply opening with a zero line:
  - as a session's first reply, panicked: index out of range [-1] at
    st.Calls[len(st.Calls)-1], which took down the Usage ledger's read;
  - after another reply, overwrote that reply's call. m8 50/5, then m9
    0/0, then m9 300/20 gave one call (m9) where the Sessions summary
    (workbuddyLine: unuse m9's zero, keep m8) counts both.
The call before is replaced now only when it carries the same id.
CodeBuddy and the other WorkBuddy builds read through the same reader.

Test: TestWorkBuddyCallsReplyStartingAtZero writes both cases.
  - On the old code: panic, index out of range [-1].
  - Broken by hand, with only a len(st.Calls) > 0 check: red, "calls
    [m9 300/20], want m8's and m9's".

Run: go test ./internal/sessions -run 'WorkBuddy|CodeBuddy|Buddy'
-count=1 ok. The full-suite record is in the report for this series.
2026-10-19 11:30:48 +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 1f411802b8 sessions: Droid's and Grok's listings open only the files that changed
Droid's listing opened every transcript to read its first line, for
whether it is a subagent's (callingSessionId), and Grok Build's read and
decoded every session's summary.json for its session_kind and parent.
The listing runs on every 15s poll of Sessions and Usage, so with
thousands of sessions each poll opened thousands of files that had not
changed.

listMemo (listmemo.go) keeps what a listing read from each file by that
file's own size and mtime, not the folded size the listing gives the
session. A listing is a round: a file not seen in it (a session deleted)
is dropped when it ends, so the memo never outgrows the sessions there
are. A read that failed, such as a transcript whose first line is still
being written, is not kept, and the next listing reads it again: a
failed read means unknown, not "nobody's". Reset clears both memos.

Measured (3000 sessions each, one listing after another, CPU by
getrusage, the machine at load ~500):
  Droid before: 1103 ms CPU / 8.3 s wall per listing
  Droid after:  27-47 ms CPU / 0.05-1.0 s wall (first listing 1166 ms)
  Grok before:  649 ms CPU / 4.2 s wall per listing
  Grok after:   252-295 ms CPU / 1.8-2.2 s wall (first listing 707 ms)
What Grok's listing still spends is its globs and two stats a session
(updates.jsonl, summary.json), not reads.

Tests: TestDroidListingReadsOnlyChangedTranscripts counts transcript
opens (scanHook): a second listing opens only the half-written one,
appending reopens only that file, a finished first line is then kept,
and a transcript written over without a caller is its own session.
TestGrokListingReadsOnlyChangedSummaries counts summary reads
(grokSummaryHook): none when nothing changed or only the updates grew,
one when the summary is written over, and the key follows it.
Broken by hand: the memo never hit -> both red ("nothing changed: read
map[...all...]"); failed reads kept -> Droid red ("nothing changed: read
map[], want only the half-written one again").

Run: go test ./internal/sessions -run 'Listing|Droid|Grok' -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
yetone 6d3caf6fa4 sessions: a Cline session whose manifest alone changed is not read again
Cline keeps a session's messages in one JSON document, rewritten whole,
and its title, start and fork in a manifest beside it, whose size and
mtime are folded into the session file's. Cline rewrites that manifest
on its own (a title given, the session's status touched), and every such
rewrite made the Sessions and Usage pages decode the whole messages file
again, though nothing in it had changed.

parseCline now keeps what its messages were counted from: the messages
file's own size and mtime, and the start and fork time the manifest gave
then, with the first prompt that names the session. When the messages
file is as it was and the manifest still gives the same start and fork,
the counts stand and only the manifest is read again for the id, cwd,
name and title. Messages rewritten (any size or mtime change), or a
start or fork that moved, read them whole again as before. A messages
document can't be read on from where it was: it is rewritten, not
appended to.

Measured (CPU, getrusage; 50 MB messages file, the manifest rewritten
between reads; machine loaded):
  before: ~205-290 ms per read after a manifest change
  after:  0.1 ms per read after a manifest change; first read ~290 ms

Test: TestClineReadsMessagesOnlyWhenTheyChange counts reads of the
messages file (clineHook) and checks each read against a whole one: a
manifest touched or titled reads none of it, and the title from the
first prompt stays; a message changed, the same size at a later time, a
fork added and the start moved each read it again.
Broken by hand: no resume -> red ("manifest touched: messages read
again"); the start and fork not compared -> red (read on differs from
whole, after the fork); the carried prompt dropped -> red (read on
differs from whole).

Run: go test ./internal/sessions -run Cline -count=1 ok, and the whole
package green at the previous commit; 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 b3642e7277 sessions: a dsh session read before is read on from where it was left, not whole
dsh only appends to a session file, a line at a time or, packed
(.zstd), a frame of lines at a time. Every reply still made the
Sessions and Usage pages read, and for a packed file decompress, the
whole file again: a packed file "can't be read on from the middle of a
frame".

It can be read on from the start of one. frames.go walks a file of zstd
frames without decoding them (RFC 8878: the frame header, then blocks
that each give their length, then the checksum), decodes one frame at a
time, and says where to go on from: the frame the first line not yet
whole starts in, and how far into what it holds. A frame not yet
written whole waits for the next read, and so does a line a frame ends
inside of.

parseDsh keeps a tail (tail.go) and the header it read, and counts each
event as it comes (dshCount) instead of collecting them all first. A
fork's inherited end-seed met in a later read starts the counts over
from the session's start, keeping its title and name, as the whole read
did by cutting at the last one. A file that shrank or was replaced is
read whole again. One change from before: a last line not ended by a
newline now waits for it, like every other appended file's.

Measured (CPU, getrusage; 50 MB of events, a reply appended between
reads; packed: 17 MB of frames; machine loaded):
  plain   before: ~110-120 ms per read after an append
          after:  0.4-2.6 ms per read after an append; first read ~120 ms
  packed  before: ~190-250 ms per read after an append
          after:  0.4-0.5 ms per read after an append; first read ~260 ms

Tests: TestDshReadsOnlyWhatWasAppended runs the shared append, half
line, cut-short and rewritten-in-place cases.
TestDshPackedReadsOnlyWhatWasAppended appends a frame (read alone), half a frame (waits), a
frame ending inside a line and the frame that ends it (read on from the
first of the two, the line counted once), then cuts the file short and
replaces it with a longer one (read whole). TestDshEndSeedAcrossReads
writes a fork's seeded lines, its end-seed and its own, a read apart
each. Every read on is checked equal to a whole read.
Broken by hand: resume off -> red in both ReadsOnly tests ("after a
line appended to 1308 bytes, read from 0", "after a frame appended to
654 bytes, read from 0"); a line split over two frames resumed at the
second frame -> red (read on differs from whole); the end-seed reset
removed -> red in TestDshEndSeedAcrossReads and TestDsh.

Run: go test ./internal/sessions -count=1 -timeout 45m 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 e03d495f83 sessions: a Kimi Code session read before is read on from where it was left, not whole
Kimi Code only appends to a session's wire.jsonl, but every message (and
every rewrite of its state.json, whose size and mtime are folded into
the wire's) made the Sessions and Usage pages read the whole wire again,
a fork's twice: once for its last marker, once to count.

parseKimi is now one pass that keeps a tail (tail.go) and what the read
carries on with: the session's start, whether it is a fork, and the
fork's marker time. A forked marker met in a later read starts the
counts over from it, as a whole read does. Title, cwd and name still
come from state.json on every read, so a state.json-only change reads
none of the wire. A forkedFrom set or cleared reads whole again, and so
does a wire that shrank or was replaced; a half line waits.

Measured (CPU, getrusage; 50 MB wire, a message appended between reads;
machine loaded):
  before: ~256-278 ms per read after an append (same as the first read)
  after:  0.3-0.6 ms per read after an append

Tests: TestKimiReadsOnlyWhatWasAppended runs the shared append, half
line, cut-short and rewritten-in-place cases on a real wire's events,
then a state.json title change (nothing of the wire read) and a
forkedFrom set (read whole). Every read on is checked equal to a whole
read. TestKimiForkMarkerAcrossReads writes a fork's copied lines, then
its marker, then its own usage, a read apart each: only the fork's own
usage counts.
Broken by hand: resume off -> red ("after a line appended to 29089
bytes, read from 0"); the marker's reset removed -> red in
TestKimiForkMarkerAcrossReads and TestKimiCodeSessionFork.

Run: go test ./internal/sessions -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 b9b4c21c5b sessions: a Droid transcript read before is read on from where it was left, not whole
Droid only appends to a session's transcript, but every message (and
every rewrite of its settings.json, whose size and mtime are folded into
the transcript's) made the Sessions and Usage pages parse the whole
transcript again.

parseDroid now keeps a tail (tail.go) and what the read carries on with:
whether the session_start line and a fork's copied lines are behind it,
and what the settings' running total was counted as (date, model,
tokens). The next read takes that total back (dropUse, which leaves no
empty model or day behind, so the summary is the one a whole read makes),
reads on from the tail, and counts the total again on the day of the last
message. A transcript that shrank or was replaced is read whole again; a
half line waits for the next read.

Measured (CPU, getrusage; 50 MB transcript, a message appended between
reads; machine loaded):
  before: ~490 ms per read after an append (same as the first read)
  after:  0.2-1.8 ms per read after an append; first read ~470 ms

Tests: TestDroidReadsOnlyWhatWasAppended runs the shared append, half
line, cut-short and rewritten-in-place cases, then a message a day later
with a grown total (counted once, moved to the new day), then a
settings-only change (nothing of the transcript read). Every read on is
checked equal to a whole read. TestDroidForkAcrossReads appends a fork's
copied lines one read at a time.
Broken by hand: resume off -> red ("after a line appended to 825 bytes,
read from 0"); the old total not taken back -> red (read on differs from
whole).

Run: go test ./internal/sessions -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 d9f6b42cbc sessions: a Grok Build session read before is read on from where it was left, not whole
Grok Build only appends to a session's updates.jsonl, but every change
to it (and every rewrite of its summary.json, whose size and mtime are
folded into the file's) made the Sessions and Usage pages parse the
whole file again.

parseGrok now keeps a tail (tail.go) with its summary: the offset after
the last whole line, the file's head and a sampled prefix hash. The next
read goes on from that offset when the file has only grown and the
summary still names the same model, created time and parent; the first
prompt still coming in chunks carries over too. A file that shrank, or
whose head or sampled prefix changed, is read whole again, and a half
line at the end waits for the next read.

Measured (CPU, getrusage; 50 MB updates.jsonl, a turn appended between
reads; the machine was loaded, so CPU time, not wall):
  before: 46 ms per read after an append (same as the first read)
  after:  0.2 ms per read after an append; first read 44 ms

Tests: TestGrokReadsOnlyWhatWasAppended checks where each read starts
(through scanHook) and that every read on from a tail equals a whole
read: a line appended is read alone; half a line waits and is counted
once; the file cut back to its old bytes, or one byte changed in place
in a line it had, is read whole; a summary-only change reads nothing of
the updates; a changed model reads whole. TestGrokPromptAcrossReads
carries a chunked first prompt across reads.
Broken by hand: resume turned off -> red ("after a line appended to
2684 bytes, read from 0"); tail.holds made to trust any grown file ->
red ("rewritten in place, read from 3055").

Run: go test ./internal/sessions -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:46 +08:00
yetone 5774c790bd plugin: a reply's chunk frame is read by its fixed shape, not through encoding/json
Each chunk of a plugin's streamed reply (up to 64 KB of base64 a frame)
went through json.Unmarshal into message. encoding/json scanned every
byte twice (validating, then decoding the string) and cost far more than
decoding the base64 itself. chunkFrame reads the one shape host.js's
chunkLine writes, {"id":N,"event":"chunk","data":"..."}. Any other line,
or one whose data holds a quote or a backslash, still goes through
json.Unmarshal. push checks the data is base64 of a frame's size either
way, as before.

Measured (64 KB frame, json vs chunkFrame, each followed by the base64
decode push does; -cpu 1, 6 runs, load average ~480, so absolute times
are inflated):
- json.Unmarshal + DecodeString: 7.3-14.0 ms/op, median ~8.7 ms
- chunkFrame + DecodeString: 0.11-2.3 ms/op, median ~0.33 ms

Test: TestChunkFrameReadsWithoutJSON. Frames json.Marshal'd with a \n,
\r\n or no line end must parse and equal what json.Unmarshal makes. It
also refuses 11 other shapes, among them:
- an escape in the data;
- a negative id, or 1e3;
- extra fields or trailing bytes;
- a 20-digit id;
- reordered keys.
Broken by hand (chunkFrame always false), it went red: "a chunk frame as
host.js writes it ... went through encoding/json".

Run (load ~420): go test ./internal/plugin -count=1 -run on the chunk
frame, host, flow, stream, chunk, credit and fetch tests: ok (54.0 s).
The whole package runs with the final checks.
2026-10-19 09:40:46 +08:00
yetone ef75a9a2b5 plugin: a streamed reply's chunk frame is joined, not stringified, and its bytes viewed, not copied
Every chunk of a plugin's streamed reply went out as
JSON.stringify({id, event: "chunk", data}), and stringify scanned every
byte of the base64 for something to escape. Base64 has nothing JSON
escapes, so chunkLine joins the line from strings instead. The line is
byte-for-byte the one stringify made. A Uint8Array chunk that isn't a
Buffer (what a Response body hands over) was also copied whole by
Buffer.from before it was encoded. It is now viewed: the bytes are
encoded before the next read, so nothing else touches them.

Measured in bun, old and new interleaved in one process, medians (load
average 363-413, so absolute times are inflated). The bench asserts the
lines are equal.
- 2032 B frame: 152.8 us -> 12.8 us (78.9 -> 6.6 ms per MB)
- 16 KB frame: 675.8 us -> 69.4 us (43.3 -> 4.4 ms per MB)
- 64 KB frame (MAX_FRAME): 2135 us -> 292.6 us (34.2 -> 4.7 ms per MB)

Test: TestHostFramesChunksCheaply streams Uint8Array parts (one of 70 KB,
so it splits at MAX_FRAME) through host.js's fetch loop in a vm. It
checks:
- 4 chunk frames;
- the bytes come back equal;
- JSON.stringify never sees a chunk;
- Buffer.from never copies a chunk.
Broken by hand twice, red both times:
- the frame built as an object again: "chunk frames are joined, not
  stringified";
- Buffer.from(chunk) again: "chunks are viewed, not copied".

Run (load ~420): go test ./internal/plugin -count=1 -run on the host,
flow, stream, chunk, credit, fetch and auth tests: ok (51.2 s). The whole package runs with the final checks.
2026-10-19 09:40:45 +08:00
yetone 8f37ed57d2 plugin: plugin-auth.json is parsed once per version of the file, not on every request
Every request read and parsed plugin-auth.json in the host two or three
times: accountKey (when no account is named), fresh (is a renewal due),
and the plugin's getAuth from its loader's fetch. Reading and parsing a
20 KB file (12 sign-ins) cost ~0.65-0.97 ms each on this loaded machine.

readAuth now keeps what it parsed while the file has the same mtime,
size and inode, as Go's filememo does. While the file's time is within
2 s of now it also keeps the bytes and compares them, so two same-size
writes inside one tick of a coarse clock (Linux) still read as two. A
file that doesn't parse is never kept, so the .bak recovery path is
unchanged. changeAuth still reads afresh under the lock. The kept
object is shared, so what a plugin is handed (getAuth for loader, usage
and check-in, the models hook's auth, pi.js's readAuth) is a copy of its
own (authCopy).

Measured (load average 360-460, so absolute times are inflated):
- readAuth on a settled 20 KB file, old and new interleaved in one bun
  process, 6 rounds of 5000: old median 970 us (min 841) and 1 file read
  per call. New median 23 us (min 2.3), a stat, and 0 file reads.
- whole fetch (TestPerfScratch, not committed, {} body, 400 fetches):
  host CPU 750-825 us -> 750-775 us per fetch, inside this load's noise.
  A control run without the big file read 875 us at the same load. Host
  RSS 53 MB -> 42 MB.

Test: TestAuthReadOncePerVersion runs host.js's own auth section in node
with readFileSync counted. It checks:
- 100 reads of a settled file read it once;
- a rewrite is read;
- a same-size rewrite with the same mtime is read;
- authCopy's copies are the caller's own.
Broken by hand twice, red both times:
- readAuth made the old uncached read: "a settled file is read once for
  100 reads, read 100 times".
- bytes of a just-written file not kept: "a same-size rewrite in one
  tick is read".

Run (-p 4, load ~470): go test ./internal/plugin -count=1 ok with
TestGatewayHookMixedPiPackage skipped. That test passed alone at 545.6 s
(pinned pi install under load); in a full package run it hit its 4-minute
start deadline ("starting plugins: context deadline exceeded").
2026-10-19 09:40:45 +08:00
yetone e3c09f4f36 plugin: a request is told the provider info built once per account, not built again per fetch
host.js ran info(provider, key) on every fetch, to hand chat.headers
hooks the provider. Each build rebuilt the model list from models.dev and
config, read and parsed plugin-auth.json twice, JSON-cloned the list and
asked the plugin's provider.models hook, which real plugins (cursor, zed
and others) answer by asking the vendor once their own TTL runs out. It ran
even when no plugin had a chat.headers hook.

infoOf(id, key) now keeps the info per account. Any change to the
account's sign-in (setAuth, removeAuth, settle, client.auth.set, renew,
take, reload, all through forgetAccount), new provider options, or a new
models.dev file builds it again, once. providers() seeds the cache with
what it built. The loader, usage and check-in read it too; check's strict
build stays direct. chat.headers gets the shared object, as OpenCode hands
plugins the provider it keeps, and the request asks for it only when a
plugin has a chat.headers hook.

Measured (TestPerfScratch harness, not committed; fake plugin, sandbox
HOME, loaded machine, two runs each):
- {} body, 1-event reply, 400 fetches: models hook asked 400 -> 0 times.
- same, a plugin with 300 config models: 0.995-1.17 ms -> 0.27-0.29 ms
  wall per fetch, host CPU 1.23-1.33 ms -> 0.30 ms per fetch, host RSS
  87-89 MB -> ~54 MB.
- 246 KB body, 2 MB SSE reply, 40 fetches: host CPU 10.25 -> 8.25 ms per
  fetch, models hook asked 40 -> 0 times.
- idle host CPU ~10-20 ms per 10 s before and after.

Tests: TestFetchBuildsInfoOnce counts the fake's models hook (new
FAKE_MODELS_LOG): 20 fetches ask it 0 more times, a new sign-in and new
options each ask it exactly once, and chat.headers and the loader still
see fake-1 and every model. Broken by hand twice, red both times:
returning no cached info ("20 requests asked the models hook 20 more
times, want 0"), and not forgetting it on sign-in ("after a new sign-in
... 0 times, want 1"). host_flow_test's mid-setup case now stubs infoOf
and registers a chat.headers hook for its "info" stage, which red on
this change without it (the stage was never entered).

Run: go test ./internal/plugin -count=1 ok (159.5s);
TestFlowAbortDuringSetup|TestFetchBuildsInfoOnce -count=2 ok.
2026-10-19 09:40:45 +08:00
yetone 2ceff7370f gui: the window back reads the state once, not once for visibility and again for focus
A window shown again hears visibilitychange and focus together, and each
called load(true): two reads of /api/state (every agent's config), with
loadCLIs, loadInstalls, the providers and the Usage refresh after each.
Under focus-follows-mouse every pointer crossing into the window was one
more. loadBack now joins a return to the read asked under a second ago;
a return while an older read is still out gets one read after it, however
many came meanwhile.

Numbers (sandbox HOME, 16 agents, 1230 catalog models, dev build):
  /api/state is 2.28 MB and ~55 ms of CPU per read (20 reads: 1.11 s).
  Reads per window return: before 2, after 1.

The core's scripts were 1,446,845 bytes, 155 under their budget; loadBack
adds 523. Every page needs it, so it is the core's own: coreScriptBudget
goes to the new total, 1,447,368, plus 1.5% (1,469,000), as the budget's
own rule says.

Test: internal/gui/tests/window-back-once.test.cjs counts /api/state
reads for a return, a later return, and returns during a held read.
On the old app.js: 8 of 8 red, "shown again ... actual 2, expected 1".

Run at this head (load average ~500, nine sessions' suites at once):
  node --test window-back-once.test.cjs, Chromium and WebKit, en and zh,
  window and panel: 8 of 8 ok. TestCoreScriptBudget ok.
  GUI files that fire focus or visibility (15 files, both engines): 194 of
  196 ok. claude-usage-asked webkit en passes 9 of 9 alone.
  tray-cell-click webkit zh is red alone 3 of 3, on 1a3b92688's own app.js
  too: #2686, output added there.
  go test -p 4 ./... -timeout 45m (HOME a sandbox): 59 packages ok, and:
  - internal/gui: TestCoreScriptBudget red, fixed here (budget above);
    TestSetAnswersWhileDevinAndProvidersHang red (13.8s sets), ok alone
    (12.6s) and the whole package ok alone (391s): #1375, output added.
  - internal/plugin: TestGatewayHookMixedPiPackage red ("starting plugins:
    context deadline exceeded"), ok alone (110.8s): #2865, output added.
  - internal/agent, internal/library, internal/gateway: timed out at 45m.
    agent timed out alone too (2701.5s): #2544, output added. library is
    #2853 and gateway #2870. Neither was rerun alone, to keep load off
    the machine.
  go vet on darwin, linux (nogui) and windows: clean. gofmt -l: clean.
2026-10-19 09:29:28 +08:00
yetone 94919109cb gateway: a silent HTTP/2 connection to a vendor is pinged and dropped (#2843)
pinewhite (#2843, v0.1.1279, Linux): for ~30 minutes every request to
group/auto-deepseek-v4-1-flash hung with no first byte. The WorkBuddy
member was resting on a 429, so they all went to ClinePass, and usage
shows only 499s with in=0. A restart answered the same request in 1.6s.

Cause: the gateway's transport (upstreamTransport) speaks HTTP/2 to
any vendor that offers it, so every request to api.cline.bot shares one
connection. It had no HTTP/2 health check. A connection that goes silent
without closing (a local proxy whose own way out died, or a NAT that
forgot the flow) stays in the pool. Every new request is multiplexed
onto it and waits for the 10-minute ResponseHeaderTimeout while the
kernel takes the writes. The agent gives up first, so nothing fails over
and nothing rests the member. Restarting dropped the connection.

Fix: netproxy.HTTP2Health() (SendPingTimeout 20s, PingTimeout 10s) on
upstreamTransport. Go now pings a connection that has had no frame for
20s and closes it when no answer comes within 10s. The requests on it
fail as a 502 ("http2: client connection lost"), so a group moves on,
and the next request dials a new connection. A live vendor answers a
ping whatever its streams are doing, so a long wait for a first byte is
not cut. The same setting goes on http.DefaultTransport in
netproxy.Install, the sibling pool that usage cards, catalogs and
sign-ins use. Not covered: requests a plugin sends from Bun.

Tests (new):
- TestSilentHTTP2ConnectionIsDropped: an HTTP/2 TLS httptest vendor
  behind a TCP relay that can go silent on its open connections (it
  takes writes, passes nothing). After the relay goes silent, a request
  must end well inside 10s, and the next one must succeed on a second
  connection.
- TestGroupMovesOnFromSilentHTTP2Connection: the same through the real
  Handler, with an ordered group a/m then b/m. Once a's connection is
  silent, the request must get b's reply.
- TestInstallChecksHTTP2Connections (netproxy).

What was run (worktree on origin/main 1a3b92688, sandbox HOME, pinned
GOCACHE/GOMODCACHE, go1.26.8 darwin/arm64):
- Red without the fix (HTTP2 lines removed, tests kept):
  TestSilentHTTP2ConnectionIsDropped FAIL "hung 10.003s, until the
  client gave up: context deadline exceeded";
  TestGroupMovesOnFromSilentHTTP2Connection FAIL "200 <empty> after
  10.005s; want b's reply"; TestInstallChecksHTTP2Connections FAIL
  "HTTP/2 after Install: <nil>".
- Green with it: those, TestCodexBackendOverHTTP1 and the Stale tests,
  -race -count=3: ok.
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok. go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build: ok.
- go test -timeout 45m ./...: 59 packages ok. The machine's load average
  was 400-460 (other sessions' GUI suites and builds).
  internal/agent, internal/gateway and internal/library hit the 45m
  alarm while a test that had just started was running (0-40s in), not
  stuck in one test. Four tests failed on a time bound:
  TestIntentClassifierGroup, TestClaudeAccountsSpentFallBackToCodex
  (gateway), TestSetAnswersWhileDevinAndProvidersHang (gui; a set took
  18s against its bar) and TestGatewayHookWaitsForStartingHost (plugin).
  None of them uses HTTP/2. Rerun alone on this change: gateway,
  gui and plugin ok. internal/library alone: ok
  (2220s). internal/agent alone hit 45m again at load ~400, as filed
  in #2723/#2544 (it doesn't call netproxy.Install or upstreamTransport
  in a test this touches). The reds are filed: #1813, #2858/#2859,
  #1375, #2723/#2544, #2853, #2870, and #2871 (new, the plugin one).

Not verified: no real ClinePass account behind a proxy that goes silent,
so the reporter's path is reproduced with an injected silent relay, not
seen live. Not tried on Linux or Windows beyond vet and build. The GUI
is not touched, so the GUI suite was not run.
2026-10-19 08:00:04 +08:00
yetone 47eb42f1a1 workbuddy: moved users get plugin 0.1.25, where WorkBuddy AI's "x0.34 credits" rates are read, not unknown (magpie-community/plugins#216)
WorkBuddy AI's /v3/config gives fast-model, balanced-model and
primary-model their credits as "x0.34 credits", "x0.59 credits" and
"x3.31 credits" (read live from the owner's account on 2026-10-19). Plugin
0.1.24 read those as unknown, so the three showed no rate. 0.1.25
(plugins c89cee5, bump ab38da6) strips a trailing "credits" unit only;
empty, negative, non-finite or other trailing text stays unknown. npm view
@magpie-community/opencode-workbuddy-auth version --prefer-online: 0.1.25.
The retired built-in has no wbCredits any more, so there is nothing to
mirror here.

Run on origin/main 1a3b92688 + this change, go1.26.8, load average ~420
from other sessions throughout:
- gofmt -l: nothing. go vet ./... ok; GOOS=linux go vet -tags nogui ./...
  ok; GOOS=windows go vet ./... ok. go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build ok.
- set -o pipefail; go test -timeout 45m ./...: 60 packages ok, 4 FAIL, all
  load and all in packages this doesn't touch. internal/provider, the one
  it does, ok (1841s).
  - internal/agent: 45m timeout, TestClaudeTierPickedAsTheMainModelStays
    23s in (#2544, #2723).
  - internal/gateway: 45m timeout, TestReplyNamesMember 1m7s in (#2870,
    filed now).
  - internal/library: 45m timeout (#2853).
  - internal/gui: TestSetAnswersWhileDevinAndProvidersHang, a set took
    18.2s (#1375). Rerun alone -count=3: ok.
2026-10-19 07:53:47 +08:00
yetone fc78eb5f6b gateway: ClinePass's upstream is read from provider_metadata.gateway.routing.finalProvider (#2847, smart-lty)
ClinePass (api.cline.bot) names the provider that answered only in a
Chat choice's provider_metadata.gateway.routing.finalProvider: under
delta in a stream chunk, and under message in a single body. upstreamOf
read only a top-level provider, message.provider and response.provider,
so the Routing page's 上游 column, the request log and the usage ledger
showed nothing for ClinePass.

upstreamOf now also reads finalProvider at those two places, and nowhere
else. A choice's content belongs to the model. providerAttempts inside
routing lists every provider that was tried, not the one that answered.
The cheap pre-check now passes a chunk that carries only
"finalProvider".

Tests:
- TestUpstreamOfClinePass checks:
  - the real chunk gives deepseek;
  - the same chunk as one body (message) gives deepseek;
  - content, tool_call arguments, providerAttempts alone and an
    object-valued finalProvider give "";
  - a top-level provider still wins.
- TestClinePassUpstreamRecorded serves the real stream through the
  Handler on /v1/chat/completions and on /v1/messages (translated). It
  checks that the route, the try, Recent() and the usage ledger all say
  deepseek.

The fixture testdata/clinepass_stream.sse is a real ClinePass stream:
api.cline.bot, deepseek/deepseek-v4.1-flash, captured 2026-10-02 in the
MIT-licensed wkeking/clinepass-channel-monitor
(internal/channellog/testdata/plain_success.log). It is not the
reporter's own bytes; #2847 has none.

What was run at 1a3b92688 + this change, on macOS (Go 1.26.8):
- gofmt -l: clean.
- go vet: darwin, linux (-tags nogui) and windows.
- Builds: darwin, linux (nogui) and windows.
- go test -run 'TestUpstream|TestClinePass|TestServed' ./internal/gateway: ok.
- Broken by hand: with the old upstream.go put back, both new tests go
  red ("real ClinePass chunk: upstreamOf = \"\"; want deepseek", plus the
  route, request-log and usage assertions on both paths).
- go test -timeout 45m ./... at load average 420-460 (several sessions'
  suites at once). agent, davsync, gateway, library, plugin and provider
  ran past the 45m timeout. gui was red on load reds that are already
  filed:
  - TestSetAnswersWhileDevinAndProvidersHang: #1375.
  - TestTrayCellClickReleasedPanel: #2645.
  - TestClaudeAccountsSpentFallBackToCodex: #2859, also #2858.
  - TestHostOnBunLackingLibsSaysWhich and TestGatewayHookMixedPiPackage:
    #2865.
  - The package timeouts: #2869.
  Every other package was ok.

Not tried: a live ClinePass account in the real app.
2026-10-19 07:38:46 +08:00
yetone 3608ed782e gui: WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS reaches magpie's WebView2 on Windows again (#2753, LuYquan)
The reporter's Nahimic DLL gets WebView2's renderer killed by code
integrity and the window goes black; the usual workaround,
WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--disable-features=RendererCodeIntegrity,
never reached magpie's renderer. The cause is not WebView2 skipping the
variable because magpie passes its own arguments: Wails v3.0.0-beta.24's
loader blanks the variable in its package init
(webviewloader.preventEnvAndRegistryOverrides), before any magpie code
runs. Seen on the Windows box: a debug build's windowsOptions read "".

- internal/webview2env reads the variable at init. It imports only
  syscall, so by Go's init order (first ready package by import path)
  it is initialized before os, and so before Wails' loader, which needs
  os.
- windowsOptions sorts it into Wails' DisabledFeatures, EnabledFeatures
  and AdditionalBrowserArgs. Wails writes msSmartScreenProtection plus
  the user's features as one --disable-features (Chromium keeps only
  the last of two), one --enable-features, and the rest as written.
  A list given twice is merged, each feature once.
- Nothing is added by default: RendererCodeIntegrity stays on unless
  the user asks.

ProcessFailed: not done. Wails' edge.Chromium has a ProcessFailedCallback,
but setupChromium never sets it, the package is under wails/v3/internal
(not importable) and a window's chromium is unexported; Wails has no
public event for a dead renderer. Reloading on renderer death needs a
change in Wails.

Run:
- gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows:
  clean. Builds for the three.
- go test ./internal/gui -run 'TestWebView2|TestWindowsOptions' on
  macOS, and the windows/amd64 test binary on the Windows box (sandbox
  dir, my own process name): TestWebView2ArgsSurviveWailsInit passes
  there with os="" (Wails blanked it) and disabled=[RendererCodeIntegrity].
- The real app on the Windows box (portable sandbox, MAGPIE_ADDR :3481,
  USERPROFILE/APPDATA/LOCALAPPDATA redirected) started with
  "--disable-features=RendererCodeIntegrity --enable-features=msTestFoo
  --lang=de": every msedgewebview2.exe of it carries one
  --disable-features with both features, --enable-features=msTestFoo
  and --lang=de. Before, the same launch showed only
  --disable-features=msSmartScreenProtection and --lang=zh-CN.

Broken by hand:
- windowsOptions reading os.Getenv instead of webview2env.Args: on the
  Windows box TestWebView2ArgsSurviveWailsInit goes red
  (os="" disabled=[]).
- webView2Args ignoring the env (""): TestWebView2ArgsMergeTheUsers red
  in "the reporter's" and "twice".
- --disable-features treated as an other argument: red in three cases,
  including the one-switch count.

Full suite at origin/main 1a3b92688 + this and the #2757/#2755 GUI
commits, go test -timeout 45m ./..., sandbox HOME: gofmt -l clean, vet
darwin/linux(nogui)/windows clean, 57 packages ok. At load 475-548 from
other sessions' suites, agent (#2544, #2723), gateway (#2108, #2191;
TestClaudeAccountsSpentFallBackToCodex #2858), library (#2853), davsync,
provider and plugin (#2869; TestGatewayHookMixedPiPackage and
TestHostOnBunLackingLibsSaysWhich #2865) ran past 45m, and internal/gui
had TestSetAnswersWhileDevinAndProvidersHang red (#1375). Rerun alone:
internal/gui and internal/webview2env ok. An earlier full run at
d783df46c + this alone: 61 ok, the same load reds. No asset changes, so
no GUI run.
2026-10-19 07:23:04 +08:00
yetone 41f5107b91 provider: the zed mover's min is 0.1.10, which picks the organization with a plan (plugins#232)
Zed 0.1.10 (plugins 5a83674) no longer always uses the default
organization. It picks the saved org, then the default, then a personal
org, as long as that org has a paid plan and models on, and it moves the
account once when an org answers 402. ReneXiong's default org has no plan
and the personal one has zed_student, so every request got a 402.
Raising the min lets keepMovedCurrent update every moved user.

Run at 1a3b92688 (origin/main) plus this change:
- npm view @magpie-community/opencode-zed-auth version --prefer-online: 0.1.10
- gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
- go test -timeout 45m ./...: 56 ok. The machine was at load ~500 from
  other sessions' test runs, and internal/agent, cli, davsync, gateway,
  library and provider hit the 45m timeout (#2108 is gateway's). Six named
  fails were timing under that load: TestIntentClassifierGroup,
  TestPluginPageReadsWhatItDeclared, TestSetAnswersWhileDevinAndProvidersHang,
  TestHostOnBunLackingLibsSaysWhich, TestGatewayHookMixedPiPackage and
  TestAllowancesCountFromTheReading. Each passes alone at the same head
  (gateway, gui, plugin, and provider with -run
  'TestAllowancesCountFromTheReading|Moved|Migrat|Mover|Zed').
- Not run: the timed-out packages again in full, since the load hadn't
  dropped. This change is one version string in internal/provider.
2026-10-19 07:07:33 +08:00
yetone 1a3b926886 agent: a [1m] main beside a smaller tier is told its own 1M, the tier held to its own (多喝热水 on Discord)
多喝热水 had Full window on, Claude Code's main on a [1m] DeepSeek 4.1 and
a smaller tier beside it. magpie told Claude Code the least tier's window
(CLAUDE_CODE_MAX_CONTEXT_TOKENS=246000), so it read 246K as the main
model's window and asked why 1M never showed. It is also the window
Claude Code falls back to when it stops taking the main for 1M.

Now a [1m] main of magpie's beside a tier that isn't takes the layout
Desktop already has (desktopPlan): the window told is the main's own
(1M), each smaller tier gets modelSettings.<id>.autoCompactWindow at its
own window, and the working window goes in the top-level
autoCompactWindow in place of the env (none under Full window). A [1m]
main alone, a Claude main and the user's own env and settings are as
before.

Run:
- TestClaudeContextWindow's new case (tier beside a [1m] main, with and
  without Full window, then the tier gone) fails on the old code
  (window "128000", no tier entry, env compact 272000) and passes now.
- Real Claude Code 2.1.302 in a sandbox CLAUDE_CONFIG_DIR on the live
  gateway, main workbuddy/deepseek-v4.1-flash[1m], haiku workbuddy/hy3:
  /context shows the main at 272k and hy3 at 192k without Full window,
  and the main at 1m and hy3 at 192k with it. With the old layout's
  env of 246000, hy3 showed 246k, past its own 192k.
  A real request on the main replied "ok".
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./... clean; go build ./... ok.
- go test -timeout 45m -count=1 ./... at 95ef45fda: every package ok.
  After rebasing onto a595f1559 (no internal/agent changes there),
  go test ./internal/agent/ again: ok.
2026-10-19 04:09:16 +08:00
yetone 81029fc63c sessions: the overview's stats and their native sessions come of one pass over the files (#2776)
combinedSessionStats, behind /api/sessions/stats and /overview (each
range read again in the background when its memo is over 10 s old, so
on every 15 s poll of the Sessions page), took sessions.StatsFor and then
sessions.List(All) only for the agent|id set that keeps a gateway session
the agent keeps too from counting twice: two passes over every agent's
files, each refreshing them all. sessions.StatsAndNative gives both from
StatsFor's one pass: the same set, a session List would list (one
nothing was said in still left out, as before), but with no 5000 limit,
so a gateway session whose native one is among the oldest of a long
history is no longer counted again.

Test: TestStatsAndNativeOnePass: one pass over the files (filesHook, new),
and the same keys as List(All) on the fixtures. Red with StatsAndNative
written as the old pair of calls: "2 passes over the files".

Measured on the synthetic sandbox HOME (3000 Claude Code, 1500 Codex,
2000 Hermes sessions), combinedSessionStats warm after a restart, CPU
time (load average ~250, wall times noisy), parent 8e2b1dce6 against
this change, 4 rounds each:
  days=30  94-99 ms -> 57-62 ms CPU
  days=0  107-130 ms -> 68-74 ms CPU
  first after a restart (days=30)  558 -> 510 ms CPU

Run at this commit (the series' last; it covers 0179cef63, bbee24810
and 8e2b1dce6 too), on a machine at load average ~250-500:
- go test ./... -timeout 45m: 60 packages ok, sessions (869.8s), usage
  ok. Red only under that load, all green when run again:
  - internal/agent and internal/gateway timed out at 45m in tests that
    don't touch sessions (TestPiOffersItsOwnOpenAICodexModels,
    TestVisionSettingPicksTheDescriber). Run again with -timeout 90m:
    agent ok (1394.2s), gateway ok (1546.9s).
  - internal/gui TestSetAnswersWhileDevinAndProvidersHang: set took
    44.6s under load; it is #1375. Alone: ok.
  - internal/plugin TestGatewayHookMixedPiPackage: "starting plugins:
    context deadline exceeded" after 718s (bun's install cache was slow).
    Alone: ok (163.6s). No issue found for it.
- gofmt -l: clean.
- GOOS=windows go vet ./...: ok.
- GOOS=linux go vet -tags nogui ./...: ok. Without the tag, vet stops in
  wails v3's own linux files (undefined: pointer, cgo off when vetting
  across OSes from macOS); go.mod is untouched here.
- No GUI assets changed, so the GUI suite was not run.
2026-10-19 03:57:52 +08:00
yetone 38f6bee23e sessions: the manage page reads its agents' files once, and only the agents it shows (#2776)
GET /api/sessions/manage went over every agent's session files three
times: sessions.Agents() for the counts, sessions.List(All) only to build
the set that keeps a gateway session its agent keeps too from being
counted twice, and sessions.ListAgent for the list. List(All) also read
every agent's changed files again and put every session together, prices
and titles included, to take its id. So a page showing Claude Code's
sessions parsed Hermes's and Codex's writes too.

sessions.Manage now does it in one pass over the files, under one hold
of the locks: the counts, the ids of the sessions of the agents that have
gateway sessions (nativeIDs: the id from the file's key, or from its
parse for the agents that write it inside the file, idInFile, which are
the only ones read), then the picked agent's list. The handler's pick
runs as a callback so the counts can include the gateway sessions. A
change to an agent not shown and with no gateway sessions waits for a
page that shows it. assemble's id rule moved into sessionID, which both
use.

That set was also wrong in two ways. List leaves out a session nothing
was said in and stops at 5000 (All), while the list beside it keeps
every one, so a gateway session whose agent's file was empty (or among
the oldest of more than 5000) was counted twice and listed once. The
set is now every native session, the same as the list's, and
POST /api/sessions/delete, which tells a listed gateway session from a
native one, uses it too (sessions.NativeIDs).
docs/subsystems/gateway-sessions.md says so.

Tests:
- TestManageReadsOnlyTheAgentsItShows: Codex's files changed, Claude
  Code's page parses none of them; asked for Codex's ids it reads them;
  the native ids equal the list's, the empty session included. Red with
  Manage reading every file as List(All) did ("read 2 of them").
- TestManageCountsAGatewaySessionTheAgentKeepsOnce: a gateway session
  whose Claude Code file has nothing said in it is counted once. Red on
  the old handler: "one session listed, counted [{claude 2}]".

Measured on the synthetic sandbox HOME (3000 Claude Code, 1500 Codex,
2000 Hermes sessions; no gateway sessions), CPU time of the request
(load average ~250 from other sessions, so wall times are noisy), the
parent bbee24810 against this change, the same run of each:
  first manage?agent=claude after a restart  2164 -> 627 ms CPU
                                    (15697 -> 10554 ms wall)
  warm manage?agent=claude   173-222 ms ->  64-88 ms CPU
  warm manage?agent=hermes   176-243 ms ->  56-70 ms CPU
  warm manage?agent=codex    237-269 ms -> 155-162 ms CPU (after its
                             first, which reads Codex's model/effort)

Run: go test ./internal/sessions -count=1, go test ./internal/gui -count=1;
gofmt -l clean; go vet. Full suite and cross-OS vet are recorded on the
last commit of this series.
2026-10-19 03:57:52 +08:00
yetone 2b2d5fd8e4 sessions: a Hermes store's path is resolved once per listing, not per session (#2776)
hermesFiles built each session's id with hermesID(path, sid), which
resolves the store's path (filepath.Abs and EvalSymlinks, a stat per
folder) and hashes it, for every session of the store, on every listing.
Every Sessions endpoint enumerates every agent, so this ran on each poll.
hermesStoreID now resolves and hashes once per store; each session's id
is that prefix and its own id, the same string as before.

Test: TestHermesStoreResolvedOncePerListing counts resolves for a store
of 10 sessions (red on the old code: 12 resolves for 10 sessions) and
checks a file's key still equals hermesID's.

Measured on the synthetic sandbox HOME (2000 Hermes sessions beside 3000
Claude Code and 1500 Codex), warm index: a CPU profile of 9 warm
requests (manage?agent=claude, manage?agent=codex, /api/sessions, three
times; 33 enumerations) put 0.96 s CPU in hermesID, ~30 ms per
enumeration of 2000 sessions. After, that is one resolve per store.

Run: go test ./internal/sessions -run TestHermes -count=1 (ok); gofmt -l
clean. Full suite and cross-OS vet are recorded on the last commit of
this series.
2026-10-19 03:57:52 +08:00
yetone 9893ae8216 sessions: a write to one Hermes session parses only that session again (#2776)
Hermes keeps every session in one state.db, and a session's parse was
reused only while the whole store's revision (state.db and its WAL, size
and mtime) stood. Any write moved it, so every Hermes session's messages
were read, de-duplicated and decoded again: on each Sessions poll while
Hermes ran, and on the first read after a restart if Hermes had run
meanwhile (the reporter's 25-40s Sessions page).

The store's revision still decides whether anything is read. When it
moved, one read transaction now takes a fingerprint of each session
(hermesPrintsFor, fingerprints): its sessions row as metadata() reads it,
and over its messages and usage rows a count, the ids, and sums of every
column parseHermes reads, values or byte lengths (active and compacted,
which a rewind or compaction flips in place, and octet_length of content,
tool calls and display metadata, which Hermes fills in later). They are
kept per store revision. Only sessions whose fingerprint moved are parsed
again. A fingerprint that can't be read is "" and reuses nothing, as
before. A rewrite of a message to text of the very same byte length with
no other column moving is the one change it can miss; said in the code.

Tests: TestHermesWriteParsesOnlyItsSession (one message inserted: 1
session parsed again, 4 on the old check; a message rewritten in place is
read), TestHermesUnreadFingerprintsParseAgain (an unknown fingerprint
reuses nothing; red with the f.rev == "" guard taken out).

Measured on a synthetic sandbox HOME (2000 Hermes sessions, 132k
messages, 465 MB state.db, beside 3000 Claude Code and 1500 Codex
sessions), one message inserted into Hermes before each request, warm
index, load average ~250 from other sessions on the machine (CPU time is
the stable number):
  /api/sessions/manage?agent=claude  before 2190 ms CPU (11962 ms wall)
                                     after   617 ms CPU ( 4669 ms wall)
  /api/sessions/manage?agent=hermes  before 2400 ms CPU (14630 ms wall)
                                     after   618 ms CPU ( 6239 ms wall)
  /api/sessions                      before 2102 ms CPU (10229 ms wall)
                                     after   357 ms CPU ( 3136 ms wall)
The fingerprint pass itself over that store: ~0.3 s CPU in sqlite3.

Run: go test ./internal/sessions -count=1 (ok, 241s); gofmt -l clean;
go vet ./internal/sessions. Full suite and cross-OS vet are recorded on
the last commit of this series.
2026-10-19 03:57:52 +08:00
yetone a595f1559c provider: a request to a routing group builds the groups' entries once, not once per look at every member of every group (colmugx, Yayoi_no_yume on X)
colmugx found magpie hotter with groups, and worse since ~v0.1.1225.
Yayoi_no_yume saw CPU jump to 100% as soon as a request entered a group,
and stay there under concurrency.

Cause: one request to a group asked for the groups' entries
(groupEntries) five or six times: Catalog from Resolve and IsDecider,
and Served from membersImageInput, outputLimit, windowIn and roomy. A
direct provider/model request asked through Resolve too. Nothing held
that work. Each build:
- went through every member of every group, the found auto-<model> ones
  included, with a linear pass over the whole catalog per member. It
  copied each large Entry it passed (groupEntries, resolveIn);
- since 8f4d091c6 (#2224) ran smallestWindow for every group, not only
  one set to ContextSmallest. That was a second full pass per member,
  which is the regression after v0.1.1225;
- parsed settings.json again for each group's disabled models
  (membersIn -> disabledList -> settings.LoadChecked).

Fix:
- groupEntries is held while a request holds the catalog. heldFrom keys
  it to the catalog slice it was built from, so it is rebuilt for a
  rebuilt catalog. Catalog and Served hand out a copy.
- Each member's entry is looked up in a map built once per build.
- smallestWindow runs only for ContextSmallest.
- resolveIn walks by index, not by copying each Entry.
- disabledList is held like heldSettings. SetDisabledModels calls
  Changed, so a change is seen at once.

Guards (each fails without its fix, broken by hand):
- TestGroupEntriesBuiltOnceWhileHeld: the same build under one Hold.
  Also checks that a caller's change to Catalog doesn't reach the next
  caller, that another catalog is built from, and that a save is seen.
- TestGroupLooksParseNoSettingsPerGroupWhileHeld: settings parses per
  look.
- BenchmarkGroupEntries (provider) and BenchmarkGroupOverhead /
  BenchmarkGroupOverheadParallel (gateway). These use fake upstreams:
  direct vs groups of 1, 4 and 8 members, one with a failing first
  member and one with a resting first member, at 200KB and 2MB, streamed
  and not, on a 12x20 and a 30x60 catalog.

Numbers. cpu-ms/op is process CPU per request. The machine was at load
~200-430, so wall times are not comparable.
- Catalog of 30 providers x 60 shared models, 200KB, non-stream,
  BenchmarkGroupOverhead, 5x:

  | Version              | direct p0/m1 | groups (g1 g4 g8u gfail grest) |
  |----------------------|--------------|--------------------------------|
  | v0.1.1225 (54ba9042d) | 242          | 976 / 1006 / 965 / 966 / 945   |
  | HEAD ccb2eea15       | 571          | 1462 / 1745 / 1719 / 1758 / 1715 |
  | this commit          | 76           | 93 / 116 / 91 / 114 / 106      |

  Parallel, HEAD -> this commit: direct 563 -> 73, groups 1355-1625 ->
  94-152. The cost of entering a group, over direct: ~+1150 ms at HEAD,
  ~+15-40 ms now. Memory per group request: 200MB -> 74-79MB. Allocs:
  442k -> 128-141k.
- BenchmarkGroupEntries, one build of the 30x60 catalog's groups, CPU:
  HEAD 233 ms; HEAD with smallestWindow gated only 151 ms; this commit
  20 ms.
- 12x20 catalog, 200KB, HEAD (before): direct 45.5, groups 83-89
  cpu-ms/op. v0.1.1225: direct 37, groups 85-97. So with a small catalog
  the overhead is old, not new. It grows with providers x models x
  groups, which is why colmugx's and Yayoi_no_yume's catalogs feel it.

Run at this head:
- go test ./... -timeout 45m at load ~430: 60 packages ok, including
  internal/provider. internal/agent, internal/gateway and
  internal/library hit the 45m timeout under that load. These were not
  failures. internal/gui failed two tests:
  - TestSetAnswersWhileDevinAndProvidersHang ("set slow/slow-1 took
    11.9s", over its 10s wall bound) failed in the run and once more
    alone (16.25s). It passed on the ccb2eea15 checkout (9.95s) and
    2 of 2 with -count=2 at this commit. It is a wall-clock bound under
    load, and this commit doesn't touch its path.
  - TestMainWindowCorners was killed while measuring and passed rerun.
- go test ./internal/gateway -run
  'Group|Member|Rout|Fallback|Rest|Window|Image' -count=1: ok (221s)
- TestGroupLooksParseNoSettingsPerGroupWhileHeld with disabledList not
  held: red, "settings.json parsed 50 times in 50 looks"
- gofmt -l internal: clean
- GOOS=linux go vet -tags nogui ./...: clean
- GOOS=windows go vet ./...: clean
2026-10-19 03:19:13 +08:00
yetone 938c31424e gateway: a long request body is checked for valid JSON once, not by every decodeJSON
decodeJSON runs jsonValid over its whole input before filling the value,
and a request's body goes through it a dozen times on its way: modelOf,
parseAnthropicRequest, swapImageBlocks, blocksOf, the prompt builder,
conversationID, requestEffort, bodyEffort, streamOf, walkImages... On a
2 MB Anthropic request the repeated checks were ~18% of the CPU of
serving it (pprof).

jsonValid now remembers the last 8 bodies of 32 KB or more that it found
valid, by length and a maphash under a seed of the process's own. Only
valid results are kept, so an invalid body is checked (and refused) every
time. A false hit needs a 64-bit collision under a seed no caller can
see; even then fillJSON still parses the body.

Guard: TestDecodeJSONChecksALongBodyOnce counts the byte-by-byte checks
of one 84 KB body over six decodes. With the lookup turned off by hand:
"a 84087-byte body was checked 6 times over six decodes, want 1".
TestDecodeJSONMemoKeepsRefusing: a body changed by one byte at the same
length, and a truncated one, are still refused after the valid one was
remembered.

Numbers (BenchmarkZZHot, a fake upstream with no network, 2 MB request,
count 3, CPU from rusage since the box sits at load ~350):
  big-nostream     before 113.4 / 140.1 / 117.1 cpu-ms/op
                   after  107.6 /  98.7 /  99.2 cpu-ms/op
  big-stream-pass  before 134.6 / 151.0 / 161.6 cpu-ms/op
                   after  124.1 / 131.0 / 144.5 cpu-ms/op
B/op and allocs/op are unchanged (65.9 MB, 181k; 81.9 MB, 310k), as
expected: the check allocates nothing.

Run (on ccb2eea15 with this commit and the previous one, the collector
fix, both in the tree, sandbox HOME, load ~350):
- go test -tags nogui ./... -timeout 45m -count=1: 62 packages ok,
  internal/gateway ok (2694s). Two reds, both in untouched packages and
  both filed:
  - internal/gui TestSetAnswersWhileDevinAndProvidersHang: set slow/slow-1
    took 10.67s against its 10s bound (#1375). Rerun alone with -count=3,
    it passed at 4.7s, 2.8s and 7.1s.
  - internal/agent ran past 45m, with TestWSLMoreAgentsPick running at the
    deadline (#2544).
- gofmt -l internal/: clean.
- go vet ./internal/gateway passed.
- GOOS=linux and GOOS=windows go vet -tags nogui ./... passed.
- go build passed.
- The memo guard is red with the lookup turned off by hand (above).
2026-10-19 03:11:12 +08:00
yetone 24f89cdb14 gateway: a streamed reply's text is gathered in a builder, not copied whole on every delta
The collector that every encoder embeds (and conversations, hooks,
relay status, search, the Claude subscription path) added each text or
thinking delta to its part with `p.Text += ev.Text`, copying the whole
reply so far on every delta. Quadratic in the reply: a 4000-delta reply
copied ~57 KB per delta. It shows most on a translated stream (a Chat
upstream served to an Anthropic client), where every chunk is one delta.

Now the last part's text grows in a strings.Builder, written into the
part when another part is touched or at finish().

Guard: TestCollectorTextLinear fails when collecting a reply allocates
more than 16x its size. Before the fix: "collecting a 116014-byte reply
allocated 247395704 bytes (2132x)". TestCollectorKeepsEveryDelta checks
that every part's text, the signature and the tool args are kept whole.

Numbers (a fake upstream, no network, 4000 events, chat -> anthropic
stream, CPU from rusage since the box sits at load ~350):
  before: 166.9 cpu-ms/op, 231 MB/op, 391k allocs/op
  after:   95.4 cpu-ms/op, 31.3 MB/op, 387k allocs/op
BenchmarkCollectorText (4000 deltas): 667 KB/op, 8048 allocs/op after.
Passthrough cases were unchanged (small-stream-pass 42 ms, chat pass 94 ms).

Run (on ccb2eea15 with this commit and the next one, jsonValid's memo,
both in the tree, sandbox HOME, load ~350):
- go test -tags nogui ./... -timeout 45m -count=1: 62 packages ok,
  internal/gateway ok (2694s). Two reds, both in untouched packages and
  both filed:
  - internal/gui TestSetAnswersWhileDevinAndProvidersHang: set slow/slow-1
    took 10.67s against its 10s bound (#1375). Rerun alone with -count=3,
    it passed at 4.7s, 2.8s and 7.1s.
  - internal/agent ran past 45m, with TestWSLMoreAgentsPick running at the
    deadline (#2544).
- gofmt -l internal/: clean.
- go vet ./internal/gateway passed.
- GOOS=linux and GOOS=windows go vet -tags nogui ./... passed.
- go build passed.
- TestCollector* pass, and TestCollectorTextLinear is red on the old ir.go.
2026-10-19 03:11:11 +08:00
yetone db61143fe7 usage: the Sessions and Routing caches copy out the strings they keep, so they no longer pin every decoded block
An unpacked block's strings are cut from one allocation (unpackInto). The
gateway-sessions projection (gatewayCache) and the vias cache kept a
session id, model, agent, provider or effort from nearly every block, and
each such substring held the block's whole decoded text: request and
response ids and errors included. keptStrings clones each kept value once
and interns it, so a cache holds only what it uses.

TestSessionCachesHoldNoDecodedBlocks writes 16 blocks x 512 rows with a
1 KB error each, reads GatewaySessions and Vias, drops the snapshot and
compares the live heap with and without the caches. Without the fix
(both call sites reverted) it is red: "the caches hold 16651 KB for 16
sessions: the decoded text of their blocks (8192 KB)". With it, green
-count=3.

Measured (macOS, sandbox HOME seeded with 600k gateway calls, the fixed
build vs ccb2eea15, the same Usage/Sessions/Routing views opened by
Playwright, after GC via /v1/magpie/heap; footprint from `footprint`):
- after the views: live heap 618 MB -> 466 MB, footprint 801 -> 670 MB
- after warm-up only: live heap 467 -> 390 MB
- CPU over the same 9m40s: ~22.4 s both
Go is the process that holds memory: on a live v0.1.1208 app the Go
process's footprint was 1045 MB, the Bun plugin host 51 MB, the two
WebKit WebContent processes 70 and 83 MB.

No single commit in v0.1.1225..HEAD is the cause: the shared-slab decode
(99fcddeeb) and both caches (c9b826337, 60f896031) predate v0.1.1225.
Idle with no page open, HEAD used 1.04 s CPU per 5 min against
v0.1.1225's 0.56 s.

Not fixed here: the gateway projection is kept once per window (up to
4), the startup heap peaks ~1.5 GB from GOGC doubling the warm-up's live
heap, and a synthetic 11k-session history did not reproduce the 1 GB
reported.

Run at this change on ccb2eea15 (load average ~275-500 from other
sessions):
- go test ./... -timeout 45m, sandbox HOME: 61 packages ok;
  internal/agent timed out at 45m; 4 reds in gateway
  (TestClaudeAccountsSpentFallBackToCodex,
  TestCodexServedNamesTheAccountThatSigned) and gui
  (TestPluginPageReadsWhatItDeclared,
  TestSetAnswersWhileDevinAndProvidersHang).
- Those 4 alone: gateway ok 40.8s, gui ok 13.7s.
- internal/agent alone (-timeout 45m): timed out again at 2732s under
  load ~500; the stacks left include a netproxy.Bridge accept loop.
  internal/agent never calls GatewaySessions or Vias, the only code
  changed. Not filed from here: the run kept only its last 25 lines,
  so the test that hung is not named.
- internal/usage: ok 123s.
- gofmt -l: clean. go vet ./internal/usage/ for darwin, linux
  (nogui) and windows: clean.
2026-10-19 03:01:38 +08:00
yetone cc8e8e3bda provider: moved Grok users get plugin 0.1.16, which keeps a sign-in with no email (llllleo9 on X)
llllleo9 couldn't add Grok: grok login --device-auth exited 0, and the
sign-in failed with "grok login finished without an account".

Grok Build 1.0.62 was run in a sandbox against a stand-in auth.x.ai. When
the id_token has no email claim (an account signed in through X), the CLI
writes "email": null, and plugin 0.1.15 refused a sign-in made beside an
already signed-in Grok Build. With GROK_AUTH_PATH set, the CLI kept the
sign-in elsewhere.

Plugin 0.1.16 (magpie-community/plugins 8cdf2d2) fixes both:
- the account is told by its email, else its xAI user id, else the
  token's sub;
- GROK_AUTH_PATH is left out of the login;
- a login that leaves nothing says which file it read and what was there.

npm view @magpie-community/opencode-grok-auth@0.1.16 --prefer-online
shows 0.1.16, which is latest, and its integrity matches the publish
run's. This commit raises the mover's min to 0.1.16, so keepMovedCurrent
updates moved users. The built-in's own Grok sign-in (runCLISignIn) has
no caller left, so the built-in is unchanged.

Run at this change, on origin/main ccb2eea15 plus this diff, macOS:
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... and go build: clean.
- go test ./... -timeout 45m: internal/provider ok (1205s),
  internal/plugin ok (1244s), and 60 packages ok.
- Four packages were red with the machine at load average 195-235, while
  six other sessions ran benchmarks:
  - internal/agent timed out at 45m in TestCodexAgentsV1WarnsWhenCodexOwnV2IsOn;
  - internal/gateway timed out at 45m in TestPluginStreamLargeReplies
    (#2551);
  - internal/library timed out at 45m in TestSkillHow;
  - internal/gui failed TestSetAnswersWhileDevinAndProvidersHang
    (15.7s, #1375).
  None of the four reads the mover's min.
- A rerun of those four, at load average 420, had not finished a
  package after 30 minutes. It isn't a record of green.
- go test -count=1 -run 'Moved|Mover|Grok' ./internal/provider: ok.

Not tried with a real xAI account: whether xAI's token for llllleo9's
account lacks the email claim, and whether their Grok Build was already
signed in.
2026-10-19 02:43:48 +08:00