Commit Graph
4068 Commits
Author SHA1 Message Date
yetone 85e4c693ee sessions: a packed rollout's long line is gathered once, at its own size
scanAt reads a line longer than its 1 MiB read buffer as several chunks.
For a plain file, a7e2c7235 (#2515) reads ahead to the end of the line and
gathers it into one buffer of exactly that size. A packed (.zst) rollout
can't read ahead, so it still grew the line by append, a chunk at a time.
That allocated about 3.8 times the line. A cold read of 120 of the owner's
real packed rollouts allocated 2.2 GB, and 1.61 GB of it was this append.

Lines the head says no to were already stepped over without being
gathered. On this corpus the gathered long lines were all wanted ones.
There were 63 user messages with pasted images on the session side
(422 MB), which codexHead lets through for Prompts and Title. There were
17 compactions (70 MB). There were also 14 plain-file messages (19 MB),
which were already sized exactly. These lines are read whole:
cxFastPrompt looks through every content part, and cxCompactionIn uses
gjson to find fields anywhere in the line. So the line still has to be
handed over whole, and this change is about how it is gathered.

- A packed file's long line is copied into pooled 1 MiB blocks until its
  end. Then it is gathered once, into a buffer of its own length.
- That buffer comes from a pool (longLines) and goes back to it when the
  scan ends. A line from it is good only until then, which is the same
  rule as for the read buffer. Under the tests (poisonReleased) the
  buffer is filled with 0xFF when it is given back.
- The plain-file read-ahead path is unchanged, apart from taking its
  buffer from the same pool.

Measured on copies in a sandbox: 120 real .jsonl.zst rollouts (1.30 GB
packed, 1.95 GB unpacked; the 60 largest and 60 recent), 30 plain Codex
.jsonl (213 MB) and 40 Claude Code project .jsonl (60 MB). CODEX_HOME and
CLAUDE_CONFIG_DIR pointed at the copies, with a fresh testenv home each
run. Each run was List(100000), StatsAt(3650, fixed now), ReadCallSource
for each of the 190 CallSources, and Calls(time.Time{}), in its own
process. Three runs each, at load average ~30-40:

                    TotalAlloc         wall
  base 9afdeb89c    2161/2198/2203 MB  3.12/2.39/2.52 s
  this commit        668/ 678/ 724 MB  2.54/2.32/2.22 s

All 4 JSON encodings (List, StatsAt, every source's calls, and Calls)
are byte-identical to the base's, checked with cmp on all 3 runs of
each binary. After the change, pprof puts scanAt's own allocation at
~134 MB for long-line buffers and ~96 MB for blocks that the pool
dropped at a GC, down from 1.79 GB.

Tests (internal/sessions/scan_buffer_test.go):
- TestScanGathersAPackedLongLineOnce: a .jsonl.zst with a wanted 20 MiB
  line, a 20 MiB line the head says no to, and two short lines. The
  wanted line is handed over byte for byte. The scan allocates at most
  2.5 times the line plus 16 MiB for the decoder's window. It passed
  -count=20. With the base scanAt put back by hand it is red 3 of 3:
  "allocated 106639008/117266584/106633368 bytes, want at most
  69206078".
- TestBlocksKeepALineInOrder: blocks give back across a block's end
  what they were given.

Run in a sandbox HOME, Go caches pinned, set -o pipefail:
- gofmt -l internal cmd: none.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet -tags
  nogui ./...: both exit 0.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/usage/
  ./internal/gui/: ok (23.8s, 21.1s, 105.7s).
- go test -count=1 -race ./internal/sessions/: ok (52.9s).
- Not run: the full suite, the GUI Playwright suite (no asset changed),
  the Windows box, a live magpie's RSS.

Siblings not changed here:
- traces.go's TraceReader reads plain rollouts with ReadBytes. That read
  is bounded by its 8 MiB poll budget.
- frames.go's dsh frames append a line split across frames.
- plugin/host.go's readLine is plugin IPC, not session files.
2026-10-21 00:07:49 +08:00
yetone 9afdeb89cd sessions: TestManageReadsOnlyTheAgentsItShows counts parses without a data race
Its parseHook did parsed++ while refresh's readers called it from several
goroutines at once, so `go test -race ./internal/sessions/` was red on
origin/main a9304efe0 (3 of 3 runs: "race detected during execution of
test", manage_read_test.go:30 written by two refresh workers). The count is
an atomic.Int64 now. Its sibling in hermes_fingerprint_test.go refreshes one
file, so one reader, and is left as it is.

Run: go test -race -count=20 -run TestManageReadsOnlyTheAgentsItShows
./internal/sessions/ ok; go test -race ./internal/sessions/ ok (44.5s), in
a sandbox HOME with Go's caches pinned.
2026-10-20 23:50:02 +08:00
yetone 5466cc7604 sessions: a packed Codex rollout whose stamp changed is decompressed once at start, for both Sessions and Requests
The start's warm-up (gui warmSessions) parses every changed session file
for the Sessions page (statsFor -> refresh -> parse), then reads every
changed file's calls for Requests (usage.QueryPage -> prefetchSources ->
ReadCallSource -> readCalls). A packed rollout (.jsonl.zst) is decompressed
whole for each read, so when the Codex app repacked all 11,591 of them on
10-20 every one was decompressed and scanned twice (~48 GB of zstd read
twice; 75 GB of zstd allocation in 67 min, 37.8 GB on each path through
scanAt).

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

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

Verified (sandbox HOME, Go caches pinned):
- TestPackedRolloutReadOnceForSessionsAndCalls (new): 3 packed rollouts
  (the two fixtures + a 40-call one). Calls-then-sessions scans each twice
  (the reference); sessions-then-calls with nothing kept, and again after
  every file's mtime changes, scans each once, and the calls, List and
  StatsAt are reflect.DeepEqual to the reference. With callsAlong replaced
  by nil in refresh it fails: "first read: ...zst scanned 2 times, want
  once" for all 3 files, and the same after repacking (6 errors). Restored:
  ok. -race -count=20: ok.
- Real rollouts: copies of 120 and of 180 of ~/.codex/sessions' packed
  rollouts (528 MB / 739 MB compressed), warm-up order (List, StatsAt, then
  ReadCallSource with 8 readers), with nothing kept ("cold") and after every
  mtime changed ("stamp"); old = callsAlong nil:
    120 files, full speed:  zst scans 240 -> 120; wall cold 0.84/0.90s ->
      0.52/0.48s, stamp 0.99/0.70s -> 0.43/0.52s; alloc 0.45-0.48 GB ->
      0.43-0.44 GB cold, 0.38-0.41 GB -> 0.38-0.39 GB stamp.
    180 files, inside sessions.Warm (3 readers of 14 cores): zst scans
      360 -> 180; wall cold 1.97/2.18s -> 1.48/1.59s, stamp 1.89/2.22s ->
      1.35/1.63s; alloc 0.57-0.63 GB both ways.
  Lists, stats and every source's calls, JSON-encoded, are byte-identical
  old vs new in all four phases (cmp).
  Allocation hardly moves: in a pprof of the 120-file run, 482 MB of ~800
  MB is scanAt gathering lines longer than its 1 MiB buffer (the packed
  rollouts' multi-MB session_meta lines), which only one of the two
  readers ever gathered, and zstd's own history buffers are 120-144 MB.
  What the change saves is the second decompression: CPU and disk reads.
- gofmt -l on the changed files: nothing. GOOS=linux go vet -tags nogui
  ./... ok; GOOS=windows go vet -tags nogui ./... ok.
- go test -timeout 45m ./internal/sessions/ ./internal/usage/
  ./internal/gui/: ok 13.8s / 17.1s / 81.7s. go test -race
  ./internal/sessions/: ok 44.5s after the next commit's test fix (red on
  origin/main a9304efe0 without it, TestManageReadsOnlyTheAgentsItShows).
Not run: the full ./... suite, the GUI Playwright suite (no GUI change),
a live magpie start against all 11,591 rollouts, Windows/Linux runs.
2026-10-20 23:50:02 +08:00
yetone a9304efe01 gateway: an image's decode is counted wherever its header sits
3eee19b08 batches a request's images by what each holds once decoded,
read from its header. fitHolds read only the first 4 KB of base64 for
the header, so a JPEG whose frame header sits behind a large EXIF
segment (a phone photo's often does, up to 64 KB) counted as holding
nothing, and was made beside three others each holding up to
codexImageMaxBytes. fitHolds now reads the header from the base64 as a
stream, as far as the format needs, and counts the bytes the image came
in too, as codexImageRefit does.

Run:
- go test -run TestCodex -count=1 ./internal/gateway/: ok.
- TestCodexAHeaderBehindExifIsCounted on 3eee19b08's codex_images.go:
  red, "a JPEG with its header behind 63 KB of EXIF holds 0 MB, want
  29 MB"; green with this change.
2026-10-20 23:14:02 +08:00
yetone 21c2ab6fa5 sessions: packed session files are decompressed by decoders kept between reads
Why: a live heap profile of v0.1.1296 (pid 554, up 67 min) allocated
173 GB, 75 GB of it in zstd decoding, through sessions.scanAt from both
usage.prefetchSources (ReadCallSource → readCalls) and sessions.refresh
(parse). openLines made a new zstd decoder for every packed file it
opened, and a decoder's first frame allocates its window: the Codex app
packs rollouts with a 2 MiB window, which a low-memory decoder holds in
3 MiB, plus ~350 KB of block buffers. scanFrames (dsh .zstd) did the same
on every read on.

What was found, on 180 real packed rollouts (360 MB, copied with their
times) and the profile:
- An unchanged packed file (same size and time) is not opened again by
  either path, while magpie runs or after it starts from what it saved
  (Saved, Reset): 180 scans each path cold, 0 on every later round. A
  changed one is read again alone.
- The 75 GB was each path's one full pass over all 11,591 packed rollouts
  at the app's start, both caches invalid for them then: about 3.4 MB a
  file for each path's decoder, and its 1 MiB copy buffer to pass over
  what came before off.
- dsh files are already read on from their last whole frame
  (TestDshPackedReadsOnlyWhatWasAppended, TestDshCallsReadOnlyWhatWasAppended).

What changed:
- openLines takes a decoder from a pool (streams) and Resets it onto the
  file; zstdFile's Close Resets it to nil and puts it back. Read or Close
  after Close is os.ErrClosed. IOReadCloser isn't used, since its Close
  closes the decoder for good.
- scanFrames decodes frames with a pooled decoder of its own pool
  (frameDecoders): a decoder that has read a stream holds its block
  decoder, which DecodeAll would wait for. Its reader comes from
  lineReader's pooled buffers, not a new bufio.Reader.
- scanAt passes over what comes before off in a packed file through its
  pooled line reader (Discard), not io.CopyN's buffer of its own.
- Decoder options and window limits are unchanged, so what is read is
  the same; an idle pooled decoder is let go by the garbage collector
  with the pool, and as many are held at once as files are read at once,
  as before.

Numbers:
- go test -bench 'PackedScan|DshFrames' -benchtime 40x, before → after:
  - an 8 MB Codex rollout, 2 MiB window, scanAt from 0: 3,364,175 →
    110,902 B/op, 25 → 6 allocs/op;
  - a 6 MB dsh session of 8-line frames, scanFrames whole: 1,959,606 →
    491,117 B/op, 63 → 22 allocs/op;
  - the same, read on from its last frame: 182,087 → 74,361 B/op, 34 → 9
    allocs/op.
- TestPackedScanKeepsItsDecoder (a warmed scan): 3,330,508 → 452 bytes.
- The 180 real rollouts, read cold by List, CallSources and
  ReadCallSource: 1,294 and 1,299 MB → 375 and 386 MB allocated (two
  runs each). The sessions and calls read (177 sessions, 306 calls) are
  byte for byte the same JSON before and after.

Tests (packed_decoder_test.go):
- TestPackedScanKeepsItsDecoder and TestDshFramesKeepTheirDecoder fail on
  the old code (3,330,508 and 181,995 bytes) and with either Put taken
  out by hand (3,330,344 and 165,539 bytes). Skipped under -race, where
  sync.Pool drops what it is given.
- TestPackedScanSameThroughAKeptDecoder: lines and places through kept
  decoders are what a decoder of its own reads, for a large file after a
  small one cut short, read on from a line, past the end, and by 8
  readers at once.
- TestUnchangedPackedNotReadAgain passes on the old code too (it held
  already). It fails when refresh's or readCalls's size-and-time check is
  broken by hand for packed files.

Run, at this commit's tree:
- go test -timeout 45m -count=1 ./internal/sessions/ ./internal/usage/:
  ok (79s, 39s).
- go test -race -count=3 -run 'TestUnchangedPacked|TestPackedScan|
  TestDshFrames|TestCodexPacked|TestDsh.*Packed|TestDsh.*Append|Frame'
  ./internal/sessions/: ok.
- gofmt -l internal/sessions: nothing. GOOS=linux go vet -tags nogui
  ./... and GOOS=windows go vet -tags nogui ./...: exit 0.
- go test -tags nogui -timeout 45m -count=1 ./... under a scratch HOME,
  GOPATH, GOMODCACHE and GOCACHE pinned: exit 0, every package ok (65,
  no FAIL); gateway 802s, agent 733s, provider 355s, sessions 273s,
  usage 92s.
Not tried: in the running app; on real dsh files (none on this machine,
so the profile's zstd was all Codex .zst). Why both caches were invalid
for the packed rollouts at that start is not found here.
2026-10-20 23:11:32 +08:00
zzjcool 3eee19b08b gateway: a codex image's header can't make its decode hold what it declares
A Codex turn's inline image is decoded, resized and written again before
it goes to ChatGPT (codexImagesFit). What a decode may hold was judged in
pixels: codexImageMaxPixels, 80<<20. A pixel is not a byte, and a
compressed image declares its size before it carries any pixels, so a
header of a few dozen bytes commanded the allocation: 110 bytes declaring
8000x8000 at 16 bits a channel held 488 MB, and four of them in one
request held 1710 MB (fitWorkers makes 4 at once, with no budget for what
they hold between them). The decode then fails and the image goes as it
came, so the bytes were spent for nothing. With a few agents sending such
a turn at once the process is one the system kills.

The bytes a decode will hold are now what is judged, from the header
alone, before anything is decoded (imageHolds: the pixel count times the
bytes its format's image allocates a pixel — 4 for anything with colour or
alpha, 1, 2 or 8 as image/png's readImagePass allocates them, in int64 so
that 70000x70000 can't wrap). codexImageMaxBytes keeps that at 320 MB,
which is what 80<<20 pixels was taken as, so every screenshot Codex sends
is fitted as before: 3456x2234 holds 29 MB, 4032x3024 46 MB, 6000x4000
91 MB. What one request makes at once is batched against fitBudget
(512 MB), so a request of 100 screenshots holds what 4 do and not what 100
do.

Verified at this head, with `-tags nogui`:

- New tests fail without the change. With codexImageRefit's two gates and
  the batching put back to the old behaviour (helpers kept, so nothing
  fails to compile):
  TestCodexAHeaderAloneCantHoldPastTheBudget — "8000x8000 at 16 bits a
  channel: 110 bytes of upload held 488 MB, past the 320 MB a decode may
  hold"; TestCodexFourHeadersInOneRequestCantHoldTheHeap — "1299 bytes of
  upload, sent as 4 images in one request, held 1710 MB, past 128 MB".
  Both pass with the change.
- The first version of the header test asserted only that the image went
  as it came, and it passed on the old code, because the old decode also
  failed — after spending the bytes. The tests measure what the decode
  allocates (runtime.MemStats TotalAlloc either side) instead.
- TestCodexFittingHoldsTheBudget covers the batching's edges, including an
  image that holds more than the budget by itself (made alone, turned away
  by codexImageRefit).
- TestCodexRealScreenshotsFitBytesTheyHold and
  TestCodexFittingLeavesATurnThatFitsAsItWas: a real screenshot is neither
  turned away nor made differently.
- go test -race -tags nogui -run TestCodex ./internal/gateway: pass
  (228s). go test -tags nogui -run TestCodex ./internal/gateway: pass.
- gofmt clean; go vet -tags nogui ./internal/gateway, GOOS=linux go vet
  -tags nogui, GOOS=windows go vet: clean. go build -tags nogui,
  GOOS=windows go build: pass.
- Full go test -tags nogui ./...: fails in internal/agent (aside, cursor,
  copilot, qoder, omp, zed), internal/cli (TestKeyNote) and
  internal/gateway (TestClaudeClientCacheAbsentUnchanged). Each was
  reproduced on origin/main dee5c9d7 with this change stashed, so none is
  this change's; they read the PATH for pnpm, cursor-agent and copilot,
  and two runs of the agent package failed different sets.

Found by an AI scan of the image paths, not by a report.

Not changed here: the same judgement is missing on other paths this scan
touched (draw.go's image requests, and holdWriter.wantWhole skipping
holdMost), which want issues of their own.
2026-10-20 23:11:32 +08:00
yetone 0e84db8f5f provider: Codex's list's tag is built again only when what it is built from changes
Why: a live heap profile of the app (v0.1.1296, pid 554, up 1h07m, taken
from /v1/magpie/heap) had 2135 MB allocated under codexListTag. 1966 MB of
it came through gateway.codexModels, where the Codex app asks for its
models (here CodexOwnListTag, a Codex on failover alone); 245 MB came
through agent.SyncCatalog's Codex Sync (a plugin's catalog.Touched and
the window's start among its callers). Each call built the whole catalog
(CodexListed: 93% of it; CodexNativeHidden, Unlisted, the groups), only
to hash it into a 12-character tag.

What changed: codexListTag keeps its answer, per kind ("" and "own"),
while a stamp of what it is built from stays the same:
- held.gen (Changed, a plugin's change, catalog.Touched or Reset);
- filememo.Gen (every write magpie makes);
- the environment (environSum);
- the time and size of magpie's providers, settings and models.dev
  catalog files, and Codex's config.toml (the new-session effort),
  auth.json and models_cache.json, as another process leaves them.
A tag is built afresh at least once a minute (codexListTagFor), for what
the stamp can't see: an account another app signed in to in a keychain,
a model retired by its date. That is the one difference: such a change
reaches the tag up to a minute later than before. A tag built while any
stamped file is under 2 seconds old isn't kept, since two writes of one
size within a coarse clock's tick leave the same stamp. The old builder
is buildCodexListTag, unchanged.

Numbers (TestCodexListTagKeptWhileNothingChanged, 8 providers of 40
models and a ChatGPT sign-in; CodexListTag plus CodexOwnListTag, average
of 50 calls):
- before: 159608 allocs, 42.9 MB a call; held (provider.Hold) 3492
  allocs, 7.0 MB
- after: 52 allocs, 10.7 KB a call, held or not

Run, at this commit's tree:
- go test ./internal/provider -run TestCodexListTag -count=1 -v: 4 pass.
- The same with codexListTag returning buildCodexListTag at once (the
  old code): TestCodexListTagKeptWhileNothingChanged FAILs with the
  numbers above.
- Broken by hand, one at a time, each fails TestCodexListTagFollowsChanges
  or another: no providers file stamp ("the providers' file written by
  another magpie: the tag stayed"), no config.toml stamp ("Codex's
  effort set in Codex: the tag stayed"), no filememo gen ("a list
  written, filememo told"), no held gen ("a list written, what is held
  dropped"), no minute bound (TestCodexListTagBuiltAgainAfterItsTime),
  no settled check (TestCodexListTagNotKeptOverAFreshFile).
- go test -race ./internal/provider -run TestCodexListTag -count=3: ok.
- go test -tags nogui -timeout 45m ./... under a scratch HOME with
  GOPATH, GOMODCACHE and GOCACHE pinned: every package ok (65), exit 0;
  provider 287s, gateway 693s, agent 655s, gui 220s.
- gofmt -l internal/provider: nothing. GOOS=linux go vet -tags nogui
  ./... and GOOS=windows go vet -tags nogui ./...: exit 0. go vet
  ./internal/provider: exit 0.
Not run: the GUI suite (no GUI file changed); the auth.json and
models_cache.json stamps have no test that fails without them; not
tried in the running app.
2026-10-20 22:17:55 +08:00
yetone 318697dcea gateway: GET / counts the catalog once a change, not on every ask
Why: in the live heap profile (yg6888 on X, ~1 GB held), 5.4 GB of a
day's 36 GB of allocations came from info. It built the whole
provider.Catalog() only to report "models": len(...). Every magpie on
this computer asks the gateway which magpie it is (gateway.ServedBy):
- a window that doesn't serve, every 15s (watchGateway);
- each providersState while it doesn't serve;
- the CLI's daemon and web commands;
- the TUI.
These asks are seconds apart, so the catalog a request holds
(provider.Hold, 1s) had always gone by the next one.

What changed: info's count is kept in the same stamped memo as
AutoVision's lists. It is keyed by provider.StampNow, and built
again after a minute at the latest. The answer keeps its shape.

Measured: BenchmarkScratchInfo (not committed) sends GET / through
s.Handler() in a sandbox HOME with the live models.json and 12 API-key
providers, with 4f044c24c applied on both sides:

| | Time/op | Bytes/op | Allocs/op |
| --- | --- | --- | --- |
| Before | 4,069,096 ns | 1,287,667 B | 219 |
| After | 323,045 ns | 15,919 B | 90 |

Test: TestInfoCountsModelsOnceAChange asks info outside a held
catalog, as a probe 15s later does, with 4 and with 400 models
enabled. It got 64 allocations against 65. With the memo bypassed by
hand it went red at 1275 against 14673. It also checks that the
count follows a provider added through provider.Save.

Run:
- gofmt -l internal/: clean.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- set -o pipefail; go test -count=1 -timeout 45m ./internal/gateway/
  ./internal/provider/ ./internal/catalog/ ./internal/gui/, at load
  ~400 (other sessions' suites), with this and the AutoVision commit
  and 4f044c24c applied:
  - gateway ok 2259.7s, provider ok 821.8s, catalog ok 16.5s.
  - gui FAIL in two tests that fail the same way without these
    changes, each run alone on 28bcd4f7e:
    - TestMainWindowCorners: killed at its 40s deadline (#1936, #2645).
    - TestSetAnswersWhileDevinAndProvidersHang: setting slow/slow-1
      took 10.9s against its 10s bound. Alone it took 4.6 to 5.9s
      without the changes, and passed (#1375).
2026-10-20 20:32:05 +08:00
yetone 243aa709b2 gateway: AutoVision and the searcher's pick keep each provider's ranked models until a list, a provider or a setting changes
Why: a live heap profile of the app (yg6888 on X, ~1 GB held) had
36 GB allocated, and 5.3 GB of it was under seer -> autoVision ->
smallModelWhere. 4.8 GB of that came through agent.magpieModels
(provider.Described, asked for every agent's model list: dsh every 30s,
and the window's state). Each AutoVision did three things for every
provider that was on:
- built its Exposed list twice: once in smallReady, then again only to
  read the picked model's price;
- asked spentModel (perKeyBarred, 1.4 GB) about every candidate model,
  before picking one;
- copied the list three times in pickSmall.
The searcher's pick (searcherReady, Searchers, chosenSearcher) goes
through the same smallReady. For a Remote magpie it asked
p.Available() once per model (remoteSearch).

What changed:
- rankSmall puts the candidates in pickSmall's order once. pickSmall of
  any subset is the first of that subset in this order, and
  TestRankSmallIsPickSmall checks that against the old pickSmall over
  2000 random lists and subsets. smallReadyOf then asks spentModel in
  rank order and stops at the first model with allowance. The model it
  picks, and whether it is ready, are the same as before. Usually only
  one model is asked.
- The candidate carries its cost, so smallModelWhere no longer builds
  Exposed a second time.
- keptSmallCands keeps each provider's ranked candidates in
  stamped[smallKey, []smallCand]. The key is the provider id, the
  signed-in account (agent, user, plan, home) and which filter ("sees",
  "search"). Entries are dropped when provider.StampNow moves, or
  after stampedFor (1 minute).
- provider.StampNow (hold.go, added with dsh's round) is made of:
  - held.gen, which Changed moves: a provider saved, an account,
    catalog.SaveLive/Touched/Reset, a plugin's change;
  - filememo.Gen (settings.Save and every other write this process
    makes);
  - environSum;
  - the time and size of the providers' file, the settings file and the
    catalog's cache file, so a write by another magpie (the CLI) counts
    too.
  The one-minute backstop covers what nothing signals: a list another
  magpie fetched, or another program changing an existing account's
  model list. A new account is a new key, so it is seen at once (within
  provider.Accounts' own 30s).
- Whether a model is out of its allowance (spentModel) is still asked
  on every call, never kept. Two callers building one key at the same
  time each build it. Nothing waits on another, and nothing is built
  under the lock.

Measured on the real path: a sandbox HOME with the live
~/.cache/magpie/models.json (5.8 MB, 231 providers) copied in, 12 API
key providers (openrouter, anthropic, openai, google, deepseek,
nano-gpt, vercel, kilo, requesty, aihubmix, zenmux, poe), and the
catalog.Provider fix 4f044c24c applied to both sides. The benchmark is
go test -bench, -benchtime 2s, not committed. The pick is
requesty/mimo-v2.6-flash before and after.

| Benchmark | Before | After |
| --- | --- | --- |
| AutoVision | 769.7 ms, 22,075,218 B, 73,732 allocs/op | 7.3 ms, 238,201 B, 1,134 allocs/op |
| AutoVision under provider.Hold | 347.8 ms, 21,532,432 B, 69,061 allocs/op | 2.1 ms, 85,207 B, 244 allocs/op |

What is left is mostly provider.All, which reads the accounts.

Tests:
- TestAutoVisionDoesNotBuildListsAgain: AllocsPerRun of AutoVision and
  searcherModel with 4 and with 400 listed models. It allows 50
  allocations of difference: 521 against 527.
  - Broken by hand (stamped.get always builds), it went red at 611
    against 1055.
- TestAutoVisionSeesEachChange checks that each change is picked up:
  - picks changed through provider.Save;
  - a vendor's list re-fetched with new prices (catalog.SaveLive);
  - providers.json rewritten directly, as another magpie would;
  - settings.Save moving the stamp;
  - a Codex sign-in written into the same HOME.
  Broken by hand (the stamp ignored, only the minute kept), it went red
  at "AutoVision = "" after Haiku and Gemini were enabled". Run with the
  other AutoVision tests, TestAutoVisionPassesOverOneOut went red too.
- TestAutoVisionKeptListsAskAllowanceEachTime checks that a used-up
  Codex account is seen on the very next call.

Run:
- gofmt -l internal/: clean.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- set -o pipefail; go test -count=1 -timeout 45m ./internal/gateway/
  ./internal/provider/ ./internal/catalog/ ./internal/gui/, at load
  ~400 (other sessions' suites), with 4f044c24c applied:
  - gateway ok 2259.7s, provider ok 821.8s, catalog ok 16.5s.
  - gui FAIL in two tests that fail the same way without this change.
    Each was run alone, with these files reverted, on 28bcd4f7e:
    - TestMainWindowCorners: the real AppKit window was killed at its
      40s deadline, alone too (#1936, #2645).
    - TestSetAnswersWhileDevinAndProvidersHang: setting slow/slow-1
      took 10.9s against its 10s bound. Alone it took 3.3 to 5.4s with
      this change and 4.6 to 5.9s without it, passing 3 of 3 (#1375).
- The new tests were run again after the split into two commits:
  go test -run 'TestInfoCounts|TestAutoVision|TestRankSmall|Searcher'
  ./internal/gateway/: ok.
2026-10-20 20:32:05 +08:00
yetone 489d816213 agent: dsh's wiring round does nothing when nothing it reads changed
A user's live heap profile showed 35.7 GB allocated in 48 minutes with
~157 MB live. 12.1 GB of that was one path: KeepDshWired -> keepDshWired
-> dshWiredOnce. It runs every 30 s, and each time it rebuilt the whole
catalog and every route, only to write nothing. Within it:
magpieModels("dsh") 9.5 GB, dshRouteAgain 4.8 GB, dshPutRoute 3.8 GB, and
Exposed/Catalog/heldOf/entriesOf ~7.7 GB under them. heldOf caches only
during a Hold.

What changed:
- provider.StampNow (hold.go) records what the catalog is built from,
  without building it:
  - held.gen, which Changed and a plugin's change move
  - filememo.Gen
  - the environment
  - the stat stamps of providers.json, settings.json and the catalog's
    cache file, which another process's writes move
- keepDshWired keeps a dshRounds between rounds.
  - It builds magpieModels again only when the stamp moved, or when its
    models are dshModelsFor (5 min) old. The 5-minute rebuild covers what
    no stamp sees: another app's account file, or a model retired by date.
  - It skips the round when these are all the same as at the last round,
    and that round wrote nothing and left the files as it found them:
    - the bytes of dsh's files: every profile's cordis.patch.yml, the
      home layer, settings.yaml, .env, .credentials.yaml, config.yaml
    - the gateway URL
    - the hash of the models
  - A read error other than "missing" hashes as unknown, so the round
    runs.
- dshWiredOnce (Sync, Connect, tests) still always does a full round.
- No singleflight and no new lock: the round already runs under dshWrites.
- docs/subsystems/agent-wiring.md says so.

Not done: caching Exposed/Catalog/entriesOf outside a Hold. Their output
depends on time (retiredNow, disabledNow) and on files other apps write,
and nothing signals a change in either, so nothing would bound how stale
the cache gets.

Measured with a throwaway test in a sandbox HOME, on top of 4f044c24c:
12 providers from a real models.json, 270 models, 3 dsh profiles.
- Before, per round: 132.61 MB, 900,624 allocations (~265 MB/min).
- After, nothing changed: 0.26 MB, 119 allocations.
- After, models older than dshModelsFor: 30.77 MB, 88,336 allocations.
  The dsh parse and write are skipped because the models' hash is the
  same.
- Averaged over time: ~6.7 MB/min, against ~265 MB/min before.

New tests:
- TestDshRoundWithNothingChangedBuildsNothing: AllocsPerRun must be at
  most 300; it is 77 now.
- TestDshRoundAfterAChangeWritesAgain covers each change:
  - a provider saved
  - a setting saved
  - the patch list written over
  - providers.json written by another magpie
  - a change no stamp sees, picked up after dshModelsFor

Broken by hand, each went red:
- skip always off: the allocation test, at 2099 allocations
- stamp check removed: the provider, setting and another-magpie cases
- roots left out of the stamp: the another-magpie case
- aging removed: the unseen-change case
- file bytes left out of the sum: the patch-list case and
  TestKeepDshWiredWritesTheRouteAgain

Run at this tree. It is built on origin/main dee5c9d75 plus a cherry-pick
of 4f044c24c, which is not part of this commit.
- gofmt -l internal/agent internal/provider: clean.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- darwin go vet ./...: clean.
- set -o pipefail; go test -count=1 -timeout 45m ./internal/agent/...
  ./internal/provider/...: ok agent 2146.7s, ok provider 709.9s.
- An earlier run that also took ./internal/gateway/ and
  ./internal/catalog/:
  - catalog: ok, 6.5s.
  - gateway: hit the 45m timeout (FAIL 2701.3s). Other sessions' GUI
    suites had the machine at a load average of ~548. The output's tail
    was cut off, so which test was running isn't known. Gateway doesn't
    call StampNow or the dsh round. Not rerun at a normal load.
2026-10-20 20:32:05 +08:00
yetone 2bd1dc81d6 sessions: a scan's read buffer is reused from a pool, not allocated per scan
Why: a 48-minute heap profile of the user's magpie allocated 6.3 GB
in sessions.scanAt, while ~157 MB was live. bufio.NewReaderSize made
~3.5 GB of it: each scan made its own buffer, up to 1 MiB (scanBuffer)
for a big file, and threw it away at the end. The earlier commits cut
how often unchanged files are scanned. This one removes the buffer
cost for the scans that still happen: a first read, a grown file, the
calls ledger.

What changed:

- scanAt takes its bufio.Reader from lineReader. lineReader keeps a
  sync.Pool per power-of-two size from 16 KiB to 1 MiB and gives the
  reader back (Reset to nil) when the scan returns.
- A line from the reader was already valid only for the callback that
  got it: long lines are copied into `long`, and callers that keep a
  line copy it.
- Tests run with poisonReleased set in TestMain. A buffer given back
  is overwritten with 0xFF, so a caller that kept a line past its
  scan reads garbage and fails, rather than reading the next scan's
  bytes in a user's magpie.
- sync.Pool drops items at random under -race, so the allocation test
  is skipped there (race_on_test.go / race_off_test.go).

Tests:

- TestScansShareTheirBuffers scans a ~2.4 MB file 50 times and needs
  under 128 KiB allocated per scan.
- TestALineKeptPastItsScanIsGarbageInTests checks the poison.
- Broken by hand: with the pool off (a new reader every time), the
  first test goes red with "a scan of a 2.4 MB file allocated 1049911
  bytes". Green again once restored.
- The whole sessions package passes with the poison on.

Measured on a read-only APFS clone of the user's ~/.claude/projects
and ~/.codex/sessions/2026/10, in a sandbox HOME, at load ~500. Cold
StatsAndNative(0) reads every file once:

| Code | Allocated | Allocations | Time |
| --- | --- | --- | --- |
| origin/main dee5c9d75 | 11,999.5 MB | 24,817,390 | 2m4.7s |
| this series | 5,672.0 MB | 24,431,553 | 1m5.9s |

An earlier run with the pool and the stats change but not the lazy
subagent title: 5,773.3 MB, 24,497,066 allocations. The cold-pass
drop is this commit's.

Run at this tree:

- gofmt -l internal: nothing.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
  - sessions: ok, 366.7s.
  - gui: only TestMainWindowCorners failed, "measuring the windows:
    signal: killed". It also fails alone on an untouched origin/main
    export, at load ~500. Filed as #1936 and #2645. Every other gui
    test passed.
- go test -race -count=3 on the scan, subagent and stats tests: ok,
  207.8s.
2026-10-20 20:32:05 +08:00
yetone 42e6aee534 sessions: the stats and id lookups don't build every session's subagents
Why: in a 48-minute heap profile of the user's magpie,
gui.combinedSessionStats → statsFor → StatsAndNative → statsIn
allocated 3.9 GB, and gui.warmSessions → Warm 5.7 GB. Their scans went
through assemble → subagentsOf → ccTask: the stats built every
session's subagents (each one's task read from its file), only to
count tokens and tell which sessions are listed. Every statsFor call
in the profile came from the warm-up's steps.

What changed:

- assemble is split. assembleListed holds the part that decides
  whether a session is listed and gives its agent, id, title, models
  and usage. assemble adds resume, carry, transcript and subagents on
  top.
- These callers now use assembleListed: the stats' native-key and
  summary loops (stats.go), Titles, the Codex provider lookup
  (codex_provider.go) and manage's id lookup.
- List, One and manage's listing still use assemble.
- The docs/subsystems/gateway-sessions.md subagent section says
  which callers build subagents.

Tests:

- TestStatsReadNoSubagentFile writes a subagent with no meta and no
  task in its first lines, then simulates a restart (Saved, Reset,
  memos cleared). It then runs StatsAndNative(0), StatsAndNative(30)
  and StatsFor(7) three times and expects 0 scans of that file. List
  still shows the subagent.
- Broken by hand: the stats back on assemble make it go red with
  "the stats read an unchanged subagent's file 1 times". Green again
  once restored.

Measured on a read-only APFS clone of the user's ~/.claude/projects
and ~/.codex/sessions/2026/10, in a sandbox HOME, at load ~500 from
other sessions. The whole series against origin/main dee5c9d75; this
commit is the change to the stats rows.

| Pass | origin/main | This series |
| --- | --- | --- |
| warm StatsAndNative(0) | 596.7 MB, 157,195 allocs, 6.2–9.0 s | 28.9 MB, 73,976 allocs, 0.08–1.1 s |
| warm StatsAndNative(30) | 594.9 MB, 6.8 s | 28.7 MB, 0.8 s |
| restart StatsAndNative(0) | 3,106.7 MB, 509,239 allocs, 30.0 s | 48.2 MB, 241,721 allocs, 1.9 s |
| restart StatsAndNative(30) | 594.9 MB, 9.6 s | 28.7 MB, 0.5 s |

Run at the final tree of this series:

- gofmt -l internal: nothing.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
  - sessions: ok, 366.7s.
  - gui: only TestMainWindowCorners failed, "measuring the windows:
    signal: killed". It also fails alone on an untouched origin/main
    export, at load ~500. Filed as #1936 and #2645. Every other gui
    test passed.
- go test -race -count=3 on the new tests: ok.
2026-10-20 20:32:04 +08:00
yetone a23fbaeadf sessions: a subagent's file is read for its task only when its meta names none, once per change
Why: a 48-minute heap profile of the user's magpie allocated 6.3 GB
in sessions.scanAt, 3.5 GB of it from ccTask. The user has 3,174
Claude Code subagent files, 1,798 of them over 1 MB. Two things
caused it:

- subagentsOf titled each one `cmp.Or(m.Description,
  ccTask(f.path))`. Go evaluates both arguments, so every subagent's
  file was read for a first user line that was then thrown away
  whenever the meta file had a description, which is nearly always.
- ccTask kept only a found task. A file whose first 16 lines name
  none was read again on every ask.

What changed:

- Claude Code and Kimi subagent titles read the file only when the
  meta (or the spawn record) gives no description.
- ccTask keeps what it read, a task or none, with the file's size and
  mtime from before the read. An unchanged file isn't read again. A
  grown, rewritten (even at the same size), or touched file is read
  again from its first lines.
- A read that fails keeps the last good result, and a deleted file
  gives "".
- A line appended while the file is being read changes the size, so
  the next ask reads it.
- The docs/subsystems/gateway-sessions.md subagent section says so.

Tests:

- TestSubagentTaskReadOnlyWhenTheFileChanges counts scans through
  scanHook for these cases:
  - first ask: 1 scan;
  - unchanged: 0;
  - grown with a task: 1, then 0 once found;
  - grown after the task: 1;
  - rewritten shorter: 1;
  - rewritten with no task: 1;
  - same size with a new mtime: 1;
  - a task appended past line 16: 1 scan, still "";
  - appended during the read: found on the next ask;
  - deleted: "", 0 scans.
- TestSubagentWithMetaTaskIsNotReadForIt lists a session after a
  simulated restart (Saved, Reset, memos cleared) and expects 0 scans
  of a subagent whose meta names its task.
- Broken by hand:
  - ccTask back to keeping only a found task (`t.task != ""`) makes
    the first test go red: "unchanged, no task yet: 1 scans, want 0".
  - The title back to cmp.Or makes the second go red: "the list read
    a subagent's file 1 times for a task its meta names".
  - Both green again once restored.

Measured on a read-only APFS clone of the user's ~/.claude/projects
and ~/.codex/sessions/2026/10, in a sandbox HOME, at load ~500 from
other sessions. Times are noisy; allocations are not. Restart, then
List(All):

| Code | Allocated | Allocations |
| --- | --- | --- |
| ccTask keep, title still cmp.Or | 153.9 MB | 270,838 |
| this commit too | 25.8 MB | 109,854 |
| origin/main dee5c9d75 | 301.1 MB | 80,004 |

The origin/main row also lacks the buffer pool (a later commit).

Run at the final tree of this series:

- gofmt -l internal: nothing.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- go vet ./internal/sessions/ ./internal/gui/: clean.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
  - sessions: ok, 366.7s.
  - gui: only TestMainWindowCorners failed, "measuring the windows:
    signal: killed". It also fails alone on an untouched origin/main
    dee5c9d75 export, at load ~500. Filed as #1936 and #2645
    (real-window AppKit tests killed at their deadline under load).
    Every other gui test passed.
- go test -race -count=3 on the new and neighbouring subagent and
  scan tests: ok.
2026-10-20 20:32:04 +08:00
yetone 9bbe177c6d gui: app.js's budget holds the Providers page's last list and the Routing trace's account names
TestCoreScriptBudget was red on this batch: app.js is 1,272,726 bytes
over origin/main's budget of 1,271,000 (75e769a9f had raised it for
Free first's option). The batch's growth is 3,276 bytes from the
Providers page drawing its last list at once (#1519), a core page with
no plugin to move it into, and 247 from noteAccounts reading account
names without Object.entries (#1481), which the core's state reading
does for every page. Raised to that size plus 1.5%, as the budget's
rule asks.

Run: go test -run Budget ./internal/gui: ok (red before this, with the
message above).
2026-10-20 20:32:04 +08:00
yetone f73f39050d catalog: a provider's model list is built once a load, without copying every model to the heap for each
Why magpie's own process sat at ~650 MB: a live heap profile of a
user's magpie (magpie heap, 48 minutes) held ~157 MB live but had
allocated 34.8 GB, ~725 MB a minute, so Go's heap peaked near 885 MB
and the footprint followed it. KeepDshWired's round every 30 seconds
was 11.8 GB of it: magpieModels("dsh") → Provider.Catalog → ... →
catalog.Provider for each catalog, which built every model again, and
mdProvider.levels alone was 5.97 GB flat. Its `kin = &x` took the
address of the range variable, so every model of the provider was
copied to the heap for every model asked: allocations grew with the
square of a provider's models.

- levels keeps the kin by id, date and levels, the same choice as
  before (newest by release date, then id, with levels, not after the
  model), with no pointer to the loop's copy.
- Provider keeps each provider's list for the load it was built from
  and gives callers a copy of it; Reset drops them, and a list built
  from a load that a Reset ended meanwhile isn't kept (gen).

Run:
- real models.json (5.8 MB), Provider for every provider id, a pass:
  63.5 MB / 272,952 allocs before; 8.96 MB / 10,478 with the levels fix
  alone; 3.2 MB / 232 with both (a throwaway benchmark, not committed).
- TestProviderAllocsGrowWithModels: red with `kin = &x` put back
  (40012 allocations for 200 models, at most 2000 wanted); red with the
  memo not stored; red with Provider handing out its own slice
  (a caller's change reached the next one). Green on this code.
- go test -race -count=3 ./internal/catalog: ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on
  catalog, provider and agent: ok.
- Full suite, go test -count=1 -timeout 45m ./... on this batch at load
  ~380: every package ok but agent and gateway (past 45m, #2869),
  TestQueueFullAndWaitedOut (#3061), TestRequestBuildsProvidersOnce
  (#2965), TestMainWindowCorners (#2645, red alone on main too) and the
  app.js budget (raised in its own commit). gateway alone: ok but
  TestClaudeAccountsSpentFallBackToCodex (#2858); agent alone past 45m
  at load ~600, its codex/running/connect tests ok alone.

Not done here: a singleflight in provider's heldOf was written and
taken out again; a waiter blocking on another request's build can
deadlock if that build needs a lock the waiter holds, and nothing here
proved it can't.
2026-10-20 20:23:58 +08:00
yetone 9d78a95ef8 routing: a flight's arc is laid again only when its ends move, and account names are read from answers without Object.entries (#1481)
Two smaller sources of the Routing page's steady garbage were left once
the rows were kept. Both were measured with CDP sampled allocation at one
request a second:

- via's j laid the arc through magpie on every frame of a flight: a new
  path string and its control points sixty times a second, though its
  ends had not moved. It now keeps the ends it laid and returns when they
  are the same. That path was 10-13 MB/min and is now ~5.
- noteAccounts walks every API answer (Routing's trace once a second) to
  learn account names for Hide accounts. Object.entries made an array for
  each object and one for each key, ~7-8 MB/min on Routing. It now walks
  with for...in and Object.hasOwn, so the same keys are visited.

Routing ~100 -> ~86 MB/min (from ~149 before the previous commit).
As with the previous commit, the WebKit WebContent footprint did not
change in a 12-minute A/B (119 -> 260 MB before, 117 -> 257 MB after).

Test: routing-steady-garbage.test.cjs, in chromium and webkit, en and zh.
It counts the arc's d writes against the frames drawn while a request
flies, and counts Object.entries calls while noteAccounts reads 50 routes.
It also checks that all 50 accounts are still found. On HEAD's client.js
the arc was laid 32 of 41 frames, and on HEAD's app.js Object.entries ran
201 times: both red.

Run: the 117 GUI files these changes reach (routing-*, panel-routing*, and
every file that drives the Routing page or noteAccounts), chromium and
webkit, their languages and widths, at concurrency 4 on a machine at load
average 500-860 from other sessions: 1520 tests, 1402 pass, 118 fail. Of
the 118, 74 are page.goto timeouts and most of the rest locator timeouts.
The 37 red files were run again at concurrency 2: 726 tests, 45 fail.
The four files red each time were run with HEAD's app.js and client.js
(these changes taken out) and are red there the same way:
group-new-head (4 of 4), routing-bodies (10 of 10), routing-keys-fold
(8) and routing-model-rest (load-dependent, 4 to 12). On origin/main
d9c6a60d8's GUI tree routing-bodies and routing-keys-fold are red too;
group-new-head passes there and goes red with 4b000ecc2 (its rowClock
throws "Invalid time value" on a route with no time), which is on this
branch and not part of this change.
routing-request-metrics fails waiting for the metric menu's Cost item
on this tree (3 of 4 alone), on HEAD (4 of 4) and on origin/main (2 of
4). The other reds were page.goto or locator timeouts under this load.
The two new files passed 4 of 4 each in the full run. No Go changed.

Not tried: real WebView2 on Windows, and the real macOS app.
2026-10-20 20:23:58 +08:00
yetone da058fc995 routing: a request's row is worked out once for each route the trace sends, not again on every update (#1481)
A trace update replaces only the routes that changed (poll's routes.set),
yet every update worked out every row in sight again: outcome,
requestMetrics with tokenBreakdown, reqTitle and the JSON signature. That
made the Routing page the one view whose JS garbage was an order above
the others. Measured with CDP sampled allocation (collected objects
included) on a sandbox magpie at one request a second, 30s per view:
Agents 10, Providers 12.7, Usage 9.3, Sessions 7, Library 8.8, Plugins
10.4 MB/min, and Routing 143-157 MB/min. Chromium's post-GC heap stayed
near 10 MB throughout, so this is churn, not a leak: it costs collector
work and gives the engines' allocators more to hold on to.

rowSays keeps what a row says in a WeakMap by route object. It is worked
out again only for a new route, or when the language, the metrics shown,
the agent's name or icon, or the cost's wording (currency) changes. The
selection stays outside it.

Measured: Routing ~149 -> ~100 MB/min with this alone.

What this does not fix: the WebKit WebContent footprint. A 12-minute A/B
on Playwright's WebKit (footprint -p, one request a second, Routing open)
went 119 -> 260 MB before these changes and 117 -> 257 MB after both
commits. Agents in the same run grew ~4 MB/min, Routing ~8 MB/min, and
nearly all of it is in footprint's "WebKit malloc" category, not the JS
heap (Chromium's heap and DOM node counts stay flat). Its cause is still
unknown. Readings near 1 GB taken earlier were inflated by the method
(a 400 MB marker array used to find the pid) and are not quoted here.

Test: routing-row-reuse.test.cjs counts the token breakdowns worked out
while three requests come in over forty listed, in chromium and webkit, en
and zh. It also checks that a request answered after it was under way
redraws its row, and that a new language redraws the rows. On HEAD's
client.js it is red: 295 breakdowns where now there are at most a few.

Run: the 117 GUI files these changes reach (routing-*, panel-routing*, and
every file that drives the Routing page or noteAccounts), chromium and
webkit, their languages and widths, at concurrency 4 on a machine at load
average 500-860 from other sessions: 1520 tests, 1402 pass, 118 fail. Of
the 118, 74 are page.goto timeouts and most of the rest locator timeouts.
The 37 red files were run again at concurrency 2: 726 tests, 45 fail.
The four files red each time were run with HEAD's app.js and client.js
(these changes taken out) and are red there the same way:
group-new-head (4 of 4), routing-bodies (10 of 10), routing-keys-fold
(8) and routing-model-rest (load-dependent, 4 to 12). On origin/main
d9c6a60d8's GUI tree routing-bodies and routing-keys-fold are red too;
group-new-head passes there and goes red with 4b000ecc2 (its rowClock
throws "Invalid time value" on a route with no time), which is on this
branch and not part of this change.
routing-request-metrics fails waiting for the metric menu's Cost item
on this tree (3 of 4 alone), on HEAD (4 of 4) and on origin/main (2 of
4). The other reds were page.goto or locator timeouts under this load.
The two new files passed 4 of 4 each in the full run. No Go changed.

Not tried: real WebView2 on Windows, and the real macOS app's WebContent.
The numbers are from Playwright's WebKit build and Chromium.
2026-10-20 20:23:57 +08:00
yetone 20c0688316 gateway: Claude Code processes are held to what the machine's memory holds; a full room is a 503 the next provider takes (#2956)
Cause: nothing bounded how many Claude Code processes magpie runs for
Claude subscriptions. Busy runs had no limit, idle ones were capped at 6
and parked ones at 16 per bridge, and one-off tests, warm-ups and /usage
reads were counted nowhere. The reporter's 512 MiB systemd service had 2
busy runs and 14 starting at once when the memory cgroup's OOM killer
ended them.

Measured (Docker arm64, real Claude Code 2.1.303):
- one idle run holds about 205 MiB RSS, 86-112 MiB of it anonymous;
- six runs under a 512 MiB memcg gave oom_kill 2 and a peak of 512 MiB.

Fix: claudeRoom (claude_room.go). Every Claude Code takes a place before
it starts and frees it when its process exits. That covers startRun and
runClaudeTree (tests, warm-up, /usage).

How many may run:
- the user's claudeRunsMost (`magpie claude-code runs N|auto`). It is
  machine-local (KeepOwn), and the Settings page's save keeps it.
- otherwise, on Linux, (limit - 256 MiB) / 128 MiB, at least 1. The limit
  is the least of MemTotal, cgroup v2 memory.max and memory.high up the
  tree, and cgroup v1 memory.limit_in_bytes. The reporter's 512 MiB
  cgroup gives 2, and 1 GiB gives 6.
- otherwise no bound: macOS, Windows, or limits that can't be read.

A full room first lets go of the oldest idle run. Its session is
shelved, so the next turn resumes it. Next it lets go of a run parked
past parkLongest. Busy runs are never let go. Otherwise it waits up to
2 minutes, then answers 503 with the reason and the command.

Routing treats that 503 as protected. No Claude account is rested or
asked next, since each would wait for the same room, and another
provider in the group answers.

Tests (each run red by hand on the broken code):
- TestClaudeRunsHeldToTheRoom: 6 conversations at room 2. With take
  forced to always admit: "6 Claude Code processes were alive at once,
  2 may be". Fixed: at most 2, and all 6 answer 200.
- TestClaudeRoomLetsAnIdleRunGoAndItResumes, TestClaudeRoomFullIs503 and
  TestClaudeOneOffsTakeRoom went red with take forced open.
- TestClaudeNoRoomPassesOnAndRestsNobody went red with the routing
  exemption off: both Claude accounts were tried and rested.
- TestClaudeMemRunsFromTheCgroup uses the reporter's literal meminfo,
  cgroup path and memory.max.
- TestClaudeCodeRunsSetsTheUsersOwn went red with validation loosened.
- TestClaudeRunsMostIsMachineLocal went red without the KeepOwn line.
- TestSettingsSaveKeepsWhatItDoesNotSend (internal/gui guard) caught a
  Settings page save clearing the value. It is kept now.

Run at this tree (macOS, go1.26.8):
- go test -timeout 45m -count=1 ./... with pipefail, under a load
  average of 650-800 from other sessions: 61 packages ok. Three were not:
  - internal/agent and internal/gateway hit the 45m timeout mid-test.
    The stacks show no hang. Re-run at -timeout 120m: agent ok (2779s).
  - In gateway, TestClaudeAccountsSpentFallBackToCodex hit its 30s wall
    bound. No room wait was logged before it, and it passed 5 of 5
    alone.
  - In the same run TestClaudeRoomLetsAnIdleRunGoAndItResumes was red
    because of its own check: a random request id in the fake's log
    spelled "a1". It now reads only the fake's "told" lines. Flipped to
    "a2", it goes red.
  - internal/gui: TestPanelJoinsFullScreenSpaces (a macOS window test)
    passes alone. TestSetAnswersWhileDevinAndProvidersHang has a 10s
    bound, and at the base commit under the same load it failed 2 of 3.
- The touched packages again, -count=1: settings, cli and gui ok.
  gateway: the room tests and TestClaudeAccountsSpentFallBackToCodex
  ok at -count=5.
- gofmt -l: clean.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.

Not tried:
- the Docker 512 MiB reproduction re-run with this build against real
  Claude Code. The fix is shown with fake runs only.
- a real cgroup v1 host.
- the site's docker docs (en/zh/ja) don't mention `claude-code runs` yet.
2026-10-20 20:23:57 +08:00
yetone 92fbabb47e gui: the Providers page draws the last list at once and the fresh one behind it
#1519 (fatkun): the Providers page asked /api/providers each time it
opened, and after a start that read takes seconds (every account's
sign-in, every agent's model), so the page showed skeletons that long.

Now, as the Agents page draws the last state:
- the app reads /api/providers once in the background after the start
  (prefetchProviders), and the page's first opening uses that read, or
  waits on it, instead of asking again. The sidebar's gateway line
  reuses the same read (sideGwRead), so a start still makes one read.
- the server keeps the list it last built in the cache folder
  (providers-state.json, 0600; lastproviders.go) without the gateway's
  recent calls and lanes or any provider's headers, proxy or extra body.
  /api/providers?last=1 serves it at once; the page draws it while the
  fresh read is out, and the fresh one replaces it.
- a row clicked on a kept list waits for the fresh one rather than
  opening an editor that would be drawn again under the reader's hands.

Tests:
- TestLastKnownProviders (internal/gui): red when the stripping of
  Headers/Proxy was broken by hand ("the kept list holds hdr-secret-1519
  / proxy-secret-1519"), green restored.
- providers-last-known.test.cjs (new): the kept list drawn before the
  fresh read answers, then replaced; a row click waits. With
  kept.last = false by hand the row-click case was red in all 5
  languages.
- sidebar.test.cjs: the narrow case now guards one /api/providers read
  in total, still one after widening to 1200px (the sidebar reuses it).
  Red on the old assets (0 reads), green on the new, both engines.

Run:
  go test -timeout 45m ./internal/gui
  ok  	github.com/yetone/magpie/internal/gui	528.667s
  gofmt -l internal/: nothing; go vet ./internal/gui, GOOS=linux and
  GOOS=windows go vet -tags nogui ./...: exit 0
  GUI, chromium and webkit, every language, wide and narrow:
  providers-last-known 20/20, sidebar 8/8, provider-proxy 4/4,
  agents-last-known 3/3, last-page 1/1 in each engine.
  provider-advanced-fold: 1-3 of 25 red per run, the same on the old
  assets (#2552).
  Chromium full GUI suite (before the kept.last and sidebar-test edits),
  under load ~200: 5681 tests, 55 red in 23 files; each was rerun alone
  and either passed or was as red on the old assets. routing-model-rest
  runs, old vs new: old 4, 2, 7 red, new 3, 3 red; routing-request-
  metrics two runs: old 1, 0 red, new 0, 2 red, each red at 23-29s
  (load ~240; the same test red on old).

Not verified: a real cold start on Windows; the webkit full suite (59
provider/sidebar/start files run: 516 tests, the reds there pass alone or
are #1863).
2026-10-20 20:23:56 +08:00
yetone 4ef718651f library: InUse answers while a sync holds the library's lock
#2774: the macOS window stayed white at start. The window waits on
boot.js before it paints, and boot.js asks library.InUse through the
built-in plugins. InUse took the library's mu, which a sync holds for
its whole run: 13-16s on the reporter's Mac, with many agents and
skills. InUse only reads library.json, and save replaces that file whole
(edit.WriteAtomic), so InUse now reads it without mu. A read beside a
sync sees the file from before or after one of the sync's writes, never
half of one. A file that can't be read is still an error, never 0.

TestInUseAnswersWhileASyncHoldsTheLock holds mu and expects InUse to
return 3 within 5s. It also expects a half-written file to be an error.
With the lock put back by hand, it goes red:
  --- FAIL: TestInUseAnswersWhileASyncHoldsTheLock (14.32s)
      inuse_unlocked_test.go:36: InUse waited on the sync's lock

The sandbox cold start measured for this work has a short library sync,
so boot.js came at about the same time before and after (4527ms against
4822ms after listen at ~4s). The reporter's 13-16s sync wasn't
reproduced here.

What was run (worktree at 9fd80b212 plus this change and the commits
before it):
  gofmt -l internal/: nothing
  go vet ./internal/library: exit 0
  GOOS=linux go vet -tags nogui ./...: exit 0
  GOOS=windows go vet -tags nogui ./...: exit 0
  go test -timeout 45m -count=1 ./internal/library: ok 1220.249s
2026-10-20 20:23:56 +08:00
yetone 84210ae7bd agent: Codex's log database is read again only when it or its -wal changed
#1665, owner's item 2: codexReached opened Codex's logs_*.sqlite on
every ask, and every Drift asks it. The report's trace shows ~2465 reads
of logs_2.sqlite in 25s of a Windows start. The read is now kept per
Codex folder. The key is the database path, the since day, and the size
and modification time of the database and its -wal. A kept read stands
for at most 15s, so a file system with coarse times can't hide a write
that kept the size. A hit older than 24h is never kept, since it falls
out of the window being read. In an interposed sandbox start, opens of
logs_2.sqlite went from 6-8 per run to 4.

TestCodexReachedReadsLogOnlyWhenItChanged asks 50 times and expects 1
read. It then writes to the log and expects a fresh read that sees the
write. With the cache check turned off by hand, it goes red:
  --- FAIL: TestCodexReachedReadsLogOnlyWhenItChanged (3.23s)
      codex_reached_test.go:50: 50 asks read the log 50 times, want 1

Owner's item 3: the PATH x PATHEXT lookup cache, 8bfe33f1f (#1771), is
an ancestor of this commit and shipped in v0.1.1214. The reporter's
trace was taken on v0.1.1212.

What was run (worktree at 9fd80b212 plus this change and the commits
before it):
  gofmt -l internal/: nothing
  go vet ./internal/agent: exit 0
  GOOS=linux go vet -tags nogui ./...: exit 0
  GOOS=windows go vet -tags nogui ./...: exit 0
  go test -timeout 45m -count=1 ./internal/agent: ok 2591.806s
2026-10-20 20:23:55 +08:00
yetone 23d4dc591a access: LANSecret answers "not shared" from settings, before caller-keys.json's lock
#1665: every agent's sync (keptaway's keeping) asks access.LANSecret.
LANSecret took mu first, which also makes and locks
caller-keys.json.lock, even when the gateway isn't shared on the LAN and
the answer is "" from settings alone. A sandbox start's lock trace
showed ~102 caller-keys.json.lock takes in its first 20s. Now the
not-shared case returns before the lock. The shared case is unchanged.
After the change, the same interposed start counted 7 opens of
caller-keys.json.lock over the run.

TestLANSecretNotSharedTakesNoLock holds mu and expects LANSecret to
return "" within 5s. Once ConfigureLAN(true, false) shares the gateway,
it expects a key. With the settings check moved back under the lock by
hand, it goes red:
  --- FAIL: TestLANSecretNotSharedTakesNoLock (5.25s)
      lansecret_unlocked_test.go:29: not shared, under another's lock: answered=false ""; want "" at once

What was run (worktree at 9fd80b212 plus this change and the commits
before it):
  gofmt -l internal/: nothing
  go vet ./internal/access: exit 0
  GOOS=linux go vet -tags nogui ./...: exit 0
  GOOS=windows go vet -tags nogui ./...: exit 0
  go test -timeout 45m -count=1 ./internal/access: ok 21.008s
2026-10-20 20:23:55 +08:00
yetone 7fe11e3804 provider: an agent's accounts are listed without logins.json's lock unless one is to be written
#1665: sideLogins took loginsMu, which also makes and locks
logins.json.lock, for every list of an agent's accounts. That is a dozen
lists for each page's read (google twice, copilot, chatgpt-api, qoder
and the rest), and nearly every one writes nothing. After the
rememberLogins fix, a lock trace of a sandbox start (MAGPIE_LOCKTRACE)
still showed ~55 sideLogins locks in the first 20s. An interposed run
counted 1107 opens of logins.json.lock over the run, nearly all of them
from sideLogins.

sideLogins now reads logins.json without the lock. keepSideLogins looks
(look=true), which changes and writes nothing and only says whether it
would. Only then does sideLogins take loginsMu, read the file again and
make the change, the same code as before. The look says "would change"
for every branch that writes. logins.json is only ever replaced whole
(writePrivate through steady.WriteFile: temp file, flush, rename), so an
unlocked read sees one write's file.

TestSideLoginsNothingToChangeTakesNoLock holds loginsMu and lists an
agent's accounts 100 times when nothing changes. It expects them to
return within 5s with the agent's own account listed. Then a new own
account must still be written. Both halves were broken by hand:
  lock always taken:
    --- FAIL: TestSideLoginsNothingToChangeTakesNoLock (5.34s)
        side_logins_unlocked_test.go:34: a list with nothing to change waited for logins.json's lock
  write never taken:
    --- FAIL: TestSideLoginsNothingToChangeTakesNoLock (0.07s)
        side_logins_unlocked_test.go:38: the agent's own account isn't listed: []

What was run (worktree at 9fd80b212 plus this change and the commits
before it):
  gofmt -l internal/: nothing
  go vet ./internal/provider: exit 0
  GOOS=linux go vet -tags nogui ./...: exit 0
  GOOS=windows go vet -tags nogui ./...: exit 0
  go test -timeout 45m -count=1 ./internal/provider: ok 696.341s
2026-10-20 20:23:55 +08:00
yetone c087834d6f provider: rememberLogins checks the time before it takes logins.json's lock
#1665, owner's item 1: rememberLogins took loginsMu first. That made and
locked logins.json.lock even when it then saw that 30 seconds hadn't
passed since its last look and returned. It is asked on every account
list and every page's read: ~370 times in a Windows start's first 25s in
the report, each one a file the antivirus filter driver works on.
loginsSeenAt is now an atomic.Int64, so the time can be read without the
lock. A look that isn't due returns before the lock. A due look checks
again under the lock, in case another ask looked while it waited.
switchSavedLogin, ForgetAccounts and the tests that reset the time now
Store(0).

TestRememberLoginsNotDueTakesNoLock holds loginsMu and asks 100 times
just after a look. It expects the asks to return within 5s, and a due
ask to look. With the check before the lock removed by hand, it goes red:
  --- FAIL: TestRememberLoginsNotDueTakesNoLock (5.67s)
      logins_due_test.go:30: a look not due waited for logins.json's lock

What was run (worktree at 9fd80b212 plus this change and the commits
before it):
  gofmt -l internal/: nothing
  go vet on the touched packages: exit 0
  GOOS=linux go vet -tags nogui ./...: exit 0
  GOOS=windows go vet -tags nogui ./...: exit 0
  go test -timeout 45m -count=1 ./internal/provider: ok 696.341s
2026-10-20 20:23:55 +08:00
yetone 3d55ff473f filelock: a lock makes its folder only when the folder is missing
#1665: in fy1q2's Windows trace, the lock folder took ~193 each of
Create, QueryInfo and Cleanup in a start's first 25s. Each one is work
for an antivirus filter driver. filelock.Lock ran os.MkdirAll on the
lock file's folder before every take, even though the folder is
nearly always there. Now Lock opens the file first and makes the folder
only when OpenFile fails with ErrNotExist, then opens it again.

TestLockMakesFolderOnlyWhenMissing counts mkdirAll calls. It expects
one for a missing folder and none for 20 takes in a folder that is
there. With MkdirAll put back before OpenFile by hand, it goes red:
  --- FAIL: TestLockMakesFolderOnlyWhenMissing (0.25s)
      filelock_test.go:96: 20 takes in a folder that is there made it 20 more times

What was run (worktree at 9fd80b212 plus this change):
  gofmt -l internal/: nothing
  go vet ./internal/filelock (and the other touched packages): exit 0
  GOOS=linux go vet -tags nogui ./...: exit 0
  GOOS=windows go vet -tags nogui ./...: exit 0
  go test -timeout 45m -count=1 ./internal/filelock: ok 7.207s
Not tried on the Windows box; the count is measured on macOS.
2026-10-20 20:23:54 +08:00
yetone 92cb1f03a5 routing: a request whose time isn't a date draws its row with no time, not an error
28e3378c3 (#2524) formats a row's time with one Intl.DateTimeFormat. Its
format throws a RangeError on an invalid date, where the old
toLocaleTimeString said "Invalid Date", so one such request threw out of
drawList and the list wasn't drawn. group-new-head's fixture gives its
requests `at`, not `time`, and went red in all 4 cases on 28e3378c3
("Invalid time value" twice, from rowClock ← reqRow ← drawList); it is
green on origin/main ef655acb4. rowClock now gives "" for a time that is
not a date.

What was run (magpie-wt-light, 28e3378c3 plus this change):
  group-new-head.test.cjs (chromium, webkit; en, zh): pass 4, fail 0
    on 28e3378c3 without it: fail 4 (page error "Invalid time value")
2026-10-20 20:23:54 +08:00
yetone a8224019af routing: a day of thousands of requests draws only the rows in sight, and its numbers are measured again on a new width only (#2524)
UNscientific-9 (#2524): picking a day on Routing's request list froze the
page for seconds with thousands of rows. renderLog built a row for every
request of the day (~20 elements each, up to 2,000 a day) and put the new
ones in among the old row by row, so both days' rows were in at once.
Beside that, metaFit was run by a ResizeObserver on the column's every
change of size; the meta-under mark it sets changes the column's height,
which measured every row's numbers again (the reporter saw 8 runs in 8s,
~200ms each).

Now:
- A list of 300 or more items is windowed: only the rows in and near
  sight are drawn, between two aria-hidden gaps as tall as the rows above
  and below. A drawn row's height is measured and kept; one never drawn
  counts as the average. Scrolling or a resize draws the rows then in
  sight, once a frame, and the first row in sight stays where it was.
- The columns stay as wide as before: for each shape of row not drawn
  (its time's digits, model and kind, its numbers), one unseen, inert
  zero-height probe row stays in the grid, so the auto columns size by
  it. The digits are tabular, so a probe stands for its shape.
- A list made mostly anew (another day) is put in with one
  replaceChildren, not row by row among the old ones.
- metaFit runs on a change of the column's width only. When it moves the
  numbers under or back, the list is drawn again for the new heights.
- A row's clock uses one cached Intl.DateTimeFormat.
Under 300 items the list is drawn whole, as before.

Not done here, from the reporter's list: drawAll still runs renderHist on
a static day at each poll. Measured with a live request arriving every
250ms while a 2,000-row day was shown (scratchpad dayidle.cjs, chromium,
4s): frame callbacks 330 / 211 ms total / 9 ms longest before, 90 / 52 ms
/ 4 ms after. A guard there would have to know every input of renderHist
(now(), lifted rests, names), so it was left out. Trimming prompt.parts
from the payload is on the server, not here. The renderer crash on
repeated switches was not reproduced.

Measured (scratchpad dswitch.cjs, 2,000 rows a day, 1280x900, five day
switches each, wall ms / longest block ms, load average ~220-290):
- chromium before: 379/304 454/374 452/374 474/389 427/376, rows=2000,
  ~39,740 elements
- chromium after: 56/22 61/20 56/19 74/21 410/17, rows 17-21, ~1,520-
  1,600 elements (the 410 is wall time under load; its longest block 17)
- webkit before: 565/461 624/493 639/526 625/516 616/516, rows=2000
- webkit after: 117/37 95/25 93/30 128/26 138/25, rows 17-21
- same grid columns and list height after as before, in both engines:
  chromium "89.4375px 94.1875px 661.078px 181.297px", scrollHeight 61602;
  webkit "89.4375px 94.1875px 641.078125px 181.296875px", 61602

Run:
- tests/routing-day-window.test.cjs (new), chromium and webkit, en zh
  zh-TW ja de, 1280px and 420px: 30 tests, 30 pass. It picks a 2,000-row
  day, checks the rows drawn are bounded and the list is as tall as all
  of them, scrolls to a wide model far down (columns unchanged, not cut),
  holds a row still across frames mid-list, reaches the last row and picks
  it, switches day, and goes By session to the list's foot. The second
  test grows the column taller three times and counts reads of the
  numbers' boxes: 0, and >0 on a new width.
- Same test on the old assets (MAGPIE_ROUTING_ASSETS, the routing
  client.js/css before this change), chromium en: 3 fail, "a day of 2000 put 2000 rows in
  the list" (both widths) and the measure test (12000 reads, not 0).
- Broken by hand: WIN_MIN 300 -> 300000 fails "a day of 2000 put 2000
  rows in the list"; the width guard taken out fails "156 !== 0" in both
  engines. Both restored.
- tests/routing-sessions.test.cjs: its 2,001-request history test now
  scrolls to a session's group instead of expecting all 2,001 rows in the
  DOM. 8 pass, 0 fail (chromium and webkit, en and zh).
- routing-*.test.cjs, panel-routing*.test.cjs and every other GUI file
  that reads the request list (claude-auth-status, claude-subagent-tag,
  dates-gui-lang, click-scroll, codex-subagent-model, codex-credits,
  desktop-subagent-model, key-nourl, phone-rows, reasoning-speed,
  remote-group-served, purpose-filter, search-instead, rest-try-now,
  search-mcp, vision-mcp), both engines, every language, concurrency 4:
  1412 tests, 1390 pass, 22 fail. 18 of those are routing-bodies,
  routing-keys-fold, routing-model-rest, routing-request-metrics and
  routing-wb-restricted, which fail the same way on the old assets
  (#2658, #2559). The other 4 (rest-try-now chromium en 1100 and ja 420,
  routing-log-icons webkit zh, routing-time-went chromium de) pass when
  their files run alone: 64 tests, 64 pass.

Not tried: WebKitGTK and the Windows WebView2 app (where the reporter's
seconds-long freeze was on Windows); the numbers above are Playwright's
Chromium and WebKit on macOS.
2026-10-20 20:23:53 +08:00
yetone ac3a2a3df5 routing: the page asks for frames only while its stage moves, and the live dot pulses only while a request is under way (#2827)
zhang-4411 (#2827): under xrdp/X11 with no GPU the Routing page's web
process took 459%-830% CPU. Beside compositing (27353a952), the page
itself drew on every frame while nothing moved: its frame loop asked for
the next frame forever once Routing was shown, and the live dot's rtlive
pulse ran with no request under way. On llvmpipe each of those frames is
rasterised on the CPU.

Now the loop stops once nothing on the stage moves and is kicked again
by what makes something move (a request arriving, a replay, the page
shown again). The dot pulses (.rt-livedot.on) only while a request is
live. With no request, the page asks for no frames.

Measured in the GUI harness (scratchpad measure.cjs, 4s windows,
Playwright on macOS, load average ~200):
- chromium, Routing idle: before 70 ms CPU/s, 60.3 rAF/s, 1 running
  animation (rtlive); after 4 ms CPU/s, 0 rAF/s, 0 animations
- webkit, Routing idle: before 62 rAF/s, 1 animation; after 0 rAF/s,
  0 animations (WebKit's per-process CPU reading was negative under
  this load, so only frames are given)
- Routing busy (requests moving) is unchanged: chromium 176 -> 186 ms
  CPU/s, ~64 rAF/s both

Run:
- tests/routing-idle-frame.test.cjs (webkit, en and zh, as the file
  runs): 9 pass 0 fail. It now also counts the frames asked for with
  nothing moving and checks the dot's animation; MAGPIE_ROUTING_ASSETS
  points it at an older asset tree.
- Same test on the old assets (9fd80b212's, MAGPIE_ROUTING_ASSETS):
  FAIL "the Routing loop kept asking for frames with nothing on its stage
  moving (26 frames in 400ms)".
- Broken by hand (animation back on .rt-livedot): FAIL "the live dot
  pulsed with no request under way". Restored.
- Routing GUI files, chromium and webkit, every language: 1104 tests,
  1086 pass, 18 fail. Every one of those 18 fails the same way on the
  old assets in the same run (base 22 fail, new 20 fail on the reruns):
  routing-bodies "opens to its request and response", and under load
  routing-model-rest, routing-keys-fold, routing-request-metrics and
  routing-wb-restricted. All are in #2658 (and #2559). The one red only
  on the new side, routing-wb-restricted zh-TW 420px, passes rerun alone
  in both engines.

Not tried: WebKitGTK, xrdp or llvmpipe. Playwright's WebKit is not
WebKitGTK, so the CPU the reporter sees is not measured here.
2026-10-20 20:23:53 +08:00
yetone 2d12ce98be gui: on Linux without a GPU WebKitGTK draws without accelerated compositing (#2827)
zhang-4411 (#2827): under xrdp/X11 with no GPU the Routing page's web
process took 459%-830% CPU, and 23% with WEBKIT_DISABLE_COMPOSITING_MODE=1,
looking the same. With no render node EGL can open, WebKitGTK's
compositing falls back to Mesa's llvmpipe, which rasterises and blends
every layer on the CPU with a thread per core.

webkitDefaults already turned compositing off under Wayland (myxxts's
flicker). It now does so under X11 too when gpuReachable finds no
/dev/dri/renderD* this process can open (none there, or each refused:
the xrdp user outside the render group). X11 with a GPU is left as it
was, and a user who set WEBKIT_DISABLE_COMPOSITING_MODE or
WEBKIT_DISABLE_DMABUF_RENDERER keeps what they set
(WEBKIT_DISABLE_COMPOSITING_MODE=0 turns compositing back on).

Run:
- gofmt -l internal/gui: nothing
- go vet ./internal/gui; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet -tags nogui ./...: clean
- go test -tags nogui ./internal/gui -timeout 45m (macOS):
  ok github.com/yetone/magpie/internal/gui 1013.214s
- webkit_linux*.go build only on Linux, so the tests ran there:
  CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go test -c -tags nogui, run in
  docker golang:1.26.8: TestWebkitDefaults and TestRenderNodeOpens PASS.
- Broken by hand (gpu() || true in webkitDefaultsFor): FAIL
  "x11 without a gpu (xrdp): WEBKIT_DISABLE_COMPOSITING_MODE="", want "1"".
  Restored.

Not tried: a real xrdp session, llvmpipe or WebKitGTK. gpuReachable was
not run on a machine where the render node is refused; the CPU figures
are the reporter's.
2026-10-20 20:23:53 +08:00
yetone 58cfca2f77 gateway: a Codex turn's rewrites look at its items in place and decode it only when one has something to change (#1532, #2354)
A long Codex session grew slower each turn through magpie because every
request went through up to eight rewrites (callItemIDs, plainItemIDs,
boundCallIDs, codexInputAs, forVendor, withoutBareReasoning,
withoutReasoningText, withModel), and each one json.Unmarshal'ed the
whole conversation into maps, even though on most turns none of them had
anything to change. When one did change something, encoding/json
re-scanned every raw item one byte per call to write the body back. In
the live heap, withModel's json.Marshal held 28.8 MB, and checkValid and
stateInString were ~25% of CPU.

- Before decoding anything, each rewrite now asks whether any input item
  is one it changes (anyInputItem, over longBody's remembered split). It
  reads the item's members where they lie, matching keys as the old
  decode did: exact and last-wins for map reads, EqualFold for struct
  reads (reasoningOf). An escaped key, or a null in a field, falls back
  to decodeJSON. The change path is still the old code.
- forVendor and withModel split the body with rawObject/rawArray. When a
  rewrite writes the body back, marshalRaw is used (marshalPlain without
  HTML escaping, marshalJSON with it). It copies each raw value with its
  strings whole, into one buffer sized up front, and its bytes are
  encoding/json's own. Where encoding/json would refuse a value, the call
  falls back to encoding/json and gets its error.
- withModel now passes a body of null through unchanged. It used to panic
  writing into a nil map.

Measured with a sandbox gateway and a fake upstream. The bodies were
shaped from local Codex rollouts and never leave the machine. The machine
was at load ~160-180, so wall times are noisy; the CPU profiles are the
steadier number.
  5 MB body, CPU per mode (17 requests, pprof):
    relay    4.36s -> 1.38s  (~256 -> ~81 ms a request)
    accounts 10.29s -> 3.78s (~605 -> ~222 ms)
    magpie   7.00s -> 3.40s  (~412 -> ~200 ms)
  wall time to upstream, medians before -> after:
    relay    100k 8.1 -> 7.2ms, 1m 66.7 -> 47.9ms, 5m 1069 -> 280-661ms
    accounts 100k 32.3 -> 17.3ms, 1m 1016 -> 373ms, 5m 4852 -> 2118-2567ms
    magpie   100k 13.3 -> 10.1ms, 1m 345 -> 139ms, 5m 2713 -> 960-1805ms
  The remaining cost at 5 MB is parse/promptOf/codexBody decoding the
  body for their own needs (decodeJSON, longBody), not these rewrites.
  SSE: the relay flushes each read and the masking writer passes Flush
  on; TTFB stayed within ~1-10ms of to-upstream before and after.

Tests:
- TestCodexRewritesAsBefore compares each rewrite's output byte for byte
  against its old code, which is kept in the test. It covers marked items
  (bad ids, magpie compactions, triggers, reasoning with text or nothing
  sealed, configuration_update, Codex metadata), duplicate and escaped
  keys, non-object items, an input that is null or an object, and 300
  random mixes.
- FuzzCodexRewritesAsBefore ran 150s: 22,796 execs, PASS.
- TestMarshalRawIsEncodingJSON and FuzzMarshalRaw (90s, 46,537 execs,
  PASS) check marshalRaw against encoding/json, with and without HTML
  escaping.
- Broken by hand to see the new tests fail:
  - With anyInputItem always true, TestCodexRewritesLeaveTurnUndecoded
    went red: "callItemIDs: 11086 allocations for a turn it leaves as it
    came (243 KB)", and every rewrite, forVendor 9172.
  - With marshalPlain's marshalRaw path off, TestMarshalRawAllocatesOnce
    went red: "marshalPlain of 420 items: 4 allocations".
- gofmt -l and go vet -tags nogui ./internal/gateway are clean.
- GOOS=linux and GOOS=windows go vet -tags nogui ./... are clean.
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m:
  ok  github.com/yetone/magpie/internal/gateway 2579.125s
2026-10-20 20:23:52 +08:00
yetone aa821d8d6b provider: a group member at an effort is looked up among the providers once a request, not at each expansion (XcodeFish, #2502)
isModel, asked by memberEffortIn for every member fixed at an effort
("claude/claude-opus-5-5:medium"), found the provider again (Find) and
read its whole model list (Available) each time. A request expands its
groups several times, so /v1/models paid that per member per expansion.
The provider look is now held for the request (heldOf "has-model"), as
the reporter's patch has it; the catalog entries' check stays as it was.
A provider saved while held is looked at anew (heldOf drops on gen).

Measured (sandbox, fake providers: 3 providers of 400 models, 6 groups
of 8 effort members, 40 GET /v1/models, -cpuprofile):
  before: isModel 0.10s of models' 0.74s under the handler (13%)
  after:  isModel gone from under the handler (0 samples); models 0.67s
The reporter's real catalog (Available reading real lists) had it at
~45 ms a request; not measured on their config.

Tests: TestMemberEffortLooksOncePerHold (new): 5 asks held = 1 look,
a save while held is seen, 3 asks not held = 3 looks. With isModel
calling providersHave directly it fails: "held: looked 5 times, want 1".
go test -tags nogui ./internal/provider -count=1 -timeout 45m:
ok  github.com/yetone/magpie/internal/provider 1152.887s
gofmt -l, go vet ./internal/provider clean.
2026-10-20 20:23:52 +08:00
yetone 881772d7de agent: copies left on the old list are found without ps on macOS, so /api/state no longer waits seconds on it (#1962, #2341)
/api/state asks StaleCopies of Claude Code and Codex on every call, and
StaleCopies ran pgrep -f, then `ps -o etime=,command= -p <pids>` over
what it matched. On a Mac with ~1300 processes and a busy CPU, ps over
the 25 claude processes the owner keeps open took 0.8-2.2s (pgrep
0.06s): measured with the commands alone, and caught in a goroutine
dump of a sandbox magpie, whose /api/state goroutine sat in
os/exec.(*Cmd).Wait under StaleCopies (connectinfo.go:156). The GUI
fetches /api/state after every save (#1962: open DeepSeek, change
nothing, save: the save itself answers in ms since 7e33a298b, the
"Saving…" wait was this) and on every page switch and focus.

On macOS listRunning now asks pgrep -lf for each match's pid and
command line, and the kernel (sysctl kern.proc.pid) for its start; ps
isn't run. Other systems keep pgrep + ps (running_other.go, the old
code unchanged); Windows lists no processes for StaleCopies at all.

Measured on a sandbox magpie (sandbox HOME, 18 agents connected,
DeepSeek provider), GET /api/state x25, machine load 236-297:
  before (origin/main 5b267fbd8): median 3.373s, 3.013s (two runs)
  after:                          median 0.343s, 0.197s
Unchanged DeepSeek save + the GUI's following /api/state:
  before: save 0.007-0.017s, state 1.9-2.6s
  after:  save 0.007-0.016s, state 0.25-0.34s

Run:
- TestRunningNeedsNoPs (a ps on PATH that only fails; a real sleep
  child found with its command line and age). On the old ps path
  (running_other.go built on darwin by a temporary tag):
    running_darwin_test.go:38: found 0 copies of sleep 314.159, want 1: []
    --- FAIL: TestRunningNeedsNoPs (7.46s)
  With the fix: PASS.
- macOS, sandbox HOME: go test -count=1 -timeout 45m ./internal/agent/
  ./internal/gui/ -> ok gui 472.390s; agent hit the 45m timeout at
  load ~250 while TestDisconnectStaysThroughSync had run 10s (no hang:
  the slowest tests are Claude tier tests, 234s and 143s, which never
  reach running). Rerun with -v -timeout 90m: ok agent 3506.886s,
  TestRunningNeedsNoPs 0.11s and every Stale test PASS.
- gofmt -l clean; go vet ./internal/agent; GOOS=linux and GOOS=windows
  go vet -tags nogui ./... clean.

Not changed: a save that does change the provider still runs
SyncCatalog before it answers (2-6s with 18 agents under this load);
moving it behind the response changes what the response's moved list
and many tests rely on, and is left for a decision.
2026-10-20 20:23:51 +08:00
yetone a257319963 plugin: an install takes the versions no longer installed out of Bun's cache (#1988)
Bun keeps every package version it ever fetched in its install cache
(~/.cache/magpie/bun/install-cache) and never takes one out. Each
release of a moved subscription's plugin that keepMovedCurrent or the
hourly updates installed added one more: the owner's Mac had 131
versions of the community plugins there, 10M, and it only grows.

After a successful install (beside pruneDist), the cache's
name@version@@registry folders whose version isn't the one in
plugins/node_modules are removed, then the links left to nothing in
each package's folder of links. A package whose installed
package.json can't be read or parsed keeps its versions (unknown, not
"not installed"). @T@ tarball entries and .npm manifests are left as
they are. What is installed is a copy, so a version taken out is only
fetched again if it is asked for again.

Measured on a copy of the live install cache with the live
plugins/node_modules package.json files:
  before: 10M, 131 entries under @magpie-community
  after:  1.0M, 18 entries (9 packages, the installed version each)

Run:
- TestInstallPrunesBunsCache (Bun's real layout, through install with
  the fake bun). With the pruneInstallCache() call commented out:
    installcache_test.go:62: opencode-grok-auth@0.1.16@@registry.npmjs.org@@@1 left in Bun's cache, not installed: <nil>
    installcache_test.go:62: opencode-kiro-auth@0.1.5@@registry.npmjs.org@@@1 left in Bun's cache, not installed: <nil>
    installcache_test.go:72: the link to the version taken out left: <nil>
    --- FAIL: TestInstallPrunesBunsCache (1.51s)
  With it: PASS. Also PASS on the Windows box (windows/amd64 binary).
- macOS, sandbox HOME: go test -count=1 -timeout 45m ./internal/plugin/
  -> ok internal/plugin 2214.050s (load ~250)
- gofmt -l clean; go vet ./internal/plugin; GOOS=linux and
  GOOS=windows go vet -tags nogui ./... clean.
2026-10-20 20:23:51 +08:00
yetone 68a96b67b8 proc: a command's context ending on Windows kills what it started too (#2341)
The Store's WSL runs System32's wsl.exe, which starts Program Files'
wsl.exe and waits on it. When `wsl.exe -l --running -q` hung past its
timeout, CommandContext killed the first only; the second, waiting on
a hung WSL service, was left. With a retry every few seconds that came
to dozens of wsl.exe a day on the reporter's machine. ProbeContext had
the same gap on Windows: Output starts the command out of a job's
reach, so the probe was killed alone.

CommandContext's Cancel on Windows now finds the command's descendants
by parent pid (a Toolhelp snapshot; a reused pid is told apart by a
start before its parent's) and terminates them before the command.
ProbeContext's Windows cancel does the same. wslrun's cancelable kept
its own Cancel and dropped proc's: it now runs proc's after stopping
the run inside the distro, so it gets the tree kill too (and a probe's
end, which it had lost).

Measured on the Windows box (10.0.0.132), cmd.exe running ping as the
two wsl.exe:
  before: 1 child left running per ended context (CommandContext and
          ProbeContext both)
  after:  0 left

Run:
- TestContextEndKillsWhatTheCommandStarted, windows/amd64 test binary
  on the Windows box. With killDescendants commented out in both
  cancels:
    killtree_windows_test.go:71: process 57548 that cmd.exe started still runs after its context ended
    killtree_windows_test.go:71: process 42264 that cmd.exe started still runs after its context ended
    --- FAIL: TestContextEndKillsWhatTheCommandStarted (4.08s)
  With the fix: --- PASS (0.09s), both subtests.
- The whole proc test binary on the Windows box: everything passes but
  TestNoCommandBypassesProc, which walks the source tree from the
  binary's folder and read other checkouts under C:\Users\yeton (the
  binary ran outside a checkout). wslrun's test binary there: PASS.
- macOS, sandbox HOME: go test -count=1 -timeout 45m ./internal/proc/
  ./internal/wslrun/ -> ok proc 54.098s, ok wslrun 2.872s.
- gofmt -l clean; go vet ./internal/proc ./internal/wslrun;
  GOOS=linux and GOOS=windows go vet -tags nogui ./... clean.

Not tried: a real hung WSL service. The box's WSL answers, so the
reporter's hang itself wasn't reproduced; the test's cmd.exe→ping
stands in for System32 wsl.exe→Program Files wsl.exe.
2026-10-20 20:23:51 +08:00
yetone 67f8dbb16c routing: the hidden tray panel no longer draws its Routing tab for every request (#2515)
The tray panel is hidden nearly all the time, yet renderPanel put up a
new head, stage and row list for every trace update (about 200 a minute
under 1 request a second), whichever tab was picked. A hidden page draws
no frames, so the infinite CSS animations on what each draw replaced
(.rt-livedot in the head, .pr-req.wait .pr-to > i on a waiting row,
.ps-dst.wait > i on the stage) were never dropped from the document's
timeline, and each held its detached tab, rows and all.

On the Windows box (WebView2, where a hidden panel reports
visibilityState "hidden"), magpie-gm sandbox, base build 9fd80b212,
main window on Routing, panel hidden on its Agents tab, a fake vendor
at 1 request a second:
- panel page after GC: 265,012 DOM nodes and 13,731 listeners after 11
  minutes of traffic (1,071 elements at start); Runtime.queryObjects:
  68,015 of 69,591 elements detached, 760 div.pr-list roots (58,733
  elements) and 1,110 div.pr-head (8,874); the heap snapshot's retainer
  path Window > HTMLDocument > DocumentTimeline > CSSAnimation > <i> >
  span.pr-to > span.pr-line > button.pr-req.wait > div.pr-list
  (detached), 6,505 ElementAnimations
- WebView2 renderers' private bytes 131 MB at minute 6, 443 MB at 17,
  555 MB at 25 (about 20 MB a minute); the reporter's 5.2 GB after 28 h
  is this rate.

Now renderPanel, while document.hidden, draws again only when the tab's
shape changes (rows shown, the off message, loaded, the group picks,
today's totals there or not), as the panel's height is fitted to every
tab measured; otherwise it marks the tab stale and draws it in full on
visibilitychange. pDraw waits the same way, and no request's dot flies
in a hidden panel. A panel shown draws exactly as before.

After, the same soak with this build (magpie-fix.exe), main window
also on Routing:
- panel page after GC at minutes 17, 47 and 60: 4,698, 4,654 and 4,654
  DOM nodes, 317 listeners, JS heap 5.0-5.2 MB, 5 animations
- WebView2 renderers 274 MB at minute 5, 318 at 25, 423 at 60 (2.7 MB a
  minute, against about 20); 3,690 requests answered by minute 60.
  The panel's own renderer (told apart by a 200 MB allocation made in
  it) still grows about 0.75 MB a minute natively with its JS heap and
  DOM flat; that is not explained by this commit.

panel-routing-hidden.test.cjs fakes a hidden page (headless pages are
never hidden: a minimised window still says "visible" and runs rAF),
sends a request every 80 ms and checks the hidden tab is drawn 0 times
over 20 of them, flies no dot, and is drawn once, newest request first,
on visibilitychange. On 9fd80b212's client.js it is red in all four
(chromium, webkit x en, zh): "the hidden tab was drawn 20 times over 20
requests" (expected 0, actual 20). With the visibilitychange redraw
taken out by hand it is red: "drawn once as the panel shows" expected
1, actual 0. With the fix, 4/4 ok.

Every GUI file that opens the tray panel (70 files, chromium and
webkit, their languages and narrow widths; node --test
--test-concurrency=4, machine load ~275): 960 of 962 pass. The two:
usage-chart-axis chromium was browserType.launch timing out at 180 s
(passes alone), and usage-fold "the view didn't scroll" 184 !== 180,
which fails the same way twice with 9fd80b212's client.js put back
(#2163, #2399). No Go code changed.
2026-10-20 20:23:51 +08:00
yetone 60a42875cd gui: a Linux alert closed with its × no longer opens the main window over the desktop (#2513)
Wails beta.24's Linux notifications report a notification the user closed
(NotificationClosed reason 2: its ×, or cleared from the list) as
DefaultActionIdentifier, the same id a click on its body gives. magpie's
response handler opened the main window (ShowMain("usage"): Show + Focus)
on any response to an alert, so on Linux dismissing a usage/balance/reset
alert raised the main window, maximised if it was left so, on top with the
input focus. On X11 with a panel that reserves no space that is a
1920x1080 borderless window at 0,0, _MOTIF_WM_HINTS 0x2,0x0, holding
_NET_ACTIVE_WINDOW: the signature in #2513.

On Linux an alert is now sent under a category whose one action has id
"default". Wails reports a category action under its own id, so a body
click comes back as "default" while a dismissal stays
DefaultActionIdentifier, and only the click opens Usage (opensUsage).
macOS and Windows are unchanged. A turn's end still opens nothing.

Not proven: that the reporter's window came from a dismissal rather than
a window they maximised themselves. Done on Linux (WSL Ubuntu 24.04,
Xvfb 1920x1080 + kwin_x11, sandbox HOME):
- double-clicking the main header maximises it to exactly 1920x1080 @0,0,
  _MOTIF 0x2,0x0, focused; the panel only gets there by WM fullscreen,
  which magpie never asks for.
- a Wails probe against a fake freedesktop daemon (dbus-python):
  plain notification: dismiss -> DEFAULT_ACTION, click -> DEFAULT_ACTION;
  under the category: dismiss -> DEFAULT_ACTION, click -> default.
- xfce4-notifyd drew no popup under Xvfb, so no real daemon's UI was
  tried, and not KDE Plasma's rendering of the "default" key.

Tests: TestDismissedAlertOpensNothing, TestLinuxAlertSentUnderClickCategory.
Broken by hand (Linux branch back to `return true`):
  --- FAIL: TestDismissedAlertOpensNothing
  quota_alert_notify_test.go:29: opensUsage(linux, magpie-alert-1 DEFAULT_ACTION) = true, want false
Restored: green.

Run at this head:
- gofmt -l: clean
- go vet ./internal/gui/ (darwin); GOOS=windows go vet ./internal/gui/: ok
- GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet -tags nogui ./...: ok
- WSL: go vet -tags gtk3 ./internal/gui/: ok
- WSL: go test -tags gtk3 -run 'TestDismissedAlertOpensNothing|TestLinuxAlertSentUnderClickCategory|TestAlertText|TestReminderText' ./internal/gui/
  ok  github.com/yetone/magpie/internal/gui 0.056s
- go test -timeout 45m ./internal/gui/ (darwin):
  ok  github.com/yetone/magpie/internal/gui 1350.238s
2026-10-20 20:23:50 +08:00
yetone a7e2c72358 sessions: a line longer than the read buffer is gathered once, at its own size (#2515)
scanAt gathered a line longer than its read buffer by appending one
buffer's worth at a time. Past 256 elements append grows a slice by
1.25x, so an 8 MiB line allocated ~37 MB, and a line past maxLine was
gathered to 32 MiB before being dropped (~175 MB allocated). The session
list and the call readers both read every session file this way at a
start, so a history whose prompts carry pasted screenshots (each a
multi-MB base64 line) allocated GBs in scanAt alone.

On the first overflow of a plain file's line, scanAt now reads ahead
(ReadAt, which moves nothing) to the line's end and gathers it into one
buffer of exactly that size. A line longer than maxLine plus the buffer
is stepped over at once, as before, but without being gathered first. A
packed (zstd) file, or a line with no end yet, keeps the old path.

Tests (internal/sessions/scan_buffer_test.go):
- TestScanGathersALongLineOnce: an 8 MiB line and a short one are both
  handed over whole, and the scan allocates at most 1.5x the line.
  Fixed: 9,451,632 bytes for an 8,388,633-byte line (bound 12,582,949).
  With the read-ahead turned off by hand: red, "allocated 36856408
  bytes".
- TestScanStepsOverATooLongLineUngathered: a maxLine+4 MiB line is
  stepped over and the next line read, with at most 8 MiB allocated.
  Fixed: 1,049,032 bytes. Turned off by hand: red, "allocated 175179080
  bytes".

Measured: a sandbox `magpie web` on a fixture HOME (150 Claude Code
sessions, each with six 4 MiB pasted-image prompts, 3.5 GB), main and
panel pages loaded in Playwright Chromium, heap profile at ~2.5 min,
macOS at a load average of ~290, two runs each:

                        allocated   in scanAt   peak RSS
  base 5b267fbd8         3.97 GB     3.31 GB     394 MB
  base 5b267fbd8         4.05 GB     3.37 GB     277 MB
  this commit            1.52 GB     1.14 GB     109 MB (pages failed to load)
  this commit            1.89 GB     1.20 GB     348 MB

What allocation shows is halved; peak RSS on this loaded machine is
noise (277-394 MB on the base) and does not show a change. The #2515
report's 3.2 GiB peak (v0.1.1265, Windows) was not reproduced: on a
5,501-file fixture v0.1.1265 peaked at 250 MB RSS and the base at 288
MB, and on 950 MB of large sessions the base peaked at 256 MB. This
commit is not claimed to be its cause; it is the largest start
allocation left on these fixtures.

Run in a sandbox HOME, Go caches pinned:
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/usage/:
  both ok (959s, 272s), set -o pipefail.
- gofmt -l internal/sessions: none. go vet ./internal/sessions/,
  GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet -tags
  nogui ./...: all exit 0.
- Not run: the full suite, the GUI suite (no asset changed), the
  Windows box.
2026-10-20 20:23:50 +08:00
yetone 28bec1507c settings: lightweight mode is on for a user who never chose it, and off for one who turned it off
The owner: 改成默认开,只对没设过的用户. A webview kept for good holds what
its page drew while hidden, which grew ~20 MB a minute on Windows under
steady requests (#2515); lightweight mode lets it go.

- settings.Lightweight is a *bool: nil (never chosen) is on, false is
  off, true is on. LightweightOn() says which; gui/lightweight.go reads
  it. KeepOwn still keeps this computer's value on a sync or a restore.
- app.js shows On unless lightweight is false, and the prefs save sends
  s.lightweight as it is: unchosen stays out of the JSON, so saving
  another setting doesn't choose it.

Caveat: until now Off was a bool with omitempty, so it was never stored.
A user who chose Off before this can't be told from one who never chose,
and gets On. Only choices made from this release on are kept.

Tests:
- settings TestLightweightKeptAndOwn: on when unset, Off saved reads back
  off, another save keeps it off, KeepOwn keeps this computer's Off over
  the other's On, and an empty one stays unset. Broken by hand
  (`!= nil && *`) it fails "off for a user who never chose".
- lightweight.test.cjs: On shown for a user who never chose; another
  setting's save posts no lightweight; Off posts false and shows Off;
  another save keeps false; On posts true; nothing scrolls. Its viewport
  is 1200 tall: rows added above had put Off under the window's foot
  (y≈1008 of 1000), where the mouse click did nothing.
- segs-glide and segs-press-redraw start from a user who turned it off,
  so On is still a pick away; README's lightweight line says the new
  default.

Run at this commit's parent (the #2683 test fix on origin/main
f73378365), chromium 1234 and webkit 2336, playwright 1.62.0:
- lightweight, segs-glide, segs-press-redraw, settings-general
  (--test-concurrency=1): 90 of 90. These are every GUI file that reads
  lightweight (grep); no others reach it.
- go test -timeout 45m ./internal/settings ./internal/gui: ok (gui 554s).
- gofmt -l internal/: nothing. GOOS=linux and GOOS=windows go vet -tags
  nogui ./...: clean.

Not tried: the real app's webview being let go after this change on
Windows or Linux; the release path is the same as with On chosen before.
2026-10-20 20:23:50 +08:00
yetone 031715d5e4 gui tests: segs-glide names each control by the nearest id above it and brings an option wholly into view (#2683)
segs-glide was red 20 of 20 on origin/main. Two causes, both in the test:

- It named a control by its parent's id, or else its options' kind.
  Full window's and Codex async's controls both sit in a .compact-at
  with no id, so both were "off|on", and Codex async's 38px thumb was
  compared with Full window's 118px one: "off|on's thumb moved
  (2.0/38.0 → 2.0/118.0)". A control is now named by the nearest id
  above it, and oneWay fails when two controls share a name.
- Behind that, en 440px failed "a click never moves the page" (160 vs
  150): reveal stopped once the option's middle was on screen, with its
  foot cut by the view's (button bottom ~979, view bottom 972), and
  Playwright's click scrolled it in by itself. Pressed by hand (mouse
  down/up, no locator.click) nothing scrolled. reveal now waits until
  the whole option is inside #view-settings.

Run at origin/main f73378365 (chromium 1234 and webkit 2336, playwright
1.62.0): segs-glide.test.cjs 20 of 20 (both engines, en/zh/zh-TW/ja/de,
900px and 440px), --test-concurrency=1. Before: chromium en 900/440 red
the same way as the issue, and en 440 red 3 of 3 on the scroll check
once the name was fixed. Broken by hand: with the old naming the new
guard fails "answer mid-glide: two controls under one name".
2026-10-20 20:23:49 +08:00
keeuu 75e769a9f9 routing: Free first spends the models that cost nothing before the ones that spend (#3054)
A provider or group can be routed `free`. Seats whose model the vendor
serves at no cost to the allowance or credits go first, in listed order.
The rest follow, also in listed order. Free means the vendor's own
catalog.Model.Free word, or else a $0 list price on every count
(provider.FreeModel). A pool with no free model behaves as In order.

routes.Seat gains Free and Strategy gains ByFree. weighRouted works Free
out only for a strategy that weighs by it, so other routings never read
a model list for it.

It is wired through every list a routing appears in:
- both save whitelists;
- plugins/rotation's Builtin;
- app.js's ROUTINGS (appScriptBudget 1,269,000 → 1,271,000 for the
  description) and the Routing page's options, hints and trace text;
- zh-TW, ja and de strings;
- the TUI's routings;
- the CLI's aliases (free, free-first).

Written by keeuu (issue #3054, three commits), squashed onto dee5c9d75
and reviewed:
- the harm checks were clean;
- FreeModel runs only for ByFree, so its Available() walk costs nothing
  for other routings;
- accounts can list different models, so Free first means something for
  a provider's own accounts too, not only for groups.

Run at this head:
- gofmt -l: clean.
- go vet: darwin (internal/routes, provider, gateway, cli, tui, gui);
  GOOS=windows ./internal/...; GOOS=linux -tags nogui ./... — all clean.
- go test ./internal/routes ./internal/provider -run
  'Free|Routing|Strateg|Builtin' ok; ./internal/gateway -run
  'FreeFirst|Weigh|Routing' ok.
- Broken by hand: with FreeFirst returning paid before free,
  internal/routes' Free tests and
  TestFreeFirstGroupSpendsTheFreeMemberFirst go red. Restored, green.
- go test ./... -count=1 -timeout 45m, at load average ~460 from other
  sessions: 62 packages ok, 3 red:
  - internal/gui TestMainWindowCorners (#1936/#2645, AppKit window
    killed at its deadline under load);
  - internal/gateway TestClaudeAccountsSpentFallBackToCodex ("no
    answer"): ok alone in 46s;
  - internal/agent timed out at 45m inside TestSnowSmallModel (1s in):
    the package is ok alone in 1519s.
- GUI, both engines (node --test, playwright 1.62.0), 23 files:
  account-arrange, builtins, context-text, context-scroll-end,
  context-window, group-member-weight, key-weight, rate-limited-sink,
  routing-reset-deadline, routing-compaction, routing-key-windows,
  routing-save, routing-sealed-task, routing-weight-chip, search-keys,
  i18n-keys, panel-routing-pick, panel-routing-providers, panel-routing,
  routing-columns, gui-de, gui-ja, gui-zh-tw. 230 of 236 pass.
  routing-save (the 6/7 counts), routing-columns, i18n-keys and the three
  language files are green.
  - account-arrange "every mode" (#2200): red in both engines, alone,
    and on origin/main dee5c9d75 too.
  - builtins chromium "Plugins › Built-in" (#2960): a 5s wait for the
    Plugins page. Red alone and on dee5c9d75 too; the webkit run checks
    the new Routing strategies subtitle and passes.
  - context-window and context-text, single cases in different
    language/engine pairs on each run: 5s waits under load (#1544,
    #2900). Untouched by this change.

Co-authored-by: keeuu <159448501+keeuu@users.noreply.github.com>
2026-10-20 20:08:25 +08:00
yetone dee5c9d75f site: 零词元's README link goes to their own tracking link
零词元 asked by mail (10-20) for their README logo to send clicks to
https://zzq.si/go/22zuh4a, so they can count what the seat brings.
/go/zerotoken/readme now redirects there instead of https://zzq.si.

Run: node --test site/worker.test.mjs (20 pass). Deployed and checked
with curl on usemagpie.ai (see the reply to this commit's push).
2026-10-20 16:32:30 +08:00
yetone 2374ffe161 gateway: a request whose agent goes while it waits for room ends its wait before giving its place back
TestMaxRPMAgentGoneWhileWaiting went red on ubuntu CI at 588f87a12
("1 still waiting for room after the agent went"). On a cancel, wait gave
the place back first and stopped its timer only in a defer after, so the
test could see the place back while the wait was still registered. The
wait now stops its timer, then gives the place back.

Run:
- Injected a 100ms pause after giveBack: the old order is red 3 of 3,
  the new order green 3 of 3.
- go test -race -run TestMaxRPM -count=10 ./internal/gateway: ok.
- go test ./... -count=1 -timeout 45m (load ~200): every package ok except
  internal/gui, where TestMainWindowCorners and TestMainWindowRightToLeft
  were killed at their deadline (#1936, #2645). Run alone: ok in 36s.
- gofmt -l clean.
2026-10-20 14:11:21 +08:00
yetone 588f87a126 gui: the Routing page measures a path again only when it moves (yg6888 on X: "打开页面很卡")
yg6888 on X: the Routing page lags, with 29 accounts in a group, nested
sub-groups and three agents sending at once.

Cause: every frame posed every flight, and each pose measured the paths
it flies along and the wire ends it meets with getTotalLength and
getPointAtLength, again on every frame. Each render also re-set every
via's "d" and formatted every row's token counts with a new
Intl.NumberFormat (toLocaleString).

Fix:
- measure() keeps a path's length in a WeakMap and measures again only
  when its "d" changes.
- tip() keeps its result.
- A via's "d" is set only when it changed.
- pointAt() reads points measured every 8 px along a path, cached per
  "d", and interpolates between them. The chord is off by under a
  pixel.
- ledNum uses one Intl.NumberFormat per language.
- metaFit runs only when rows were redrawn.

Numbers: CPU profile of the page for 40 s under a busy sandbox gateway,
machine load ~250:

                    main thread  rAF calls  per call  getPointAtLength  getTotalLength  ledNum
  before            28.0 s       4047       6.9 ms    5.58 s            5.04 s          1.13 s
  after             15.9 s       3635       4.4 ms    1.50 s            0.50 s          0

The GUI test counts per frame: ~15 lengths and ~27 points before, ~4
lengths and 13-16 points after. Paths still move during the rows' FLIP
slide and the agent tick, and they are measured again then.
renderHist's own time (~1.8 s) and getBoundingClientRect (~1.2 s) are
not changed here.

Test: routing-busy-frames.test.cjs, in Chromium and WebKit, en/zh/de.
It pumps three agents' requests and asserts fewer than 8 lengths a
frame, fewer than 200 formats, and token titles grouped in the page's
language. Red on the old client.js and app.js. Example green:
"chromium en 382 frames, 1519 lengths, 4864 points, 0 formats".

Run record, the three commits on origin/main d9c6a60d8 (machine load
~270-480, with other sessions' GUI suites running):
- gofmt -l: clean. go vet ./... on darwin, GOOS=windows and
  GOOS=linux -tags nogui: exit 0.
- go test ./... -count=1 -timeout 45m (sandbox HOME, 11:02-11:34): 64
  ok, 1 FAIL: internal/gui TestCoreScriptBudget, app.js 155 bytes over
  from the first ledNum. ledNum was made smaller (1,268,907 of
  1,269,000 bytes), then internal/gui -count=1 alone: ok (329 s).
- Before the rebase (723f40778 on 9588501c0): internal/gateway ok
  (2064 s), internal/agent ok at -timeout 120m (it timed out at 45m
  at load ~700, #2869), internal/gui red only in
  TestSetAnswersWhileDevinAndProvidersHang (#1375).
- GUI suite, all 140 files, Chromium and WebKit, every language, at
  load 400-840 on 723f40778. Every red was run alone against
  9588501c0, and none comes from this change: routing-bodies
  (#2559/#2658), routing-keys-fold and routing-model-rest (#2658),
  routing-mode-goes WebKit (#2151, head 2/20 vs base 3/20),
  routing-request-metrics (#2571), routing-wb-restricted (#1905),
  usage-agents-hide (#2276/#2399), usage-fold (#2399), usage-checkin
  WebKit Qoder (#2549), usage-refresh (#2184). 5 s first waits under
  load were added to #2900. The usage-ledger route-callback race at
  page close was filed as #3001.
- After the rebase, each alone in both engines: routing-busy-frames,
  routing-intent-entry, routing-key-windows, routing-pause and
  usage-ledger were green.
- After the smaller ledNum, each alone, both engines, all languages:
  routing-busy-frames 6/0 (one later run lost Chromium's launch at
  180 s twice; Chromium alone right after: 3/3), usage-ledger
  Chromium 16/16 and WebKit 17/0. usage-ledger-leave and
  routing-request-metrics were red in browser launch and 5 s waits on
  this head and on d9c6a60d8 alike (#2900, #2571). Added to #2900:
  a WebKit zh usage-ledger run hung after a 5 s timeout.
2026-10-20 13:26:12 +08:00
yetone 68133754a3 gateway: a request's body is read in place, not copied by every reader (yg6888 on X: ~1 GB)
yg6888 on X: "magpie 占用内存有点高 随时1个g", with a group of 29
accounts and three agents sending at once.

Cause: each reader of a request decodes its turns into json.RawMessage
values (the images walk, the conversation id, the prompt, the edits, the
chat parse), and decodeJSON copied each value it filled, as
encoding/json does. A 1.5 MB conversation allocated ~42.8 MB on its way
through a group. Three agents at once kept the heap in the hundreds of
MB, and the GC ran behind it.

Fix:
- readRequestBody holds the body (holdBody) until the request's context
  ends. A RawMessage decodeJSON fills from inside a held body shares the
  body's bytes, capped so an append can't write into it. The body must
  be at most 16x the value (heldShareMost), so a small value kept past
  its request (a cache entry, a signature) never pins a whole body.
  Anything not held is still copied: a stream's buffer, a scanner line,
  a body built and changed in place. The list is bounded at 64 bodies
  (heldBodiesMost) and each leaves it through context.AfterFunc.
- The ratio leaves a long conversation's many small turns copied, so
  the two readers that run on every request take them in place:
  - conversationID takes the turns with elementsOf, slices of the
    body.
  - walkImages, which runs several times a request, first scans the
    turns without decoding (anyImageBlock/anyImageIn) and returns at
    once when there is no image. Keys and kinds are compared with
    jsonStringIs, so an escaped "type", a duplicate key, a tool
    result, a Responses function_call_output and Gemini's inlineData,
    fileData and functionResponse still count.

Numbers: sandbox gateway, fresh process each run, 150 requests of a
1.5 MB conversation, 3 at once through a group, machine load ~250:

                    peak RSS  HeapSys  GCs  allocated   bytes.Clone
  before            273 MB    222 MB   117  6416 MB     3635 MB
  held bodies       233 MB    186 MB    74  3379 MB     1480 MB
  + id/image scan   223 MB    174 MB    64  2853 MB      927 MB

That is ~42.8 MB allocated per request before and ~19 MB after. What is
still copied comes from the translators (stringOrText, editMessages,
parseChat, responsesContent), unquoteJSON (~670 MB), io.ReadAll
(~480 MB) and rewriteModel (~225 MB). None of these is changed here.

Tests:
- TestRequestBodyRawValuesShareIt, TestDecodeJSONCopiesWhatIsNotHeld and
  TestHeldBodiesBounded (fastjson_held_test.go).
- TestImageWalkReadsTextOnlyTurnsInPlace: a 938 KB text-only
  conversation allocates under len/8 per walk plus id, and eight image
  shapes are still found.

Broken by hand, each red:
- no share cap
- no ratio
- no bound
- no release
- pre-scan removed (8,780,204 B per iteration)
- tool_result skipped (case not found)
- id decoding each turn (1,044,859 B over the 117,265 limit)
- kind compared as raw bytes (the escaped case is not found)

No subsystem page covers decodeJSON.

Run record, the three commits on origin/main d9c6a60d8 (machine load
~270-480, with other sessions' GUI suites running):
- gofmt -l: clean. go vet ./... on darwin, GOOS=windows and
  GOOS=linux -tags nogui: exit 0.
- go test ./... -count=1 -timeout 45m (sandbox HOME, 11:02-11:34): 64
  ok, 1 FAIL: internal/gui TestCoreScriptBudget, app.js 155 bytes over
  from the first ledNum. ledNum was made smaller (1,268,907 of
  1,269,000 bytes), then internal/gui -count=1 alone: ok (329 s).
- Before the rebase (723f40778 on 9588501c0): internal/gateway ok
  (2064 s), internal/agent ok at -timeout 120m (it timed out at 45m
  at load ~700, #2869), internal/gui red only in
  TestSetAnswersWhileDevinAndProvidersHang (#1375).
- GUI suite, all 140 files, Chromium and WebKit, every language, at
  load 400-840 on 723f40778. Every red was run alone against
  9588501c0, and none comes from this change: routing-bodies
  (#2559/#2658), routing-keys-fold and routing-model-rest (#2658),
  routing-mode-goes WebKit (#2151, head 2/20 vs base 3/20),
  routing-request-metrics (#2571), routing-wb-restricted (#1905),
  usage-agents-hide (#2276/#2399), usage-fold (#2399), usage-checkin
  WebKit Qoder (#2549), usage-refresh (#2184). 5 s first waits under
  load were added to #2900. The usage-ledger route-callback race at
  page close was filed as #3001.
- After the rebase, each alone in both engines: routing-busy-frames,
  routing-intent-entry, routing-key-windows, routing-pause and
  usage-ledger were green.
- After the smaller ledNum, each alone, both engines, all languages:
  routing-busy-frames 6/0 (one later run lost Chromium's launch at
  180 s twice; Chromium alone right after: 3/3), usage-ledger
  Chromium 16/16 and WebKit 17/0. usage-ledger-leave and
  routing-request-metrics were red in browser launch and 5 s waits on
  this head and on d9c6a60d8 alike (#2900, #2571). Added to #2900:
  a WebKit zh usage-ledger run hung after a 5 s timeout.
2026-10-20 13:26:05 +08:00
yetone bdf4d7a9cc gateway: a Chat request is decoded for silent assistant turns only when it has one (yg6888 on X)
yg6888 on X: "magpie 占用内存有点高 随时1个g", with three agents
sending at once through a group.

Cause: silentAssistantsOut runs on every attempt of every Chat request
relayed as sent. It decoded every message into a map to find assistant
turns that say nothing, and almost no request has one. For a 1.5 MB
conversation that cost ~4 MB a request, the gateway's largest
allocation after the body itself.

Fix: anySilentAssistant scans the messages in place first.
- Only an assistant turn whose content has no visible ASCII text is
  decoded, and silentAssistant still makes the call on it.
- A request with no such turn returns unchanged without a decode.
- Role and content are compared with jsonStringIs, which unquotes only
  a string that has an escape in it. An escaped "assistant" still
  counts.
- textSaysSomething passes over escapes, so "\n" or an escaped U+3000
  is left for silentAssistant to judge.

Behaviour is unchanged. docs/subsystems/gateway-routing.md describes
silentAssistantsOut, and the description still holds.

Test: TestSilentAssistantsOutDecodesOnlyAssistants. It covers an
escaped role, a literal U+3000, escaped whitespace, and the allocation
of a text-only conversation. Broken by hand, each red:
- pre-scan removed (allocation over the bound)
- role compared as raw bytes (402 messages kept vs 401)
- escapes read as text (402 vs 401)

Run record, the three commits on origin/main d9c6a60d8 (machine load
~270-480, with other sessions' GUI suites running):
- gofmt -l: clean. go vet ./... on darwin, GOOS=windows and
  GOOS=linux -tags nogui: exit 0.
- go test ./... -count=1 -timeout 45m (sandbox HOME, 11:02-11:34): 64
  ok, 1 FAIL: internal/gui TestCoreScriptBudget, app.js 155 bytes over
  from the first ledNum. ledNum was made smaller (1,268,907 of
  1,269,000 bytes), then internal/gui -count=1 alone: ok (329 s).
- Before the rebase (723f40778 on 9588501c0): internal/gateway ok
  (2064 s), internal/agent ok at -timeout 120m (it timed out at 45m
  at load ~700, #2869), internal/gui red only in
  TestSetAnswersWhileDevinAndProvidersHang (#1375).
- GUI suite, all 140 files, Chromium and WebKit, every language, at
  load 400-840 on 723f40778. Every red was run alone against
  9588501c0, and none comes from this change: routing-bodies
  (#2559/#2658), routing-keys-fold and routing-model-rest (#2658),
  routing-mode-goes WebKit (#2151, head 2/20 vs base 3/20),
  routing-request-metrics (#2571), routing-wb-restricted (#1905),
  usage-agents-hide (#2276/#2399), usage-fold (#2399), usage-checkin
  WebKit Qoder (#2549), usage-refresh (#2184). 5 s first waits under
  load were added to #2900. The usage-ledger route-callback race at
  page close was filed as #3001.
- After the rebase, each alone in both engines: routing-busy-frames,
  routing-intent-entry, routing-key-windows, routing-pause and
  usage-ledger were green.
- After the smaller ledNum, each alone, both engines, all languages:
  routing-busy-frames 6/0 (one later run lost Chromium's launch at
  180 s twice; Chromium alone right after: 3/3), usage-ledger
  Chromium 16/16 and WebKit 17/0. usage-ledger-leave and
  routing-request-metrics were red in browser launch and 5 s waits on
  this head and on d9c6a60d8 alike (#2900, #2571). Added to #2900:
  a WebKit zh usage-ledger run hung after a 5 s timeout.
2026-10-20 13:25:58 +08:00
yetone d9c6a60d8a Merge commit '791604559' into pf/serve 2026-10-20 06:17:10 +08:00
yetone 3806014ac8 redact: Chinese personal names are masked, where the model misses or overreaches them (#1977)
OpenAI's Privacy Filter gives common Chinese names (张伟, 李娜, 陈建国,
黄晓明) almost no PERSON weight. Lowering the O label's emission by 2 or
4 in a patched pf-serve didn't bring them back. It also returns spans
that run past the name (「王芳,她下周一」, 「张伟先生」).

zhname.go adds a rule layer behind the model, only when personal data
is covered:
- a surname (single, compound, or 小/老 + surname) with a 1–2
  character given name is masked when something around it says it is
  a person:
  - a role before it (客户, 联系人:, 我叫, 作者:, @);
  - a verb before it (给, 告诉, 抄送) or after it (说, 反馈, 先生);
  - a title or 总 (孙经理, 邓总);
- a name joined by 和/与/跟/及/、 to a name already found counts too;
- words that start with a surname (张量, 高度, 王国, 周五, 总是) are
  never taken;
- the model's PERSON spans with Han in them are cut at punctuation or a
  title, and only when at least two characters remain.

Run:
- Real model, end to end through MaskJSON (pf-serve q8, Metal):
  - masked 张伟, 王芳 (cut), 李娜, 刘洋, 陈建国, 赵丽颖, 欧阳娜娜, 司马光,
    黄晓明, 周杰伦, 小王, 老李, 马云, 王老板, 邓总, 孙经理, 刘总监,
    吴敏, 郑浩, 何静, 唐宁, 许文强, 罗志祥, 林老师 and 郭靖;
  - Japanese, Korean and English names are unchanged.
- Missed, with nothing around them that says person: 「模块是谢磊写的」
  and 「和黄蓉团队」.
- False positives: none over 2237 lines of the repo's Chinese docs and
  i18n, or 61 developer sentences.
- Cost: ~19ms CPU over 880KB.
- Broken by hand:
  - with the layer off, TestChineseNames has 8 names unmasked;
  - with the two-character guard off before a title, 感谢李老师 goes red.
- Checks:
  - gofmt -l is clean;
  - go vet is clean on darwin, GOOS=linux -tags nogui and GOOS=windows.
- go test ./... -timeout 45m at load ~750: 63 packages ok, redact
  among them. internal/agent (TestReconnectKeepsTheLastPick) and
  internal/gateway (TestLargeRequestEndpoints) hit the 45m timeout with
  no failed assertion, and are being rerun alone.
2026-10-20 05:15:19 +08:00
yetone 7916045591 library: RTK's tag for Grok Build and Grok App gives their own reason and rtk-ai/rtk#2136, not DeepSeek Harness's (新v学员 on Discord)
Every agent RTK has no hook for got dsh's tooltip on the RTK tab: "{agent}'s
hooks can only allow or deny a command, not change it" with
rtk-ai/rtk#3847 ("FR: Support DSH"). For Grok Build that is wrong twice:
the issue is dsh's, and Grok's PreToolUse hooks can rewrite a command
(updatedInput, shown on rtk-ai/rtk#1890). What holds is that rtk init has
no Grok agent (src/hooks/init in rtk v1.0.1 has none), and
rtk-ai/rtk#2136 is the open request for Grok Build (#4513 was closed as
its duplicate). Each link was checked with gh issue view; the others in
rtk.go (#3847, #3934, #4311, #3898, #4187, #3404) are right.

rtkNoHookWhy in plugins/library/client.js gives each agent its own reason:
dsh keeps its text and #3847, Grok Build and Grok App cite #2136 (Grok App
runs Grok Build), and an agent with no entry gets a reason with no link.
New strings in zh, zh-TW, ja and de. rtk.go's grok and grok-app reasons,
which the CLI shows, cite #2136 too.

TestRTKNoHookIssuesAreEachAgents fails when an rtkNoHook agent has no page
reason (or the reverse), when the page and rtk.go cite different issues,
when two agents cite the same issues without a reason in sharedRTKIssues,
or when the fallback carries a link. library-rtk-nohook.test.cjs checks
Grok Build's tag says #2136 and never #3847, DeepSeek or "hook".

Run in a worktree rebased on origin/main 16327872c, sandbox HOME, caches
pinned:
- Broken by hand: with the old client.js the new test fails "client.js has
  no rtkNoHookWhy: the no-hook tag isn't per agent"; with Grok's page link
  set to #3847 it fails "dsh and grok both cite [rtk-ai/rtk#3847]: one's
  reason was copied onto the other". Restored, it passes.
- gofmt -l on the changed Go files: empty. 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 (before the rebase).
- GUI: i18n-keys plus all 39 library-*.test.cjs, Chromium 351/351 and
  WebKit 351/351.
- set -o pipefail; go test -timeout 45m ./... at load ~500-650: 60
  packages ok; 4 red, none in the code changed here, each already filed:
  internal/agent timed out at 45m (#2544), internal/gateway timed out at
  45m (#2870), internal/gui TestSetAnswersWhileDevinAndProvidersHang
  10.4s set under load (#1375), internal/library
  TestCheckStdio/timeout_ends_the_tree (#2765). go test ./internal/library
  -run 'RTK|TestCheckStdio' then passed (136.9s).
- Not tried: the real app with a real Grok Build install; the change is
  tooltip text and links only.
2026-10-20 04:13:35 +08:00
yetoneandLoKi 822f2b3042 agent: dsh lists a vendor's reply limit at most a quarter of the window, so it has room to compact (#2823, LoKi on Discord)
dsh takes a model entry's maxTokens as the output of every request. Before
deciding when to compact, it reserves that output plus 65536 of headroom
out of contextWindow (dsh-compaction-basic resolveCompactSpec). When a
vendor's reply limit is close to its window, dsh compacts at a sliver of
the window, or can't compact at all. magpie now lists a vendor's figure
held to a quarter of the window (dshMaxTokens). It does this on every
pi-ai route and in the legacy llm-deepseek entry, the same rule VS Code
and Copilot in JetBrains already use. A Max output the user set stays as
they set it (outputOr).

LoKi's patch capped only an output >= the window. That misses #2823's own
case (a group at 500000 / 393216) and outputs above window - 65536, such
as 131072 / 65536. The quarter rule covers all of them, and a cap can only
lower the reservation.

Run: real dsh 0.2.0-rc.2 headless, sandbox HOME/DSH_HOME, a fake OpenAI
SSE server with a tool-call step so pre-step compaction runs, and an
observe-only loader hook on resolveCompactSpec.

  origin/main e5b57794e:
    524288/524288   "leaving no message budget"
    500000/393216   threshold 41248
    131072/65536    "leaving no pressure budget"
    1000000/393216  threshold 541248

  this change (maxTokens / threshold / retain):
    524288   131072 / 327680 / 62914
    500000   125000 / 309464 / 60000
    131072    32768 /  32768 / 15728
    1000000  250000 / 684464 / 120000

  The request's max_tokens matches each new value.

Tests: TestDshOutputLeavesCompactionRoom (every route plus legacy;
vendor, user-set, unknown window and unknown output cases).
TestDshModelLimits now expects 100000 for 400000/128000, and
TestMaxTokensWithinContextWindow (the every-agent guard, which the first
full run caught) holds dsh to a quarter of a known window.
Broken by hand:
  - dsh.go reverted: 4 vendor cases and TestDshModelLimits red.
  - Only the legacy writer reverted: 4 llm-deepseek failures.
  - outputOr dropped: the user-output cases red.
  - Old dsh.go under the new TestMaxTokensWithinContextWindow: 3 dsh rows
    red (32000, 51200, 16000).

Checks: gofmt -l clean. go vet darwin, linux -tags nogui and windows ok.
go test -timeout 45m ./... at e5b57794e plus this change, before the
sync_test fix: every package ok except internal/agent, where
TestMaxTokensWithinContextWindow was red (fixed here), and
internal/gateway, where TestDesktopSubagentUnsetDoesNotDecode was red (1
alloc, want 0). That is #2699, an allocation counted from another
goroutine in a whole-package run. It passes alone -count=3, and this
change touches no gateway code. After the fix, internal/agent ran whole
and was ok (2084s), and vet on all 3 OSes was ok again.

The Windows TempDir flake LoKi saw in
TestDshSetEffortWritesALegacyEntryWithTheCatalog did not reproduce: 10
runs of ^TestDsh on the Windows box passed. A goroutine/file probe at
each TestDsh cleanup (macOS and Windows) found no late writer. Filed as
#2982.

Co-authored-by: LoKi <317300729+lokic7123-star@users.noreply.github.com>
2026-10-20 03:12:29 +08:00
yetone 5f73537f5b gateway: Codex's own turn on one ChatGPT account is asked again on an overload, then its fallbacks (夜松云 on Discord)
Codex signed in to ChatGPT with magpie as openai_base_url, one account,
no usage cap: Codex's own gpt-* turns go through codexUpstreamOn with no
account, relayed as Codex sent them. That path was pass-through since
0f0b8fc87 because routing was only built for more than one account, and
the relay keeps Codex's own token, request bytes and headers, streams at
once, and keeps native compaction with the backend (#2582). It also
meant no retry and no fallback: a 529, or the backend's in-stream
response.failed server_is_overloaded (#1418), went straight to Codex,
which doesn't retry ServerOverloaded itself.

Now, on that path only (POST /responses to the ChatGPT backend, no
account picked):
- a transient overload (codexBusy: busy() minus 429, edgeSaidDrop and
  codexReset) is asked again of the same account, same body and
  headers, up to lastRetries times after retryPause<<n, as the accounts
  loop asks its last account; only before any reply byte reached Codex;
- a stream is held through a holdWriter with reasoning let through
  (thinkingShown) and one keptAlive across tries, so Codex gets the
  stream's keepalives, never a failed try's frames;
- once retries are spent, a codex subscription with fallbacks
  (codexFallsBack, never a compaction) goes on to them: codexFallBack
  serves codex/<model> with this account left out (fallbacksOnly via
  handedOnKey) and the same keepalive; without fallbacks Codex gets the
  last try's failure as before;
- nothing rests; each try is a HandedOn usage record and a trace try.
A success is relayed as before; nothing is held when no retry or
fallback is left. Prompts, base_instructions and Codex's bytes/headers
are untouched.

Docs: docs/subsystems/gateway-routing.md. No README/site page said one
account is relayed unchanged (grepped en/zh/ja).

Tests: codex_one_account_overload_test.go (529 then 200; #1418 stream
then answer; bounded 1+lastRetries for status and stream; falls back
for status and stream; 400 asked once; kept alive with and without a
fallback). Each overload test fails on ef655acb4 (one request, the
overload relayed); the refusal test passes there, as it should. Broke
by hand: without the fallbacksOnly hook the FallsBack tests go red
("ChatGPT asked 4 times").

Run (sandbox HOME, at ef655acb4 + this change):
- go test -run 'Codex|Overload|Fallback|Patience|Hold' ./internal/gateway: ok
- go test -race -count=5 -cpu 1,4 on the new tests,
  TestCodexOwnModel*, TestCodexResetJudgedByTheBytesSent: ok
- gofmt -l: clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: ok
- set -o pipefail; go test -timeout 45m ./...: 61 packages ok, internal/gateway
  included (2633s); load average ~200-250. Three reds, each already
  filed, none in code this touches:
  internal/gui TestSetAnswersWhileDevinAndProvidersHang (#1375, passes
  -count=3 alone), internal/library
  TestRTKCheckLatestDoesNotWaitForThePackageManager (#2848, passes
  -count=3 alone), internal/agent past 45m (#2723; alone with
  -timeout 90m: ok, 3226s)

- rebased on fb101b0d5: gofmt, the three vets of internal/gateway and
  go test -run 'Codex|Overload|Fallback|Patience|Hold' ./internal/gateway: ok

- rebased again on 16327872c (internal/provider only): go vet
  ./internal/gateway ./internal/provider: ok
2026-10-20 03:04:43 +08:00