Commit Graph
4448 Commits
Author SHA1 Message Date
yetone 75e78a5a04 tui: quitting hands the gateway to magpie's service on Linux
zaidu259434 on X: "启动codex这些cli连接会失败,AI分析没自动启动magpie的网关".
With magpie installed inside WSL (or on a server over SSH), nothing
opens magpie at login, and XDG autostart doesn't run there. So once
`magpie tui` quit, the agents it had connected asked a gateway that was
gone.

When the terminal quits having served the gateway with an agent
connected, on Linux and where magpie doesn't open at login, keepGateway:
- starts magpie's service (magpie daemon) when it is installed;
- installs it when the user never removed it (daemon.Removed: Uninstall
  now leaves a daemon-removed mark, and Install clears it), so it starts
  with the system or the login from then on, and says how to remove it;
- otherwise (no systemd, which is WSL's default, or the user removed it)
  starts `magpie serve` in its own session, logging to magpie's cache,
  and says so. In WSL it also says how to turn systemd on.
macOS, Windows, nothing connected, or magpie opening at login: the same
"gateway stopped" note as before. Docs: gui-shell.

Run:
- TestKeepGatewayAsTheTerminalQuits covers each of those cases, and
  TestUninstallRecordsTheUsersNo checks the mark.
- go test -timeout 45m on the four packages, the same run as the
  previous commit's: all four ok (gateway 428s, agent 255s, tui 23s, daemon 16s), at 6874095b1 plus this change, before the rebase
- GOOS=linux and GOOS=windows go vet, and gofmt -l, are clean.
- Real run in the magpie-desktop distro (WSL2, systemd on): a Linux build
  from this tree started under setsid as serveInBackground does,
  answered 200, and still answered 200 with its pid alive 30s after its
  wsl.exe session ended. It was stopped afterwards.

Not tried:
- the interactive TUI quit itself in WSL (over ssh there is no terminal
  to drive it), so the message and the path it picks are covered by the
  unit test only;
- a real daemon.Install inside WSL (it writes a systemd user unit for the
  distro's user).
2026-10-25 12:42:20 +08:00
yetone a1c1b7053b gateway: WSL under NAT reaches the Windows gateway with sharing off
zaidu259434 on X (tweet 2114203077989527990): on Win11, Codex and the
other CLIs in WSL failed to connect to magpie. A distro in NAT
networking (WSL's default) reaches Windows at the address Windows has
on the WSL network (vEthernet (WSL), 172.17.32.1 on the test box), and
magpie wrote that address into the distro's agents. But the gateway
listened on 127.0.0.1 alone unless LAN sharing was on, so every request
from WSL timed out. Turning sharing on wasn't enough either: the WSL
adapter is in Windows' Public profile, and a Private-only allow rule
still keeps WSL out (reproduced on the box).

- gateway: while it listens on loopback alone, on Windows it also
  serves at each address on a vEthernet (WSL...) adapter (serveWSL,
  looked for again every 10s, since the VM brings its adapter up and
  down). A request there counts as this computer's only when it comes
  from that network to that address with the WSL key (fromWSL). The key
  is `wsl-` plus 48 hex in magpie's folder (wsl-key, 0600), with
  `-<agent>` after it optional. The request is then served as a
  loopback one with the token (asFromLoopback). Anything else there is
  judged as another machine's, so a Docker Desktop container on the
  same network gets 403.
- agent: WSL twins at that address get the WSL key (keyAt, agentKeyAt,
  ourKey and gatewayKey know it). Whether it answers is asked from
  inside the running distro (reachFrom, wslReach: curl, wget or bash's
  /dev/tcp), never from Windows, where the listener answers whatever the
  firewall keeps out. A distro that can't connect is shown the firewall
  rule that lets it in (Profile Any, vEthernet (WSL*), magpie.exe).
- The NAT notices no longer say it answers only while sharing is on (en,
  zh, zh-TW, ja, de).
- Docs: gateway-routing (WSL under NAT) and agent-wiring.

Run:
- TestWSLCallerServedWithSharingOff and TestServeWSLListensBesideLoopback
  (gateway), and TestWSLAgentsGetTheWSLKey and
  TestWSLReachAskedInsideTheDistro (agent). All four were red with the
  fix taken out: "403 magpie isn't shared on the local network",
  "answers = false", the token given at the WSL address, and no drift.
- go test -timeout 45m ./internal/gateway ./internal/agent ./internal/tui
  ./internal/daemon: all four ok (gateway 428s, agent 255s, tui 23s, daemon 16s), at 6874095b1 plus this change, before the rebase
- GUI, NODE_PATH playwright 1.62.0, both engines: i18n-keys,
  agent-notice-lang, agent-unreachable, wsl-agents-setting, gui-zh-tw,
  gui-ja and gui-de, 105 of 105 ok.
- gofmt -l is clean, and GOOS=linux and GOOS=windows go vet are clean on
  the four packages.
- Real run on the Windows 11 box: a magpie.exe from this tree ran
  `serve` in a sandbox HOME, with MAGPIE_ADDR=127.0.0.1:3446 and sharing
  off. It listened on 127.0.0.1:3446 and 172.17.32.1:3446. From the
  magpie-desktop distro (NAT):
  - With no firewall rule, a request timed out (000 at 5s), and the
    probe script said "no".
  - After adding the rule this change advises:
    - the probe said "ok";
    - the WSL key got 200 in 0.09s, and so did key-codex;
    - no key got 403 "magpie isn't shared on the local network";
    - Bearer magpie got 403.
  The rule and the process were removed afterwards.

Not tried:
- a real Codex turn from WSL through this (the sandbox had no provider);
- `wsl --shutdown` re-addressing the adapter (it isn't my box to shut
  down; the 10s re-listen is covered by the unit test only);
- mirrored networking, which is unchanged.

Not changed: the Windows firewall prompt. magpie listens there itself,
so Windows asks once, and Public has to be ticked; the unreachable
notice gives the command for when it wasn't.
2026-10-25 12:42:20 +08:00
yetone 15f0d4cdeb sessions: a Claude Code session goes on in Codex, and a Codex one in Claude Code
0xPlato on X asked for conversations to carry across agents, at least on
one machine. A session row's Continue in (换 Agent 继续) now offers Codex
for a Claude Code session and Claude Code for a Codex one, when the other
is installed. Picking it converts the session then: a new session in the
target's own store, which its own resume opens. Listing converts nothing.

- Claude Code to Codex: a rollout in CODEX_HOME/sessions/YYYY/MM/DD with
  session_meta (model_provider from config.toml now, no
  base_instructions, so Codex uses its own), response_items and the
  event_msg user/agent messages the TUI shows. Codex indexes it on
  resume itself.
- Codex to Claude Code: CLAUDE_CONFIG_DIR/projects/<cwd>/<uuid>.jsonl,
  lines chained by parentUuid, assistant model "<synthetic>" so usage
  counts no call for them.
- Carried: user and agent text, pasted images, shell calls natively
  (Bash and exec_command) with their output, other tools as the agent's
  text (name, input, result in fences, cut at 64 KiB). Dropped: thinking,
  reasoning, signatures, encrypted content, Claude Code's own and Codex's
  context messages. After a compaction only what replaced the history.
- The source is only read. The new file goes through temp, sync, rename
  and never over an existing path. Asking again for an unchanged file
  gives the same session (memo by path, target, size, mtime).
- POST /api/sessions/carry {agent, id, to, open}: copies the resume line,
  or with open (Mac app) opens it in the session terminal. The details
  pane's Continue in line converts from its copy button too.
- Read-only and WSL sessions get no offer. Pi, omp, OpenCode, Kimi,
  Cursor and the rest are not converted.

Run (worktree at 42976f9a0, rebased onto origin/main before push):
- Real use in a sandbox HOME (HOME, CLAUDE_CONFIG_DIR, CODEX_HOME under
  magpie-wt/carry-sb), real binaries Claude Code 2.1.310 and Codex
  0.162.1, through magpie's gateway:
  - Claude to Codex: a Claude session that ran Bash, Write, Read and Edit
    was converted. `codex exec resume <id>` answered what the dog was
    called, which command ran and what was added. `codex resume` showed
    the whole history in the TUI.
  - Codex to Claude: a Codex session with exec_command and apply_patch was
    converted. `claude -p --resume <id>` answered the colour, the commands
    and the function added. `claude --resume` showed the history in the
    TUI.
- Fixtures in internal/sessions/testdata/carry are those real sandbox
  files. Claude's attachment text (system prompt, instruction files) and
  api-request lines were taken out; the line chain is kept.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
  sessions ok (15.7s), gui ok (119s), size budgets among them.
- Broken by hand, each red: Codex context kept (environment_context
  carried), no convert offer (all four TestCarry* red), images dropped
  (TestCarryImagesAndCompaction red). sessions-convert.test.cjs is red
  in chromium on the old client.js.
- GUI (playwright 1.62.0, chromium and webkit): sessions-convert in en,
  zh, zh-TW, ja and de, every sessions-*.test.cjs, i18n-keys,
  click-scroll, gateway-conversations: 424 of 424 pass.
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build.

Not tried: Windows and WSL with real binaries (WSL sessions get no
offer), images through the real binaries (round trip in tests only),
Open in session terminal on a real Terminal (the POST is tested, the
terminal path is the existing openTerminal), a Codex session compacted
by OpenAI (encrypted, not carried), and the full ./... suite.
2026-10-25 12:25:06 +08:00
yetoneandchiperman 6874095b15 gui: the sidebar's gateway line is drawn from boot.js, before the providers' read (#3429, chiperman)
After a refresh the sidebar's gateway line came in about 1.5s late: it
was drawn only by sideGwRead, which waits 1500ms before it reads
/api/providers. chiperman's commit (c1f457a1b) has boot.js carry where
this process's gateway listens, and app.js draw it at once. Ported with
changes:
- api.go puts sideGateway in boot.js only when this process serves the
  gateway (served.Load() != nil), with the URL from gateway.URL(), the
  one /api/providers reports, and marked boot. Another magpie serving
  the port: nothing is sent, and the providers read decides as before.
- app.js starts sideGwAt from boot.js, so the first layoutNav draws it;
  chiperman's separate renderSideGwBoot is folded into that. A value
  from boot.js is read again at 1500ms like before, so /api/providers
  has the last word: served is set before the listen succeeds, so a
  listen that failed, or a gateway stopped since, shows "Gateway
  stopped" then. Without the re-read the boot line could stay stale.
- app.js is 45 bytes under its budget, which is unchanged.
Not fixed here, and pre-existing on main: Settings' address Apply leaves
the line on the old port until a reload (#3531). Seen in real sandbox
apps on main (3483 -> 3486) and with this change (3481 -> 3485).

Tests: TestBootSaysWhereItsGatewayListens (gui) checks boot.js's
sideGateway for 127.0.0.1:3481 and for 0.0.0.0:3483 shown as 127.0.0.1,
and none when this process doesn't serve. sidebar.test.cjs gets the
line from boot.js before any providers read, and a new subtest: the
boot.js line for 3425 is read again and turns to "Gateway stopped" on
3490 once providers says so, with one read.

Run on origin/main 46c418832 at this commit:
- Real app at the pre-rebase c28576084 and origin/main beside it,
  sandbox HOME, `go build -tags dev`, MAGPIE_DEV_UI
  127.0.0.1:3482, gateway on 3481 (main's on 3483), both engines,
  load and two reloads each: main shows the line 1885-2015ms after
  load; this change 70-216ms. One providers read in each.
- gofmt -l: nothing. go vet (darwin) of gui/gateway/cli,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test -count=1 -timeout 45m ./internal/gui/ ./internal/cli/
  ./internal/gateway/: ok (gui 133s, cli 39s, gateway 405s) (TestCoreScriptBudget among them).
- GUI, both engines: sidebar, refresh-page, gateway-port, mobile-web,
  compact-at, routing-kind: 64/76; the 12 reds are sidebar's page list
  missing Insights › Masking, red on origin/main too (#3498). With that
  list given "masking" for the run only, sidebar is 18/18.
- Broken by hand: sideGwAt = null fails 10 sidebar subtests ("the
  gateway's line from boot.js"); the old `!sideGwAt` guard fails the
  new subtest in both engines; `false &&` in api.go fails
  TestBootSaysWhereItsGatewayListens.
- Whole GUI suite at the pre-rebase pair c28576084: see the #3425
  commit before this one; every red file has an issue (#3557 and #3558
  filed for it, #3535 earlier).
- Not tried: Linux or Windows real app.

Co-authored-by: chiperman <34889778+chiperman@users.noreply.github.com>
2026-10-25 12:06:13 +08:00
yetoneandchiperman 00d44d6928 routing: Codex's composer predictions story says their model is picked in Codex's row on the Agents page (#3425, chiperman)
Routing's Kind description for composer_predictions still sent users to
Settings › General › Codex composer predictions. That setting moved to
Codex's row on the Agents page. chiperman's commit (5e372e168) fixed the
Routing text in five languages. It is ported here with their zh, zh-TW
and ja; the de wording is mine.

Grepping for other texts that still name the old Settings place for a
setting that moved into an agent's row found four more, now fixed:
- app.js compactField, the provider editor's "Compact at": empty follows
  Long conversations, now "in their settings on the Agents page (else in
  Settings)". The field's text is one string now, and the header comment
  no longer repeats it, so app.js stays inside its budget (unchanged).
- gateway sealedWayOut: "Codex subagents on any model" is in Codex's
  settings on magpie's Agents page, not "magpie's Settings".
- gateway codex_titles: "Codex composer predictions are off" and "Codex
  titles are off" answers name the same place.
- cli `magpie model` help text.
Each gateway message has a test that fails on the old wording, and the
GUI files assert the new place and the absence of the old one.

Run on origin/main 46c418832 with this commit and #3429's after it (the
pushed pair; the Go and GUI runs below were at the pair's head):
- gofmt -l: nothing. go vet (darwin) of gui/gateway/cli,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test -count=1 -timeout 45m ./internal/gui/ ./internal/cli/
  ./internal/gateway/: ok (gui 133s, cli 39s, gateway 405s)
- GUI, both engines: compact-at, routing-kind, mobile-web, sidebar,
  refresh-page, gateway-port: 64/76; the 12 reds are sidebar's page list
  missing Insights › Masking, red on origin/main too (#3498). With that
  list given "masking" for the run only, sidebar is 18/18.
- Broken by hand: the old app.js/i18n text makes compact-at fail on
  "says where Long conversations is"; the old Routing text makes
  routing-kind fail.
- Whole GUI suite (both engines, -concurrency 4) at the pre-rebase pair
  c28576084: 12,519 tests, 12,350 pass, 169 fail in 31 files. Each red
  file was run alone at that head and at origin/main 641b1217f. All are
  red on main too or pass alone, and each has an issue: the 30 files of
  #3527's list (#3497, #3498, #3488, #3523, #2648, #3479, #3099, #3402,
  #3404, #3500, #3408-#3415, #3094, #2174, #3091, #3104, #3406),
  gateway-caller-keys (#2572, #1671), plugin-github (red alone on main,
  #3218), mobile-web (passes against the commit's base; after the rebase
  it passes at this head), codex-resets-used (#3535),
  routing-busy-frames (#3557) and zhipu-team (#3558). signin-port-blocked's
  11 were ENOSPC from a full disk mid-run; 40/40 alone.
- Not tried: a real Codex session hitting the sealed-task or titles
  message; the text was read in the tests only.

Co-authored-by: chiperman <34889778+chiperman@users.noreply.github.com>
2026-10-25 12:06:13 +08:00
yetoneandEdward4226 46c4188327 gateway: Codex's access_programs goes to OpenAI alone, so OpenCode Go's DeepSeek and GLM answer (#3172)
csic21, HONGs23 and TimWongUp (#3172): a Codex subagent inherits
access_programs {"cyber":"standard"}, magpie relayed it to OpenCode Go,
and Go answered DeepSeek and GLM with 503 "Upstream request failed:
Endpoint is unavailable."; without the field, or with null, 200. Go's
Haiku took it.

Scope: Codex itself sends the field only with a ChatGPT sign-in, or an
API key on its provider named "openai" (codex-rs core/src/
cyber_access_program.rs, for_auth and for_provider; read at openai/codex
970111f6c). It comes to magpie because Codex thinks magpie is OpenAI,
the same reason forVendor takes OpenAI-only parts out (#292). So the
class is "only the upstreams Codex would send it to", not an OpenCode Go
rule: no other vendor has a Cyber program to read, and Go is the one
seen to refuse it. keepsAccessPrograms keeps it for a ChatGPT (Codex)
account, a host ending in openai.com, another magpie (IsRemoteMagpie,
whose own upstream decides) and a codexAsSent relay when Codex sent the
request. Every other Responses upstream, relayed or built (from Chat
too), plugins included, goes without it. A relay that fronts ChatGPT
loses it unless set codex=as-sent, as Codex with a custom provider
would send it none.

- forwardOnce takes it out before the user's extraBody is merged, so an
  access_programs the user wrote there still goes (Edward4226's branch
  did it after, which would override the user's own value).
- withoutTopMember (from Edward4226's branch, using longBody's spans on
  a long body) removes the member, every one of that name, the rest byte
  for byte; a body that isn't a valid object goes as it came. A
  bytes.Contains check first, so a body without it costs nothing.
- Chat and Messages builds never carried it (now tested).
- Docs: gateway-routing.md, providers-accounts.md, ir.go comment.

Run:
- TestAccessProgramsGoToOpenAIAlone (new; fakes by the gateway client's
  RoundTrip, no network): Go DeepSeek/GLM from Codex and from curl, null,
  Chat built as Responses, Zen, a relay, codexAsSent with and without
  Codex's headers, the user's extraBody, OpenAI (daybreak_blue, null,
  from Chat), another magpie, a Chat and a Messages upstream.
  TestWithoutTopMember (new). TestCodexAccessProgramsReachBackend,
  TestAccessProgramsNullKept, TestCodexAccountTakesExtraBody pass.
- Broken by hand, each red: no strip (9 cases: Go, Zen, relay, extraBody);
  IsRemoteMagpie out; openai.com out (3 OpenAI cases); codexAsSent out;
  codexAsSent without fromCodex; Codex account out
  (TestCodexAccessProgramsReachBackend red); strip moved after extraBody
  (the user's value lost).
- gofmt -l clean; go vet -tags nogui ./... for darwin, linux, windows.
- HOME=<scratch> go test -tags nogui -timeout 45m ./internal/gateway/:
  ok (414s), at 42976f9a0 plus this change.

Not tried: a real OpenCode Go account on this head (the reporters' and
Edward4226's real A/B runs show the field alone turns 503 into 200);
OpenCode Zen's DeepSeek with the field (now sent without it either way);
a real Codex collab_spawn end to end.

Co-authored-by: Edward4226 <Edward4226@users.noreply.github.com>
2026-10-25 11:55:16 +08:00
yetone a2ff7e6cab plugin: add takes a community plugin's name (WorkBuddy, think-tags, qoder-cn)
Atlas on Discord (#help, 10-25, Linux): `magpie plugin add WorkBuddy`
said "isn't an npm package name". Worse, a bare `workbuddy` passed the
npm-name check and installed npm's unscoped workbuddy@latest, not
@magpie-community/opencode-workbuddy-auth.

plugin.Add, which the CLI, the Plugins page's field (/api/plugins/add)
and the movers all go through, now resolves a bare name first
(internal/plugin/resolve.go). Case aside, a name one community listing
goes by is its package, at the version given: the package or its bare
name, the short name (workbuddy, think-tags), the shown name (WorkBuddy,
Command Code), a provider id it serves or the subscription it replaces,
and a retired subscription's id through its mover (qoder-cn; provider
sets plugin.SubscriptionPlugin = MovePackage). The CLI says which
package it picked. A name two listings go by, or none that isn't an npm
name, is refused with the community plugins listed. A name no listing
goes by is npm's own package (opencode-gemini-auth keeps working), but
only when the list was fetched within the six hours: when the fetch
fails, the copy kept or built in may not name a newer plugin, so the
name is refused with why, and npm:<name> installs npm's package as
written. market() now says whether its list is a fresh fetch (marketErr).
Scoped names, paths and git specs are unchanged. A backup's or a sync's
plugins go in by their own spec (plugin.AddExact via addPluginExact),
never resolved, so a restore isn't held by GitHub being unreachable.
Update, Upgrade and InstallMissing use add with stored specs, unchanged.

Tests (fake registry over httptest, fake bun; no network):
TestResolveCommunityNames, TestResolveRefusesWhatItCantName,
TestResolveListUnread, TestAddByCommunityName. TestUpdateAllUpdatesAPinnedPlugin
adds an unscoped third-party name, so it now serves a registry.

Broken by hand: Add without resolve -> TestAddByCommunityName red with
the reporter's own error ("WorkBuddy" isn't an npm package name) and
workbuddy -> workbuddy@latest. The unread-list rule turned off (valid
name goes to npm regardless) -> TestResolveListUnread red.

Real use, sandbox HOME, built binary, real npm and GitHub:
`plugin add WorkBuddy` -> installed @magpie-community/opencode-workbuddy-auth@latest,
listed workbuddy and workbuddy-ai; `think-tags` -> middleware-think-tags;
`opencode-gemini-auth` -> npm's, google-plugin listed; `qoder-cn` with
MAGPIE_PLUGIN_MARKET=off -> opencode-qoder-auth; "Work Buddy Pro" ->
refused with the 38 community plugins listed; `twinz` with the list off
or at a dead URL -> refused, saying why and npm:twinz.

Run at this head (rebased on origin/main 42976f9a0): gofmt -l clean;
go vet (darwin) and GOOS=linux / GOOS=windows -tags nogui vet of
plugin, provider, cli, backup, gui clean; go test -timeout 45m
./internal/plugin ok (120s, after the pinned-update fix),
./internal/provider ./internal/cli ./internal/backup ./internal/gui ok.

Not tried: the full ./... suite; Windows and Linux runs of the tests.
No GUI JS changed: the Plugins page's field goes through the same Add,
and its status still says "<typed name> is installed" rather than the
package picked; the installed list shows the package.
2026-10-25 11:52:02 +08:00
yetone 42976f9a08 usage: a renamed provider is shown once, by the id it has now
cybercaius on Discord (#help, 10-25): "已经更改供应商 id 的也没有变更过来反而
分开显示了". Reproduced in a sandbox HOME (magpie web on 3582, fake upstream
on 3583): after renaming myrelay to newrelay in the editor, the Requests
page's provider list had both myrelay and newrelay, each named "myrelay",
because the model-list probe row was still under myrelay. The summary was
already folded; the probe chunk, the Sessions tab's vias and the gateway's
loggedAnswers (lead-first routing) were not renamed at all.

What changed
- provider.Renames (UsageRenames): Of(id, time) is the id a call recorded
  under id at that time belongs to now. Every usage reader goes through it:
  summarizeFrom (and its historical-key set), ledgerMatched, NewPricer,
  NewCoster, the Requests page's gateway blocks, probe rows and other
  computers' days, window holds and their history, buildVias, and
  gateway loggedAnswers. Visit stays as recorded so Of is taken once.
  The summary, Requests and vias caches key on Renames.Key.
- An id reused by another provider no longer pulls the new one's calls
  into the old one. Rename onto, or Save of a new provider under, an id in
  another's Was moves it into that one's Gave with the time (giveID):
  calls before then stay the old provider's. freeID treats Was ids as
  taken, so adding the vendor again gets "-2". Renamed() (refs) skips ids
  a provider or subscription holds now.
- A providers.json that can't be read keeps the last renames read instead
  of none (a failed read is unknown), so usage doesn't split meanwhile.
- History: nothing in usage.jsonl is rewritten. Calls from before this
  release under a renamed id show under the new id at once. An id that was
  reused before this release has no hand-over time, so its calls show under
  whoever holds the id now, as before.

Siblings checked: budget keys by caller key; per-key limits, RPM and
concurrency count live requests by the current id; tray totals go through
QueryPage; codex_memory reads Requested refs. None needed a change.

Run at the tree before the rebase; rebased onto 894603bcd (GUI-only,
none of these files) and provider, usage, usageapi, the build and the
Rename/Answer/Lead tests of gateway and gui run again there: ok.
- TestRenamesByWhenTheIDWasTaken (provider), TestRenamedProviderShownOnce
  (usage), TestRenamedProviderAnsweredItsLead (gateway): each red with its
  piece broken by hand (Save's giveID, freeID's Was, the last-good renames,
  probe rename, vias rename, block pricer's timed path, summarize's time,
  loggedAnswers' rename), green with it.
- go test -timeout 45m provider usage usageapi budget middleware cli agent
  gui gateway sessions profile tui: all ok.
- gofmt -l, go vet ./internal/..., GOOS=linux/windows -tags nogui vet of
  provider/usage/gateway and build of the binary: clean.
- Sandbox: rebuilt binary on the same HOME; /api/usage/requests lists only
  newrelay, the probe row included.

Not tried: the GUI suite (no JS or asset changed; /api/providers gains an
omitempty "gave"), Windows tests run on the Windows box, a real account,
and the full ./... suite (other sessions' suites were running).
2026-10-25 10:53:45 +08:00
yetone 894603bcd8 masking: the Insights card says what Turn on masking masks, and your own words count as on
Lesnolie on X: masking is on and Insights › Masking "stays at 0". Run in a
sandbox HOME, built from origin/main, against a fake upstream: every count
is right. Each case below went chat, responses and anthropic, streamed and
not, in Claude Code and Codex shapes:
- with secrets only on, a request with a key masks it, the summary, the
  shield badge and the day's record under masking/ count it, and the reply
  gets it back;
- an email counts only with Mask personal data on.
The 0 is what the page promised. The off card said "keys, passwords,
computer names and emails become placeholders", but its Turn on masking
button turns on secrets only. Computer names aren't masked even with
personal data on. Everyday agent traffic carries no key, so the count
stays 0, under a line that says a request with personal data shows there.

Now:
- The off card names what the button masks: keys, passwords and tokens,
  and emails and phone numbers once Mask personal data is on.
- With secrets alone on and nothing masked yet, the empty line says only
  keys, passwords and tokens are masked now, and that emails and phone
  numbers are masked once Mask personal data is on, with a link to
  Settings › Privacy.
- Masking with only your own words counts as on, as the gateway's
  masking.Wanted does. It no longer shows "Masking is off" while words
  are masked.

Text in en, zh, zh-TW, ja and de.

Run, both engines (Chromium, WebKit):
- GUI: masking-records, i18n-keys, redact-kinds, privacy-model and
  mask-actions all pass.
- redact-words-any-case is red, 10 of 10, and is the same on origin/main
  641b1217f with the old page.js and i18n.js (#3500, not this change).
- go test -tags nogui ./internal/gui: ok.
- gofmt -l: clean. go vet linux (nogui) and windows ./internal/gui/...:
  ok.
Broken by hand: with origin/main's page.js and i18n.js the new tests are
red in Chromium: en's off card "promises what Turn on masking doesn't turn
on", and every other language times out waiting for the Only keys line or
for the card to be on.
Not tried: the real macOS, Linux and Windows apps, the whole GUI suite.
Not changed (seen while checking):
- Put-back counts, sent text and values live only in the serving
  process's memory, so a window that doesn't serve the gateway, or one
  after a restart, shows none.
- user@host.local counts as an EMAIL.
2026-10-25 10:40:54 +08:00
yetone 641b1217f2 redact: a URL's user:password@host is a PASSWORD and a host, not one EMAIL (#3538)
With Mask personal data on, postgres://app:hunter2pass@db.acme-corp.cn:5432/x
went as app:{{EMAIL_…}}:5432/x: the EMAIL rule took hunter2pass@db.acme-corp.cn,
which starts where the PASSWORD rule's value does and is longer, so it won
the overlap. The kind was wrong and the host the model may need was hidden.

Now an EMAIL match whose start is inside a URL's authority (after
scheme:// with no /, ?, #, space, quote or @ between) is turned away
(notUserinfo, the rule's `at`), and the local model's EMAIL the same way
(modelFits). The password is the PASSWORD rule's and the host goes as
written. An address in a URL's path or query, in mailto: and in prose is
an EMAIL still.

Sibling found on the way: the PASSWORD rule asked for a user before the
colon, so redis://:pass@host (Redis has a password and no user) was not
masked with Mask secrets alone, and was only covered by the EMAIL accident
with personal data on. The user part may now be empty; without that the
email fix would have sent a Redis password as written.

Behaviour change to note: a userinfo with no password
(https://yetone@github.com/..., ssh://git@gitlab...) was an EMAIL and now
goes as written; it is a user name in a URL, not an address. With Mask
personal data on and Mask secrets off, a URL's password now goes as
written, as Mask secrets off says (it went as an EMAIL by accident).

#3029's file names (…@2x.jpg) are untouched: realEmail is unchanged and
TestFileNameIsNoEmail/TestMoreFileNamesAreNoEmail pass. #3365 (rule SECRETs
and known values) is a different rule; this changes nothing it reports.

Test: TestURLUserinfoIsNoEmail (internal/redact/userinfo_test.go) with the
report's literal string, mysql://, amqp://, mongodb+srv://, https://user:pass@,
redis://:pass@, a user with no password, ssh://git@, and emails in prose,
mailto:, a URL path, a query, and a query after a userinfo; a request via
MaskJSON; and the local model's EMAIL.

Broken by hand:
- redact.go and model.go reverted: red, 9 table cases plus the request and
  model checks (the literal went as postgres://app:{{EMAIL_…}}:5432/x).
- model.go alone reverted: red on the model check only.
- the PASSWORD regex's user back to +: red on both Redis cases (with
  personal on it went fully unmasked).

Run at this head (rebased on origin/main d153f0259):
- go test -count=1 ./internal/redact/... ./internal/masking/... ./plugins/redact/...: ok
- go test -count=1 ./internal/gateway/ -run 'Mask|Redact|Privacy|Masked': ok
- gofmt -l internal/redact internal/masking plugins/redact: empty
- GOOS=linux, windows, darwin go vet on the three packages: ok
Not run: the full suite (no suite lock on this machine; owner: don't hold
the push for it). Not tried in the GUI's Try it preview by hand; it calls
the same redact.Preview path the tests exercise.
2026-10-25 09:57:21 +08:00
yetone d153f02593 docs: a privacy masking how-to in en, zh and ja, linked from every docs page
YH31377807 on X asked how to use magpie's local masking (咋用?能出个
教程吗?). The docs had only a short section on the Privacy page.

/docs/masking, /docs/zh/masking and /docs/ja/masking: turning it on in
Settings › Privacy, settings.json for magpie serve and Docker (no CLI
command exists), what each switch masks, an example, how to check it
(Try it, the shield badge on Gateway and Routing, Insights › Masking,
~/.config/magpie/masking), Mask/Warn/Block and Never mask, and limits.
Each docs page's nav and footer link it; the Privacy pages' masking
section points to it.

Checked against the source: the secret rules and personal kinds in
internal/redact/redact.go and more.go (Categories and their defaults),
masking.Wanted and options in internal/masking, the sealed/kept keys in
redact/json.go, Hint for the Block message, gwmw.ErrUnmasked (503) and
maskBlocked (400), the GUI labels from index.html/app.js and their zh and
ja strings in i18n.js, plugins/redact's name. The example's output is
redact.Preview's on that text, run in a throwaway test (placeholders
differ per run's key).

Run: node --test site/worker.test.mjs site/install.test.mjs (31 pass).
The three pages rendered in Chromium and WebKit at 390 and 1280 px with
no horizontal scroll and no page errors; tags balanced.
Not tried: the GUI itself; labels read from source.
2026-10-25 09:51:40 +08:00
yetone 769355ab93 library: an MCP server's startup timeout reaches Codex as startup_timeout_sec, a hand-written one stays (#3168, miaomiaozi)
The Library's MCP server editor has a "Startup timeout" field (seconds),
shown when an agent that reads one is installed (AgentView.Startup; Codex
only). It is written to Codex's [mcp_servers.<name>] startup_timeout_sec,
user-wide and in a project's .codex/config.toml. Empty writes nothing, so
Codex keeps its own 30s, as before. The key and its unit are from Codex's
own source: RawMcpServerConfig in codex-rs/config/src/mcp_types.rs
(cb2581dae8de) has startup_timeout_sec: Option<f64> in seconds, and the
older startup_timeout_ms, which is read only when _sec is absent.

A value the user wrote in config.toml is never written over. magpie
records the value it last wrote (Applied.Startup per agent,
Project.Startup per project file). A value in the entry that differs from
that record, one there before magpie wrote any, or any
startup_timeout_ms, is the user's (startupTheirs), and magpie leaves the
key alone. Once the user takes theirs out, magpie's goes in. The TUI's
server editor keeps the GUI-set value, as it does for OAuth.

Other agents with a startup timeout (Grok Build, Hermes, OpenCode) and a
`magpie mcp add` flag are #3536.

Run, in a sandbox HOME with pinned GOMODCACHE/GOCACHE:
- go test -tags nogui ./internal/library ./internal/tui: ok (162s, 16s).
- New tests: TestCodexStartupTimeout, TestCodexStartupTimeoutKeepsUsers,
  TestCodexProjectStartupTimeout. Broken by hand, each red:
  every existing value counted as the user's -> "startup_timeout_sec =
  120, want 45"; magpie always winning -> "= 20, want 90"; no encode (the
  old code) -> "= <nil>, want 120".
- GUI: new mcp-startup-timeout.test.cjs, Chromium and WebKit, en zh zh-TW
  ja de, 1100 and 390px: 22/22; red on the old client.js (no field).
  The 59 GUI files the change reaches (mcp-*, library-*, i18n-keys,
  gui-de/ja/zh-tw, every editServer/lib-editor file): 935 of 937 pass.
  The red, library-row-remove's hook-row trash in Chromium, fails the
  same way on origin/main 208bd5c48 run alone (2 of 2); it is #3099.
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; linux nogui, windows and darwin builds ok.
- Real Codex: config.toml written by magpie under a scratch CODEX_HOME,
  read by codex-cli 0.162.1 `codex mcp list --json`:
  "startup_timeout_sec": 2.0.

After rebasing on origin/main 208bd5c48: go vet library+tui, linux nogui
and windows builds ok; go test -tags nogui internal/library (130s), tui
ok; internal/gui red once on TestRestartHandsTheGatewayOver (#3451, a
handover EOF, untouched here), then -count=3 alone and the package again
ok; GUI mcp-startup-timeout + i18n-keys 26/26.

Not tried: a real Codex start that actually times out (codex exec needs
a signed-in account in the scratch home); the full ./... suite.
2026-10-25 09:41:32 +08:00
yetone 208bd5c48b gui: Settings descriptions wrap instead of ending in … (arculongus on Discord)
arculongus (English UI, screenshot) couldn't read many Settings rows: the
line under a setting's name ended in "…". The generic `.row .sub` rule holds
a row's line to one line with an ellipsis; a few Settings rows opted out
(`.wraps`) and the rest were cut, among them Image generation's ChatGPT
note, Image recognition MCP server and Web search's Searches for other
models.

Fixed for the class, not the rows in the screenshot: every setting row's
line (`.row.pref .sub`) now wraps whole beside its control. That covers
every Settings part, Plugins › Built-in and an agent's own settings (the
same rows). The control keeps its size (`.prefs .val` is `flex: none`,
max 60%), and nothing else in the layout moves. The window is never
narrower than 560pt, so a row stays a few lines at most. Lines elsewhere (provider
and account cards, chips, URLs) stay one line; their full text is already
reachable through the hover title.

Tests:
- New settings-lines-wrap.test.cjs checks every visible Settings part plus
  Plugins › Built-in, in chromium and webkit, en/zh/zh-TW/ja/de, at
  1000px and 440px. No row's line is cut or nowrap, each control stays
  inside its row, and the page never scrolls sideways (more than 30 rows
  checked). It also checks the three reported rows by name.
- Tests that assumed one-line rows now follow the taller rows:
  - searcher-pick: the help wraps rather than ellipsizing with a title.
  - settings-general: one line only at 1000px, never cut at either width.
  - reader.cjs reach(): goes up to 8,000px, not 2,400.
  - member-model-setting, turn-done, connect-address-kept, tray-cost and
    tray-totals: wheel to the control with reach() before
    clicking, not scrollIntoViewIfNeeded or Playwright's own scroll, which
    the app undoes.
  - update-download, update-restart and tray-totals: a click whose row
    grows a line may scroll, but only to keep the clicked control under
    the pointer (the app's hold, #2134). tray-totals allows 2px, because
    WebKit's whole-pixel scrolls drifted 1.3px over four holds.
  - mobile-web: compares against an origin/main baseline without this
    change.
- Docs: gui-shell.md and gateway-routing.md.

Run (worktree from origin/main a6399dd49, then rebased):
- The new test passes 20/20. Broken by hand: pointed at the old assets
  (MAGPIE_WRAP_ASSETS), it is red 10/10 in chromium and red in webkit
  ("general: a row's line is cut short").
- Whole GUI suite (872 files) in two runs, at concurrency 3-4 and load
  20-150:
  - The 170 Settings-reaching files first: 2515/2575.
  - Then the other 702: 9767/9920.
  - Each red was rerun on settings-wrap-base. The files this change made
    red (settings-general, turn-done, update-download, update-restart,
    member-model-setting, codex-auto-reset-settings, mobile-web,
    connect-address-kept, quota-reads, tray-cost, tray-totals) are fixed
    above and pass on rerun: 86/86, 34/34, 112/112 and 50/50.
  - Also red on origin/main, already filed:
    - redact-words-any-case: #3500
    - s3-sync webkit: #2448
    - usage-checkin Qoder tab: #2549
    - plugin-card-update: #3079
    - builtins and gateway-mode masking tab: #3498
    - fonts webkit: #3227
  - The other files red on origin/main 31bff66be, run alone at a
    comparable count, all have issues: routing-pause #3410,
    routing-rule-effort #3411, routing-rule-remove #3094/#3096,
    routing-intent-entry #3408, routing-live-patch #2174, routing-manual
    #3409, routing-steady #3412, menu-input-scroll #3402, header-centre
    #3479, gateway-caller-keys #2572, gateway-key-models #2648,
    gateway-key-limit #3523, quota-count-wrap #3404, usage-agents-hide
    #3414, usage-fold #3415, usage-ledger #3001/#3104, sidebar and
    gateway-mode #3498, account-discovery #3497, sidebar-overlay-scrollbar
    #1863, account-alias #2984.
  - provider-user-agent failed only on browserType.launch timeouts (load)
    and passed on rerun.
- After the rebase onto b027ca264, these were run again at the pushed head: the
  14 changed or affected GUI files (the new test, the eleven above,
  quota-reads, which main already wheels, and i18n-keys) passed 302/302.
  go test -tags nogui ./internal/gui (budgets included) was ok, with no
  budget raised.
- Before and after screenshots, Settings › Models at 1000px and 700px,
  chromium and webkit, were looked at: the rows that ended in an ellipsis
  now read whole, and each control has the size and place it had before.

Not tried: the real app (WKWebView, WebKitGTK, WebView2). This is a CSS
white-space change with no motion and no new API.
2026-10-25 09:21:42 +08:00
yetone b027ca264d sessions: a pass over every session looks at Codex's title index once (#3493)
assemble and assembleListed asked CodexTitles for each Codex session,
and each ask took the index's lock and stat'ed session_index.jsonl. A
start's stats step assembles every session, so on the owner's data
(sbpairs copy: ~10G Claude, ~50G Codex rollouts) CodexTitles was 60ms
of step 0's 860ms CPU profile. codexTitleOf gives a pass one function
that looks at the index on its first ask and again only when another
reader loaded a different index in between; every caller of assemble
and assembleListed makes one per pass, beside its pricer().

Run at this head (rebased on origin/main below):
- zzwarm step 0 CPU profile on the sbpairs real data: CodexTitles,
  codexTitlesAt and loadCodexTitles 60ms -> absent; statsRead 340ms ->
  270ms cum. Wall times at load 40-76 were within noise both ways.
- TestCodexTitleOfLooksOnce: no index, an index made mid-pass not seen
  in that pass, seen in the next, a rename mid-pass keeps the first
  name. Broken by hand (re-ask on every call): red at "an index made
  after the first ask".
- go test ./internal/sessions ./internal/usage ./internal/gui ok;
  -race ./internal/sessions ok; GOOS=linux/windows go vet -tags nogui
  ./internal/sessions ok; gofmt clean.

Not changed: gui's own CodexTitles callers (trace.go, context.go) ask
for a few ids at a time already.
Not tried: a Linux or Windows real-data run.
2026-10-25 08:40:59 +08:00
yetone 115ca34343 usage: the chunks' file is mapped, not read into the heap (#3493)
A start read requests-v1.bin's 44MB of chunk archives into the heap,
where they stayed: a fifth of the heap at rest, and with GOGC 25 a
larger heap goal through every warm-up step. They are pointer-free and
only ever decoded, so on unix the file is now mapped read-only
(MAP_SHARED, PROT_READ) and each chunk's Archive is a capped slice of
the mapping. A cleanup unmaps it once no chunk refers to it. The file is
only replaced by a rename (toDisk), never written in place; a read past
its end, if another program cut it short, is caught by readMapped
(SetPanicOnFault) as a failed read, not a crash: the chunk unpacks as
nil and reads as no rows, as a corrupt archive did before, until its
session file changes or magpie starts again. Windows can't
rename over a mapped file, so it reads the file as before
(request_disk_map_other.go).

decodeMapped keeps the decode's closure out of unpackReusing: with the
closure there, data escaped to the heap and every row's take() through
it was slower, which made step 2 0.12-0.2s slower than before (found by
profile: unpackReusing.func2 0.28s -> 0.64s over three runs).

Run at this tree, on the owner's real data (sandbox HOME with
.claude/projects and .codex/sessions linked read-only, ~421k rows), warm
runs interleaved with v0.1.1471 (b1f44d099), load 26-32:
- phys_footprint_peak: 285-298MB -> 232-259MB
- phys_footprint at rest: 221-227MB -> 176-179MB
- peak live heap 200MB -> 157MB, heap at rest 198MB -> 147MB
- step 2 (QueryPage All): 771-952ms -> 754-814ms; warm-up 1.68-1.96s
  -> 1.54-1.89s
- every one of the 15624 mapped chunks unpacks to the same rows
  (reflect.DeepEqual, 359553 rows) as its archive copied to the heap
- mmap of the file alone and a CRC pass: 6.5ms, read+CRC 8-10ms

Tests: go test -timeout 45m ./internal/usage ./internal/sessions
./internal/gui ok; -race on the usage request/chunk/page/disk tests ok;
gofmt clean; go vet -tags nogui with GOOS=linux and GOOS=windows ok.
TestRequestDiskChunksMapped checks every chunk read from the file is of
the mapping and that it is unmapped once forgotten; it is red with the
mapping turned off. TestRequestDiskMappingCutShort is red ("fatal error:
fault SIGBUS") with SetPanicOnFault off.

Not tried: a Linux or Windows real-data run (Linux vet only; Windows
keeps the old path); a file truncated under a running magpie outside
the test.
2026-10-25 08:29:23 +08:00
yetone b1f44d099e usage: Codex's effort reuses the pairing the page of its period just made (#3493)
The warm-up builds the Requests page of All and then Codex's model and
effort over All. The page keeps its pairing of the calls (pairMemo, by
chunk serials), but the effort paired every session file's calls again
from nothing, the warm-up's step 3. It now reads requestIndex.pairs[p]
before taking its private copy and pairs through pairRowsMemo, so
unchanged chunks keep their pairing, and it keeps the new pairing for
the next page or effort. Storing a period's pairing is one helper,
keepPairs, that queryPage uses too.

Run at this head (on e1f5f9c16, which origin/main still was):
- TestCodexEffortReusesPagePairing (new): the page pairs once, the
  effort after it pairs 0 times, and equals an effort that pairs on its
  own. Broken by hand (memo -> nil): red, "the effort after the page
  paired again (2 pairings)".
- go test ./internal/usage ./internal/gui ./internal/sessions: ok.
  -race ./internal/usage: ok. go vet -tags nogui GOOS=linux and
  GOOS=windows for usage and gui, gofmt: clean.
- Real data (a copy of the owner's sessions, 421,292 calls), warm-up
  three runs each after one to write the cache file, e1f5f9c16 -> this:
  step 3 0.52-0.58s -> 0.24s; warm-up alloc 1.24-1.29GB -> 1.06GB;
  warm-up 1.80-1.85s -> 1.50s (one 1.77s). Max RSS unchanged (~310-333MB).
- CodexModelEffort(All)'s JSON hash on that data, four runs alternating
  base and this: identical every time (78f93906...).

Not tried: the effort of a period whose page was not built first (it
pairs as before, from nil).
2026-10-25 08:05:33 +08:00
yetone e1f5f9c164 usage: the passes that pair a page's calls read a chunk's strings in place (#3493)
A Requests page decodes each packed session chunk in five passes, one
chunk at a time (chunkRows). Every decode copied the chunk's whole string
section out of the pooled buffer, though four of the passes (folding
Codex's repeated calls, pairing Codex response ids, Claude's repeated
message ids, request-id matching) only look strings up and clone the few
they keep. That copy was the largest allocation of a warm start's page.

Those four passes now read through lentRows: the chunk is decoded into a
buffer the reader owns, and its strings are of that buffer until the next
chunk is decoded over it. The cell pass and every reader that keeps rows
still copy.

What was run, at this head:
- Real data (sbpairs: 421,206 calls, 15.6k session files), warm-up steps
  three runs each, before / after:
  step 2 (first Requests page): 0.88-1.03s / 0.76-0.79s,
  ~560 MB / 446 MB allocated; whole warm-up 1.41-1.45 GB / 1.21 GB
  allocated; maxrss 320-336 MB / 318-319 MB.
- Real pages, base and this change alternately: QueryPage of All, today,
  7d and 30d at offsets 0 and 500, and CodexModelEffort(All). Totals,
  rows and every string are the same; the only differences are float
  costs' last digits, from summation order, which differ between two
  base runs as well (and one new live call).
- Broken by hand: storing the lent message id and request id without
  their clones turns TestRequestPageSameFromPackedLocalChunks red.
- go test ./internal/usage ./internal/gui ./internal/sessions ok;
  -race -run 'TestRequest|Codex|Packed|Visible|Match' ./internal/usage
  ok; GOOS=linux and GOOS=windows go vet -tags nogui of usage and gui
  clean; gofmt clean.

Not tried: the full ./... suite (one suite per machine; only the
packages this reaches were run).
2026-10-25 07:57:24 +08:00
yetone ac149224f9 usage: many rows made since the last write have it written once a run (#3493)
The file of the session files' chunks (requests-v1.bin) was written
only once 64 files' chunks had been made since the last write. Long
sessions that ended since then are few files with many rows: on the
real history (sbpairs) two starts in a row each made 9 files' chunks
again, 84,625 calls (one Claude Code session alone is 52,191), and
neither wrote them, so every start did it again, and the sessions that
ended next joined them until they were 64 files.

noteBuilt also counts the rows made, and writes the file once a run
when they are 20,000 or more. Once, as a session still at work is made
again after each of its calls; the 64-file write is as it was.

Run on 13f907013, and the packages again rebased on 73d17f90c
(usage, gui, sessions ok; vet and gofmt clean):
- real history in a sandbox HOME (the sbpairs copy of the caches), a
  page in each of three processes: before, 9 files (84,625 calls) read
  at each of two starts; after, a start that made every chunk (the
  source changed) and then 0 files read, then 2 (live sessions).
- the rows rule alone on the real history (requestDiskLeast raised past
  15.6k): with no file, a start wrote it (44,275,132 bytes), and the
  next start read it and made 2 files' chunks.
- TestRequestDiskRowsWrittenOnce: red with the rows rule removed ("no
  file of them") and red with the once guard removed ("written again
  for 4 rows").
- go test -count=1 ./internal/usage ./internal/gui ok; go test -race
  -run 'TestRequest|TestQueryPage|TestChunk' ./internal/usage ok;
  GOOS=linux and GOOS=windows go vet -tags nogui on both ok; gofmt -l
  clean.

Not tried: a full go test ./... (one suite per machine).
2026-10-25 07:47:12 +08:00
yetone 73d17f90ce codex: every CODEX_HOME folder's sessions count, its account renewed there
phantom3792 on X: with several ChatGPT accounts kept the way Codex
supports, magpie counted only the default profile's usage, and the
accounts added from the other profiles read no quota.

Codex's mechanism, from openai/codex at 970111f6cb62:
- One sign-in per folder. In codex-rs/login/src/auth/storage.rs the
  sign-in is $CODEX_HOME/auth.json, or the keychain item that
  compute_store_key(codex_home) names.
- Sessions live in the same folder. rollout/src/lib.rs writes sessions/
  and archived_sessions/ under codex_home.
- `--profile <name>` only lays $CODEX_HOME/<name>.config.toml over
  config.toml (config/src/loader/mod.rs), and the sign-in stays shared.
So a second account is Codex run with CODEX_HOME=~/.codex-work, and
magpie read only the folder it runs with.

There were two causes:
- Sessions: codexFiles() walked CodexDir() alone. The sessions list,
  traces and the usage ledger (sessions.Calls) never saw other folders'
  rollouts.
- Quota: an account added by importing another folder's auth.json is
  refreshed from magpie's copy. The import rotates the refresh token,
  which leaves two holders of one token, and whichever refreshes first
  signs the other out. The saved account goes "sign-in has expired" and
  its quota read fails.

The fix:
- appdir.CodexHomes finds the folders: CodexHome first, then folders
  named codex* or .codex* in the home folder or beside CodexHome, or
  one level down in one (~/.codex-profiles/work), that hold auth.json
  or sessions/.
- sessions: codexFiles and Dirs read every folder.
- provider: rememberLogins saves each folder's account with Home set
  to it (codexHomeLogins). The one ~/.codex is signed in to stays that
  folder's.
- renewSaved renews such an account where that folder's Codex keeps
  it (codexHeldIn, as heldByCodex does for ~/.codex). This one funnel
  covers quota, gateway, warm-up, keep-alive and revoked sign-ins.
  codexLoginAuth reads its expiry from the same place.
- switchSavedLogin, NextLogin's spares and forgetLogin leave such an
  account alone. Their errors name the folder and the
  CODEX_HOME=... codex command.
- docs/subsystems/providers-accounts.md gains a row.

Run (worktree at 42ab93551 plus this diff, sandbox HOME, pinned
caches, log kept whole):
- go test -tags nogui -timeout 45m ./internal/appdir/
  ./internal/sessions/ ./internal/provider/ ./internal/usage/
  ./internal/cli/: all ok.
- gofmt -l internal/: clean.
- GOOS=linux and GOOS=windows go vet on appdir, sessions and provider:
  clean. go vet -tags nogui ./internal/gui/: clean.

Rebased onto 13f907013, which changes internal/sessions only. At that
head, sessions and appdir passed in full, and provider -run 'TestCodex|Login'
passed.

Broken by hand, each red:
- codexOtherHomes returning nil: TestCodexOtherHomeAccountReadsQuota
  fails with the reporter's symptom ("sign-in has expired", refreshed
  with the copy's spent token).
- renewSaved without the home path: ~/.codex-work/auth.json is not
  renewed in place.
- switchSavedLogin without its refusal: ~/.codex/auth.json is
  rewritten to the other account.
- CodexDirs returning CodexDir alone: TestCodexOtherHomeSessionsCounted
  lists 1 session, not 2.

Not tried:
- A real second CODEX_HOME with real accounts. The fixtures copy the
  real auth.json shape and the rollout layout, not real tokens.
- A folder outside the home folder that isn't next to CODEX_HOME.
- Codex keeping the other folder's sign-in in the keychain (the reader
  is the same readCodexLogin per folder).
- An entry whose folder was signed out keeps Home and goes back to
  being refreshed from its copy.

Not done (#3530): Codex thread names (session_index.jsonl) and a
config sqlite_home are still read from CODEX_HOME only.
2026-10-25 07:42:13 +08:00
yetone 13f9070135 sessions: a kept file of one day holds that day's models once (#3493)
A long history's kept parses held 28MB live after a start's decode of
sessions.json (15,624 files). 15,345 of them have exactly one day, and
that day's model map is the file's own, so every such file held two
equal maps of ~700B each. decodeCache's share now points the day at the
file's map when they are equal.

A kept state is never written: use, unuse and dropUse are the only
writers of Models, and every parser (sessions.go, calls.go, calls_dsh,
dsh, droid, grok, kimi, cline) writes a clone, which copies the two
maps apart.

Run, at this head on 42ab93551:
- the real sessions.json (sbpairs, 22.8MB): live heap after decode
  28MB -> 21MB, 3 of 3.
- StatsAt(3650) over the real sessions in a sandbox HOME, digest of
  the 96 days before 10-24: a21dc1d1... with this change (twice, the
  second from the cache it wrote) and with the sharing turned off
  (twice): the same.
- TestDecodeCacheSharesOneDaysModels: red with the sharing removed
  ("holds its models twice") and red with clone keeping the shared map
  ("the kept state was written").
- go test -count=1 ./internal/sessions ./internal/usage ./internal/gui
  ok; go test -race ./internal/sessions ok; GOOS=linux and
  GOOS=windows go vet -tags nogui on the three ok; gofmt -l clean.

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

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

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

Not tried: an upgrade of the real app from one release to the next.
2026-10-25 07:23:45 +08:00
yetone 89dc164765 sessions: sessions.json is written a file's parse at a time
A save marshalled the whole index into one buffer: 22.8MB for a long
history (15,624 files), grown by doubling to ~85MB of allocation a save,
and a save follows every refresh that read a changed session file, so a
start while agents run, and a Sessions or Usage poll after any call. It
is written through a json.Encoder into a 256KB buffer handed to a 1MB
bufio.Writer on the temp file, keys in json.Marshal's order and escaped
as it escapes them, so the file is the same bytes.

Measured on the real sessions.json (sbpairs, 22,836,803 bytes):
json.Marshal 54-73ms and 85MB alloc; encodeCache 51ms and 14MB alloc;
the output equal byte for byte.

Run at this tree (3767addd4 + the race skip + this change):
- go test -race -count=1 ./internal/sessions: ok
- go test -count=1 ./internal/sessions ./internal/usage ./internal/gui
  ./internal/agent/...: ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions: ok;
  gofmt -l clean
- TestEncodeCacheIsMarshal compares with json.Marshal for 3002 files (a
  key and a title with <, &, quotes and U+2028, a file of no parse), an
  empty index and none. Broken by hand (keys in map order): red; restored:
  green.

Not tried: the save on Windows or Linux.
2026-10-25 07:17:17 +08:00
yetone ce60cb9908 sessions: TestDecodeFrameKeepsDefinitions is skipped under -race
The test counts what a kept gob Decoder saves, and under -race sync.Pool
lets a quarter of what is put in it go, so the kept Decoder is often a new
one: 158 allocations a frame against 478, over the 1/4 bar. It skips on
raceOn as the package's other pool tests do (TestScanFramesReadsALongFrameOnce).

Run: go test -race -count=1 ./internal/sessions: was red on this test at
3767addd4, ok now; go test -count=1 ./internal/sessions: ok (the test runs
and passes there).
2026-10-25 07:17:17 +08:00
yetone 3767addd4d usage: a block's strings and shapes are read into buffers the next block reuses
Each Requests pass (warm-up step 2's whole-history page, step 3's Codex
effort pairs) decodes every packed block through chunkRows, which already
reused the rows' buffer. Each block still made its strings slice, its
shapes slice and a []int of every string's offset and length, ~170MB of
the ~450MB a pass allocated on a 15.6k-file history. chunkRows now keeps
the strings' and shapes' slices too (unpackReusing), and the offsets are
found by walking the copied section's length prefixes a second time
instead of being stored. The strings themselves still point into one
copy per block, so a row taken from a block keeps its text after the
buffer moves on; only the slices are reused, and nothing holds a block's
slices past the next of().

Measured (real history, sbpairs: 15,656 call shards, gui warm-up steps,
zzbase = 2a3d9f5ae, alternated, two rounds each):
- total alloc through step 3, cold: base 3171/2994MB, new 2610/2626MB
- warm (requests-v1.bin read): base 1763/1751MB, new 1399/1408MB
- times within noise: cold step 2 base 1.86/1.61s, new 1.56/1.85s;
  step 3 0.55-0.79s both

Run at this tree (2a3d9f5ae + this change):
- go test -race -count=1 ./internal/usage: ok
- go test -count=1 ./internal/gui ./internal/sessions: ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage
  ./internal/gui: ok; gofmt -l clean
- TestChunkRowsReuseReadsEachBlock reads blocks of 400, 3, 120, 1 and
  400 rows through one chunkRows against their unpacked rows. Broken by
  hand (keep a string the earlier block left in the buffer): red; restored:
  green.

Not tried: a Windows or Linux run of the warm-up.
2026-10-25 07:06:36 +08:00
yetone 2a3d9f5aeb usage: a session file's rows are made by the reader that read it (#3493)
A cold Requests build (every upgrade) read the call shards eight at a
time, but turned every call into a row on the one loop that takes them:
logRecord, the account resolver, pricing, interning and packing, ~1 s
of serial CPU over a real history, with the readers waiting on the
window behind it.

prefetchSources becomes prefetchEach: each reader has a make of its own
from newMake, and the loop has its own for a source not wanted. Request
rows are made there. Each make has its own Pricer and Swapped memo, so
neither needs a lock; the session resolver is made once (sync.OnceValue)
and only read after. The serial number is still given in the loop, in
source order. The window now holds packed chunks, smaller than the
calls it held.

Measured on a copy of real data (15,656 shards, 3,451 Claude Code
subagent meta files), GUI warm-up step 2 (QueryPage(All)), cold
(requests-v1.bin written for the other binary), alternating runs:
- before (432393217): 3.24 s / 448 MB maxrss, 2.18 s / 433 MB
- after: 1.85 s / 417 MB, 1.84 s / 410 MB
The readers are now mostly in syscalls (shard and meta.json reads).

Run at this head (432393217 + this):
- go test -count=1 -timeout 45m ./internal/usage: ok; with -race: ok
- go test -count=1 -timeout 45m ./internal/gui: one red,
  TestRestartHandsTheGatewayOver (18 of 19 requests answered, EOF), the
  open #3451; alone -count=5 it passes. Load was ~45.
- TestPrefetchEachMakeIsAReadersOwn: 9 makes (8 readers, the loop's
  own) and no race. Broken by hand: one make shared by every reader ->
  -race reports DATA RACE, red.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage ok.
2026-10-25 06:58:27 +08:00
yetone 432393217a sessions: a shard's gob definitions are compiled once, not once a shard (#3493)
Every call shard's frame is its own gob stream: callFrame's type
definitions, then the frame. loadCalls made a gob.Decoder for each, so
each of a start's ~15.6k shards compiled the same definitions again. A
cold Requests build (every upgrade, since requests-v1.bin is keyed on the
binary) spent ~400 MB of its allocation and most of its GC there.

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

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

Run at this head (94503901c + this, origin/main has only 402577c15 in
internal/gateway since):
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage: ok
- TestDecodeFrameAsAFreshDecoder: every frame equals a fresh Decoder's,
  a frame of other definitions in between, and cut, padded, empty and
  definitions-only frames are errors that leave the next frame reading.
- TestDecodeFrameKeepsDefinitions: 8 allocations a frame kept vs 478
  fresh.
- Broken by hand: always a fresh Decoder -> KeepsDefinitions red (479
  vs 478); reuse without comparing definitions -> AsAFreshDecoder red
  ("unknown type id or corrupted data" on the other writer's frame).
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/sessions ok.
2026-10-25 06:45:23 +08:00
yetone 402577c15a gateway: image generation is an MCP server on the gateway, /mcp/magpie/image
JonahFu on X runs magpie in Docker in gateway mode, so he has no Library and
no stdio Magpie Image server, while image recognition is an HTTP MCP server
on the gateway (/mcp/magpie/vision). Now image generation is one too, with
the stdio server's tools: generate_image, generate_video and
generation_result, drawing with Settings › Images › Image generation.

- image_mcp.go: served by serveMCP, so it is guarded as the vision server
  is (local or a shared magpie's caller, a refused Origin 403, POST only,
  the key's limit reserved per call). A drawing is s.images run in-process
  on a clone of the request (caller and key kept), so routing, key models,
  usage and the timeout setting are draw.go's own. It runs as a job (15
  min at most); the tool answers within 20s or gives an id that
  generation_result waits on. Images come back as MCP image content (5 MB
  each at most) and at /mcp/magpie/image/files/<name>, kept in memory an
  hour, 256 MB at most, readable only by the key that made them. Videos
  go through videosCreate/videosGet in-process and are given as
  /v1/videos/<id>/content. Image generation Off is a tool error naming
  where to turn it on, before the arguments are read.
- Input images go through the vision server's reader, now mcpImageSrc
  (vision_mcp.go), so a file path is read only for a local caller.
- The tool schemas live in the gateway (ImageToolProps, VideoToolProps,
  ResultToolProps); internal/imagemcp takes them and adds only its path
  argument. Its tools/list JSON was compared byte for byte with the old one.
- Settings › Models: #imageMcpRow under #visionMcpRow with the address and
  a copy button; the gateway-mode Image generation sub now points at it.
  en, zh, zh-TW, ja, de.
  The two rows are drawn by one helper (mcpRow), which took the vision
  row's own code, so the row costs 462 bytes of app.js.
- core_budget_test: appScriptBudget 1,321,336 -> 1,321,424 and
  coreScriptBudget 1,528,525 -> 1,528,972, the exact sizes with the row,
  with no room added (10-25). Nothing moved out: the row is Settings'
  own, which the core draws.
- search-api.test.cjs: the new row pushed the search row partly below the
  1400px window at 420px, where scrollIntoViewIfNeeded leaves it, and
  magpie puts back a scroll the reader didn't make, so the test's
  coordinate clicks missed. It now brings the whole row on screen with
  the wheel and checks it is still there a second later. Red with the new
  row before this, green after; green on origin/main's GUI either way.
- oneport_test knows ImageMCPPath and ImageMCPFiles (ClientPath covers
  them).

Run (worktree at this commit, on origin/main 94503901c):
- go test -tags nogui -run 'ImageMCP|VisionMCP|ClientPath|SearchMCP'
  ./internal/gateway/ ok; ./internal/imagemcp ok; the image and vision MCP
  tests with -race -count=3 ok.
- Red on the old code: TestImageMCPDrawsAndServesTheImage (the route is
  404).
- Broken by hand, each red: no route (DrawsAndServes), no key check on
  files (Guarded), no Off check (SaysWhenOff), no reserveFor
  (HeldToKeyLimit), no local-only file read in mcpImageSrc (Guarded).
- GUI, chromium and webkit, every language, at this commit: image-mcp,
  vision-mcp, i18n-keys, images-library-way, search-api,
  settings-sections, gui-de, gui-ja, gui-zh-tw (123/123). Before the
  helper and the rebase: image-mcp, vision-mcp,
  images-library-way, images-codex-one, image-timeout-setting,
  images-missing, i18n-keys, gui-de, gui-ja, gui-zh-tw, settings-sections,
  vision-not-marked (201/201); claude-lean-prompt-setting,
  classify-timeout-setting, disabled-models, member-model-setting,
  loop-guard-setting, refusal-retries-setting, search-first, search-order,
  search-mcp, searcher-pick, side-effort, search-api, search-keys (198/198
  after the search-api fix; search-api alone 8/8 twice).
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- Full suite (go test -tags nogui -timeout 45m ./...): the run before the
  helper was red only in TestCoreScriptBudget, fixed above; a run at this
  commit was started and not finished at push (pushed at once, the
  owner's rule), its result goes on the push report.
- Real: magpie serve (nogui) in a sandbox HOME on 127.0.0.1:3592, its
  Image generation a provider pointed at the live gateway's
  codex/gpt-image-2.5. curl: initialize (Magpie Image), tools/list (the
  three tools), Origin https://evil.example 403, GET 405, an unknown file
  404, GET /v1 lists /mcp/magpie/image, Off answers the Off text for both
  tools. generate_image reached Codex through the live gateway and came
  back as the tool error "yetoneful@gmail.com's sign-in has expired".

Not tried: a real image drawn end to end (the only drawing account's
sign-in has expired; image content and file URLs are covered by fake
upstreams), a real video, a call from another computer with a gateway key
(the remote and key paths are covered by TestImageMCPGuarded), Docker.
2026-10-25 06:42:03 +08:00
yetone 94503901c0 sessions: a string many kept files repeat is held once
decodeCache's Unmarshal made a string for every file's title, cwd and
model names, however many files gave the same one. On the real history
copy (sbpairs, 27,699 kept files) 23,689 sessions a script ran carry one
~420-byte prompt as their title. The kept parses held 54 MB after a
collection, 11 MB of it such copies. Each decode worker now takes those
fields (title, cwd, first, named, model, provider, msg_model, msg_day,
codex_nickname, and the Codex identity's role and parents) through
unique.Make, so the parses hold 44 MB. The decode took 104-114 ms, as it
did (121 ms when measured for e2dbb0340).

One QueryPage(All) from requests-v1.bin under GOGC=25, as the GUI's
warm-up runs it: max RSS 319-327 MB -> 296-305 MB. From cold (no file):
390 MB, against 448-462 MB before this and 31bff66be.

TestDecodeCacheSharesRepeats decodes 2000 files of two titles and one
cwd, model and role, and counts the copies held. It is red with share
taken out (2000 of each).

Run at this head: go test ./internal/sessions ./internal/usage (ok);
go vet ./internal/sessions, GOOS=linux and GOOS=windows -tags nogui;
gofmt -l. Not run: the full suite (one per machine).
2026-10-25 06:27:13 +08:00
yetone 31bff66be3 usage: a session file's few calls are kept packed too
pack left a chunk of fewer than 64 rows as rows. Most session files hold
a handful of calls, so a cold build (the first start after an update, or
with no requests-v1.bin) kept 13,972 of 15,624 local chunks unpacked:
98,320 rows. The same chunks read back from requests-v1.bin are all
archives, so the cold build alone held them as rows. Now every chunk with
a row is packed when its archive is smaller, as the file's entries
already were.

Measured on the real history copy (sbpairs: 15.6k session files, 420k
calls), one QueryPage(All) from cold under GOGC=25 as the GUI's warm-up
runs it, three runs each, old then new:
- heap in use after: 267/267/269 MB -> 229/227/232 MB
- peak heap in use: 357/367/341 MB -> 308/338/336 MB
- max RSS: 454/462/448 MB -> 420/424/449 MB
- page: 2.95/2.41/2.52 s -> 3.66/2.19/2.42 s (no change past noise)
A page after a new call, packed chunks read from the file: 120-143 ms,
as before.

TestFewRowsArePacked packs three rows and reads them back. It is red
with the old 64-row floor.

Run at this head: go test ./internal/usage (ok);
go test -run 'Usage|Request|Tray|Session' ./internal/gui ./internal/gateway
(ok); go vet ./internal/usage, GOOS=linux and GOOS=windows
-tags nogui; gofmt -l. Not run: the full suite (one per machine).
2026-10-25 06:20:17 +08:00
yetone e2dbb03405 sessions: the kept parses are decoded on a few goroutines at start
One json.Unmarshal of sessions.json (40MB, 27,679 files on a long
history) took 310 to 440ms of every start before the first page (#3493).
decodeCache checks the file is valid JSON (gjson), reads its version and
zone, splits the files without copying them, and decodes each file's
parse with json.Unmarshal on up to 8 goroutines. The result is what one
Unmarshal gave: a key given twice is its last, and the file is refused
where it was refused (bad JSON, another version or zone, no files, a
parse that doesn't decode). Only the keys are copied out of the read.

Real data (sandbox copy of the live sessions.json, load ~60): Unmarshal
311ms, decodeCache 121ms, reflect.DeepEqual the same 27,679 parses.

Run at 5d2260d3e (origin/main, fetched): go test -timeout 45m of
sessions (14.6s), usage (18.4s), usageapi (7.9s), cli (35.9s) and tui
(15.4s) ok; TestDecodeCacheIsUnmarshal -race ok. gofmt clean; GOOS=linux
and GOOS=windows go vet -tags nogui ./internal/sessions/ clean.

TestDecodeCacheIsUnmarshal (new) compares decodeCache with Unmarshal on
3000 files, escaped keys, a null parse, a key given twice, no files, an
old version, another zone, a bad parse first and last, a cut file,
trailing bytes, a missing comma and garbage. Red with the validity check
taken out (trailing, missing comma), with a bad parse ignored, with the
first of two keys kept, and with the zone not compared.
2026-10-25 06:09:30 +08:00
yetone 611b9e1731 redact: what the local model misreads in agent requests is not masked
With "Use a local model" on, the model masked far more than the rules
did. Over 3 MB of real Claude Code requests (19,258 texts, the fields
MaskJSON leaves as sent skipped) the model alone masked about 1,800
pieces before this change, almost all wrong; the rules masked 17. It
took the turn's <total_tokens> count, run ids, commit hashes and
versions for accounts; Claude, Opus and other model names, a user name
inside a path and skill names for people; pieces of toolu_/srvtoolu_
ids, of base64 images, bare hashes, grep alternations, session file
names, links and Go module-cache names for secrets.

modelFits now judges each span the model reports against the text
around it: a span cut out of a longer word is no finding; a person's
name has no digits, path signs or lowercase words (bar van, de, bin and
the like) and no assistant's name; an account or phone number is
number-like and not a hash, version or size, and a bare run of digits
needs a cue before it ("account", "卡号", "phone", "手机"); a secret
starts with a letter or digit, is not a link, a UUID, a pattern of
words or a piece of a base64 run, and a bare hex run needs "key",
"token", "password" or 密钥/密码/令牌 before it. madeID takes prefixes
up to 8 letters (srvtoolu_).

After: the model masks 32 pieces on the same texts, 13 of them real
email addresses; what's left wrong is mostly a lone capitalised word
(Rerun, Relay, Xferd, Alma). On the synthetic set rules+model miss 1 of
20 secrets (rules alone 4) and flag 0 of 15 clean texts. The default
stays off.

Run at this head (rebased on 5d2260d3e):
- go test ./internal/redact: ok. TestModelMisreadsNotMasked holds the
  real bytes of 23 misreads, TestModelFindsStillMasked 9 real finds
  (an account with its cue, Rina Kowalczyk, Ludwig van Beethoven, a
  mobile and a London number, an address, a secret, a cued hex key,
  an email). With modelFits taken out of modelSpans by hand, 17 of the
  first 18 misreads went red.
- The corpus and synthetic measurement with the real privacy-filter
  q8 model (a scratch test, not committed; the corpus stays local).
- go vet (darwin, linux, windows) and gofmt on internal/redact: clean.
- Full suite (-timeout 45m, behind other sessions' runs): queued, not
  finished at push.

Not tried: the GUI, since nothing in it changed; a request through a
running gateway with the model on.
2026-10-25 06:05:06 +08:00
yetone 5d2260d3e6 usage: the Requests page's chunks are kept on disk, so a start doesn't open every call shard again
A started magpie opened every session file's call shard (~15.6k on a busy
machine) and turned each call into a row again before its first Requests
page could show (#3493). requests-v1.bin (beside sessions.json) now keeps
each session file's chunk as the page packs it: an entry stands while its
file's size and mtime are the same, as a call shard does, and the whole
file while the binary that wrote it and the index's root and meta (prices,
names, providers) are the same. Each entry has a length and CRC-32; a bad
one ends the read and the entries before it stand.

- The file is read when 64 or more session files want reading (a start, a
  change of prices), and written behind the lock once 64 or more chunks
  were made since the last write; fewer are a few shard reads next start,
  not worth writing the whole file again. The idle trim does not write.
- A chunk of another computer's day is not kept; times keep their zone
  (Local, UTC, a tz-database name or a fixed offset).

Real data (sandbox HOME with the live ~/.codex/sessions and
~/.claude/projects symlinked read only, 15,603 sources, 420k rows, load
~90 to 130): a cold All page 3.6s; written in 76 to 168ms behind the lock,
44MB. A start from the file: fromDisk 50ms for 15,602 chunks, then the
blocks 100ms, against the shard reads before; the whole page 1.5s, most of
it now readRequestState (0.65 to 1.1s), which is next. Same total, cost
and input as the cold page.

Run at 500aa7096 (origin/main, fetched): go test -timeout 45m of usage
(14.7s), usageapi (6.5s) and gui (143.5s, before the idle-save removal,
which touches no GUI path) ok; TestRequestChunksFromDisk -race -count=3
ok. gofmt clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/usage/ clean.

TestRequestChunksFromDisk (new): a start reads no session file, a file
written over to the same size is read again for its mtime, new prices read
every file, a file cut short stands for the entries before the cut, and
garbage reads every file; every page equals the ledger's. Red with the
header compare taken out, with the size/mtime check taken out, and with
the write skipped.
2026-10-25 05:54:24 +08:00
yetone 5b32b7ea80 plugins: a Bun Windows can't load (0xc0000139, before 10 1809 / Server 2019) says so and what to do (zgcwkj on Discord)
zgcwkj runs magpie-cli-windows-amd64.exe as a Windows service (nssm) and
every plugin install failed with "bun add …: exit status 0xc0000139: (and
from the community repo's dist branch: bun add ./dist/….tgz: exit status
0xc0000139: )".

Why: 0xc0000139 is STATUS_ENTRYPOINT_NOT_FOUND, the loader refusing the
exe before it runs. Reading the PE imports (debug/pe) of Bun's
windows-x64(-baseline) zips: 1.3.14 and later, so magpie's floor 1.4.2
and the latest 1.4.4, import kernel32's CreatePseudoConsole,
ClosePseudoConsole and ResizePseudoConsole, which Windows has from 10
1809 (build 17763) / Server 2019 on. 1.3.13 doesn't. Bun's docs say
"Windows 10 version 1809 or later" (bun.com/docs/installation). So
Windows Server 2016 and Windows 10 1507 to 1803 (LTSB 2015/2016) can't
run any Bun magpie uses. 1.4.2's pinned SHA-256 matches the asset.

What changes:
- wontLoad (internal/plugin/bun.go) reads an exit of 0xc0000139 as
  "this Windows" and 0xc000001d or SIGILL as "this processor" (Bun's x64
  build targets SSE4.2), as a *BunUnstartableError whose message says
  which, the versions Bun needs, and MAGPIE_BUN.
- bun add, bun update, cantStart and whyDied (the host's start) wrap it.
- An install no longer tries the dist branch after it: that bun add
  can't start either, and its error read as the dist branch's.
- The GUI's fail() answers it with code bun_unstartable, bunWhy and
  said, an i18n.js key (bunSaid in api.go), which api() in app.js puts
  through t(): en, zh, zh-TW, ja, de, in the window and in magpie web.
  The sentences live in Go so app.js grows one line: with both in
  app.js, TestCoreScriptBudget was 128 bytes over app.js's budget and
  487 over the core's, and no budget is raised here.
  TestBunSaidIsTranslated fails when a language lacks one. The CLI
  prints the English message.
- No fallback to an older Bun: 1.3.13 is below BunVersion and Bun
  doesn't support that Windows, and the -baseline assets are now the
  same binary.
- docs/subsystems/provider-plugins.md says all this.

Run:
- New tests: TestWontLoadSaysWindowsOrCPU (injected NTSTATUS exits, a
  real kill -ILL), TestInstallOnUnstartableBunSaysWhyAndSkipsDist (0
  dist requests), TestHostOnUnstartableBunSaysWhy, TestFailSaysBun
  Unstartable, TestBunSaidIsTranslated, plugin-bun-unstartable.test.cjs (chromium and webkit,
  every language, window and web).
- Real Windows (10.0.26200 box, a sandbox dir of its own): a
  windows/amd64 nogui magpie-cli.exe with a fake magpie-bun.exe that
  exits 0xc0000139, `plugin add @magpie-community/opencode-raccoon-auth`
  printed the new message, and no dist folder was made.
- gofmt -l; go vet darwin, linux -tags nogui, windows; builds of all three.
- Full suite (go test -tags nogui -timeout 45m ./..., through
  suite-lock, at a6399dd49 plus this change with both sentences in app.js):
  every package ok except internal/gui's TestCoreScriptBudget (128
  bytes over app.js's budget, 487 over the core's). After the sentences
  moved to bunSaid: internal/gui and internal/plugin ok, budget
  included (core 1,528,331 of 1,528,525 before scoping the line to the
  code, ~20 bytes more after).
- GUI (chromium and webkit, node --test): i18n-keys, every plugin-*
  file and signin-paste-plugin, 660 of 660 before the move to bunSaid;
  after it 656 of 660 at load ~140: plugin-card-update webkit (#3079)
  and plugin-quota-error chromium ja, whose Chromium launch hit
  Playwright's 180s timeout before the test ran. Both files alone: 16
  of 16, 14 of 16 (which one not kept), 16 of 16, 16 of 16.
- Rebased on ff6090354: TestCoreScriptBudget, the new Go tests,
  plugin-bun-unstartable and i18n-keys again ok; gofmt; windows and
  linux vet of internal/plugin and internal/gui.

Broken by hand (each restored):
- wontLoad always nil: the three plugin tests fail, the install one
  with the reporter's exact "(and from the community repo's dist
  branch: …)" shape.
- the dist skip removed: 1 dist request.
- the whyDied check removed: the host test fails.
- fail()'s block removed: the gui Go test fails.
- app.js's line turned off: the GUI test fails, 16 of 16 (chromium).
- one language's key renamed: TestBunSaidIsTranslated fails (3 of 4).

Not tried: a real Windows before 1809 (the box is Windows 11) and a real
processor without SSE4.2; zgcwkj's Windows version is still unknown.
2026-10-25 05:54:07 +08:00
yetone ff6090354e gateway: dsh's session and compaction marks are held on Messages and Responses too (#3298)
A user's own dsh llm-deepseek row pointed at magpie (e3491e2bb's docs)
calls /v1/messages with x-deepseek-harness-session-id and
x-deepseek-harness-compact. #2505 reads both in sessionOf/dshCompacts
for every route already, but TestDshMarksSessionAndCompaction only
covered /v1/chat/completions. TestDshMarksOnEveryRoute sends both marks
(and llm-deepseek's x-deepseek-harness-user-id) to /v1/messages on an
Anthropic provider and /v1/responses on a Responses provider, and checks
the recorded session, kind "compact" or none, and that the vendor gets
no x-deepseek-harness-* header. No behaviour changes: this guards what
the docs now tell users, and so it passes on the old code too.
docs/subsystems/gateway-sessions.md names it.

Broken by hand: dropping x-deepseek-harness-session-id from
sessionHeaders turns all four cases red (session ""); making dshCompacts
always false turns both compact cases red (kind ""). Restored after
each.

Run before the rebase onto 500aa7096: go test ./internal/gateway
-count=1 -timeout 45m (ok, 450s). At this head, after it (500aa7096
changes internal/sessions only): go test ./internal/gateway -run
'TestDshMarks|Session' ok, go test ./internal/sessions ok; gofmt -l internal/gateway empty; GOOS=linux and
GOOS=windows go vet ./internal/gateway ok. Real dsh 0.2.1-rc.2 through a
sandbox magpie recorded its session on /v1/messages (see e3491e2bb).

Not tried: streaming on these two routes in the test (the real dsh run
streamed /v1/messages), Windows test run.
2026-10-25 05:51:52 +08:00
yetone e3491e2bb0 docs: point dsh's own DeepSeek row at magpie by hand (#3298)
tom047784 (Discord) wants dsh's llm-deepseek row, which keeps DeepSeek's
cache across in-history prompt and tool updates and uploads images
through the Files API, to go through magpie. magpie doesn't take that
row over (the key would mean two things, it would override the user's
own entry, and a file_id belongs to one account while magpie fails
over), so this documents the entry a user writes themselves:
docs/reference.md under "Notes on some agents", and a FAQ entry in
site/public/docs start.html (en, zh, ja).

Checked against @deepseek-ai/dsh-llm-deepseek 0.2.1-rc.2's source
(npm pack into a scratchpad, read only): messagesApiRoot adds /v1 to
baseURL unless it ends in /v1; apiKeyEnv is a credential reference read
from dsh's credentials and then the environment; an explicit models list
replaces DEFAULT_MODELS, whose in-history/addition-only settings are on
deepseek-flash only; any Files failure rebuilds the request inline,
bounded by maxInlineRequestImageBytes (20 MiB) against
maxRequestFilesBytes (128 MiB). Against magpie: internal/agent/dsh.go
drops only magpie-marked llm-deepseek entries and removes
MAGPIE_GATEWAY_KEY on Disconnect; POST /v1/files answers 404; the
catalog ids are deepseek/deepseek-flash and deepseek/deepseek-v4-pro.

Tried: real dsh 0.2.1-rc.2, `dsh --profile headless`, sandbox DSH_HOME
and HOME, a magpie built from this tree on its own port. Through a fake
Anthropic upstream: "say pong" answered; the upstream got
output_config.effort, thinking, tools, dsh_session_log and
dsh_plugin_packages as sent, the provider's key, and no
x-deepseek-harness-* header. A mid-history system message with
tool_addition and the mid-conversation-tool-changes anthropic-beta went
through unchanged (curl). With a real DeepSeek key copied into the
sandbox: dsh read a file with a tool, three calls all 200, cache_read
5760 on a later call; a system message added in the history after two
turns was followed and cache_read_input_tokens was 3456. Usage rows had
agent dsh, /v1/messages and dsh's session; x-deepseek-harness-compact: 1
recorded kind compact.

Not tried: an image turn through dsh (the inline fallback is from the
source and the 404), the desktop app and its Models-page key entry,
Windows.
2026-10-25 05:50:34 +08:00
yetone 500aa70965 sessions: listing the session files stats them on a few goroutines and sweeps the shard folder once a minute
Every Requests page lists every session file again
(CallSourcesAndCodexIdentities), and on a busy machine that listing was
most of a warm page after the pairing memo (#3493): ~130ms for 15.6k
Codex rollouts and the Claude Code transcripts, of which the lstat of
each rollout was half, stat()ing each Claude file a sixth, and
pruneCalls a sixth: it read the ~16k-shard cache folder and sha256'd
every path on each call.

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

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

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

Tests: TestCodexFilesStatInOrder (new; 1500 rollouts with folders,
links and files of every size in one day, -race -count=3) is red when
statFiles keeps what failed to stat and when a worker skips half its
batch. TestCallShardsSweptOnceAMinute (new) is red with the gate taken
out. TestAbandonedCallTempsAndLRU now clears the gate before the call
that must sweep.
2026-10-25 05:42:59 +08:00
yetone 49ba48739a gui: a cost that isn't a number shows nothing, not a throw over the page (#3406)
fmtCost read t.cost and called toFixed on it. A total with no cost
(null, or a reply without the field) threw "undefined is not an object
(evaluating 'c.toFixed')" in renderUsage (plugins/usage/page.js), so the
Usage page stopped drawing and the error's status line sat over the
window's foot. In quota-reads (#3406) that line covered Settings'
Allowance reads button at de 360 in WebKit, 2 of 11 red on main.
magpie's own /api/usage always sends a number (internal/usage/usage.go,
no omitempty), and the test's fake answers {}, so a user meets this only
on a reply without a cost. A cost not read is unknown, so it now shows
nothing, not $0.

quota-reads: once the page error was gone, de 360 in WebKit was still
red. The button sits at 392-414 under a view that ends at 392, and the
app puts back the scroll Playwright makes, so the click landed on the
footer. The test now wheels to the button with reader.cjs's reach, as
a reader would, and fails when the page shows an error status.

Run at a6399dd49 plus this change (origin/main was 4982ded8a at fetch,
which changes no GUI file):
- quota-reads, both engines: 22 of 22 (was 9 of 11 in WebKit).
- currency, tray-cost, tray-totals, routing-request-metrics and
  api-key-usage, both engines: 92 of 92.
- i18n-keys 4 of 4; go test -run 'Budget|I18n|Asset' ./internal/gui ok.
Broken by hand: with the old fmtCost line and the new test, quota-reads
is 0 of 22 in both engines ("an error is shown: ... toFixed").
Not run before the push: the whole GUI suite (started after it) and
go test ./... (no Go change).
2026-10-25 05:32:34 +08:00
yetone 4982ded8a6 usage: a turned page reuses the last pairing while its chunks are the same
A Requests page paired every Codex session file's calls with the
gateway's again on each query: clone, fold forks, match response ids.
That unpacked every session chunk three times and was about half of a
warm page (#3493). pairRowsMemo names the chunks of a pairing by their
serials (the probe chunk, which has none, by its rows' log offsets and
times) and keeps what the pairing found: the rows left out (skip,
matched), the actors it changed and each chunk's compactions. The next
query over the same chunks and window applies that to fresh clones
instead of pairing again. A changed file gets a new serial, a new
window or period misses, and adopt drops the memos with the parts.

Run at a6399dd49 (= origin/main, fetched):
- TestRequestPairsReusedAcrossPages (new): a gateway call paired with
  its rollout, a fork copying another file's call and a Claude call,
  every page of All/Today/Week at limit 1 and the whole page against
  pageFromLedger. Broken by hand three ways, each red on the memo hit:
  apply without matched ("all page 1: 4 rows, 157 input"), without skip
  ("4 rows, 127 input"), without compactions (page differs).
- Real data, same process (scratch test, not committed), fresh pairRows
  vs the memo applied over a second read: sandbox with the live
  rollouts (symlinked, read only) and a copy of usage.jsonl: All 15607
  chunks, 4801 skip, 1469 matched, 2 actor sets; Today 58 matched; 7d
  1075 matched. Actors, compactions, skip, matched equal, and pages
  equal for 3 filters per period. Without the gateway log: All 15600
  chunks, 4801 skip, all periods equal.
- Timing on that sandbox (load 110-143), page turns after the first:
  v0.1.1449 mean 407 / 460 ms, this change 154 / 145 ms.
- go test -count=1 -timeout 45m ./internal/usage/... ./internal/usageapi/...
  ./internal/sessions/...: usageapi and sessions ok; usage red only on
  TestUsageReadAfterAppendHashesNothingOnAFineClock/whole-second_stamp,
  which is #3511 (taken by another session). At -count=20, load 154,
  it fails 3/20 here and 2/20 at the base 1313b047f; it builds no page.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ok.

Not tried: the GUI against a live gateway; the page reads the same
QueryPage the tests and the real-data run used.
2026-10-25 05:18:41 +08:00
yetone 3387ea6156 gateway: an Antigravity drawing out of the image model's quota goes on to the next account and rests that model there (01huadalang)
01huadalang (Discord): with several Antigravity accounts, when one
account's image quota is spent, magpie doesn't move on to the next.
Model, entry point and error text were asked for and not answered yet.

What every image path does (generate_image MCP and /v1/images both go
through images() -> drawOnAccounts -> drawCodeAssist; a chat on the
image model goes through serve's candidate loop):
- A 429 (antigravityQuota, "You have exhausted your capacity on this
  model. Your quota will reset after 3h19m30s.") already went on to the
  next account, but rested nothing, so every drawing asked the spent
  account first again.
- Antigravity also says a model's quota used up as a 200 whose stream is
  the error event (the Code Assist decoder keeps its message; the chat
  path's TestAntigravityTurnedAwaySaidInsideTheReply). drawCodeAssist
  told every such error as 502, which accountRefusedDrawing doesn't move
  on for, so the drawing ended on the spent account while the next had
  its quota. The chat path already fails over on it.

Fix (internal/gateway/draw.go):
- saidStatus: an error said inside a drawing's 200 is 429 when its words
  say quota or rate (usedUpWords, quotaCodes, rateWords), 402 for credit,
  else the 502 it was. drawCodeAssist uses it, and so does the images
  API's 200 with no image (its sibling).
- restDrawer: an account's drawing refused as failQuota (failure) rests
  the image model on that account alone (restID, Rest.Model), until the
  reset the refusal names (resetsAt) or quotaRest, held to longestQuota.
  The account's text models aren't touched; keys and other failures rest
  nothing, as before. candidates' restLast then asks the accounts that
  still have the model first.

Tests (internal/gateway/antigravity_draw_test.go), Antigravity's real
QUOTA_EXHAUSTED 429 body (antigravityQuota) as a 429 and as the stream's
error event:
- TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn
- TestAntigravityDrawingQuotaRestsTheImageModel (u1 then u2, then u2
  alone; rest until ~3h19m30s; the account itself not resting)
- TestAntigravityDrawingOtherErrorInsideTheReplyStays (a 500 INTERNAL
  inside the reply asks no other account, rests nothing)

Broken by hand: draw.go at origin/main with the new tests: the first two
red (502 on the spent account; "asked u1 u2 u1 u2"), the third green.

Run at this head:
- go test -tags nogui -timeout 45m ./internal/gateway: ok github.com/yetone/magpie/internal/gateway 432.7s (go test -tags nogui -timeout 45m ./internal/gateway at 5509128b1 + this diff)
- gofmt -l internal/gateway: clean
- go vet ./internal/gateway on darwin, GOOS=linux and GOOS=windows: ok

Not tried: a real account. The owner's machine has one Antigravity
account, and none with its image quota spent, so neither rotation nor
the real in-stream error body was seen live; the stream case is
Antigravity's 429 body sent as the event, not a captured stream.

Docs: gateway-routing.md's Image generation row.
2026-10-25 05:16:50 +08:00
yetone a6399dd494 usage: a Requests page sums each chunk once and reuses it while the chunk is the same
Turning a page, or the 15s refresh of the open page, built every sum,
chart and share from every row of history again. On the owner's real
history that was 1.15-1.36s a page (load 170) after the chunks were
already cached.

Each chunk's rows are now folded into cells: one per provider, agent,
model, kind, caller, account, computer, source, filter bits and chart
bucket, with its totals. A page merges the cells. The cells of a chunk
are kept per (period, filter, since, until, zone), up to 4 such sets,
keyed by the chunk's serial (a new one every time a chunk is read or
frozen) and a signature of what pairing gave it: rows skipped or
matched, Codex actors and their identities (with the parent's role), and
compactions. A changed file, a gateway tail block or an identity change
from another file sums that chunk again. The newest rows are taken from
chunks in Latest order, stopping once the heap holds rows newer than
the next chunk. Cell strings are unique handles, so the cache holds no
chunk's string block. Totals and Part sums are linear, so merged cells
equal the row-by-row sums; date-mode buckets store the day number and
are placed against the chart's first day at merge time.

What was run (macOS, arm64):
- Real history (sbmem sandbox HOME, read-only links to the owner's
  data), zzbench dump of 9 cases x 2 pages (offset 0/50 after a warm
  7/50 call, and 120/30) with the base 1313b047f and this change: 0
  differences over 18 pages (floats at rel 1e-9).
- zzbench timing at load 170: warm pages 1.15s / 1.36s mean -> 0.45s /
  0.41s; first page 3.1s / 2.8s -> 2.4s / 2.6s.
- New TestRequestCellsFollowIdentityAndFiles: a child chunk whose
  parent's file changes (its root moves to top-z) without the child
  being read again, a changed child file, a gateway append, compared
  to pageFromLedger for All and Week. Broken by hand: reusing a part
  whatever its signature turns it red ("a cached part kept the old
  root: 0 rows, 0 input"). Passes in TZ=UTC too.
- go test -count=1 -timeout 45m ./internal/usage/... ./internal/usageapi/...
  ./internal/sessions/...: usageapi and sessions ok; usage red only on
  TestUsageReadAfterAppendHashesNothingOnAFineClock/whole-second_stamp,
  #3511 (taken by another session). -count=10 of it: 2 FAIL on this
  change and 2 FAIL on the base 1313b047f, at load ~100-145. Every
  other usage test passes.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage/.

Not done here: the pairing setup (unpacking unchanged chunks for
visibleLocal, matchedBlocks and foldCodexRows) is now most of a warm
page, ~0.18s each; it is next.
2026-10-25 05:02:18 +08:00
yetone 5509128b1b readme, site: privacy masking gets its own section, with the Masking page
The owner asked for masking to be shown prominently in the README and on
usemagpie.ai. Each says what masking does, how, and what it costs:

- README.md, README.zh-CN.md: a bullet in "Is magpie for you?", a
  "Privacy masking" section second under What it does (screenshot, a
  table of how values are found, put back, kept off disk and shown, and
  the trade-off: the model sees the placeholder, so a task about the
  value needs Never mask), and a line in Privacy linking to it.
- site/public/index.html, site/i18n.js: a #masking section after the
  menu bar, a nav link, en/zh/ja/de strings; the screenshot follows the
  language (de keeps the English one).
- site/public/docs/{,zh/,ja/}privacy.html: a "Masking what goes to
  providers" section and its TOC entry.
- site/public/img/masking{,-zh,-ja}-{light,dark}.png: Insights › Masking
  drawn by the real GUI assets in Chromium with mocked /api data, 1912px.

Every claim was checked against the code: off by default
(settings.Redact omitempty), 503 when asked for and not serving
(reference.md), the local model's 1.6 GB (internal/pii modelSize), the
UI names in each language from internal/gui/assets/i18n.js.

Run at this tree: site `node --test` 31 pass 0 fail (worker.test.mjs
checks every key in every language). The section rendered with each
dictionary applied in Playwright Chromium: en 1280 light, zh 1280 dark,
ja 390 light, de 760 dark; no horizontal scroll, the right screenshot
per language. Not tried: `wrangler dev` (it fails to start on ICON_MAX,
unrelated); the deployed site is checked with curl after deploy.
2026-10-25 04:41:06 +08:00
yetone 1313b047f5 usage: a Codex thread's model and effort are read through the request index
CodexModelEffort, which the Sessions list asks for, read the ledger again
on every build: sessions.AgentCalls(since, "codex") opened all of Codex's
shards (12k rollouts, 15.6k shards on the reporter-sized sandbox) after
any new call, beside the Requests page reading the same files into its
own index (#3493). It now reads through the request index as a page
does: readRequestBlocks (moved out of queryPage), the page's pairing and
visit (pairedRows, moved out of buildRequestBlocksOf), and the sums added
row by row as they are visited (effortSums), so a build after a call
reads only the files that changed, and the first of the Sessions list
and the Requests page reads them for both. The LogCalls path still
builds from codexEffortRows.

The visit's row is one per visit now: as a returned closure's local it
was moved to the heap, one allocation a row, which
TestRequestPageAppendDoesNotRepriceHistory caught (10890 allocations over
8000 records against 2000).

Measured before the rebase onto dbbe97991 (its parent ffe493773 adds
rows for magpie's own probes, none in this sandbox), on a sandbox copy of real data (sbmem: 12,069 Codex
rollouts, ~416k rows), base 22a7f86c9 against this, /api/sessions then
the Requests page then /api/sessions, one CPU profile over each run:
  total CPU          16.75s -> 9.40s  (first run 20.10s -> 8.32s)
  CodexModelEffort    4.21s -> 1.65s
  sessions.loadCalls  5.61s -> 1.22s  (now only under the first build;
                                       the page that follows reads none)
  wall, first run: sessions 4.97s -> 2.84s, requests 7.72s -> 2.01s
  (load average 78-133 from other sessions' suites, so wall is noisy)
/api/sessions of both binaries: 4,930 Codex sessions, 4,604 model/effort
entries, every token count equal and every cost equal within 1e-9
(summation order).

Tests, at this head after the rebase: go test ./internal/usage ./internal/sessions ./internal/usageapi;
./internal/gui -run 'Session|Codex|Effort'; ./internal/usage -race -run
'Codex|Effort|RequestPage'; gofmt; GOOS=linux and windows go vet -tags
nogui ./internal/usage ./internal/gui. TestCodexEffortRowsAreTheWholeLedgers
now also holds codexEffortOfIndex to the whole ledger's sums for All,
Today and Week; it goes red with a gateway call's actor broken by hand.

Not tried: a live Codex session writing while the list polls (the build
after a call is the page's incremental read, measured in 22a7f86c9).
2026-10-25 04:28:31 +08:00
yetone dbbe979914 masking: the flow goes under the number before its middle bunches up (window ~760px)
ZeRo Xu on X (10-25) showed the Masking card in a narrow window: the
flow beside the number had its middle squeezed to a sliver, the lines
bunched up and "OpenCode Zen" was cut to "OpenCod…".

The band put the flow beside the number down to a 640px container. Measured
with the reporter's data (Codex 19.6K; openai 14.1K, Codex 3.7K, OpenCode
Zen 1.9K) the flow's middle is 410px at a 1068px container, 162 at 820,
110 at 760 and 80 (its floor) at 700, where the names are cut. Now the
flow goes under the number from a 780px container, as it already did
under 640, so it has the card's whole width; the 640px rules (narrow
side columns and the rest) are unchanged.

Run at this head: GUI masking-records, privacy-usage-stats, privacy-model,
mask-actions, i18n-keys, click-scroll (both engines, all pass); go test
-run Budget ./internal/gui ok. Screenshots at 1280, 1000, 900, 820, 780,
760, 700 and 560 in Chromium and WebKit, before and after.

Not tried: the real Linux (WebKitGTK) and Windows apps; CSS only, no
motion or new API.
2026-10-25 04:18:58 +08:00
yetone ffe493773c usage: magpie's own Test, Detect APIs and model list requests are rows of the request log, counted nowhere
neiko and gys619 on Discord: a provider's Test or Detect APIs left no
trace in Usage > Requests, so a failing test couldn't be read back.

The provider package marks the context of the editor's Test, Detect APIs
(and per-model detection) and a model list's refresh with a kind
(internal/probelog). Each request sent under the mark is written once:
by the provider's Do, or by probelog.Transport under http.DefaultClient
(netproxy.Install), whichever sends it first; the Claude Code run and
the gateway's translated test write theirs from their result. A row
keeps time, provider, account, model, host, path (no query, no
user:password), method, status, ms and the first 500 bytes of the error.

The row is usage.SourceProbe, agent "magpie", Kind provider_test /
api_detect / model_list ("Test", "Detect APIs", "Model list" in Called
for; purposes.js regenerated). The log index keeps probes apart
(logSnapshot.probes), so Visit, Load, Summarize, budgets, Vias, heatmap,
shared days, LastSeen and observers never meet one. The request page
lists them (probeChunk) and counts none: Row.IsProbe, since a packed row
keeps the row's Source and not its record's. The page shows a muted
badge "magpie's own · not counted in any total" (en, zh, zh-TW, ja, de);
no new control, no layout change.

Tests, each red on the old code:
- usage TestProbeRowsListedNotCounted: listed, clipped, and absent from
  Sum, Through, every By group, Summarize, Load, LastSeen, OwnDays and
  the observer; a provider filter lists it and sums 0.
- provider TestTestWritesItsRequestsDown / TestDetectWritesItsRequestsDown:
  every request the fake server saw is exactly one row, with the right
  kind, model and 401 text; an unmarked Do writes nothing.
- probelog TestNoteKeepsNoSecret, TestTransportOnce.
- GUI usage-ledger-probe: badge per language, both engines, 1180/420,
  light and dark, no left border, no sideways scroll.
- gui TestProviderDetectDraft now expects the log line (source probe,
  kind api_detect, no key) and leaves usage.jsonl out of the unchanged
  config comparison.

Broken by hand, each went red: request_page's uncounted check,
log_index's probe skip, Append's observer skip, Do's Taken (6 rows for
4 requests), Test's and Detect's marks, probelog's query strip,
page.js's badge (11 GUI fails).

Run at this head (on origin/main 22a7f86c9): gofmt -l clean; go vet
./..., GOOS=linux -tags nogui and GOOS=windows clean; go test -count=1
usage, probelog, netproxy, usageapi, provider and gui packages ok (the
rebase over 22a7f86c9 applied cleanly; upstream's 8b460833e chunk
cache leaves probeChunk, built per query, alone).

Run one rebase earlier (on origin/main 0b72ccbef; request_page.go
merged by hand onto 7d67910f7/66b6d6ade's per-row Totals, with
uncounted rows skipping the caller and account groups too):
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, log tee'd:
  every package ok (gateway 640s, agent 514s, provider 278s, usage 77s)
  but internal/gui's TestRestartHandsTheGatewayOver (7 of 8 requests
  answered during the restart), 3 of 3 green alone after (#3451).
- gofmt -l clean; go vet ./..., GOOS=linux -tags nogui and GOOS=windows
  go vet ./... clean.
- GUI usage-ledger-probe, usage-ledger-reported, i18n-keys,
  purpose-filter, quota-pool-model: 72/72. usage-ledger's "newest live
  route needs no return-to-live button" is red on origin/main 0b72ccbef
  alone too (#3104).
- Whole GUI suite, both engines, at the pre-rebase base 761904b5a:
  1313 tests; reds, each also red on origin/main 7b1faf99f alone:
  account-discovery "agents' sign-ins read" (#3497), builtins
  "Plugins > Built-in" (Masking page in the list, #3518 filed), and
  context-map "two tiles overlap" chromium ja 420 (#3488; 1 of 2 red on
  main alone, 3 of 3 green on this branch alone). Earlier package run:
  TestRestartHandsTheGatewayOver red under load, passes alone (#3451).
- No size budget raised.

Not tried: no real vendor account (fake servers only); a plugin's model
list, fetched in the JS plugin host, isn't written down; the real GUI
app wasn't launched (Playwright only).
2026-10-25 04:12:06 +08:00
yetone 22a7f86c9b sessions: the Requests page walks the Codex folders once a rebuild
readRequestState asked CallSources and then CodexIdentities, and each
walked ~/.codex/sessions and archived_sessions, lstat()ing every
rollout. Over the 12,069 rollouts of a real Codex folder that was two
walks of ~75ms on every rebuild, which runs on each 5s refresh while
an agent works. CallSourcesAndCodexIdentities walks once and hands the
list to both; CallSources and CodexIdentities stay as they were for
their other callers.

Run at this head:
- go test -timeout 45m ./internal/sessions ./internal/usage
  ./internal/usageapi: ok. TestCodexIdentityParentChainsAndSummaryCache
  now checks the one-walk pair equals CallSources and CodexIdentities.
- GOOS=linux and GOOS=windows go vet -tags nogui on both packages, gofmt.
- Real data (sandbox HOME over the owner's ~/.codex, 12,069 rollouts,
  ~416k rows): CPU profile of two rebuilds, codexFiles 0.31s before,
  0.12s after. Wall times on a loaded machine were 1.0-2.1s both ways,
  too noisy to compare.

Not tried: Windows or WSL folders (wslFiles is still walked as before).
2026-10-25 04:07:20 +08:00
yetone 1b32bdcfcb gui: magpie web's port answers the gateway's /v1 routes too, so one proxy location serves both (zgcwkj on Discord)
zgcwkj puts magpie behind nginx on one domain and wanted the browser UI
(magpie web / serve --web, 127.0.0.1:3430) and the gateway (:3425) from
one port, so one location works. Now the web port hands every gateway
client route to the gateway: /v1/..., /v1beta/..., /models, /chat/completions,
/responses, /messages, /images, /embeddings, /rerank, /audio, /videos,
/muse-code/models, /backend-api/codex/..., the search path and /mcp/...
(gateway.ClientPath). Everything else stays the page's, behind webGuard as
before. /api/* stays split: on the web port it is the UI's API; Ollama's
/api/* and Claude Desktop's /api/hello still need the gateway port, since
the two can't share the path.

Security: a handed-over request goes through the gateway's whole own
stack, not a copy of it. gateway.Server.Front() is lanGuard(Handler()),
built once; ListenAndServe serves the same handler. When this process
serves the gateway, the web port calls Front() in process; when another
magpie does, toGateway reverse-proxies to gateway.URL(), keeps the Host,
copies Forwarded/X-Forwarded-* back (ReverseProxy strips them), and adds
X-Forwarded-For for a non-loopback peer, so remote, proxied, rebound,
Origin null, *.localhost and foreign-Origin requests are judged exactly as
on the gateway port. The web cookie is never a gateway key. Paths that
aren't clean (/v1/../api, /v1//x, /v1/./x) are not client paths, so they
never reach the gateway as one. The allow list (AllowGuard) still wraps
both.

Tests:
- TestClientPathCoversHandler reads every mux pattern Handler registers
  and fails when one is neither a ClientPath nor /, /api/* or /_magpie/*,
  so a new gateway route has to be placed.
- TestClientPathOnlyClean.
- TestWebOnePortServedHere / ServedElsewhere: with no web cookie, the UI
  API (/api/settings) is never reached for: no Origin (GET, POST),
  Origin null, a foreign Origin, a rebound Host (GET, POST), through a
  proxy (XFF), from another machine, /v1/../api, /v1/%2e%2e/api,
  /v1//api, and with a gateway key. The gateway routes on the web port:
  local agent 200; Origin null POST 403; foreign Origin 403; rebound Host
  403 (with the page's cookie too); proxy or remote without a key 401
  (with the page's cookie too); with a gateway key 200; not shared 403.
- TestWebAssetsAreNoClientPath: no embedded asset shadows a client path.

Run (full packages at the first rebase, on origin/main 0b72ccbef):
- go test ./internal/gateway ./internal/gui -count=1 -timeout 45m:
  ok (gateway 644s, gui 193s).
- Rebased again on origin/main 8b460833e (upstream touched catalog,
  provider, redact and usage only); at this head: the three builds and
  the vets below again, and go test -run 'TestClientPath|TestWeb'
  ./internal/gateway ./internal/gui: ok. The full packages were not
  rerun at this head.
- gofmt -l internal/gateway internal/gui: empty
- go vet ./internal/gateway ./internal/gui; GOOS=linux go vet -tags
  nogui ./internal/gateway ./internal/gui ./internal/cli; GOOS=windows go
  vet ./internal/gateway ./internal/gui: ok
- go build .; GOOS=linux go build -tags nogui .; GOOS=windows go build .: ok

Broken by hand, each red, then restored:
- no onePort (the old web handler): agent 401 not 200, Origin null 401
  not 403 (ServedHere).
- Front without lanGuard: rebound Host 200, proxy without a key 200.
- toGateway not copying the forwarding headers: proxy without a key 200,
  not shared 200 (ServedElsewhere).
- no X-Forwarded-For for a remote peer: another machine 200.
- Host not kept: rebound Host 200.
- ClientPath taking unclean paths: TestClientPathOnlyClean red (4 paths).
  The gui tests stay green under this break, since the gateway's mux
  answers /v1/../api/settings with a redirect, not the UI API; the clean
  check is a second wall.

Real try: the built binary, `magpie serve --web=127.0.0.1:3472` under a
sandbox HOME (MAGPIE_ADDR=127.0.0.1:3471, MAGPIE_NO_ACCOUNTS=1,
MAGPIE_TEST_SANDBOX), then Homebrew's nginx 1.31.7 (bottle unpacked in a
scratch folder, proxy_pass to 3472 with Host and X-Forwarded-For) on
127.0.0.1:3473. Direct on 3472: / 401, /?k= 303, /api/settings 401
without and 200 with the cookie, /v1/models 200, Origin null POST 403,
foreign Origin 403, X-Forwarded-For 403 (not shared). Through nginx, not
shared: /v1/models 403 with the "came through a proxy" reason; the UI
signs in with /?k= and /api/settings is 200 with its cookie. Sharing
turned on and a key added from the UI API through nginx: /v1/models 401
without a key and 401 with only the page's cookie, 200 with the key;
/v1/messages and a streamed /v1/chat/completions with the key reach the
gateway (404: the sandbox has no provider); /api/settings with the key
401; Origin null and foreign Origin without a key 401; /v1/../api/settings
401; /api/tags 401 (the page's API, not Ollama's). A rebound Host on
either port is refused only for a request that looks like a browser's
(Sec-Fetch-Site), the same as the gateway port before.

Not tried: a real model reply (and so a long stream) through the one
port, since the sandbox has no provider; https, WebSocket (Codex's
/backend-api/codex websocket) through nginx; Windows and Linux, other
than vet and build; the GUI suite (no GUI asset changed).
2026-10-25 04:01:52 +08:00
yetone 8b460833e0 usage: the Requests page keeps its chunks while it is open
Every new call is a new page key, so the open Requests tab works its
page out again on each 5s refresh. The session files' packed chunks
were held to 24 MB. A history of 416,000 calls has 63 MB of them, so
each rebuild read 2,679 shards again (39 MB), gob-decoded them, priced
each call and packed it again, and dropped them again after.

Now the chunks are held to 128 MB while the page is asked for. After 2
minutes with no ask (requestIdle), a timer cuts them back to the 24 MB
they were held to before (requestIdleBytes), so an unopened page holds
what it held before.

Measured on the real sandbox data (sbmem, 416,665 rows):
- zzbench, one QueryPage of period=all and six rebuilds at new offsets,
  alternated with v0.1.1439's code at load ~150-200: user CPU
  17.26 / 16.09 s before, 10.79 / 10.21 s after; sys 3.41 / 3.01 ->
  1.98 / 2.14 s; peak RSS 604 / 664 MB -> 566 / 543 MB. A debug count
  showed 2,679 shards read per rebuild before and 1-2 after (the
  files that grew).
- A running magpie (`web --gateway` under sbmem), /api/usage/requests
  period=all at offsets 1-5, warm file cache, load ~175: rebuilds
  1.98 / 1.99 / 1.50 / 1.69 / 1.52 s on v0.1.1439, 1.30 / 1.18 / 1.09 /
  1.07 / 1.07 s now. Cold (the first run after building), one rebuild
  took 23 s; v0.1.1439's cold rebuilds took 5.5-8.0 s, and the warm
  reruns didn't show it again.
- Heap in use on that server, by /v1/magpie/heap: after the builds
  175.7 MB (v0.1.1439) and 199.1 MB (now); after 140 s unasked 161.7
  and 149.8 MB. Footprint 339 -> 286 MB and 302 -> 254 MB.

Tests: TestRequestChunksTrimmedWhenIdle checks that three chunks over
the idle bound are kept while the page is asked for, and dropped once
it goes unasked. It waits for that state, not for a time. Broken by hand
both ways: without the idle trim it fails ("3 chunks kept after the
page went unasked"), and with the build trimming to the idle bound it
fails ("0 chunks kept while the page is asked for"). It also passes
with -race -count=3.

Run at this head: go test -count=1 ./internal/usage ./internal/gui ok
(16.1s, 201.8s); go vet -tags nogui for GOOS=linux and windows on
internal/usage ok; gofmt -l clean. Not run: the full suite (other
sessions' suites hold the machine).
2026-10-25 03:58:02 +08:00
yetone 511c4a765e redact: code naming a secret (secretKey: Uint8Array, toBase64Url(…)) is not masked as one
Kieran Zhang on X (10-25) showed TypeScript masked as secrets:
`secretKey: Uint8Array;`, `details.2`, `toBase64Url(...)`. The SECRET
rules took any letters-and-digits value after a secret's name, and an
identifier like Uint8Array or a call like toBase64Url has both.

Both SECRET rules (the named-secret one and the bare "key" one) now ask
notCode: a value that is an identifier path (a.b.c) is code, not a
secret, when a "(" follows it (a call), or when it sits unquoted after a
":" and code punctuation (; , ) } ] | ? & < >) or the end follows (a
type or an object member). A quoted value, an `=` assignment, or a YAML
style `password: Passw0rd123` line is masked as before.

Run at this head:
- internal/redact TestCodeIsNoSecret: the reporter's four literal lines,
  a union type, an object member and a spaced call go as written; seven
  real secrets (quoted, escaped JSON, env, YAML, query-like) still mask.
  Red on the old code (6 of them masked), green after.
- go test -timeout 45m ./internal/gateway ./internal/gui ./internal/otlp
  ./internal/pii ./internal/redact ./internal/sessions ./internal/settings:
  all ok except internal/gui TestMainWindowCorners, an AppKit window
  killed at its 40s deadline at load ~146; it is red alone too, filed as
  #1936 and #2645, and this change doesn't reach it.
- go vet on darwin, linux and windows; gofmt -l clean.

Not tried: the reporter's own file in a live session; an unquoted
`apiKey: SomeIdent,` in YAML now goes as written, which reads as code.
2026-10-25 03:53:35 +08:00
yetone ea33a78a05 provider: a proxy's level- or speed-named model takes its model's levels (nianshou5)
nianshou5 on Discord added their own CLIProxyAPI (CPA) as a custom
provider, and its models offered no reasoning effort in the ChatGPT app
while a plugin's did. CPA's /v1/models gives id, object, created and
owned_by alone (sdk/api/handlers/openai OpenAIModels strips its
registry's thinking levels), so every level comes from magpie borrowing
the model's. That works for an id models.dev knows (gpt-5.5, claude-*,
gemini-*, deepseek-*), but CPA's Antigravity and xAI channels name a
model for the level or speed they serve it at: gemini-3.8-flash-high,
claude-opus-5-5-high, claude-opus-4-6-thinking, gpt-oss-120b-medium,
grok-3-mini-fast. No catalog lists those names, so they had no levels,
and Codex, the ChatGPT app, /v1/models and the gateway's effort fitting
all read none. CPA's own registry gives those models levels or a
thinking budget it fits an effort to.

borrowedEfforts, which is reached only for a model its provider gave
no word on, now tries the id without a trailing
-minimal/-low/-medium/-high/-xhigh/-max/-thinking/-fast
(catalog.Unsuffixed) after every other match failed. A vendor whose own
list names a model so keeps its own word (effortsOf takes the
provider's), and a variant whose base magpie doesn't know
(grok-4.7-build-fast) still takes none. Every list reads Entry.Efforts
or Provider.Known, so Codex CLI's magpie-models.json, the Codex and
ChatGPT apps' /backend-api/codex/models, /v1/codex/models and /v1/models'
reasoning_levels all change together.

The reporter's one visible id, whatstoken/deepseek-v4.1-flash-1017,
already borrowed low,high,max on main against this machine's real
models.dev cache; their other two CPA ids are not known yet (asked on
Discord). So this fixes the class of CPA ids that had none; it may not
be their case.

TestCPAVariantModelsBorrowLevels serves CPA's /v1/models bytes from an
httptest server, fetches them with catalog.Fetch, and checks
Entry.Efforts, Provider.Efforts and the Codex list's
supported_reasoning_levels. It is red with the fallback turned off by
hand (three ids with "" in each list) and green with it.

Run at the pushed head (rebased on origin/main 0b72ccbef):
- go build ./...; GOOS=linux and GOOS=windows go vet ./internal/catalog
  ./internal/provider: ok
- go test -count=1 ./internal/catalog ./internal/codexcat, and
  -run 'CPA|Effort|Level|Borrow|Kin|Host' ./internal/provider: ok
Run at the same change on 7d67910f7, before the rebase:
- gofmt -l internal/: clean
- go test -count=1 ./internal/catalog ./internal/provider
  ./internal/codexcat: ok
- go test -run 'Effort|Level|Reason|Think|Codex.*Catalog|ModelsList'
  ./internal/agent ./internal/gateway: ok
- Against a copy of the real models.dev cache, every id in CPA's
  internal/registry/models/models.json as a custom provider: the five
  suffixed ids above now get their base's levels.
Not run: the full suite (machine at load ~190 with eight suites queued;
not holding the push). Not tried: a real CPA instance or the real
ChatGPT app.
2026-10-25 03:51:20 +08:00
yetone 0b72ccbeff agentplug: connect's models carry /v1/models' native_endpoints and pricing
cleary5779 on Discord builds an agent as an agent plugin and wants, in
connect({ gateway, model, models }), the API each model passes straight
through on and what it costs. Each entry of models (and model) now also
has, by the names /v1/models uses:

  "native_endpoints": ["/v1/chat/completions"],
  "pricing": {"prompt": "0.0000003", "completion": "0.0000012",
              "input_cache_read": "0.00000003"}

Each is left out when not known: a group or a model translated anyway
has no native_endpoints, an unpriced model no pricing, never [] or 0.
The fields connect had (id, name, context, output, images, efforts) are
as they were.

No second lookup: nativeEndpoints moved from the gateway to
provider.NativeEndpoints, and openRouterPricing/perToken to
catalog.OpenRouterPricing/PerToken (internal/catalog/openrouter.go); the
gateway calls them as before. magpieModels already priced each model with
provider.EntryPricer, the price /v1/models gives (m.Price); it now also
keeps NativeEndpoints in catalog.Model.Endpoints (json:"-"), which
plugged's wire turns into the two keys.

Docs: reference.md's agent plugins section (what connect gets, with an
example), agent-wiring and gateway-routing subsystem pages, and the
site's Plugins page in en, zh and ja.

Run at this tree (on origin/main 66b6d6ade), load ~150:
- gofmt -l internal: nothing. go vet on the touched packages,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test ./internal/catalog ./internal/provider: ok (agentplug has no
  tests). go test ./internal/gateway -run 'Models|PerToken|OpenCode|
  Native|Cursor': ok.
- go test ./internal/agent -run 'Plugged|Pi|Price|Alma|ModelOrder|Image|
  Group|Codex': one red, TestCodexThreadsComeBackOffMagpie/disconnect
  (.cache/magpie/sessions.json left in its TempDir), open as #3422; it
  passes 5 of 5 alone and this change doesn't touch sessions.
- TestPluggedConnectSeesEndpointsAndPricing is red with plugged.go's two
  keys taken out (no native_endpoints, no pricing on model or models),
  green with them.
Not run: the full ./... suite (machine at load ~150 with several suites
queued); the whole agent and gateway packages. Not tried: a real agent
plugin reading the fields.
2026-10-25 03:39:50 +08:00