Commit Graph
4359 Commits
Author SHA1 Message Date
yetone dcfda5f166 gateway: a relayed Responses stream's tidies pass its events in place (#3383)
idTidy and phaseTidy each copied every event of a relayed Responses
stream twice, once out of their buffer and again onto an output grown
event by event, and dropped their buffer's bytes at each write so the
next write took new ones. eventData copied each event's data even when
it is one line, as nearly every upstream's is, and phaseTidy decoded a
reply's whole last event into a map to find no message without a phase.

- tidyEvents goes through a write's whole events into one output sized
  for them; an event that goes as it came is copied once, and the part
  of an event still coming moves to the buffer's front.
- eventData gives a one-line event's data as ev's own bytes; its callers
  only read it.
- phaseTidy.ended reads the output in place (anyUnphased, which agrees
  with unphased item by item) and decodes only when a message needs a
  phase.

Measured with BenchmarkZZCodexStream (a 680 KB Codex /v1/responses
stream through serve, kept out of the tree): 14.16 -> 12.53 MB/op,
~53,450 -> ~49,700 allocs/op.

Run at this head:
- go test ./internal/gateway -timeout 45m: ok (439s, at 848b3bf7e rebased on 4b9694c34)
- New tests: TestAnyUnphasedAgreesWithUnphased (null, number and
  missing phase and role, a non-list output), TestEventDataJoinsAsSSE,
  TestTidiesPassAStreamSplitAnywhere (1, 7, 64 bytes and whole, the
  caller's buffer cleared after each write). Broken by hand: moving
  nothing to the buffer's front turned the split test red, and reading
  a null role as an assistant's turned the agreement test red; restored,
  green.
- gofmt -l clean; go vet ./internal/gateway on darwin, and GOOS=linux and
  GOOS=windows with -tags nogui: ok
- Real APIKEY.FAN account (deepseek-flash over its /v1/responses, so
  both tidies run; sandbox HOME with only that provider copied): five
  Codex-shaped streams, 5 of 5 answered "ok" at 1859da57b and at this
  head.
- Those five real replies, the same with every phase taken out, and a
  real OpenAI billing_not_active reply (error then response.failed),
  replayed to both builds in 7-byte, 4 KB and whole chunks: the client's
  bytes are identical between the builds in every case but the error
  reply at 7 bytes, where both builds cut the stream at a varying point
  after the error event (old: 3633 and 4757 bytes;
  new: 3500, 3857 and 4757),
  as before this change.

Not tried: a real Copilot account (the case idTidy is for); the OpenAI
key's account is not active.
2026-10-24 22:20:26 +08:00
yetone 4b9694c34c gateway: a prompt's estimate reads the request's items in place (#3383)
promptBuilder decoded every item of a request through decodeJSON, which
copies each content and output RawMessage out of the body unless it is
at least 1/16 of a held body. On a long Codex conversation that is every
item, copied once per request on promptOf's goroutine. What the builder
keeps of the body lives no longer than the builder, and the body
outlives it (promptOf's request; promptPieces' kept body, whose pieces
are read out before PromptText returns), so its 18 decodes now use
decodeJSONView, which shares capped slices of the body.

Measured with BenchmarkZZCodexStream (a 680 KB Codex /v1/responses
stream through serve, kept out of the tree): 14.92 -> 14.16 MB/op,
~54,200 -> ~53,450 allocs/op.

Run at this head:
- go test ./internal/gateway -timeout 45m: ok (399 s)
- go test ./internal/gateway -run Prompt: ok
- gofmt -l clean; go vet ./internal/gateway on darwin, and GOOS=linux and
  GOOS=windows with -tags nogui: ok
- Real DeepSeek (deepseek-flash, sandbox HOME with only that provider
  copied), five Codex-shaped /v1/responses streams through a recording
  proxy, built at 1859da57b and at this head: 5 of 5 answered "ok" on
  each, and the five upstream bodies are byte-identical (cmp).

Not tried: other vendors' plugin paths with real accounts; the change is
in the local estimate only and does not change what is sent upstream.
2026-10-24 22:09:39 +08:00
yetone 1184862583 agent: Codex background compaction writes the bare async_compaction = true where a Codex older than 0.163 reads the config (多喝热水)
多喝热水 (Discord #help, Windows, v0.1.1384, Codex desktop with ChatGPT
sign-in): Codex wouldn't open, "config.toml:154:1: invalid type: map,
expected a boolean". That line is the [features.async_compaction] table
1978eabe5 (#2490/#2493) writes.

Codex versions, from codex-rs source and the real binaries:
- up to 0.163.0-alpha.5 (0.160.0, 0.162.1 included) FeaturesToml is a
  flattened BTreeMap<String, bool>: any table under [features] fails the
  whole config; an unknown bool key is only a warning.
- from 0.163.0-alpha.8, async_compaction is FeatureToml<…>, bool or
  table, and model_async_compact_threshold_percent is read only from the
  table (the bool gives Codex's default 65).
- the provider table's capabilities = {...} is safe: 0.161 and older
  ignore unknown provider keys (schemars-only deny_unknown_fields),
  0.162 parses it. 0.160.0 and 0.162.1 load a config holding it.
- ChatGPT.app 26.1013.40934 bundles Codex 0.163.0-alpha.10.2
  (Contents/Resources/codex-cli/codex-package.json); the reporter's
  Windows app rejects the table, so it bundles one before alpha.8.

Fix: the table is written only when every Codex found here that reads
this config (the CLI on PATH, the desktop app's bundled codex on macOS,
the Store app on Windows, the editor extension, Codex in WSL) has a
version at or after 0.163.0-alpha.8. Otherwise, or when a version can't
be read (the Windows app, the extension), magpie writes the bare
[features] async_compaction = true with no share. A table magpie wrote
before is taken back through its stash (only the keys the stash names
as magpie's; an emptied table goes), so a config already broken opens
again on the next sync. A table or bool the user wrote stays. The stash
records a bool it wrote (`bool`), and the table comes back once every
reader is new enough. Settings' state carries codexAsyncHeld, and the
Codex row says which Codex holds the share back and that it needs
0.163. The note costs app.js 390 bytes; its budget and the core's are
raised by exactly that, the agent's own row in the core.

Run:
- real binaries, sandbox CODEX_HOME/HOME, `codex features list` on the
  config magpie writes (TestCodexAsyncConfigLoadsInRealCodex,
  MAGPIE_TEST_CODEX_BINS): 0.162.1, 0.163.0-alpha.8 and 0.164.0 load it;
  alpha.8 and 0.164.0 report async_compaction true. By hand before the
  fix: 0.160.0 and 0.162.1 exit 1 on the table ("invalid type: map,
  expected a boolean"), load the bool and nothing; alpha.8 and 0.164.0
  load all three.
- broken by hand (table always allowed): the real-binary test is red
  for 0.162.1 with Codex's own error, OldCodexGetsTheBareKey red in all
  four cases, TableTakenBackForOldCodex red ("magpie's table not
  mended"). Green again with the fix.
- go test -tags nogui ./internal/agent ./internal/gui ./internal/edit
  ./internal/settings: ok (gui after the budget, re-run alone: ok).
- GUI (node --test, chromium + webkit): codex-async-compact,
  agent-prefs, settings-general, segs-glide, i18n-keys: 100 pass, 0 fail.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...; go build for darwin, linux (nogui),
  windows: ok.

Not tried: the Windows box (Store-app detection, reading its bundled
codex's version, a non-Store install), a WSL distro, a real Codex run
past the share, the whole GUI suite. The full go test ./... is queued
behind other sessions' suites (one per machine) and wasn't waited for.
2026-10-24 22:02:49 +08:00
yetone 1859da57bd gateway: readers of a rewritten request see its input in place (#3383)
Only the body a request arrived with is held (holdBody), so decodeJSON
shares a raw value with it and copies one from any other body. Once a
route rewrites a Codex request (its model, its fields), the new body is
held by nobody, and each reader that only looks at it copied the whole
input to do so: conversationID, hasSealedAgentMessage,
orphanedToolOutputs, joinToolRuns, pairToolItems, withReasoningText,
and affinity's seal and kind strippers. Each such copy was ~0.4 to
0.5 MB on a 680 KB request.

decodeJSONView is decodeJSON whose raw values always share the bytes
they came from, capped, for a reader that keeps nothing it decodes and
writes none of it. Those readers use it. Each one only reads, or builds
a new body with json.Marshal or marshalPlain (which copy), or returns
the body it was given. promptBuilder keeps raw parts past its return,
and parseResponses keeps its result, so both stay on decodeJSON.

Measured on the 680 KB Codex request benchmark (30x, 3 runs):
16.37 MB/op, 54,703 allocs/op -> 14.96 MB/op, 54,222 allocs/op (-8.6%).

What was run:
- TestDecodeJSONViewShares: q["input"], q["tools"] and an item's
  content from decodeJSONView point into the body and are capped, and
  decodeJSON still copies from a body that isn't held. With `share ||`
  taken out of fillJSONIn it is red ("tools []: not body's own bytes,
  capped"); restored, green.
- fjCompare checks decodeJSONView against json.Unmarshal on every seed
  as it does decodeJSON.
- Real DeepSeek A/B through a recording proxy in a sandbox HOME, Codex
  UA, 5 requests with a tool-call history: 2d21034d8 and this commit
  each answered "ok" 5 of 5, and the 5 upstream bodies are byte for
  byte the same.
- go vet (darwin; linux and windows with -tags nogui), gofmt -l clean.
- go test -timeout 45m ./internal/gateway/: ok (492s) at beef295be

Not tried: the full ./... suite at this head (queued behind others).
2026-10-24 21:59:05 +08:00
yetone 2d21034d81 gateway: a decoded struct's keys are read without a string made for each (#3383)
fillJSONIn made a string of every member key of every object it decoded
into a struct (unquoteJSON), then a []byte of that string to look the
field up, and a []bool for each struct to see a key twice. A Codex
request's history is thousands of small objects, so these were a
quarter of its allocations. keyName gives a plain ASCII key's bytes
between its quotes and leaves any other key to unquoteJSON as before,
and the fields seen are bits of a uint64 unless a struct has more than
64 of them.

Run at 83234fe92 + the previous change + this one:
- BenchmarkZZCodexStream (680 KB Codex request, probe not committed),
  -benchtime 30x -count 3: before ~72,780 allocs/op, 16.42 MB/op;
  after 54,698 / 54,692 / 54,696 allocs/op (-25%), 16.33 MB/op.
- TestDecodeJSONIsUnmarshal gains a non-ASCII key, a fullwidth key and
  keys with control bytes; TestDecodeJSONKeyTwice checks fillJSON refuses
  a key twice in a 3-field struct and a 70-field one. Broken by hand:
  keyName not looking for escapes turns TestDecodeJSONIsUnmarshal and
  FuzzDecodeJSON red; dropping the twice check in either the bits or the
  slice path turns TestDecodeJSONKeyTwice red.
- go test -fuzz FuzzDecodeJSON -fuzztime 60s: ~966k execs, no failure.

At c0b3aadfe (on d7ad3f2a3):
- Real account, sandbox HOME with only DeepSeek, through a recording
  proxy to api.deepseek.com: 5 Codex-UA /v1/responses requests with a
  tool-call history on d7ad3f2a3 and on this; all 10 answered "ok", and
  the 5 bodies sent upstream are byte-identical.
- gofmt clean; GOOS=linux and windows go vet -tags nogui ok.
- go test -timeout 45m ./internal/gateway/: ok (449s) at c0b3aadfe
2026-10-24 21:49:50 +08:00
yetone d7ad3f2a3e gateway: input scanners read a request's items in place, not copied (#3383)
Seven readers of a Responses request's input (the seal stripper and
withoutKinds in affinity, hasSealedAgentMessage, joinToolRuns,
orphanedToolOutputs, pairToolItems, withReasoningText) and the prompt
builder decoded `input` into a []json.RawMessage. fillJSONIn clones each
RawMessage under a sixteenth of the held body, so every item of a long
Codex history was copied once per reader, per request. None of them
keeps an item past its return (they marshal new output or assign into
the slice), so inputList hands them elementsOf's capped subslices of the
raw input instead. hasSealedAgentMessage reads an item's content the
same way.

Run at 83234fe92 + this change:
- BenchmarkZZCodexStream (a 680 KB Codex request through the gateway,
  a probe not committed), -benchtime 30x -count 3:
  before 20,077,746 B/op 76,687 allocs/op;
  after  16,417,942 / 16,430,955 / 16,469,180 B/op, ~72,780 allocs/op
  (-18% bytes).
- Real account, sandbox HOME with only the DeepSeek provider, through a
  recording proxy to api.deepseek.com: 5 Codex-UA /v1/responses requests
  each with a user message, reasoning, function_call,
  function_call_output and assistant message in the history, on the old
  and new binary. All 10 answered "ok"; the 5 bodies sent upstream are
  byte-identical between old and new.
- gofmt -l clean; GOOS=linux and windows go vet -tags nogui
  ./internal/gateway ok.
- go test -timeout 45m ./internal/gateway/: ok (667s).

Rebased onto 1537817e0: build, both vets and go test -run
'Responses|Affin|Seal|Prompt|Tool|Codex|Reasoning|Orphan|DecodeJSON'
./internal/gateway/ ok (64s).

Not tried: the full ./... suite at this head (it runs after the push).
2026-10-24 21:38:12 +08:00
yetone 1537817e0d provider: a partners.json that doesn't parse is kept aside before a try writes over it (#3362)
loadPartners reads a partners.json that is there but doesn't parse as
an empty cache: no list, and no Seen. Before 603408f38 only a fetch
that got the list wrote the file, so the loss waited for one. Now every
try writes it before the fetch is sent (Tried), offline too, so the
first try after a start wrote the empty cache over it: Seen holds the
presets of partners no longer listed, which providers added from them
still use (their endpoints, regions and key page), and those were gone.
A failed read is unknown, not empty (docs/code-standards.md).

savePartners now goes through lastgood.KeepUnparsed first, as
balance_history, credits_daily and codex_switch do for files their
readers take as empty when they don't parse: such a file is copied
aside as partners.json.bad-<time> before it is written over, and a
file that can't be read at all (or a copy that can't be kept) is not
written over. A file not there, or empty, writes as before.

Old data: a file already written over by 603408f38 is not in any
release (603408f38 lands in the same push), so nothing is lost before
this; a partners.json damaged earlier was written over by the next
successful fetch, as it still is, now with its copy kept.

Run (tree of this stack, on f6a96b2f0, go1.26.8, darwin/arm64):
- TestPartnersUnparsedFileKeptAside (a cut-short partners.json, the
  list server answering 503, one try): with savePartners' KeepUnparsed
  removed by hand, red: "partners.json that didn't parse was written
  over with nothing kept aside ([])". With it: green, the .bad- copy
  byte for byte the file, and the try's error recorded.
- go test -tags nogui -race -count=5 -run 'Partner|Icon'
  ./internal/provider: ok.
- Broken by hand in 603408f38's own code, each red in
  TestPartnersKeepTheirLastTry: no save before the fetch (line 590:
  "while a fetch is out the file says ... error "partners: 503 ..."");
  the failure logged every try (573: "logged 3 times, want once").
- internal/gateway and internal/cli -run
  'Goroutine|Heap|CPU|Help|Profile': ok. goroutinesRefused made to
  return "" by hand: TestGoroutines... red ("Origin null with a key
  (lanGuard true): 200 ..."), restored green. The dump's frames carry
  argument words in hex, not what they point at, as 54636afa2 says.
- Full suite at this stack's head, go test -tags nogui -count=1
  -timeout 45m ./... (tree 0ef74708, one suite on the machine's
  other runs' load): exit 0, 70 packages ok, no red.
Not tried: a real app left running against usemagpie.ai; an unreadable
(EACCES) partners.json; Windows.
2026-10-24 21:33:06 +08:00
yetone c5e71f7a0b netproxy: a system proxy read that answers within readWait is what the request waiting for it goes through (#3421)
Review of 3370a79f7 (JoeyWu-tech's #3421). Breaking its "a request
waits for a read until since+readWait" by hand (wait = 0, so every
request went on at once with the proxy held, Proxy{} on a first start)
turned its tests red only through an incidental read count, not through
what the wait is for: magpie started where only the system's proxy
reaches the vendors sending its first requests through that proxy, not
direct.

TestQuickSystemProxyReadIsWaitedFor holds a read, starts a request, and
answers the read at once with http://127.0.0.1:7890: the request must
take it.

Run (tree of this stack, go1.26.8, darwin/arm64):
- wait = 0 by hand: red, "the first read answered at once, but the
  request waiting for it took {URL: Mode:...}" (no proxy). Restored:
  green.
- go test -tags nogui -race -count=20 ./internal/netproxy: ok (72s).
The stack's full-suite record is in the #3362 fix's body.
2026-10-24 21:33:06 +08:00
JoeyWu-tech 93435f27dc docs: the partner list is fetched on a process's first ask and hourly, and by the gateway's magpie unasked (#3362)
providers-accounts.md still said the list is fetched every 6 hours.
97902e93 made it a process's first ask and hourly after
(partnerEvery = time.Hour), and 7e0c0310 has the magpie serving the
gateway fetch it when it starts and whenever it is due, asked for or not
(KeepPartnersFresh).

Left out of this landing: the author's same fix to the privacy pages
(site/public/docs/privacy.html, zh/, ja/). A community change to site/
waits for the maintainer to look (docs/contributors.md); they stay on
JoeyWu-tech's branch, commit e46eee4b2, for that.

Landed by review from JoeyWu-tech's branch (posted on #3362 as
Coffemon's). The run record is in the stack's last commit.
2026-10-24 21:33:06 +08:00
JoeyWu-tech b18a6a080b gateway, cli: magpie goroutines writes the running magpie's goroutine stacks to a file (#3362)
#3362's second ask: an app stuck at something could only be read by
killing it, which ends what was stuck. magpie heap and magpie cpu
already ask the running gateway for a profile over loopback; magpie
goroutines asks it for every goroutine's stack. That works on Windows
too, where there is no SIGUSR1.

GET /v1/magpie/goroutines (goroutines.go) answers the callers
/v1/magpie/heap answers (profileRefused: a program on this computer
over loopback, no browser mark, a loopback Host; a gateway key lets
nothing else in) with runtime/pprof's goroutine profile at debug=2,
the form a crash prints: each goroutine's state and wait ("[select,
4320 minutes]"), its frames with source lines, and who started it. It
is text/plain and no-store, and X-Magpie-Goroutine-Stats names the
process (pid, program, version, window, uptime, goroutine count).
Arguments are words in hex, never what they point at, so the dump
holds no keys, prompts or messages; it does name magpie's source files
and the program's path, which the usage says.

magpie goroutines [<file>] writes it to <file>, else
magpie-goroutines-<date>-<time>.txt in this folder, 0600 and never over
a file there, then prints the file and the process. --help, -h and help
print the usage and ask nothing; a flag it doesn't take, "-", a blank
name or a second file are refused before the gateway is asked. A
magpie older than this one answers 404 and is told to update; with
none answering, it says so.

The refused callers TestHeapProfileOnlyToThisComputer listed move into
profileCallersRefused, which the CPU test and the new one share.

Run on b437e4ad, go1.26.8. internal/gateway and internal/cli are the
same here and at the branch's head (tree 613df3a9), where the checks of
them ran:
- gofmt -l and go vet as in the commit before: clean.
- go test ./internal/gateway -run 'Goroutine|Heap|CPU|Profile': ok;
  ./internal/cli -run 'Goroutines|Heap|CPU|Help': ok.
- Broken by hand: goroutinesRefused letting every caller in makes
  TestGoroutineDumpOnlyToThisComputer red ("Origin null with a key":
  200); debug=1 for 2 makes it red (the parked goroutine isn't in the
  dump); without the route it is red (404), and so is
  TestGoroutinesWritesTheRunningGatewaysDump ("older than this one").
  Restored, green.
- Full suite at this commit, go test -tags nogui -count=1 -timeout 45m
  ./... (tree e5cf04af, 498s): 62 packages ok. 14 reds in 7 packages,
  none in a file this commit touches, each red on b437e4ad without it:
    internal/agent TestInstalledVersion, TestOmpDetectedWithPiDir,
    TestCursorFolderFromTheEditorIsNotTheCLI and TestZedAppPath:
    proc.Look keeps "not found" for a tool written in the tick of its
    folder's last change (#3141).
    internal/agent TestCodexDriftReached: Drift answers from the read of
    Codex's log taken before the test's last insert (#3398).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
    internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
Not tried: a real stuck app; magpie goroutines against the app on macOS
or Windows (the tests serve gateway.New().Handler() on loopback).
2026-10-24 21:33:06 +08:00
JoeyWu-tech a2cef8bf4f provider: partners.json keeps when the list was last tried and how it ended (#3362)
"partners":null} for three days, and nothing told a fetch that failed
every time from one that never came back, or from none being asked. A
failed fetch wrote nothing and logged nothing.

refreshPartners now keeps two fields with the list:
- tried: when the last fetch started, written before it is sent;
- error: how it failed (whitespace folded, cut at 500 runes), cleared
  when the next one starts.
Read together: error set, the last try failed; tried after at with no
error, a try is still out; tried long ago, nothing has asked since. A
failure is logged once until its error changes or a fetch gets the list
again, and the fetch that gets it after a failure is logged too. The
desktop app's log goes nowhere a user can read, so for the app the file
is what tells.

Checked for #3362 on the way: v0.1.1296's fetch, keep and save, given
the bytes /api/partners serves now (Kimi Code, listed from 10-23 00:00
+08:00) over the 10-20 file, writes the file, with the icon fetched or
not. So it isn't the save or the list.

Run on b437e4ad, go1.26.8. internal/provider is the same here and at
the branch's head (tree 613df3a9), where the checks of it ran:
- gofmt -l clean; go vet -tags nogui of internal/provider, gateway, cli
  and the root package with GOOS=linux, darwin and windows: clean.
- go test ./internal/provider -run Partner -count=1: ok.
- go test ./internal/provider -run '^TestPartners' -race -count=20: ok.
- TestPartnersKeepTheirLastTry on b437e4ad's partners.go: red at
  partners_test.go:511 (after a 503 there is no partners.json at all).
- Broken by hand, each red in TestPartnersKeepTheirLastTry: no write
  before the fetch (line 535: a try out shows no try since the last);
  the error not cleared when a try starts (535: a try out still shows
  the last error); the failure logged on every try (518: "logged 3
  times, want once"). Restored, green.
- Full suite at this commit, go test -tags nogui -count=1 -timeout 45m
  ./... (tree a661f529, 482s): 62 packages ok. 15 reds in 7 packages,
  none in a file this commit touches, each red on b437e4ad without it:
    internal/agent TestInstalledVersion, TestHowInstalled,
    TestOmpDetectedWithPiDir, TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI and TestZedAppPath:
    proc.Look keeps "not found" for a tool written in the tick of its
    folder's last change (#3141).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
    internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
Not tried: a real app left running against usemagpie.ai, on macOS or
Windows.
2026-10-24 21:33:06 +08:00
JoeyWu-tech f252b403d3 provider: the icon prune leaves a listed partner's logo, so the add sheet keeps drawing it (#3424)
partnerIcon keeps a partner's logo in the icons folder beside
providers.json and, while its iconUrl stays the same, uses the file it
kept as it is (97902e93), so the file only ages. No provider points at
it until one is added from the partner, and pruneIcons, after every
save of providers.json, removes a picture no provider or plugin names
once it is an hour old. A logo kept from an earlier day is that old at
once, so the first save after a start (a key, a model picked, an order,
a sign-in, a sync's pull) took it: /api/icons/<name> answered 404 while
the partner still named file:<name>, the add sheet's img fell back to
the generic icon, and the next fetch, finding the file gone, downloaded
it again, for a save an hour on to take. Before 97902e93 every fetch
downloaded it again, six hours apart, and a save an hour after each
took it the same way.

Now pruneIcons also leaves the pictures of the partners listed now
(keptPartnerIcons), as it leaves a plugin's (keptPluginIcons). A
process that hasn't asked for the list reads it from partners.json, as
Partners does, so a save from the CLI leaves them too. A partner no
longer listed loses its logo at the next prune unless a provider added
from it names it, as before. With the list off (MAGPIE_PARTNERS=off,
and every test that names no list) nothing is kept for it.

Lock order: store, then pruneIcons, then partnerMu. Nothing under
partnerMu saves providers.json or takes a lock store holds, and no
fetch runs under it.

Old data: a logo pruned before this is fetched again by the list's next
fetch (at start, then hourly), as it was; nothing to move.

What was run (tree 0409d43e, on a93190ae, go1.26.8):
  broken by hand, with this change: pruneIcons without the
  keptPartnerIcons loop:
    partners_test.go:489: the listed partner's logo was pruned: stat
    .../icons/d1774929a9b62027.png: no such file or directory
    partners_test.go:496: the logo was downloaded 2 times, want once
  a real run: magpie web in a sandbox HOME with the real list
  (usemagpie.ai/api/partners, Kimi Code) and stats off. A first start
  kept Kimi Code's logo; its file was set two hours back, as one kept
  from an earlier day is; a second start's fetch used it as it was;
  then magpie provider add Local url=http://127.0.0.1:9/v1 saved
  providers.json:
    main (a93190ae): the file gone, GET /api/icons/<name> 404,
    /api/providers still naming file:<name>, and a new Chromium drew
    Kimi Code in the add sheet with the generic icon
    this change: the file kept, 200, and the add sheet drew the logo
    (128 px wide)
  gofmt -l internal/provider: nothing
  GOOS=linux, darwin, windows go vet -tags nogui ./internal/provider:
  exit 0; CGO_ENABLED=0 GOOS=darwin and windows go build -tags nogui
  .: exit 0
  full suite, go test -tags nogui -count=1 -timeout 45m ./...: a first
  run stalled, the test binaries of 14 packages sitting in close(2) for
  45 minutes until the timeout (internal/provider ok); run again with
  nothing changed (445 s): 62 packages ok, internal/provider among them.
  13 tests red in 8 packages, none in a file this change touches:
    internal/agent TestInstalledVersion, TestOmpDetectedWithPiDir and
    TestZedAppPath: proc.Look keeps "not found" for a tool written in
    the tick of its folder's last change (#3141).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
    internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
    internal/middleware TestFailOpen: "spin took 1.508697807s", past
    its 1 s bound under the run's load; alone, -count=10: ok.
Not tried: the desktop app's webview (a browser that drew the logo
before keeps drawing it from its cache, since /api/icons answers
immutable for a year), macOS, Windows.
2026-10-24 21:33:06 +08:00
JoeyWu-tech 4725c772bb netproxy: a hung system proxy read holds no request; a failed one keeps the last proxy (#3421)
System() ran readSystem under sysCache's lock, and on macOS that is
scutil --proxy, started with proc.Command and no timeout. When neither
magpie's settings nor the environment name a proxy, every request's
proxy comes from there (For, through Func: http.DefaultTransport, the
gateway's upstream transport, MCP, updates), so a scutil that never
answered held each of them on that lock for as long as it hung, past
its own deadline too: net/http looks at a request's context before it
calls Proxy, not while. With no system proxy set, scutil runs again
every 2 s it is asked. And a read that failed was taken as no proxy:
where vendors are reached only through the system's proxy, a scutil
that failed once sent the next 2 s of requests direct. The code
standards' "nothing that can block runs under a lock its reader needs"
and "a failed read means unknown".

Found while chasing #3362, an app whose partner fetch never came back.
Nothing there shows scutil was what hung; it is the one wait on that
path with no end.

Now:
- One read runs at a time, outside the lock. A request waits for it
  until readWait (2 s) after it began, then takes what was read
  before. Before the first read that is nothing, so direct, as a
  failed first read was. A read already past readWait holds nobody.
- A read that fails keeps what was read before, and the read after it
  holds nobody either: requests go on with the proxy read before until
  a read answers.
- scutil gets toolWait (10 s) and is then ended (readTool, through
  proc.CommandContext), and that read fails.
- Windows' registry: a key or value that isn't there is no proxy, as
  before; any other error is a failed read. Elsewhere there is no
  system proxy to read, and nothing changes.

ggbdpq's patch on #2562 has testenv stand in for scutil with exit 1.
Under this change that read fails with nothing read before it, which
is still no proxy, so it does what it did.

What was run (tree 6f5e4b92, on f3eb9292, go1.26.8):
  before this change (2374ffe1, whose internal/netproxy differs from
  f3eb9292 only in login_test.go), a scratch test with readSystem
  held: a GET through Func with a 1 s deadline was still waiting
  after 10.008s
  go test ./internal/netproxy -run
  'Stuck|FailedSystem|ToolThatHangs|SetAfterStart': ok
  -race -count=20 ./internal/netproxy: no race; red in every run only
  at TestBunProxyLoginWithReservedCharacters (Bun 1.3.11 on PATH names
  port 80 in the request line, #3397)
  -race -count=40 -cpu 1,2 of the four tests above: ok
  broken by hand, with this change:
    the read back under the lock (System as it was, new signature):
      stuckread_test.go:103: 8 of 8 requests still wait on a read of
      the system proxy that never ends
      stuckread_test.go:137: a request still waits on a read of the
      system proxy that never ends
    a request waiting for the read with no bound: the same two
    a read for each request:
      stuckread_test.go:107: 8 reads of the system proxy at once,
      want 1
    readWait counted from each request, not from the read:
      stuckread_test.go:114: a request waited 1.000135471s for a read
      already past readWait (1s)
    a failed read replacing what was read before:
      stuckread_test.go:144: a failed read dropped the proxy read
      before: {URL: HTTP: SOCKS: Bypass:[]}
    the request after a failed read waiting for the next one:
      stuckread_test.go:159: a request waited 1.000232607s for the
      read after a failed one
    the tool never ended (WithCancel for WithTimeout):
      stuckread_test.go:185: a tool that never answered read as {URL:
      HTTP: SOCKS: Bypass:[]}, true (sleep 30 ran out, 30.00s)
  gofmt -l internal/netproxy: nothing
  GOOS=linux, darwin, windows go vet -tags nogui ./internal/netproxy:
  exit 0; CGO_ENABLED=0 GOOS=darwin and windows go build -tags nogui
  .: exit 0
  full suite, go test -tags nogui -count=1 -timeout 45m ./...
  (467 s): 62 packages ok. 14 reds in 7 packages, none in a file this
  change touches:
    internal/agent TestInstalledVersion, TestOmpDetectedWithPiDir,
    TestCursorFolderFromTheEditorIsNotTheCLI,
    TestCopilotFolderFromAnIDEPluginIsNotTheCLI and
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI: proc.Look keeps "not
    found" for a tool written in the tick of its folder's last change
    (#3141).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
    internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: as above
    (#3397), and red the same on f3eb9292 without this change.
Not tried: macOS (a real scutil, hung or not) and Windows (registry
errors). The tool test runs echo and sleep on Linux in scutil's place.
2026-10-24 21:33:06 +08:00
JoeyWu-tech ba4b754b22 gateway: a relayed Chat stream's tool call with no index is given its call's (#3386)
xianfeng-zhu (#3386): Cursor's Private Inference on magpie's
/v1/chat/completions, a Gemini model behind it, failed every turn that
made a tool call with AI_TypeValidationError at
choices[0].delta.tool_calls[0].index ("expected number, received
undefined"), then a 499 loop; turns without tools went fine. Gemini's
OpenAI-compatible API sends its calls with no index (Linka's frames in
gemini_compat_cut_test.go have none either), where the OpenAI contract
has one on every fragment, and a relayed stream went on without one.
The AI SDK's OpenAI provider, which the report names as what Cursor
reads Chat with, checks every chunk and turns that one away, so the call
is never made. OpenAI's own node SDK, through its stream helper, keeps
no call at all.

chatTidy, which already mends a relayed Chat stream's empty ids, empty
names and "stop" after calls, now gives a fragment with no index (none,
or null) the index of its call (streamCallIndexes.give). A fragment with
an id other than the open call's, or after the first in its delta,
starts the next call, as chatDecoder reads a new id; any other goes on
with the open one. So two calls in chunks of their own are 0 and 1.
Given both 0, as their place in the delta would give them, OpenAI's
node SDK merged them into one call with both arguments run together. A
fragment with an index keeps it, and a stream whose calls have theirs
goes as it came. It runs before the ids are mended, so a call with no id
either (#3386's chunk) gets both.

Not changed: the translations write an index already (chatEncoder,
chatWholeEvents), and a whole reply's message needs none. Nor is a call
given a type: Gemini's frames have "type": "function". The report's
chunk has neither an id nor a type, and is taken as cut short: magpie
gives a call with no id one (#2611, v0.1.1277), so the chunk it sent
would have had one.

What was run (tree e6023c66, on a93190ae, go1.26.8):
  a real run: magpie built at a93190ae and at this commit (go build
  -tags nogui), magpie serve in a sandbox HOME, its provider's Chat URL
  a local server replaying Linka's frames (the call, its signature and
  the usage in one chunk, then "stop", then [DONE]) under
  gemini-4-argon, so the Gemini paths run as for Google's host
  (geminiCompat). Clients on magpie's /v1/chat/completions, with the
  tool codemode:
    curl, the chunk magpie sends on: main, the call with no index; this
    change, index 0 (0 and 1 with the second call below)
    @ai-sdk/openai 2.0.136 (ai 5.0.281), streamText:
      main: AI_TypeValidationError, path choices, 0, delta, tool_calls,
      0, index, "Invalid input: expected number, received undefined";
      no tool-call
      this change: tool-call codemode {"code":"run()"}, finish
      tool-calls
    @ai-sdk/openai 2.0.48 and 2.0.122, older releases that turn away a
    new call with no id (2.0.48 one with no type too): main, the same
    validation error; this change, the call
    openai 5.23.2, chat.completions.stream and finalChatCompletion:
      main: no tool_calls (finish_reason tool_calls)
      this change: call_1 codemode {"code":"run()"}
    @ai-sdk/openai-compatible 1.0.59, which gives a missing index the
    call's place in its delta: the call, on main and with this change
    with a second call in a chunk of its own (made up from Linka's
    frame, id call_2):
      @ai-sdk/openai 2.0.48, 2.0.122 and 2.0.136: main, the validation
      error for each; this change, both calls
      openai: main, no tool_calls; this change, call_1 {"code":"run()"}
      and call_2 {"code":"two()"}
      @ai-sdk/openai-compatible: both calls, on main and with this
      change
    the replay sending both calls at index 0, as their place in the
    delta would give them: openai keeps one call, id call_2, arguments
    {"code":"run()"}{"code":"two()"}, on main and with this change,
    which keeps an index the upstream sent
    #3386's chunk as the report shows it, the call with no id and no
    type: this change sends it on with index 0 and an id (#2611's);
    @ai-sdk/openai 2.0.122 and 2.0.136 make the call, 2.0.48 throws
    "Expected 'function' type." and openai "tool call snapshot missing
    `type`"
    two such calls, each in a chunk of its own: nothing tells them
    apart, here as in chatDecoder, so both go with index 0 (the second
    is given its id after, where its signature is carried);
    @ai-sdk/openai 2.0.136 makes both calls, 2.0.122 the first only,
    2.0.48 and openai throw as above
  broken by hand, with this change: chatTidy without the give step:
    TestChatTidyGivesCallsAnIndex: no line's calls have an index
    ("line 4: indexes [[-1 -1]], want [[1 2]]")
    TestGeminiCompatRelayedCallsHaveAnIndex: every case, "call 0 went
    with index <nil>, want 0"
  go test -race -count=20 -cpu 1,2 of those two, TestChatTidy* and
  TestStreamedCallGivenAnID: ok
  gofmt -l internal/gateway: nothing; GOOS=linux, darwin, windows go vet
  -tags nogui ./internal/gateway: exit 0; CGO_ENABLED=0 GOOS=darwin and
  windows go build -tags nogui .: exit 0
  full suite, go test -tags nogui -count=1 -timeout 45m ./... (475 s):
  63 packages ok. 14 tests red in 7 packages, none in a file this
  change touches:
    internal/agent TestHowInstalled, TestOmpDetectedWithPiDir,
    TestZedAppPath, TestCopilotFolderFromAnIDEPluginIsNotTheCLI and
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI (qoder-cn): proc.Look
    keeps "not found" for a tool written in the tick of its folder's
    last change (#3141).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress (the
    package's only red), internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
Not tried: Google's own endpoint with a key (the frames are Linka's, as
the repo keeps them), Cursor itself, macOS, Windows.
2026-10-24 21:33:06 +08:00
yetone 9a2106220c gateway: a background sub-agent's notification after tool results reaches the Claude run (stones_2026 on Discord)
Claude Code 2.1.310 runs Agent sub-agents in the background by default.
When one ends while the main agent is mid-turn, Claude Code tells its
model with a <task-notification> in a {role: "system"} message after the
tool results (several that end together share one text block), or as a
text block of the results' message. On the Claude subscription path
saidWithResults drops every system message that isn't the user's own
mid-turn words (#2060, c4f4aaaa9), and agentNotice matches
<task-notification> too, so the run's Claude Code got only the tool
results. Its model never heard the sub-agent finished and kept waiting.

withTaskNotices now appends each such notification to the last tool
result inside <system-reminder>, where Claude Code itself puts one when
a notification lands in a tool result. saidWithResults strips them
first; token counts and hooks' notices are still dropped, and the
user's mid-turn words still go through as theirs. The other two shapes
already got through: a notification after the main agent's reply (a new
turn) and one inside a tool_result string (what Sonnet 4.5 gets).

Captured with a real Claude Code 2.1.310 against a local fake upstream
in a sandbox HOME (no real account): the system message after the
results, the shared text block, and the notice beside the user's
mid-turn message.

Tests (internal/gateway/claude_task_notice_test.go):
TestClaudeTaskNotificationsGoOnWithTheResults (4 cases),
TestClaudeTaskNotificationBesideTheUsersMessage (5 cases: the user's
mid-turn message and the notification in one block, in both orders, in
a system message and in a reminder after the results, with and without
Claude Code's "IMPORTANT: ... address the user's message" line),
TestWithTaskNoticesLeavesOtherResults, TestClaudeTurnToldTheTaskNotification.
Broken by hand (call site passes the bare results, no stripping): all 9
cases of the first two fail, e.g. "the run was never told SUBRESULT-A
finished: call-1 was answered \"slept\"". Stripping alone turned off:
the two user-first cases fail, the notification written to Claude Code
as the user's words.

Run at this head, rebased on origin/main 83234fe92:
- gofmt -l internal: clean; go build ./...; go vet ./internal/gateway on
  darwin, GOOS=linux and GOOS=windows: ok
- go test -race on the new tests and the #2060 mid-turn/hook tests: ok
- go test -run 'TestClaude|Context' ./internal/gateway: ok (64.5s)
- guard packages internal/proc, internal/testenv: ok
Full gateway suite (-count=1 -timeout 45m, alone on the box): ok in
819.6s at 1dd279f69 (base e219f699c), with the first version of the
BesideTheUsersMessage test; the widened test was run on its own above
(-race -count=3 too). Not run again after the rebase onto 83234fe92
(gateway/gui context parts, no overlap with this file) because three
other sessions' suites were running; CI runs it at this head.

Not tried: a real Claude account; the other candidates for the report
(a lost stream tail, concurrent streams ending together) with a
concurrent fake upstream, since the captures show content being dropped,
not a cut stream; the Windows box; go test ./... beyond gateway and the guard packages.
2026-10-24 21:29:57 +08:00
yetone 83234fe920 gateway, gui: the skills an agent lists are their own part, not memory
The owner (10-24, on the Routing context map's "技能 / 记忆 · 9.6K"):
为什么这里又叫技能,又叫记忆?Skill 跟 Memory 应该是不一样的东西. The
gateway put Codex's <skills_instructions> in the memory part beside the
instruction files and reminders, so the tile said Skills of Memory.
Claude Code's skill list wasn't seen at all: it sat in its environment
message, counted as the system prompt.

- gateway: PartSkills ("skills") comes after tools. Codex's
  <skills_instructions> goes there. So does Claude Code's list, from
  "The following skills are available for use with the Skill tool:" to
  the next blank line, taken out of whatever text holds it: its own
  prompt, a harness message or a reminder.
- Routes kept before this (routing history) are read with an item
  tagged skills moved out of memory into the skills part, so old
  requests read the same way. The text view re-reads the body and finds
  them under skills too.
- Usage's context baseline counts skills, as it did inside memory.
  memory-heavy is now instruction files and reminders alone.
- gui: the card has a Skills part (slate, --c7), with its note in en,
  zh, zh-TW, ja and de. The text view's "no longer kept" line is one
  helper instead of two copies of the sentence, which makes the room for
  it under the core script budget, with no room added.

Run (darwin):
- go test ./internal/gateway -run 'Text|Prompt|Context|History|Skill|Route'
  ok; go test ./internal/gui ok; go vet both, gofmt clean.
- New: TestPromptOfClaudeCodeSkills (on testdata/workdir's real Claude
  Code 2.1.296 body: 1502 tokens of skills out of the 2130-token
  environment item), TestSplitSkillsEnds, TestSkillsApartOfKeptPrompt.
  Broken by hand (splitSkills and skillsApart made no-ops): all three
  red.
- GUI, chromium and webkit: context-map 22/22 (new: the skills tile's
  tip names Skills and not Memory in every language, and it isn't
  memory's colour), context-window 24/24, context-text 20/20,
  context-scroll-end 14/14, routing-context-fold 24/24,
  routing-ctx-still 16/16, i18n-keys 4/4.
Not run: the whole GUI suite (load ~400 on the box); a live Codex or
Claude Code request through the real app.
Not changed: the "system prompt, tools and memory" wording of the
baseline's tags, which now count skills too.
2026-10-24 21:03:52 +08:00
yetone e219f699ca gateway: with no S3 bucket the request archive keeps calls on this computer, oldest removed past 1 GiB (CyberCaius)
CyberCaius on Discord: "请求存档只能存在 s3 存储桶里,不能保存在本地吗". The
Usage page's Request archive switch refused without an s3:// sync. Now,
with no bucket, the same switch keeps each call in
<settings.Dir()>/request-archive/<date>/<id>.json: the same file the
bucket gets, masked the same way (Archived, archiveRequest), written to a
temporary file beside it, synced and renamed, 0600 in a 0700 folder.
Past its size (RequestArchiveLocalMB, 1 GiB unless set) the oldest calls
go first, down to a tenth under it; the call just written is never
removed, empty day folders go, and a .part file an hour old is removed
on the next scan. The running total is counted once and then added to,
so a write walks the folder only once it is over.

On by default or a switch: a switch, still off unless turned on. Bodies
can hold secrets, so nothing is written to a disk where the user didn't
ask. The local switch is its own field, RequestArchiveLocal, in KeepOwn
with its size, so sync never turns it on at another computer, and
RequestArchive synced from a computer with a bucket keeps nothing on one
without (archiveDest). The GUI switch writes RequestArchive while sync
has a bucket and RequestArchiveLocal while it has none; the tooltip names
the folder and the size, and a failed write reads "Not saved" (en, zh,
zh-TW, ja, de). GET /api/archive reads this computer's copy first, then
the bucket. The Settings page's save keeps both fields (api.go).

Docs: sync-backup.md and gui-shell.md say where the archive goes and why
the switch is per computer; the privacy pages (en, zh, ja) say what the
folder holds, that it is off by default, and how large it grows. The
READMEs' Privacy is about what is sent and is unchanged.

app.js stays under TestCoreScriptBudget (its comment was shortened, and
one t() call folded); no budget raised.

Run (worktree diff on 5222a4b12, sandbox HOME):
- go test -tags nogui -count=1 ./internal/settings/ ./internal/gui/
  ./internal/gateway/: ok (29s, 73s, 507s)
- node --test request-archive, request-archive-usage, routing-bodies,
  gui-zh-tw, gui-ja, gui-de, i18n-keys (chromium and webkit): 37/37 pass
- gofmt -l internal/: clean; go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean; go build for darwin, linux
  (nogui), windows: ok
- TestCoreScriptBudget: ok

After rebasing onto origin/main 3840333c5: -run Budget|Archive|SaveKeeps|
RequestArchiveLocal in gui, gateway, settings ok; request-archive and
i18n-keys 8/8; gofmt clean; linux and windows vet clean.

Broken by hand, each red, then put back:
- archiveDest's local branch off: TestArchiveOnThisComputer red
- RequestArchive also writing to disk: TestArchiveNeverOnDiskUnasked red
- no pruning: TestLocalArchiveRemovesOldestPastItsSize red
- KeepOwn line removed: TestRequestArchiveLocalIsThisComputers red
- POST setting RequestArchive with no bucket:
  TestArchiveSwitchKeepsOnThisComputer red
- GET not reading the local copy: TestArchiveSwitchKeepsOnThisComputer red
- api.go not carrying the fields: TestSettingsSaveKeepsWhatItDoesNotSend red
- writing in place, not through temp+rename: TestArchiveOnThisComputer red
  (mode 0644, a .part left)

Not tried: the real app with a real agent's calls (the gateway tests
drive real requests through serve with a fake vendor); Windows' file
modes (0600 is skipped there); the full ./... suite before the push (the
machine had a queue of sessions' suites; it is queued after).
2026-10-24 21:01:18 +08:00
yetone f6a96b2f0b usage: a change time with a fraction settles in 100ms, so a read after an append hashes no log (#3394)
readLogSnapshot checks its snapshot against a SHA-256 of the log's whole
prefix whenever the log's change time is under a second old. Under steady
traffic every read came within a second of the gateway's last append, so
each one hashed the whole usage.jsonl again: 1.8 times the log for each
append and read. A stamp with a nonzero fraction of a second comes from a
clock that ticks in milliseconds (APFS in ns, Linux's coarse clock 1-10 ms,
NTFS ~15.6 ms), so it settles in logFineSettle = 100ms. A stamp in whole
seconds (HFS+, FAT, a share) keeps the one-second settle.

Run:
- go test -count=1 -timeout 45m ./internal/usage/ ./internal/budget/: ok.
- TestUsageReadAfterAppendHashesNothingOnAFineClock (20000-row log, 5
  appends, each followed by two reads): fine stamp 0 bytes hashed;
  whole-second stamp 50.7 MB. Broken by hand (logFineSettle = time.Second):
  54 MB hashed, red.
- Real account, sandbox HOME, a deepseek-only providers.json and a 98 MB
  usage.jsonl (the owner's own log, repeated 50 times). magpie serve took
  30 real /v1/responses calls with a Codex user agent to
  deepseek/deepseek-flash, all answered, while /v1/magpie/usage?period=today
  (the Usage page's read) was polled every second. Process CPU time, two
  runs each: before 3.11 s and 3.05 s, after 1.95 s and 2.25 s. The same
  calls with /v1/magpie/quotas polled cost 0.2 s on both binaries, since
  that path never reads the log.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage/ clean.

Not tried: an HFS+ or FAT volume (the test skips when the file system
gives whole-second stamps, and covers that case by truncating the stamp);
the full suite at this head runs after the push.
2026-10-24 21:00:05 +08:00
yetone 2dfaf75539 redact: a masked body is held at its size, not in a buffer grown by doubling (#3383)
With masking on, the masked body is what a request holds while it
streams (MaskJSON, 285 MB live in the report's heap). walk built it in a
bytes.Buffer grown by doubling, up to twice the body. It now makes room
for the body and a sixteenth at the first value it masks, and copies the
result to its size when placeholders grew it past an eighth spare.

Run:
- the heap probe, 8 requests of 9.7 MB held mid-stream with Privacy
  masking on: 138 MB before, 86 MB after (Anthropic to Anthropic);
  translated to Chat 235 MB before, 183 MB after.
- TestMaskedBodyHeldAtItsSize: green; red with both changes off
  ("the masked body of 4356589 bytes is held in 7077888").
- go test ./internal/redact/ ./internal/masking/ ok; gateway -run
  'Mask|Redact|…' ok (see the commit before).
2026-10-24 21:00:05 +08:00
yetone 106a245502 gateway: a request's body goes once it is answered, not when its stream ends (#3383)
The transport holds a request until its reply's body is closed, a
stream's whole length, and with it the bytes.Reader body and the GetBody
NewRequest made over it. So every streaming request kept the body it
sent upstream alive to its end: for a Claude Code request translated to
Chat, the marshalled body (marshalRaw/appendHTMLEscaped in the report's
heap, 503 MB live).

provider.SetBody gives a request a body whose reader drops its bytes
once read and whose GetBody reads them again until provider.LetGo.
forwardOnce lets go once its retries (RetryOneAuth, RetryZhipuCoding)
are done; Codex's zstd turn, Copilot Auto's model swap and Gemini's Code
Assist envelope set their bodies the same way, so LetGo reaches them.

Run (worktree perf-stack, on the four commits before it, over
origin/main 137187a40):
- a heap probe, 8 Claude Code requests of 4.7 MB held mid-stream to a
  Chat upstream: 152 MB held before, 88 MB after; the rest is the body
  as it came (another member) and as read (a continuation). Anthropic
  to Anthropic holds the body once, 41 MB.
- TestStreamingRequestsLetTheirSentBodyGo (bar 3x the body each) and
  TestSetBodyLetsItsBytesGo: green; red with LetGo commented out of
  forwardOnce ("8 streaming requests of 4 MB hold 166 MB, 4.2 times the
  body each") and with LetGo storing nothing ("the request holds its
  body's bytes after it was answered").
- go test ./internal/provider/ ./internal/redact/ ok; ./internal/gateway
  -run 'Mask|Redact|Codex|Copilot|Gemini|Google|Antigravity|Zhipu|Auth|
  Retry|Stream|Continu' ok; GOOS=linux and windows vet -tags nogui
  clean, gofmt clean. The full suite runs at the pushed head.
Not tried: a real vendor; the bytes on the wire are the same.
2026-10-24 21:00:05 +08:00
yetone b0d0092be5 middleware: a streaming request's runtimes let its body go once its request hooks are done (#3383)
A request keeps its middleware runtimes until its reply has streamed,
so its hooks share ctx.state, and moejs kept the body each hook was
given, parsed, in the runtime's registers until End: a long context's
body was alive for the whole reply, ~10 MB for a 7 MB body. The report's
inuse profile had 448 MB under moejs ParseJSON with many agents
streaming at once. Request and Tried now call ReleaseCallData on the
request's runtimes once their hooks are done; ctx, and what ctx.state
holds, stay. Not after each onEvent: an event is small and its hooks run
a thousand times a reply.

Run:
- TestStreamingRequestHoldsNoBody: 8 requests streaming with a 7 MB
  body hold under 7 MB, and onEvent still reads ctx.state; with the
  release commented out by hand it fails ("8 streaming requests hold 69
  MB, their body is 7 MB").
- go test -count=1 ./internal/middleware/ ./internal/gwmw/: ok.
- go test -count=1 -run 'Middleware|Think|Strateg' ./internal/gateway/
  ./plugins/...: ok.
- gofmt -l clean; go vet darwin, GOOS=linux and GOOS=windows -tags nogui
  clean for internal/middleware.
2026-10-24 21:00:05 +08:00
yetone 4753a6cfbb gateway: a look at the routing history reads today's file only past what it counted, and parses only its latest routes (#3383)
The Routing view asks /api/gateway/history every 15s while requests are
done. History read a day's .jsonl whole whenever its size had changed,
which today's always has, so a busy day's 350 MB file (19,751 routes in
the report) was read through at every look, and asking for today
unmarshalled all its routes to keep the latest 2000. Now a .jsonl's
count is kept with where each of its lines starts: a look reads only the
bytes added since, and the asked day parses its latest historyMax plus
200 lines (historySlack, for a route done after later ones began). A
last line without its newline is counted, as readDay reads it, but
tallied again at the next look, as it may be half written; a file
smaller than what was counted is counted again from its start. .gz days
are read as before, an asked one skipping the unmarshal of all but its
latest lines.

Run:
- TestHistoryReadsOnlyWhatWasAdded: ok; red on the old history.go
  ("want 2252 requests", got 2251: it read the blanked routes again).
- BenchmarkHistoryLook (20k routes, ~100 MB, one added per look):
  54.1 ms/op on the old code, 1.19 ms/op now.
- go test -count=1 -run 'History|Trace|Route' ./internal/gateway/
  ./internal/gui/: once exited 1 with the failing test's name lost to a
  tail; rerun with the whole log kept, then -count=3: ok every time.
- gofmt -l clean; go vet darwin, GOOS=linux and GOOS=windows -tags nogui
  clean for internal/gateway.

Not done here: the route's Order list's size on disk, and moejs's
retained JSON (#3383's other two findings).
2026-10-24 21:00:05 +08:00
yetone f8fa8147ba sessions: a page-asked first read uses half the cores, not twice them (#3238)
The index's cold scan with a page waiting started min(max(8, 2*NumCPU),
32) readers, as if reading waited on the disk. On an SSD decoding and
parsing is the work: on the Windows box (32 cores) a cold start over
6751 real Codex session files (15156 MB) with /api/sessions waiting
held 2154% CPU, the ~2000% the reporter saw, while other apps ran
beside it. Now max(2, NumCPU/2) readers; the quiet warm-up's NumCPU/4
slots are unchanged.

Run:
- TestAskedIndexReadsWithHalfTheCores: ok; with the old count put back
  by hand it fails ("the index read 28 files at once, want 2 to 7").
- go test -count=1 ./internal/sessions/: ok (64s).
- gofmt -l clean; go vet darwin, GOOS=linux and GOOS=windows -tags nogui
  clean for internal/sessions.

- On the Windows box (32 cores), a cold read of 14051 session files
  (~44 GB) with a page waiting, magpie built from this commit's parent
  against this one: peak CPU 1634% -> 1172% (about 900-1100% sustained),
  peak working set 1612 MB -> 1108 MB, ~22s -> ~27s to read them all.
2026-10-24 21:00:05 +08:00
yetone fc9430e12d proc: Windows lists processes from a Toolhelp snapshot, not a new PowerShell and WMI each time (#3467) 2026-10-24 21:00:05 +08:00
yetone b5d46acbed agent: Kiro Crew runs on a harness connected to magpie
Vincent on Discord asked for Kiro Crew (kirodotdev/KiroCrew v0.9.0: the
KiroCrew.app desktop app, the kirocrew CLI, its dashboard and the Gateway
on :5476). Crew has no model provider of its own. It runs each session on
an ACP harness picked by agent.acp_backend (and dispatched members by
agent.member_acp_backend) in $KIROCREW_HOME/config.json, default
~/.kiro/crew (src/kiro_crew/config/paths.py, loader.py, sections.py;
ACP_BACKENDS_MEMBER_DISPATCH in agent_sdk/backends.py).

Connecting sets those keys to an agent already connected to magpie,
tried in this order: Codex, Claude Code, OpenCode, Pi, Goose. One whose ACP
adapter is installed (codex-acp, claude-agent-acp, pi-acp) wins, so one
click is enough. magpie looks for the adapter where Crew does and installs
nothing; when it's missing, the notice gives the npm command. With no harness
connected the connect is refused with a message naming which agents to
connect. A harness set in config.local.json wins over config.json, so magpie
doesn't write it and the row says so. The previous values are stashed. On
Disconnect they are put back, but only for keys that still hold what magpie
wrote, and a file magpie created is removed once it's empty. The row reads as
connected only while its harness is still wired to magpie. deepseek is not
offered: Crew runs it as dsh --profile acp, which magpie's dsh wiring doesn't
reach. KIROCREW_HOME and the adapter path variables are read from the login
shell (agentenv).

Run (Go and the GUI files at base 137187a40, then again after the rebase onto 3d758d034):
- go test -tags nogui ./internal/agent ./internal/agentenv: ok, in a
  sandbox HOME
- gofmt -l is clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/agent/... ./internal/agentenv/...: ok
- GUI: the new agent-kiro-crew-lang.test.cjs (refusals, notice and words in
  en, zh, zh-TW, ja and de; chromium and webkit; 1100 and 420px) 22/22. The
  agent*, gui-*, i18n* and header-relang files (45), concurrency 2 at load
  ~250: 632/633. The red was agent-models-own, chromium en 420, where the dsh
  row's model click timed out at 5s (#1666, filed). After the rebase that
  file and the new one, run alone: 38/38.
- After the rebase: go build ./...; the KiroCrew, Notice, FolderVars,
  EveryPicker and ListsModels tests: ok. go test ./internal/gui: everything
  passed except TestMainWindowCorners, which was killed at its 40s
  measurement at load ~200 (#1936, #2645, both filed; this change touches
  no window code).
- No go test ./... at the pushed head before the push: the machine is at
  load 200-300, other sessions are queued for the suite lock, and ships go
  out at once (owner, 10-22). Queued to run behind them at the pushed
  head.
- Real Kiro Crew: Crew v0.9.0 was installed from source into a sandbox venv,
  and its own loader (load_config_with_content_stamp, overlay_pins) read the
  config.json magpie wrote over the real Codex wiring in a sandbox HOME:
  acp_backend='codex', member_acp_backend='codex'. With a config.local.json
  pin it reads the pinned value and overlay_pins is True. Disconnect gave the
  user's file back as it was, and removed the file magpie had created.

Broken by hand, each red:
- restore off: Connect, PicksAHarness, HarnessPick, MakesItsFile
- the pin check off: LocalPin
- adapter preference off: PicksAHarness
- the member key always written: PicksAHarness, HarnessPick
- harness wiring unchecked in on(): FollowsItsHarness, OnRealCodexWiring
- the ja translation of the pinned refusal removed: the new GUI test, ja at
  both widths

Not tried: Crew's Gateway starting a real session through codex-acp
against magpie's gateway, and none of Crew's harnesses was run under it.
Adapter paths on Windows. A user who pinned agent.model to a kiro-only
model on a non-kiro harness.
2026-10-24 20:59:25 +08:00
yetone 3840333c51 site: APIKEY.FAN is a README sponsor
APIKEY.FAN added a README seat to its in-app one. README.md shows its
English logo ("Enterprise AI Gateway"), README.zh-CN.md its Chinese one
("企业级 AI 中转站"), each with a dark copy whose #111111 lettering is
#F2F2F2, the orange mark unchanged. Both link usemagpie.ai/go/apikeyfan/readme,
which sponsors.js sends to apikey.fan/?aff=mg_readme, the link APIKEY.FAN
gave for the README.

Run: node --test site/*.test.mjs (30 of 30 ok). The four logos rendered
with rsvg-convert on white and on GitHub's dark background and looked at.
After the deploy, /go/apikeyfan/readme is checked for its 302.
2026-10-24 20:50:18 +08:00
yetone 3d758d0345 gui: Settings › About's Version row keeps its height while the update read is out (#3469)
xisdumpling: going back to Settings › About from another page made every
row jump up about 12px and back. renderSettings rebuilds #about, and the
new Version row had no line under its name and no Check button until
renderUpdate's GET /api/update came back.

Now renderUpdate keeps the last state it drew (updateLast, which
renderUpdateBadge's read at start fills in too). A row made again draws
that state at once, then reads. Once the read is back it bumps the
row's sequence, so timers the early draw started stop. There are two
exceptions:
- no early draw while a check is out (the old code drew the row blank,
  then "checking");
- Download from GitHub clears the cache before it redraws Settings, so
  the mirror's old error isn't drawn again.

Size: app.js and the core are under their budgets, which are not raised.
No function in app.js has a single plugin as its only user, so the
room came from renderUpdate itself: one opener for the release page
(4 copies), one dim() (2) and seqOf(r) (9).

Run, at a3b8d706e's tree rebased on 5222a4b12:
- update-row-held (new), update-check, update-mirror, update-wait,
  update-restart, i18n-keys and settings-sections, in Chromium and
  WebKit: 92 of 92 pass.
- go test -tags nogui ./internal/gui/ -run 'TestCoreScriptBudget|I18n|Asset': ok.
- Before the last rebase: go test -tags nogui ./internal/gui/...: ok.
  The 31 GUI files that reach Settings › About or /api/update, in both
  engines (update-*, settings-*, i18n-keys, header-*, whats-new*,
  cli-behind, menu-scroll, refresh-page, segs-glide): two reds were mine
  and are fixed above (update-mirror zh, update-check "drawing the row
  again while a check runs"). Two are not mine:
  - update-wait chromium en, under load, is #3275. It passes 3 of 3
    alone.
  - header-centre webkit "en at 125%" is red on origin/main 5222a4b12
    too. It is a ResizeObserver loop reported as a page error, filed as
    #3479.

Broken by hand: update-row-held.test.cjs, run against origin/main's
app.js, is red in both engines: "the row was 60.28125px with \"Up to
date\" and Check; 36 of 39 frames drew it otherwise" (WebKit 39 of 40).

Not tried:
- the real Windows app, where it was reported. The test runs the
  page's own show("agents") then show("settings") path with the update
  read held;
- the first-open case in the real app (the cache comes from the start's
  badge read). It is covered only by reading the code.
2026-10-24 20:34:42 +08:00
yetone 7765f27fcc gateway: a model an account refuses goes on to the accounts not listing it yet
01huadalang (Discord): Antigravity with several accounts, only some can
use Gemini 4. The model and its bar showed only after the right account
was made preferred and probed, and a request failed with the preferred
account's error instead of going on to the account that serves it.
st3lland (Discord): on ZCode (plugin) accounts serve different models.
Owner: no manual setting, magpie knows per account and routes.

Two causes:
- perKeyBarred puts an account whose own saved list lacks the model in
  pl.unlisted / pl.left (Unlisted) and serve never asked it. So when
  the listing accounts refused the model (Antigravity's real 404
  NOT_FOUND "Requested entity was not found.", codeAssistModelMissing;
  plugins through modelRefused's unservedWords), the agent got that
  error even though an account whose list was simply stale serves it.
  Now, once every listing account of that subscription/model has been
  asked and one refused it as unserved (unservedTry), its unlisted
  accounts are asked next, right after it and before any other member
  or fallback (unlistedNext, askUnlisted for the trace). The refusing
  try rests as before (restAfterMarked, for that model). Not for a
  pinned account, a sealed conversation or strict affinity; a gateway
  key's account list narrows unlisted too (allowedCandidates). Other
  refusals (403 PERMISSION_DENIED, 429 RESOURCE_EXHAUSTED) don't open
  the unlisted accounts.
- Antigravity's per-account lists were refreshed only on the first
  listing, a probe, a sync or a Refetch, so a model granted later and
  its bar (chosenWindows filters by exposed models) stayed hidden. Its
  quota reading already fetches fetchAvailableModels per account; now
  it saves that account's list (noteAntigravityList) and re-merges the
  pooled list from every On account's list when it changed. An Off
  account's reading changes nothing.

Other vendors: the unlisted route only opens on the existing unserved
classifiers (Antigravity's 404, plugins' unservedWords), unchanged here;
TestUnlistedAccountNotAskedForOtherRefusals holds that the other real
Antigravity bodies don't open it.

Run (at the rebased head on origin/main 5222a4b12):
- go test ./internal/gateway -run TestUnlistedAccount (4 new) and
  ./internal/provider -run 'TestAntigravityQuotaReadingListsNewModels|
  TestAntigravityModelsAcrossAccounts': ok.
- Targeted: ./internal/gateway -run 'Unlisted|Antigravity|Fallback|Refus|
  Unserved|KeyModel|Lists|Plan|Rest' and ./internal/provider -run
  'Antigravity|Google|Gemini|Pool|Lists': ok (gateway 34.9s, provider 4.5s)
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- Full suite: queued behind three other sessions' full runs on this
  machine (load ~300); its result goes on this commit's follow-up, not
  claimed here.
- GUI: no asset changed; none run.

Broken by hand, each red, then restored:
- unlisted fallback off (false && unservedBy[key]): AskedAfterModelRefused
  404, BeforeFallback served a's fallback.
- unlisted appended after fallbacks instead of inserted: BeforeFallback red.
- key doesn't narrow unlisted: HeldFromKey got b's 200, want a's 404.
- quota reading keeps no list: QuotaReadingListsNewModels pooled list
  lacks Gemini 4.

Not tried: no real Antigravity accounts with and without Gemini 4 (the
404 body is the one on record from earlier reports); no real ZCode
"model not available" body is on record, so none was invented and ZCode
relies on modelRefused's existing words; the plugins repo is unchanged
(ZCode's models(provider,{auth}) already lists per account). Known
limit: a resting listed account that is the lone candidate is still
asked first on later turns until the unlisted account's list refreshes
at its next quota reading, one extra request a turn.
2026-10-24 20:32:33 +08:00
yetone 5222a4b129 gui tests: segment-press-dialog waits for the add sheet the page opens itself
With no provider, the Providers page opens its add sheet itself once
/api/providers is in (app.js renderProviders), and the add button goes
away. The test pressed #addProvider right after goto: when the list came
first, as it does on a busy machine, the press waited 30s for a button
that was gone. It was red 1 of 2 runs at f35c721c4~1 (load ~310) and
3 of 4 in the 112-file #modal run; the test now waits for the sheet's
tile instead.

Run: segment-press-dialog, chromium and webkit, en and zh, 3 runs in a
row: 4/4 ok each. No other test that presses #addProvider has an empty
list.
2026-10-24 20:16:25 +08:00
yetone 3d56822d41 gui: a provider's editor grows from where its row was pressed
The owner (10-24, 点击这里,然后放大弹窗的时候,应该从点击处可放大吧):
pressed past its name, a provider row's editor grew from the row's left
end, its logo and name, not from the press. Pressed on the logo itself
(the row's drag handle), it didn't grow from the row at all: the handle
was recorded with no way to find it again once the row was drawn anew,
so the dialog opened with no morph.

The press now keeps its x. rowOwnRect still takes a strip the size of
the logo and name, and when the press is past them it centres that strip
on the press, inside the row. A press on .pv-handle counts as the row's.
Closing goes back to the same strip.

Run (darwin, chromium and webkit, on d0a54d74a's calm() refactor):
- modal-morph: 6/6 ok at 1240 and 420px. Its first open now presses the
  logo, and a new case presses at 62% of the row and checks the strip:
  centred within 3px of the press, as wide as the first one, inside the
  row, closing back to it. Broken by hand: without the handle mapping,
  red at "opening clips the dialog: none"; without the centring, red at
  "again: the strip centred on the press".
- modal-centred-late 6/6, group-morph 22/22 ok.
- go test ./internal/gui -run TestCoreScriptBudget: ok, with no room
  added (calm() made the room).
Not run: the whole GUI suite (load ~400 on the box); the real Wails app.
2026-10-24 20:12:27 +08:00
yetone ed0425fc9f gui: every reduced-motion check in app.js asks calm()
app.js asked matchMedia("(prefers-reduced-motion: reduce)") in nine
places, and calm() did the same as a const defined at the dialog code.
calm is now a function declaration, so code above it can call it too,
and every other place asks calm(); stillMotion and navCalm stay its
names where they were. Nothing changes in what moves: this frees ~470
bytes of the core script budget for the next change (the editor
growing from where its row was pressed).

Run (darwin, chromium and webkit):
- node --check app.js: ok. go test ./internal/gui -run
  TestCoreScriptBudget: ok.
- GUI: modal-morph 6/6, held-animations 4/4, routing-ctx-still 16/16,
  context-map 22/22 ok.
Not run: the whole GUI suite (load ~400 on the box).
2026-10-24 20:12:27 +08:00
yetone 31275d0734 gateway: a history call to a tool the request doesn't declare gets a stub where it is refused (pi, T3 Code tool_search)
Gearclickist on Discord: pi and T3 Code, on magpie's /v1 chat/completions,
load tools on demand. The tools a tool_search found are called in the
history but not declared in the next request's tools, and pi sends
"tools": [] with history calls when it has no tools left.

Cause, per upstream (magpie forwarded the calls unchanged on every path,
seen in a probe through fakes):
- Anthropic Messages (API, Bedrock/Vertex Claude, relays): a call to a
  tool it isn't given is accepted, but calls with no tools at all get
  400 "Requests which include tool_use or tool_result blocks must
  define tools". anthropicBody dropped tools when the request had none,
  so pi's tools: [] turn failed. Now each tool the history called is
  declared as a stub (any object, "Called earlier in this conversation;
  not available now.") with tool_choice none, as LiteLLM's dummy tool
  and the Kiro plugin do.
- OpenAI Chat/Responses, ChatGPT backend, Gemini/Code Assist: take the
  history as it is; left as sent (TestUndeclaredHistoryToolTakenAsSent).
- Stricter Chat/Responses/Messages upstreams (relays in front of Kiro or
  Bedrock, vendors that check each call's name): a 400/422 that names an
  undeclared history tool as not found/unknown/not defined, or says tools
  must be defined beside the calls, is asked once more with a stub per
  missing tool, relayed or translated, and remembered per provider and
  API (historyToolsRefused). tool_choice none only where the client
  offered no tools. Namespaced Responses calls are left to the namespace.
- Claude subscription: runs real Claude Code with the history as text,
  not affected. Kiro plugin already stubs its history's tools.

Run, at 54874c9ee rebased on origin/main:
- the new tests and the gateway's ToolStrict/Anthropic tests: ok
- gofmt -l: clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean (before the rebase)
- go test -tags nogui ./... -timeout 45m was running at the pre-rebase
  commit when this was pushed (ship-immediately); its result goes on the
  tag's report.

Broken by hand, each red, then restored green:
- the refusal matcher off: RefusedThenStubbed (chat, responses,
  anthropic) and ToollessHistoryRefusedOnChat red
- the remembered upfront stubs off: RefusedThenStubbed red (3 asks)
- anthropicBody's stubs off: ToollessHistoryToAnthropicDeclaresStubs red
- the stubs' tool_choice none off: same test red ("tool_choice \"\"")

Not tried: no real vendor was asked (fakes only); the refusal wordings
for stricter vendors are modelled, not captured from the reporter, who
named no upstream; the other community plugins' own translators
(Cursor, Devin, Qoder, ...) were not read for this; real pi/T3 Code not
run against this build.
2026-10-24 20:11:06 +08:00
yetone b995095637 gui: a routing group's strategy is switched from its row (MoChou, #3450)
MoChou (#3450): changing a routing group's strategy took opening the
editor, finding the routing control, picking and saving. The routing
tag on each group row is now a pop-up button: it opens the app's own
menu (openProtoMenu, no native select) with the routings the editor
offers (GROUP_ROUTE_OPTS plus JS plugin routings), the current one
checked. Picking one saves the group through /api/groups/save with
every other field as it was, as the editor's Save would. Manual keeps
the pick the group had; with none the gateway takes the first member
(provider.cleanGroup), as with the editor. "Rate limited to the back"
is dropped when the new routing can't sink, as the editor does.
Re-picking the checked routing saves nothing; an editor with unsaved
changes asks first (confirmDiscard). The row's Edit button and switch
are unchanged; clicking the tag doesn't open the editor and doesn't
scroll. Keyboard: Enter/Space opens, arrows move, Escape closes back to
the tag, and focus returns to the same group's tag after the save
redraws the list. At <=560px in the window the row keeps only its
routing tag (the other tags stay hidden as before). New string "How
{name} routes: click to change it" in zh, zh-TW, ja, de.

Run (worktree; the new test, i18n-keys and internal/gui budget/i18n tests again at this head after rebasing on e698a688f, 22/22 ok):
- internal/gui/tests/routing-group-strategy.test.cjs (new): 18/18 ok,
  chromium + webkit; en/zh x light/dark, 520px window and 390px web,
  zh-TW/ja/de strings.
- Not the whole GUI suite: the machine sat at load 130-540 behind
  other sessions' suites for 2.5h. Ran every routing-*, i18n-*,
  plugin-* and gui-* file, both engines (1031 cases before I stopped
  it at load 500): reds only in routing-groups-jump (1 case, filed
  #3478; 3/3 alone), routing-intent-entry, routing-keys-fold,
  routing-levels, routing-manual, routing-mode-goes, routing-pause,
  routing-rule-effort, routing-rule-remove, all 5s timeouts or
  counts read early. routing-manual passed 4/4 rerun alone;
  routing-pause and routing-rule-remove fail the same way on an
  origin/main c819e00c4 copy at the same load (filed: #3410, #3411,
  #3408, #3096, #3094, #1612).
- go test -tags nogui ./internal/gui (core script budget): ok.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., gofmt -l, the three builds: clean.

Broken by hand, each red in the new test, then restored:
- origin/main's assets (MAGPIE_ROUTING_ASSETS): 18/18 fail ("the row's
  routing is a button", 0).
- keeping sink for Manual; dropping stopPropagation (the editor
  opened); dropping the focus restore; hiding every tag at narrow
  width.

Screenshots of the row and open menu, light and dark, en and zh, both
engines, checked by eye.

Not tried: the real app (WKWebView/WebKitGTK/WebView2) with real
groups; Windows; a JS plugin routing in the menu (only its code path
through withJS, which the editor shares).
2026-10-24 19:54:30 +08:00
yetone 137187a401 gateway: Claude Code's auto mode classifier follows a /model switch at once
CyberCaius on Discord: after switching models, the first auto mode
permission check went to the previous model. The model is Claude Code's
choice, not magpie's. Claude Code 2.1.310 ($Xe/BB) names
ANTHROPIC_DEFAULT_SONNET_MODEL for the classifier, not the session's
model. magpie's sonnet tier follows the main model only once Follow runs
(the GUI's state poll), and Claude Code reads env again only on its next
start. So right after /model the classifier named the old main model.

At the gateway, a classifier request (recognised from its body: a
<transcript> and a <block>/<severity> verdict, no tools) on a sonnet tier
that follows a main model settings.json no longer has goes to the tier
the new main model gives it (followAt, keeping the tier's effort). It is
left alone when the user set CLAUDE_CODE_AUTO_MODE_MODEL, when the sonnet
tier is their own, when the base URL isn't magpie's, or when the main
model hasn't moved. WSL distros are read the same way. Only the
classifier is rerouted: a turn naming the old model may be another open
session that is still on it. The haiku, opus and subagent siblings are
#3474.

Run (sandbox HOME; packages at 7edf5b0a3, then rebased on f35c721c4,
where the build, Windows build, Linux vet and the classifier, StandIn,
tier and Follow tests ran again: ok):
- TestAutoModeClassifierFollowsTheSwitchedModel (gateway) and
  TestClaudeClassifierFollowsTheSwitchedModel (agent): pass.
- go test -tags nogui -timeout 45m ./internal/agent ./internal/gateway
  ./internal/cli: ok (agent 787s, gateway 1191s, cli 129s, load ~450).
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet on the three packages; go build, GOOS=linux -tags nogui,
  GOOS=windows: ok.

Broken by hand, each red then restored:
- classifierStandIn never rerouting: gateway test red ("went to m1").
- claudeClassifierIn returning "": agent test red at line 56.
- without the own-sonnet-tier check: red at line 84.
- without the CLAUDE_CODE_AUTO_MODE_MODEL check: red at line 67.

Not tried: real Claude Code doing a /model switch against this build. A
full ./... suite didn't run either: another session's full suite held the
machine, with several more queued behind it.
2026-10-24 19:47:12 +08:00
yetone e698a688fd gui: Insights › Masking shows each request as sent, what was masked and how
What masking did moves out of Settings › Privacy into a page of its own
under Insights (plugins/redact: client.js, page.js, redact.css, i18n.js).
Privacy keeps how it is found and what to mask, with a "What was masked"
row that opens the page.

- The top card is Privacy's card, made shorter: the flow animation
  (agents → this computer → providers) with magpie's bird on the centre
  line and "magpie masks it on this computer" under it, so a screenshot
  says who masked it; the count and a 7-day bar. Nothing the list repeats.
- The list: one row per masked request, narrowed by kind, by who found it
  (rules or the local model), by agent or provider, or to held-back
  requests; or by value, each with how often it was put back.
- A request: the message as it went to the vendor beside the original,
  each mask marked, unchanged parts folded; picking a value lights every
  place it was masked; a held-back request offers "Mask it instead".
- Gateway's masked badge and ?view=masking&key=N (trace.go's mainView)
  open one request.
- Classes are msk-: library.css owns mk- (a first cut stacked the flow).
- Budgets lowered to the core's size after the move.
- Not shown: rule names and the local model's confidence; the records
  don't keep them.

Run on f5b1d36ff (rebased since onto 344d11484, which only raised the
budgets and changed a dialog's centring and two unrelated files):
- masking-records.test.cjs: 32/32, Chromium and WebKit, 5 languages,
  1100px and 640px (card, list, filters, detail, put back, held back,
  Gateway badge, deep link, Settings row, no scroll on click), with
  key-import and i18n-keys: 48/48.
- go test ./internal/maskrec ./internal/redact ./plugins/redact
  ./internal/gui ./internal/provider: ok. TestCoreScriptBudget and
  TestMainView ok; gofmt -l clean.
- Before the rebase, on 628e18987: go test ./... -timeout 45m, every
  package ok; GOOS=linux go vet -tags nogui ./... and GOOS=windows go
  vet ./... clean.
- Budgets lowered to the sizes at the pushed head (app.js 1,317,486,
  core 1,524,789), ~26KB under what f35c721c4 raised them to after
  ce5b23cdb's add-key spinner put the core over.

Broken by hand: the bird's href (#bird → #nobird) turns masking-records
red.

Not run at this head when pushed: internal/gateway, which main's newer
commits touched (run right after; the result goes on the release).
Not tried: the whole GUI suite (hours long, and another session's runs
held the machine), the real Linux (WebKitGTK) and Windows apps.
2026-10-24 19:45:03 +08:00
yetone 51667a34c6 maskrec: records narrow by several kinds, by who found them, and to held-back requests
The Masking page's facets ask for a set of kinds (Secrets is API keys,
passwords, private keys...), for what found the values (rules or the
local model), and for the requests held back. Filter.Kind takes a comma
list, Filter.By and Filter.Blocked are new, and /api/masking/records
passes by= and blocked=1 through.

Run: go test ./internal/maskrec ./internal/gui -run 'Filter|Records|Masking|MainView|ShowMain' ok.
2026-10-24 19:41:03 +08:00
yetone 9b57261b62 masking: a record keeps its request as sent, how long masking took and what the answer put back
For the 观测 › 脱敏 page's request view. In memory only: the masked body
of the latest 100 requests (each up to 4MB, 64MB in all), and by
placeholder how many places of the answer had the value put back
(redact.Writer.Put, counted once per place even when a stream splits
the placeholder). Took (µs) is written to disk too; it holds nothing of
the request.

GET /api/masking/sent?key= gives the body, POST /api/masking/values the
values the masker still remembers, both no-store.

Run: go test ./internal/maskrec ./internal/redact ./internal/gui
-run TestMaskingRecordsAPI and ./internal/gateway -run TestMasked; ok.
Broken by hand: without toldBack, TestMaskedRecordKeepsSentAndBack is red.
2026-10-24 19:41:02 +08:00
yetone 344d11484e provider: Remove takes the account listed, by its slot, not a hidden one of the same name
dev (Discord) couldn't remove a ZCode account. The ZCode app's own
account had been removed in magpie (hidden), and a second one signed in
through magpie had the same name. Two things in the source caused it:

- editSideLogin matched the first saved entry by agent and name, hidden
  ones included, so Forget took the hidden "zcode" slot. It signed out
  the ZCode app's own account and left the listed zcode#l47q19 one.
- pluginLogins applied the own account's name (pluginOwnUser) after
  pluginLabels had added the slot suffix to tell same-name accounts
  apart, so both read "dev@z".

Now:
- pluginLabels applies the own names first and adds the suffix after,
  so the listed names are unique ("dev@z (l47q19)").
- Forget, Switch and On/Off resolve the name against the accounts as
  listed, then edit that saved entry by its slot (Home) or own-ness
  (listedMatch/sameSaved). editSideLogin, which the other callers use
  (chatgpt_api, copilot_lapsed, google, signin_revoked), prefers a shown
  entry over a hidden one of the same name.
- A saved id doesn't help here: it is made from the name, so both
  accounts had the same id (66dbee89c5d33fcd).

Existing data: an account whose name collided with another one is shown
with its slot suffix from the next read on. Nothing is rewritten.

Run:
- go test -tags nogui -timeout 45m ./... in a sandbox HOME: ok, every
  package, at 7edf5b0a3 plus this change.
- gofmt -l is clean; go vet ./..., GOOS=linux go vet -tags nogui ./...
  and GOOS=windows go vet ./... pass; go build for darwin, linux (nogui)
  and windows pass.
- Sandbox repro with real binaries built from origin/main and from this
  change, a sandbox HOME seeded with dev's layout (the hidden zcode slot
  and zcode#l47q19, both dev@z), and the real Bun plugin host, using
  `magpie accounts zcode` and `magpie accounts forget zcode <name>`:
  - old: listed as "dev@z", and forget left plugin-auth with only
    zcode#l47q19 (the wrong one signed out);
  - new: listed as "dev@z (l47q19)", and forget left plugin-auth with
    only zcode and logins.json with the hidden zcode entry.

Broken by hand: the three new tests in same_name_login_test.go fail on
the old code:
- TestRemoveListedAccountLeavesHiddenNamesake: "the account removed is
  still signed in", "the hidden ZCode app's account was signed out in
  its place";
- TestPluginOwnNameKeepsSlotApart: "accounts *dev@z (own),dev@z";
- TestForgetSideLoginTakesTheListedOne: "left [own hidden, magpie's]".

Not tried:
- a real ZCode account;
- clicking Remove in the GUI. The GUI sends {agent, user} as before,
  and the server now resolves it by slot;
- Copilot and Google. Their lists carry no saved entry, so they get the
  prefer-shown fallback only.
2026-10-24 19:40:14 +08:00
yetone f35c721c48 gui: a dialog stays centred while its content comes in, until it is pressed
The owner (10-24): a plugin's page opened low, not in the middle. It
opens short, with a skeleton, and its README comes after; holdModal held
the top the skeleton had put it at, so the dialog grew down to the
window's foot and sat low.

Until the reader's first press or key in it, holdModal now keeps the
dialog centred over what it holds, measured by its layout height
(content that comes during the open's morph was read under its scale).
From the first pointerdown or keydown it holds its place as before, so
what is under the pointer doesn't move.

Run (darwin, chromium and webkit, logs kept whole):
- modal-centred-late (new): 6/6 ok, 3 runs in a row; on the old app.js
  red at "centred after the README came" (bottom gap 0, top 181.5).
- The 112 GUI files that use #modal: started, not finished at the push;
  the owner asked to release without waiting. Reds it finds get their
  own commits.
TestCoreScriptBudget: main was already 208 bytes over the core budget
(f5b1d36ff's refresh and ce5b23cdb's spinner, each checked alone); with
this change's ~1.1KB both budgets are raised to the exact sizes, with no
room added. go test ./internal/gui -run Budget: ok.
Not tried: the real Wails app; Windows and Linux webviews.
2026-10-24 19:34:34 +08:00
yetone c819e00c4e routing: a ClinePass route reads as its route, with what was asked for (zRain)
zRain (Discord #feedback, 10-24; magpie 0.1.1377, Windows, Codex CLI
0.164.0) asked clinepass/cline-pass/deepseek-v4.1-flash-1017 from Codex
(/backend-api/codex/responses -> /v1/chat/completions, 200). The reply
named vmc/deepseek-v4p1-flash-1017-contributor-fallbacks. Routing showed
"served vmc/..." titled "likely another model", with no upstream.

What was found:
- The pin goes out on Codex's Responses path the same as on a Chat
  client's. The test below checks the sent body on both paths. The
  built-in ClinePass pins only with "DeepSeek and GLM models only from
  their makers' own APIs" ticked. The Cline plugin pins Pass DeepSeek by
  default. zRain's id is the built-in, so with the tick off nothing asked
  for DeepSeek.
- upstreamOf reads finalProvider from choices[].delta/message
  provider_metadata on every path (Codex streamed, chat streamed,
  Responses streamed and not). zRain's rows had none, so the reply most
  likely carried none there. canonicalSlug is not recorded; left alone.
- The contributor-fallbacks name is ClinePass's own route. Its name does
  not mean another model.

Change:
- provider.ClinePassAsked: the upstream a request asks the Cline API for
  (ClinePin with the tick, or deepseek on the plugin's provider).
- Try.Pin records it on the answering try.
- Routing: a cline-pass/ model served as vmc/... is tagged "ClinePass
  route ...". Its title and story say it is the route's name, not another
  model's, and then one of:
  - who answered, when the reply said;
  - that the asked provider wasn't confirmed;
  - that nothing was asked, naming the tick for DeepSeek/GLM.
- The Usage page's Requests title says the route too, without the pin it
  doesn't keep.
- Strings in zh, zh-TW, ja and de.

What was run (rebased on origin/main 7edf5b0a3):
- TestClinePassAsked (provider) and TestClinePassTryKeepsWhatWasAsked
  (gateway: chat and responses, tick on/off, sent body and try pin).
- Broken by hand: the try literal without Pin, and the tick-on cases go
  red ("try pin \"\" (want \"deepseek\")").
- go test -count=1 ./internal/provider in a sandbox HOME: ok (280s).
- ./internal/gateway -run 'Cline|Upstream|Swap|Served|Try|Trace|Route':
  ok.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows on gateway
  and provider.
- go test -run 'Budget|I18n|Strings|Plugin' ./internal/gui: ok.
- GUI: routing-cline-route.test.cjs, new, Chromium+WebKit, en+zh, every
  string in all 4 languages. Pointed at the old assets
  (MAGPIE_ROUTE_ASSETS): 4 of 4 red. Now 4 of 4 green.
- GUI: every routing-*, usage-* and gui-* file, plus i18n-keys,
  panel-routing, remote-group-served and session-identity, at
  concurrency 3, load ~110. Reds: routing-held-dot (WebKit zh 560px,
  timeout; passes alone at the rebased head) and routing-intent-entry
  "Add a rule makes a rule by intent" (also red on origin/main 117937b8d
  in WebKit alone: #3408).

Not tried:
- No real ClinePass account. The raw bytes of a contributor-fallbacks
  reply are unseen, so whether ClinePass puts finalProvider elsewhere for
  that route is unknown. No parser change was made without them.
- Full go test ./... was not run: the machine is at load ~110 with other
  sessions' suites.
- Not run on the Windows box.
2026-10-24 19:21:02 +08:00
yetone f5b1d36ffa usage: a card's refresh opens after its "Refreshed just now", so the text never moves
The owner: on hovering a usage card, the refresh icon appearing pushed
"刚刚刷新" right each time. The icon opened from width 0 in front of the
text, so the text moved by the icon's width on every hover.

The refresh button now comes after the text in every place quotaRefresh
is put (the read-when line, a panel row's name, the panel's error line,
both panel sub lines, and a failed window's line after its fix button),
and opens rightward into the card's padding: open, it is 14px with a
-2px right margin, so the text before it stays where it was. A panel
row's name ellipsizes rather than being pushed.

Run (darwin, chromium and webkit, logs kept whole):
- usage-card-refresh, panel-quota-refresh, quota-curve,
  quota-balance-error, usage-remote-key-limits, usage-remote-cards:
  144/144 ok
- quota-refresh-order, usage-refresh, i18n-keys: 17/17 ok
usage-card-refresh's hover check now asserts the text's rects don't
move when the icon opens and that the icon sits after the last of them;
on the old code it fails at the text moving.
Not tried: the real Wails app; the Windows and Linux webviews.
2026-10-24 19:19:24 +08:00
yetone ce5b23cdb4 gui: adding a key shows a spinner and Adding… until it is done; the name field is narrower
The owner, on the provider editor's add-key row: a key's Add (one key,
and Paste several's) only faded while the gateway checked the key with
its provider, which can take seconds, so nothing seemed to happen. It
now goes through saving(), the editor Save's spinner and "Adding…",
takes Enter once while it runs, and gives its label back when the key is
refused. The name field, only for telling keys apart, takes 1/3 of the
row instead of 2/5.

Run:
- key-import.test.cjs, new case: spinner, aria-busy and Adding… while
  keys/add is held, a second Enter posts nothing, a refusal puts Add
  back and keeps the row, the name field narrower than the key's.
  12/12, Chromium and WebKit, en and zh, at load 510.
- The GUI files on the key list, provider editor and accounts
  (key*, provider-*, account-*, zen-anon-key, gateway-own-key,
  api-key-usage, keep-login, lane-limit, i18n-keys) in both engines.
  Four reds at load ~190: the new case (a click over the file's 5s; the
  file now allows 15s) and key-replace (420px, twice) and
  provider-advanced-fold, files this change doesn't touch; checked
  against origin/main after this push.
- go test ./internal/gui -run Budget ok.

Broken by hand: old app.js turns the new case red (Add, not Adding…);
old app.css too (name 180px beside a 269px key). An injected 3.5s delay
before the first post turned the case red through its 3s wait; it now
waits for the posts it expects.

Not tried: the real Linux and Windows apps, the whole GUI suite.
2026-10-24 19:11:47 +08:00
yetone 48194bbee0 routing: an In order group's later members aren't said to go after a known allowance (bitssly on X)
bitssly on X (10-24) asked why, with a group set 按顺序 (In order), an
account whose quota isn't known "can't be used", quoting the Routing
page: "opencode:剩余额度未知,排在已知的之后。" and "腾讯-国际:剩余额度未知,
排在已知的之后。"

Cause: the gateway does what the mode says. planGroup/planLevel try an
In order group's members in the order given and never by what each has
left; each member's own accounts go as that member's provider routes
them (Smart by default, where an unknown allowance still comes before
any account at 90% or more and is tried when the known ones fail). The
explanation was wrong. weighed() gives an ordered group's rows their
member's routing (""), so the page's smart() judged each row against
every known row of the whole request: an In order group's later
members read as ranked behind a known allowance, and the first got a
Smart reason ("its allowance renews soonest ...") instead of In order.
A By weight group's first had the same fault.

Change:
- client.js: placeRouting/wholeMembers/weighedWith scope what a row is
  weighed against to its own member when the level that placed it takes
  members whole (order, weight). firstWhy says "In order: {who} is
  first ..." for such a group, and "By weight: it's {who}'s share ..."
  for a weighted one; the unknown, learns, spent and low asides are said
  only of an account weighed against another of its own member. Rebased
  onto 6d707af08 (Creat.wu, memberSplit): its member line now asks the
  scoped someKnown(x), so an unknown account alone in its member gets no
  line at all, and one beside a known account of its own member gets
  6d707af08's one line for the member.
- i18n.js: the By weight line in zh, zh-TW, ja, de.
- routing-order-unknown.test.cjs: In order, Smart and By weight groups
  over Codex (known), OpenCode Zen Free "opencode" (unknown) and two
  WorkBuddy AI accounts (one known, "腾讯-国际" unknown); chromium and
  webkit, en/zh/zh-TW/ja/de, 1100 and 420 wide.
- docs/reference.md: Smart's unknown account is still tried when the
  known ones fail; an In order group keeps its order whatever is known.

Why the quotas are unknown: OpenCode Zen Free is a free tier with no
allowance to report. Tencent Cloud Token Plan and Volcengine access-key
plans are read for the Usage page but not for routing; that class is
#3251. No plugin change.

Run:
- old client.js with the new test: red on the why line (chromium en/zh
  1100: "c@x.test goes first: of those with quota to spare, its allowance
  renews soonest ..." where "In order: c@x.test is first ..." was due).
- at the rebased head (origin/main 1f8f80e4a plus this):
  routing-order-unknown, routing-weight-member-low and i18n-* 64/64.
- go test -timeout 45m ./internal/gui/... at the rebased head: ok but
  TestMainWindowCorners (killed measuring windows at load ~80; red alone
  too; #1936, #2645, AppKit, not this change). Before the rebase: ok
  (112s).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean. No Go file changed, so gofmt has nothing to check.
- whole GUI suite at ab287a839 (before the rebase), concurrency 4, load
  50 to 80: files a* to roughly o* ran; reds, all outside routing and
  filed: api-key-theme chromium system (#3307, also 1 of 3 alone),
  fonts webkit narrow (#3227), library-mcp-health-wsl ja (#3350),
  menu-input-scroll chromium en/zh (#3402). The rest of that run is void:
  my own rebase put conflict markers in client.js mid-run. The files from
  n* on are run again at the pushed head after this push.

Broken by hand: someKnown made global again (the old aside scoping):
red, the opencode aside is back under the In order group.

Not tried: the reporter's own trace and accounts (not shared); a Go
test for the gateway's order (unchanged here, covered by the existing
fallback tests); routing reading the access-key plans (#3251).
2026-10-24 19:09:41 +08:00
yetone 117937b8d9 sessions: every agent in the Agent menu and in Continue in shows its icon
The Sessions page's agent picker showed the chosen agent's icon on its
button, but the menu it opened listed bare names. Each item now carries
its icon between the tick and the name, level with the name; the
"Continue in another agent" menu does the same. The icons are drawn by
the sessions plugin after the menu opens, so the core scripts stay
within TestCoreScriptBudget (a first try in openProtoMenu went 116
bytes over).

Run: sessions-toolbar and sessions-talk GUI tests, chromium and webkit,
en and zh, light and dark: 8 pass. Broken by hand (no icons drawn):
sessions-toolbar red in chromium, "every agent in the menu has its
icon". go test ./internal/gui/ -run 'TestCoreScriptBudget|Plugin' ok.
Looked at the webkit zh dark menu screenshot.
Not run: the whole GUI suite (load ~380 on this machine).
2026-10-24 19:02:50 +08:00
yetone 7edf5b0a3d gui: the context window is a map of tiles by default, the block grid a switch away
After flohoeller's "Context map" on X. The Context window card (Usage ›
Context, and Routing's request card) drew its window as 400 cells. It now
draws it as a map:
- Each item is a tile sized by its tokens, inside its part's area
  (squarified, parts in their usual order).
- The tile has a soft fill of its part's colour, its name, and
  "tokens · part".
- The free space is a hatched tile that names its share.
- The used share is drawn on a gentle curve (share^0.35), so a window
  8% full still has tiles to read. The free tile states the real share.

Small items:
- Items too small to read go in one "{n} more" tile.
- A part whose items would leave a strip thinner than 14px is one tile.
- No tile is laid under 700px².

Hover and click:
- A hovered tile tells its item, part, tokens and share (a part's tile
  lists its largest five) and dims the others.
- A row or the legend lights its tiles.
- A clicked tile opens its text, as a cell does.

Motion:
- Tiles come in with a short stagger (opacity, scale .94, blur), over
  560ms with the iOS ease.
- A live update keeps the same nodes and glides them to their new rects.
- Tiles that are gone fade out.
- With motion reduced, or on a still pane, nothing moves.

The block grid is kept. A small segmented switch at the end of the legend
(Context map / Block grid) picks the look for every card, remembered in
localStorage magpie.ctxLook. The card eases to the other look's height.
The new look is the default, and the old one stays one click away (UI
restraint, owner's ask).

The text view shows an image the request sent inline (the gateway's Src,
previous commit), where it said "An image: magpie doesn't show it here".
It fades in, and a click opens it larger with a FLIP scale. An image with
no Src, or one that fails to load, keeps the old note.

Words: "Context map" and "Block grid" in zh, zh-TW, ja and de.

The core budget goes to 1,549,478, the new size with no room added:
context.js is drawn by the Routing page as well as Usage, so it is the
core's own (+14.4KB).

Tests:
- Seven existing tests read the grid's cells. They now pin
  magpie.ctxLook=grid.
- New context-map.test.cjs, in both engines, en/zh/zh-TW/ja/de, at
  1100 and 420px:
  - The map is the default, with a free tile.
  - Every tile is inside the map, none overlap, and none is a sliver.
  - Hover gives the tip and dims the others.
  - A refresh keeps the nodes.
  - A click opens the text.
  - An inline image loads (naturalWidth 2) and opens larger. One without
    Src is named.
  - The switch to the grid survives a reload, and the map comes back.
  - With motion reduced, nothing animates.

Run at this head (rebased on 1f8f80e4a):
- context-map, i18n-keys, context-window, context-text, held-animations,
  routing-live-patch, routing-ctx-fold, routing-ctx-still and
  routing-context-fold, Chromium and WebKit: 130 pass, 0 fail.
- go test ./internal/gui/: ok (TestCoreScriptBudget at the new budget).
- gofmt -l internal/: nothing. go vet: ok, with GOOS=linux -tags nogui and
  GOOS=windows.

Broken by hand, each red in context-map.test.cjs (restored after each):
- pieceView never showing the picture.
- The grid as the default.
- The thin-strip rule removed ("two tiles overlap").
- drawMap ignoring calm() (the reduced-motion test).

Looked at: screenshots in light and dark at 1100 and 420px, at 8% and 90%
full.

Not run: the whole GUI suite (it runs after the push), and the real Linux
app (WebKitGTK).
2026-10-24 18:40:01 +08:00
yetone 069bf0583b gateway: a prompt's inline image comes to the text view as a picture it can show
The Context window's text view said "An image: magpie doesn't show it here"
for every image a request carried. The gateway now reads the image's
source as the request sent it (Anthropic's base64 source, a Responses
input_image's image_url, a Chat image_url, Gemini's inlineData) into
PromptPiece.Src, from the same masked bodies kept in memory as the text.

Only a data: URL of PNG, JPEG, GIF or WebP whose payload is base64 is
given: a remote URL (Gemini fileData, an http image_url) or anything else
(svg, a data URL with markup in it) stays "", so the view never fetches
from anywhere and never renders markup. Src is read out only when the
text is asked for (read()), like the text itself.

Run:
- go test ./internal/gateway/ -run PromptText: ok.
  TestPromptTextImagesArePictures sends each protocol's image and checks
  its Src, and that a URL source, an svg, a data URL with <script> and
  Gemini's fileData come back "".
- Broken by hand: read() setting pc.Src = "" turns the test red; restored,
  green.
- gofmt -l internal/: nothing. go vet ./internal/gateway/,
  GOOS=linux and GOOS=windows: ok.
Not tried: a real Claude Code or Codex session's image through a live
gateway (the GUI side is covered by context-map.test.cjs with a fixture).
2026-10-24 18:29:53 +08:00
yetone 1f8f80e4af provider: Kiro's mover min is 0.1.16 (cache unknown, not 0)
opencode-kiro-auth 0.1.16 (plugins 9f6c4e8) says magpie_cache_unknown
when Kiro gives no token counts. Before, it reported cache_read 0, which
the Routing page showed as 0% (zeewell on X). keepMovedCurrent brings
every moved Kiro user up to it.

`npm view @magpie-community/opencode-kiro-auth version --prefer-online`
gives 0.1.16 at landing. Its publish run is red only on the known
think-tags E404 (plugins#180); the run's log has
"+ @magpie-community/opencode-kiro-auth@0.1.16".

Run at this head (origin/main 628e18987 + the routing commit): gofmt and go vet (darwin, linux, windows) clean;
go test -timeout 45m ./internal/provider ./internal/gateway: ok, ok.
2026-10-24 18:16:17 +08:00
yetone 436bcc946d routing: a request whose vendor counts no cache tokens shows no hit rate, not 0% (zeewell on X)
zeewell on X: every Kiro request in a routing group showed cache 0%, for
claude-sonnet-5.5 and claude-opus-5.5 from Claude Code, with 148k to
182k tokens and consecutive calls.

The cause, from real Kiro calls on the owner's account (read-only, from
a sandbox): Kiro does cache. A repeated 900-line prefix cost 0.0912
credits and then 0.0484, with or without cachePoints, and with a fixed
conversationId too. But Kiro's reply holds only assistantResponseEvent,
metadataEvent {stopReason}, contextUsageEvent (a percent) and
meteringEvent (credits). There are no token counts at all, and
kiro-cli 2.32's own trace shows the same. The plugin wrote
cache_read_input_tokens: 0, which magpie showed as 0%.

opencode-kiro-auth 0.1.16 (plugins 9f6c4e8) now leaves the cache fields
out and says `magpie_cache_unknown: true`. This commit reads that field:
- aUsage reads it into Usage.cacheUnknown, ORed in Usage.add.
- routeUsage sets RouteUsage.CacheUnknown (cache_unknown, omitempty) on
  a try that counted no cache read or write.
- The Routing page's promptOf leaves such a try out of the hit rate. The
  row and its session then show no Cache metric, as for older history.

Clients are never told the field. Usage.anthropic() leaves it out, and
a passthrough forwards the plugin's bytes as they came. The gateway
already relays cache_control to an Anthropic-protocol plugin as Claude
Code sent it, so nothing was lost on the way to Kiro.

Left alone: the usage ledger. usage.Record has no such flag, so the
Usage page's aggregate hit rate still counts a Kiro prompt as a miss.
Filed as #3464.

Run at this head (rebased on origin/main 628e18987):
- gofmt -l internal/gateway internal/provider: clean.
- go vet ./internal/gateway ./internal/provider: clean on darwin, with
  GOOS=linux and with GOOS=windows.
- go test -timeout 45m ./internal/gateway ./internal/provider: ok, ok
  (465s, 126s).
- go test ./internal/gui -run Budget: ok.
- GUI: routing-request-metrics.test.cjs, chromium and webkit, en and zh:
  4 of 4 pass.
- Every routing-*.test.cjs, one base back, at load 130 to 150: the only
  reds were routing-intent-entry, routing-keys-fold and routing-manual.
  Run alone, those three files also go red on a fresh origin/main
  628e18987 worktree (8 reds there, 5 on this branch). They are already
  filed: #3408, #1612 and #3409. This change touches only promptOf's
  cache_unknown rows, which none of their fixtures have.

Broken by hand:
- With aUsage.usage() not carrying the field, TestCacheUnknownReachesTheRoute
  fails in its four Kiro cases (Claude Code whole and streamed, translated
  whole and streamed). The counted-miss case still passes, at 0%.
- With promptOf's skip removed, the GUI test fails in chromium for en and
  zh: "a vendor that counts no cache tokens has no hit rate, not 0%".

The test fixtures are the plugin's real reply bytes from Kiro, captured
10-24.

Not tried: a magpie build running the 0.1.16 plugin against Kiro from the
GUI. The plugin's own end-to-end run against Kiro gave
{"input_tokens":0,"output_tokens":19,"magpie_cache_unknown":true}.
2026-10-24 18:16:17 +08:00
yetone 628e18987b gui: Settings › Privacy puts the local model first, marked New
The owner asked for "Find with a local model" to come earlier on
Settings › Privacy, where people see it at once, with a light mark.

"How it's found" (#findList) moves from below the try box to right
under the masking card, before "What to mask", and its first row is
the local model, then Rules. The model's name carries a small accent
"New" badge (.badge.new: accent-soft background, accent text; en New,
zh/zh-TW 新, ja 新着, de Neu). app.js stays inside its budget with no
raise (1,343,322 of 1,343,324): comments were trimmed to fit.

Tests: privacy-model checks the badge in every language, that the
model's row is the page's first settings row, and that #findList comes
before #redactList. redact-rule-row and redact-words-any-case wheel
their row into view first (wheelTo, reach): with the section above
them, at 640px their row sat under the bar along the page's foot, and
the second control under the sticky tabs in WebKit.

Run at 35c648593 (on 616c87256), both engines:
- go test ./internal/gui: ok
- GUI: account-discovery, account-mask-sessions, account-mask,
  click-scroll, i18n-keys, mask-actions, mask-emails, masking-records,
  privacy-hides-accounts, privacy-model, privacy-usage-stats,
  provider-unmasked, redact-kinds, redact-rule-edit, redact-rule-row,
  redact-words-any-case, settings-search, settings-sections,
  sidebar-glide, sidebar-overlay-scrollbar, sidebar-tab-top, sidebar:
  all pass
- Screenshots in zh, light and dark, 1100 and 640, Chromium and WebKit.
Rebased on ef37b6fb7: go test
./internal/gui -run 'Budget|I18n|Key', i18n-keys, privacy-model and
redact-rule-row pass again (and redact-words-any-case).
Broken by hand: with the old index.html order, privacy-model is 11 of
12 red in Chromium.
Not tried: the real Linux and Windows apps, the whole GUI suite.
2026-10-24 17:50:20 +08:00
yetone 56b90893f7 provider: Command Code's mover asks for commandcode 0.1.16 and Qoder's for qoder 0.2.33, so no request names magpie (plugins #352, #354)
commandcode 0.1.16 sends the Go catalog with Node fetch's own User-Agent
and /alpha/generate with the working folder's slug, as command-code
1.88.0 does, where both said "magpie". qoder 0.2.33 names a task with
the prompt's first ten characters, as Qoder.app 0.4.3 does, not "magpie
session". keepMovedCurrent brings every moved user up to them.

Both versions checked with npm view --prefer-online at landing:
opencode-commandcode-auth 0.1.16, opencode-qoder-auth 0.2.33.

Run at this tree (base origin/main ef37b6fb7):
- gofmt -l internal/provider/: nothing
- GOOS=darwin|linux|windows go vet ./internal/provider/: ok
- go test -timeout 45m ./internal/provider/: ok (106s), log kept whole

Live (in the plugins repo, sandbox HOME): commandcode against the owner's
GOAT key and qoder against the owner's Qoder account, 0 recorded
requests naming magpie.
2026-10-24 17:47:21 +08:00