Commit Graph
7089 Commits
Author SHA1 Message Date
yetone 2201b66285 provider: the Qoder mover's min is 0.2.24, where Qoder's 400 "Error in upstream response" is a 502 (SlouchyQuill507 on Discord)
SlouchyQuill507 (Discord, qoder-cn) found Qoder's failures of the model's
own vendor, "Error in upstream response", reaching magpie as a 400: the
client's fault, never asked again or of another account. That runs in
the plugin for moved users, so the fix is
@magpie-community/opencode-qoder-auth 0.2.24 (plugins 4af310c,
"qoder 0.2.24"), which answers it as a 502 and keeps genuine 400s (Qoder's
request codes, other invalid requests) as 400. Raising the mover's min
makes keepMovedCurrent update every moved user to it. tooLongUnsaid still
tells an overflow that fails this way apart by its size, at 502 as at 400.
npm view @magpie-community/opencode-qoder-auth@0.2.24 version
--prefer-online: 0.2.24.

The same plugins push has cline 0.1.10 (the plugin's side of d2c434b5a:
glm-5.3-flash pinned by OpenRouter's provider.only ["z-ai"]); Cline has no
mover, so nothing here names its version.

Run at 0fe039f14 plus this change: gofmt -l (none); go vet ./... on darwin,
GOOS=linux -tags nogui and GOOS=windows: clean.
set -o pipefail; GOMODCACHE=/Users/yetone/go/pkg/mod go test -timeout 45m ./...:
62 packages ok; internal/agent, internal/gateway and internal/library hit
the 45m timeout with load average near 100 from other sessions' suites
(the tests running at the timeout had run 0-7s, no hang in the stacks).
Rerun of those three alone at load ~30: ok (agent 1345s, gateway 1130s,
library 914s), exit 0.
Rebased onto 4ae6c06dc (Codex compaction, routing, GUI tests; nothing in
internal/provider/migrate_qoder.go): gofmt -l (none), the three vets of
internal/provider and go test ./internal/provider/ ok (216s).
2026-10-21 03:18:24 +08:00
yetone 4ae6c06dc3 docs: gateway-routing says how magpie's Codex compaction is made portable
The magpie1: item, the message codexInputAs sends for it, and
sessions.PortCodexRollouts: what it changes, the writer-lock protocol, when
it runs, what was tried (Codex 0.162.1 resume against an upstream that
refuses magpie1: as OpenAI does) and what wasn't (a Codex in WSL).
2026-10-21 03:05:24 +08:00
yetone 19901812e7 gateway: a ported Codex rollout reads the same through magpie as magpie's compaction item did
TestPortedCompactionReadsTheSame: codexInputAs sends the same input for
magpie's item and for the message sessions.PortCodexRollouts writes in its
place, for a magpie model (native or not) and for Codex's own.

Run: go test ./internal/gateway -run TestPortedCompactionReadsTheSame.
2026-10-21 03:05:24 +08:00
yetone 4896fc3ba1 codex: a thread magpie compacted goes on after magpie is quit or disconnected (LukeMa on X)
When magpie answers Codex's compaction itself (a magpie model, Codex's
own models through magpie's accounts, a CC Switch table), the item it
returns carries encrypted_content "magpie1:"+base64(summary). Codex keeps
it in the rollout (a response_item, and the compacted checkpoint's
replacement_history) and replays it with every later turn. Sent to the
ChatGPT backend directly, it is refused: "The encrypted content for item
cmp_magpie_1 could not be verified ... invalid_encrypted_content"
(probed with a real request on gpt-5.6-luna; the same summary as a user
message was answered).

Codex's remote compaction v2 keeps exactly one Compaction item, so magpie
can't answer with a plain message instead. sessions.PortCodexRollouts
writes each of magpie's items in a rollout as the message it stands for
(codexsummary.Message: Codex's summary prefix, a newline and the summary,
as a user message), which is what Codex's own local compaction stores and
what the gateway already sends in its place, so it reads the same through
magpie and goes on without it.

- Only magpie's compaction items change; other lines keep their bytes,
  the file its line count, mode and time. An unreadable one is left out
  of a list with its replacement_history_metadata entry, as Codex's own
  ghost-snapshot strip does.
- Published as Codex publishes a compressed rollout: temp file and
  rename, under thread-writer-locks/.coordination.lock and only with the
  thread's lock free. A thread a Codex has open is left for a later pass.
  A Codex home without thread-writer-locks is left alone.
- .jsonl.zst rollouts are read and written packed.
- Passes: 2 minutes after the GUI or magpie serve starts and every 10
  minutes; on Codex Disconnect (3s); as the GUI quits (3s). The first
  pass reads rollouts written since 2026-09-24; later ones only what
  changed since the last whole pass, plus what was left held
  (codex-portable.json in magpie's folder).

Run at this series' head (on origin/main 0fe039f14):
- Real codex 0.162.1, sandbox HOME/CODEX_HOME, exec </dev/null, against a
  fake upstream. In magpie mode it auto-compacted and the rollout's
  compacted line held magpie1:. In OpenAI mode, `exec resume --last`
  failed with "Error running remote compact task: ...
  invalid_encrypted_content". After PortCodexRollouts on that home, only
  that line changed (42 lines before and after). The same resume exited
  0, and the upstream saw the summary message.
- Broken by hand. With the thread-lock TryLock check off,
  TestPortCodexRolloutsLeavesAnOpenThread went red. With the replacement
  off, TestPortCodexRollouts went red. Both green with the fix restored.
- gofmt -l clean. go vet ./... (darwin) clean, GOOS=windows go vet
  ./internal/... clean, and GOOS=linux go vet -tags nogui ./... clean.
- go test ./... -count=1 -timeout 45m: 64 packages ok, two reds.
  - internal/agent ran out of time at 2706s (load average 25 to 57), the
    known #2723/#2544. Alone, go test ./internal/agent -count=1 is ok in
    901s.
  - internal/provider TestHoldReadsMigrationsOnce: "migrations.json read
    again while held" at 2.70s. It passes alone 5 of 5. I didn't touch
    that package. Filed #3095: heldFor (1s) can run out between the
    test's two reads.

Not tried:
- api.openai.com itself after a port. The refusal was probed on the
  ChatGPT backend, and the resume ran against a fake.
- A Codex in a WSL distro. Disconnect skips it, because its locks can't
  be taken from Windows.
- The Codex app still holding a thread when magpie quits. Its lock is
  held, so the file is left for the next pass, and the thread in that
  app's memory keeps the magpie1 item until it is loaded again.
2026-10-21 03:05:24 +08:00
yetone 694674cf0d codexsummary: one owner for magpie's Codex compaction item and the message it stands for
The "magpie1:" mark, Codex's summary prefix and the reading of a magpie
compaction as Codex's own local-compaction summary message move from the
gateway into internal/codexsummary, so the rollout rewrite that comes next
(internal/sessions, which the gateway imports) reads it the same way. The
gateway's behaviour is unchanged.

Run: go build ./internal/...; go vet ./internal/gateway ./internal/codexsummary;
go test ./internal/codexsummary; go test ./internal/gateway
-run 'Compact|CodexInput|Rewrite|Native|CallItem|Protection' (ok, 57s).
2026-10-21 03:05:23 +08:00
yetone 4bb93b3255 gui tests: routing-wb-restricted waits for the posted lift instead of a fixed 300ms (#2658)
The test pressed Try now, paused 300ms and then read what its fake
/api/gateway/unrest had received. On a busy machine the POST reached the
fake after the pause and the list was still empty. It now waits up to 5s
for the lift to arrive and then checks it.

Red before: with a 600ms delay injected into the fake, the old test is 2
of 2 red (chromium en, 1100 and 420), the new one 2 of 2 green.

Run (macOS, Playwright 1.62.0, chromium and webkit, every language and
width the file runs): 20 of 20 green alone, and green in the
--test-concurrency=6 run of the 37 reach/wheelTo files (590 of 590).
2026-10-21 02:44:28 +08:00
yetone 2543fb2c18 gui tests: routing-bodies and routing-request-metrics wheel to a row like a reader before clicking it (#2559, #2658)
routing-bodies has been red since it was added (af601541e, 10-16): its
pick(1)/pick(2) never pressed the body choice. routing-request-metrics'
480px tap was flaky the same way. Cause: both brought the row into view
from code (locator.scrollIntoViewIfNeeded, element.scrollIntoView in an
evaluate). The app puts back any scroll that isn't the reader's (app.js,
"where the reader is"), so by the click the row was back under the
footer or out of the window, and the click landed on the footer, a
.rt-steps li.why or a .rt-cap instead.

Both taps now use reader.cjs's reach, which wheels like a reader until the
control is clear in its view, then click its center. The page is
unchanged.

Red before: with an injected 300ms wait between the scroll and the
click, the old routing-bodies is 10 of 10 red (at pick(1)) and the old
routing-request-metrics 4 of 4 red (waiting for the Cost
menuitemcheckbox); the new ones 10 of 10 and 4 of 4 green under the same
wait. Without injection, the old routing-bodies was 10 of 10 red on this
machine.

Run (macOS, Playwright 1.62.0, chromium and webkit, every language and
width the files run, load average 60-190 from other sessions):
- alone: routing-bodies 10 of 10, routing-request-metrics 4 of 4 green.
- under --test-concurrency=6 with every GUI file that uses reach or
  wheelTo (37 files, 590 tests): 590 of 590 green.
2026-10-21 02:44:27 +08:00
yetone b8ed806e33 gui tests: reach reads the control it wheels to in one call, so a row drawn again between two looks isn't taken for in sight (#2658)
routing-model-rest and routing-wb-restricted were red 1-2 of 20 alone
on a busy machine ("the button can't be reached"). Cause: each test's own
wheel loop read the Try now button with locator.evaluate, which finds the
element in one call and reads it in the next. Routing draws its account
rows again on its own, and a redraw between the two calls handed the
check the button just replaced: out of the page, a zero box at the
window's top, which "bottom < innerHeight - 80" took for in sight. The
loop stopped after one wheel (the failing run's view sat at scrollTop
200 with the button at y 1836).

reader.cjs's shared reach (and wheelTo) had the same two-call read, and
reach threw on a replaced element (closest(".view") null) or returned
early without scrolling. They now read with locator.evaluateAll, which
finds and reads in one call, and look again when nothing matches.
routing-model-rest and routing-wb-restricted use reach instead of their
own loops.

The tests were red before: with an injected redraw (the Try now button
replaced by a clone every 2ms during the scroll), the old
routing-model-rest is 4 of 4 red (chromium en/de, 1100/420), the new one
4 of 4 green. A page-side main-thread hog showed the same [0,null] reads.

Run (macOS, Playwright 1.62.0, load average 60-190 from other sessions):
- alone, both engines, every language and width the files run:
  routing-model-rest 20 of 20, routing-wb-restricted 20 of 20 green.
- under --test-concurrency=6, with every other GUI file that uses reach
  or wheelTo (37 files, 590 tests): 590 of 590 green.
2026-10-21 02:44:26 +08:00
yetone a4f9f0b96e routing: a request of an agent the stage leaves out is listed, not flown
The stage draws at most four agents (staged's slice(-4)), but poll plays
every request under way. A fifth agent's request reached play with no
drawn agent, and `tick(A.node)` threw "Cannot read properties of
undefined (reading 'node')" for each one: about 85 a minute under mixed
traffic, found while measuring the hidden-page growth (14f57e028).
play's finally cleaned up after it, so nothing was kept, but every such
request was an uncaught error. play now returns before making its dot
when the agent isn't on the stage, and lets go of its playing mark.

Test: routing-fifth-agent.test.cjs, six agents taking turns at a request
every 80 ms, chromium and webkit, en and zh. Without the change 4 of 4
red with the error above (20+ times each run); with it 4 of 4 green.
routing-fifth-agent, routing-hidden-stage and routing-idle-frame
together: 21 pass, 0 fail.
2026-10-21 02:44:25 +08:00
yetone e8ab1333be routing: out of sight, the page builds nothing for each request (#2515, #2513)
The Routing plugin's poll called sync() and empty() on every trace update,
and loadDays, the session-name refresh and "magpie-costs-changed" called
renderHist(), whether or not the page was in sight. So on every page, in
the tray panel and in a hidden window, each request put up the Routing
stage again (agent nodes, account rows, wires) and its request list. In a
hidden window no frame is drawn and the document timeline stands still, so
the entrance and live animations (rtin on li.new, rtlive on the live dot,
rttick) on each replaced node stayed on it and held the node: the same
class as 67f8dbb16, one level up.

sync(), empty() and renderHist() now return while !shown(). resume(), run
on the first frame back in sight (pause() clears `seen`), already redraws
everything: sync(true) or empty(), plays the requests under way, and
renderAll() draws the list. The caption is still written while hidden.

Measured, sandbox `magpie web` built from this tree (nogui), 3 rps of
mixed-agent traffic through its gateway, chromium, the page's hidden
state faked as in panel-routing-hidden, MutationObserver over the whole
body for 60 s hidden (scratch rafhid.cjs):
  before (a9304efe0), per minute hidden:
    main on Agents:   720 rt-node, 494+494 rt-what b/span, 240 rt-req,
                      179 wire paths, 179 icons (~2300 nodes)
    main on Routing:  same, plus 5 path.via
    tray panel:       same as main on Agents
  after:
    main on Agents:   0 Routing nodes (5 Agents-page nodes)
    main on Routing:  5 path.via (an in-flight play's step; removed by
                      fly's finally)
    tray panel:       0
  Elements in the hidden main window on Agents: 3056 -> 1457 (the Routing
  page is drawn when first shown).
  Usage, Providers, Sessions, Gateway and Library parked hidden: 0 nodes.
Starting on Agents and then picking Routing draws 4 agent nodes, 60 rows
and the caption at once, chromium and webkit, no page errors.

Tests:
- New routing-hidden-stage.test.cjs: hidden by another page picked and
  by the window hidden, chromium and webkit, en and zh: 8/8 pass. With
  client.js reverted to a9304efe0: 8/8 red (20-21 rt-what b/span added
  over 20 requests).
- routing-idle-frame.test.cjs waited for .rt-req rows with Agents picked,
  which only existed because the hidden page drew them; it now waits for
  the live dot. webkit 9/9, chromium 9/9.
- routing*, panel*, gui-de/ja/zh-tw and i18n-keys, chromium and webkit
  (node --test --test-concurrency=6): 1312 tests, 1300 pass, 12 red:
  - 8 routing-bodies.test.cjs: red 10/10 alone on this tree and on
    a9304efe0 with this change reverted (pick(2) is never pressed).
  - 2 routing-idle-frame "plays once when Routing resumes": the run
    predates the test change above; 9/9 after it, in both engines.
  - 1 routing-request-metrics.test.cjs: flaky on both trees, 1-2 of 4
    red in each of three runs alone on each (metric menu item not found).
  - 1 routing-wb-restricted (chromium de 1100px): 20/20 twice alone.
- The 16 other GUI files that read the Routing page's DOM
  (click-scroll, purpose-filter, phone-rows, dates-gui-lang, ...): 278/278.
2026-10-21 02:44:25 +08:00
yetone 10939ebdf1 sessions: a dsh frame is read into one buffer of its own size
scanFrames reads a dsh session (zstd frames, a batch of whole lines
each) frame by frame, and readFrame took each frame's bytes by growing
its buffer a block at a time (blocks are at most 128 KiB). A frame with
a pasted image is megabytes long, and growing to it by append allocated
several times what it read (3.7 times on the first case below).

- frameSize finds a frame's length from its headers alone (frame
  header, then each block's 3-byte header, then the checksum), read
  ahead with ReadAt without moving the file, and readFrame makes its
  buffer that large at once. The buffer is still reused across frames.
- frameHeaderLen and blockLen are readFrame's own header arithmetic,
  moved out so both read the format the same way.
- A skippable frame, or one the file doesn't hold whole yet, has size
  0, and readFrame reads it as before: a frame still being written
  waits for the next read, and a size that turned wrong (the file
  rewritten in between) only makes the buffer grow again.

scanFrames runs on dsh session reads (dsh.go's session list and
calls_dsh.go's calls), cold once per file and then on from the last
frame read.

Measured (TotalAlloc of scanFrames over a whole dsh file, 3 runs
each, all within 2%):

  session                                    before      after
  3 frames, images of 1/3/5 MiB (9.4 MB)     34.85 MB    18.93 MB
                                             (3.69x)     (2.01x)
  one frame, a 6 MiB image (the test below)  38.4-39.5 MB 12.6-13.7 MB

pprof (memprofilerate 1) put readFrame's take at 24.8 MB of the first
case's 34.9 MB. What is left is the frames once and DecodeAll's output.

Tests (internal/sessions/frames_size_test.go):
- TestFrameSizeIsWhatReadFrameReads: frameSize equals what readFrame
  reads for frames with and without a checksum, a 3 MiB and a 2 MiB
  line, and is 0 for a skippable frame and a frame cut short.
- TestScanFramesLongLinesUnchanged: the lines scanFrames hands over
  equal a whole-stream decode's, for a 5 MiB line with an empty line
  after it, a 3 MiB line split across two frames, and a 1 MiB line;
  and with the last frame half written, the read stops at the frame
  before it and reads on, once it is whole, to the same lines.
- TestScanFramesReadsALongFrameOnce: a scan of one frame with a 6 MiB
  line allocates at most the frame plus the line plus 2 MiB. With
  frameSize's hint replaced by 0 (the old growth) it is red 3 of 3:
  "a scan of a 6291688-byte frame allocated 38445616/39495688/39495704
  bytes, want at most 14680367". Passed -count=10.

Run at this commit's tree on origin/main c84864ffc, macOS arm64, go1.26.8,
sandbox HOME: gofmt -l internal clean; go vet ./internal/... ok, and
GOOS=linux/windows go vet -tags nogui of sessions and usage ok;
go test -race -count=3 ./internal/sessions/ ok (512s); go test
-timeout 45m ./... exit 0, 65 packages ok, none failed. (On the older
base a9304efe0 the race run was red in TestManageReadsOnlyTheAgentsItShows,
TestOpenCodeSubagents and TestLongReadKeepsWhatItRead: test-only races
that 9afdeb89c and c84864ffc fixed on main.)
2026-10-21 02:44:23 +08:00
yetone bb5930b71b sessions: a trace poll reads a long line once, at its own size
TraceReader.Poll, which the OTel exporter runs each tick while session
export is on, read every appended line with bufio.ReadBytes through a
4 KiB reader. Every line was a copy of its own, and a line longer than
4 KiB (a function output, a pasted image in a Codex rollout) was gathered
in 4 KiB clones and then copied whole: about twice the line.

- Lines are read through the pooled line reader every other session
  reader uses (scanBuffer's size, 16 KiB to 1 MiB), with ReadSlice. A
  line the buffer holds is handed to the cursor in it; the cursor's
  parse copies what it keeps (encoding/json copies into RawMessage and
  strings), so nothing outlives the read.
- A longer line is gathered into one buffer made at its length, read
  ahead with lineLen as scanAt does, and reused for the next long line
  of the same poll. It is dropped when the poll returns.
- A line with no newline yet (half-written) is left for the next poll,
  as before. When the read ahead finds no end the gathering stops at
  once instead of growing the line first. A file rewritten between the
  read ahead and the read only grows the buffer again, never cuts a
  line.

Measured (TotalAlloc of one cold Poll, a fresh TraceReader over one
Codex rollout in a sandbox CODEX_HOME, 5 runs averaged, 3 runs each,
all equal to within 0.1%):

  rollout                                     bodies  before    after
  3 turns, images of 1/3/5 MiB (9.5 MB)       off     38.2 MB   28.7 MB
                                              on      57.3 MB   47.6 MB
  300 turns, 20 KB images (9.9 MB, 760 spans) off     35.6 MB   20.8 MB
                                              on      60.0 MB   45.1 MB

pprof (memprofilerate 1) puts ReadBytes at 18.7 MB per poll before and
the new read at 9.2 MB after, exactly the long lines read once. The rest
is the cursor's own parse (RawMessage copies of payload and content),
which this change leaves alone.

Tests (internal/sessions/trace_lines_test.go):
- TestNextTraceLineReadsWhatReadBytesRead: lines and end offset equal
  ReadBytes' for long lines (1/3/5 MiB, past the 1 MiB buffer), a line
  of the buffer's size, empty lines, CRLF, a short and a long unended
  last line, no line yet, an empty file; from 0 and from the first
  line's end.
- TestNextTraceLineWaitsForALongLineToEnd: a 3 MiB line without its
  newline is not read, and is read whole once it has one.
- TestTracePollOfLongLinesIsUnchanged: the spans Poll exports (bodies
  off and on) from a rollout with 3 and 2 MiB images, written in three
  parts that end inside long lines, are reflect.DeepEqual to those a
  cursor fed the whole file's ReadBytes lines exports.
- TestTracePollReadsALongLineOnce: a poll of a 6 MiB reasoning line
  allocates at most 2.5 times the line (12.6-13.7 MB over -count=20).
  With Poll's ReadBytes loop put back by hand it is red 3 of 3: "a poll
  of a 6291589-byte line allocated 19025024 bytes, want at most
  15728972".

Run at this commit's tree on origin/main c84864ffc, macOS arm64, go1.26.8,
sandbox HOME: gofmt -l internal clean; go vet ./internal/... ok, and
GOOS=linux/windows go vet -tags nogui of sessions and usage ok;
go test -race -count=3 ./internal/sessions/ ok (512s); go test
-timeout 45m ./... exit 0, 65 packages ok, none failed. (On the older
base a9304efe0 the race run was red in TestManageReadsOnlyTheAgentsItShows,
TestOpenCodeSubagents and TestLongReadKeepsWhatItRead: test-only races
that 9afdeb89c and c84864ffc fixed on main.)
2026-10-21 02:44:22 +08:00
yetone f1e4516da2 gui: Codex's and Claude Code's own settings are in the agent's row on the Agents page, not in Settings
The owner, 10-20: Settings › General held Codex subagents, Long
conversations, Codex background compaction, thread titles, thread
descriptions, composer predictions, the auto-review model and the
memories model, apart from the agents they set; "很割裂、很分散,不直观".

They now sit with their agent (AGENT_PREFS): in its opened row on the
Agents page (a Settings list in connectPanel), in a sheet from the
tray panel's row ("Settings" line, openAgentPrefs) and from the agent's
menu ("{agent} settings"). Each row is the one element moved between
those places, so its handlers and state go with it. Settings' search
still finds them, with a row that opens the agent's sheet
(#agentPrefLinks). A gateway has no Agents page and none of them.
Strings for zh, zh-TW, ja and de; docs (reference, agent-wiring,
gui-shell) point at the new place. app.js 1,277,298 bytes and the core
scripts 1,469,058, so both budgets rise.

Run on 6416d639c (the dialog morph, on origin/main 75e769a9f), macOS,
playwright 1.62.0:
- agent-prefs.test.cjs (new) plus the 10 migrated files (codex-titles,
  codex-descriptions, codex-auto-review, codex-predictions,
  codex-memories-settings, codex-async-compact, compact-at,
  settings-general, bare-ids, gateway-mode) and modal-morph: 152/152,
  chromium and webkit, every language, wide and 420px.
- go test ./internal/gui/: ok after the budget rise.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Two GUI tests leaned on the Agents page's old height and are moved with it:
agent-models-loading clicked "elsewhere" at (900, 650), which is now
Codex's Disconnect button in its opened row, so it clicks the page's lead
line; agent-expand-steady clicked Goose's row while Codex's opened row
(~554px with its settings) pushed it out of a 560px view, so it wheels
Goose's link into sight first (reader.cjs reach). codex-subagents-lead
and agent-models-redraw clicked controls below Codex's opened row and
timed out in WebKit ("outside of the viewport"); they wait for the row to
finish sliding open, then wheel the control into sight. With Settings ›
General shorter, segs-press-redraw's sweep left Usage's warm-up tabs
above the view in WebKit; it wheels them back when they are. panel-effort
opened Kimi's row below Codex's opened one the same way. login-allow's
wheel loop read the shorter General page's button 50ms after each wheel and
clicked beside it (de, 440px); it uses reach. mobile-web shut each agent
picker by tapping the Agents tab, which a picker opened low in Codex's
taller row covers on a phone; it taps the header's name (the lead line
can sit under the header's tabs, and a tap there opened Library), wheels
each row and field into sight before tapping it, and says which agent and
field a step timed out on. All seven pass in Chromium and WebKit.

After the rebase onto main (32 commits on), with the test fixes above:
- go test ./internal/gui/ ./internal/plugin/ ./internal/agent/ ok;
  gofmt -l clean; go vet GOOS=linux -tags nogui and GOOS=windows.
- 95 GUI files (every agent-, codex-, claude-, settings- and modal- file,
  and every file either side changed): 1375 pass; the 8 reds were
  segs-press-redraw, fixed above. The 16 other files that click an
  Agents row: 369/370, rail-tip red on main too (#3091).
- The full suite's reds are listed in the dialog morph's commit; each was
  run alone on this head and on origin/main.
- mobile-web's "desktop matches origin/main" compares Settings and the
  Agents page with main's assets, so it is red until this is on main; its
  phone checks pass in Chromium and WebKit.
2026-10-21 02:06:23 +08:00
yetone ceaf2505ab gui tests: agent-expand-steady reads the switch's place to a quarter pixel (#1583)
"the switch moved 19 !== 18" in WebKit. The row didn't move: probed shut
and open, the switch sits 18.50px down the row both times. where()
rounded the float difference to a whole pixel, and 18.4999 against 18.5
reads 18 against 19. A quarter pixel keeps any real move of the switch
red and stops the rounding flipping.

Run: webkit 3 runs before on 6416d639c + the agent-settings change
(which makes the row taller): 2 of 2 red each run; after: 0 red in 3
runs; chromium 2/2.
2026-10-21 02:06:20 +08:00
yetone d9d1680ab6 gui: a dialog grows out of the row that opened it and folds back into it
The owner, 10-20: a provider's editor "从右上角弹出" and should open from
the provider's row and close back into it, as iOS does. openModal scaled
the dialog from the row's rect, but a row is wider than the dialog, so
scale alone left a full-size dialog sliding in from the row's middle.

Now the dialog starts as a strip the row's size (transform plus a
clip-path inset, morphFrom), grows into the dialog on the spring, and
closeModal runs it back into the row. The backdrop fades its own
background and blur (VEIL_OFF) instead of the modal's opacity, which
faded the dialog with it, so a dialog folding back stays visible until
it lands. A ResizeObserver keeps the start on the row when an editor
settles its size after it was measured. Reduced motion still only fades.

Every page's dialogs open through the core, so app.js's budget rises
(1,271,683 bytes).

Run on origin/main 75e769a9f + this commit, macOS, playwright 1.62.0:
- modal-morph.test.cjs (new): 6/6, chromium and webkit at 1240 and 420px;
  it fails without the change in webkit.
- gofmt -l clean; go test ./internal/gui/ -run TestCoreScriptBudget ok.
- Full GUI suite (814 files, --test-concurrency=4) on this commit with
  the two after it, on 75e769a9f before the rebase: 11,385 pass, 90
  fail. The morph's own reds (modal-morph chromium 1240 and 420) were
  under load: 6/6 run alone on the rebased head. The rest are the agent
  settings commit's (fixed there) or red alone on origin/main a9304efe0
  too: codex-predictions 420px (#2624), quota-count-wrap and
  quota-name-translated (#2228), routing-bodies, routing-request-metrics,
  s3-sync (#2658), usage-agents-hide, usage-fold (#2399), usage-checkin
  webkit and rail-tip (#3091). agy-launch and name-suffix-remote were red
  only in the full run and pass alone.
- An earlier full run on this commit alone was cut short, not finished.
2026-10-21 02:06:18 +08:00
yetone 0fe039f14d gateway: Ollama's /api/chat and /api/generate, for Zed's Ollama provider (super_lalalalala on Discord)
Zed's Ollama provider chats on POST /api/chat, which magpie answered 404:
it served only /api/version, /api/tags and /api/show. Both routes are now
served on the mux, so lanGuard, counted, corsGuard, callerGuard, withCaller
and keyLimited cover them as they cover /v1/chat/completions. The body is
turned into a /v1/chat/completions body and handed to the same
handle(provider.Chat) on a clone of the request, so routing, a key's models,
usage and errors are the /v1 path's own.

Request (ollamaChatBody, after Ollama v0.12.6's api/types.go and Zed's
crates/ollama):
- messages: images as data-URL parts (type sniffed); a tool message's
  images in a user message after it; an assistant's thinking as
  reasoning_content; tool_calls given ids when Ollama sent none, and
  arguments sent as a JSON string;
- a tool result goes with its call by tool_call_id, else tool_name (what
  Zed sends), else in order; one with no call is a 400;
- /api/generate: system, prompt and images as a two-message chat;
- tools, format ("json" or a schema), think (a level is
  reasoning_effort, false hides thinking in the reply);
- options: temperature, top_p, seed, stop, presence/frequency penalty,
  num_predict > 0 as max_tokens; num_ctx, top_k and Ollama's other own
  options are dropped.

Reply (ollamaWriter): NDJSON lines unless stream:false, then one object;
message.content/thinking (or response) as they arrive, tool calls with
an id and their arguments as an object, and a done line with done_reason
(stop or length) and the token counts. An error is {"error":"..."} with
the status /v1 gives. A request with nothing to say is answered
done_reason "load", as Ollama warms a model.

/api/show took "plan/seer:latest" (what `ollama run plan/seer` asks for)
as unknown and the CLI then tried to pull it; ollamaName now gives the
bare id for show and both chat routes.

Broken by hand, each red: tool_name ignored, tool-call ids not kept,
arguments as a string, num_ctx passed upstream, status 200 on an error,
thinking kept with think:false, no route, and /api/show without
ollamaName (plan/plain:latest 404).
Real client: a sandbox gateway (magpie serve, sandbox HOME and
XDG dirs, MAGPIE_ADDR=127.0.0.1:3592) over a fake OpenAI upstream on
3591, with the ollama CLI 0.6.8: `ollama list` lists plan/seer,
`ollama show plan/seer` prints it, `ollama run plan/seer "hi"` and
`ollama run plan/seer:latest "hi"` print the upstream's streamed
"Hello from the sandbox gateway" (the :latest one failed with a pull
error before ollamaName). curl /api/chat and /api/generate, streamed and
stream:false, and a chat with tools, a nameless tool call and a
tool_name result: NDJSON/whole replies, upstream got ids paired and no
num_ctx. Zed itself not run (it would read the live Zed settings).

Run: gofmt -l (none); go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows: clean. `set -o pipefail; go test -timeout 45m ./...` at
1ebda9026 (this batch on 318697dce, movers then at qoder 0.2.21,
workbuddy 0.1.26, no devin raise): 65 packages ok, exit 0. Rebased onto
a9304efe0 (codex images, codex list tag, sessions decoders): gofmt, the
three vets and go test of internal/gateway, internal/provider,
internal/plugin and internal/sessions ok. Then the mover mins were raised
to qoder 0.2.23, workbuddy 0.1.27 and devin 0.1.21 (the only change
since, three strings): gofmt, the three vets of internal/provider and
go test ./internal/provider/ ok at the head of this batch.
2026-10-21 01:11:05 +08:00
yetone a2f8fd86a0 devin: moved users get plugin 0.1.21, where a large chat request goes gzipped as the devin CLI sends it
0.1.21 (plugins e2c3a35, 4fd68ba): a Connect request frame past 8 KiB is
gzipped, with the frame's compressed flag and Connect-Content-Encoding:
gzip, as the devin CLI sends it; an uncompressed large chat request
could be refused 413 upstream (plugins #275, BGMYE).
npm view @magpie-community/opencode-devin-auth@0.1.21 version
--prefer-online printed 0.1.21 before the raise.

Run: gofmt -l (none); go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows: clean. `set -o pipefail; go test -timeout 45m ./...` at
1ebda9026 (this batch on 318697dce, movers then at qoder 0.2.21,
workbuddy 0.1.26, no devin raise): 65 packages ok, exit 0. Rebased onto
a9304efe0 (codex images, codex list tag, sessions decoders): gofmt, the
three vets and go test of internal/gateway, internal/provider,
internal/plugin and internal/sessions ok. Then the mover mins were raised
to qoder 0.2.23, workbuddy 0.1.27 and devin 0.1.21 (the only change
since, three strings): gofmt, the three vets of internal/provider and
go test ./internal/provider/ ok at the head of this batch.
2026-10-21 01:11:05 +08:00
yetone 59d2815f38 workbuddy: moved users get plugin 0.1.27: efforts for a model that says only supportsReasoning, and DeepSeek Harness not refused as 11128
0.1.26 (plugins 68170b3): a model whose config gives supportsReasoning
and a default effort but no effort list lists low, high, max and that
default, instead of being marked as not reasoning (8 models in #255).
0.1.27 (plugins 6fd976a): DeepSeek Harness opens its system prompt with
"You are an AI agent powered by DeepSeek Harness.", which WorkBuddy
refuses as "Illegal API invocation from an unapproved channel" (11128);
the plugin rewords that one line to a neutral one (plugins #279, #280).
npm view @magpie-community/opencode-workbuddy-auth@0.1.27 version
--prefer-online printed 0.1.27 before the raise.

Run: gofmt -l (none); go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows: clean. `set -o pipefail; go test -timeout 45m ./...` at
1ebda9026 (this batch on 318697dce, movers then at qoder 0.2.21,
workbuddy 0.1.26, no devin raise): 65 packages ok, exit 0. Rebased onto
a9304efe0 (codex images, codex list tag, sessions decoders): gofmt, the
three vets and go test of internal/gateway, internal/provider,
internal/plugin and internal/sessions ok. Then the mover mins were raised
to qoder 0.2.23, workbuddy 0.1.27 and devin 0.1.21 (the only change
since, three strings): gofmt, the three vets of internal/provider and
go test ./internal/provider/ ok at the head of this batch.
2026-10-21 01:11:05 +08:00
yetone d2c434b5a6 gateway: ClinePass pins glm-5.3-flash through OpenRouter's provider.only (sdytman on Discord)
sdytman (#feedback, 10-20) found that Cline doesn't send every model
through Vercel's AI Gateway: glm-5.3-flash goes through OpenRouter
directly, which ignores providerOptions.gateway.only, so the Upstream
tick (dd70c5e6a) didn't pin it. OpenRouter reads a top-level
provider.only with its own slug, "z-ai" for Z.AI
(openrouter.ai/api/v1/providers; its glm-5.3-flash endpoints list
"Z.AI z-ai/fp8"). deepseek-v4.1-flash and deepseek-v4.1-flash-1017 do go
through Vercel, so they keep providerOptions.gateway.only ["deepseek"].

provider.ClinePin now returns the upstream and whether the model's route
is OpenRouter, from a table whose first entry is glm-5.3-flash by exact
name (glm-5.3-flashx and glm-5.3 stay on Vercel's "zai" as before; which
router Cline uses isn't visible from its feed or either router's model
list, both of which list every one of these models). clinePin appends
"provider":{"only":["z-ai"]} at the body's end for such a model, so the
cached prefix is unchanged, and leaves a body naming provider or
providerOptions itself as sent. Applies to the Cline plugin's provider
too, since magpie writes its requests before the plugin sends them.

Not tried with a real request: there is no Cline account here.

Broken by hand, each red: no glm-5.3-flash entry (gets providerOptions
zai), a client's own provider field not checked (two pin keys), and
providerOptions for every model (flash has no provider.only). Not tried
with a real ClinePass request: no account here.

Run: gofmt -l (none); go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows: clean. `set -o pipefail; go test -timeout 45m ./...` at
1ebda9026 (this batch on 318697dce, movers then at qoder 0.2.21,
workbuddy 0.1.26, no devin raise): 65 packages ok, exit 0. Rebased onto
a9304efe0 (codex images, codex list tag, sessions decoders): gofmt, the
three vets and go test of internal/gateway, internal/provider,
internal/plugin and internal/sessions ok. Then the mover mins were raised
to qoder 0.2.23, workbuddy 0.1.27 and devin 0.1.21 (the only change
since, three strings): gofmt, the three vets of internal/provider and
go test ./internal/provider/ ok at the head of this batch.
2026-10-21 01:11:05 +08:00
yetone dcf6ea6a79 provider: moved Qoder and Qoder CN users get plugin 0.2.23
0.2.20 keeps unnamed tool-call fragments out of the chat history; 0.2.21
adds Qoder CN personal-access-token sign-in and the daily check-in for
PAT accounts; 0.2.22 pairs a tool result whose call lost its id with
that call, where Qoder refused the whole request as an orphan tool turn
on long Codex sessions (plugins #277, #278); 0.2.23 sends the desktop
app's Cosy-Version 1.1.69 instead of the CLI's 1.1.49 beside the desktop
client type and machine identity it already sends (plugins #281).
npm view @magpie-community/opencode-qoder-auth@0.2.23 version
--prefer-online printed 0.2.23 before the raise.

Run: gofmt -l (none); go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows: clean. `set -o pipefail; go test -timeout 45m ./...` at
1ebda9026 (this batch on 318697dce, movers then at qoder 0.2.21,
workbuddy 0.1.26, no devin raise): 65 packages ok, exit 0. Rebased onto
a9304efe0 (codex images, codex list tag, sessions decoders): gofmt, the
three vets and go test of internal/gateway, internal/provider,
internal/plugin and internal/sessions ok. Then the mover mins were raised
to qoder 0.2.23, workbuddy 0.1.27 and devin 0.1.21 (the only change
since, three strings): gofmt, the three vets of internal/provider and
go test ./internal/provider/ ok at the head of this batch.
2026-10-21 01:11:05 +08:00
yetone c84864ffcc sessions: tests swap the time zone only after the background cache writer is done
go test -race -count=3 ./internal/sessions/ failed in TestOpenCodeSubagents:
testenv.Zone (via inZone) wrote time.Local while saveCache's goroutine,
started by List() in an earlier iteration, read it in os.MkdirAll ->
time.Unix (sessions.go:717 -> writeCache :761).

inZone, the only place this package's tests change the zone, now drains
the writer before the swap and again before it is put back. The same drain
written by hand in TestHermesStatsIncludesRecentUsageForOldTranscript is
dropped: inZone does it for every caller.

Run: go test -race -run 'TestOpenCodeSubagents|TestHermes' -count=20
./internal/sessions/ ok (184s); before, -count=3 failed with the race.
2026-10-21 00:13:04 +08:00
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