Commit Graph
1067 Commits
Author SHA1 Message Date
yetone 3fd7e16983 agent: PenguinHarness is installed from the Agents page and served by magpie with nothing to set up
rankyurky asked on Discord #feedback for PenguinHarness (npm
@prismshadow/penguin-cli, command penguin). Every value comes from
Penguin's own source (0.2.17):

- Config: $PENGUIN_HOME (else ~/.penguin/data, every OS) /
  $PENGUIN_PROJECT_ID (else default_project) /.project_config.toml.
  magpie writes [providers.magpie] (base_url, client_type, api_key),
  one [[models]] entry per magpie model (context_window, vision,
  max_tokens, [models.pricing] in usd_per_mtok) and default_model in
  Penguin's own inline spelling. Penguin's server reads the file again
  when its mtime changes, so no restart; a default naming no entry is
  refused by Penguin, so Check fails when one is missing.
- A file magpie creates is 0600 in a 0700 folder, as Penguin keeps it.
  Disconnect restores the user's own default_model (or none), drops a
  magpie vision model, and removes the file when magpie made it.
  Penguin's own entries, providers and command_policy rules are kept.
- A sync that changes nothing writes nothing (bytes and mtime kept), so
  Penguin's watcher isn't woken.
- Install: curl -fsSL https://penguin.ooo/install.sh | sh, or
  irm https://penguin.ooo/install.ps1 | iex on Windows; update: npm, or
  penguin update --yes for the tarball, except on Windows where
  update.ts refuses it.
- WSL: a penguin kind with no restart notice; the WSL test now expects
  an empty Notice for a kind with no restart.
- agentenv: PENGUIN_HOME, PENGUIN_PROJECT_ID; the project id is in
  NotPaths, or appdir dropped a value like "work" as a relative path.
- edit.SetTOMLArrayTables: replaces every [[name]] entry with key =
  value (with child tables) by blocks, or removes them; blank lines
  between replaced entries go with them, and an unchanged result isn't
  written.
- GUI: penguin-color.svg icon; README (en, zh-CN), docs/reference.md
  and docs/subsystems/agent-wiring.md.

Run (worktree at ca9b5048e, GOMODCACHE/GOCACHE pinned):
- go test -tags nogui -timeout 45m ./internal/agent ./internal/edit
  ./internal/agentenv ./internal/appdir ./internal/usage: all ok but
  TestWSLMoreAgentsPick (penguin has no restart notice), fixed in the
  test; rerun -run 'TestWSL|TestPenguin|TestEveryAgent|TestFolderVars|
  TestEveryNotice' ok.
- internal/gui: TestCoreScriptBudget, TestAssetTypesHoldAgainstTheRegistry,
  icon and i18n guards ok; no budget raised.
- GUI Playwright, chromium and webkit: i18n-keys, getting-started,
  agent-cli-missing, agent-update-all, gui-ja, gui-de, gui-zh-tw:
  123 tests, 123 pass. The icon renders in colour in both engines.
- gofmt -l internal/ clean; go vet -tags nogui ./... with GOOS linux,
  windows and darwin clean.
- Real Penguin 0.2.17 (npm, Node 25) in a sandbox HOME against a sandbox
  magpie serve and a fake upstream: penguin run -m "Say PONG" answered
  "PONG from fake" through magpie (usage agent "penguin",
  /v1/responses -> /v1/chat/completions); switching the model in magpie
  took effect with no Penguin restart; a no-op sync kept bytes and
  mtime; magpie penguin default restored the user's custom/my-own and
  left no magpie line; with no prior file it was created 0600 and
  removed on disconnect. The fixture is the file Penguin itself wrote.

- Rebased on origin/main d9a8148d7 and run again there: internal/agent -run
  'TestPenguin|TestWSL|TestEveryAgent|TestFolderVars|TestEveryNotice|
  TestSync', internal/edit, internal/agentenv and the internal/gui
  guards ok; gofmt clean.

Broken by hand, each went red: the no-op skip (mtime test), the 0600
create, the inline default_model spelling, the own-default restore,
removing magpie's file, dropping the vision model, the NotPaths entry,
and both SetTOMLArrayTables fixes (blank-line growth, unchanged write).

Not tried: the full ./... suite (machine load ~190-200, as asked); a
Windows or WSL real binary; Penguin's desktop app; a real vendor key
through Penguin. Penguin sends the openai SDK's User-Agent, so the
agent is named from its key, not its UA.
2026-10-27 01:38:45 +08:00
yetone d9a8148d7c routing: Speed first sends a request to the provider or key that answered the model fastest lately
joeliu96872540 on X: when one model is reachable through several API
channels, they want an option that sends each request to whichever has
been answering fastest, because they compare channel speeds by hand
today. Speed first (`fast`; `fastest` and `speed` also work) is a new
routing beside Free first. It applies to a provider's keys and accounts
(provider editor › Routing) and to a group of one model on several
providers (Routing page › group › Routing).

How it decides. When a streamed answer ends, gateway/speed.go records two
numbers for that account or key and model (restID): the time to first
token and the output tokens per second, as usage.DecodeOf computes them
for the Requests page. Each is a decayed average with a 20m half-life.
After an hour with no answer the record goes stale, and the store holds
at most 4096 records. This is O(1) at the answer choke point, beside
servedCandidate. For a pool routed by BySpeed, weighRouted reads one map
entry per candidate, and only for that pool. The usage history is never
read on a request.

routes.Fastest ranks each awake seat by its estimated time to a
200-token reply: TTFT + 200/TPS. A seat that reported no TPS gets the
median TPS of the others. Seats within 10% of the fastest in their band
keep their listed order, so near-ties don't swap on every request.
Seats with no recent measurement go after the measured ones. One request
in five, counted per pool, goes first to an unmeasured seat, rotating
among them, so each gets measured again. Resting seats go behind the
awake ones, and used-up seats behind those. Rests and failover are the
same as for every other routing.

The request trace gets lateTtft and lateTps, and the row-story sentence
says "answered m fastest lately: first token in 0.8s, 60 tokens a
second". It has a variant for a probe turn and one for when no seat has
been measured yet. i18n covers zh, zh-TW, ja and de. Also updated: the
CLI (`magpie group|provider set <id> routing=fast`, plus a new
`routing=` pair on provider set that refuses manual), the TUI name, the
rotation plugin's Sub, docs/subsystems/gateway-routing.md,
plugin-runtime.md, docs/reference.md and site start.html (en, zh, ja).
There is no new layout: it is one more item in the existing pickers.
app.js stays under its budget with no raise.

Tests:
- routes/fastest_test.go:
  - ordering: fastest first, slow writer loses, alike keep order,
    resting and used-up, median pace, none measured;
  - the probe turn at 5, 10, 15 and 20, rotating between seats;
  - a resting seat never gets a probe turn.
- gateway/speed_test.go:
  - decay, staleness and per-model records, with an injected clock;
  - a group of slowv and fastv routed fast: after the speeds are
    measured and seeded, the request goes to fastv with lateTtft set;
  - the same group routed in order still goes to slowv.
- cli: parseRouting and the provider routing= pair.
- GUI routing-speed-first.test.cjs: the row story for measured,
  no-pace, probe and none, in en, zh, zh-TW, ja and de, in chromium and
  webkit: 40/40.

Broken by hand:
- Fastest returning the listed order: the routes tests and the gateway
  group test go red.
- noteTrySpeed removed: "the streamed answer wasn't measured".
- The client.js case renamed: routing-speed-first 0/20 in chromium.

Run at b5a5caff2 (base 5b4dec58e):
- `go test ./... -count=1 -timeout 45m`, alone on the machine, at load
  130-230. Every package is ok except:
  - internal/provider: TestUnreadLoginsWriteErrorsKeepCredentials
    crashes with "close of synctest channel from outside bubble"
    (#3632, open);
  - internal/gui: TestMainWindowCorners and
    TestTrayCellClickReleasedPanel are killed at their deadline under
    load (#1936, #2645).
- gofmt -l is empty. go vet is ok on darwin, on GOOS=linux with -tags
  nogui, and on GOOS=windows for ./internal/....
- GUI files the change reaches, both engines, every language they test,
  all ok: i18n-keys, gui-de, gui-ja, gui-zh-tw, routing-save,
  routing-save-keeps-the-row, builtins, panel-routing,
  panel-routing-pick, panel-routing-providers, panel-routing-hidden,
  routing-key-windows, key-weight, key-weight-fit, group-member-weight,
  routing-weight-chip, account-arrange and routing-speed-first (40/40).
- routing-group-strategy was 4/18: the menu now has 9 items and the test
  still counted 8. Fixed in this commit; rerun, it is 18/18.
- routing-save-blank (a webkit click timeout) and routing-columns (zh
  "side by side") each failed one subtest at load ~200. Rerun alone,
  they are 4/4 each. Both are already filed (#1924, #1612).

Rebased on 8f023b511, where upstream changed gateway.go, app.js, client.js,
the routing plugin's i18n.js and gateway-routing.md; the rebase was clean.
At this head I reran gofmt, go build ./... and go vet (darwin, linux
nogui, windows) on routes, gateway and cli, and go test for routes, cli,
provider and gateway (the routing and speed tests) and for gui -run
Budget: all ok. The GUI files i18n-keys (4/4), routing-speed-first
(40/40) and routing-group-strategy (18/18) also passed.

Not tried:
- A real run against several channels of one model. Speeds come from
  real answers, so the first minutes after a start are in listed order
  plus probes.
- A non-streamed reply is not measured, a sub-millisecond TTFT is not
  counted, and a restart forgets every speed.
- The Windows runtime: only go vet ran for it.
2026-10-27 01:37:38 +08:00
yetone b5d17b26e0 gateway: Antigravity's 429 to Codex's GPT-5 prompt says why and rests nothing, on the web-search path too (Jodiezzzzzz on X)
From Codex, every call to antigravity/claude-opus-5-5 failed with
"exceeded retry limit, last status: 429" while dsh worked on the same
account. The call was an agent_created_thread, and the vendor said
"Resource has been exhausted (e.g. check quota)".

Cause: a Codex thread begun on a GPT-5.x model keeps "You are Codex, an
agent based on GPT-5..." as its first developer message after /model,
resume -m or a fork, and magpie lifts it into systemInstruction.
Antigravity answers that line with a fake 429, whatever quota is left,
as it does Claude Code's (#666). Codex also sends a web_search tool every
turn, so for an Antigravity model magpie serves search itself (translate
-> searchReply -> askTranslated), and that path passed the bare 429 back:
no hint, no 400, so Codex retried to its limit.

- antigravityTurnsCodexAway: the two Codex GPT-5 opening lines count as
  a turned-away prompt; antigravityHint picks the Codex hint for them.
- antigravityRound wraps the search path's ask, so its 429 and an
  in-stream refusal get the same 400, hint and no rest as translate's.
- antigravityForeseen returns the hint, so a group skips Antigravity for
  the next 6h saying which prompt.
- The Routing page shows the new hint (routing/client.js HINTS) in en,
  zh, zh-TW, ja and de.
- Rest: none. The refusal is about the prompt, not the account (Fail
  "prompt"); a second account answers the same.

Plugins: middleware-antigravity-cloak 0.1.1 (plugins a52d1b3) breaks
the two Codex lines with U+200B. Its body says "npm had 0.1.0": wrong,
the package is not on npm; dist had 0.1.0 and now has 0.1.1 (6fd1438).
No mover applies.

Real account (owner's Antigravity, sandbox HOME copy, gateway built from
this branch) and real Codex 0.162.1:
- codex exec resume <a gpt-5.5 thread> -m antigravity/gemini-3-flash:
  before, 429 retried to "exceeded retry limit"; after, one request and a
  400 with the Codex hint; route try (429, prompt), no rest.
- A new Codex chat on the same model: 200.
- The two lines with U+200B after the first letter: 200; whole: 400.

Broken by hand:
- antigravityTurnsCodexAway returning false: the Codex tests go red
  (Codex got 429; the group's skip doesn't say why).
- The antigravityRound wrap removed: the search=true subtests go red
  ("Codex got 429").

Run:
- go test -count=1 -timeout 45m ./internal/gateway/: ok (476s, at
  865df2472; main's next three commits touch only GUI files).
- go test -count=1 -timeout 45m ./internal/gui/: ok (230s, at the pushed tree on a6d7e02c7).
- gofmt -l: clean; go vet ./internal/gateway/ for darwin, linux, windows.
- GUI, chromium and webkit: routing-ag-turned-away, i18n-keys, gui-ja,
  gui-de, gui-zh-tw, routing-wb-refused, routing-blocked 41/41; at the
  pushed tree routing-ag-turned-away, i18n-keys, routing-steps-cap and routing-js 34/34.
- Rebased on b9ab17231 (routing client.js): routing-ag-turned-away,
  i18n-keys, routing-free-seat 45/46, the red webkit zh-TW `.rt-day`
  click timeout at load 163 (#3781's class); routing-ag-turned-away
  alone 20/20 after. go test -run 'Budget|I18n|Hint|Routing' on
  internal/gui and internal/gateway: ok.
- Rebased again on 68ee4117a (gateway: gemini_schema, unrouted,
  masking wait): gofmt, vet x3, and go test -run
  'Antigravity|CodeAssist|Search|Gemini|Unrouted|Masking|Translate|Continu'
  ./internal/gateway/ ok; the whole package was not run again at this
  tree.
- Under load 89-150: TestTrayCellClickReleasedPanel killed at 20s
  (#2645), routing-js webkit zh (#3774), panel-routing and
  routing-zcode-blocked webkit zh click timeouts (#3781). All pass alone.

Not tried: Claude Opus itself (the sandbox account's free-tier Claude
quota was spent while probing, so gemini-3-flash stood in; the prompt
check is model-blind); the cloak installed in a running magpie; the
Windows box; the full GUI suite.
2026-10-27 01:33:53 +08:00
yetone 68ee4117af gateway: a Gemini model's untyped tool schemas go typed (Vertex refused cua-driver's drag)
kthink on Discord: dsh with cua-driver's MCP tools on Command Code's
google/gemini-3.8-flash (the commandcode plugin), every request 400
INVALID_REQUEST from Vertex: "`mcp__cua-driver__drag` functionDeclaration
`parameters.target` schema didn't specify the schema type field."
cua-driver's drag schema before cua's #4888 has target as an anyOf of an
untyped oneOf and null, and scope a const with no type. Command Code's
gateway turns JSON Schema into Vertex's Schema object, whose type is
required, and an untyped node stays untyped.

geminiToolTypes (forwardOnce, so plugin requests too) is keyed on the
model id (last '/' segment starts with "gemini"), not the provider:
each untyped schema under tools' function.parameters / parameters /
input_schema gets the type its enum/const, keywords or branches say,
null left out; {} or a description alone is a string, a tool root an
object. Mixed-type unions, unresolved $ref/unions and anything under
not/if are left as they came. Written in place after the brace, so the
rest of the body is unchanged. withTypes no longer writes a trailing
comma into an empty {} (it produced invalid JSON there).
Google's own Gemini API / Code Assist (parametersJsonSchema) and
Antigravity (plainSchema) bodies have no such tools and are not walked.

Run at this tree, rebased on origin/main 8f023b511 (tests and vet run again there; GOMODCACHE/GOCACHE pinned):
- go test ./internal/gateway/ -run 'Gemini|Kimi|Grok|OneOf|PlainSchema|Tool|LoopGuard|Doc' -count=1: ok
- gofmt -l internal/gateway/: clean
- go vet ./internal/gateway/ (darwin), GOOS=linux go vet -tags nogui,
  GOOS=windows go vet: ok; go build ./... for darwin, linux (nogui), windows: ok
- Not run: the full ./... suite (machine load ~200, other sessions' suites).

Broken by hand:
- geminiToolTypes call commented out of forwardOnce:
  TestGeminiToolTypesCuaDriverDrag red on chat, messages and responses.
- emptyObjectAt check replaced by true: TestGeminiToolTypes red, invalid JSON.

Tests: TestGeminiToolTypesCuaDriverDrag uses cua-driver's literal old drag
schema (testdata/cua_driver_drag_untyped.json) through the server on
/v1/chat/completions, /v1/messages and /v1/responses; a GPT model on the
same provider gets the tools byte for byte. TestGeminiToolTypes covers the
type rules, and that claude/gpt/gemma/kimi ids get the body bytes.Equal.

Not tried: a real Command Code account or a real Vertex request; the
schema's acceptance by Vertex is from its documented Schema object and
cua's own Vertex lint (cua-driver-testkit vertex.rs), not a live call.
2026-10-27 01:28:39 +08:00
yetone 8f023b5119 pii: a long text goes to the masking model in overlapping pieces, a piece at a time, each kept (#3682)
A text over 12 KB was sent to pf-serve whole. On a weak GPU one such
text could take longer than classifyTimeout, so the request failed and
nothing was kept, and every other request waited behind it.

Now find.go cuts a long text into pieces of at most 12 KB (pieceSize).
Each piece overlaps the one before by up to 1 KB, cut after a line's
end where there is one, else after a space, else at a rune's start.
- Each piece is cached on its own, so a request stopped part way and
  sent again asks only about the pieces not done yet.
- Spans are shifted to the text's offsets and merged: overlapping
  spans become one with the longer one's label, and same-label spans
  that touch are joined.
- pf-serve gets one chunk per call. The turn is given up between
  chunks, so a short request waiting for the model goes next instead
  of after the whole long one.

Run:
- go test -count=1 ./internal/pii/: ok.
- gofmt -l and GOOS=linux/windows go vet ./internal/pii/: clean.
- go test -count=1 -timeout 45m ./internal/pii/... ./internal/gateway/...
  at f8b58fb48 (this change on origin/main 865df2472): pii ok 31s,
  gateway ok 571s. GOOS=linux/windows go vet of every package without
  Wails (88), and GOOS=windows go vet ./...: clean.
- Real model (pf-serve v2 Metal, q8 model from ~/.cache, M4 Pro) on a
  96 KB generated text with names, emails, phones and keys, sent whole
  and in its 9 pieces: 2208 spans either way, 2206 the same. 2 were
  found only whole and 2 only in pieces, none at a cut (model context,
  not the split). Pieces took 1.23s against 2.06s whole.

Broken by hand:
- No yield between pieces: TestShortRequestGoesBetweenPieces red.
- No cache put per piece: TestLongTextKeepsPiecesWhenStopped red.
- merge as a no-op: TestMergeAcrossPieces and
  TestLongTextFoundAcrossPieces red.
- pieceOverlap = 0: TestLongTextFoundAcrossPieces red (the name cut
  in two was not found).

Not tried: a real weak GPU (Vulkan) with a long text, and span quality
on a real PII corpus. The comparison above uses generated text.
2026-10-27 01:14:23 +08:00
yetone 16f6e568f4 gateway: masking's time no longer counts toward the 2 minutes before routing (#3682)
yunwang2442-creator: a 480 KB request the local masking model takes 90s
over on an RX 470/580 (more on its CPU, and more behind the requests
ahead of it in the model's one turn) was answered 504 at unroutedMost,
2 minutes from its arrival, its masking cut off, and the same again
each time it was sent.

unroutedMost now counts the request's time other than masking: a
masking (noteMasking), its wait for the model's turn with it, is
tracked like the known waits, and most's timer (checkMost) looks again
when the last masking ends, with what is left. unroutedUnknown is as
before.

Reconciled with 5a94eec3a, not taken as the report wrote it: the report
asked for unroutedMost to count only unknown waits. Next to the 30s
unknown bound that is dead code (unknown fires first), and a known wait
that hangs (a plugin's gateway hook, an image description never ending)
would be held for good, the heyusaku6 case. So only masking is left out.
Masking stays bounded inside internal/pii: classifyTimeout per request
to pf-serve, gpuLoadTimeout/loadTimeout per load, and a model that keeps
failing holds requests back at once (heldBack, retryAfter); a client
that leaves lets go of the turn's queue (FindContext).

The masking 504 message no longer says "what the model has already
read is kept, so it goes quicker": a request cut off mid-read had
nothing kept. It is reached now only by a masking begun as the rest of
the wait ran out.

TestHeldForTheMaskingModelSaysSo, which held a request at the model
past unroutedMost and expected the 504, is now
TestMaskingModelWaitNotCutOffAtMost (no answer past 5x unroutedMost;
the model's wait lets go when the client leaves) and
TestUnroutedMsgSaysTheMaskingModel (the message's words).
TestUnroutedMostLeavesOutMasking: masked 3x unroutedMost, not answered;
then held by an image description that never ends, answered 504.

Run: go test -count=1 -run 'Unrouted|Masking|Held|Mask'
./internal/gateway/ ok; go test ./internal/pii/ ok; gofmt -l clean;
GOOS=linux and GOOS=windows go vet of both ok. Full gateway and pii
run before the push, recorded in the last commit of this set.
Broken by hand: checkMost counting from arrival again
(TestMaskingModelWaitNotCutOffAtMost and TestUnroutedMostLeavesOutMasking
red, 504 while masked); checkMost never giving up
(TestUnroutedMostLeavesOutMasking and TestUnroutedRequestShownThenAnswered
red).
Not tried: a real long request through a real pf-serve on a weak GPU.
2026-10-27 01:14:23 +08:00
yetone dd5b0ab311 pii: a GPU too slow for one request is tried again, and a lost GPU comes back without a restart (#3682)
yunwang2442-creator's RX 470/580 (Vulkan): a 480 KB request ran past
classifyTimeout, magpie ended pf-serve, and classifyTurn set srv.cpu on
any GPU error. Nothing cleared it short of a restart of magpie, so every
request after it ran on a CPU about 3x slower. A slow request is not a
lost GPU.

Now:
- ended for taking too long on the GPU (h.slow), the try again is on
  the GPU; a second one in a row is a lost GPU, and the CPU is tried;
- a GPU that dies answering, or whose load hangs (cebd0d4c3, kept), is
  lost at once, as before;
- a lost GPU is tried again after gpuRetryAfter: 10 minutes, doubling to
  2 hours while it keeps failing. The CPU's pf-serve makes way for the
  GPU's at that request; one that fails moves back to the CPU, for
  longer;
- a GPU that answers clears cpu, gpuLost and the count.

Tests (fake pf-serve modes gpuhang, gpuhangonce, gpudiesonce):
TestGPUTimeoutStaysOnGPU, TestGPUHungTwiceMovesToCPU,
TestLostGPUTriedAgain, TestGPURetryAfter; they use gpuInstall, so the
GPU is Vulkan's off macOS.

Run: go test -count=1 ./internal/pii/ ok; the four with gpuInstall's
Linux branch forced on macOS, ok; gofmt -l clean; GOOS=linux and
GOOS=windows go vet ./internal/pii/ ok.
Broken by hand: the slow request's GPU retry removed (TestGPUTimeout-
StaysOnGPU and TestGPUHungTwiceMovesToCPU red); the gpuAgain retry
turned off (TestLostGPUTriedAgain red); a GPU's answer not clearing
the state (TestLostGPUTriedAgain red).
Not tried: a real Vulkan GPU, or a real GPU hang; the GPU's reload on a
retry is a fake's here.
2026-10-27 01:14:23 +08:00
yetone 7279bdc28b pii: pf-serve-vulkan runs its MoE in 2048-token chunks unless the user set PF_MOE_CHUNK (#3682)
yunwang2442-creator (#3682, Windows, RX 470/580-class 8 GB GPU through
Vulkan, q8 model): with privacy-filter.cpp's default PF_MOE_CHUNK (4096)
a 480 KB text took 159s and was killed at classifyTimeout's 150s; with
2048 it took 90s, and 2048 was 1.77x faster at every size from 24 KB to
480 KB and the fastest of 1024/1536/2048/2560/3072 on 48 KB.

What PF_MOE_CHUNK is (privacy-filter.cpp at the pinned 735a6c286,
src/model.cpp and docs/cpu-perf.md): the MoE FFN runs over the window's
tokens in chunks of this many; per-token, so exact (no halo). Its default
is the forward window (4096), where it is inert. So 2048 changes speed
only, not what is found.

Measured here, M4 Pro, Metal, the real pf-v2 pf-serve and q8 model run
directly (not through magpie, ~/.config/magpie untouched), interleaved
A/B, two rounds of two runs, at load ~250 from other sessions:
  24 KB: 4096 0.40-0.43s, 2048 0.44-0.45s, 1024 0.49-0.66s
  96 KB: 4096 1.86-1.92s, 2048 1.98-2.15s, 1024 2.22-2.27s
  spans the same (5) at every setting.
So 2048 is ~6% slower on Metal: magpie sets it for pf-serve-vulkan only.
macOS's Metal pf-serve and the CPU's keep the engine's default. A
PF_MOE_CHUNK in magpie's environment (set, even empty) is the user's and
is inherited by every pf-serve, never overridden (moeChunk).

Run: go test ./internal/pii/ -run 'TestVulkanServeGetsMoEChunk|
TestServeStartsWithoutResidency' (ok). The full ./internal/pii/...
./internal/gateway/... run is recorded on the last commit of this stack.
Broken by hand: moeChunk ignoring the user's value -> the "user's own"
case red (2048 where 3072 was set); moeChunk never matching Vulkan ->
the "vulkan" case red.
Not tried: a real Vulkan GPU (none here; the 1.77x is the reporter's
measurement), an NVIDIA or Intel GPU through Vulkan, where 2048 may be
slightly slower as on Metal.
2026-10-27 01:14:22 +08:00
yetone a6d7e02c77 gui: a page wheeled right after a click scrolls on macOS 13's WebKit too (issennknight on Discord)
issennknight (macOS, trackpad): every page scrolled again, but a saved
profile opened on the Agents page and then scrolled through often stayed
where it was. macOS 13's WebKit scrolls a view under wheels it never
dispatches, so the view guard puts each such scroll back and takes three
put back the same way within a second as the reader's run (30d3001a0).
That rule skipped every put-back while a click held what it clicked, and
a click holds for 4s: a profile opened and wheeled through at once was put
back on every scroll and the page stood still ("sometimes" = within 4s of
a click). A wheel the page hears was fine.

Now a held view's put-back is the hold's only when the page was redrawn
since the hold last held it (the view's height, or where the first held
parts sit, moved from what hold() left in h.lay). A scroll with the page
laid out as the hold left it counts as at rest, so the reader's run is
given back a click before it too. One scroll by code after a click is
still put back: view-wheel-unheard's last case now checks that (its old
per-frame code scroll is a run, given back by design).

Other inner scrollers checked: the panel's Profiles popover (overflow
auto, overscroll-behavior contain) is outside any .view and the guard;
the provider editor's .mchips keeps contain except under 640px tall, an
earlier deliberate call, left alone.

Tests:
- New view-wheel-after-click.test.cjs: wheels (unheard and heard) over
  the long profile's details right after the click, to the foot, past it
  and back up; the short one's too; nothing but the view scrolls. en, zh,
  zh-TW, ja, de at 420 and 1000 wide, Chromium and WebKit. Red on
  origin/main's assets (MAGPIE_AFTER_CLICK_ASSETS) in 20 of 24 subtests,
  "ten wheels of 30px right after the click scroll the page: from 153 to
  153"; the heard cases pass there. Green with the change.
- Before the rebase, 59 GUI files the change can reach (every scroll/wheel/view-/click/
  hold/held/keep/profile/unroll/jump/stay/still file, old-webkit,
  text-size, sidebar*, last-page, routing-days-fit, routing-failed-open,
  update-auto, i18n-keys, gui-de/ja/zh-tw), both engines, at
  --test-concurrency=4 on a box at load 130-160: 810 of 816 pass. Reds,
  each red alone on origin/main 865df2472 too: menu-input-scroll (#3402),
  old-webkit Safari 15.0 (#3403), quota-holds WebKit (#3777, new);
  routing-scroll-end 440x620 "stage's columns 3 !== 2" under load, 22/22
  alone on both (#3778, new). The whole GUI suite was not run: other
  sessions' GUI suites held the machine.
- go test -tags nogui ./internal/gui ok before the rebase.

At the pushed head (rebased on ca9b5048e, which touched app.js): the budget
tests ok (app.js 1,314,407 bytes of 1,321,319, not raised), and
view-wheel-after-click, view-wheel-unheard and click-scroll pass 54/54 in
both engines. The 59-file run above was at the base de54b4ff9.

Broken by hand: putting back the old gate (any put-back under a hold
skipped) turns the new test red as above. Removing the new redraw gate
(h = false) is not caught by a test: in both engines a redraw under a
click is held by heldSizes before the guard hears a scroll (logged: no
put-back during a 30-frame shrink at the foot), and the synthetic
redraw fixtures I tried passed with the hold removed too, so none is
shipped.

Not tried: real macOS 13 / WebKit 16.6 and a real trackpad; the unheard
wheel is a capture listener stopping the wheel event.
2026-10-27 00:54:18 +08:00
yetone 865df24727 gateway: a Chat stream's tool calls sent by turns are read by index, one call each
mysterious_dove (Discord, on 098ac9696): a Chat upstream that streams two
tool calls' fragments by turns (index 0, 1, 0, 1, 0, 1, the first of each
with id and name, the rest only arguments) reached Codex as six
function_call items: the first two with their names and `{}`-ish partial
arguments, four with no name, half the arguments and fresh ids.
chatDecoder started a new call at every change of index.

chatDecoder now reads fragments by tool_calls[].index (toolCall). The open
call streams as it comes; a call that starts while the open one's
arguments aren't yet whole JSON is held by its index and given whole, in
index order, at finish_reason or [DONE]. A sequential stream streams as
before; a repeated id still continues its call, a new id at the same
index still starts the next one.

Siblings: every Chat-to-X translation (Responses, Anthropic Messages,
Gemini, a whole reply via collector) reads through chatDecoder, so all
are fixed here. Checked and unchanged: chattidy's streamCallIndexes,
chat_call_ids, grok_integral, whole_stream and textcalls already key by
index or build no calls from fragments.

Tests (translate_stream_test.go): TestInterleavedToolCallsToResponses
(the exact interleaved stream: 2 function_call items, whole JSON args,
index order, one output_index and item id per item across added/delta/
done), TestInterleavedToolCallsToAnthropic (2 tool_use blocks),
TestInterleavedToolCallsWhole (2 calls), TestToolCallsNamedFirstThenArgued
(names first, then args, [DONE] with no finish_reason).

Broken by hand: with origin/main's chat.go put back, all four fail
("6 function_call items, want 2"; 6 tool_use blocks; 6 calls of fragments).

Run at this head (rebased on d157700a0): go test ./internal/gateway/ -run
'TestInterleaved|NamedFirst|ToolCall|Parallel|ChatTranslation|RepeatedToolCall'
ok; gofmt -l internal/gateway/ empty; go vet, GOOS=linux go vet -tags
nogui, GOOS=windows go vet ./internal/gateway/ ok.

Not tried: the full `go test ./internal/gateway/... -timeout 45m` before
the push: other sessions' gateway suites held the machine for 2h (load
150-200) and a second suite at once would only time out; it runs after
the push. Not tried against the reporter's real upstream; the fixture is
built from the report's description, not captured bytes.
2026-10-27 00:28:06 +08:00
yetone 5b4dec58e4 providers: a vendor's keys saved a provider each are one provider with those keys
yuluo_yx on X: "NVIDIA #595"…"#600" at integrate.api.nvidia.com and
"Mistral #0001"… at api.mistral.ai were a provider each on the
Providers page and a row each on Routing, and with thousands of keys
magpie started slowly. They came from an app that keeps an entry a key
(CC Switch) imported in one batch: ImportFromApps only offered "add as
another key" against providers that existed before the batch, so each
entry became a provider of its own (nvidia, nvidia-2…).

Fold (internal/provider/fold.go):
- FoldCopies runs in startUp, before anything lists the providers, so
  every user who has such copies already finds them folded. Automatic,
  not a one-click offer: they are the same account's keys at the same
  address, what the user wanted is one provider (zero-config rule), and
  nothing is lost: each copy's id goes in the provider's Was, so its
  calls count with it by key (ProviderKeyID is the key's fingerprint,
  unchanged) and a model picked by the old id still resolves.
- Only copies by name fold at start-up: a base name and that name with a
  number after it (" #12", or freeName's " 2"), at least one numbered.
  They must also be alike in all but the key: the provider with id,
  name, keys and on/off left out, their per-model settings, and every
  place that names them (Visible, picked/hidden/ordered models, groups,
  fallbacks). A copy shown to one agent alone, given its own models or
  settings, or named by the user ("Home relay" / "Work relay") stays
  apart. Subscriptions, hidden ones, Vertex and StepFun-signed ones are
  never folded.
- The first copy that is on takes the rest; it is named the base name
  ("NVIDIA") and its key keeps its old name. Others become keys in the
  providers' order, named as they were, off if they were off.
- Group members, weights, rules, classifier, pick and fallbacks name the
  provider once; per-model settings and fetched lists of the folded ids
  go; balance and window history kept by their id moves to their key's
  name, where a provider with several keys reads it.
- A providers.json that doesn't parse is left alone (read() would have
  given its .bak, and a fold would write that over it).
- ImportFromApps folds what one import added by shape alone, whatever
  the entries are called.

Routing needed no change: a provider's keys for one model already fold
into one row ("2400 keys"), opened on click (FOLD_AT, #1319).

Numbers, sandbox HOME with 2400 NVIDIA + 600 Mistral copies (gen.py,
NVIDIA preset + 2 models, Mistral 15 models), `magpie web`, every
outgoing request through a dead proxy:
- before (origin/main 9809a8ac9): first /api/state 200 after 6.38s
  (4.9s on a second try), /api/state 2.6-4.5s and 86,475,466 bytes,
  /api/providers 6.4-8.4s and 11.7 MB, RSS ~1 GB.
- after, first start (folding): first /api/state after 1.73s; later
  starts 0.52s. /api/state 5-13 ms and 100,833 bytes, /api/providers
  25-80 ms and 315 KB, RSS 69 MB. The file ends with 2 providers,
  nvidia with 2400 keys and mistral with 600.
With 3000 keys in one provider nothing else scaled badly enough to
show (#3164 and @NetRozee's thousand-key work already made the key
paths once-per-list), so nothing more was changed.

Tests: TestFoldCopies, TestFoldCopiesIntoOneOn, TestFoldCopiesUnreadable,
TestImportFoldsAKeyAnEntry. Broken by hand, each went red: refs left
out of the shape (a copy shown to Codex alone folded), per-model
settings left out, Off not carried, Was not appended (usage of the
folded id stayed its own), the first-on rule, the history move, the
settings move, the unparseable-file guard, and the import's fold.

Run: gofmt -l (clean); go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./... (clean); go test -tags nogui
./internal/provider ./internal/cli ./internal/settings
-skip TestUnreadLoginsWriteErrorsKeepCredentials: all ok (provider
121s). That test crashes alone on origin/main 834935149 too ("close of
synctest channel from outside bubble", filememo.Forget), filed as #3632.

Not tried: the GUI suite (no asset changed; the pages read the same
APIs), a real CC Switch database with hundreds of entries (the fixture
is CC Switch's schema with four), a user whose copies have different
per-key settings (they stay apart by design), and the full ./... suite
before the push (other sessions' suites were running at load ~110).
2026-10-26 23:27:55 +08:00
yetone 9809a8ac9a gateway: Codex side calls go at an effort the model takes, and a refusal for no effort is asked again at low
cybercaius on Discord: Codex's side calls are meant to go at low effort,
but some went with none or no effort, and the upstream answered 400 as
the model needs one.

Cause, from Codex's source: a title asks low only on Codex's own title
model (gpt-5.6-luna, thread_title.rs `(model == THREAD_TITLE_MODEL)
.then_some(Low)`); on any other model, a magpie one included, it sends no
effort. The auto-review (guardian select_review_model) asks low only when
the model's preset lists low, else the preset's default, and codexcat
writes no levels and no default for a magpie model whose levels aren't
known, so it too goes with none. magpie fitted an effort asked to the
model's levels but never added one that was absent, and its off-effort
retry fired only for none/minimal refusals that list levels.

Fix:
- codexSideEffort: a title, description, summary, prediction, auto-review
  or memory call on one of magpie's models whose levels are known, asking
  no effort or an off one the model hasn't, is asked at its lowest on
  level (onEffort: low where it has it). Groups, other efforts and models
  with unknown levels go as asked.
- serve, forwarded and translated (Chat and Responses, not Anthropic):
  a 400 whose body says an effort is required (effortRequired: "reasoning
  effort is required", "missing required parameter: reasoning.effort",
  "requires a reasoning effort", "reasoning cannot be disabled") to a
  request that asked no effort or none is asked again once at onEffort.
  Any other 400 goes back as it came, asked once; a none that was refused
  is remembered (offRefused) as before. A no-effort refusal isn't
  remembered, so a model with unknown levels pays the 400 each time.

Ran (at this head, rebased on origin/main):
- go test -count=1 -timeout 45m ./internal/gateway/... ./internal/agent/...: ok (gateway 521s, agent 316s), at the pushed tree (2ca0da8e5 before this body was written), base 51202cd43
- go test -race -count=5 on the new tests: ok
- gofmt -l internal/gateway: clean; GOOS=linux and GOOS=windows go vet
  -tags nogui ./internal/gateway: clean

Broken by hand:
- codexSideEffort returning the body as it came:
  TestCodexSideCallAskedAtAnEffortTheModelTakes red (asked at ["" "low"])
- the backend's guardian/memory normalisation off: the same test red at
  the auto-review (["low" "" "low"])
- the forwarded retry off: TestEffortRequiredRefusalAskedAgainAtLow red
  (chat false: 400 "Reasoning effort is required")
- the translated retry off: the same test red (chat true)

Not tried: cybercaius's own upstream; its exact 400 text wasn't in the
report, so effortRequired is built from the wordings above, and
TestEffortRequiredWords holds that a level or field refusal isn't read
as one.
2026-10-26 22:55:29 +08:00
yetone 81a73c1c01 gateway: a Codex title that comes before its conversation's first turn follows the model just switched to
cybercaius on Discord: after switching Codex to another model, the first
new conversation's title was still written by the model before.

Cause: Codex writes a title on a temporary thread of its own
(tui/src/app/thread_title.rs, thread_source "thread_title"), with no
parent link to the conversation, started as the first message is sent and
so racing that conversation's first turn. codexLeads.of found neither a
parent nor its own thread and took the key's last turn, which, when the
title came first, was the previous conversation's, on the old model.
Composer predictions run on a fork and named it (forked_from_thread_id),
which of() never read, so they too took the key's last turn rather than
their conversation's.

Fix: of() reads the forked-from thread. The app's side turns (titles,
descriptions, summaries, predictions) read through codexLeads.sideOf: a
call tied to no thread magpie has seen, whose key's last turn is older
than 3s, waits for the next own turn (a channel saw() closes), up to 5s
or the request's cancellation, and takes that turn's model. Subagents and
memories keep codexSessionOf with no wait: they carry their lead's
thread. The auto-review follows the session only through codexcat's
per-entry override, and compaction goes on the conversation's own turn
model, so neither reads codexLeads.

Ran (at this head, rebased on origin/main):
- go test -count=1 -timeout 45m ./internal/gateway/... ./internal/agent/...: ok (gateway 521s, agent 316s), at the pushed tree (2ca0da8e5 before this body was written), base 51202cd43
- go test -race -count=5 on the new and neighbouring Codex side tests: ok
- TZ=UTC go test -run TestCodexTitle ./internal/gateway: ok
- gofmt -l internal/gateway: clean; GOOS=linux and GOOS=windows go vet
  -tags nogui ./internal/gateway: clean

Broken by hand:
- the backend's session reader put back to codexSessionOf:
  TestCodexTitleBeforeTheFirstTurnFollowsTheSwitch red ("the model
  switched from got 2 requests, the title among them")
- meta.Forked taken out of lookup: TestCodexPredictionFollowsTheThreadItForks
  red ("the forked conversation's model got 1 requests")

Not tried: a real Codex TUI or app switching models against a live
magpie (the race is reproduced in the test, ordering forced by waiting on
the state). A rename suggestion asked later, with no turn beside it, now
waits the 5s before going on the last turn's model.
2026-10-26 22:55:29 +08:00
yetoneandskygunner 51202cd431 plugin: a check-in outcome magpie doesn't know names what the plugin said
A plugin check-in that answered an outcome not in the list, with a
message, became failed with the plugin's message alone, so "the daily
credits were refreshed" read as magpie's own failure reason. The reason
now names the answer first: the plugin answered "yes": <message>. With
no message it stays "the plugin answered no outcome" or the answer.

Split out of skygunner's fix/usage-absent-used branch (#3650), which
carried it beside the usage fix.

Run: go test ./internal/provider -run TestPluginCheckinRunsAsTheBuiltinsDo
ok. Broken by hand: host.js's old line makes it red (Msg was the message
alone). Not tried: a real plugin answering an unknown outcome.

Co-authored-by: skygunner <skygunner@users.noreply.github.com>
2026-10-26 22:42:59 +08:00
yetoneandskygunner 9733ed1b4a usage: a plugin window that doesn't say used is no reading (#3650)
A plugin usage window that leaves out `used` was read as 0 in host.js
usageOf. The card then showed "100% left" (or NaN% once the GUI saw a
missing value), and allowanceOf ranked the account as the one with all
of its allowance left, so smart routing put spent accounts first.

Now a left-out used is null from the host, plugin.UsageWindow.Used is a
*float64, and quotaOfPlugin makes such a window Text and Aside: the card
shows its display (else "No allowance reported"), with no percentage and
no meter, and routing leaves it out. An account whose windows all tell no
share has no allowance and is not known to routing (routedAllowance), as
one never read: not preferred and not rested. A window that says used:0
is a reading at 0, as before.

Ported from skygunner's fix/usage-absent-used (6791aa99). Changed from
the branch:
- lastAllowances (the reading kept on disk) built an empty allowance for
  such an account, which routing read as known with all of it left. Both
  it and Allowances now go through routedAllowance.
- quotaText shows "No allowance reported" for a no-share window with no
  display, rather than a blank.
- A host-level test (the bun host with the fake plugin) and the GUI test
  widened to both engines, every language, 900 and 390px, used and left.
- The branch's check-in wording change is its own commit.
Note: an account whose windows are all aside or text was known with 0%
used before; it is now not known, so loginRoom won't pick it as the
next account with room.

Run at this tree (base 9298d2a7c):
- go test ./internal/provider -run 'Absent|NoShare|PluginUsage|PluginText|
  AllowancePooled|PluginPool|GLMPlan|WorkBuddyCredits|QuotasDedupe'  ok
- go test ./internal/plugin ok; gofmt -l empty; go vet ./...,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... ok
- GUI: usage-no-reading.test.cjs chromium+webkit ok; i18n-keys ok;
  TestCoreScriptBudget ok (budget not raised)
Broken by hand, each red, then restored:
- quotaOfPlugin without the Text/Aside branch: 3 absent tests red
- routedAllowance always ok and allowanceOf not skipping Text:
  TestRoutingKnowsNoAccountThatSaidNoShare red
- host.js's old used line: TestPluginHostPassesAnAbsentUsedOn red
- usage-no-reading on origin/main's assets: red in both engines
  ("12 / 300 · NaN% used")
Not tried: a real Loomy account, a live routed request.

Co-authored-by: skygunner <skygunner@users.noreply.github.com>
2026-10-26 22:42:59 +08:00
yetone 43001be863 gateway: a relayed Chat body's unpaired tool calls are paired before Kimi sees them
Paidaixinbao on X: Qoder through magpie on Kimi Code, a conversation
forked at an earlier turn fails on every prompt while a new one works.
A Chat client's body to a Chat upstream was relayed as-is, and only
translated requests had their tool exchanges mended (pairToolMessages).
A forked or stopped history can hold a call with no tool answer, calls
split over two assistant messages, a user turn between a call and its
answer, or an answer to no call. Kimi turns the whole request away with
400 "an assistant message with 'tool_calls' must be followed by tool
messages responding to each 'tool_call_id'..." or "tool_call_id  is not
found". toolPairsOut now pairs such a body on the Chat relay (joining
split calls, answering the unanswered, turning an orphan answer into
user text); a paired body goes out byte for byte.

Run:
- Real Kimi Code API (kimi.com/coding/v1, 2026-10-26; the account's
  plan has lapsed, so a body past validation answers 403 and a refused
  one 400): unanswered call, split calls, user between call and answer,
  one of two answered and an orphan answer are each 400; every one of
  them after toolPairsOut is 403, past validation. A tool turn without
  reasoning_content, null content, repeated ids, out-of-order and
  double answers, prefill and a reasoning field all pass as-is, so
  they are not the cause and are left alone.
- gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -timeout 45m ./internal/gateway: ok, at this commit.
- Two fixtures held an unpaired body only by accident and are paired
  now: image_input's chat-tool case (a lone tool message) and the
  large-chat upstream golden (its last call left unanswered); the new
  large-chat hash is the same on the old code.

Broken by hand: without the toolPairsOut call all six subtests of
TestChatRelayPairsToolsForKimi go red against a fake Kimi with Kimi's
own wording; without joinSplitChatCalls the split case goes red;
reading only string content in toolAsUser turns the parts case red.

Not tried: the real Qoder app and the reporter's own forked history,
so which shape their fork holds is not proven; Qoder's "unsupported
request" text is not magpie's wording. A real Kimi model answer (the
plan has lapsed, only validation was seen). A non-Kimi Chat upstream,
though the rule is OpenAI's too and runs for every Chat relay.
2026-10-26 22:40:48 +08:00
yetone 4a33cf0a98 update: a Stable channel in Settings → About, and magpie update channel
ssharpcc on X reads every changelog before updating, for fear of a ban
when behind, and with many releases a day that is a lot of reading.
Settings → About → Update channel (zh: 更新渠道, 稳定版 / 每个版本) picks
Every version, the default and today's behaviour, or Stable: one version
a week, the newest that had been out three days as the week began
(Monday 00:00 UTC), and an urgent release at once. usemagpie.ai chooses
it from the release list (the previous commit); a release is urgent when
a line of its notes starts with "**Urgent release:**", which
magpie-releases' release run writes from an `Urgent: <why>` trailer
(magpie-releases 73f6cff).

- settings: updateChannel, "" or "stable"; anything else is refused.
- update: on Stable the feed is asked with channel=stable; What's new
  shows every release since the installed one (up to 1500) instead of
  the newest 40, so a week's notes read as one list.
- gui: the row is segs, never a <select>; a save that doesn't send the
  channel keeps it; switching asks the feed again at once, and a
  download from every version newer than Stable's pick is dropped,
  never restarted into. What's new's notes are kept per channel.
- cli: magpie update channel [stable|every] ("all" too), and it says
  which with nothing after it.
- docs: reference.md's Update channel (the rule and the marker); the
  privacy pages (en, zh, ja) name ?channel=stable on /api/latest.

The full Go and GUI suites were not run: the disk was at 3 GB free and
other sessions had GUI suites and a 45-minute gateway run going the
whole time.

Run, at this tree before the rebase:
- gofmt -l (clean); go vet on darwin, GOOS=linux -tags nogui and
  GOOS=windows for ./internal/update/... ./internal/cli/...
  ./internal/settings/... ./internal/gui/.
- go test -count=1 ./internal/update/... ./internal/cli/...
  ./internal/settings/...: ok. ./internal/gui -run
  'TestUpdateChannelSwitch|TestWhatsNewKeyedByChannel|TestCoreScriptBudget':
  ok (the app.js budget passes).
- GUI, chromium and webkit: update-channel (22: en, zh, zh-TW, ja, de at
  900 and 420 wide: default lit, Stable saved, kept by another save,
  kept over a reload, Every saved back, no click scrolls, no sideways
  scroll at 420), i18n-keys, gui-ja, gui-de, gui-zh-tw and every
  update-*.test.cjs: 253 of 253 pass.
- The live feed: /api/latest?channel=stable answers 0.1.1327 (out
  2026-10-22 21:55 UTC, the last before Friday 10-23 00:00) with 15
  assets after the first real cron run filled the ledger (400 releases
  back to 10-10); /api/notes 0.1.1200..0.1.1327 gives 124 notes, none
  empty (1213 and 1218 were never published).

After rebasing on afc99490f: TestCoreScriptBudget, the channel Go tests
(update, cli, gui) and GUI i18n-keys + update-channel (both engines,
26 of 26) pass again.

Broken by hand, each red: the feed asked without channel=stable
(TestLatestAsksTheChannel); Stable capped at 40 (TestStableNotesAreAll);
any channel saved (TestUpdateChannelSaved); "all" dropped
(TestUpdateChannelCmd); a save without the field clearing it, no new ask
on a switch, the newer download kept (TestUpdateChannelSwitch); one
notes key for both channels, What's new capped at 40 on Stable
(TestWhatsNewKeyedByChannel); app.js's other saves dropping the channel,
Stable's click saving "" (update-channel 11 of 11 red); the zh label or
a de subtitle taken out (update-channel and i18n-keys red).

Not tried: the full go test ./... and the whole GUI suite (above); a
real app switching channel against the live feed; Windows and Linux
runs (vet only); a real urgent release.

Requested by ssharpcc on X.
2026-10-26 21:09:44 +08:00
yetone 6e6aba51c8 providers: a key may be for another plan of its vendor, sent to that plan's endpoints
yckonnnn on X uses Volcengine's pay as you go and its Agent Plan, and
wants a key of each in one provider. Each plan takes its own keys at its
own endpoints (/api/v3, /api/plan/v3, /api/coding/v3), and every key of
a provider went to the provider's one plan, so only one kind worked.

A key now may say which of its preset's Regions it is for
(KeyAccount.Plan; Provider.KeyPlan for the first key, as KeyProtocol).
None, or the provider's own plan, is the provider's plan, stored as
none: old configs read and write as before. Presets whose plans take
keys of their own (PresetDef.KeyPlans): zhipu, zai, stepfun,
stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud,
volcengine, siliconflow. Not: yylx (one key everywhere),
bailian-decision (decide only), bedrock and bedrock-mantle (regions of
one account).

Every reader of the region or a base URL, and what it does now:
- WithKey (keys.go): moves the key's copy to its plan (atKeyPlan:
  Chat, Responses, Anthropic, Decide, KeysURL, Website, Catalog via
  atRegionOf; a provider at a host of its own keeps that host) and marks
  it keyView. Every gateway key path goes through it: chat, Responses,
  Messages, count_tokens, failover, embeddings (serveRetrieval via
  onKeys), drawing (drawOnAccounts via perKeyBarred), key tests
  (test.go), key_models.go, gui/groups.go, markedKey.
- perKeyBarred (gateway/fallback.go): a key whose plan's list lacks the
  model (PlanServing) is not asked; only when no key's plan has it.
- fetch / fetchPerKey / planOnly (models.go): a mixed provider lists
  each key's plan, a NoList plan from its preset list with no request,
  pay as you go from /api/v3/models with its own key.
- planMedia (PlanEmbeddings, PlanDrawers, PlanVideos): every plan's.
- PlanQuotas (planquota.go): each key read at its own plan's source.
- volcPlanQuotas, tencentPlanQuotas: one view per plan (planViews).
- KeyBalances (balance.go): each key at its plan's host (SiliconFlow).
- startVideo / videoMaker (gateway/video.go): a mixed provider starts on
  a key whose plan makes the model (onKeys) and names it in the id
  (keyMark), so the poll goes to that key's plan.
- GUI: POST /api/keys/plan (SetKeyPlan, then the lists are read again);
  the editor keeps KeyPlan with an unchanged first key, typed() clears
  it with a new one; KeepSecrets, AddCopy, backup's withoutKeys carry it.
- app.js: planPicker, a plan chip in each key row (the app's own menu,
  openProtoMenu, through pickPill, which protoPicker now shares), shown
  for a KeyPlans preset while the provider has several keys or the key
  has a plan; i18n zh, zh-TW, ja, de.

A key's plan is not guessed from the key: Volcengine's keys carry
nothing that says their plan. Xiaomi's tp-, Tencent's sk-tp-, MiniMax's
sk-cp- and Bailian's sk-sp- are noted in code but not used.

Not done: a gateway key held to some keys (videoAsker) on a mixed
provider's video may pick another key; a mixed provider whose own plan
has no balance source while a key's plan has one is not read; keys left
out for their plan don't show in the Routing trace; StepFun's plan
windows are a sign-in per site, unchanged.

Credit: yckonnnn on X (tweet 2114657701305487483).

Run at this commit on origin/main 1bb8143b3 (macOS, go1.26.8):
- gofmt -l internal: clean. go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean.
- go test -count=1 -skip TestUnreadLoginsWriteErrorsKeepCredentials
  ./internal/provider/ ./internal/gateway/: ok (103s, 421s). The skipped
  test crashes the whole provider package on main (#3632, from 091153bf).
- TestCoreScriptBudget: ok, budgets not raised (app.js 1,307,430 bytes).
- GUI, chromium and webkit: key-*, provider*-*, add-sheet, i18n-keys,
  gui-de, gui-ja, gui-zh-tw (58 files): 956 of 956 pass. key-plan.test.cjs
  covers en, zh, zh-TW, ja and de at 420 and 1000px.
Earlier, at the same change on origin/main 9120acaff:
- go test -timeout 45m ./...: 71 packages ok, internal/gateway and
  internal/gui among them. internal/provider crashed on #3632 only; run
  again with that one test skipped, it passed.
- The whole GUI suite (node --test tests/*.test.cjs) did not finish: the
  disk ran out at about 319 tests and the run was stopped. Up to then the
  only reds were account-discovery in both engines, #3497, red on main.
Broken by hand: without atKeyPlan in WithKey, TestKeyPlanEndpoints,
TestKeyPlanModelList and TestKeyPlansEachToItsOwnEndpoint go red; without
the planless filter in perKeyBarred the gateway test goes red; without
the plan chip key-plan.test.cjs goes red.
Not tried: real Volcengine (or any other vendor's) keys of two plans in
one provider; the video path (startVideo with mixed plans) has no test of
its own; Windows and Linux were vetted, not run.
2026-10-26 20:37:07 +08:00
yetone 1bb8143b37 gateway: thinking pi sends back in reasoning goes to DeepSeek once, as reasoning_content
ArvinCharl on X (tweet 2114658365963976779, v0.1.1560): pi on a
self-hosted DeepSeek through the Chat path keeps the thinking the server
returned in `reasoning` and sends it back there. withReasoningOnToolTurns
copied it into reasoning_content and left `reasoning` in, and the server,
which reads the two as one field, refused the request with "duplicate
field reasoning".

When magpie fills reasoning_content (asReasoningContent), the message's
`reasoning` is left out, so the thinking goes once. Sibling:
reasoningDetailsAsContent (Kimi, #1765) filled reasoning_content from
`reasoning` the same way and now leaves it out too. reasoning_details
stays on the DeepSeek path: it is a list of typed entries (an encrypted
one, a signature), not another name for the text, and an upstream that
refuses it already has it taken out (reasoningDetailsAsContent,
withoutMessageReasoning). A message with reasoning_content of its own is
left as the client sent it. Not changed: flattenContent (replies to the
client, typed thinking parts, no `reasoning` field added), buildChat
(writes reasoning_content alone), mistralThinking (drops all three).

TestChatToolTurnWithoutReasoningRelayed asserted the old duplicate on
its OpenRouter-field turn and now wants reasoning_content alone.

Run at 9df403f80 (rebased on origin/main 77f860105):
- gofmt -l: clean.
- go vet ./internal/gateway/ with GOOS darwin, linux, windows: ok.
- go test -count=1 -timeout 45m ./internal/gateway/...: ok (429s),
  no FAIL in the log.
- Not run: the full go test ./... suite; the disk had 1.2 GB free after
  the gateway run.

Broken by hand: with the delete of `reasoning` commented out,
TestSelfHostedDeepSeekGetsReasoningOnce (400 "duplicate field
`reasoning`" from a fake that refuses both fields, the reporter's
message shape), TestKimiReasoningDetailsWithReasoningGoOnce and
TestChatToolTurnWithoutReasoningRelayed go red; restored, green. The new
test also checks a body with no tool calls comes back byte for byte.
#1462/#1822/#494/#1765 tests pass.

Not tried: a real self-hosted DeepSeek server or a real pi session; the
fake reproduces the reported refusal.

Reported by ArvinCharl on X.
2026-10-26 19:43:24 +08:00
yetone 5a94eec3ae gateway: a request held 30s before routing in no known wait is answered then
sharwowwow on X: "转圈两分钟才报 504,这个超时阈值本身就很折磨人。网关要是能
早点失败、早点给明确错误,排查能省不少时间。" A request held before any
route was answered 504 only after unroutedMost (2m), whatever held it.

Now the time a request spends in a wait magpie knows of is added up as it
happens (noteWait/waited, the union of overlapping waits), and a request
held unroutedUnknown (30s) outside them gets the same 504 and message
then. unroutedMost (2m) stays the cap for one in known waits. Known waits,
each read from the code between counted and noteRoute:
- the request's body arriving: r.Body is wrapped (waitedBody), so every
  read of it (keyLimited, requestBody, readRequestBody) counts;
- masking (noteMasking);
- System One's or the decision model's classifier (askWaited);
- an image's description (seenBody);
- Codex's auto reset before the route (autoReset);
- plugins' gateway hooks / plugin host start (GatewayBegin) and JS
  gateway middleware (Begin, Request);
- every notePhase (slot, rpm, upstream); these come after the route for
  watched requests today, so it only guards a future change.
What is left is magpie's own work (catalog build, parsing, planning,
affine, reading the usage log), ~8.5s at its slowest (a cold catalog
sync); 30s is about three times that, with room for a loaded machine.
The log says "30s of it in no wait magpie knows of".

Run at this tree (rebased on origin/main 9120acaff):
- gofmt -l internal/gateway: clean.
- go vet ./internal/gateway/... on darwin, GOOS=linux, GOOS=windows: ok.
- go test -timeout 45m ./internal/gateway/...: ok (478.0s).
  Also ok on the earlier bases a5ce158e5 (655.8s) and 7d075df9d (448.1s).
Not run: the full go test ./... and go vet ./..., because the machine's
disk was full (under 1GB free for over 20 minutes; a build and one
gateway run failed with "no space left on device", every red naming it). No -race run.

Broken by hand, each test red, then restored:
- without the 30s answer (u.giveUp(true)),
  TestUnroutedUnknownHoldAnsweredSooner: not answered before unroutedMost;
- without the body wrap, TestUnroutedSlowBodyNotCutOff: answered 504
  while its body was still arriving;
- without masking's excuse, TestUnroutedMaskingNotCutOff: answered 504
  while it was masked.
TestUnroutedSlotWaitNotCutOff stays green without notePhase's excuse (the
slot wait is after the route); it guards that a slot wait is never cut.

Not tried: no test of its own for the classifier, auto reset, gateway
hook, JS middleware or image-description excuses; no run in the real app
or against a real provider.
2026-10-26 19:04:27 +08:00
yetone ea1f9492bc cli: magpie tools lists, and magpie tool calls, the tools magpie's MCP servers give agents (iwinux)
iwinux on Discord (#feedback) wanted magpie's image generation, image
recognition and web search without going through an agent's MCP, and had
written a Python script for generate_image. magpie now has it:

  magpie tools [<name>]
  magpie tool <name> [--<param> <value>…] [<words>…] [-o <file|folder>] [--json]

Both ask the running gateway's own MCP servers (gateway.OwnMCPServers:
image, vision, web-search, plugin tools) over HTTP, with the local token
and the magpie-tool/1 User-Agent, so the tools, schemas, models from
Settings and usage counting are the ones an agent gets. Nothing is
started besides (#3318: the cases sit before startUp, beside mcp).

- Parameters are read against the tool's inputSchema: types (integer,
  number, boolean, array given once per item, object as JSON), enum, -
  and _ alike, --p v or --p=v. The words left over are the tool's one
  required text, else its prompt. An unknown flag or parameter, a missing
  required one, a bad value, a value given twice or both words and the
  same --param are refused with "nothing was called"; no request is sent.
- A file path a parameter takes (its description says file and path)
  is made absolute, since the gateway doesn't know the current folder.
- --help prints toolUsage (static): help is handled before anything runs.
- A still-being-made answer is waited on with generation_result (1s
  between asks, 30 min at most). The gateway's image server now says so
  in _meta too: usemagpie.ai/pending is the id, usemagpie.ai/files the
  files made ({url, inline}); an older gateway is read from its text.
- Images and videos are saved through imagemcp.Target (now exported):
  -o file or folder, else the current folder named from the prompt,
  numbered when more than one, never over a file that is there; a file
  not inline is downloaded by its path from the gateway asked (the token
  goes nowhere else). --json prints the raw answer and saves nothing.
- No magpie at the address: "magpie isn't running at <url>: open the app
  or run magpie serve". MAGPIE_GATEWAY=<url> points at another.

Docs: usage lines in magpie help, docs/reference.md (Use), the gateway
routing subsystem page (_meta and the CLI), README en/zh, site docs start
page en/zh/ja.

Tests (internal/cli/tool_cli_test.go, never the network; every test sets
MAGPIE_GATEWAY to its own httptest server):
- TestToolsListsTheServersTools, TestToolReadsParameters,
  TestToolRefusesWhatItDoesntKnowAndCallsNothing (no tools/call, no file),
  TestToolHelpCallsNothing (no request at all), TestToolSavesTheImage,
  TestToolWaitsOnWhatIsStillMade (pending _meta, then the old text form,
  download with the key from the gateway asked, not the URL's host),
  TestToolErrorIsSaid, TestToolSaysMagpieIsntRunning,
  TestToolDrawsThroughTheGateway (the real gateway.New().Handler() with a
  fake vendor: lists, draws, saves the vendor's PNG).
- TestImageMCPDrawsAndServesTheImage, ...SlowDrawingIsWaitedOn and
  ...MakesVideos now check the _meta. Red on the old behaviour: with
  withMeta setting nothing (what main answers) all three fail ("_meta
  map[], want pending img_…").
- Broken by hand: dropping the unknown-parameter check makes
  TestToolRefuses… red (the --model call was made); saving an inline
  image by its URL instead makes TestToolSavesTheImage red. Both restored.
- TestHelpOnEveryCommandDoesNothing covers tool and tools.

Run with this change on origin/main 630fd1d69, then rebased on cebd0d4c3
(internal/pii, internal/gui, docs and site/ changed between, nothing
this change touches): there
gofmt, go vet of cli/gateway/imagemcp, internal/cli, internal/imagemcp and
the gateway's TestImageMCP/TestVisionMCP/TestSearchMCP again, ok.
At 630fd1d69:
- gofmt -l: nothing. go vet ./...; GOOS=linux go vet -tags nogui
  ./internal/...; GOOS=windows go vet ./internal/...: clean.
- go test ./... -timeout 45m: internal/gateway, imagemcp and the rest ok;
  ten packages failed with "no space left on device" (the machine's disk
  was full from other runs). Those rerun when space was back: agent, cli,
  davsync, gui, library, sessions, settings, tui, usage, usageapi,
  wslrun, plugins/... ok. internal/provider crashes in
  TestUnreadLoginsWriteErrorsKeepCredentials with "close of synctest
  channel from outside bubble" (filememo.Forget), twice: that is #3632,
  open, on main since 091153bf7, nothing this change touches.
- Real try: a nogui build of this head as magpie serve on 127.0.0.1:3482
  under a scratch HOME, a custom provider pointed at a local fake images
  API. magpie tools listed image, vision and web-search with their
  parameters; generate_image "…" --size 1024x1024 -o hero.png saved a PNG
  and the vendor got prompt and size; --n 2 --quality high saved two
  numbered files; --model was refused before calling; analyze_image and
  web_search said what to set up (no vision model or search API there);
  --help asked nothing. Usage counted the calls as magpie's own.

Not tried: a real image vendor, a real vision or search model, a video,
a plugin's tool through magpie tool, Windows and Linux runs (vet only).
2026-10-26 18:42:35 +08:00
yetone cebd0d4c35 pii: a hung GPU load moves to the CPU, a failure says what ended pf-serve, and a failing model holds requests back at once
lazyeo on Discord (Apple M2, 16 GB, macOS 27.0.1, since v0.1.1577): with
Settings → Privacy's local model on, every request, even the first after
a restart, waited out the gateway's 2-minute 504 ("still loading"), and
Settings showed "pf-serve ended: ggml_metal_device_init: tensor API
disabled for pre-M5 and pre-A19 devices … recommendedMaxWorkingSetSize".
Their goroutine dump has startOne(path, cpu=true): a GPU pf-serve had
failed and every request was loading the CPU one.

What was wrong:
- macOS had one pf-serve candidate, the Metal one; a load that hung on
  the GPU waited out loadTimeout (3m) with no CPU to fall back to.
- The error was pf-serve's stderr, which on every pre-M5 Mac starts with
  ggml's Metal init lines (the CPU mode too), so a kill by magpie's own
  classify watchdog read as a Metal crash. On an M4 Pro the CPU mode
  reads ~1.4 KB/s, below classifyTimeout's 4 KB/s, so a slower Mac's CPU
  pf-serve is killed by magpie on larger requests.
- Each failed request left the next one to load again, so a model that
  keeps failing held every request for its full 2 minutes.

Changes (internal/pii):
- candidates(): the GPU one (Vulkan, or macOS's Metal pf-serve), then
  pf-serve with PF_DEVICE=cpu. A GPU load gets gpuLoadTimeout (40s, inside
  the gateway's 2m); a GPU that fails or hangs moves the run to the CPU
  and sets gpuLost, as one dying in classify already did.
- died(): "didn't answer in Xs (N KB on the CPU), so magpie ended it"
  when the watchdog killed it, else "ended (exit status/signal)", then
  the last 3 stderr lines that aren't ggml/Metal/Vulkan startup chatter
  (a line saying error/fail/assert/abort is always kept).
- After a failure, FindContext holds requests back at once with that
  error (before and after taking the turn), until a retry 30s later,
  doubling to 10m while it keeps failing; a success or Stop resets it.
  The request is still held, not sent masked by the rules alone; the
  message says how to turn the model off.
- pii.go's comment and docs/subsystems/gateway-routing.md say so.
- Tests: a cleanup race in fakeInstall, and the seam above (cache.go
  gets disk.saves).

Run (worktree at origin/main a6c808b68 + this, sandbox HOME):
- go test -count=1 ./internal/pii/ ok; -race -count=1 ok (54.7s).
- Broken by hand, each red, then restored:
  - old candidates (macOS Metal alone, plain one not forced to CPU):
    TestHungGPULoadMovesToCPU both subtests "didn't load in 3s on the
    GPU" and TestVulkanThatWontStartFallsBack starts = [vulkan MTL0,
    pf-serve MTL0].
  - not remembering the fallen-back GPU: TestHungGPULoadMovesToCPU red
    (starts = [CPU] only after Stop, GPUError empty).
  - old died(): TestEndedForSlownessSaysSo and
    TestDeathSaysExitAndLastWords red with the M2's Metal lines as the
    error.
  - heldBack() returning nil: TestFailedModelHoldsRequestsBackAtOnce red
    ("didn't answer in 300ms", a queued request loaded again).
- Real pf-serve and model (pf-v2-darwin-arm64) on an M4 Pro, macOS 26.2,
  outside magpie: GPU load 9.9s cold / 0.86s warm, 200 KB in 2.3s; CPU
  load ~20s, 50 KB in 36.4s; the CPU mode's stderr also has the
  "tensor API disabled for pre-M5" lines.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok; go build for darwin, linux (nogui),
  windows ok.
- After the first full run, TestHungGPULoadMovesToCPU was red at load
  ~220 (the stand-in hadn't logged its GPU start inside a 3s budget). It
  now gives the GPU load up once the stand-in has started on it
  (`giveUp`, a seam over time.After), not after a duration: 8 of 8 green
  at load 220, and still red with the old candidates.
- -race then caught fakeInstall's cleanup restoring dir while the disk
  cache's 2s save timer, already fired, was writing (cleanup stopped
  only a timer that hadn't fired). disk.saves now counts a timer's
  write until it is done, and cleanup waits on it. -race -count=3
  ./internal/pii/ ok (143.9s).
- go test ./internal/gateway/ ./internal/redact/ ./plugins/redact/ ok
  (gateway 601.5s); internal/masking has no tests.
- Full suite: not completed. go test ./... -timeout 45m at 18:06
  (load 118, no other Go suite running) failed to build 16 packages and
  failed TestWarm, proc's TestEndProbesThenExitLeavesNothing and
  settings' TestSaveConcurrent, all "no space left on device": the
  disk was at 189 MB free (900 of 926 GB used, not by this run). By the
  time space came back, other sessions' suites were running (a gateway
  run, a -p 3 multi-package run, the GUI suite), so a second full run
  would have broken one suite per machine. Every package that ran and
  isn't named above was ok.
- Rebased on 7d075df9d (pushed head's parent): go build and
  go test ./internal/pii/ ./internal/redact/ ok there.

Not tried: an M2 or macOS 27 (no such machine), so why lazyeo's GPU
pf-serve failed first is still unknown; the new error and gpuLost will
show it. No known llama.cpp/ggml issue for macOS 27 or the pre-M5 tensor
line turned up. A CPU too slow for a large request is still killed by
classifyTimeout; it now says so and holds the requests after it back at
once.
2026-10-26 18:36:27 +08:00
yetone d3191a51c8 gui: with Hide accounts on, an account's eye shows that one account in this window (yogurt36)
yogurt36 on Discord, for a screen share: with Hide accounts on, one
account should be readable while the others stay masked. Now an
account's name on the provider editor's row (accountNameButton and the
one-account line) and on its Usage card (quotaWho) has a quiet eye, in
sight on hover or keyboard focus, with an aria-label. A click shows
that account, its address and the name the user gave it together
(kin), everywhere the window draws it, tooltips included: the shown
set is skipped in hits(), which every mask goes through. It lives in
memory only. The tray panel keeps hiding it, and closing the window
hides it again: the page stays loaded while the window is hidden, so
hideMain runs mainClosedJS (hideAccounts.closed) first. With Hide
accounts off there is no eye. Strings in zh, zh-TW, ja and de.

Run (macOS, playwright 1.62.0, rebased on 630fd1d69; at push 0f6615ffc, site only, came under it):
- account-eye.test.cjs: 20/20 in chromium and webkit, en zh zh-TW ja
  de, 900px and 360px (no select, no stripe, no sideways scroll, a
  click scrolls nothing, Tab (Alt+Tab in WebKit) reaches the eye).
- Red on the old code (feature stashed): both tests fail.
- Broken by hand, each red, then restored: the shown check in hits();
  closed() without shown.clear(); kin() returning only the address.
- TestClosingHidesShownAccounts (new): red without shown.clear() and
  without the ExecJS(mainClosedJS) call in hideMain.
- go test -run 'TestCoreScriptBudget|TestBuiltinClientsLoaded|
  TestClosingHidesShownAccounts' ./internal/gui: ok. app.js
  1,306,355 bytes, under 1,321,319; budgets not raised.
- i18n-keys.test.cjs: 4/4.
- gofmt -l clean; go vet (mac), GOOS=linux go vet -tags nogui,
  GOOS=windows go vet ./internal/gui; go build, GOOS=linux go build
  -tags nogui, GOOS=windows go build: ok.

After the last rebase one chromium en/zh run of account-eye showed 1
fail of 4 with 179MiB free on the disk; its log wasn't kept, so the
test is unnamed. Every run since, with its log kept, passed: 4/4 and
then 20/20 in both engines.

Not run: the whole GUI suite and the full go test ./internal/gui
(another session's suite held the machine and the disk was full; one
link hit ENOSPC and passed on retry). They run after the push.
Not tried: the real Wails window's close (hideMain) by hand.
2026-10-26 18:18:24 +08:00
yetone 05eeb4e1b9 gui: a recorded call's body viewer moves from app.js to the Gateway plugin's script
callBodyPanel and what only it uses (the JSON tree, the stream's events
and reply, sseView/sseShown) move whole, unchanged, from app.js to the
end of plugins/gateway/client.js. Nothing in the core called them: the
Gateway page's recent calls, Usage's ledger and Routing's trace do, and
every plugin's script is loaded by index.html whether the plugin is on
or off, before any of them runs. app.js goes from 1,320,558 to
1,304,307 bytes; the budgets are not changed here. This makes room for
the per-account eye in the next commit without raising a budget.

Checked that the moved block is closed: none of its 12 names (and
sseView, sseShown) is used in app.js outside it, or in context.js,
plugins.js, kernel.js, pluginpages.js or start.js, and none is declared
in another script. docs/subsystems/plugin-runtime.md says where it is.

Run at this commit (Chromium + WebKit, NODE_PATH playwright 1.62.0):
json-tree, recent-call-bodies, request-archive-usage, request-archive,
routing-bodies, sse-body and i18n-keys: 58 pass, 0 fail.
go test ./internal/gui -run 'TestCoreScriptBudget|TestBuiltinClientsLoaded': ok.
The whole GUI suite and go test ./internal/gui ran with the next commit
at the pushed head (see its body).
2026-10-26 18:18:18 +08:00
yetone 630fd1d691 masking: Clear records… deletes what masking kept, after a confirm (maxyou2090)
maxyou2090 (#feedback) turned on strict masking and it recorded many
requests, with no way to delete them short of finding
~/.config/magpie/masking by hand.

Insights › Masking's list now ends in "Clear records…" (beside "Kept on
this computer for 30 days", shown while anything is kept). It asks first
with the app's confirm dialog (Cancel / Clear, red), then posts
/api/masking/clear and reads the page again: an empty list and card. A
clear that fails says why in the status pill and the list stays.

maskrec.Clear removes each day's file whole under the store's lock (a
day is removed, never rewritten, so there is no half-written file to
guard against), forgets each day's cached summary, and drops the text
around placeholders and the bodies kept in memory. A day it can't
remove stays, is still listed, and is named in the error. Keys keep
rising, so a record after the clear never takes an old key. What the
masker holds for each placeholder stays: a placeholder still in an
agent's context is put back in its answers. GET on the route does
nothing. Strings in zh, zh-TW, ja and de. gateway-routing.md says it.

Tests:
- internal/maskrec TestClear (three days and a stray file: the days go,
  the stray stays, List/Sum/Get/SentOf are empty, keys keep rising, a
  new Add counts) and TestClearSaysWhatStays (a directory it can't
  write: the error names 2026-10-26.jsonl and the record is still
  listed). With Clear stubbed to return nil both go red
  (maskrec_test.go:220 "left in ...", :260 "err <nil>").
- internal/gui TestMaskingRecordsAPI: GET clears nothing, POST clears,
  records/summary empty, record/sent 404. Red with Clear stubbed
  (masking_test.go:127).
- GUI masking-records.test.cjs: "Clear records asks first, then
  empties the page" in Chromium and WebKit, en/zh/zh-TW/ja/de, 1100 and
  640px (Cancel sends nothing; Clear posts once; nothing wider than the
  window; the click scrolls nothing; nothing left in English), and "a
  clear that fails says why and keeps the list". Red on the old page.js
  (the button never appears).

Run, at this commit (on origin/main 44a626bed; vet, maskrec, the gui Masking tests and the 22 new GUI cases again after that rebase):
- gofmt -l internal/maskrec internal/gui: clean. go vet on darwin,
  GOOS=linux -tags nogui and GOOS=windows for both packages: ok.
- go test ./internal/maskrec: ok. go test -run 'Masking|Budget|Script'
  ./internal/gui: ok.
- GUI: masking-records.test.cjs whole and i18n-keys.test.cjs, both
  engines: 86 pass, 0 fail (before the rebase onto a6c808b68, which
  touched no GUI file); the 22 new cases again after it: pass.
- Full suite, go test -tags nogui ./... -timeout 45m, at bdc25ec13: not
  a record. The machine's data volume was full (897 of 926 GiB, 3.2 GiB
  free afterwards), and backup, mcpauth, davsync, provider, cli, gateway
  and gui failed on "no space left on device" or failed to build.
  maskrec passed in it. The whole GUI suite was not run for the same
  reason.

Not tried: clearing in the real app with a real masking folder.
2026-10-26 18:07:19 +08:00
yetone 44a626bed3 gateway: an image's detail reaches a Chat or Responses upstream; Responses' original goes to Chat as high (mysterious_dove)
mysterious_dove on Discord (Codex): a Responses request translated to
Chat Completions lost every image's detail, so detail=high and
detail=original were dropped. The IR had no field for it: Part now
carries Detail, read from a Responses input_image and a Chat image_url
object, in message content and in a tool's output (toolOutput).

- Chat (buildChat, chatImage/chatDetail): low, high and auto go as they
  came; Responses' original, which Chat lacks, goes as high; an image
  with no detail goes without one, as before. Both the message image
  and a tool's image (the follow-up user message) use it.
- Responses (buildResponses and the orphaned tool output rewrite,
  responsesDetail): the sibling. A Chat client's low/high, and a
  Responses client's original, reached a Responses upstream as auto.
  They now go as sent; anything else, none included, is still auto
  (#1474's strict vLLM needs one).
- Anthropic and Gemini have no such field; nothing is sent there.
  Ollama's native route has none either. buildChat/buildResponses are
  the one choke point for translations, plugins included.

The GUI "downgrade list" with "图片 detail=high 降级:丢弃" named in the
report isn't in magpie, the plugins repo or the site (grepped for the
labels, 降级, detail=, downgrade): it is not changed here.

Doc: docs/subsystems/gateway-routing.md gets a bullet beside the tool
images one.

Tests (internal/gateway/image_detail_chat_test.go):
- TestResponsesImageDetailReachesChat: high, original, low, auto, none,
  and a function_call_output image with original -> high, high, low,
  auto, "", high.
- TestChatImageDetailReachesResponses: low, high, none -> low, high, auto.
Red on the old code (chat.go, ir.go, responses.go stashed): Chat images
had detail "" for all four, Responses had "auto" for low and high.
Broken by hand (chatDetail returning "original" for original): red
with detail "original", want "high" on images 1 and 5.

Run:
- gofmt -l internal/gateway: nothing. go vet ./..., GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go
  build -tags nogui, GOOS=windows go build: ok.
- go test -tags nogui ./internal/gateway (sandbox HOME): ok 492s.
- Full go test -tags nogui -count=1 -timeout 45m ./... in a sandbox
  HOME at 22a563c4f (this change on 689cf4142), after another
  session's suite ended: 71 packages ok, internal/provider FAIL with
  "close of synctest channel from outside bubble" in filememo.Forget
  from TestUnreadLoginsWriteErrorsKeepCredentials: that is #3632, open,
  not touched here.
- Rebased on a6c808b68 (hermes.go, app.css, a GUI test, a doc: no file
  in common). The rerun at the pushed head could not build: the disk is
  full machine-wide ("no space left on device", 150MB free), so the
  tests were not run at the pushed head.

Not tried: a real Chat upstream reading detail (no reply differs in a
way a test can see without a vision model and a large image). No GUI
or i18n change, so no GUI run.
2026-10-26 17:58:26 +08:00
yetone a6c808b688 hermes: every bot still on magpie's model follows the model magpie sets (tjhhhh_84378)
Hermes copies the launch profile's model block into a new profile
(hermes_cli/profiles.py _seed_model_config, or --clone's config.yaml) and
never reads the main config again. magpie put its provider into each
profile but left each profile's model alone, so after a model change in
magpie every other bot (profile) still opened on the model magpie had set
when it was made (tjhhhh_84378 on Discord, with the Hermes gateway closed).

Now picking a magpie model for Hermes also moves each other profile whose
model.provider is magpie and whose model.default (or model.model, which
Hermes reads with default unset) is the model magpie had set onto the new
one (hermesFollow). "The model magpie had set" is recorded in stash.json
(hermes:<path>:magpie.default); for a config connected before the record,
it is the connected config's own magpie model. A profile on any other
model, magpie's or its own, was set by its user and is left alone, also
when it is on a model magpie used before. Disconnect forgets the record.
A profile made after the change is seeded from the current config, so it
starts on the new model already. RenameProvider goes through the same
field Set, so a renamed provider moves the following bots too.

Test: TestHermesProfilesFollowMagpieModel (internal/agent): a seeded bot
and a model.model bot follow pro -> flash (no record yet) and, through an
own model on the main config in between, -> max; a bot on magpie's
deepseek/lite and a bot on its own provider stay; a bot its user moved
back to the previous magpie model stays. On the old hermes.go it fails:
  hermes_test.go:613: flash: writer is on magpie/deepseek/pro, want magpie/deepseek/flash

Run:
- gofmt -l internal/agent: clean. go vet ./internal/agent on darwin,
  GOOS=linux -tags nogui and GOOS=windows: ok, at this commit (rebased
  onto origin/main 689cf4142; nothing under internal/agent changed in the
  rebase).
- go test -tags nogui -count=1 -run Hermes ./internal/agent at this
  commit: ok (33.6s). Whole ./internal/agent before the rebase: ok (307s).
- Full suite, go test -tags nogui ./... -timeout 45m -count=1, sandbox
  HOME, at a57d2460b (this change on 88ac42843): every package ok except
  two reds already filed on main, in packages this doesn't touch:
  internal/gui TestRestartHandsTheGatewayOver ("11 of 12 requests during
  the restart answered", #3451) and internal/provider's synctest crash in
  filememo.Forget from TestUnreadLoginsWriteErrorsKeepCredentials (#3632).
- Broken by hand: hermesFollow's call removed, the test goes red at
  hermes_test.go:613 as above.

Not tried: the real hermes binary (under a temp HERMES_HOME it rewrites
the live launcher); its seeding was read in hermes_cli/profiles.py.
2026-10-26 17:48:30 +08:00
yetone 6e96903346 codex: auto-review follows the session on a ChatGPT Free plan (cybercaius)
cybercaius on Discord measured codex-auto-review spending a Free
account's allowance ("实测在 free 账号不免费"). magpie left an unset
auto-review to Codex (codex-auto-review), and held such a call by no
usage cap, on #1593's finding that OpenAI counts it in no window; that
was measured on a paid account.

Decision: with nothing picked and Codex signed in to a Free plan (the
ID token's chatgpt_plan_type is "free"), auto-review counts as "Same as
the session", as Codex's other side calls do, so the review stops
spending the free allowance when the session is on one of magpie's
models. On Codex's own model nothing changes (its entries keep OpenAI's
reviewer). A paid plan, or a plan magpie can't read, keeps Codex's pick;
a pick in Settings always wins.

- codexcat.AutoReviewModel is the setting in effect; the plan comes from
  provider.CodexSignInPlan (liveLogin, keychain read cached), read once
  per model list, and the list tag already re-stamps on auth.json.
- freeOnChatGPT no longer exempts a Free plan's codex-auto-review call
  from usage caps (capHeld).
- GUI tooltip says it (en, zh, zh-TW, ja, de); docs updated.

Run at the pushed tree (on origin/main 88ac42843), go test -tags nogui
-count=1 -timeout 45m: internal/gateway ok 447s, internal/codexcat ok,
internal/gui ok, internal/agent/... ok; internal/provider crashes in
TestUnreadLoginsWriteErrorsKeepCredentials ("close of synctest channel
from outside bubble" in filememo.Forget), red the same alone on
origin/main 88ac42843, filed as #3632 with a patch there; with that
test skipped internal/provider ok 152s. gofmt -l clean; GOOS=linux go
vet -tags nogui ./... and GOOS=windows go vet ./... clean.
- GUI (chromium + webkit, every language): codex-auto-review, i18n-keys,
  gui-ja, gui-zh-tw, gui-de, search-keys, agent-prefs: 79 of 79 pass
Broken by hand: with AutoReviewModel returning the raw setting,
TestCodexAutoReviewOnAFreePlan fails; with freeOnChatGPT ignoring the
plan, TestAccountCapHoldsAutoReviewOnAFreePlan fails.
TestCodexSignInPlan reads a Free plan from a sandbox auth.json.
Not tried: a real Free ChatGPT account; whether OpenAI bills
codex-auto-review on Plus/Pro is still #1593's measurement.
2026-10-26 17:19:00 +08:00
yetone e0b39f7784 codex: titles, descriptions, predictions and memories follow the session's model (cybercaius)
cybercaius on Discord: after v0.1.1576 (a1174674d) Codex's subagents and
memories followed the session's magpie model, but the Codex app's
titles, descriptions and composer predictions, and memory consolidation
before any turn, still went to the ChatGPT sign-in's own models, and the
pickers had no "Same as the session" (跟随当前会话) option.

- Server.codexSessionOf is the session's model when it is one of
  magpie's: the model the conversation's own turns last went on
  (codexLeads: parent thread, own thread, else the key's last), else,
  before any turn came through magpie, Codex's config model
  (agent.CodexSideModel). A model turned off, gone or held from the
  caller's key gives "".
- codexSideTo (titles, descriptions, summaries) and now predictions take
  it when the setting is unset, so a session picked in the app, not
  only in config.toml, keeps them off the ChatGPT allowance. A session on
  Codex's own model leaves them as Codex sent them.
- codexFollowTo (subagents, memories) uses the same reader, so a memory
  consolidation Codex runs at start follows the configured model.
- GUI: the unset option of the titles, descriptions and predictions
  pickers is "Same as the session" now (it is what unset does), and the
  memories row says so; tooltips in en, zh, zh-TW, ja and de.
Zero config: nothing to set; an explicit pick still wins.

Run at the pushed tree (on origin/main 88ac42843), go test -tags nogui
-count=1 -timeout 45m: internal/gateway ok 447s, internal/codexcat ok,
internal/gui ok, internal/agent/... ok; internal/provider crashes in
TestUnreadLoginsWriteErrorsKeepCredentials ("close of synctest channel
from outside bubble" in filememo.Forget), red the same alone on
origin/main 88ac42843, filed as #3632 with a patch there; with that
test skipped internal/provider ok 152s. gofmt -l clean; GOOS=linux go
vet -tags nogui ./... and GOOS=windows go vet ./... clean.
- GUI (playwright 1.62.0, chromium + webkit, en/zh/zh-TW/ja/de):
  codex-titles, codex-descriptions, codex-predictions, codex-memories,
  codex-memories-settings, codex-auto-review, codex-subagent-model,
  codex-subagents-lead, agent-prefs, settings-general, i18n-keys, gui-ja,
  gui-zh-tw, gui-de, search-keys: 189 of 189 pass.
Broken by hand: with codex_follow.go/codex_titles.go/codex_backend.go
reverted, TestCodexAppSideTurnsFollowTheSession,
TestCodexAppSideTurnsStayWithAnOwnModelSession and
TestCodexMemoriesBeforeAnyTurnFollowTheConfig fail; reverting only the
predictions route fails the first one's composer_predictions case.
Not tried: a real Codex app session; the side calls were driven through
the gateway with recorded request shapes in a sandbox HOME.
2026-10-26 17:19:00 +08:00
yetone 083a8a2d47 gateway: a failed Codex compaction says what failed, never "Unknown error" (outrageous_piglet)
outrageous_piglet on Discord (magpie 0.1.1575): Codex's compaction ended
"Error running remote compact task: unexpected status 502 Bad Gateway:
Unknown error". codex-rs says "Unknown error" of an error status whose
body is empty or whitespace (UnexpectedResponseError::display_body).

Every path a compaction reaches, probed with a fake upstream answering
502/500/503/405/501 with an empty body, an HTML page and {"error":{}}:
- a magpie model (codexCompact, through serve, every wire): always a
  message, but a bare "Fake: 502 Bad Gateway" that doesn't say it was
  the compaction or where it went;
- Codex's own model on /responses: an empty body was already said
  (#409), a web page relayed as its markup;
- Codex's own model on /responses/compact (and compactOn's account):
  relayed byte for byte, so an empty body reached Codex empty. This is
  the path that gives "Unknown error".

Now:
- codexUpstreamOn says an empty or web-page error on /responses/compact
  as on /responses (codexSaidNothing): the model, the status, who it went
  to (Codex's sign-in, its API key, or the magpie account), and the page's
  title. An error OpenAI says in JSON still goes as it came.
- codexCompact's relayed failure is said as the compaction's, with who
  answered it (compactFailed), keeping the vendor's code, param and
  Retry-After.
- 405 and 501 join 404 (lacksEndpoint): the summary is asked again as
  text, then made locally, so a provider without the endpoint still
  compacts.

The reporter's provider and model aren't known, and their URL is
/responses, where magpie at 0.1.1575 already says an empty body; the
only empty relay found is /responses/compact. A proxy between Codex and
magpie answering 502 itself would also read so; not ruled out.

Run: go test -tags nogui -run 'Compact|Codex|NotAnAPI|Empty'
./internal/gateway ok. New tests TestCodexOwnCompactFailureIsSaid,
TestCodexCompactFailureSaysCompaction and
TestCodexCompactNoEndpointCompactsLocally fail with codex_backend.go
reverted by hand; TestCodexOwnCompactErrorAsSaid guards the unchanged
JSON relay and passes on both.
Run at the pushed tree (on origin/main 88ac42843), go test -tags nogui
-count=1 -timeout 45m: internal/gateway ok 447s, internal/codexcat ok,
internal/gui ok, internal/agent/... ok; internal/provider crashes in
TestUnreadLoginsWriteErrorsKeepCredentials ("close of synctest channel
from outside bubble" in filememo.Forget), red the same alone on
origin/main 88ac42843, filed as #3632 with a patch there; with that
test skipped internal/provider ok 152s. gofmt -l clean; GOOS=linux go
vet -tags nogui ./... and GOOS=windows go vet ./... clean.
Not tried: a real Codex against a real failing upstream.
2026-10-26 17:19:00 +08:00
yetone 634cbf587b agent: Claude Desktop on an imported profile for magpie's gateway is connected, and Reconnect keeps it
aa86222 on Discord: Claude Desktop's configuration (magpie's profile, with
the connectors added in it) exported on one computer and imported on
another becomes a new configLibrary entry under a random id Desktop makes
(createConfig in Desktop 2.7032's main process), applied beside magpie's
own. It points at this magpie's gateway, yet the Agents row said
"已不经过 magpie:配置已变更", since desktopCheck took any appliedId but
magpie's own as another gateway. Reconnect then applied magpie's own
profile, dropping the imported one with its managedMcpServers, and on the
old code a later switch-off applied the first entry left (CC Switch's).

Now an applied gateway profile whose inferenceGatewayBaseUrl is this
gateway (desktopIsOurGateway) counts as on magpie (desktopAppliedGateway).
Check reads its URL and key; Reconnect (desktopOn, when magpie's entry is
already listed) keeps it applied and leaves every setting in it as it is;
only a key this gateway would refuse (another magpie's named key) is set
to magpie's Desktop key, by Reconnect or by Sync at magpie's start
(desktopKeyApplied). magpie's own keys (gateway.Token, magpie-<agent>)
count as taken. A profile for another gateway (CC Switch) is still drift
and Reconnect still applies magpie's. The first switch-on still seeds
magpie's profile from an applied one (#2035, unchanged). appReads includes
the applied profile, so a key fix asks for Desktop's restart.

Run (macOS, sandbox HOME only, at 27ca0bef5 + this change):
- go test ./internal/agent -timeout 45m -count=1: ok (205s)
- gofmt -l internal/agent: clean; GOOS=linux and GOOS=windows go vet
  ./internal/agent: ok
- TestClaudeDesktopImportedProfileIsOnMagpie: fixture is _meta.json with
  CC Switch's entry (127.0.0.1:15721), magpie's, and the imported one
  applied, the imported profile carrying managedMcpServers.

Broken by hand: with claudedesktop.go put back to origin/main (and a stub
desktopAppliedGateway returning ""), the new test fails in 3 of 4
subtests: check says "uses another gateway configuration now", Reconnect
applies 00000000-…-6d6167706965, off applies CC Switch's entry, and the
other-magpie key is never fixed.

Not tried: a real Desktop export/import across two computers (the format
is from Desktop 2.7032's app.asar: configLibrary createConfig + writeConfig,
exportConfig); the GUI (no GUI file changed). Not changed: a machine
where magpie never connected Desktop and an imported profile is applied
still reads as not connected; connecting there seeds magpie's profile
from it (#2035).
2026-10-26 17:00:46 +08:00
yetone a7072926d6 agent: connecting Kiro Crew connects the harness it is set to (wuping9525)
wuping9525 (Discord, Windows): Kiro Crew's Agent Harness was Claude Code,
Claude Code was installed but not connected to magpie, and turning Kiro
Crew on refused with "connect Codex, Claude Code, ... first". On a Mac it
worked only because a harness (Codex/Claude Code) was already connected;
Crew's home is found the same way on Windows (USERPROFILE\.kiro\crew).

Now, when agent.acp_backend names one of magpie's harnesses (codex,
claude, opencode, pi, goose) and that agent is installed but not
connected, connecting Kiro Crew connects it in the same action and runs
Crew on it; the notice says so. The stash's kirocrew.joined records it.
Kiro Crew's Disconnect disconnects that agent again only if magpie
connected it and the user hasn't disconnected it since (kiroCrewUserLeft
in Agent.Disconnect); a disconnect the user made before stays recorded as
theirs. A failed Crew write undoes the join. config.local.json pins,
kas/kiro/deepseek and harnesses not installed behave as before.

Windows: the adapter search also tries npm's .cmd/.exe/.bat shim names,
and the app is detected by ~\.kirocrew-app\.venv\Scripts\kirocrew.exe.
New notice translated in zh, zh-TW, ja, de; docs/subsystems/agent-wiring.md
and docs/reference.md updated.

Run (macOS, sandbox HOME, GOMODCACHE/GOCACHE pinned), at base 11c3fbb19;
after rebasing on 2921471de (no change under internal/agent or internal/gui
since), go vet and go test -run 'KiroCrew|Disconnect' ./internal/agent
again: ok.
- go test -tags nogui -timeout 45m ./internal/agent ./internal/gui: ok
  (252s, 62s)
- new tests: TestKiroCrewConnectsItsHarness (real Claude Code wiring in a
  sandbox), TestKiroCrewLeavesTheUsersHarness (connected before, taken
  back after, off before), TestKiroCrewHarnessNotHere, TestKiroCrewOnWindows
  (kiroCrewOS forced to windows, PATH emptied)
- gofmt -l clean; go vet nogui for darwin, linux, windows; windows build
- GUI: agent-kiro-crew-lang, i18n-keys, gui-de, gui-ja, gui-zh-tw in
  chromium and webkit: 35/35 pass

Broken by hand, each red: no join (ConnectsItsHarness, taken back after,
off before), no kiroCrewUserLeft hook (taken back after), always forgetting
the user's disconnect (off before), no .cmd names and no venv exe
(OnWindows), no leave on Disconnect (ConnectsItsHarness, off before);
notice dropped from the NOTICES list: agent-kiro-crew-lang 9 red.

Not tried: a real Kiro Crew or Windows machine (the Windows box's ssh
timed out); the disconnect preview doesn't show the joined harness's
files, since it copies only Crew's folder.
2026-10-26 16:31:14 +08:00
yetone 56900e4845 agent: Claude Desktop on magpie gets the MCP servers the user added signed in (aa86222 on Discord)
aa86222 on Discord: Claude Desktop on magpie's gateway (3p mode) didn't
sync its connectors. Two parts:

- A claude.ai account's connectors can't reach 3p mode. Desktop calls
  them through claude.ai with the signed-in account
  (/api/organizations/<org>/mcp/servers/<id>/tools/call in Desktop
  2.7032's main bundle, refused with no_active_org without an account),
  and 3p mode has none. Anthropic's 3p docs say "Made by Anthropic"
  connectors are only in standard Desktop; others reach 3p through
  managedMcpServers or plugins
  (claude.com/docs/third-party/claude-desktop/extensions). magpie doesn't
  answer or pass any of these: they never go to the inference gateway.
- What magpie can do: 3p mode reads its MCP servers from
  Claude-3p/claude_desktop_config.json, a file of its own, so the
  servers added signed in (Settings -> Developer, in
  Claude/claude_desktop_config.json) were gone from the list. Switching
  on now copies each mcpServers entry Claude-3p has none of the same
  name for (desktopCarryMCP). One already there (the user's, or the
  Library's, which writes both files) stays. Sync does it once for a
  Desktop already on magpie (stash mark claude-desktop.mcp-seen), so a
  server the user takes out in 3p isn't brought back. Off takes back
  each copy still as copied (stash claude-desktop.mcp); one the user
  changed stays. Claude's own file is never written.

Run, at this tree:
- go test -count=1 -timeout 45m ./internal/agent ./internal/library
  ./internal/desktopdir: ok
- gofmt -l internal/agent: clean; go vet ./internal/agent for darwin,
  GOOS=linux and GOOS=windows: ok
- the built binary in a sandbox HOME (macOS): `magpie claude-desktop
  provider magpie` copied a filesystem server into Claude-3p's
  claude_desktop_config.json with Claude's file byte for byte; `provider
  ""` removed Claude-3p again, Claude's file unchanged.

Broken by hand: desktopCarryMCP returning at once turns
TestClaudeDesktopCarriesTheMCPServers, TestClaudeDesktopMCPKeepsThe3pServers
and TestClaudeDesktopSyncCarriesTheMCPServersOnce red; desktopUncarryMCP
returning at once turns the first two red (off left the copies); Sync
carrying on every run turns the third red.

Not tried: a real Claude Desktop reading the carried servers in 3p mode
(it reads ~/Library, so the sandbox can't host it, and the live one is
not touched); Windows and Linux folders (same code path through
desktopSets); the reporter's own connectors, which weren't described
beyond "can't sync" and are most likely claude.ai ones, which this
cannot bring.
2026-10-26 15:46:02 +08:00
yetone 4e5b2ad81c gateway: another magpie added by hand rests only the model it refused
lagrangepoint1813 on Discord: Pi on a magpie whose provider is another
computer's magpie got "Remote Magpie: Claude Code: You've hit your
session limit" for every model of it, whichever Pi was switched to.
remoteModelRest rests such a refusal by model (restID) only for the
Remote magpie preset; that magpie was added as an OpenAI-compatible
provider of the user's own name (preset null in providers.json, the
reporter found), so the 429 rested the whole key
(restKey) and quotaHeld answered every model of it from that rest for
the five hours it named. A magpie's reply names the provider that
answered or held it (X-Magpie-Provider), as no vendor's does: keepRetry now notes it as
answeredThereHeader (this magpie writes its own provider into the same
header of its reply, so it can't be read there; the note is kept from
the client), and remoteModelRest reads a refusal carrying it as another
magpie's model's, whatever the provider was added as. A quotaHeld or
verifyHeld answer now names its member too (noteMember), as an asked
one does, so a refusal the other magpie held is read the same. The
key's own limit there (remoteKeyLimitHeader) still rests it whole.

TestAnotherMagpieAddedByHandRestsTheModel (two gateways over HTTP; the
other magpie asking Claude Code, and already holding it): both subtests
red on the old code with the reporter's message, green with this
change; -count=3 with TestRemoteMagpie* and Verify* green. Broken by
hand: reading X-Magpie-Provider straight from the reply header rested
by model everywhere (TestOwnQuotaRest, TestVerifyRefusalRestsTheLastOne,
TestAntigravityQuotaStillRests, TestCodexCompactCutSummaryFailsOver,
TestOpenRouterFreeAccountRateLimitKeepsProviderRest went red, the header
being this magpie's own); without noteMember on the held answer the
held-there subtest stays red.

Run at this head (on origin/main a1174674d):
- go test ./internal/gateway -count=1 -timeout 45m, both
  commits together: ok (391s)
- gofmt -l internal/gateway: clean; go vet ./internal/gateway, also
  GOOS=linux and GOOS=windows: ok

Not changed: a held answer's "(out of its allowance: …)" is said
twice when the other magpie held it too (seen in the old code's red);
the model alone is held now, the wording is left as it was (#3701).
Not changed: a Remote magpie's key-limit header doesn't reach
remoteModelRest in the main loop either (keepRetry doesn't copy it),
filed as #3705. A reply from a hand-added magpie that breaks off after
its 200 still rests the key whole (no quotaHeld answer follows from it).
Not tried: the reporter's real Claude subscription on the other magpie.
2026-10-26 15:42:59 +08:00
yetone 7c2f27ccdf gateway: a strict conversation keeps its member past a reply that broke off
imwhatiam123 on Discord: a routing group of Qoder CN and WorkBuddy AI
set to Stays: Strict moved a session to WorkBuddy AI. A reply that
broke off after its 200 (#733, common from a plugin-served provider)
called unanswered, which forgot the stick, so the agent's retry was
routed as a new conversation (why "first", kept null) from the top of
the order. Strict promises the conversation never moves to another
account, member or key, its failure going to the agent: the stick is
now kept under strict, so the retry goes back to the same member,
fails there while it fails, and goes on there once it answers. The
member still rests for new conversations as before. Every other mode
forgets the stick as before.

TestStrictGroupKeepsItsMemberPastABrokenReply: red on the old code (the
retry went to second), green with this change.

Run at this head (on origin/main a1174674d):
- go test ./internal/gateway -count=1 -timeout 45m, both
  commits together: ok (391s)
- gofmt -l internal/gateway: clean; go vet ./internal/gateway, also
  GOOS=linux and GOOS=windows: ok

Earlier run at e5dd86965 (this change alone): one red,
TestStreamingRequestsLetTheirSentBodyGo (#3503, heap read), 5 of 5 alone.
Not tried: a real Qoder CN / WorkBuddy AI group; the break is the
test's fake upstream's SSE error after some text.
2026-10-26 15:42:59 +08:00
yetone a1174674da codex: subagents and memories follow the session's magpie model; auto-review can too (cybercaius on Discord)
Codex's side calls ask for one of Codex's own models by its bare name
whatever the conversation is on: a subagent goes on the model the lead
names in spawn_agent, memories on gpt-5.6-luna/terra, auto-review on
codex-auto-review. With Codex signed in to ChatGPT and the conversation
routed onto one of magpie's models, each of those went to the ChatGPT
account instead (cybercaius: "can't pick follow the main model").

- gateway (codexFollowTo, codexLeads): a collab_spawn or memory call
  that asks for a bare model, with nothing set for it (no magpie
  subagent model, no [agents] default_subagent_model, no [memories]
  extract/consolidation_model in Codex's config), goes on the model its
  conversation's own turns go on (parent thread, own thread, else the
  key's last turn), when that is a magpie model the key may use. A task
  the ChatGPT backend sealed stays on ChatGPT. The trace shows a
  subagent's pick as {asked -> to}.
- agent.CodexSideSet reads Codex's config.toml for those keys; an
  unreadable config counts as set (leave as sent).
- Auto-review gets "Same as the session" (settings value "session"):
  codexcat writes each magpie entry's own id as its
  auto_review_model_override. Not the default: codex-auto-review runs
  free on a ChatGPT sign-in (#1593).
- GUI: the option in all languages; Memories' default text says it
  follows the session. app.js stays under its budget by folding five
  identical writingPrefs then/catch chains into prefWrite.

Ran (sandbox HOME, -tags nogui -count=1 -timeout 45m):
- go test ./internal/gateway ./internal/agent ./internal/codexcat
  ./internal/settings ./internal/cli ./internal/gui: ok.
  ./internal/provider: FAIL with "close of synctest channel from outside
  bubble" in filememo.Forget (TestUnreadLoginsWriteErrorsKeepCredentials),
  which is #3632 on main; this change touches nothing there.
- TestCodexSubagentFollowsTheSession and TestCodexMemoriesFollowTheSession
  go red with codexFollowTo returning "" (broken by hand).
  TestCodexSideCallsKeepTheConfigsModel, TestCodexSideCallsStayOnChatGPT,
  TestCodexSideSet, TestCodexAutoReviewFollowsTheSession pass.
- GUI (playwright 1.62.0, chromium + webkit): codex-auto-review (en, zh,
  zh-TW, ja, de), codex-memories, codex-memories-settings, codex-titles,
  codex-predictions, codex-descriptions, settings-general, agent-prefs,
  i18n-keys: 120/120 pass. TestCoreScriptBudget passes, budget unchanged.
- gofmt -l clean; go vet -tags nogui for linux, windows and darwin ok.

Again after rebasing on origin/main 49f15d124 (25341b4ca on top touches
only internal/redact; rebuilt): nogui builds (darwin, linux,
windows), TestCoreScriptBudget, the tests above, and the GUI files 120/120.

Not tried: a real Codex with a real ChatGPT account and a relay model.
2026-10-26 15:35:12 +08:00
yetone 49f15d1244 masking: a record names the provider the request went to, not the group's first member (Max You and Linka on Discord)
Linka on Discord: Insights › Masking's records said WorkBuddy AI, the
first member of their auto group, for requests that Codex in the same
group had answered. Max You: providers no route sends to show up under
Privacy all the same.

Cause: serve() recorded the masking (noteMasked) as the route began,
with p.ID, the first planned provider, before any try. A request the
first member failed, or a member resting or unable to serve, went on
to the next, and the record (on disk, and counted into the flow and
the provider filter) kept the first. Embeddings recorded tries[0] and
video the same way.

Fix: maskrec.Hold keeps a record in memory at once (the route's badge
and the answer's Restored need its key) and writes it to disk only
when done is told the provider and model of the last try.
noteMaskedUntil wraps it, and serve, embeddings and video call done
in a defer with call.Provider and the model tried last. A request
that never reached a try keeps the planned one, as before. Since a
long request's line is now written after later ones, List sorts each
day's lines by key, so paging with before skips nothing.

Old records keep the name they were written with; there is no record
of which member had them. They leave with the 30 days.

Tests:
- TestMaskedRecordNamesTheProviderThatHadIt (gateway): a group a/m,
  b/m, a answers 500, b 200, with Mask secrets on; chat and
  embeddings. On the old code both subtests fail:
    masked_sent_test.go:96: recorded on "a", the request went to b
- TestHoldNamesWhoHadIt (maskrec): the held record goes on disk with
  done's provider and model, done's second call counts for nothing,
  Sum counts that provider, and List pages a late-written record in
  key order. With the sort taken out it fails on the first page.

Run at this tree (base a1e91e500), sandbox HOME, caches pinned:
- gofmt -l clean; go vet darwin, linux (nogui), windows on gateway
  and maskrec; builds darwin, linux nogui, windows.
- go test -tags nogui -count=1 -timeout 45m ./internal/maskrec/
  ./internal/gui/ ./internal/gateway/: ok, ok (75s), ok (523s).
- The full ./... suite was not run: other sessions held the machine's
  suite slot.

- Rebased onto ef0a03e13 (no change under internal/gateway or
  internal/maskrec since a1e91e500); builds on 3 OSes and the Mask/Hold
  tests of both packages ok again at the pushed head.

No GUI file changed. Not tried: a real group failover in the app.
2026-10-26 15:29:36 +08:00
yetone ef0a03e137 otel: Langfuse is set up from its host and the project's two keys
A user on X asked for Langfuse built in. magpie could already export to
Langfuse over OTLP, but Settings › Observability had the user type the
endpoint .../api/public/otel and a percent-encoded
Authorization=Basic%20<base64(pk:sk)> header by hand.

Settings › Observability now has a Collector row: OTLP or Langfuse.
With Langfuse, the user picks the host (Cloud EU, Cloud US, or
Self-hosted with an address, which also covers Langfuse's JP and HIPAA
regions) and fills in the public and secret keys. Once both keys are
there, magpie saves:
- the endpoint <host>/api/public/otel;
- Authorization: Basic base64(pk:sk), in otel.headers as before, so the
  secret is stored where it was and a backup without keys leaves it out;
- on a first setup, also x-langfuse-ingestion-version: 4, metrics off and
  export on. langfuse.com/docs/opentelemetry/get-started (read 10-26)
  gives the same header for every region and for self-hosted, and says
  that without it OTLP data can arrive up to 10 minutes late.
A Langfuse endpoint set up by hand opens in this view with its keys
decoded into the fields. Opening it saves nothing. Changing a key or the
host keeps the user's other headers, their metrics and export choices,
and an ingestion header they set or left out. Switching from another
collector leaves that collector's headers behind and does not send them
to Langfuse.

The Observability page moved from app.js into the otel plugin
(assets/plugins/otel/page.js, with i18n.js for its words, in Client),
because app.js had 13 bytes of budget left. The app.js and core budgets
are lowered to what is left (1,321,319 and 1,537,645; app.js is
1,321,313 after rebasing on 2620dc319). "Collector" and "Secret key" go
in the core i18n.js because other files use the same words.

Docs: reference.md's Langfuse paragraph (with the env form for magpie
serve) and the en/zh/ja privacy pages.

Run (macOS):
- go test ./... -timeout 45m -count=1 at the pre-rebase head (parent
  e5dd86965): every package ok but internal/provider, which crashed in
  TestUnreadLoginsWriteErrorsKeepCredentials with "close of synctest
  channel from outside bubble" in filememo.Forget. That is #3632, red on
  main since 091153bf7.
- The whole GUI suite (make test-ui, concurrency 4, Chromium and WebKit)
  at the same head: 16 reds. Each red file was run alone here and at the
  parent e5dd86965. The same reds came back at both: menu-input-scroll
  (#3402), old-webkit (#3403) and plugin-card-update's webkit Update
  (#3079). The parent also failed fonts' webkit run. page-width,
  api-key-theme, panel-arrange, panel-balance-order, own-requests,
  library-mcp-health-wsl and plugin-list-error passed alone here: 137
  passes, 7 fails, all of them the three filed above.
- At the pushed head (rebased on origin/main c87a0179b): the budget
  tests; otel, otel-langfuse, i18n-keys, settings-sections, builtins,
  idle-ticks and page-width, both engines, 58 pass; go test
  ./internal/otlp ./plugins/otel ./internal/gui, all ok except
  TestRestartHandsTheGatewayOver (#3451). That test failed 1 of 8 here
  and 1 of 8 on origin/main dce7fe609.
- Before the rebase: otel-langfuse (new: first setup, US, self-hosted,
  hand setup kept, another collector's headers dropped, 5 languages at
  1100/520/360px) with otel, i18n-keys, settings-sections, builtins,
  readable-focus, segs-press-redraw, ux-safety, dialog-backdrop-drag and
  mono-icon-redraw: 113 pass. go vet for darwin, linux and windows on the
  touched packages; gofmt -l clean.
- Broken by hand: with every save treated as a first setup and the old
  collector's headers carried over, otel-langfuse's "set up by hand keeps
  its values" and "another collector's headers" went red.
- New TestOTelLangfuseSetup: settings saved as the page writes them reach
  a fake collector at /api/public/otel/v1/traces with the Basic header and
  ingestion version 4, and nothing on /v1/metrics.
- Real app: a -tags dev build in a sandbox HOME (ports 3461/3462). I
  drove its real Settings page with Playwright: Langfuse, then
  Self-hosted http://127.0.0.1:3463, then both keys. settings.json got the
  endpoint, Basic header, version 4 and enabled. A gateway request then
  reached a local fake collector at /api/public/otel/v1/traces with
  Authorization Basic base64(pk-lf-real-ui:sk-lf-real-ui) and
  x-langfuse-ingestion-version 4.

Not tried: a real Langfuse Cloud or self-hosted project (no account here),
so Langfuse accepting the spans and how they show in its UI aren't checked.
The TUI and magpie serve still have no Langfuse shortcut; serve takes the
env form in reference.md. The Linux app (WebKitGTK) and Windows weren't
tried; the change is form fields and segs, with no motion.
2026-10-26 15:11:37 +08:00
yetone fed0055da8 plugin: a plugin stuck on its vendor no longer holds up the plugins loaded or listed with it
shualaitianduai on Discord: a plugin whose sign-in kept failing (401)
held up the plugins behind it. host.js loaded the plugins one after
another and answered init only when all were in, so a plugin function
that never returned held every other plugin until init's two-minute
deadline failed the whole host. providers() listed the providers one
after another too, so one stuck models hook held the whole list past
refreshDeadline (30s), and every provider's list went stale.

Now loadPlugins loads every plugin side by side, each given
pluginLoadWait (20s) for its import and plugin function, and each
config hook as long; one still loading is told as not loaded ("the
plugin's load didn't finish in 20s") and init answers with the rest.
Hooks are kept in the list's order, as before. providers() lists every
provider side by side and gives each models hook pluginListWait (20s,
inside refreshDeadline): one that hasn't answered is listed as fallen
back with that as its listError, so magpie keeps the list it had, and
that answer isn't kept for requests (keepInfo). Documented in
docs/subsystems/provider-plugins.md.

Run at this head (base origin/main e5dd86965), sandbox HOME, caches
pinned:
- TestStuckPluginLoadHoldsNoOther and TestStuckModelListHoldsNoOther
  (testdata/stuck): red on origin/main's host.js ("Plugins = [],
  starting plugins: context deadline exceeded" after 30s; "Providers
  = [], context deadline exceeded" after 15s), green here (2.1s each).
- go test -count=1 -timeout 45m ./internal/plugin/: ok (165s).
- go test ./internal/provider/: ok with
  -skip TestUnreadLoginsWriteErrorsKeepCredentials, which crashes with
  "close of synctest channel from outside bubble" in filememo.Forget,
  filed as #3632 and not touched here.
- go test -run Plugin ./internal/gateway/: ok.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags
  nogui on internal/plugin: ok.
Not run before the push: the whole go test ./... (run after it); not
tried with the reporter's own plugin, which wasn't named.
2026-10-26 15:09:09 +08:00
yetone a1e91e5002 davsync: S3's If-Match/If-None-Match go outside the signature, so a kept ETag no longer turns a working key into 403 (CyberCaius on Discord)
CyberCaius on Discord: S3 backup works, then every sync fails with
"the S3 server refused the access key ID or secret (HTTP 403
SignatureDoesNotMatch)", and edits to the S3 settings "won't save".
The keys work in other S3 clients, and switching to WebDAV and back
to S3 fixes it until the next time.

Cause: the SigV4 signer signs every header on the request, and
7ab91961d's conditional requests added If-None-Match (GET, the ETag
kept in sync-state.json) and If-Match (PUT). SigV4 needs only host
and x-amz-* signed. A server, or a proxy in front of it, that checks
the signature over a condition as it reads it back rather than as it
arrived refuses a signed one with SignatureDoesNotMatch. The first
sync has no ETag kept, so it passes; from the second on every sync is
conditional and refused. WebDAV and back changes stateKey, so the
state starts again with no ETag and one sync works. "Won't save" is
the same 403: /api/davsync/save writes the settings and then syncs,
and the form stays open with the sync's error.

Fix: sendTo signs every header except if-*, and sets the conditions
after signing. The docs page says so.

Test: TestS3ConditionsOutsideTheSignature, where the fake S3 rereads
an If-* header without its quotes before checking the signature. It
syncs three times, saves a second provider and syncs again, and
checks that the conditional GET and PUT reached the server.
On the old s3.go it fails with the reporter's text:
  s3_test.go:612: sync 2: the S3 server refused the access key ID or
  secret (HTTP 403 SignatureDoesNotMatch)

Run at this head (base e5dd86965), sandbox HOME, caches pinned:
- gofmt -l: clean. go vet (darwin), GOOS=linux go vet -tags nogui and
  GOOS=windows go vet on internal/davsync; builds for darwin, linux
  nogui and windows: ok.
- go test -tags nogui -count=1 ./internal/davsync ./internal/cli
  ./internal/gui (each package that imports davsync): davsync and cli
  ok. gui had one red, TestRestartHandsTheGatewayOver ("9 of 10
  requests during the restart answered", connection reset). That is
  #3451, at load 50; it passes 3 of 3 alone. Commented on #3451.
- No full ./... suite: other sessions were running full suites on
  this machine (gateway, agent).

Not tried: the reporter's own S3 vendor, which isn't known yet.
2026-10-26 15:08:14 +08:00
yetone e5dd86965b pii: the masking model's requests take turns without holding the status, Stop or a restart (#3682)
After a restart, with Settings → Privacy's local model on, every request
queued for minutes on srv.mu in classify. That lock was held across
start() (up to 3m loading) and the model's answer (30s and more), and
Now(), Stop() and the idle timer took it too. The user saw a 504
"held this request for 2m0s without routing it to any provider".

Now:
- pf-serve's requests take turns through a one-slot channel (`turn`),
  so writes on its one pipe never interleave. srv.mu only guards state.
  Now() never waits: it reports Loading and how many are Waiting. Stop()
  never waits either: it kills a pf-serve that is loading or answering,
  and the request on it fails with errStopped (no retry). Fetch's
  upgrade stops pf-serve only once its turn is free (stopWhenFree).
- A request waits for its turn under its own context (FindContext). The
  gateway passes the request's context through a new gwmw.ContextTeller,
  so a client that went away, or a request the gateway answered 504,
  leaves the queue. A turn already begun still finishes and caches.
- What Find learned is kept on disk (found-<model sha>.bin, beside the
  model): a text's sha256 and its spans' offsets and labels, never the
  text. Written via temp-and-rename. A bad, cut-short or over-long file
  is read as empty, and a cached span that doesn't fit its text is
  asked again. A restart no longer asks about every history again.
- A request waiting for its turn reads the cache again when it gets it,
  so requests queued with the same history ask the model once.
- The guarantee stays: a request the model can't mask is held back, never
  sent masked by the rules alone. A wait that ends panics inside
  gwmw.Safely, as a failed model did, and the request fails closed.
- The 504 for a request held while masking says it waited for the local
  masking model, what the model was doing (loading, or masking another
  request with N waiting), that what it read is kept, and that the model
  can be turned off in Settings → Privacy (unroutedMsg).

Tests (each red on the fix broken by hand, in the sandbox HOME):
- TestStatusAndStopDontWaitForARequest / ...ForALoad: red with Now()
  taking the turn (Now waited), and the suite hung with Stop() taking it.
- TestWaiterLeavesWhenItsContextEnds: red with the waiter ignoring ctx.
- TestQueuedRequestReadsWhatTheOneAheadLearned: red without the re-read.
- TestRestartReadsWhatWasFound: red with loadCache a no-op. It also
  checks the file never holds the text.
- TestBadCacheFileIsReadAsEmpty: red with a cut-short file's entries kept.
- TestCachedSpanOutsideItsTextIsAskedAgain: red without the fits check.
- gateway TestHeldForTheMaskingModelSaysSo: red with the masker handed
  context.Background() (the wait never let go), without noteMasking, and
  with the old message. TestUnroutedMsgNamesTheModelOnlyWhenItIsOn: red
  with the old message.
- TestMaskingOnAndOff's panicky fixture embeds masking.Masker, which now
  has the Context methods. It panics on those too, and still refuses.

Run at this head (base origin/main 098ac9696, fetched before the commit),
in a sandbox HOME, load ~25:
- go test -timeout 45m -count=1 on internal/pii, internal/redact,
  internal/gwmw, internal/gateway, internal/gui and plugins/redact/...:
  all ok, apart from TestMaskingOnAndOff (the fixture above). After its
  fix, internal/gateway and internal/pii were run again whole: ok.
  internal/masking has no tests.
- go test -race -count=1 ./internal/pii/: ok.
- gofmt -l clean; go vet ./... (darwin); GOOS=linux and GOOS=windows
  go vet -tags nogui on the changed packages and internal/gui, and
  go build -tags nogui ./...: ok.

Not tried:
- A real pf-serve and model: everything above ran against the test's
  stand-in pf-serve. A real cold restart with the model on was not timed,
  and neither was Windows CPU.
- pf-serve is not warmed when magpie starts, so the first request after
  an update to the model still waits for its load. That wait now says so
  and can be left.
- The GUI does not show Loading/Waiting yet; GET /api/privacy-model carries
  them (status.loading, status.waiting).
2026-10-26 14:15:53 +08:00
yetone 13f9c7fca1 claude bridge: a caller elsewhere is told its environment is where the tools run
vv_nil on X: a Mac Claude Code through a Linux gateway's Claude
subscription gets Claude Code's own prompt from the gateway's run, which
names Linux and a temp folder, beside the caller's, which names the Mac
and its project. The model spent extra tool calls finding out whether its
environment had changed. A run that can't work in the caller's folder
(the folder isn't on this computer, or Claude Code is in WSL) now has
envElsewhereNote after the caller's instructions: the environment they
describe is where every tool runs, and goes before one given earlier.
Every tool of a run is the caller's, so that is true. The note names no
app or vendor. A run in the caller's own folder, a lean run and a caller
naming no folder are told nothing more. clientWorkDir is split so
clientNamedWorkDir gives the folder named, wherever it is.

Run: go test ./internal/gateway -run
'Claude|Bridge|Subscription|Lean|Vendor|Prompt' (ok, 49s), go vet for
linux and windows, gofmt -l. TestClaudeCallersWorkDirElsewhereIsNotUsed
now checks the note in both runs for a folder not here, a relative one
and a Windows path, and not for no folder; TestClaudeRunsInTheCallersWorkDir
checks a run in the caller's folder isn't told it. With envElsewhere
forced false by hand the first is red (0 of 2 runs).
Not tried: a real Claude Code run from a Mac client through a Linux
gateway, so how many tool calls it saves is not measured.
2026-10-26 11:01:58 +08:00
yetone c2c88e85e9 redact: a date in the last year or ahead is not a birthday
JackyCcao on X: under Mask personal data the birthday rule took the day
the agent ran on, 2026-10-24, for a birthday in 122 requests. dateOK now
takes a date after 生日/DOB/born for a birthday only when it is over a
year before today (dateClock, held in the test). A date in the last year
or ahead is a run date, a deadline or a log's; a baby's birthday in a
prompt is far rarer than those. Older dates are masked as before.

Run: go test ./internal/redact (also TZ=UTC and TZ=Pacific/Kiritimati),
go vet for darwin, linux and windows, gofmt -l. TestBirthdayNotRecent
holds today at 2026-10-24 (today, yesterday, a year less a day, ahead,
each format) and then reads the real clock; with the year check taken
out by hand it is red ("生日:2026-10-27" masked). The GUI's
redact-kinds test only toggles the category and is unchanged.
Docs: gateway-routing.md and masking.html (en, zh, ja).
Not tried: the reporter's own request text (the screenshot shows only
the masked date), so which words were before it is not known.
2026-10-26 10:57:18 +08:00
yetone 7499ebb5ef gateway: magpie goroutines answers ahead of the locks a stuck request holds
Two users on X (v0.1.1549 to v0.1.1557, Windows, Codex routing) see
/api/hello answer while /v1/models, Providers and agent requests hang.
`magpie goroutines` (b18a6a080, #3362, since v0.1.1404) can capture the
stuck process, but its route sat behind lanGuard's allow list
(settings.json's file lock) and holdCatalog (provider.Hold, filememo),
so a request stuck holding any of them would hang the dump too.

dumpFirst serves GET /v1/magpie/goroutines, for callers
goroutinesRefused lets in, ahead of lanGuard in Front and ahead of
counted/holdCatalog in Handler. It reads only the request, the
environment and the runtime. Every refused or other request goes on
as before; a caller it lets in is one lanGuard and corsGuard already
let in (loopback, unproxied, no browser marks, loopback Host).

docs/reference.md now says how to run it from an app install, where
magpie isn't on PATH unless Settings > Command line adds it:
macOS /Applications/magpie.app/Contents/MacOS/magpie goroutines;
Windows PowerShell
  & (Get-ItemPropertyValue 'HKCU:\Software\Microsoft\Windows\CurrentVersion\App Paths\magpie.exe' '(default)') goroutines | Out-Host
(| Out-Host so PowerShell waits for the GUI-subsystem exe), or a
portable copy's own path.

Run, at this tree on c0985122b:
- go test -tags nogui -count=1 -timeout 45m ./internal/cli ./internal/gateway:
  ok cli 36.2s, ok gateway 388.7s
- TestGoroutineDumpAnswersWhileRequestsWait -count=3: ok
- gofmt -l: clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/...: exit 0

Broken by hand:
- Front back to lanGuard(s.Handler()): the new test is red at 20.02s
  ("the dump didn't answer while settings.json's lock was held").
- Both refusal checks (dumpFirst and goroutineDump) removed:
  TestGoroutineDumpOnlyToThisComputer red, 25 failure lines.

Real use, Windows box: v0.1.1558 magpie-windows-amd64.exe (SHA256
matches SHA256SUMS) serving a sandbox home on :3447; the App Paths
one-liner above saved the dump and printed "goroutines 41", exit 0;
`& exe goroutines` with and without | Out-Host both saved it.

Not tried: a really stuck app; this build on Windows or macOS (the
real-use run above was v0.1.1558, without dumpFirst); an interactive
PowerShell console without | Out-Host; the Handler-only path has no
red test, since provider.held can't be held from the gateway package.
2026-10-26 05:53:34 +08:00
yetone 3b717d5e0d affinity: a Claude Code subagent's answer no longer moves its lead off its account's cache
Claude Code sends its session's id (x-claude-code-session-id) with every
request of the session, its subagents' too; only x-claude-code-agent-id
says a request is a subagent's. Affinity kept one stick per scope and
session, so a subagent on the lead's model wrote its own answer over the
lead's stick. The lead's next turn was then judged by the subagent's cache
("no-cache" for a small one, "cold" for a 5-minute write past five
minutes) or kept wherever the subagent had gone, and with two Claude
accounts it moved to the other one: a new Claude Code there was told the
whole conversation and Anthropic wrote it all to that account's cache
again, at the 1-hour write price (slkassinthehood on X: two Pro accounts'
5 hours spent in ten minutes, ~318k tokens a request).

stickKey keeps a subagent's stick apart, by its agent id. The lead's key
is the session's, as before: sticks on disk are found after the upgrade,
and Codex's leadFirst, which reads a lead's stick by its thread id, is
unchanged. strictKeep reads the same key.

Run, at this commit's tree (base 42ec2700b):
- TestClaudeConversationKeepsItsAccountsCache: two Claude accounts (fake
  Claude Code reporting a 300k 1-hour write), least-used routing, a lead
  conversation through the gateway with Claude Code's headers. Red on the
  old affinity.go: after a subagent's turn the lead was answered by tok-b
  in a new Claude Code, logged "a new Claude Code is told the whole
  conversation: 7 messages"; also red 20 minutes on. Green with the fix:
  the lead stays on tok-a, in the same Claude Code, every step.
- go vet -tags nogui ./internal/gateway/
- go test -tags nogui ./internal/gateway/ -run
  'Affinity|TestClaude|Strict|Rotate|Codex.*Lead|LeadFirst|Subagent|HourCache': ok
- Full suite (go test -tags nogui ./... -timeout 45m, suite-lock, sandbox
  HOME, at 5e566f0c3 on base 42ec2700b): 70 packages ok, internal/gateway
  ok (675s); internal/provider FAIL: "close of synctest channel from
  outside bubble" in filememo.Forget under
  TestUnreadLoginsWriteErrorsKeepCredentials, red on main since 091153bf
  and filed as #3632. Not touched by this change.
- After rebasing onto origin/main 5214d5114 (the two claude bridge fixes):
  gofmt -l, go vet and go test -tags nogui -timeout 45m ./internal/gateway/
  at cf69f883b's tree: ok (419s).

Not tried: the reporter's own accounts and client; whether their lead
moved this way is not known from their screenshot (it shows the hour's
total, not reads against writes).
2026-10-26 02:21:36 +08:00
yetone 5214d5114f claude: a run on a new account's first turn keeps its tool results
On the first request on a newly seen Claude sign-in, claude auth status
has no email yet, so the account is named from its plan ("Claude Max").
The bridged run's Claude Code then writes the profile, the account is
named by its email, and the turn's tool results came under another owner:
"tool results account changed", the run let go, and a new one told the
whole conversation (~8k more cache writes). Seen in a real run as
"claude\x00Claude Max\x00own" -> "claude\x00<email>\x00own".

- provider: Account.Unnamed marks the placeholder name;
  ClaudeOwnName gives the own sign-in's name once it has one.
- gateway: the run's owner is an atomic pointer (owned()); an own,
  unnamed owner ends in "\x00unnamed". takeNamedOwner lets such a run go
  on as the same provider's own sign-in, named; every other owner change
  still lets the run go. A turn that ends without a tool call takes the
  name before its keys are made (nameOwner), so the next turn finds the
  idle run.
- docs/subsystems/claude-subscription-bridge.md says so.

Run:
- TestClaudeToolResultsKeepTheSelectedAccount gains "named since" (kept)
  and "unnamed, another account" (let go);
  TestClaudeRunTakesOnlyItsOwnSignInsName; TestClaudeIdleRunKeptUnder-
  ItsOwnSignInsName (named since / still unnamed); provider asserts
  Unnamed on the plan-named account and not on an email-named one.
  Broken by hand: without takeNamedOwner in serveSubscription "named
  since" goes red (a new run replies); renaming any own owner goes red
  (a@ -> b@ taken); without nameOwner the idle case goes red; with
  unnamed never set the provider test goes red.
- Real run: sandbox HOME, dev build of this tree on 127.0.0.1:3741, the
  owner's Claude Max sign-in with .claude.json and logins.json removed
  first (auth status: no email), a real Claude Code 2.1.310 client in a
  sandbox config asked to write, wc and read pelican.html. One Claude
  Code pid for the whole turn, the log says the run "goes on as" the
  email, no "account changed" line. Before this change the same setup
  logged the owner change and "tool results account changed".
- gofmt; go vet darwin, linux -tags nogui, windows for gateway and
  provider; go test ./internal/gateway ok 392.7s; go test
  ./internal/provider ok 89.3s with -skip TestUnreadLoginsWriteErrors-
  KeepCredentials, which crashes the package on main alone (#3632,
  filememo synctest, not this change).
- Full suite at this tree (3ea0dd908, committed first as 3a201180b on 42ec2700b): go test
  -tags nogui -count=1 -timeout 45m ./... -skip TestUnreadLoginsWrite-
  ErrorsKeepCredentials (#3632): exit 0, 71 packages ok, no FAIL in the
  kept log. No other suite ran on the machine (no suite-lock script
  here; ps checked before the start).
Not tried: a sign-in switch mid-turn from one named account to another
(still lets the run go, by the test).
2026-10-26 01:59:38 +08:00
yetone 680b505687 claude: a run works in the caller's own folder, not magpie's temp folder
The bridged Claude Code told its model "Primary working directory:
<tmp>/magpie-claude-work-501", against the folder the client's own prompt
names. Under a real Claude Code client the model wrote pelican.html into
magpie's temp folder, through the client's tools, which run in the
client's folder.

startRun now runs Claude Code in the folder the caller names
(clientWorkDir): the last one in the system prompt or a non-assistant
message, as Claude Code ("Primary working directory:"), Codex (<cwd>),
OpenCode ("Working directory:") and pi ("Current working directory:")
write it, when it is an absolute path to a folder here. Otherwise (a caller
elsewhere, a WSL Claude Code, no folder named) the shared folder as before.
The caller's project's sessions are never swept; a run's session is still
removed by its id. CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=1 keeps the
repository's status out of the prompt (setting sources and auto memory
were off already). The text sent upstream is unchanged apart from the
folder Claude Code reports itself.

Run:
- TestClaudeRunsInTheCallersWorkDir (Claude Code, Codex, OpenCode, pi,
  named twice) and TestClaudeCallersWorkDirElsewhereIsNotUsed (missing,
  relative, Windows path, none): red on the old code (the runs used the
  shared folder). Broken by hand: sweeping the caller's folder goes red
  ("were swept"); dropping the env var goes red ("repository's status").
- Real run: sandbox HOME, dev build of this tree serving 127.0.0.1:3741 on
  the owner's Claude Max sign-in (keychain linked in, login copies deleted
  after), a client Claude Code 2.1.310 with its own CLAUDE_CONFIG_DIR,
  ANTHROPIC_BASE_URL at the sandbox, run in $SB/wm and asked to write
  pelican.html: it landed in $SB/wm; nothing new in magpie-claude-work-501
  (its only pelican.html is the capture's, from before).
- go test ./internal/gateway at the staged tree (checkout-index), gofmt,
  go vet; the full suite run is recorded in the next commit, at the pushed
  head.
Not tried: a Windows client (a Windows path falls back, by the test), a
Claude Code in WSL (falls back by code).
2026-10-26 01:48:52 +08:00
yetone a60493ab60 gateway: Codex run by Claude Code's Codex plugin is counted as Codex, not Claude Code
wyztony on X: "claude通过/codex skill时,用量不会记录codex的记录".
OpenAI's Codex plugin for Claude Code (codex-plugin-cc 1.0.6,
/codex:rescue and /codex:review) runs `codex app-server` with clientInfo
named "Claude Code". Codex 0.162.1 then sends "originator: Claude Code"
and "User-Agent: Claude Code/0.162.1 (...) (Claude Code; 1.0.6)", so
agentOf read every such turn as Claude Code's ("claude") and the Usage
page showed none of them under Codex.

agentOf now takes a "Claude Code" name back to Codex when the request
carries Codex's own turn headers (x-codex-window-id or
x-codex-turn-metadata), which Claude Code itself (claude-cli/...) never
sends. An app running Codex as its own engine under its own name (Lody)
keeps its name, as TestFromCodex already holds. fromCodex is unchanged,
so nothing sent upstream changes. Every path keyed on agentOf
(Codex subagent pick, spawn_agent models, drawing route, Codex backend
records, titles, search, active sessions, callerOf) follows.

Run:
- TestCodexPluginForClaudeCodeIsCodex: red on the old code with the
  check turned off by hand ("plugin task: recorded as \"Claude\", want
  \"codex\""), green with it. Cases: the plugin's captured headers,
  originator only, claude-cli, the name without Codex's turn headers,
  Lody with them.
- Real use in a sandbox HOME: codex-cli 0.162.1 wired to a sandbox
  `magpie serve` on a fake Responses upstream, driven by the plugin's own
  codex-companion.mjs (db52e28). Before: task and review rows were
  "agent":"claude". After: both "agent":"codex". Plain `codex exec` (a
  skill-folder /codex skill) was already "codex" through the gateway and
  read from its rollout when direct.
- gofmt; go vet darwin, linux, windows.
- Full suite (go test ./... -timeout 45m, one suite on the machine) was
  started at this tree and was still running at push; per the owner's
  ship-at-once rule, a red it finds goes in its own commit.

Not changed, outside magpie: with Codex not routed through magpie,
/codex:review runs an ephemeral thread and Codex writes no rollout, so
there is nothing on disk for magpie to read; /codex:rescue writes one
and was already counted as Codex. Past rows stay under Claude Code.
2026-10-25 23:02:33 +08:00
yetone 41b0445ccf provider: a local server's address is a field shown first, and address= on the command line (LM Studio on another computer)
mengxiangziyou on X: "供应商里的LM Studio只能用本地的,怎么用局域网里其他机器
上的LM Studio, baseUrl 不能改". Moving a local preset (Ollama, LM Studio,
oMLX, MLX-Serve) to another host has worked since #1165, but the window
put the Address in a "Server address" fold under the key, while the
Endpoints row showed http://localhost:1234/v1 as plain text. Reproduced
in a sandbox: Add > LM Studio shows the URL and nothing to change it
with unless the small fold is found.

- GUI: the Server address field is shown first, above the key, never
  folded, for a new provider and a saved one alike (its label and hint
  are the strings the fold used, so no new i18n keys). Saving still
  sends the URLs moved only when the address was changed.
- CLI: `magpie provider add|set <id> address=<host:port>` moves every
  URL the provider has (chat, Anthropic, Responses, decision), each
  keeping its path; from the preset's when it was saved with none, and
  `address=` alone puts a local server back at its preset's. A provider
  of the user's own moves its own URLs. Vertex refuses it as it does
  url=. Before, Ollama on another computer needed url= and anthropic=.
- TUI: unchanged (asked on adding, `w` after).
- docs/subsystems/providers-accounts.md: Local servers row.

Security: only upstream URLs move. The gateway's own loopback/origin
guards are about inbound requests and don't read them; the one rule
that looks at an upstream being on the LAN (Unredacted) stays the
user's own switch.

Run at this tree (origin/main 642180a80 + this change; rebased onto
2f44e075a, which touches none of these files, then build, the new CLI
tests and local-address.test.cjs run again there: ok):
- New TestProviderAddressMovesALocalServer and TestProviderAddressPairs
  (internal/cli): fail on the old providers_cli.go with `unknown field
  "address"`, pass with it.
- local-address.test.cjs (both engines, en/zh/zh-TW/ja/de, 900 and
  440px): with the old app.js 3 subtests fail at "shown when added,
  nothing to open"; 22/22 pass with it.
- GUI files add-sheet, decide-endpoint-label, local-address,
  nokey-editor, provider-insecure-tls, remote-magpie, provider-unmasked,
  i18n-keys, gui-de, gui-ja, gui-zh-tw: 161/161 pass.
- go test -tags nogui -timeout 45m ./internal/cli ./internal/provider
  ./internal/tui ./internal/gui in a sandbox HOME: all ok.
- gofmt -l clean; go vet (darwin), GOOS=linux go vet -tags nogui,
  GOOS=windows go vet on internal/cli; go build, GOOS=linux go build
  -tags nogui, GOOS=windows go build: ok.
- Real use, sandbox HOME, built binary (-tags dev): a fake LM Studio
  bound to the Mac's LAN address 10.0.0.111:41234. The window's Add >
  LM Studio showed the field; typing 10.0.0.111:41234 and Add saved
  chat http://10.0.0.111:41234/v1, listed lmstudio/lan-qwen-9b from
  that host (GET /v1/models there), and a chat completion through the
  gateway reached it. `provider set lmstudio address=` put it back at
  http://localhost:1234/v1; `address=10.0.0.111:41234` moved it again
  and the next request went there.

Not run: go test ./... over every package (other sessions' suites on
this machine, load ~60), the whole GUI suite, a real LM Studio on a
second machine, the Windows and Linux apps.
2026-10-25 20:29:22 +08:00
yetone 5be7d05d28 agent: Desktop on magpie offers its own import of the signed-in sessions (lambdua on X)
lambdua on X: "claude Code桌面端支持么? 我桌面端切换账号,对话都能全都不见".
Nothing is lost. Desktop on magpie runs in 3p mode, whose userData is
Claude-3p, a folder apart from Claude/. Desktop 2.7032 keys Code and
Cowork sessions by account and org (claude-code-sessions/<acct>/<org>):
in 1p the claude.ai login's, in 3p the install id in ant-did and a fixed
org. So the sessions made signed in stay in Claude/ untouched and show
again when Desktop is switched back; claude.ai chats are on Anthropic's
servers. magpie's on/off never writes or removes a session (desktopOff
removes only what magpie made, and only when empty).

Desktop has its own importer (Settings -> Import: the signed-in userData,
other Claude* folders, ~/.claude/projects; copies under new ids, originals
left), but in 3p only when the profile's claudeAiImport.enabled is true
(3p-only policy, default off, since 1.28929.0). magpie's profile now gets
"claudeAiImport":{"enabled":true,"bannerBehavior":"detect"} once per
folder set (desktopSeedImport, stash mark claude-desktop.import): on the
switch on, and from Sync at magpie's start for a Desktop already on
magpie. A claudeAiImport already there is kept; one the user removes is
not written back (the mark is read, never unstashed).

Run (suite at origin/main 5df62c5cd, then rebased on 2f44e075a):
- go test ./internal/agent/ -run Desktop -count=1: ok.
- go test ./... -timeout 45m -count=1 at 5df62c5cd (log kept whole):
  every package ok but two reds already on main and filed:
  TestFolderVarsAreListed (#3600, fixed in 2f44e075a) and
  TestNoCommandBypassesProc (#3567, internal/tui/keep.go, open).
- after the rebase onto 2f44e075a: go test ./internal/agent/
  ./internal/proc/ -count=1: agent ok; proc red on #3567 only.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/agent/
  ok; GOOS=windows go build ./... ok; GOOS=linux go build ./internal/agent/
  ok (the CLI and GUI need Wails' cgo, not cross-built here).
Broken by hand:
- desktopSeedImport returning at once (the old code): TestClaudeDesktopFresh,
  TestClaudeDesktopOnKeepsTheUsersOwnGatewayProfile and the new
  TestClaudeDesktopOffersItsSessionImport go red.
- the mark read with unstash (consumed on read): the new test goes red
  with "seeded again over the user's choice". My first draft had this
  bug; the test found it.
Schema checked in Desktop 2.7032's asar (read-only, extracted to a
scratchpad): claudeAiImport is a flat leaf key whose value is the object
{enabled, bannerBehavior}, gated in 3p on enabled === true.
Not tried: a real Desktop in 3p mode with the key (would mean running
Desktop against the live userData); the live Claude folders were only read.
2026-10-25 20:29:08 +08:00