Commit Graph
2204 Commits
Author SHA1 Message Date
yetone ac4af58230 gateway: a LazyCat app is shared at its own domain, and a cgroup v2 container is known
mtoolstec on X runs magpie in LazyCat (懒猫微服) and, with "Share on
local network" on, Settings offered http://172.28.3.65:3425: the
container's own address, which nothing outside the box reaches, and no
hint that it was a container's.

LazyCat injects LAZYCAT_APP_DOMAIN (magpie.<box>.heiyu.space) into every
container of an app and serves the app there over HTTPS. The
magpie-lzcapp package sets MAGPIE_PUBLIC_URL=https://{{.S.AppDomain}}
through a manifest template, which only lzcos 1.3.8+ renders; unrendered,
url.Parse refuses the "{" host and publicURL() was "" (the log says
"ignoring invalid MAGPIE_PUBLIC_URL"). A hand-written manifest may not
set it at all. Then ContainerAddrs() needed inContainer(), which knew
only Docker's and Podman's marker files and a runtime's name in PID 1's
cgroup. Under cgroup v2 with a private cgroup namespace (Docker's
default since 20.10) /proc/1/cgroup is "0::/", and a runtime that writes
no marker file got past it, so the container's addresses were listed as
the computer's.

- publicURL() falls back to https://$LAZYCAT_APP_DOMAIN when
  MAGPIE_PUBLIC_URL is unset or invalid (a DNS name only; lower-cased).
  Everything built on PublicURL follows: LANURLs, PublicHost (the
  rebinding Host check), magpie web's links and trusted origin, the
  image MCP base, the CLI's advertised URL. InContainer() is true there
  too (updates go through the image).
- inContainer() also takes a container's init as PID 1 (magpie itself,
  as our image starts it; tini, docker-init, dumb-init, catatonit), and
  a cgroup namespace's root ("0::/") on an overlay root filesystem
  (/proc/1/mountinfo). Neither alone catches a host: a systemd host is
  in /init.scope even on a read-only overlay root, and an init without
  cgroups on ext4/btrfs is not overlay. hostNetwork is unchanged, so a
  container on the host's network still lists the host's addresses.

What the user sees: in LazyCat, "Share on local network" shows
https://magpie.<box>.heiyu.space (and the Gateway URL is that domain).
In any other cgroup v2 container on a bridge network without a marker
file, Settings shows the container hint to set MAGPIE_PUBLIC_URL.

Run:
- TestInContainer (13 fake roots: systemd host, systemd on overlayroot,
  cgroup-less init on btrfs, WSL, markers, cgroup v1, kubepods, cgroup v2
  on overlay, magpie/docker-init/tini as PID 1) and TestLazyCatPublicURL
  (LazyCat domain, mixed case, the unrendered template, MAGPIE_PUBLIC_URL
  winning, bad domains) pass on Linux (wsl-run, magpie-desktop).
- Broken by hand: with origin/main's lan.go both tests are red (4 and 4
  cases).
- Real systems: the WSL2 distro (systemd host, 0::/init.scope) reads
  inContainer=false. Docker 28.2.2 on xiaomi-gpu, debian:12-slim with
  /.dockerenv removed (cgroup "0::/", overlay root, PID 1 sh) reads
  inContainer=true hostNetwork=false; with --init (docker-init) true;
  with --network host inContainer=true hostNetwork=true, so it still
  isn't called a container's addresses.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., and the darwin/linux nogui/windows builds pass on mote at
  the first base (ddd6c649b); after the rebase onto 7 newer main commits,
  go vet ./internal/..., linux and windows vet of gateway/gui/cli and the
  build pass on mote.
- Linux (wsl-run): internal/gateway ok (1230s) at the rebased head;
  internal/cli (1707s) and internal/gui (624s), -tags nogui, ok at the
  first base.
- Not run: the full ./... suite. It was queued on mote's suite.lock
  behind ~15 other sessions' runs for 46 minutes and I stopped it; CI
  runs it on this push. No GUI file changed.

Not tried: a real LazyCat box (none here); the env names and the
https domain are from developer.lazycat.cloud/advanced-envs and the
lazycat-contrib/magpie-lzcapp manifest.
- After a last rebase onto fdd38154b (6 commits in usage, library,
  providers, settings and docs; none in internal/gateway), nothing was
  run again.
2026-11-10 00:10:23 +08:00
yetone ddd6c649b3 draw: a plugin's model that says it gives images alone is an image model
maonekone (Discord #feedback, 11-09): a plugin can't say which of its
models draw; magpie took a plugin's image model only by its name
(DrawsID and ImagesAPI words). Now a model the plugin lists with
modalities.output ["image"] (no text), on its openai-compatible API, is
listed among the drawers and drawn at the images API through the
plugin's fetch, whatever its name. A model that answers in text and
images still chats.

Run (mote): TestPluginDeclaredDrawerDraws red on the old code ("drawers
[]"); with only the listing change, red again (the draw went to chat
completions); green with both. go vet ./internal/gateway ok; go test
-run "Draw|Image|SenseNova|Loomy|Plugin" ./internal/gateway ok (74s).
Not tried: a real plugin declaring such a model; the full suite.

Reported-by: maonekone (Discord #feedback)
2026-11-09 22:39:41 +08:00
yetone 39569d5604 claude desktop: an optional Claude Magpie app beside your own Claude (#5671)
baranwang on X asked to keep Claude Desktop's own (1P, Anthropic) sign-in
while using magpie. Turning on "Separate app" in Claude Desktop's row on
the Agents page (or `magpie claude-desktop launcher add`) moves magpie's
3P wiring into ~/Library/Application Support/Claude-Magpie-3p and adds
~/Applications/Claude Magpie.app. That launcher opens Claude.app with
--user-data-dir on that folder, so it runs side by side with the user's
own Claude.app. Its icon is Claude's icon with a magpie badge. Off is the
default, and turning it off (`launcher remove`) moves the wiring back
and removes the app. It is macOS only: Desktop's packaged app strips
CLAUDE_USER_DATA_DIR, and on Windows it hardcodes LOCALAPPDATA\Claude-3p.
The folder ends in -3p because Desktop adds -3p to any other name.
Restarting the isolated app ends only its own process (pkill on its
--user-data-dir) and opens the launcher again.

Run at 1b25cda26 (this change on origin/main be9dbce02); rebased onto
fdabddeb4 (catalog only), then go build ./..., vet and the budget and
launcher tests again: ok. All
on mote:
- gofmt -l clean; go vet ./internal/...; GOOS=linux go vet -tags nogui
  and GOOS=windows go vet on agent, cli, desktopiso, desktopdir, gui.
- go test (whole packages) desktopiso, desktopdir, settings, settingsapi,
  proc: ok. -run Isolated|TestDesktopInstance|TestAddStartsDesktopOnTheFolder|
  TestScript|TestAddLeavesTheirs|ClaudeDesktop|Restart in agent;
  TestClaudeDesktopLauncher|TestEveryRouteHasACommandOrIsNamed|Help in cli;
  TestCoreScriptBudget|TestSettingsSaveKeepsWhatItDoesNotSend|Budget|Desktop
  in gui and gateway: ok.
- An earlier full `go test ./...` at fef23255f had four reds, all from
  this change and fixed here: the route without a command (now in
  notYet), settings_keep's DesktopIsolated, os/exec instead of proc, and
  the core script budget (paid by sharing the switch helper with the
  largest-window line and cutting comments; no raise). A second full run
  of the touched packages queued ~7h on mote's suite lock behind other
  sessions and was stopped; the targeted runs above replace it.
- GUI on mote, both engines: desktop-isolated (new; en, zh, zh-TW, ja,
  de; 1100 and 640; aria-checked, posts, status text, no scroll, no
  select, absent without `isolated`), desktop-longest, click-scroll,
  plain-names, i18n-keys: ok. page-width-steady, panel-fold and
  zero-priced-free are red, the same 33 tests at origin/main be9dbce02
  (diffed): #4541/#5013, #5796, #5262. i18n-keys' "a plugin's words are
  its own" is red on main too (#5332).
- Whole GUI suite on WSL at an older head: 400 of 22778 red across
  ~100 files of other pages, in line with #5559 (478 of 21666 on main
  there). Not rerun on mote.

Real use, on mote in a sandbox HOME with Claude.app 4.23118 linked in:
`claude-desktop magpie`, then `launcher add`, moved the wiring to
Claude-Magpie-3p (deploymentMode 3p, mcpServers and locale carried).
Opening Claude Magpie.app started Claude with
--user-data-dir=.../Claude-Magpie-3p; it wrote configLibrary and
model-catalog there (3P mode) and no -3p-3p folder. A second, 1P Claude
ran beside it on its own sandbox folder. Opening the launcher again
kept one instance; the pkill pattern matched only the isolated pid; both
quit on SIGTERM. `launcher remove` put the wiring back and removed the
app.

Broken by hand: a folder without -3p (Desktop made -3p-3p), the
CLAUDE_USER_DATA_DIR env route (ignored by the packaged app), os/exec in
the quit (TestNoCommandBypassesProc red).

Not tried: a screenshot of the running app (screencapture fails over
ssh); a model request through a gateway from the isolated app; Windows
and Linux (not offered there). Known: the Dock shows Claude's own icon
for the running isolated app, and Chrome pairing is off in a moved
userData folder.
2026-11-09 22:31:16 +08:00
yetone 88b541a25c images: every pointer names Settings › Models › Images, where the page is
The image models moved under Settings › Models, but the Library's Magpie
Image sheet, the MCP server's instructions to agents, the gateway's
"no image model" errors, the video tool's text and the docs still sent
users to "Settings › Images", a tab that no longer exists (the scattered
settings audit after netube99 on X). Every user-facing string now names
Settings › Models › Images in en, zh, zh-TW, ja and de, as do the site's
Qwen docs (en, zh, ja), llms-full.txt, the subsystem pages and comments.

Run in the tree with this change and the rest of the audit's fixes
(mote, base cd0ba05c2):
- go vet ./internal/gui ./internal/gateway ./internal/agent
  ./internal/provider ./internal/settingsapi: ok
- go test -run 'Image|Draw|Video|Hidden|Group|Settings' ./internal/gui
  ./internal/gateway ./internal/settingsapi: ok; ./internal/imagemcp,
  ./internal/library, ./internal/catalog: ok
- GUI: i18n-keys, i18n-en-no-cjk, image-models-hide,
  library-browser-setup: pass in Chromium and WebKit
- gofmt -l: nothing
Not tried: a real agent reading the new MCP instructions (text only).
2026-11-09 21:51:53 +08:00
yetone dae104bfac capre: a length check, not an unrolled repeat, holds nine patterns
Go's regexp unrolls a bounded repeat into that many copies of its
class: [A-Za-z0-9.-]{0,254} (the session terminal's bundle id) was
89kB of program, kept from start to exit, and Codex's item-id refusal
`.{0,1000}?` 88kB. Measured one by one over magpie's 540 package-level
patterns (1.5MB in all), the nine largest bounded ones were ~440kB.

capre.MustCompile(expr, max) is the pattern with * or +, matching only
a string of max characters at most (rune count, so the (?i) Kelvin
sign and invalid bytes count as the regexp counted them). The nine:
settings' bundle id, library's name and agent id (now name@wsl:distro
cut in two), Anthropic tool names, the trace page's name and find,
access's MCP server, OpenClaw's profile and Codex's provider id. The
item-id refusal is a function: the tail within 1000 characters of a
head.

Run on mote (go1.26.8):
- go test ./internal/capre ./internal/access ./internal/settings
  ./internal/library ./internal/sessions ./internal/agent ./internal/gui
  . : ok; ./internal/gateway -run 'ItemID|Undeclared|ToolName|Refus': ok
- TestCappedMatchesBounded holds each old pattern against its new one
  over 14 units x 19 lengths (0..300, at each bound +-1); with the
  length check taken out it is red (1586 mismatches).
  TestItemIDRefusalAsTheRegexp holds the function against the old
  regexp at 998..1002 characters of x, é, 日, \xff, \n; with 1001 it is
  red. TestCappedIsSmall: 1304 bytes held, 49680 bounded.
- go vet native, GOOS=linux and GOOS=windows over the touched packages
  (gui natively: its Linux build needs cgo); gofmt -l clean.
- Real build, GODEBUG=inittrace=1: magpie's own inits allocate
  11.93MB -> 10.61MB.
- Idle on the real-account copy, 180s heap: regexp programs (sampled)
  4.54MB -> 3.01MB.

Not tried: the full ./... suite; the gateway package beyond the run
above.
2026-11-09 21:47:24 +08:00
yetone c056b7c8c3 provider: a Responses provider's turns may go over the Responses WebSocket (#5781)
A provider the user added with an http(s) Responses address can now send
its Responses turns over the Responses WebSocket that magpie already
speaks to chatgpt.com (codexSocket), with `socket=auto|on|off`:

- off, or absent: today's behaviour exactly. Provider.Via hides any
  socket value an outer context carried, so such a provider never dials.
- auto: tries the socket, falls back to HTTP when the handshake is
  refused or the socket ends before the reply, and speaks HTTP to a host
  for 10 minutes once it refused the handshake (codexShun).
- on: the same fallback, but never shuns; the socket is tried each turn.

Provider.Via puts the provider's Responses host and path in the request's
context (withSocket); codexSocket's gate is provider.SocketTurn, which
takes a ChatGPT turn as before, or a POST to that host at
<Responses>/responses. The rest is the ChatGPT leg's: the kept socket and
its delta (codexKeepKey now also hashes the scheme, X-Api-Key and
Api-Key), the error frames, 1009 handling. A provider's reply with no
Content-Type is marked text/event-stream, since it is read as one.
Routing, keys, limits, usage and masking are unchanged: only the
transport under the request differs.

Set with `magpie provider set <id> socket=auto|on|off` (refused on a
provider with an account, no http(s) Responses address, or Vertex,
TakesSocket), saved in providers.json as "socket", shown by `provider
show`, and in the editor's Advanced as a WebSocket tick beside HTTP
version (ticked saves auto, keeps a CLI's on, unticked saves off; shown
only while the Responses address is http(s) and there is no account).
docs/subsystems/providers-accounts.md describes it.

app.js pays for its rows by three long comments cut to one line
(renderMove, the vendors' status pages, header rows): the core's scripts
are 478 bytes smaller than on 0eac4e6aa (1,533,069 of 1,533,802); no
budget raised.

Run on mote at this change on origin/main 0eac4e6aa (since then main
added a39b63e88 and 7cabf0da9, internal/sessions only):
- gofmt -l clean; go vet (darwin) of provider, gateway, cli, gui, clean.
- go test -tags nogui ./internal/gui ./internal/cli: ok;
  ./internal/provider -run TestSocket: ok.
- go test ./internal/gateway -run 'TestResponsesProvider|TestCodexSocket|
  TestCodexKept|TestCodexTurn|TestHTTP1|TestInsecureTLS': ok. The new
  tests use an httptest WebSocket upstream: a turn over the socket, a
  provider without the field never dialling (and one on the same host
  with it), a refused handshake shunned on auto and tried again on on, a
  socket closed before the first event going over HTTP, the kept
  socket's delta on the next turn, and the reply being a stream.
- node --test provider-socket (new; chromium and webkit, en zh zh-TW ja
  de, 1100 and 420 wide), provider-http1, provider-insecure-tls,
  i18n-en-no-cjk: pass. i18n-keys' "a plugin's words are its own" is
  red for three words in files this doesn't touch, filed as #5327/#5332,
  #5426 and #5482.
- One rebase earlier (on 2a48974e8, the same change): GOOS=linux (nogui)
  and GOOS=windows go vet of the four packages clean, and the whole of
  ./internal/provider ok.
- Broken by hand, each red then green: SocketTurn codex-only (all six
  gateway tests red); a path-suffix gate in place of the context
  (WithoutSocketNeverDials, TestSocketTurn red); the never-shun case
  removed (RefusedOnTriesAgain red); the Content-Type line removed
  (ReplyIsAStream red).

Not tried: a real Responses upstream speaking the WebSocket (no network
in tests); the keep key's X-Api-Key/Api-Key separation has no test of
its own; the editor in the Linux app's WebKitGTK; the full suite (run
after the push).

Reported-by: matrix0487 (Discord)
Reported-by: faithleysath (#5781)
2026-11-09 18:57:29 +08:00
yetone 40cbdaa7e8 provider: an account's window can be capped at a fixed amount of its unit
A window magpie reads with a total and a unit (a day's 1000 credits, a
plan's requests) can now be capped at an amount of that unit, not only
a share: 9won_25273 asked to stop an account at 300 of its day's credits.

- AccountWindowAmounts keeps it per account and window (capId). An
  amount and a window's own share replace each other.
- WindowCaps.limitShare turns it into a share of the total for the mark
  and NearCap. CapHeld and capReached hold the account once the window's
  count reaches the amount (past), and rest it as the percentage cap
  does: the next account takes the request. cappedError and the trace
  say "has used 300 credits ... past its cap of 300".
- A reading with no total ignores the amount; the account's share
  applies.
- GUI: the window meter's menu has one more item, Amount..., typed in
  place (provider/windowcap with amount). It shows only on a window
  with a unit and total. Strings in zh, zh-TW, ja, de.
- CLI: magpie provider account-cap <id> <account> --window <name>
  --amount <n|off>.

Usage outside magpie counts: every cap reads the vendor's own count, so
what the account spent in the vendor's app or on another machine counts
from the next reading on. magpie can only hold back its own requests.

Run, at this head on Linux (wsl-run, magpie-desktop):
- gofmt -l: clean; go vet ./... for linux (-tags nogui) and windows: ok (darwin
  vet needs cgo, so it runs with the full suite on mote afterwards)
- go test -run 'Lang|ToolLoop|LoopGuard|Cap|Amount' ./internal/gateway
  ./internal/provider ./internal/cli: ok (TestWindowAmountCapHeld,
  TestSetWindowAmount, TestWindowAmountHoldsTheAccount, the CLI cases)
- GUI window-cap, window-cap-pool, account-cap in chromium and webkit,
  420 and 1100 wide, en zh zh-TW ja de: 78 of 78 in each engine. An
  earlier webkit run lost the amount test's page once ("Target page,
  context or browser has been closed"); it passed in 2 more full-file
  runs and 60 of 60 alone
- i18n-keys: only "a plugin's words are its own" red, words that aren't
  this change's (#5332, #5426, #5482)
Broken by hand: limitShare ignoring amounts (of < 0): TestWindowAmountCapHeld
and TestWindowAmountHoldsTheAccount go red.
Not tried: the full go test ./... at this head (queued on mote, runs
after); a real account at an amount cap.
iFlytek: 9won's 讯飞 overshoot isn't covered. Loomy's daily window sends
used as a count and amount as what is left (plugins#889); AStudio's
wallets tell a balance only, which no cap can hold (#5770).

Reported-by: 9won_25273 (Discord)
2026-11-09 18:19:02 +08:00
yetone 3245b730d2 gateway: the tool-loop notice is written in the conversation's language
When magpie stops a conversation going round one tool call, the notice the
agent shows was English only and began "magpie stopped this turn". A
conversation in Chinese got an English notice. The notice goes upstream
with the next turn, so it now names neither magpie nor a vendor's limits.

conversationLang (reply_lang.go) reads the user's own words in the whole
body. It skips tool results, system prompts and whole <tag> blocks, and
decides by script: kana -> ja, Hangul -> ko, Han -> zh or zh-TW (by
simplified/traditional-only characters), Latin with German marks -> de,
otherwise en. toolLoop.notice(lang) picks the matching text; the setting
is named as the GUI names it in that language (Korean, which the GUI
lacks, names it in English).

Run, at this head on Linux (wsl-run, magpie-desktop):
- gofmt -l: clean; go vet ./... for linux (-tags nogui) and windows: ok (darwin
  vet needs cgo, so it runs with the full suite on mote afterwards)
- go test -run 'Lang|ToolLoop|LoopGuard|Cap|Amount' ./internal/gateway
  ./internal/provider ./internal/cli: ok
  (TestLangOfEachLanguage, TestConversationLangReadsTheUsersWords: each
  language, mixed, empty; TestToolLoopNoticeInTheConversationsLanguage)
Broken by hand: counting kana as Han in langOf; all three tests go red.
Not tried: the full go test ./... at this head (queued on mote, runs
after), a real agent looping in Chinese. The reply loop guard's notice
(loop_guard.go) is still English and names magpie: #5764.

Reported-by: tenacious_eagle_96548 (Discord)
2026-11-09 18:19:02 +08:00
yetone 0024660445 gateway: a key's slot is taken before an account's turn near its cap
ox0pine on X: a gateway key held to one provider sometimes hung "in
routing". With the key's MaxConcurrency set and its account within 5
points of a usage cap, two turns could each wait for what the other
held:

- Turn B took the account's near-cap turn, then the key's slot (kept for
  the whole request, key_slots.go), and got a passing failure (503).
- B slept and went back to the same account (i--). At the top of the
  loop it gave the near-cap turn back.
- Turn A, waiting for that turn, took it and waited in keySlot for the
  key's slot, which B held.
- B found the turn taken, was the last candidate and waited in
  nearCap.take, which A held. Neither could move until its agent hung up.
  Neither had a try that could start, so the GUI showed "routing…".

serve now takes the key's slot before the near-cap turn, so locks are
always taken key, near-cap turn, lane. The wait still counts in the try's
Queued (nearInKey). Eager routes already took the slot before serve.
forward and codexUpstreamOn take it in their handlers and never take a
near-cap turn.

TestKeySlotAndNearCapTurnNeverWaitOnEachOther: one Codex account at 89%
with a 90% cap, a key held to codex/* at MaxConcurrency 1. The first
try gets a 503, and a second turn is sent while the first is paused.

Run on mote (mote-run):
- the new test on the old serve: red 5 of 5 (both clients time out at
  8s). Green after, and green without the key's cap on the old code.
- -run 'NearCap|Key|Cap' -count=2: ok.
- go vet ./internal/gateway for darwin, GOOS=linux and GOOS=windows;
  gofmt -l clean.
- rebased on origin/main f5f68b433, then again: -run 'NearCap|Key|Cap'
  ok (70s), vet darwin/linux/windows ok, gofmt clean.
- full go test ./internal/gateway -timeout 45m through lockf
  ~/suite.lock: not run. It waited 1h17m behind other sessions' suites
  for the lock and is still queued; shipped without it (owner: never
  hold a verified fix behind a full suite).

Not the reporter's case. They later said (v0.1.3371) the key's one
provider is a custom API-key provider, and the row clears by itself in
about a minute. This hang needs a subscription account near a usage cap
and never clears by itself. A probe of a custom key provider behind a
held key (Models plan/*, Accounts held to one of two keys; plain, 429s
and patience, MaxRPM 1, MaxConcurrency 1) had a try in the trace that
matched the order at every 150ms poll, so the Routing page would read
"answering", not "routing…". Their ~60s wait is not found yet.
2026-11-09 18:15:24 +08:00
yetone 8cecbcec9b gateway tests: nearCapAccounts waits for a reading of its own
nearCapAccounts made Codex's allowance stale and polled Allowances until
it said the wanted share. A test before it that left the same share in
usedCache (one that only read usage, sending no turn) let the poll pass
at once on the old reading, while the reading it had asked for was still
out. That reading landed after the test's first reply was heard (92%)
and put the account back at 89%, so TestNearCapWaitsThenHolds sent the
second turn too: codes map[200:2].

It now waits through provider.ReadUsageNow, which waits for a reading
begun after it asked.

Run on mote (mote-run):
- a setup-only test (codexSignedIn, newNearCapBackend at 89,
  nearCapAccounts) beside TestNearCapWaitsThenHolds, -count=6: red 4 of
  6 before, ok after.
- -run 'NearCap|Key|Cap' -count=2: ok.
2026-11-09 18:15:24 +08:00
yetone 2b22425b45 agent: Claude Science in a WSL distro is found and run on magpie from Windows
shuitunlulu_ (Discord) has Claude Science in WSL2, and Windows magpie
didn't find it. It is now a WSL twin (claude-science@wsl:<distro>), found
by the probe's claude-science (~/.local/bin or PATH). Its daemon is
restarted there through wsl.exe with ANTHROPIC_BASE_URL set, the same steps
as this machine's (claudescience.go is now one scienceHost for here and for
each distro), and v0.1.3334's keeper puts it back on magpie in each running
distro that has a note (claude-science-wsl-<distro>.json). With no note,
nothing runs in WSL.

The daemon takes http only to a loopback address and sends its Claude
sign-in as the key. In mirrored networking it gets the gateway's address.
Under NAT magpie starts a relay in the distro: socat on
127.0.0.1:<gateway port> to Windows' WSL address. The daemon gets
http://127.0.0.1:<port>/<WSL key>; the gateway's lanGuard takes the key
off the path (takeWSLPathKey) before fromWSL judges it. Connect says so
when the distro has no socat. Disconnect stops the relay with the
connections it forked, as one process group. When Windows' firewall keeps
WSL out, the row shows the same firewall drift and rule as other WSL
agents.

Run:
- gofmt -l clean
- go vet: darwin, GOOS=linux -tags nogui, GOOS=windows (mote)
- go test ./internal/agent ./internal/gateway on mote (macOS)
- go test ./internal/agent on xiaomi-gpu (Windows 11): 26 FAIL; 25 fail
  the same at origin/main c7ebb6f8d on that box (#4115, #5019, #3700,
  #5344, #2808, #4785, #2958, #1827, #4786). The 26th,
  TestHermesProfilesFollowMagpieModel, passed 5/5 alone on both and
  failed only in the whole-package run (#4115, #2540). Every
  ClaudeScience test passed there.
- At the pushed head (rebased on 9dd7aabca, which changes neither
  package): go vet darwin + windows and -run 'ClaudeScience|WSL' of agent
  and gateway ok on mote.
- Full suite, -timeout 45m: not finished at push. It waits on the lock
  behind other sessions' runs on mote and on magpie-desktop; the
  packages it changes (agent, gateway) were run above.
- Real run against magpie-desktop (Ubuntu 24.04, NAT, claude-science
  0.1.72 in ~/.local/bin) from a Windows test binary, with a sandbox
  XDG_CONFIG_HOME and a stand-in gateway on 127.0.0.1 and 172.17.32.1:
  - Connect took about 10s, and /proc/<daemon>/environ had
    ANTHROPIC_BASE_URL=http://127.0.0.1:<port>/wsl-...
  - The relay outlived wsl.exe (setsid, its own SID).
  - With the firewall blocking the test binary, the row's drift named the
    firewall and the New-NetFirewallRule.
  - With a temporary allow rule for the test binary (removed afterwards),
    curl in WSL through the relay reached the stand-in with the key path,
    and no drift showed.
  - Daemon and relay were killed as a WSL restart would; one keeper pass
    brought both back.
  - Disconnect left no relay and no relay forks (a held curl fork
    included), and the daemon ran without the variable.

Broken by hand:
- relay := false: the NAT test went red six ways.
- Without lanGuard's takeWSLPathKey line: TestWSLKeyInPath got 403.
- Check's firewall branch off: TestClaudeScienceInWSLFirewall red.
- A plain kill of the relay pid left a fork connecting on the real distro;
  that is what led to the process-group kill.

Not tried:
- The real magpie GUI on Windows with this build.
- A daemon's own model request through the relay; only curl was sent.
- Bridged networking.
- A distro without socat; that path was run only in the fake.

Reported-by: shuitunlulu_ (Discord)
2026-11-09 17:46:13 +08:00
yetone a6a99717e0 gateway: thinking with no signature never goes to Claude
citricdu (Discord, 0.1.3356): Claude Code auto-compacted a session on a
Smart group that had moved to Cursor's Grok 4.7, then the group went
back to Kiro's Claude Opus 5.5. The compacted history kept a thinking
block Grok made, which magpie hands a Messages client signed "", and
Kiro answered 13 times in a row with a bare invalid_request_error. The
same request without the block was answered.

withoutForeignThinking dropped only DeepSeek's UUID-signed blocks and
kept an empty signature on purpose ("a block with no signature Claude
takes"), and Kiro's refusal names nothing boundRefusal reads, so
refuseBoundThinking never mended it. Now every thinking block whose
signature is empty, blank or missing is left out for an upstream
serving Claude (api.anthropic.com, or a claude- model: relays, Bedrock
and Vertex ids, a plugin's fetch such as Kiro's), on every route
forwardOnce takes (relayed, translated, plugin, count_tokens), and
refuseBoundThinking runs it too. Text, tool_use and tool_result stay;
Claude's own signed thinking and redacted_thinking are untouched. A
model that learned thinkingBackNeeded (DeepSeek under another name)
keeps its unsigned blocks. Chat and Responses translated into Messages
already dropped unsigned thinking in anthropicBody.

Tests: TestUnsignedThinkingNotSentToClaude builds the reporter's shape
(the compaction summary, then two tool turns opening with Grok's
thinking signed "") against a fake Kiro that gives the same bare 400,
relayed and through the fake plugin's fetch (FAKE_KIRO model added).
TestGrokThinkingThenClaude runs the switch itself: a group answered by
a Chat Grok, then moved to Claude mid tool loop.
TestWithoutForeignThinking adds an unsigned block, Bedrock and Vertex
ids, a missing and a blank signature.

Run (mote, at this head rebased on 136178803):
- gofmt -l: clean; go vet ./internal/gateway: clean
- go test -run 'TestUnsignedThinkingNotSentToClaude|TestGrokThinkingThenClaude|TestWithoutForeignThinking|TestDeepSeekThinkingThenClaude|Bound|TestPluginBoundThinkingLeftOut|ThinkingBack' ./internal/gateway: ok
Broken by hand: the old predicate (DeepSeek signatures only, the
"signature" precheck only) put back: TestWithoutForeignThinking,
TestUnsignedThinkingNotSentToClaude/relayed and
TestGrokThinkingThenClaude fail (Kiro relay 400 "Improperly formed
request."). The plugin subtest passes on the old code too.
Not run before push: the full suite and the Linux/Windows vet; they
are queued behind other sessions' suites, and their result follows.
Not tried: a real Kiro or Anthropic account; Kiro's exact error text
is the reporter's description, not captured bytes.

Reported-by: citricdu (Discord)
2026-11-09 17:24:09 +08:00
yetoneandreyoung 4314f4b776 otel: export the gateway key's name as magpie.gateway_key.name (#5751)
reyoung (#5751) shares one magpie through several gateway keys and wants
requests in Langfuse or another collector told apart by key. The ledger
row already had CallerKeyName, but the OTLP allow-list dropped it, and
the observer's root and attempt records never carried it.

Ported from reyoung's 9d82162aa (reyoung/magpie feat/otel-gateway-key-name),
applied unchanged onto current main:
- observeRequest takes access.Caller(r).KeyName when observing begins
  and puts it on every End and Attempt record (CallerKeyName), so the
  root span and every try (failures, retries, fallbacks) carry it with
  no lookup at export time.
- otlp's allow-list grows by this one attribute, on generation and
  ledger spans (otelAttributes, so the duration and token histograms
  too) and on the root span. Omitted when the name is empty. The key's
  id and secret are never sent; provider account names stay out.
- docs/reference.md, plugin-runtime.md and the en/zh/ja privacy pages
  say the name goes to the user's collector.

Added on top: docs/reference.md says each key name multiplies a
metric's series, and that keys sharing a name are counted together.

Review of the fork (read every line; run only on mote): no new address,
dependency or credential; the name is read from the auth context at
request time, the same source appendUsage uses for the ledger row;
reported rows (another computer's) already have the caller key cleared
and never reach observers; session spans of local transcripts have no
key. READMEs (en, zh) mention OTLP only as a feature, with no list of
what is sent, so they are unchanged.

Run on mote (lockf ~/suite.lock), at base c7ebb6f8d plus this change:
- gofmt -l internal/gateway internal/otlp: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: ok.
- go test ./internal/otlp ./internal/gateway -run 'TestOTel|TestObserve':
  ok.
- go test -count=1 -timeout 45m ./internal/otlp ./internal/gateway
  ./plugins/otel: ok.
- go test -count=1 -timeout 45m ./... (macOS): every package ok (92),
  exit 0.

Rebased onto 136178803 after that run (5 commits; gateway.go and
prev_response.go, nothing in observe.go, otel*.go or internal/otlp).
The touched packages' run at the pushed head is queued behind mote's
suite lock and was not done before the push.

Broken by hand (each on mote, then restored):
- observeRequest without the name (o := &observed{}):
  TestOTelExportsGatewayKeyName/true red, "span 0: gateway key name ""
  seen 0 times".
- gatewayKeyAttr returning before adding the attribute:
  TestOTelBatchWireAndPrivacy red (attributes lack
  magpie.gateway_key.name) and TestOTelExportsGatewayKeyName/true red.

Not tried: a real Langfuse collector; Windows and Linux runtime runs (vet
only); the site pages are not deployed by this commit.

Co-authored-by: reyoung <728699+reyoung@users.noreply.github.com>
2026-11-09 17:21:48 +08:00
yetone 93bbcc8bfb gateway: a Responses conversation another resource made goes whole, without its item ids
hykql (Discord) uses Azure OpenAI behind a relay that spreads one key
over several resources. A turn after the first was answered by another
resource, which turned it away: "The requested item was created under a
different Azure OpenAI resource. Use the same resource that created the
item to access it." prevRefused only knew "previous_response", so the
400 reached the client, and sending the conversation whole would not
have helped: the items magpie brings back still carry the first
resource's ids.

- prevForeign knows that refusal. A request whose conversation magpie
  holds is asked once more, whole, with the ids of the items magpie
  brought back taken out (prevElsewhere): an item that may go without
  its id (idOptional) loses it, reasoning stays only with its
  encrypted_content, the client's own new input is as sent. Nothing is
  asked again when magpie doesn't hold the conversation, or when the
  body would be the same, so an unknown previous_response_id is still
  relayed as sent and its refusal passed on.
- A kept turn remembers the provider and key whose reply it is (made).
  Going on with another one, those ids are left out at once: it never
  made them. The same provider and key gets them as before.
- No setting and no GUI. This is the part of hykql's branches
  (feat/responses-state-client-profile, feat/provider-editor-responses-
  state) the review kept; their retry stripped previous_response_id from
  a delta magpie doesn't hold (a 200 with the history gone), and their
  client profiles included Claude Code's User-Agent. Neither is taken.

Run on mote (lockf ~/suite.lock mote-run), at c7ebb6f8d plus this change:
- gofmt -l internal/gateway: clean.
- go vet ./internal/gateway on darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- The three new tests and the existing previous-response tests: ok.
- Broken by hand: prevForeign returning false turns
  TestPreviousResponseOtherResourceDeltaSentWhole and
  TestPreviousResponseOtherResourceWholeSentWithoutIDs red; stripping
  only when forced turns TestPreviousResponseToAnotherProviderSentWithoutIDs red.
- go test -tags nogui -timeout 45m ./internal/gateway: ok (859s).
- Again at the rebased head (on 608c1543e): gofmt clean, the three vets ok, ./internal/gateway ok (873s).

Not tried: a real Azure resource pair. The refusal text is the report's
and hykql's own fixture, not reproduced. Whether Azure takes one
resource's encrypted_content on another is not known; if it refuses it,
the refusal reaches the client as before.

Reported-by: hykql (Discord)
2026-11-09 16:55:21 +08:00
yetone 608c1543e8 gateway: a bare model name goes to the asking agent's own subscription first
freefcw on X: Codex, started by Mirasim, asked for gpt-6-astra by its bare
name. Its own ChatGPT subscription serves it, but magpie sent it to Devin
through the group it found (auto-gpt-6-astra, soonest renewal first).
With found groups off it still went to another vendor: Resolve takes the
first provider in the Providers order, AutoStandIn and agent.Reseat did
the same.

Now:
- A bare model id the asking agent's own subscription in magpie serves (a
  provider whose Account.Agent is the agent: Codex's ChatGPT accounts,
  Claude's for Claude Code, Copilot's) goes there, found groups on or off
  (gateway ownFirst, provider.OwnRoute). count_tokens counts it there too.
- Kept as they were: a group the user made or changed by that name; a found
  group magpie set one of the agent's fields to (agent.SetToGroup over the
  applied record, #750's bare spelling included, wired as
  gateway.SetToGroup); a gateway key held to some models; ids with a
  provider in them and group refs; clients magpie doesn't know as an agent.
- Found groups off: a bare id several providers serve, none of them the
  agent's own, is refused for an agent that has a subscription of its own
  in magpie, with a 400 naming the provider/model ids and
  "magpie group auto on" (provider.OffSpread). Off, magpie picks no vendor.
- AutoStandInFor and Reseat's sameModel prefer the agent's own
  subscription for a found group that is gone.

Docs: gateway-routing.md's Model resolution row and the bare-ids section.

Run (mote, at this tree on c7ebb6f8d):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/provider
  ./internal/agent ./internal/cli ./internal/gateway: all ok.

Broken by hand, each red:
- ownFirst off in serve (and AutoStandIn back):
  TestBareNameGoesToTheAgentsOwnSubscription went to the relay with groups
  on, and again with groups off alone (the reporter's two cases).
- OffSpread check off: TestBareNameOnSeveralVendorsRefusedWhileGroupsOff
  answered 200 from the relay.
- SetToGroup check off: TestBareNameOfAGroupSetOnTheAgentStaysTheGroups.
- The user's-group and own-entry checks off: TestOwnRoute, TestOffSpread.

Not run at this head: the full ./... suite (mote's suite.lock had five
suites queued); it runs under the lock after the push, any red filed.
Not tried: a real Codex with a real Devin plugin account; Reseat's own
preference has no test of its own (needs a fetched Codex account in the
agent package's sandbox).

Reported-by: freefcw (X)
2026-11-09 16:28:02 +08:00
yetone c7ebb6f8d9 settings: Video generation picks the model Magpie Image makes videos with
The same Discord (#feedback) user: a custom provider's video model still
couldn't be chosen. A custom provider's video model was already found
(seedance, kling, veo, wan, hailuo ids by name, or marked by hand with
right-click › Makes › Video model, #1399), but generate_video always used
AutoVideomaker's pick, the first video model of the first provider, with
nowhere to choose another, as Settings › Images does for images.

settings.VideoGen (provider/model or a routing group) is now the model a
request that names none makes its video with, while it resolves; else
AutoVideomaker's, as before. Image generation turned off turns video off
with it, as before. Settings › Models › Images gets a Video generation
row under Image generation: Automatic (naming the automatic pick) and
every model Magpie Image can make videos with. A pick that no longer
makes videos (provider gone or off, model unmarked) says so and the
automatic one is used in its place; the settings API refuses a model
that makes none, and keeps the pick when a save doesn't send it.

The row is drawn by videogen.js, imported when Settings draws Image
generation, with one call in app.js: drawn in app.js it put the core
scripts 616 bytes over TestCoreScriptBudget (1,534,418 > 1,533,802, found
by the first full run), and the budget is not raised.

Run on mote:
- At this change on bceeabd93 (rebased onto c630d9a29, which changes
  only the gateway key page): gofmt -l clean; GOOS=windows go vet and
  GOOS=linux go vet -tags nogui of the changed packages: ok. go test -run
  'Budget|VideoGen|Videomaker|TestSettingsSave|TestKeysAreWhatTheSaveWrites'
  in settings, settingsapi, gateway, gui: ok. GUI: video-gen-pick
  (32 subtests: chromium and webkit; en, zh, zh-TW, ja, de at 1100px, en
  and zh at 400px), old-webkit, i18n-en-no-cjk and the six image/Settings
  files (image-timeout-setting, images-codex-one, images-library-way,
  images-missing, image-models-hide, image-mcp): 220 of 220 ok.
- At 95a3fa3e0 (the change before the videogen.js move and the rebase):
  go test -timeout 45m ./internal/settings ./internal/settingsapi
  ./internal/gateway ./internal/gui: ok except TestCoreScriptBudget
  (fixed above). i18n-keys at 4394ea1b9: only the known plugin-words red
  (#5332).
- Not run at this head: the whole of those four packages and the 183 GUI
  files a Settings change reaches; the suite lock on mote was an hour
  deep in other sessions' suites.

Broken by hand, each red:
- videomaker ignoring VideoGen: TestVideoGenPicksAMarkedModel.
- settingsapi not keeping a pick a save doesn't send:
  TestVideoGenCheckedAndKept.
- No Video generation row: video-gen-pick.test.cjs, 30 of 32.
- videoGen left out of the Settings page's prefsKeep:
  TestSettingsSaveKeepsWhatItDoesNotSend ("VideoGen: not sent by the
  Settings page"), found before it was added.

Not tried: a real video generation with a custom provider's model (the
gateway tests hold the vendor's replies).
2026-11-09 14:25:55 +08:00
yetone c630d9a29c gateway: the key page's Claude Code setup keeps each tier on its own family
The /me page's Claude Code tab wrote the picked model into
ANTHROPIC_MODEL and into ANTHROPIC_DEFAULT_OPUS_MODEL, _SONNET_ and
_HAIKU_ alike, so picking Opus sent every Haiku background call to Opus
too (and picking a GPT model made "haiku" a GPT model).

The pick now sets only ANTHROPIC_MODEL. /v1/magpie/me returns `tiers`,
built by keyPageTiers from the models this key may use: for opus,
sonnet and haiku, the newest model of that family (claudeTier and
claudeVersionOf; routing groups and fable are skipped). A tier the key
has no model for is left out of the snippet, so Claude Code keeps its
own default for it.

Siblings: the agent writer (internal/agent/claude.go) has its own tier
design (tiers follow the main model, haiku to the provider's Haiku, the
user's own tiers kept) and writes the user's real config; it is a
different situation and is left as is. OpenMausBot's snippet writes
only ANTHROPIC_MODEL.

Run (mote, via suite.lock):
- go test -count=1 -run KeyPage ./internal/gateway/: ok
- GUI key-page.test.cjs: chromium 13/13, webkit 13/13
- gofmt -l: clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., and go build for darwin, linux (nogui) and
  windows: ok
Broken by hand:
- old keypage.html: the new GUI test is red in both engines
  (ANTHROPIC_DEFAULT_HAIKU_MODEL 'claude/claude-opus-5', want
  'claude/claude-haiku-4-5')
- keyInfo without keyPageTiers: TestKeyPageTiersAreTheirFamilys red
  ("tiers map[]")
Full suite (go test -tags nogui -timeout 45m ./...): queued behind
other sessions on suite.lock at push time; its result goes on the
follow-up, with an issue for any red.
Not tried: a real Claude Code against the page's snippet, and the
gateway binary in a sandbox HOME.

Reported-by: strinah (Discord)
2026-11-09 14:22:05 +08:00
yetone c81065ca72 providers: System One for a custom provider and Ark's pay as you go
A user on Discord (#feedback) found no System One endpoint under a custom
provider's More endpoints (OpenAI Responses), no System One choice in its
Model settings, and on the Volcengine Ark page neither an endpoint nor any
model a routing group could ask as its classifier.

System One is asked at POST …/systemone under a provider's Decide base;
a model is offered as a group's classifier only when its provider has
one. Two causes:

- A custom provider kept a Decide URL only when its API was "System One
  base URL". With a Responses or chat URL there was no field for it, and
  Save sent "" for one the provider didn't have yet. More endpoints now
  has "System One URL" for any API, saved as typed.
- Ark's pay as you go answers System One on the same key at
  ark.<region>.volces.com/api/v1, but a provider asked at …/api/v3 (the
  preset's or a custom one, chat completions or Responses) had no Decide
  unless the user knew to type it. normalize now sets it (arkSystemOne);
  a URL the user gave is kept. The Coding and Agent Plans answer System
  One 404, so they get none, and decideKeys leaves out a key whose plan
  has none (a Coding Plan key beside a pay-as-you-go one). Ark's one
  decision model is offered whatever chat models are picked, as
  Bailian's is (OfferedDeciders).

Run on mote at this head's tree (65aacb8f8, on e0f6eda64):
- gofmt -l clean; GOOS=windows go vet and GOOS=linux go vet -tags nogui
  of internal/provider, internal/gateway, internal/gui: ok.
- go test -timeout 45m ./internal/provider ./internal/gateway
  ./internal/gui: ok (provider 136s, gateway 849s, gui 131s).
- GUI: custom-systemone-url.test.cjs (chromium and webkit; en, zh,
  zh-TW, ja, de; 1200px and 420px), i18n-en-no-cjk, i18n-keys,
  editor-advanced-align: ok but i18n-keys' "a plugin's words are its
  own", red on main for three plugin words Go files also say (#5332,
  #5426, #5482). Earlier, at c9d253e4a, 30 GUI files a provider editor
  change reaches: the same red, and editor-advanced-align's two whole-run
  reds under load 670 (#4615), green alone and in the run above.

- Rebased onto 77076eef4 (four commits: a group editor's Advanced,
  Remote magpie cards, npm updates on Windows; none in these files' code
  paths): gofmt, both vets, go test -run 'Ark|Decide|Decider|Classif|
  SystemOne' of the three packages, custom-systemone-url and
  i18n-en-no-cjk: ok.

Broken by hand, each red:
- arkSystemOne returning "": TestArkPayAsYouGoDecides and
  TestArkDecisionSkipsPlanKeys.
- OfferedDeciders without the bailianApart exemption:
  TestArkPayAsYouGoDecides (the providers with chat models picked lose
  their classifier).
- decideKeys without the Decides filter: TestArkDecisionSkipsPlanKeys,
  "doubao-seed-2.1-lite asked with: [k-api … k-coding]".
- No System One URL under More endpoints: custom-systemone-url, every
  subtest.

Not tried: a real Ark account (the decision call is held to the
recorded reply); a provider whose main key is on the Coding Plan with a
pay-as-you-go key beside it gets no Decide, since normalize reads the
provider's own URLs.
2026-11-09 13:05:00 +08:00
yetone 77076eef47 agent: an npm update on Windows lets go of magpie's own claude and codex first
CLJY (Discord) had %APPDATA%\npm with only the 308-byte sh shim of claude:
no claude.cmd, no claude.ps1 and no codex at all, and `npm i -g
@anthropic-ai/claude-code` ended in "npm warn cleanup ... EPERM ...
unlink ...\.claude-code-<rand>\...\claude-code-win32-x64\claude.exe".
On Windows a running program's file can't be removed. npm moves the old
package aside, takes the old shims away, and stops partway when a
claude.exe of that package is still running; the sh shim is what is left.

magpie keeps such processes running itself:
- the Claude subscription bridge keeps up to 6 Claude Code runs waiting
  for their conversations' next turns, for up to an hour;
- Codex's app-server daemon has no idle exit, and magpie restarts it.
Its Update button ran npm with both still up.

- agent.UpdateCLI, on Windows through npm, bun or pnpm, first lets go of
  them: gateway.LetGoIdleClaudeCode ends every waiting run (its session
  shelved for the next turn, as a run let go past idleMost is) and returns
  once each has exited; provider.StopIdleCodexDaemon stops the daemon when
  no codex session is on it. Runs in a turn and sessions are left.
- An update on Windows that leaves the CLI's file gone fails, saying to
  quit it and reinstall, instead of "updated".
- proc's toolIn (FindTool) and codexExecutable no longer take the bare
  extensionless file on Windows, which CreateProcess can't run. Beside
  name.exe and name.cmd, the sh shim alone stands for the .exe it runs
  (Claude Code's bin\claude.exe), read from cmd-shim's exec line and kept
  inside its folder; a node shim (codex) or any other script is skipped.
  The testdata shims are cmd-shim 7's bytes, made with cmd-shim@7 on the
  Windows box.

Run at this head (rebased on origin/main; after the rebase, vet on all
three systems and the changed tests again: ok on Windows and macOS):
- gofmt -l internal/: clean. go vet of proc, agent, provider and gateway
  on macOS (mote), Windows (win-run) and Linux (wsl-run): ok.
- Windows (win-run): internal/proc ok;
  TestToolInNPMShShimAlone, TestLetGoIdleClaudeCodeFreesTheExe and the
  TestClaudeIdle* tests pass. internal/agent, internal/provider and
  internal/gateway (-run "Claude|LetGo|Codex") have Windows reds, and
  the same run at origin/main c9d253e4a has the same ones (26 in agent,
  15 in provider, 2 in gateway), except TestUsageReadAndReadAgain, a
  clock-tick flake filed as #4796.
- macOS (mote): internal/proc, internal/agent, internal/provider and
  internal/gateway (-run "Claude|LetGo|Codex") ok.
- Linux (wsl-run): internal/proc and internal/provider ok; internal/agent
  red only in TestGrokInstalled, red the same on origin/main c9d253e4a
  (3 of 3), filed as #3548.

Broken by hand:
- toolIn taking the bare name again: TestToolInNPMShShimAlone red on
  Windows (6 cases).
- letGoIdle not waiting for the trees: TestLetGoIdleClaudeCodeFreesTheExe
  red on Windows, and with that check off the removal fails with "Access
  is denied" - the user's EPERM.
- no let-go call and no gone check: TestUpdateCLIOnWindowsLetsGoFirst red;
  StopIdleCodexDaemon ignoring sessions: TestStopIdleCodexDaemon red.

Not tried: a real npm update of Claude Code or Codex on the Windows box
with magpie running; the Windows-only path is tested with
updateGOOS = "windows" on macOS, and the process lock with a copy of the
test binary.

Reported-by: CLJY (Discord)
2026-11-09 12:56:42 +08:00
yetone 08a42c40ff provider: a Remote magpie's cards are passed on down a chain of magpies
yuyong_id (Discord) chains three magpies through Remote: magpie1 has a
Codex subscription, magpie2 uses magpie1, magpie3 uses magpie2. magpie2
showed magpie1's Codex card; magpie3 showed none.

Cause: since 8c71cd27f a magpie told only its own cards
(CachedCards kept From == "") and the receiver skipped any card it was
told with a From (remoteCards). So no card from a remote, of any
provider, reached a third magpie; Codex wasn't special. Antigravity and
DeepSeek showing at magpie3 means magpie2 has those accounts itself
(not checked with the reporter).

Fix:
- CachedCards passes on the cards it already holds from each Remote
  magpie (passedOnCards, from the 30s cache: it asks no remote, and a
  held remote's cards stay home).
- Each card told carries Via, the magpies (catalog.Self) it passed
  through; a receiver leaves out a card that comes back to it or has
  passed more than MaxVia magpies (catalog.Loops, the same rule as
  magpie_via for models).
- Refresh on a passed-on card ("m1/codex" at magpie2) goes to
  RefreshUsage, which asks that remote again, instead of a 400.
- Sibling: the status line (KeptQuotaReport, /v1/magpie/quotas?kept=1)
  read CachedCards too, so a magpie's own Remote cards were missing
  from it; now there.
- A held key still sees only own cards (quotaScope unchanged).
- Codex's resets stay with the magpie next door only, as before.
- catalog.Self becomes a func with SetSelfForTest, so one test process
  can play magpie2 and then magpie3.

Run on mote at b9cdac0c6 (rebased on origin/main 8a7f77cb7):
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build ./...: ok.
- New TestRemoteChainPassesOnCards (magpie1 fake -> this gateway as
  magpie2 -> magpie3 reading it: Codex, Antigravity, GLM plan and a
  DeepSeek balance arrive, named "Codex · M1 · M2", Via [m1 m2],
  refresh reaches magpie1, a looped card is dropped),
  TestKeptReportHasRemoteCards and the updated TestRemoteMagpieCards,
  with TestRemoteMagpie*, TestRemoteSelf, Quota* and TestCachedCards:
  ok; -race -count=3 on the new and changed ones: ok.
- On origin/main with only these tests (and the Via field / Self func
  they compile against): all three FAIL. magpie3 gets just the
  "nothing read on that magpie yet" stand-in for magpie2, the kept
  report is empty, and the third magpie's card is nil.
- Full suite (-tags nogui -timeout 45m ./... under the suite lock):
  cut short when mote closed the connection, before any package
  reported. Rerunning at the pushed head.
- Rebased again onto origin/main e0f6eda64 (gateway changed): go vet
  of gateway, provider and catalog and the same targeted tests: ok on
  Linux (wsl-run magpie-desktop, -tags nogui); mote was refusing ssh.

Not tried: three real magpies on separate machines.
Not changed: a passed-on card's quota history (#5747).

Reported-by: yuyong_id (Discord)
2026-11-09 12:47:12 +08:00
yetone e0f6eda641 gateway: a probe's reply that thinks its 16 tokens and ends unsaid is answered (plugins#827)
Through a Remote magpie, the plain model test of Open Design's
glm-5.3-flash was red. The model always thinks. It spent the test's 16
tokens on that and ended after content_block_stop, with no message_delta
or message_stop. So:

- translate made it a 502 "ended before it was complete";
- the 502 is busy, so the remote retried it and waited out its 60s
  patience;
- the asking magpie had given the remote only 20s (testWait), and said
  no answer came.

Each step is now fixed for the class, not for this model:

- A reply whose request was capped at a short probe's worth
  (cutVoidTokens, 1024) and that spent some of it, then ended cleanly
  with nothing saying it ended, ended at its length (endsAtProbeCap).
  - This holds in translate, in streamTranslated and in gathered (a
    Responses plugin's stream asked whole becomes response.incomplete at
    max_output_tokens).
  - It covers Anthropic and Responses upstreams only. Gemini always
    ends with a finishReason, so a Gemini stream without one stays a cut
    (TestGeminiUpstreamEndedShort, asked for 256, caught a wider first
    draft).
  - A reply asked for more than 1024, or one that spent nothing, is
    still the 502.
- A client may say how long it waits (provider.WaitHeader,
  X-Magpie-Wait, in seconds). The gateway then takes no same-one retry
  pause and no patience round that would end within clientRoom (10s) of
  that wait (keptAlive.outlives), so the client gets the error while it
  still waits. Like every X-Magpie- header, it is not sent upstream.
- A model test through a remote magpie waits pluginTestWait (60s), as a
  plugin's test does here, and sends that wait as X-Magpie-Wait.

Not changed: a stream relayed as it came (passthrough to an agent of the
same protocol) still gets no end added. That is filed as #5736 and named
in gateway-routing.md.

Run, through mote-run:
- At the pushed tree, rebased on origin/main b68218f43 (802f03e68 after
  it changes only site/): go vet, GOOS=windows go vet and GOOS=linux go
  vet -tags nogui of internal/gateway and internal/provider are ok. go
  test of both packages with -run
  "ProbeCap|Gathered|ClientWait|RemoteMagpie|EndedShort|Gemini|SingleProvider|Responses|Enum|Group|Spent|Capped|Patience"
  is ok. That covers the base's new Responses-enum and group commits.
  At 8a7f77cb7 the same kind of run, with Compact|Signin|Carry for that
  base's commits, was ok.
- Full run at 9c34dc7cb (the same change, rebased on origin/main
  e2afbfc15): go vet
  ./internal/..., GOOS=linux go vet -tags nogui ./internal/..., and
  GOOS=windows go vet ./internal/... are ok; go test ./internal/gateway
  ./internal/provider -timeout 45m: provider is ok; gateway is ok
  except TestCodexGeneratedImagesPastOldLimit (#5281: held 31s
  without routing in a full run; at this head it passes alone, 3 of
  3, with -count=3)
- At 32a31963b, the first draft: go vet ./..., GOOS=linux go vet -tags
  nogui ./... and GOOS=windows go vet ./... were ok; gofmt -l was empty.
  The suite there:
  - TestGeminiUpstreamEndedShort was red. The rule was too wide, and it
    is scoped above.
  - TestCodexGeneratedImagesPastOldLimit was red: #5281, the
    images-body hold, not on these paths.
  - TestCodexListTagNotKeptOverAFreshFile was red: #4216, under load.

Broken by hand, then put back:
- endsAtProbeCap returning false:
  - TestProbeCapEndsAtLength goes red, both whole (502 ended before it
    was complete) and stream (no finish_reason length).
  - TestGatheredProbeCapIncomplete goes red (capped 16: 502).
- outlives returning false: TestClientWaitBoundsPatience/short_wait goes
  red (upstream asked 6 times).
- probeOnce's remote-magpie wait and header taken out:
  TestRemoteMagpieProbeWait goes red ("no answer in 1s", X-Magpie-Wait
  said "").

Not tried: a real Open Design account, and a real two-magpie Remote
setup. The fixture is the reporter's described ending (thinking block,
content_block_stop, close), not their captured bytes.

Reported-by: Gitleonan
2026-11-09 12:42:35 +08:00
yetoneandcrayon b68218f43e gateway: a Responses reply to a client that isn't Codex carries only the Responses enum's events (#4482)
Grok Build, reading /v1/responses through async-openai's typed
ResponseStreamEvent, lost whole turns on a ChatGPT account: the backend
speaks part of the Codex protocol (codex.rate_limits,
codex.response.metadata, response.metadata, a keepalive event), and the
client read each as `unknown variant` and ended the turn.

passthrough now runs responsesEnumTidy (responses_enum.go) last in its
chain for a Responses stream to a client that isn't Codex (the
fromCodex / agentOf pair codex_own_v1.go uses): every event whose
`event:` name, or data `type` where it names none, is outside the OpenAI
Responses enum is dropped; a keepalive goes on as an SSE comment so a
quiet upstream still keeps the client's idle timer alive. sniff and
codexLimitsTap read the upstream bytes before it, so failover and the
account's windows are unchanged. Codex itself gets every event as it
came. A plugin's Responses reply goes through the same passthrough, so
it is covered too. The WebSocket route's synthesized header frames
(socketTurnWriter.headerFrames) go to Codex alone too.

The response.failed shape from the report (missing created_at /
sequence_number) was already fixed on main by 29bfd5dc8 (plugins#852);
crayonlu's test for it is kept.

Ported from crayonlu's codex-lead-events branch (917878484, four
commits), with the keepalive comment and OpenAI's audio events added to
the enum.

Run (mote, macOS arm64, Go 1.26.8):
- focused: TestResponsesEventsOutsideTheEnumStayWithCodex,
  TestResponsesEnumAllowed, TestPassthroughResponsesEndsShort,
  TestSocketHeaderFramesOnlyForCodex, TestCodexSocketServed,
  TestResponsesEventsAreClientShaped: ok.
- broken by hand: gateway.go and responses_ws.go back to origin/main
  with the tests kept: both foreign clients red (codex.rate_limits,
  codex.response.metadata, response.metadata, keepalive there=true, no
  keepalive comment) and the socket test red with the leaked frames;
  the Codex cases stay green.
- gofmt -l clean; go vet -tags nogui ./internal/gateway on darwin,
  GOOS=linux and GOOS=windows ok.
- go test -tags nogui -timeout 45m -count=1 ./internal/gateway: ok
  (2186s), at this tree on origin/main c9d253e4a.
- rebased on 44d6dd75d (gateway.go changed upstream): the focused
  tests above with the new cap/group tests (TestCapGroup*,
  TestCodexOneAccountSpent*, TestPluginCapPool*) ok; vet ok.
Not tried: a real ChatGPT account with Grok Build (a second sign-in can
rotate the live refresh token); the full ./... suite (mote at load ~760
with a long suite-lock queue).

Reported-by: crayonlu
Reported-by: Jeo-Meek
Co-authored-by: crayon <hicrayon@outlook.com>
2026-11-09 12:36:18 +08:00
yetone 44d6dd75d1 gateway: a subscription's capped or spent turn goes on to the user's group with it in
adorable_piglet on Discord (v0.1.3354): a Codex subscription with a usage
cap set in magpie, first in a routing group with two APIs after it. Past
the cap the Codex app's turns were answered 429 "usage cap reached" and
never reached the APIs; only switching the subscription off in Providers
moved them.

Cause: the Codex app signed in to ChatGPT asks Codex's own model
("gpt-5.5"), never "group/<id>". With a cap on the account,
codexAccounts routes the turn as codex/gpt-5.5, and serve plans the
codex provider and its own Fallback list only. A group that merely has
codex/gpt-5.5 in it was never planned, so with every account held the
answer was cappedError's 429. A request for the group itself was already
routed on past the cap (TestCappedSubscriptionGivesWayInGroup, green on
the old code too). The same gap was on Codex's own sign-in out of its
allowance at OpenAI: codexFallsBack counted the subscription's Fallback
only, so the backend's usage_limit_reached reached Codex.

Fix:
- provider.GroupsAfter(id): the routing groups the user built that have
  the model in them and another member to go on to, in the user's order;
  auto groups, hidden or switched-off ones are none.
- serve: when every account is held at its cap (pl.capped, no candidate
  left, CapStop off), or for a turn codexFallBack handed on, the provider
  is planned again with those groups after its own fallbacks
  (groupsAfter), each group routed as a request to it is. One place, so
  it holds on every protocol (chat, responses, messages, Codex's backend
  path), streaming or not, and for plugin-served subscriptions.
- codexFallsBack counts those groups as fallbacks too.
- Stop at the caps (CapStop) still answers 429 (planPaused returns
  before any fallback, the groups included).

Tests:
- TestCappedCodexOwnModelGoesToItsGroup: backend path with "gpt-5.5" and
  /v1/responses with "codex/gpt-5.5", stream and not; red on origin/main
  3cabaab54 (4 of 4, 429 usage cap reached).
- TestCodexOneAccountSpentGoesToItsGroup: one ChatGPT account, the
  backend's usage_limit_reached, group [codex/gpt-5.5, a/m].
- TestPluginCarefulPool: the fake plugin as Factory through a real
  plugin host, both accounts past their caps, no fallback, group
  [factory/fake-1, spare/m2]: 429 with Stop at the caps on, the API with
  it off.
- TestCappedSubscriptionGivesWayInGroup (11 routings x 4 paths) and
  TestSubscriptionCappedMidConversationGivesWay pin the group/<id> case.

Broken by hand (each through mote-run):
- the serve block off: TestCappedCodexOwnModelGoesToItsGroup 4 of 4 red
  and TestPluginCarefulPool red ("group, stop off: 429").
- GroupsAfter out of codexFallsBack: TestCodexOneAccountSpentGoesToItsGroup
  red (429 usage_limit_reached).
- the handedOnOf arm out of serve: the same test red.
- the !p.CapStop guard out: still green, since planPaused itself returns
  before fallbacks with CapStop; the guard only saves a second plan.

Run at this tree (mote-run, mote under load from other sessions):
- gofmt -l . empty; go vet (darwin, GOOS=windows, GOOS=linux) of
  internal/gateway and internal/provider ok.
- go test -timeout 45m -count=1 ./internal/gateway ./internal/provider:
  provider ok (673s); gateway FAIL (2545s) on TestBurstTellsNoSpeed/
  responses_from_chat_burst alone (5000 tokens in 1091ms read as a
  speed), a timing red under load, ttft untouched here; 3 of 3 green
  alone at this tree, noted on #2719 (the same test's chat_burst).
  That run was at base 3cabaab54.
- Rebased onto origin/main 8a7f77cb7 (9 gateway/provider files changed
  there): gofmt empty, go vet ok, and go test ./internal/gateway -run
  "Cap|Capped|Fallback|TestCodexOneAccount|TestPluginCarefulPool|
  TestSubscriptionCapped" ok (199s) at the pushed tree.

Not tried: a real Codex app and ChatGPT account past a real cap (fakes
only). Not covered: an account that crosses its cap in serve's near-cap
walk (planned with room, held at its turn) still gets the 429 for that
turn; the next turn is planned with it held and goes to the group.
Drawing (images) and embeddings keep their own planning and are
unchanged. No GUI change.
2026-11-09 12:31:00 +08:00
yetone c9d253e4a2 gateway: an agent's compaction is recorded as Compaction, not a plain turn
shangyuan0818 (Discord, v0.1.3354): Claude Code's compactions don't show
in Usage → Requests. Through the gateway they were recorded and counted,
but as ordinary turns (Kind ""), so nothing read as a compaction: the
Compaction purpose listed none, the OTel export skipped them as turns
the transcript has (Claude Code's compaction is skipTranscript, so it
has none), and the reply ended the agent's turn.

The main handler now marks a call compacting() recognises (Claude
Code's summary ask, OpenCode's and the other agents' prompts) as
KindCompact, on every route it serves (messages, chat, responses,
gemini), unless a header already set its kind. The check reads the
facts parse the request already makes (bodyFacts.compact). Codex's
backend route already took the kind from its header; it now uses the
same constant.

Not fixable here: Claude Code used directly (not through magpie) never
writes a compaction's usage to its transcript (only compact_boundary
with token counts before and after), so magpie can't count those.

Run (mote, at this change on 3cabaab54):
- go test -timeout 45m -count=1 ./internal/gateway ./internal/usage ./internal/otlp: ok
- go vet ./internal/gateway, GOOS=linux and GOOS=windows: ok
- gofmt -l internal/: clean
Rebased onto 25eec8f6c (4 commits, 65 lines in internal/gateway, an
images-API change); at the pushed head: go vet ./internal/gateway and
go test ./internal/gateway -run 'Compact' (every compaction test): ok.
Broken by hand: TestCompactionRecordedAsCompaction on the old code is
red in 4 of 5 cases (claude code fork, claude code plain, chat,
responses: recorded as kind "", want "compact"); the plain turn stays "".
Not tried: a real Claude Code /compact through a sandbox gateway, and
Claude Desktop (assumed to be the same, since it runs Claude Code).
2026-11-09 11:37:06 +08:00
yetone e2afbfc153 gateway: an image model the user marked draws at the images API first
A Discord user asked how to add an image model to a custom provider.
The way is: Add model by its id in the provider's editor, right-click
it, Makes: Image model, Save, then pick it in Settings > Images. The
menu says such a model "draws at the provider's images API
(/images/generations)", but viaFor ignored the mark: a model whose name
isn't on catalog.ImagesAPI's list (a relay's jimeng-4.0) was asked on
chat completions first, and reached the images API only if chat
answered 404/405 or named images/generations. A relay that answers
chat with any other error never drew it. Now a marked image model is
asked at the images API first; a provider without one (404/405) still
has it drawn on chat completions, by draw's existing fallback.

Run (mote, at 3cabaab54 plus this change; the two commits since, 8a58c0e30 and
dc098c1e8, touch no gateway, provider, catalog or settings file):
- go test ./internal/gateway -count=1 -timeout 45m: ok (1808s)
- GOOS=linux and GOOS=windows go vet ./internal/gateway: ok; gofmt -l clean
Broken by hand: with the new viaFor case turned off,
TestMarkedImageModelDrawsAtTheImagesAPI fails ("images API sent []").
Not tried: a real relay's image model; other packages' suites (only
internal/gateway changed). No GUI change.
2026-11-09 11:31:24 +08:00
yetone 5506c84437 gateway: a skill's body reaches the run with its Skill call's result
Claude Code answers a Skill call with "Launching skill: <name>" and sends
the skill's SKILL.md after the results, as a text block headed "Base
directory for this skill: …". Since d84f58fd2 (#5403) that text counts
as the agent's own (desktopNote), so it is no longer said to the run as
the user's, which was right, but nothing handed it to the run either:
on the Claude subscription route a model that launched a skill saw
"Launching skill: pdf" and never what the skill says. Every skill
launched through magpie's Claude subscription lost its body.

withSkillBodies appends each such body to its Skill call's result (two
skills at once each get their own), else to the result it follows, else
to the last; saidWithResults still leaves it out of the user's words.

Found with a real Claude Code 2.1.316 in a sandbox HOME against the live
gateway: a proxy between them showed the body in the request, and the
model answered as if it had none.

Run (mote, at this tree):
- go test -tags nogui ./internal/gateway -run
  'SkillBod|Desktop|TaskNotice|SaidWith|MidTurn|Notice' -count=1: ok.
- TestSkillBodyRealClaudeCode parses the request Claude Code sent
  (testdata/claude-code-skill-launch.json: its own bytes, trimmed to the
  launch turn, paths shortened) and checks what the run is handed.
- Broken by hand (withSkillBodies returning results as they came):
  TestSkillBodyReachesTheSkillResult and TestSkillBodiesTwoSkills red.
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m: ok
  (1220.8s), at origin/main 6b0b7a96e. Rebased on 8f74442e4, whose
  gateway change is browser.go: -run
  'SkillBod|Browser|ClaudeSub|TaskNotice' ok.

Not tried: a real run through a gateway built from this tree (the
Claude subscription's sign-in would be refreshed by a sandbox copy).

docs/subsystems/claude-subscription-bridge.md says what withSkillBodies
does, beside withTaskNotices.
2026-11-09 08:38:02 +08:00
yetone 4f3ec591ae browser: an extension older than magpie's is to be reloaded, says the sheet and the agent
magpie rewrites the extension's folder when an older one connects, but
Chrome runs what it loaded until the extension is reloaded on
chrome://extensions or the browser starts again, so a user who never does
either stays on the old code. Now that is said:

- Library → Magpie Browser: under "Connected to your browser · 0.1.8" a
  line says "Magpie Browser 0.1.9 is ready: reload Magpie Browser on
  chrome://extensions (edge://extensions in Edge)." Looked at from another
  computer (the zip install), it says to download it again, unzip it over
  the old folder and reload it. /api/library/browser has outdated.
- The agent: the first browser answer on such a connection starts with a
  line telling it to have the user reload it (or download it again, for
  one connected with a gateway key). Once a connection.

The extension still isn't made to reload itself: an unpacked one that
calls chrome.runtime.reload() doesn't come back (the finding in
browser.go's hello).

The fake extension in the gateway's tests now says magpie's own version
(it said 0.1.0, which every test would now be told about).

Run (on mote):
- internal/gateway TestBrowser* (new TestBrowserSaysTheExtensionIsOlder,
  TestBrowserSaysNothingOfACurrentExtension), ok.
- internal/gui TestBrowser* (new TestBrowserStateOutdated), ok.
- GUI: library-browser-setup, library-browser-away, library-browser-ask,
  browser-access, i18n-keys in Chromium and WebKit, every language, at
  1100 and 420 wide: 127 of 128. The red is i18n-keys "a plugin's words
  are its own" for three keys this change doesn't touch, red on main and
  filed (#5332, #5482, #5426).
- go vet for darwin, linux (nogui) and windows; gofmt -l clean.

Broken by hand:
- the once-a-connection check removed: TestBrowserSaysTheExtensionIsOlder
  red ("s1's next answer" has the note again).
- the sheet's line never shown: library-browser-setup red, 20 of 20.
- Outdated without Connected: TestBrowserStateOutdated red.

Not tried: the whole GUI suite before this push (run next), and a real
Chrome with an older extension loaded by hand.
2026-11-09 06:57:40 +08:00
yetone 81798f7793 browser: a recording is an MP4, encoded in magpie (GIF on format: gif)
record_stop now makes an H.264 MP4 by default, from the same frames as
the GIF (a second a frame, the last held three, the first frame's
size). record_stop takes format: "mp4" (default) or "gif"; any other
value is refused and the recording goes on, so the agent can ask again.

internal/h264 is a small encoder with no cgo and no ffmpeg:
Constrained Baseline, CAVLC, deblocking off. The first picture is IDR.
After that a macroblock the same as before is P_Skip, and a changed one
is Intra16x16 (V/H/DC by SAD). Colour is BT.709 limited range, and an
odd size is cropped. The MP4 puts its moov before mdat, so a player can
start before it has the whole file. QP 23.

The image MCP's file route serves through http.ServeContent, so a
player's Range request gets 206. Safari plays an MP4 only when it is
served that way. extOf gives video/mp4 the extension .mp4.

Run (on mote unless named):
- internal/h264 TestDecodersMakeTheSamePicture. ffmpeg n7.1 (local;
  mote has none) decodes 7 cases to the encoder's own reconstruction,
  byte for byte (diff 0): 330x190 q24, 800x522 q20, 64x48 q10,
  48x32 q40, 96x64 q0 (escape codes), 96x64 q51, 18x18 q23.
  TestEncodeKeepsThePicture: PSNR 42-44 dB at q24.
- internal/gateway: TestBrowserMP4, TestBrowserGIF*,
  TestBrowserRecordStopWithNothing, TestBrowserToolListIsSmall
  (4585 bytes vs 12138), TestImageMCP*.
- TestBrowserRecordsAVideo, in a real Chrome for Testing (chromium-1234)
  with the extension: the MP4 has video/mp4 and a .mp4 link, and a Range
  request gets 206. Chrome opens the link and plays it: 800 wide, 5 s,
  a frame read back from a canvas. format gif decodes to 3 frames, and
  format webm is refused.
- All of internal/gateway's Browser and ImageMCP tests on origin/main
  3fc6ee411, green. The 3-frame recording was MP4 24 KB, GIF 26 KB.
- go vet for darwin, linux and windows; gofmt -l clean.

Broken by hand:
- w.Write in place of ServeContent: TestBrowserRecordsAVideo is red
  ("a range: 200").
- avcC's NAL length size changed from 4 to 2: Chrome's playback check is
  red (this change also stops the script waiting more than 10 s).
- Before the fix in this change, a non-symmetric Hadamard gave PSNR
  ~20 dB and an ffmpeg mismatch. Both tests were red.

Not tried: Safari or Firefox playback, a Windows or Linux run of the
real-browser test, or a recording of hundreds of frames for time and
size.
2026-11-09 06:03:39 +08:00
yetone 82ca554be9 routing: a provider's accounts routed In order give a conversation back to the first
CryptoSarom on X: with a provider's accounts set to In order, a
conversation that had moved to the second account (the first was
resting) stayed on the second once the first was ready again. Only a
group's members went back to the first; a provider's own accounts never
did, because inOrder was read from the group's routing alone.

- gateway.go: inOrder comes from the provider's routing, or the group's
  when the request is to a group.
- affinity.go: backToFirst compares accounts (who()) for a provider's
  own accounts. For a provider it overrides only a cache that would have
  kept the conversation (cacheHolds: worth keeping and still warm), so a
  cold or empty cache keeps its own "cold"/"new" label.
- plugin_factory_cap_test.go: "auto, cached on B" pinned the old
  stay-on-B behaviour; it now expects A, the first account, on purpose.
- GUI: the Routing affinity line for "order" without a group says the
  provider goes in order and the first is ready again (all languages).
- docs/subsystems/gateway-routing.md: the In order bullet covers a
  provider's own accounts.

Run on mote at this tree on aa3d11d5b; rebased onto c6702f462, which changes only context.css and its own GUI test: gofmt -l clean,
GOOS=linux and GOOS=windows go vet ./internal/gateway ok, go test
./internal/gateway -count=1 -timeout 45m ok (985s).
GUI: routing-affinity-order (new accounts case) and i18n ok in both
engines. i18n-keys "a plugin's words are its own" is red from three
strings not in this change, filed as #5332, #5426, #5482.

Broken by hand: inOrder := false turns
TestOrderedAccountsGiveTheConversationToTheFirst red (k1 k1 k1 k1, why
"cache"). Without cacheHolds TestForeignSealedItemsAfterAColdSwitch went
red (why "order" for a cold switch).

Not tried: a real account pair in the live app.
2026-11-09 05:42:44 +08:00
yetone aa3d11d5b7 kimi: a key's booster wallet is read, and a key spending it isn't rested to the month (#5721)
apple_test_src on X (#5721): a Kimi Code key at 98.85% of its month was
rested until the month renews, while Kimi still served it from its
booster wallet. magpie never read the wallet.

readKimiCode now reads booster_wallet (or boosterWallet). A BOOSTER wallet
with an amount over 0 adds an "Extra usage" row: amountLeft, in cents x 1e6,
in the currency of monthlyChargeLimit, else monthlyUsed, else USD. When
something is left, the plan windows are marked Credits. The gateway's full()
then doesn't count a key on its booster as full at the month's 98%. A 429
quota refusal rests it as any refusal does, not until the month renews.
A wallet that is empty, of another type or missing changes nothing.

Tests: TestReadKimiCodeBooster runs on the reporter's literal body
(testdata/kimi-booster-5721.json, where 0 is left: no Credits) and on the
same body with amountLeft injected (snake and camel case). A GIFT wallet
and amount 0 add nothing. TestKimiKeyOnItsBoosterIsNotRestedToTheMonth:
a key with booster left isn't full and its 429 rests it under 24h; a
spent key is still rested by its window.

Run on mote: gofmt -l clean; GOOS=linux and GOOS=windows go vet of
internal/provider and internal/gateway; go test ./internal/provider
./internal/gateway -count=1 -timeout 45m: both ok (154.9s, 951.7s).
Broken by hand: routing.go reverted turns the gateway test red ("a key
on its booster counts as full at the month's 98%"); dropping the Credits
marking turns the provider test red.
Not tried: a real Kimi key with booster balance left (the reporter's
body has 0 left).
2026-11-09 05:06:48 +08:00
yetone 1a37cc8516 agent: Antigravity CLI's thinking effort is picked in its row, and the gateway asks it of Gemini
xyenon on Discord: agy's effort can't be set for magpie's models. agy 1.5.3
has --effort for one session only, and turns it away for a custom model
(/effort says "not adjustable"); settings.json has no key for it (--settings
rejects every name tried as an unknown setting). Its requests ask
thinkingConfig {"includeThoughts":true,"thinkingBudget":-1}, the model's own
choice. So the pick lives in magpie, as the Antigravity app's and Cursor
Private Inference's do: agy's row gets an effort field
(provider.AgentEffort("agy")), shown while agy is on magpie's models, with
the levels the model lists. Nothing picked leaves agy's requests as today.

The gateway had no Gemini case in withFixedEffort, so a pick, a fixed member,
a rule's effort or a mapped level did nothing on a Gemini-wire request.
withGeminiEffort writes the thinkingConfig as the model takes it, from
vertexBudgets: a Gemini 2.5 gets a budget in its range (it refuses a level;
none is its least, or 0 for flash), a Gemini 3 a level from low to high
(minimal kept), a Gemini before 2.5 is left alone. includeThoughts is kept as
asked. The effort block and the needs-reasoning retry call it with the
upstream model (withModelEffort).

At a stopped WSL distro the field reads nothing (#3896), as
TestWSLColdPlaceOpensNothing asks.

Run on mote (mote-run), at the pushed head (rebased on 192d2eda8):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.
- go test ./internal/agent ./internal/gateway, whole packages: ok
  (gateway 943s) before the rebase; internal/agent again whole after the
  cold fix: ok. At the head: -run "Agy|WSLCold|AntigravityEffort" and
  -run "Agy|Effort": ok.
- GUI: agy-effort.test.cjs (new; window and panel, chromium and webkit,
  en zh zh-TW ja de) and cursor-local-effort: 54 pass, 0 fail.
  agent-field-names, agent-layout pass; i18n-keys' "a plugin's words are
  its own" is red as on main (#5332).

Broken by hand, each red then restored:
- withModelEffort returning the body as sent: TestAgyAgentEffort red
  (thinkingBudget -1 sent at high).
- agy's effort field taken out: TestAgyEffort red ("no effort field").
- 2.5's budgets taken from vertexBudgets: TestAgyAgentEffort and
  TestWithGeminiEffort red (thinkingLevel sent to gemini-2.5-flash).
- the field's cold check taken out (its first version):
  TestWSLColdPlaceOpensNothing red, stat of agy's settings.json.

Not tried: the full ./... suite (the suite lock on mote had ~10 runs queued,
some for 9h; agent and gateway were run whole instead); the real agy binary
against a sandbox gateway (TestAgyAgentEffort sends agy 1.5.3's captured
request body); a real Gemini API with a pick; a real stopped distro.

Reported-by: xyenon
2026-11-09 04:48:46 +08:00
yetone c6bdc172a0 netguard: a fake-IP resolver's own AAAA beside its fake A is left out, not refused
jiezhengj (Discord, 11-08): under Clash Verge Rev's TUN (mihomo
1.19.33, enhanced-mode fake-ip, fake-ip-range 198.18.0.1/16) every
web_fetch of `magpie mcp search` answered "it is at a private address".
#2593 already lets a name whose every answer is in 198.18.0.0/15 through,
so that wasn't it. Clash Verge Rev writes dns.ipv6: true and
fake-ip-range6: fdfe:dcba:9876::1/64 into its default config (and fills
in 2001:2::/64 when IPv6 is on without one), and mihomo then answers
AAAA from that pool too (dns/middleware.go withFakeIP, read at
v1.19.33). The resolver's answer was 198.18.x.y beside fdfe:dcba:9876::z,
the ULA is private, a fake answer beside a private one is refused, so
every name failed.

netguard.FakePaired names that AAAA: an IPv6 address in fc00::/7 or
2001:2::/48 while the same answer holds an IPv4 one in 198.18.0.0/15.
It is dropped where Loon's paired AAAA is dropped (dropLoon in the
gateway's publicTransport, iconIPs for a provider's icon, the two
places that share netguard), and the fake A is judged and pinned in its
place. 2001:2::/48 (RFC 5180 benchmarking) joins Public's special ranges;
it wasn't covered by 2001::/32 and passed as public.

Why this opens nothing new: the AAAA is never dialled. What is dialled
is the fake A, exactly as when the resolver answered the A alone, which
#2593 already allows: an address in 198.18.0.0/15, which no host on a
normal network uses, so without a TUN it goes to the default route and
reaches the internet or nothing. A hostile DNS that pairs 198.18.0.9
with fd00::<a LAN host> gets the 198.18 address dialled, never the LAN
one. Through a proxy on this computer the proxy gets the name, as for a
pure fake answer; a hostile resolver could already give a proxy another
answer for that name than it gave magpie, so the pairing adds no route.
What stays refused (tests below): a ULA or 2001:2:: alone or beside a
real A, a fake pair beside 10.0.0.1 or ::1, a fake A beside a public
address, and ULA / 2001:2:: / 198.18 address literals.

Ran (on mote; whole packages at base f1a4b5751, the -run set, vet and
gofmt again after the rebase onto the next main):
- go test ./internal/netguard ./internal/provider ./internal/gateway
  -run 'FakePaired|FakeIP|Loon|Icon|Public|Fetch|Guard|Private': ok
- go test -timeout 45m ./internal/netguard ./internal/provider
  ./internal/gateway (whole packages): ok (netguard 0.2s, provider
  130s, gateway 838s)
- go vet for darwin, GOOS=linux and GOOS=windows on those packages,
  gofmt -l internal cmd: clean

Broken by hand: with netguard.go, image_fetch_guard.go and icon.go back
at origin/main, TestFakeIPWithItsIPv6Answer fails with the reporter's
own message ("couldn't fetch http://example.com/: it is at a private
address ..."), TestFakeIPRefusesTheRest lets http://[2001:2::7]/
through, and TestIconIPsLoon refuses fdfe:dcba:9876::5 + 198.18.0.5 and
keeps 2001:2::5. Green with the fix.

Not tried: a real Clash Verge Rev / mihomo TUN on mote or the Mac (the
answers are a fake resolver in the tests, nothing reaches the network);
sing-box's inet6_range is covered only as far as it is a ULA. Not run:
the full ./... suite (mote's suite.lock had five full runs queued).

Reported-by: jiezhengj (Discord)
2026-11-08 22:55:09 +08:00
yetone 7a56c83e72 gateway: a compaction Copilot sealed stays out of Codex's auto-review
echo_ts (Discord #feedback) runs Codex Desktop's turns on GitHub Copilot
through magpie, with Copilot's native compaction on, and Codex's
auto-review on its built-in codex-auto-review through the ChatGPT
sign-in. The guardian's review carries the conversation's history, so
after the first compaction it carried Copilot's sealed compaction item
too. A request for one of Codex's own models with no magpie Codex
account to route it is relayed to the sign-in as it came, and
codexInputAs keeps any non-magpie1: compaction ("OpenAI's own, for
OpenAI"), so OpenAI was sent Copilot's ciphertext and refused every
review: 400 invalid_encrypted_content "The encrypted content P4ih...bDU
could not be verified". After the next compaction, the new ciphertext.

The siblings: a side call routed through magpie (the auto-review set to
a magpie model, a subagent or a title on another provider's model)
met checkpointReaders, found no writer among its candidates and was
refused with checkpointError, so the review failed there too. A turn or
a /responses/compact on one of Codex's own models relayed to the sign-in
sent the seal to OpenAI to be refused (sealedCompact took a Copilot
writer for the sign-in's own and relayed it).

Now:
- compactionAside names the calls Codex makes beside the conversation
  with its history in them: the guardian (or anything asked on
  codex-auto-review), memory, subagent, title, description, thread
  summary, prediction and suggestion. In serve, when the writer of the
  sealed compaction isn't among such a call's candidates, it goes on
  without the compaction item (withoutCompaction, body and plain);
  instructions, developer/user messages, the turns since and their tool
  calls and outputs stay. The conversation's own turns are still held
  to the writer or refused saying why (#1099), unchanged.
- foreignToSignin: on the relay to Codex's own sign-in (codexBackend), a
  compaction magpie recorded as sealed by a provider other than the
  Codex subscription is never relayed. A side call goes without it; a
  turn or a /responses/compact is answered checkpointError, magpie's
  own explanation, with nothing sent to OpenAI. A seal with no record
  (OpenAI's own, compacted on the sign-in), one the codex provider
  sealed, and one whose provider can't be read are left as before.
No portable plaintext summary exists for a native compaction (only the
writer can read it), so the side call goes without it rather than with
a summary.

Run (on mote, through mote-run, at 9730e0199 + this change):
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/usage/: ok (gateway 926s, usage 35s)
- go test -run 'TestForeignCompaction|TestNativeCompaction|TestCodex'
  ./internal/gateway: ok, again after rebasing onto f1a4b5751
  (which changed internal/gateway: trace.go and others)
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  ./internal/gateway; GOOS=linux go build -tags nogui, GOOS=windows go
  build: clean; gofmt -l internal: clean

Broken by hand: with the three non-test files at 9730e0199,
TestForeignCompactionLeftOutOfAutoReview is red in 4 subtests: the
review through the sign-in gets the reporter's exact 400 ("The
encrypted content P4ih...bDU could not be verified ...
invalid_encrypted_content"), the review and a subagent on another
provider's model are refused "compacted natively by copilot@student",
and a gpt-5.5 turn and its /responses/compact sent Copilot's seal to
OpenAI.

Not tried: the reporter's real Codex Desktop, Copilot or ChatGPT
account; the shape is from their report (Copilot compaction item with
encrypted_content, guardian on codex-auto-review). A Copilot compaction
magpie has no record of (made before compactions.json, or older than
30 days) still goes to the sign-in as before. No full ./... run: mote's
suite lock has had full suites queued for 4h; the change is confined
to internal/gateway.

Reported-by: echo_ts
2026-11-08 22:33:12 +08:00
yetoneandFlandern1211 16e79fc6b0 dsh: a request still answering shows under its fork, not its source (#5542)
The Routing page's live card for a dsh fork's request showed under the
source until the reply was written: it has no reply id yet, and the
opening it is keyed by is the one the fork copied. The messages of the
request's turn are in the branch's own session file before the request
goes out, so they name it:

- gateway: Route.LastConvs, the ids of the user messages the request's
  turn carries, newest first (dshLastConvs, dsh only, at most 4);
- sessions: TurnConvs, the ids of the newest turn's user messages, reset
  at turn/start, not kept from a fork's seed, at most 4 (dshTurnKept);
  dsh's parse version goes to 3;
- gui: ownerBy asks the reply id, then the turn's messages, then the
  opening (ownerOfRoute on the Routing page).

Changed from Flandern1211's patch (957caf84) in review:
- the turn lookup has the reply id's guard (forkedFrom): a "继续" in
  another conversation's newest turn no longer takes a route;
- in dsh's captured requests (sessions/testdata/dsh-gateway) the newest
  user message is the runtime context, the same for every session of a
  folder, so it names no one: the gateway reads the whole run of the
  turn's user messages (typed + context), and passes over Messages'
  tool_result steps, where the patch returned nil;
- looseKeys asks for a turn's keys only while the route answers and for
  convsKept, not for every older route: those keys are never listed
  once a newer turn starts, and would relist every agent's sessions on
  each 2s poll;
- one spelling per message and at most 4 kept (a v3 file has no
  turn/start, so TurnConvs grew with every message, 3 ids each);
- no TurnConvs on Context's records (it counts done calls, named by
  reply), LastConvs dropped from the history (saveRoute) and from what
  the page is sent;
- dshLastConvs reads messages by their members, not decoded: 0.49 ms
  on a 2.2 MB body of 800 tool steps (convOf 0.30 ms), 1.10 ms before.

Run on mote at 2be7aaeea (this change on 9730e0199; then rebased over
ec7a18d12, which changes GUI strings and .cjs tests only, no Go):
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/
  ./internal/gateway/ ./internal/agent/: ok (sessions 30s, gui 158s,
  gateway 952s, agent 262s).
- CGO_ENABLED=0 GOOS=linux and GOOS=windows go vet -tags nogui of the
  three packages: clean; gofmt -l internal: clean.
- No GUI asset changed, so no .cjs run.

Broken by hand, each red: LastConvs not set in serve
(TestDshRoutesCarryTheSessionConvs on the real captured requests), no
turn/start reset, no cap, no guard on the turn lookup, no looseKeys
bound, no LastConvs keys in looseKeys (end-to-end Routing test stays on
the source), no strip of the page's routes, no tool_result skip, no
strip in saveRoute.

Not tried: a real dsh fork live (no dsh session files on this Mac or
mote); the contributor measured their version on magpie web.

Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
2026-11-08 22:25:58 +08:00
yetone 9730e01992 claude: a reply the client keeps as several text blocks goes on in its run (#5705)
A run is kept idle under a key hashed from the conversation with its
reply as the one text it said (every text event run together). The
Anthropic encoder closes a text block at any other event: a thinking
block, a web search, cited text, an attempt Claude Code asked again. So
the client holds the reply as several text blocks and sends them back
that way. messageWords joined parts with a space, so the client's reply
read "Looking at it: Here" where the run's read "Looking at it:Here".
The keys differed, the loose-turn check failed too, and the next turn
logged "no run waits for this turn: no run here has had this
conversation". It was then told to a new Claude Code from a transcript,
which wrote the whole conversation to the cache again (jerrychoi: ~706K
tokens 56s after a cold rebuild, with the first run still alive).

The words hashed for a message now hold no whitespace. Where the client
spaces or splits its text no longer counts, for the turn key, the
conversation keys and the loose turn alike. lostMedia reads per-part
words (messageParts), which are unchanged.

Run (on mote, through mote-run, at b657a2121 + this change):
- go test -count=1 -timeout 45m ./internal/gateway: ok (890s)
- go test -run TestClaudeReplySplitIntoBlocksGoesOnInItsRun -count=3: ok
- GOOS=linux go vet ./internal/gateway, GOOS=windows go vet
  ./internal/gateway: clean; gofmt -l: clean

Broken by hand: with the old messageWords, the new test is red with the
reporter's exact line, "claude: no run waits for this turn: no run here
has had this conversation", followed by "a new Claude Code is told the
whole conversation: 3 messages".

Not tried: the reporter's own reply structure is not known. It may have
been thinking between texts, a web search or citation, or a retried
attempt; the issue asks for the block types. No real Claude account was
used. The test skips on Windows (a shell script stands in for Claude
Code). No full ./... run: the change is confined to internal/gateway.

Reported-by: jerrychoi
2026-11-08 22:01:34 +08:00
yetone b657a2121b gateway: URL-safe or unpadded inline base64 goes upstream as standard base64 (#5697)
Cause: Google's Python SDK (google-genai) writes a part's bytes with
base64.urlsafe_b64encode, so an image sent with Part.from_bytes reaches
magpie's /v1beta/models/{model}:generateContent with '-' and '_' in
inlineData.data. Google's own API reads either alphabet; magpie passed
the string on as it came, and dludream's Gemini provider (gemini-2, a
Gemini API behind a proxy) answered 400 "Failed to base64-decode image
data". The same request with '+' and '/' answered. Every reader of an
image's bytes inside magpie (HEIC and webp conversion, resizing, the
describer, token counts) decodes the standard alphabet too, so such an
image was passed over by each of them as well.

Fix: stdBase64Body (base64_input.go) writes inline base64 a client sends
as standard, padded base64 at the top of serve, before anything reads
the body, and in count_tokens: every image block of every protocol
(Chat and Responses data: URLs, Anthropic base64 sources, tool results)
through walkImages, and every Gemini inlineData part whatever its type
(a PDF, a recording; turns, function responses, the system instruction,
camel or snake case), spliced in place so the rest of the body keeps its
bytes. So every route has it: Gemini passed through to a Gemini
provider, translated to Chat, Messages or Responses, a plugin's fetch,
and another client's image sent to a Gemini provider. Base64 that is
standard and padded already is not touched (the body comes back byte for
byte), nor is a string with both alphabets or one that isn't base64.
A byte scan (a 64+ character base64 run ending a string with '-'/'_' in
it or a length not a multiple of 4) keeps the walk off other requests.

Test: the fixture is the reporter's literal case, a 32x32 white PNG as
PIL writes it, base64.urlsafe_b64encode'd (it has a '-'; the test checks
standard base64 refuses it). TestURLSafeBase64ReachesUpstreamAsStandard
posts it through the gateway to a fake upstream that answers as
dludream's did (400 "Failed to base64-decode image data" for non-standard
base64): Gemini to a Gemini provider named gemini-2 at the reporter's
path gemini-2/models/gemini-3.8-flash, Gemini to Chat, Messages and
Responses, Chat and Messages to Gemini, and an unpadded URL-safe PDF.
TestStdBase64Body covers each protocol's block shape, fields kept, and
standard bodies left byte-identical; TestGeminiStdBase64SystemFirst a
system instruction before the turns.

Run on mote at this tree (on origin/main b85475e57):
- go test -count=1 -timeout 45m ./internal/gateway/: ok (902s)
- the new tests with -v: every subtest passes
- go vet ./internal/gateway/ for GOOS=linux, windows, darwin: clean
  (windows and darwin also over ./internal/...; linux over ./internal/...
  stops in wails' cgo files when cross-compiled, untouched here)
- gofmt -l: clean
Rebased onto 2c31815c5 (a one-line Kiro mover min in internal/provider);
at the pushed head the new tests, the HEIC/webp tests and go vet of
internal/gateway ran again: ok.

Broken by hand: with the stdBase64Body line in serve commented out, all
7 subtests of TestURLSafeBase64ReachesUpstreamAsStandard went red with
the upstream's 400; without the sort of the Gemini edits,
TestGeminiStdBase64SystemFirst went red (both parts left URL-safe).

Not tried: the reporter's real upstream (Google's API or their proxy);
the fake answers as their report shows. Not tried with the Python SDK
itself; the fixture is the bytes it writes. Inline base64 of non-image
files in Chat (file_data, input_audio) and Anthropic document blocks
is not rewritten: their official SDKs send standard base64, and no
report has them otherwise.

Reported-by: dludream
2026-11-08 20:53:19 +08:00
yetone 9bef67d420 gateway: Claude Code's and Codex's requests reach a Remote magpie as magpie's, so it takes X-Magpie-*
linkaww (Discord #feedback, Mac v0.1.3315 to a Docker remote v0.1.3288):
a capture showed X-Magpie-Claude-Cache-TTL reaching the remote on a
request whose User-Agent was claude-cli/2.1.319, not magpie/. The
remote takes X-Magpie-* only from a magpie's request (magpieAsks), so it
dropped the cache lifetime (Opus still 5m, Haiku 1h), the agent, the
computer (X-Magpie-Via), X-Magpie-User-Agent, and X-Magpie-Hops, the
guard that answers 508 when two magpies are each other's remote.

Cause: forwardOnce sets magpie's User-Agent for a Remote magpie
(userAgentFor, OwnClient), then #179's copy of Claude Code's headers
(p.Account == nil) put claude-cli/... back over it. Codex had the same
hole: its copy (codexClientHeader) puts codex_cli_rs/... on too, which
keepTurnAsks had already worked around.

Fix, on the sending side: after every copy, a request to a Remote magpie
goes with magpie/<Version> (forwardOnce). Decision, retrieval, image and
video requests already set it at their call sites and copy no client
header. On the receiving side, so a relay behind the remote that serves
only Claude Code or Codex still gets their headers: the remote knows
Claude Code by the User-Agent the near magpie named (claudeCodeAsks,
agentUA) for #179's copy, ?beta=true, the test-as record and Desktop's
move, and both copies put on the agent's User-Agent (agentUA), not the
magpie/ one that came in. Codex is known there by its originator, as
before. A key+URL provider that is not a magpie still gets Claude Code's
and Codex's own User-Agent (TestClaudeCodeHeadersReachAnthropicRelay,
TestRemoteMagpieClientHeaders).

The reporter's guess that this empties the remote's Usage > Sessions is
not borne out: with the bug the remote still recorded each call's
session id (x-claude-code-session-id was copied), only under agent
"claude-cli" with no via. Filed separately.

Run (on mote, mote-run, at this tree):
- TestRemoteMagpieTakesClientsHeaders (new): Claude Code and Codex
  through two in-process gateways to a relay. The remote is asked as
  magpie/, with X-Magpie-User-Agent; callerFrom on what it got reads agent,
  via, hops 1, the relayed UA and the TTL 5m picked in settings.json; the
  relay gets the agent's UA, originator, x-app and ?beta=true and no
  X-Magpie-*; the remote's record names the agent and a via.
  Red on the old gateway.go: UA claude-cli/codex_cli_rs at the remote,
  agent "claude-cli", via "", hops 0, ttl "".
- go test -tags nogui ./internal/gateway -run
  'Remote|ClaudeCode|Codex.*Header|UserAgent|ClaudeCacheTTL|Desktop|SawClient|TestAs|Hops|Loop': ok.
- gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway: clean.
Broken by hand:
- the magpie UA reset taken out: the new test red in both subtests
  (remote sent claude-cli/codex UA, nothing taken).
- the remote-side detection put back to fromClaudeCode(in) and the copies'
  UA left as it came: the new test red (x-app and ?beta=true lost,
  relay sent magpie/dev) and TestRemoteMagpieClientHeaders' three Codex
  cases red 403.
Not tried: a real Docker remote or a real Claude Code; the full suite was
not run at push (run after). The remote must update too for its relays
to send them as the agent: an older remote, asked as magpie/, copies no
Claude Code x-app, X-Stainless-* or ?beta=true to its relay, and puts
magpie/ over Codex's User-Agent there (it is known by its originator), so
a relay behind it that serves only Claude Code or Codex refuses until it
updates. The TTL, agent, via and hops need only this (sending) side.

Reported-by: linkaww
2026-11-08 19:10:30 +08:00
yetone e215d335a6 gateway: a gateway key can cap its requests at once; the rest wait their turn
young02036 on Discord: a provider can be given a concurrency, so why
can't a gateway key? A key now has an optional MaxConcurrency, from 1
to 1000. Left unset (every key today), nothing changes.

- access: Key and Change get MaxConcurrency, and Identity carries it, the
  issuer's cap included. The concurrency-key action refuses a value
  below 0 or above 1000.
- gateway (key_slots.go): every route that asks a model is held to the
  key's cap, however the request came (loopback, LAN, a Remote magpie, a
  Responses socket's turn). One request too many waits in the key's
  queue in arrival order. It shows as "slot" in Active, and its wait goes
  into the try's Queued. A request whose agent goes away while it waits
  leaves the queue and sends nothing. A stream holds its slot until it
  ends. serve's routes (chat, responses, messages, ollama, gemini, the
  Codex backend) wait inside the try, after keepQueued, so a streaming
  agent gets keepalives while it waits. The other model routes (images,
  embeddings, rerank, audio, videos, search, decisions, native) wait
  before their handler runs. forward and codexUpstreamOn take the slot
  too, so nothing reaches a vendor without one. A key issued under
  another waits for its own slot, then for its issuer's.
  /v1/magpie/concurrency lists each capped key under "keys", and counts
  its waiters in "waiting". A key's limit (key_limit) reports the cap.
  Not held, as a provider's MaxConcurrency doesn't hold them: GET,
  HEAD, OPTIONS, count_tokens, :countTokens and MCP.
  TestKeySlotEveryRoute fails when a route is judged neither held nor
  free.
- cli: magpie gateway-key concurrency <id> [<n>|off]. It refuses 0, a
  negative, over 1000, a fraction, a word, --help or an extra argument
  with its usage.
- gui: the key row gets a badge in the provider concurrency badge's
  style. It opens the app's menu with No limit, 1/2/3/5/10 and Other…,
  and Other… takes a number typed in place. A value that isn't a whole
  number up to 1000 is refused and nothing is sent. Browser and
  read-only keys have no badge. Strings are in en, zh, zh-TW, ja and
  de. An unset badge, which a hover shows, gives way before the masked
  key (flex-shrink 8). Without that, at 420px in en and de, the extra
  badge squeezed the key until its copy button slid under the pointer
  that came to drag the row, and gateway-key-arrange went red.
- docs/subsystems/gateway-routing.md describes it.

Run (on mote, at this tree on origin/main 0f8c3d867; rebased onto 627fd1a3b,
which touches none of these files, and the budgets were run again):
- go test -timeout 45m ./internal/access ./internal/gateway ./internal/cli
  ./internal/gui: access, gateway (839s) and cli ok. gui had one red,
  TestGatewayModeStatsNameTheGatewaySessions, run at 00:40 PST: its
  record an hour back falls on yesterday in a day's first hour. It
  passes from 01:09, so it is unrelated; filed as #5690. The Budget/Size
  tests were run again after the CSS change: ok.
- gofmt -l: clean. go vet for darwin, plus GOOS=linux and GOOS=windows
  (-tags nogui), on those packages: ok.
- GUI (node --test, Chromium and WebKit, 1100 and 420 wide, en, zh,
  zh-TW, ja and de): every file that loads the gateway keys (59) plus
  i18n-keys and i18n-en-no-cjk. The reds left are the same on
  origin/main and already filed: gateway-key-models en (#5233, #4081),
  i18n-keys "a plugin's words are its own" (#5332), phone-connect-menu
  at 420 (#4706, #4707). After the flex-shrink fix:
  gateway-connect-keys, gateway-key-arrange, -concurrency, -mcp,
  -own-rotate and -quotas passed 104/104 in both engines, against
  84/84 on base.
- The tests:
  - TestKeyConcurrency, over LAN with cap 2: 2 of 3 requests reach the
    vendor and the third is shown as "slot". Another key isn't held. A
    cancelled waiter leaves the queue and never reaches the vendor. The
    third goes once one ends, every lane is given back, and its Queued
    is at least 40ms.
  - TestKeyConcurrencyKeepsStreamAlive: a waiting stream gets 200 and
    keepalives.
  - TestKeyConcurrencyEager: on embeddings an issued key waits on its
    parent's lane, a cancelled waiter leaves, never more than 1 runs at
    once, and a GET takes no slot.
- A real `serve` in a sandbox HOME (built from this tree, MAGPIE_ADDR
  127.0.0.1:38612) against a fake slow SSE upstream. Steps: `provider
  add fake url=…`, `gateway-key add`, `gateway-key concurrency <id> 1`,
  then three concurrent keyed streams. /v1/magpie/concurrency showed the
  key at busy 1, waiting 2, limit 1 (two in "slot"). The upstream's
  most at once was 1, and it saw 3 requests one after another (200s at
  1.9s, 3.7s and 5.5s, each with [DONE]). Afterwards "keys" was empty.
  `concurrency <id> 2000` exited 1 with its usage.

Broken by hand (each went red, then restored):
- keySlot returns nil: TestKeyConcurrency ("timed out waiting for c
  queued") and KeepsStreamAlive.
- The issuer's lane skipped: TestKeyConcurrencyEager.
- The eager take skipped: TestKeyConcurrencyEager.
- The CLI's bounds check removed: "accepted [concurrency id 0]".
- The GUI's bounds check removed: gateway-key-concurrency.
- Without the flex-shrink line: gateway-key-arrange chromium/webkit en
  and de 420px.

Not tried / not done:
- Full suite not run at push (neither `go test ./...` nor the whole GUI
  suite).
- Not tried with a real vendor account or a second computer on the LAN.
  The LAN path is covered by TestKeyConcurrency's lanServer.
- The key's badge shows the cap, not live running or waiting counts.
  /v1/magpie/concurrency has those.

Reported-by: young02036 (Discord)
2026-11-08 17:52:09 +08:00
yetone 627fd1a3b7 claude: a turn Claude Code ends with no answer is a 502 saying why, not a 200 with content null
steven_4422 (Discord) sent 18 PNG frames as image_url parts to
claude/claude-sonnet-5-5 in a Chat request, not streamed, and got 200
with {"message":{"content":null},"finish_reason":"stop"} and zero
usage; 17 were answered. Whatever ended Claude Code's turn, the bridge
took an end with nothing said as the answer:

- a run that exits with a request waiting and nothing begun (the
  interactive helper at its deadline, or failing to send the message,
  exits 1 with the reason on stderr) closed the segment empty;
- a turn whose result came with no message, or only a <synthetic> one
  of Claude Code's own words, left the segment open to be closed empty
  by the exit or the run's timeout;
- relay finished a reply whose events ended with neither a KStop nor a
  KError: the collector's empty result went as a 200, a stream ended
  as a finished reply.

Now readOutput ends such a turn with a 502 carrying Claude Code's own
words, else its result's, else "said nothing of why"; the exit
goroutine emits "Claude Code ended before it answered" with its exit
and stderr; relay turns an unended reply into a 502 (whole) or an
error event (stream) in every protocol. A 5xx lets another account
take over, as other bridge failures do.

Claude Code itself (2.1.316, read from its binary and run on mote
against a fake Messages API) has no image-count limit: it passed 18,
24 and 40 images through, by -p and by the interactive helper, and
turns the API's refusal of an image into an is_error result, already
a 4xx/5xx here. So 18+ images are passed through, and what refused or
dropped the reporter's turn is upstream of magpie; the client now gets
its reason instead of an empty answer.

Run (mote, at this head, rebased on 0f8c3d867):
- go test -tags nogui -race -count=1 -timeout 45m ./internal/gateway/
  ./internal/claudetui/: ok (gateway 1607s,
  claudetui 131s), no races.
- GOOS=linux and GOOS=windows go vet of both packages: ok; gofmt -l clean.
- Full suite: not run at push.

Broken by hand: with claude_subscription.go at its parent and the new
tests kept, all 36 TestClaudeSilentTurnFails cases and all 4
TestRelayUnendedReplyFails cases are red: the exit variant, not
streamed, gives the reporter's body byte for byte (200, content null,
zero usage); streamed, a 502 with no reason; the result and synthetic
variants hang until the test's 20s deadline.

Not tried: a real Claude account at 18+ images (no credentials on
mote, and the Keychain is off-limits), so the upstream reason for the
reporter's turn is unknown; the interactive mode through the gateway
against real Claude Code (the helper alone was run with 18 and 40
images against a fake API).

Reported-by: steven_4422 (Discord)
2026-11-08 17:05:09 +08:00
yetone 0f8c3d8672 claude: a deferred built-in the bridge's model calls reaches the client as WebFetch, not mcp__magpie__WebFetch
Claude Code with tool search on leaves WebFetch, WebSearch, CronCreate and
the other deferred built-ins out of tools until a ToolSearch loads them.
The run's model, offered the client's tools as mcp__magpie__<name>, called
mcp__magpie__WebFetch, and toolStart handed that over whole: the 11-02
fix for an unloaded magpie MCP tool (packinggoods) kept the full name for
every cut name the client hadn't declared. The client answered "No such
tool available: mcp__magpie__WebFetch", the model retried, and
status lines such as claude-hud showed a "magpie" MCP failure.

toolStart now keeps the prefix only when the cut name has the router's
form, <server>__<tool> (magpieServerTool): the client names magpie's MCP
tools mcp__magpie__<server>__<tool>, and its built-ins (WebFetch,
WebSearch, CronCreate, CronDelete, CronList, NotebookEdit, Monitor,
TaskStop, SendMessage, EnterWorktree, ExitWorktree: the deferred list of
a real Claude Code session) have no __ and no prefix. A sibling the same
line got wrong: another MCP server's deferred tool, called as
mcp__magpie__mcp__linear__get_issue, is handed over as
mcp__linear__get_issue, the client's name (it was handed over whole too).
toolStart is the one place a called name is mapped back for the client:
streamed and whole messages and the interactive mode's early call
(r.onCall) all go through it; mcpCall's declaredName serves offered
tools only, and the history's names (bridgeName) are unchanged.

Run (on mote, at this tree):
- go test ./internal/gateway -count=1 -timeout 45m: ok
- gofmt -l: nothing; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok; go build: ok
Broken by hand: magpieServerTool returning true (the old behaviour)
turns TestClaudeBridgeHandsOverAnUnloadedMagpieTool red on the new
WebFetch and mcp__linear__ cases ("handed a call of
mcp__magpie__WebFetch, want WebFetch").
Not tried: a real Claude Code client with tool search on (the reporter's
Windows setup); a deferred tool the run's model calls by the bare client
name (WebFetch) is still the run's Claude Code's to answer and isn't
handed over. A client MCP server of its own named "magpie" with a tool
lacking __ would now be cut; magpie's router names every tool
<server>__<tool>.
Rebased on eadc6cdb9 (GUI routing files only); at the pushed head
go test ./internal/gateway -run 'TestClaudeBridge|TestClaudeToolChoice|
BridgeToolName': ok.
Full suite: not run at push.

Reported-by: steven_4422 (Discord)
2026-11-08 16:05:42 +08:00
yetone 1aabc66fd1 gateway: /v1/models answers its ETag, and 304 to a client that has the list already
clyzhicore (Discord) runs a server magpie as the gateway and a local magpie
that takes its /v1/models and writes the models into dsh. They asked for
an ETag or a list you can wait on, so the local side knows a change at
once and a dead connection costs little. The wait is there since
06c4582cc (v0.1.3172: X-Magpie-List-Wait with If-None-Match, and the
Remote magpie follower). What was missing, and is added here:

- A plain GET /v1/models (no wait header) is answered with the same ETag
  a wait answers (listTag of the bytes this caller gets), Cache-Control
  private, no-cache, and 304 with no body, at once, when If-None-Match
  names it (strong or W/, in a comma list, or *). A tag it doesn't name,
  or none, is answered the list as before, same bytes. A refused list
  (400) stays untagged. Any client (a script, curl, another tool) can
  now poll cheaply.
- A wait's answer, 200 or 304, says in X-Magpie-List-Wait how many
  seconds it held. A plain answer doesn't.
- The follower (waitRemoteList) takes a 304 that comes sooner than
  followQuick (5s) without that header as a magpie that doesn't wait.
  This guards the change above: a proxy that drops X-Magpie-List-Wait
  would now get a tagged plain list and an instant 304, and the follower
  would ask every followGap (1s). It now leaves such a magpie to its
  schedule and asks again after followOldAgain (1h), as for one from
  before the wait. Servers from 06c4582cc on hold each wait to its end
  (50s), so their 304s pass.

Compatibility: an old server (no ETag) is still left to the schedule,
as TestRemoteMagpieOldListNotFollowed checks. An old client never sends
If-None-Match without the wait header and gets the same bytes plus an
ETag. The GUI doesn't read the gateway's /v1/models through Wails (whose
304 on WebView2 is a 505, gui/api.go writeJSONSame), so that doesn't
apply.

Hidden models (their second ask) already exist and are not changed: a
provider's "Only through routing groups" (Provider.Unlisted, `magpie
provider listed <id> no`) and a group's listed=no (Group.Unlists, `magpie
group set ... listed=no`, CLI only) keep models out of /v1/models while
groups still route to them.

docs/subsystems/gateway-routing.md says the above.

Run (on mote, through mote-run, first at 04ed05733):
- gofmt -l on the changed packages: clean.
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet
  ./...; go build ., GOOS=linux -tags nogui, GOOS=windows: all ok.
- go test -tags nogui -race -count=1 -timeout 90m ./internal/gateway:
  ok 2145s, no DATA RACE (mote at load ~100-130).
- go test -tags nogui -count=1 -timeout 45m ./internal/provider: ok 126s.
- After rebasing onto origin/main (5 commits, none in these files):
  gofmt -l clean; go vet (darwin, linux nogui, windows) of both
  packages ok; -race -run "ModelsWait|ModelsList|RemoteMagpie": gateway
  ok 12.5s, provider ok 4.8s.

Broken by hand, each red:
- models() back to listModels (no tag on the plain list):
  TestModelsListConditional ("ETag \"\"") and TestModelsWaitTagged ("a
  plain list: 200, ETag \"\"").
- tagNamed never matching: TestModelsListConditional (200 with the body
  for each of the tag, W/, a list and *).
- No X-Magpie-List-Wait on a wait's answers: TestModelsWaitTagged ("a
  wait's list says it held \"\"", same for its 304).
- The followQuick check off: TestRemoteMagpieStrippedWaitNotAskedOver
  ("asked 28 times in 300ms, want 2").

Not tried: two real magpies, or a real reverse proxy that drops the
header (the stripped case is a fake in the test). Not run on Windows or
Linux. The full suite (go test ./...) and the GUI suite: not run at push.
Following a provider added as a plain OpenAI-compatible endpoint (not the
Remote magpie type) is not done: its list URL comes from fetchOne's
several bases, and it still goes by its #2135 schedule.

Reported-by: clyzhicore (Discord)
2026-11-08 15:45:57 +08:00
yetoneandggbdpq 4375805354 gateway tests: the long plugin reader's deadline follows the reply's progress, not the wall clock (#3286)
TestPluginStreamLongActiveReader went red under -race on macOS CI
(run 42449115269 at 691a10446, 75.54s): "SSE read after 38977536
content bytes: context deadline exceeded (Client.Timeout ...)". The
test's client carried a fixed 75s Client.Timeout over the whole
request, and the reply it reads is paced at 2.5MiB/s, so 40MB takes
16s on an idle machine and whatever a loaded -race runner makes of it
otherwise. The reader was still reading when the deadline cut it.

Change (test only):
- pluginReplyGateway's client has no total deadline. pluginReplyComplete
  arms a 60s idle guard (context.WithCancelCause) that progress resets:
  a frame the fake vendor wrote, an SSE event with content reaching the
  client, or, for a JSON reply, a read with more than whitespace in it.
  A reply that stops part way is red with "nothing moved for 1m0s"
  beside the read error.
- Wire bytes alone are not progress. ggbdpq's patch on the issue (the
  base of this change) reset the guard on any read with bytes; with that
  rule and the vendor's writes, broken by hand (credit never given back),
  the test was still waiting at 168s, because the gateway's ": keepalive"
  lines (every 15s, for up to 5 minutes) kept resetting it.
- TestPluginStreamLargeReplies runs through the same guard;
  TestPluginStreamStalledClientKeepsOtherRequestsMoving's second request
  keeps its own 3s context.
- The test's comment no longer speaks of a stall window: the host's
  credit window replaced it, and the test now says so.

Timing assumptions left: 60s with no progress anywhere is a stall
(progress arrives every few ms at the slowest pace here), and the
12s floor on elapsed is held by the reader's own pacing (16s minimum).

Run on mote (go1.26.8), base 1d5b5dc2d:
- Reproduced by capping the reader at 512KiB/s (1<<19) on the old
  code: red at 75.18s, "SSE event after 38723584 content bytes:
  unexpected end of JSON input" (the 75s deadline cut a line).
- The same cap on this change: ok, 81.45s, all 41943040 content bytes
  (vendor done after 72s).
- Broken by hand, host.credit a no-op: red at 65.43s, "SSE read after
  491520 content bytes: nothing moved for 1m0s".
- Broken by hand, the body given up 10s after its first read (the old
  stall window, ignoring progress): red at 10.19s, "SSE error after
  18219008 content bytes: ... the consumer stalled past the window".
- go test -race -count=1 ./internal/gateway: ok (1805s).
- gofmt -l internal/gateway: clean; GOOS=linux and GOOS=windows go vet
  ./internal/gateway: ok.
- Full suite: not run at push.

Fixes #3286

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-08 15:11:41 +08:00
yetone 9a92fd099b claude: a long auto mode classifier keeps its cache marks as claude -p (#5585, #5655)
With Claude Code's interactive mode on, the classifier was pasted into a
new run each call with none of its marks: Claude Code marks only the last
block of what it is pasted, and the classifier's tail changes every call,
so each call read only Claude Code's own prompt and wrote the whole
transcript again (126K and 132K a call at 1h's 2x in iamnil's rows).
Desktop's header-less classifier lost its marks at parse time
(e5f66f8a6); an opted-in one lost them when pasted.

There is no honest way to make the interactive Claude Code put a mark
mid-message: rewriting its body in tap.js would make the request unlike
Claude Code's and can pass the four-mark limit. So a classifier whose
marks keep 64KB or more of history (marksPrintAt, keptByPrint) runs as
claude -p, which keeps the marks (DISABLE_PROMPT_CACHING, the client's
marks in the first message, the tail through CLAUDE_CODE_EXTRA_BODY).
-p counts about 2x a token; with S Claude Code's prompt, M the marked
transcript and D the new part, interactive ~ 0.1S + 2M a call and -p ~
2(0.1(S+M) + 2D), which meet at M ~ 15-20K tokens. A shorter classifier
and every other request stay interactive; claudePrint names it
"cache-marks". No entrypoint, system prompt or identity text changes.

Run:
- TestClaudeTUIClassifierKeepsLongMarksAsPrint (with and without the
  header; a short classifier as control) is red with keptByPrint forced
  false (the old routing) and green with the fix.
- On mote at 70c10074c: go test -tags nogui -run
  'Claude|Classifier|AutoMode|Cache' ./internal/gateway ok; go vet
  ./internal/gateway for darwin, linux and windows ok; gofmt clean.
- Real account (one Max account, sandbox HOME, its keychain item copied
  to the sandbox's service name and deleted after; port 3481; Claude
  Code 2.1.316; claude-haiku-4-5), two classifier-shaped calls sharing a
  ~244KB prefix, interactive mode on:
    before (4ab1191bc): call 1 read 0 wrote 49,838; call 2 read 0 wrote 49,865
    after:              call 1 read 0 wrote 49,763; call 2 read 49,748 wrote 42
  The gateway logged both after-runs as claude -p with the reason.

Not tried: Claude Desktop's real classifier (the body was built to its
shape), Sonnet, Windows/WSL. Full suite not run at push; queued on mote
under the suite lock.

Reported-by: jerrychoi
Reported-by: iamnil (Discord)
2026-11-08 11:39:44 +08:00
yetone 7880a00ac6 models: a model of a key's provider can be asked on System One
axelburks on Discord: a relay serves its decision model under a name of
its own (an Ark endpoint id). A key's provider with a System One URL
beside a conversation URL can set a model's API to decide (System One
in Model settings' API row, its chip's right-click, or `magpie model
api <pid/model> decide`). The model is then a decision model there:
asked on System One by its own name, offered to routing groups, kept
out of the conversation models, and a turn for it is refused with 400
before the vendor is asked. Auto gives it back. A provider with no
System One URL, with that URL alone, an account, a remote magpie and
Vertex refuse it, saying why. Chat routing (apisAmong) ignores decide.

Broken by hand: removing the decideSet check in DecidesModel turns
TestModelSetToSystemOneIsADecisionModel and
TestModelSetToSystemOneAskedThere red.

Run, on this stack over origin/main 0fc3455e2 (mote's suite lock had
hours of queue, so the suites ran on WSL magpie-desktop under flock):
- go test -timeout 45m ./internal/{provider,gateway,gui,cli,settings,fx}
  on WSL, ok; ./internal/codexcat on mote, ok; gofmt -l clean;
  go vet on mac, GOOS=linux -tags nogui and GOOS=windows on mote, ok;
  TestCoreScriptBudget ok (paid by cutting comments, no raise).
- GUI, both engines, every language, on WSL at the pushed head and at
  0fc3455e2: every touched test file plus the provider-editor files a
  first run found red. No red at head that isn't red at 0fc3455e2. The
  shared reds have issues: i18n-keys #5332, model-chip-steady #4388,
  model-copy-id #4621, models-works-only #4391, plugin-move-unserved
  #4392, provider-fetch-again #5232, provider-levels-save #4394,
  provider-levels-scroll #4395, provider-models-rest #4396,
  provider-picks-stay #4397, provider-typed #4673, remote-magpie #4398,
  zero-priced-free #5262, model-reasonless (webkit de) #4100,
  name-suffix-no-names #1937.
- Rebased on origin/main 4ab1191bc (gateway.go moved under it) and run
  again at the pushed head: gateway and provider ok on WSL, gofmt,
  vet (mac, linux nogui, windows) and the budget ok, i18n-keys,
  model-headers and routing-groups-back with only #5332's red.
Not run at push: the whole GUI suite (1277 files).

Not tried: a real relay's System One endpoint; fake vendors only.

Reported-by: axelburks (Discord)
2026-11-08 11:28:54 +08:00
yetone 7a6211d047 providers: a model's own headers, in Model settings
axelburks on Discord: a vendor routes one model by a header of its own.
A key's provider (built-in or custom) can give each model headers
(settings.ModelHeaders["pid/model"]). They go on that provider's
requests for that model alone, after the provider's headers and after
auth: a name both have is sent once, as the model's, so a user's value
is never overridden by the provider's or magpie's key header. The
gateway names the model (provider.WithModel) on every route that asks
one: chat on each API, translated and streamed, count_tokens, System
One's decision, embeddings, images, videos and the model test. A
fallback provider serving the same model id gets its own headers only.
Accounts and plugins carry their sign-in's headers and take none.

The editor's "Name, price and reasoning level" panel is now "Model
settings" (every language), with + Add header per model, staged and
made with the Save; Restore default takes them away.
The rows being typed are kept out of the draft's
compare, so an untouched editor still closes without asking.

Broken by hand: dropping WithModel from gateway.go turns
TestModelHeadersReachTheirModelOnEveryRoute red; dropping the provider
id check in modelOf turns TestModelHeadersStayWithTheirProvider red.

Run, on this stack over origin/main 0fc3455e2 (mote's suite lock had
hours of queue, so the suites ran on WSL magpie-desktop under flock):
- go test -timeout 45m ./internal/{provider,gateway,gui,cli,settings,fx}
  on WSL, ok; ./internal/codexcat on mote, ok; gofmt -l clean;
  go vet on mac, GOOS=linux -tags nogui and GOOS=windows on mote, ok;
  TestCoreScriptBudget ok (paid by cutting comments, no raise).
- GUI, both engines, every language, on WSL at the pushed head and at
  0fc3455e2: every touched test file plus the provider-editor files a
  first run found red. No red at head that isn't red at 0fc3455e2. The
  shared reds have issues: i18n-keys #5332, model-chip-steady #4388,
  model-copy-id #4621, models-works-only #4391, plugin-move-unserved
  #4392, provider-fetch-again #5232, provider-levels-save #4394,
  provider-levels-scroll #4395, provider-models-rest #4396,
  provider-picks-stay #4397, provider-typed #4673, remote-magpie #4398,
  zero-priced-free #5262, model-reasonless (webkit de) #4100,
  name-suffix-no-names #1937.
- Rebased on origin/main 4ab1191bc (gateway.go moved under it) and run
  again at the pushed head: gateway and provider ok on WSL, gofmt,
  vet (mac, linux nogui, windows) and the budget ok, i18n-keys,
  model-headers and routing-groups-back with only #5332's red.
Not run at push: the whole GUI suite (1277 files).

Not tried: a real vendor that routes by header (Ark); fake vendors only.

Reported-by: axelburks (Discord)
2026-11-08 11:28:54 +08:00
yetone 29bfd5dc8b gateway: a Responses stream magpie ends is a whole response.failed (plugins#852)
When a Responses stream ended short or was cut, passthrough wrote a
response.failed with only object, status and error. Grok Build reads
the Responses stream through async-openai's types. Their Response needs
id, created_at, model, object, output and status, and the event needs
sequence_number. So a Grok plugin stream cut by the vendor ended in
"serialization error: missing field `created_at`" instead of the error
(lxyer's report behind plugins#852).

Now passthrough writes a whole response.failed:
- usageSniffer keeps the stream's response id, created_at and the next
  sequence_number;
- if responsesTextCalls renumbered the events on the way out, the
  failure follows the last number the client got;
- id, created_at, model and the error are filled in.
Before any event there is a fresh resp_ id and the time now.
The Chat and Gemini failures are unchanged. The translator paths
already end through responsesEncoder, which writes a whole response,
and nothing else writes a Responses streamFailure.

Run:
- On mote, at this tree: gofmt -l; go vet ./... on darwin, linux nogui
  and windows; builds for all three; go test -tags nogui -timeout 45m
  ./...: 87 packages ok, one red,
  TestCancelledSignInEndsItsFetch in internal/plugin, which this change
  doesn't reach (open as #5264). That run was at the base 0fc3455e2.
  Rebased on 00198b26e (#5655, gateway): gofmt -l, vet on all three
  systems and go test ./internal/gateway again: ok. Rebased again on
  cdf734757 (automode text, OpenMausBot): vet, build and
  -run 'StreamFailure|AutoMode|Automode|Anthropic' ./internal/gateway ok.
- Red on the old code (the tests at 0fc3455e2's gateway.go and
  sniff.go): TestResponsesStreamFailureIsAWholeResponse ("no
  sequence_number", "response.created_at missing") and
  TestResponsesStreamFailureBeforeAnyEvent.
- Real Grok Build 1.0.67 on mote (`grok -p`, api_backend responses)
  against a fake server replaying each ending:
  - the old frame: "missing field 'created_at'";
  - a whole response without sequence_number: "missing field
    'sequence_number'";
  - the new frame, after text, after response.created, and bare: read,
    and retried as server_error, with no serde error.

Not tried: Grok Build 1.0.77 (the reporter's), and a live Grok stream
cut by the vendor.
2026-11-08 11:03:09 +08:00
yetone 06324e99e8 automode: say that Claude Code may have no local check behind a gateway
chenxiang0010 saw "Auto mode can't check actions in this session ...
your requests go through 127.0.0.1:3425, which doesn't pass it
through". magpie's comments and the gateway-routing and agent-wiring
pages said that Claude Code, finding no safeguard_results, classifies
locally. Claude Code 2.1.312 to 2.1.316 (read from their bundles) turn
that local classifier off behind a non-Anthropic base URL when
Anthropic's per-account flag tengu_bright_dragonfly is "all"
(PA(), bbt(): auto_mode_side_calls_retired, localClassifierSwitchedOff).
A call with no server verdict then gets "No classifier runs for this
session", and each action the check would judge asks for approval.
2.1.314 adds the text for CLAUDE_CODE_AUTO_MODE_SERVER=0: "Claude Code
no longer has a check of its own to use instead".

So on a route only Anthropic doesn't answer (another vendor's model,
another subscription's Claude, a translated route, a relay that drops
the fields), auto mode has no check at all for such an account. magpie
can't answer one on Anthropic's behalf. The reviewed routes (Anthropic's
API, a relay passing the fields, the Claude subscription bridge) still
carry the beta, safeguards and safeguard_results as before. Comments and
docs only, no change in behaviour.

Not changed: answering 400 naming safeguards on an unreviewed route, as
Claude Code's gateway spec allows. It sets a refused latch for the
session, so a later /model to a reviewed Claude stays unchecked, while
the strip loses nothing.

Run: gofmt -l internal (clean); go vet -tags nogui ./internal/gateway
./internal/agent on mote (ok).
Not tried: a real Claude Code run, since the flag is Anthropic's per
account and the reporter's route is unknown.

Reported-by: chenxiang0010 (Discord)
2026-11-08 10:55:10 +08:00
yetone 00198b26e0 gateway: a session's side call goes on the account its main conversation is on (#5655)
With two Claude accounts, Claude Desktop's own Sonnet calls beside an
Opus chat (desktop-beside), and Claude Code's auto mode classifier, ran
on account B while the chat was on A. Each model's conversation is kept
under its own scope (p.ID/model), so the side call was routed as a
session of its own: leastHeld, or Smart's order once its cache was cold,
put it on the account the fewest others held, and B's 5 hours drained on
calls the user never made there.

Decided (product call delegated): one session goes on one account. The
user picked one, the vendor sees one client, and the cost is one cache
write of the side call where the session goes on reading it.

withSession (affinity.go) puts first, for a request whose session a
header names, the key or account of that session's largest conversation
under another model's scope (answered within heldFor, at least
cacheWorth kept, larger than this one's own). It acts for Why first,
gone, cold, no-cache, cache and session; never mid-turn, under Strict,
for a subagent (withLead), past a rest, reserve, credits or a fallback
routing put first, nor to an account that isn't readyForNew. The trace
says Why "lead" with LeadModel, and the Routing page says "Put on
{first}, where this session's {model} is: one session goes on one
account." in en, zh, zh-TW, ja and de. docs/subsystems/gateway-routing.md
says the same.

Not fixed here: the classifier's ~110-130K cache write per call. That one
is ours too: in Claude Code's interactive mode the bridge pastes the
classifier's transcript as one block without the client's marks
(claudetui userPieces, clientCache.pasted), so only the fixed prefix
(Claude Code's system plus the appended rules, the 68,925) is read and
the rest is written again on every call. The cause and a candidate fix
are on #5585. It changes what a real Claude Code sends and can't be
checked without a real account.

Run (mote, through mote-run), at this head (aeeeed54a's tree, origin/main
0fc3455e2 unchanged after a fresh fetch):
- go test ./internal/gateway ./internal/gui -count=1 -timeout 45m: ok (964s, 157s).
- TestSessionSide*, TestGroupAccountsHoldEveryRoute,
  TestPluginFactoryStandardOnlyCaps, TestWholeSession*, TestBusyModel*,
  TestInOrderKeeps* -count=2: ok.
- gofmt -l: clean. go vet ./internal/gateway for darwin, linux, windows: ok.
- node --test routing-affinity-lead (new), routing-affinity-order,
  routing-affinity-cache-write, i18n-keys, i18n-en-no-cjk: 67/68
  (Chromium + WebKit, 1100 and 420, en/zh/zh-TW/ja/de). The one red is
  i18n-keys "a plugin's words are its own", red on main for strings this
  change doesn't touch (#5327/#5332, #5426, #5482).
- The first package run of this change failed TestGroupAccountsHoldEveryRoute
  and TestPluginFactoryStandardOnlyCaps/auto (both green at 0fc3455e2):
  without a session header the id is the opening's hash, so two
  conversations that opened with "hi" were one session, and a main with
  nothing cached led. Both are excluded now, each with a subtest.
- The full go test ./... under the suite lock was queued behind four
  other sessions' suites and had not started when this was pushed.

Broken by hand, each red: the withSession call removed (both new tests;
"the session's m2 call went to k2 while its chat is on k1"); the named
session check removed (no session named); the cacheWorth bar removed
(main holds no cache, and TestPluginFactoryStandardOnlyCaps).

Not tried: real Claude accounts, real Claude Desktop. A session already
split before this release moves its side call at the side call's next
turn, writing its cache once on the main's account.

Reported-by: jerrychoi
Reported-by: iamnil (Discord)
2026-11-08 10:40:22 +08:00
yetone 350599a0f1 gateway: a held request's route is done before its 504 goes (#4200)
TestUnroutedRequestShownThenAnswered went red on ubuntu CI under -race
at d4a6e9315: the client had the 504, and the held request's route
still said Done:false, Status:0. Cause: giveUp wrote the answer
(heldWriter.answer) and only then marked the route done, with its
status, error and, after writeHeld, its report's name. A client that
reads the 504 and looks at the Routing page at once (or the GUI's next
poll) could find the request still routing and naming no report. Not a
test-only race.

The class: giveUp is the only path that answers for a held request
(checkMost and checkUnknown both end there). answer is split in two:
claim takes the reply under heldWriter.mu (false if the handler began
one; the handler's writes go nowhere from then), and send writes it.
giveUp now writes the report before taking f.mu again (out of f.mu,
it is a file), claims the writer, marks the route Done/Status/Error/
Millis/Held in one update, and only then sends, all under f.mu as
before so the handler can't return between claim and send. A report
written for a request routed or answered meanwhile is removed. The
#4300 order (report taken before the answer) is kept.

heldAnswered (the tests' hook once the 504 is out) is an
atomic.Pointer now: with the route final before the answer, a test can
end while its giveUp still runs, and -race caught the plain var read
against the test's cleanup. TestUnroutedRequestShownThenAnswered holds
giveUp in that hook until it has read the route, so a route ended after
the answer is seen undone every time; it also checks the route names its
report as it is answered. The subsystem page says the route is final
before the answer.

Run (mote, Go 1.26.8, at base 44b762d50):
- Old giveUp, new test: go test -tags nogui -race -count=5 -run
  'TestUnroutedRequestShownThenAnswered$' ./internal/gateway: 5 of 5
  red, "the held request's route: ... Done:false Status:0" (the issue's
  text).
- This change: the same test -race -count=50: ok.
- Broken by hand (the route update moved back after send and the hook):
  -count=5, 5 of 5 red at unrouted_test.go:420.
- go test -tags nogui -race -count=3 -run 'Unrouted|Held'
  ./internal/gateway: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway (under
  suite.lock): ok (801s).
- go vet -tags nogui ./internal/gateway; GOOS=linux and GOOS=windows go
  vet -tags nogui ./...: clean. gofmt -l: clean.
- Rebased on origin/main 1cb3dc435 (internal/pii only): go test -tags
  nogui -race -count=3 -run 'Unrouted|Held' ./internal/gateway: ok.
Not tried: a real held request in the app; the full ./... suite.

Fixes #4200
2026-11-08 07:20:19 +08:00
yetone 3379ebc423 browser: let a tab go 20s after its last call, CDP as Claude in Chrome uses it, input a person sends
Discord again took Magpie Browser for a bot. This lines the extension
up with Claude in Chrome 1.0.105 (fcoeoabgfenejglbffodgkkbkcdhcgfn), read
from its assets/mcpPermissions-*.js, and with what a real mouse and
keyboard send:

- A tab is let go 20s after the last call in it ends (Claude's qC=2e4),
  not 5 minutes after it was last attached. Before it goes, focus
  emulation is turned off, as Claude's detachDebugger does. A page behind
  the user's tab no longer goes on for minutes saying it has focus while
  its window reports 0x0. A tab no call used is left on its clock, so
  another session's calls don't hold it; typing that goes on after its
  call keeps its tab (re-armed every 10s) and lets it go when it ends.
- Attach turns on Page, Network (the page can't see it; settle needs it)
  and Runtime only where it was already (a dev host or browser_console),
  then focus emulation once. DOM.enable and Accessibility.enable are gone:
  Claude turns neither on, nothing listened to their events, and the
  calls magpie makes (getFullAXTree, resolveNode, getContentQuads, ...)
  work without them.
- A pressed button has pressure 0.5 (was 0; Claude sends force 0.5 when
  buttons != 0). Shift, Control, Alt and Meta have location 1 (left), as
  a real keyboard's; Claude passes the key's location too.
- No nativeVirtualKeyCode: it took the Windows code, and on macOS it is
  read as a Mac key code. Claude doesn't send it.
- Long text keeps a person's pace (~165ms a character, quickened only
  past 4 minutes) instead of fitting 35s, which reached 20+ characters a
  second. browser_type answers after 40s with how far it got; the typing
  goes on, and the tab's next call waits for it (BUSY after 60s).
- manifest 0.1.8.

Run on mote, headful Chrome for Testing (MAGPIE_BROWSER_HEADFUL=1):
go test ./internal/gateway -run TestBrowser -v: all 27 pass, among them
the new TestBrowserLetsATabGoAfterItsCalls (23.7s; the page's own
document.hasFocus() is on during calls and off within 15-45s after),
TestBrowserTypesALongTextAtAPersonsPace (66s, <= 9 chars/s, Enter after
the whole text) and TestBrowserActsLikeAPerson (pressure 0.5, Shift
location 1). Snapshots, frames from other sites, uploads and drags pass
without DOM/Accessibility enabled.

Broken by hand: IDLE_MS back to 5 minutes, TestBrowserLetsATabGoAfterItsCalls
is red ("still has emulated focus 45s after the last call"). Without force 0.5
on a click, TestBrowserActsLikeAPerson is red ("pressure 0: a mouse's is
0.5"); without location 1 on human.js's Shift, red ("location 0"),
once the test checks every Shift down, not only the last, which came
from keys.js's Shift+Enter.

go vet (darwin, windows, linux) ./internal/gateway ./internal/browserext:
ok. go test ./internal/browserext ./internal/gateway -timeout 45m
(headless): ok, gateway 866s.

Not tried: a real Discord account. Per the 11-08 limit nothing scripted
touches it. Not fixed: a background tab's outerWidth/outerHeight/screenX
are 0 while focus is emulated (Claude in Chrome has the same; the device
metrics override broke availHeight), and a page's own window.open from
the agent's tab still comes to the front for a moment.
2026-11-08 05:59:31 +08:00