Commit Graph
212 Commits
Author SHA1 Message Date
yetone ec104b8625 gateway: a Codex account can spend its credits before magpie moves to another account (jojonas_xyz on X)
jojonas_xyz on X: "我账号额度用完了自动给我切了别的号…找不到怎么关掉设置…你怎么知道
我不是想用 credits 呢". (Roughly: "my account ran out of quota and magpie
switched me to another account by itself; I can't find a setting to turn
that off; how do you know I didn't want to use the credits?")

Cause. At 90% or 98% of a window, smart routing's tier put the account
behind every account that still had room, whether or not it had ChatGPT
credits. Codex's own sign-in (NextLogin / SwitchWhenSpent) moved at the
spent share in the same way. The account's credits were spent only once
every other account was used up, and the switch was a log line. The Use
credits switches that existed (on, and "Only after other accounts" from
699ddf152) were only on the Usage page and the panel. None of them meant
"stay on this account and spend its credits".

Change.
- A fourth credits mode, first: settings.CodexCreditsFirst. on, first,
  last and off are exclusive; one mode replaces another.
- routes.Seat.First: a first seat's tier is 0, so routing keeps it in
  front past its windows while it has credits. The trace records
  Weighed.CreditsFirst.
- NextLogin keeps Codex's own sign-in on such an account (spendsFirst).
- The POST /api/codex-credits handler takes "first". The general
  settings save keeps the stored value.
- The CLI: `magpie quota credits <account> first`.
- GUI. No new page and no new component, only the Use credits row that
  already exists:
  - 供应商 → Codex → 账号 ⋯ → 使用积分 → 「先用完积分再换账号」. The
    Providers ⋯ tools now carry the credits row too, which is where the
    reporter looked.
  - 用量 → Codex 账号卡 → 使用积分 → 「先用完积分再换账号」.
  - The menu-bar panel's folded line reads 「开,先于其他账号」.
  - The "First again once it has room" tag on a moved-off account now
    points to the switch in its title.
  - Strings are in en, zh, zh-TW, ja and de.
- "Only after other accounts" (gokoshiki, 699ddf152) is unchanged.
  Its off title now says what off means.
- Docs: docs/reference.md and docs/subsystems/gateway-routing.md.

Budgets: at this head app.js is 1,312,105 of 1,316,874 bytes, and
TestCoreScriptBudget passes (231 bytes under before the rebase). Comments
were condensed; no budget was raised.

Run on mote, at this tree (rebased on origin/main 9d08993c8; the rebase
moved the settings save into internal/settingsapi, which now carries
CodexCreditsFirst beside CodexCreditsLast):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider
  ./internal/routes ./internal/settings ./internal/settingsapi
  ./internal/gui ./internal/cli at 9d08993c8+1: gateway, provider,
  routes, settings and settingsapi ok. Two reds, both filed:
  - internal/gui TestMainWindowCorners/macOS_26_SDK: #3949.
  - internal/cli TestLibraryMCPHub, TempDir cleanup not empty: #4140.
  At the pre-rebase tree (da0005df8+1) internal/gui also had
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestColdTurnsTaken
  (#4510), red the same at da0005df8; both pass at this head.
- New tests:
  - internal/provider/codex_credits_first_test.go
  - internal/gateway/codex_credits_first_test.go (routing and the trace)
  - internal/gui/codex_credits_first_test.go (POST sequence, sandbox HOME)
  - internal/gui/tests/codex-credits-first.test.cjs: the Usage page and
    Providers ⋯ at 900 and 440px, and the panel at 360px; chromium and
    webkit, en zh zh-TW ja de. It also checks for no select, no stripe,
    the i18n keys, and that a click does not move the page.
- The whole GUI suite (make test-ui), at da0005df8+1 on mote at load
  66 to 213, in two parts (a wiped scratchpad cut the first log; its red
  titles were kept): 59 files with a red. 45 of them are red at
  origin/main da0005df8 too, each under an open issue: #4304 (mote
  umbrella), #4600, #4471, #4120, #4119, #4621, and per file balance-fix
  #4682/#4683, gui-ja #4580, page-width-steady #4541, phone-connect-menu
  #4706/#4707, quota-curve #4768, segs-press-redraw #4566, signin-proxy
  #4643/#1814, zhipu-team #4728, model-copy-id #4621 (red 4 of 4 on main).
- The 14 green at da0005df8 were run again at this tree. One was this
  change's: usage-curve-zoom-back. The Codex card's fourth credits line
  (366px, was 344) held the DeepSeek card beside it to 261px, so the
  "card grows" check at 1100px had no room. Its fixture now turns the
  Codex account's credits off, since the count of credits lines isn't
  what it tests; 20 of 20 pass.
- At this head (9d08993c8+1), on mote at load 75 to 84: codex-credits-first,
  codex-credits-last, codex-credits, routing-codex-credits-again,
  panel-options-fold, usage-curve-zoom-back, i18n-keys and the 13 files
  above: 232 tests, 227 pass. Each red has an open issue:
  - models-fold webkit en/zh, "ebody holds" after the click: #4071; red
    the same at 9d08993c8 (run there).
  - account-weight webkit, same "ebody holds": #4644 (red at
    da0005df8+1, green in this run).
  - routing-many-keys chromium de "2 keys in sight at the foot": #4082
    (under load; red again alone here, green at 9d08993c8 in one run).
  - signin-closes-sheet chromium en/zh: #2628 (green alone at this head
    in a second run).
  - signin-again and signin-port-blocked, red once at da0005df8+1 under
    load, pass at this head and at 9d08993c8.

- Rebased last onto 94f6f6092 (three commits; c0477aa72 changes the
  Codex Providers row): go test -run 'Budget|CodexCredits|SettingsSave'
  ./internal/gui ok, and codex-credits-first, codex-credits,
  codex-credits-last, providers-reset-use, i18n-keys and
  usage-curve-zoom-back: 92 of 92 pass.

Broken by hand, each red, then restored:
- spendsFirst forced false: the provider test is red.
- The gateway's l.first forced false: both gateway tests are red.
- codex-credits-first.test.cjs against origin/main's assets: red
  (TimeoutError on the switch).

Not tried:
- No real ChatGPT account with credits went past its window. The routing
  order and NextLogin are tested on fakes only.
- The Linux and Windows apps were not run.

go vet -tags nogui ./... with GOOS darwin, linux and windows on mote:
clean (cgo enum warnings only). gofmt -l on the changed Go files: clean.

Claude has no equivalent: magpie reads no extra_usage and has no Use
credits modes for Claude. Filed as #4662 (see #4241).
2026-11-01 21:19:22 +08:00
yetone 7d1f2ecba3 claudecode: magpie keeps the Claude Code it downloaded at the newest release
alextjy on Discord runs magpie in Docker with Claude Code from
`magpie claude-code install`, and asked whether a magpie update touches
it and how it updates. The download lives in <cache>/claude-code
(/config/cache, on the volume), so a new image keeps it. But nothing
ever updated it: every run magpie starts sets DISABLE_AUTOUPDATER, so it
stayed at the version first installed until the user ran install again.

claudecode.KeepCurrent now runs while magpie serves (a WhileServing
loop): a minute after start and every six hours it asks
downloads.claude.ai for the latest release and downloads a newer one,
checked against the manifest's SHA-256 and size as install does. The
version it replaced is removed on the next look rather than at once,
since a run being started may hold its path (Install, the CLI's, still
removes it at once; a folder with a .part download in it is left
alone). It does nothing when magpie downloaded none, when the machine
has its own `claude` (that one is run and updates itself), or when
DISABLE_AUTOUPDATER is set for magpie, Claude Code's own way to hold a
version. A failed look keeps the download and is logged. It never
downgrades.

The status line of `magpie claude-code`, the Docker docs (en, zh, ja)
and the bridge's subsystem page say so.

Run:
- wsl-run (Ubuntu 24.04, Go 1.26.8): go vet, then go test -race -v
  ./internal/claudecode/ -run 'Keep|Install|Find': all pass.
- Broken by hand on WSL, each red: no newer() check
  (UpdatesMagpiesDownload, LeavesWhatIsntMagpiesToUpdate), no own()
  check (the_machine's_own), pruning at install (UpdatesMagpiesDownload),
  no prune on the next look (UpdatesMagpiesDownload).
- Real use on WSL, sandbox HOME and XDG_CACHE_HOME: a throwaway program
  with a fake 2.1.1 download ran KeepCurrent against the real
  downloads.claude.ai. After 1m34s it logged "updated from 2.1.1 to
  2.1.316", the kept binary's --version said "2.1.316 (Claude Code)",
  2.1.1 was still there for the next look, and the loop ended with its
  context.
- mote, at this tree: GOOS=windows and GOOS=linux go vet -tags nogui of
  both packages, go vet ./internal/claudecode/, go build ., then
  go test -tags nogui ./internal/claudecode/ ./internal/cli/ -timeout 45m:
  VET-OK; claudecode ok 0.680s, cli ok 56.673s.
- gofmt -l clean.

Not tried: the Docker image itself (no docker on the test boxes), and a
Windows run whose replaced binary is still in use (prune leaves what it
can't remove for the next look). Full suite not run: the change is the
claudecode package, one WhileServing line and one CLI status line. A
WSL run of ./internal/cli/ at the default 10m timeout timed out while
the box ran other sessions' full suites; the 45m run above replaces it.
2026-11-01 19:00:51 +08:00
yetone e42ee3b816 library: Magpie Browser's extension sits in ~/Magpie Browser Extension, dragged from the sheet onto chrome://extensions
The owner, on the v0.1.2442 sheet: the extension was written to
~/.config/magpie/browser-extension, a hidden folder no one can find to
choose in Load unpacked.

- Set up writes it to "Magpie Browser Extension" in the home folder
  (browserExtDir), where Finder and Explorer show it, and shows it
  selected in its parent (open -R on the Mac, explorer /select, on
  Windows, the home folder on Linux) rather than opened, to drag from.
- On the Mac the sheet has the folder itself: a press on it that moves
  hands the folder to the system's drag (POST /api/library/browser/drag,
  filedrag_darwin.go: beginDraggingSession from the key window with a
  file URL and the folder's icon, only while the button is still down),
  so it drops onto chrome://extensions as from Finder. Chromium's
  extensions page loads a dropped folder as unpacked
  (drag_and_drop_handler.ts: entry.isDirectory -> loadUnpackedFromDrag),
  with Developer mode on, which step 2 asks for.
- Elsewhere step 3 says to drag the folder from the window that opened,
  or Load unpacked and choose it.
- Old installs: a browser that loaded the hidden folder still does, and
  that folder is kept up to date as long as it has a manifest; the sheet
  offers set up again, into the new folder.

Run at ace58117a on mote: go vet ./internal/gui (darwin), GOOS=linux -tags
nogui and GOOS=windows vet; library-browser-setup and i18n-keys GUI
tests, 46 of 46 (5 languages, Chromium and WebKit, 1100 and 420 wide,
with and without the drag: a click posts no drag, a press that moves
posts one); internal/cli parity tests ok. At df0320156: go test
./internal/gui ./internal/cli, cli ok, gui red only in
TestMainWindowCorners, which is #3949 and red the same at df0320156
without this change.
Not tried: the native drag by hand into a real Chrome (no way to drive
a mouse drag here), and Explorer's /select on the Windows box.
2026-11-01 17:28:15 +08:00
yetone 5dfbca6274 cli: magpie settings list|get|set|reset, through the window's own save (#4745)
Stage 1 of #4745 (StringKe): every setting POST /api/settings saves can
be read and set from the terminal.

- internal/settingsapi holds the save the handler made: Merge (the
  carry of keys a page leaves out, moved verbatim from api.go, plus
  upstream's RouterNote line), the vision/imageGen/searcher checks,
  settings.Save's own checks, catalog.Touched. POST /api/settings and
  `magpie settings` both call settingsapi.Apply, so a value is checked
  and saved one way. It sits outside internal/gui so the nogui build
  has it.
- `magpie settings` (list, the default, with value, default and
  choices; get; set; reset to settings.Defaults()), --json on list and
  get. Body sends the whole file with one key changed, so a key the
  save keeps when absent (noBird, refusalRetries, ...) is set even to
  off. A flag where a key or value goes, an unknown key (with near
  matches named) or a refused value writes nothing and exits 1;
  --help prints usage.
- Parity guards: TestKeysAreWhatTheSaveWrites (each Settings field sent
  changed on its own; what the save takes must equal Keys),
  TestSettingsCLISetsWhatTheWindowSaves (every key the page's prefsKeep
  and savePrefs send is a key), TestEveryRouteHasACommandOrIsNamed
  (each /api route has a command or a reason in notYet, which later
  stages shrink; 36 have one now).
- Item 3 of the stage (per-provider CLI-only fields in the window) is
  left for stage 2.
- The open app's in-process follow-ups (fonts, Dock, tray menu, alerts,
  language, update re-check) run only from the window's save: #4752.

Run (mote, at the pushed head 1c3591b5d + this):
- gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; GOOS=linux go build -tags nogui;
  GOOS=windows go build: clean (before rebase, the vets again after).
- go test internal/settingsapi, internal/settings, internal/cli: ok.
  internal/gui -run Settings|Prefs|Keep after the rebase: ok. The full
  internal/gui run before the rebase had three reds:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, fixed on main in
  b646a9127), TestColdTurnsTaken (fixed on main in 647323409) and
  TestMainWindowCorners/macOS_26_SDK (#3949, mote is macOS 27).
- Real run in a sandbox HOME on mote with a magpie built from this:
  settings --help / help, list, get, set theme dark, noBird on,
  redactWords "acme, globex", usageAlert 85; refused theme neon, `them`
  (names theme), usageAlert lots, trayUsageEvery 4, vision
  nobody/nothing, each exit 1 with settings.json unchanged; set
  usageAlert --help printed usage and wrote nothing. Then `magpie web`
  with MAGPIE_WEB_KEY: GET /api/settings read back each value the CLI
  set; POST /api/settings lang ja, then `settings get lang` said ja;
  reset theme gave system.

Broken by hand, each red, then put back: noBird dropped from Keys
(TestKeys, TestBodySetsOneKeyOnly, the CLI set test and the GUI parity
test red); Body dropping false values (TestBodySetsOneKeyOnly and the
CLI "noBird off" check red); a route taken out of notYet and another
renamed (TestEveryRouteHasACommandOrIsNamed red, 3 errors). On the old
code the new tests don't compile (no settingsapi, no command).

Not tried: a real run on Windows or Linux; the live app reacting to a
CLI write while open (#4752); the GUI node suite (no page file changed).
2026-11-01 15:57:43 +08:00
yetone 5d63b3f995 accounts: a Claude import never writes an older sign-in over a newer one (#4532)
Importing a claude-swap export of the account Claude Code was signed in
to wrote the file's sign-in over Claude Code's own (addLogin, using).
cswap exports what it saved when it last switched; Claude Code has
refreshed since, each refresh spending the refresh token before it, so
the file's was spent and Claude Code was signed out. A saved account was
replaced the same way. Only an identical refresh token was caught.

Now a Claude sign-in for an account magpie already has (Claude Code's
own, or a saved one that can still be used) with another refresh token
is taken only when the file's expiresAt is later than what magpie has,
the account's own config directory counted (claudeNewerKept). Otherwise
it is "exists" with why, nothing written. cswapEntry and loginEntry read
claudeAiOauth.expiresAt. The CLI prints the reason.

Run (mote, -tags nogui):
- TestImportCswapKeepsNewerSignIn: older-than-live, undated, newer-than-
  live, older-than-saved. Red with the check turned off by hand (three
  subtests: updated over live / saved), green with it.
- go test ./internal/provider -run 'TestImport|Login' ok.
- go vet ./internal/provider ./internal/cli on darwin, linux, windows;
  gofmt clean.

Not tried: a real cswap export against a real Claude Code sign-in. A
sign-in that was itself imported and never run is saved with expiresAt 1
(so Claude Code refreshes it first), so any dated file still replaces it.
2026-11-01 15:07:37 +08:00
yetone c688211d13 gateway: a ChatGPT (Codex) account gets loaded tools where they were loaded, keeping its cache (#4738)
infinitex233 (#4738, Discord): Claude Code -> magpie -> a Codex account,
and every ToolSearch load dropped cache_read to 0. loadsInPlace sent the
additional_tools item (#2660) only to OpenAI's own API, so for an
account the loaded tool went into the top-level tools and the cached
prefix broke at the tools.

Tried on the real ChatGPT backend first (owner's account, sandbox HOME
on mote with a copied auth.json whose refresh_token was replaced, so the
live token was never rotated; ~/.codex untouched). A probe client sent
Claude Code's shape: ToolSearch with two deferred mcp tools, then the
tool_reference result, then the calls, 4 requests per run.
- additional_tools item (on, and this commit's default): request 2..4
  read 7680-8320 tokens from cache on gpt-5.6-terra, gpt-6-luna and
  gpt-6-sol; the model called read_a and read_b from the item; no
  "turned away additional_tools" in the log.
- tools top-level (off): request 2 and 3 read 0 from cache (8044 and
  8163 tokens in), as the reporter saw.
So the backend takes it, and this makes it the default for a ChatGPT
account (p.Account.Agent == "codex"). Copilot and other sign-ins stay
off: not tried.

- loadsInPlace: AdditionalToolsOff wins, then AdditionalTools, then an
  account is in only if it's Codex's, then OpenAI's API as before.
- `magpie provider set <id> additional-tools=on|off|default`: off is new
  (AdditionalToolsOff, kept through an account's Save by accountSettings
  and through the GUI editor's save like AdditionalTools). The old
  "off"/"no" meant default; now they turn it off where the default is on.
- The 400/422 fallback that names the item still applies, so a backend
  that stops taking it costs one retry and then sends tools top-level.
- No prompt, instructions or identity line changed.

Run (mote, at base 586b59fe7, this commit and the previous together):
- go test -count=1 -timeout 45m ./internal/provider ./internal/gateway
  ./internal/cli ./internal/gui: provider ok 248s, gateway ok 830s,
  cli ok 105s; gui FAIL on two filed reds that this doesn't touch:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, #4739) and
  TestMainWindowCorners/macOS_26_SDK on macOS 27 (#3949).
- Rebased on origin/main 9feb1024c, then again at this head: gofmt
  clean, vet darwin/linux/windows ok, provider ok 179s, cli ok 88s,
  gateway -run 'LoadsInPlace|LoadedTools|Codex|AdditionalTools|InPlace|
  Account' ok 99s, gui -run 'Provider|Settings|Account' red only on
  #4739. The whole gateway and gui packages ran at the base only.
- gofmt -l clean; go vet -tags nogui ./... for darwin, linux, windows ok.
- New TestCodexAccountLoadsInPlace (a fake ChatGPT backend through the
  gateway: the item with read_a, then tools top-level after
  additionalToolsOff in providers.json); TestLoadsInPlaceScope extended
  (Codex on, Codex off, OpenAI off, Copilot off by default and on when
  set); CLI test for off, on after off, default.
- Broken by hand: with the Codex default taken out of loadsInPlace,
  TestCodexAccountLoadsInPlace and TestLoadsInPlaceScope go red.
- GUI node suite not run: no JS changed; the Go editor save only keeps
  one more field, covered by the Go tests above.

Not tried: the reporter's own setup (Windows, gpt-6.1-terra), a real
Claude Code client (the probe sent its request shape), Copilot or any
other signed-in vendor with the item.
2026-11-01 14:59:44 +08:00
yetone 788057340b library: Magpie Image Recognition in Discover beside Magpie Image and Web Search (matrix0487 on Discord, #4653)
matrix0487 asked on Discord (#feedback) for all three of magpie's own MCP
servers, image recognition, image generation and search, in the Library's
Discover. Image generation and search were there; image recognition was
an address to copy in Settings only (#4653).

- `magpie mcp vision` (browsermcp.RunVision) relays stdio to the
  gateway's /mcp/magpie/vision, as `mcp search` does. analyze_image's
  relative image path is made one in the agent's folder on the way
  (imageFrom), since the gateway can't know where the agent runs; an
  absolute path, ~, a URL or a drive goes as written.
- library: magpie-vision is a featured, opt-in server (no agents until
  picked), any binary's `mcp vision` is one server (serverKey), and it
  gets the 120s tool timeout (selfTimeout).
- Settings › Models › Images: the Image recognition row has Give agents
  Magpie Image Recognition… / Turn on the Library, none with recognition
  off or in gateway mode. The three links are one helper, libWay, used by
  Image generation and Web search too (no budget raised: core 1,533,011
  of 1,533,105).
- Never a dead tool: Discover lists all three whatever is set up, and one
  that can't answer yet says why (gateway.OwnUnready, set by
  /api/library/market/servers as `unready`): a "Not set up yet" badge on
  its card with the reason as its title, and the reason in its sheet
  (nothing set up, or turned off in Settings / Plugins). It can still be
  added; its tools already answer with the same reason until then.
- Strings in en, zh, zh-TW, ja, de; docs/subsystems/library.md.

Run, all on mote (macOS 27) through mote-run, at this head's tree
(rebased on 21882a68d):
- gofmt -l internal/: clean. go vet darwin; GOOS=linux -tags nogui;
  GOOS=windows: browsermcp, cli, library, gateway, gui, imagemcp ok.
- go test -timeout 45m: internal/library, browsermcp, cli, imagemcp ok;
  internal/gateway ok (whole package, 556s, before the rebase; OwnMCP,
  OwnUnready, VisionMCP, SearchMCP after it). internal/gui: three reds,
  none from this change, each red on origin/main 21882a68d too:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, from 8d8df0639,
  filed #4739), TestMainWindowCorners/macOS_26_SDK (#3949),
  TestColdTurnsTaken (#4510). Budget tests ok.
- New: TestMagpieImageRecognitionIsOptIn, TestVisionBridgePassesLines,
  TestImageFromLeavesTheRest, TestOwnUnreadyWhileNotListed.
- New GUI test vision-mcp-library.test.cjs: chromium + webkit, en, zh,
  zh-TW, ja, de, 1100 and 420px (link opens the sheet with its hint and
  unready line; Library off → Turn on the Library; one added opens
  Discover with all three, only the unready one badged, inside its card;
  gateway mode and recognition off show no link; no horizontal overflow,
  no page errors): 206/206 with search-mcp-library and
  images-library-way. On e84870f17 (old code), chromium: every link and
  Discover case red.
- i18n-keys, gui-de, gui-zh-tw ok; gui-ja's one red is #4580, the same
  on origin/main 21882a68d.
- Broken by hand: serverKey without "vision" → TestMagpieImageRecognitionIsOptIn
  red; imageFrom not joining the folder → both browsermcp tests red.
- Real use, sandbox HOME on mote, nogui build, `magpie serve` on
  127.0.0.1:3591: `magpie mcp vision` initialize / tools/list answered;
  analyze_image of shots/a.png says "magpie has no model that sees
  images…"; missing/b.png names /…/work/missing/b.png (relative path
  resolved); an extra argument exits 1; gateway down answers id 9 with
  "magpie isn't running, so Magpie Image Recognition can't be reached".

Not tried: analyze_image against a real seeing model through the relay
(the sandbox had no provider; the gateway path is the one /mcp/magpie/vision
already serves); a real agent adding it from Discover; WSL (unchanged,
the MCP router serves it there); the whole GUI suite, queued after
mote's running one.

Reported-by: matrix0487 (Discord)
Closes #4653
2026-11-01 14:12:42 +08:00
yetone b1fc435407 library: Magpie Web Search, magpie's search MCP server in Library › MCP (lutra_fs)
lutra_fs on Discord: magpie's search MCP shows in Settings › Models but
not in Library › MCP servers. They were right. The gateway's web search
MCP (/mcp/magpie/web-search) was only an address to copy in Settings ›
Models › Web search. It was never a Library server, so no agent could be
given it from the Library, and the Library didn't list it.

Change:
- `magpie mcp search`: a stdio relay to the gateway's search MCP, made by
  widening browsermcp's Magpie Browser relay into a bridge with its own
  path, title and an optional session (search sends none, and has a 5
  minute client). It takes no arguments. When magpie isn't running, it
  says "Magpie Web Search can't be reached: start magpie".
- library: Magpie Web Search (magpie-web-search) is a featured,
  opt-in server beside Magpie Image and Magpie Browser. It is installed
  with no agents, so the user picks them in its sheet, and it switches
  per agent like any other row. Its command is the full binary path, and
  serverKey treats any binary's `mcp search` as the same server. Each
  agent's tool timeout is at least 120s.
- Settings › Models › Web search › MCP server: under the address there is
  a "Give agents Magpie Web Search…" link that opens its Library sheet,
  or "Turn on the Library" while the Library is off, as Images does for
  Magpie Image. Gateway mode has no link.
- The sheet's hint says where each search goes and what it costs. All
  strings are in en, zh, zh-TW, ja and de.
- docs/subsystems/library.md names magpie's own servers and the new one.
- An agent in WSL gets it through the MCP router, as Magpie Browser
  does. The image-only WSL side() is unchanged.
- The sibling, Image recognition's MCP server, is still in Settings only.
  That is filed as #4653.

Run, at this head (rebased on origin/main a6217e83d), on mote: gofmt -l
is empty. go vet passes for darwin, linux (nogui) and windows.
internal/library, browsermcp, cli and imagemcp pass. The internal/gui Go
package and the GUI files search-mcp-library, search-mcp,
images-library-way, i18n-keys, gui-ja/de/zh-tw, searcher-pick and
search-keys: 197 passed, 2 failed. The 2 reds are both known. gui-ja is
the {agent} ja string, #4580. searcher-pick's chromium en case reads a
null box: red 1 of 3 here and 2 of 3 at a6217e83d, filed as #4274.
internal/gui's three reds are red at base and filed:
TestSettingsSaveKeepsWhatItDoesNotSend #4514,
TestMainWindowCorners/macOS_26_SDK #3949 and TestColdTurnsTaken #4510.

New test: search-mcp-library.test.cjs covers Chromium and WebKit, 5
languages, at 1100 and 420px. On the old code it is red, 52 failed and
10 passed; the passes are its gateway-mode cases, which expect no link.
TestMagpieWebSearchIsOptIn and TestSearchBridgePassesLines are new too.

Broken by hand: with "search" taken out of serverKey,
TestMagpieWebSearchIsOptIn goes red (Have empty).

Real use: on mote, in a sandbox HOME, with a nogui build and the
gateway on 127.0.0.1:3611. `magpie mcp search` answered initialize with
serverInfo magpie-web-search and listed web_search in tools/list.
web_fetch https://example.com returned "Example Domain". With the
gateway killed it gave -32603 "magpie isn't running, so Magpie Web
Search can't be reached…". With an extra argument it exited 1 with
"takes no arguments".

Whole GUI suite on WSL magpie-desktop (load 120 to 180), at the
pre-rebase tree 73595f737: 17260 tests, 16684 passed, 574 failed. The
base, origin/main da0005df8, ran on the same machine: 516 failed, and
324 top-level tests were red. Each of the 161 files with a red was then
run alone on mote at head:
- At head, 118 of them pass alone. They aren't caused by this change.
- 43 fail alone at head, and every one of those also fails alone at
  base. Two pass at base once: login-import is flaky at both (#1307),
  and usage-curve-zoom-back went red once of two at base and passed 2 of
  2 at head.
  view-open-wheel was red 1 of 2 at both, filed as #4723.
- segs-press-redraw ("searchAllRow option 1") fails the same way at
  base, filed as #4566. gui-ja's {agent} string is #4580, and
  usage-ledger is #4078.
- Reds with no issue are now filed one per test: #4680 to #4728.
  Already filed: #4638 claude-mode, #4650 routing-request-model, #4176
  skeleton-bird and #1937 name-suffix-no-names.
Not tried: web_search with a real search API key (mote has none). An
agent in WSL using it directly. A run on the Windows box.
2026-11-01 12:38:01 +08:00
yetone 6f3dfc282f sessions: a scan's index is written at its end and on SIGTERM, not a minute later
A refresh's saves waited out saveGap (1 min) after the last one written,
the scan's checkpoints and its end too: the first checkpoint was written,
the rest waited. A magpie ended in that minute (quit, updated, `web` or
`serve` stopped by SIGTERM, whose handler died without sessions.Saved())
kept a few hundred of the files it read, and the next start read every
rollout again.

- A refresh that reads scanFiles (32) files or more is a scan: its
  checkpoints wait scanSaveGap (15 s) and its last save waits for nothing.
  A poll's few changed files still wait out saveGap. Saves folded into one
  take the shortest gap asked, and a shorter one wakes a waiting save.
- The signal handler writes the index before dying, bounded by
  saveOnSignal (5 s).

Real history in a sandbox HOME (11,994 Codex rollouts, 52.5 GB, plus
Claude projects; 17,140 files), index removed, `magpie web` killed by
SIGTERM ~44 s in (right after the first /api/sessions answered):
- v0.1.2521 tree: 1,200 entries kept (1,415 on a second try). Restart:
  /api/sessions 23.63 s, 1:38 of CPU.
- this change: 17,140 kept. Restart: /api/sessions 1.30 s, 3.4 s of CPU.

Tests, on mote: TestScanSavedWithoutTheGap and
TestSignalSavesTheSessionIndex are new. Broken by hand: with the scan's
gaps left at saveGap the first fails ("a scan's last save waited out
saveGap"); with the save call taken out of the handler the second fails
("died without the session index saved"). go test ./internal/sessions/
./internal/cli/ ok. gofmt -l clean; go vet (darwin), GOOS=windows go vet,
GOOS=linux go vet -tags nogui of both packages ok.

Not run: the full suite; the GUI app's own quit and update paths (they
return to main, which already called Saved); Windows and Linux runs.

Picked onto 0c3163804 (origin/main at push); not run again there.
2026-11-01 11:34:13 +08:00
yetone 9162277b91 routing: Until used up stays on the next account once the first is used up (dzxx0496)
dzxx0496 on Discord: with free accounts one after another, the first used
up, requests went to the second; when the first renewed they went back to
it ("如果第一个恢复了,它又优先用第一个了"). No routing did what they asked:
In order and Smart both put the first back first.

A new routing, Until used up (drain, 用完再换): requests stay on one seat
until its quota is used up, then go on to the next in the list and stay
there. A seat counts as used up when its known allowance is at 100% or
it was refused for quota or credit (failQuota / failCredit, routes.Drained
called where the rest is recorded, so a failover inside one request moves
the pool too). A rate limit or other failure only passes it over while
it rests, as In order does. Each pool (a provider, a group/<id>) keeps its
own place; routes.Forget clears it.

Offered wherever a routing is picked: the provider editor, a group's row
menu and editor (app menu, no native select), the TUI, `magpie group set
<id> routing=drain` and a provider's routing=drain. Nothing defaults to
it, so no saved setting changes. SpentShareOf is 100 for it, as for In
order. Words in en, zh, zh-TW, ja and de (i18n.js and the routing
plugin's own), docs/subsystems and the site's start page (en, zh, ja).

Tests:
- internal/routes/drain_test.go: stays on the next when the first renews,
  through a rate limit, all used up, a seat gone, per pool, Forget,
  Drained after a renewal.
- internal/gateway/drain_test.go: a real request path with a fake upstream;
  k1 refused for quota, k2 takes over, k1 renews: drain stays on k2,
  In order goes back to k1. Red without the Drained hook (request 3 went
  to k1). A rate limit comes back to k1; drain is saved on a provider and
  a group.
- routing-drain.test.cjs: the Routing page's why and mode line in 5
  languages, 1100px and 420px, Chromium and WebKit; red on the old assets
  (20 of 20).
- routing-group-strategy, routing-save, builtins: the menu has 11 routings.

Run on mote (macOS) at origin/main 699ddf152 with this commit and its
two neighbours (nb5p chip, dzxx0496 renewal, dzxx0496 Until used up).
Pushed on b2145eac1, whose five commits since change app.css and app.js
only for a key row's chips; at the pushed tree gofmt, the gui, routes
and gateway vets (Linux nogui, Windows), TestCoreScriptBudget (core
1,532,891), the Drain Go tests and 11 GUI files (gateway-model-chip-
height, routing-drain, routing-renews-stay, routing-behind-why,
routing-group-strategy, routing-save, builtins, i18n-keys, gui-de,
gui-zh-tw, key-row-chips-fit) were run again: 190 of 190 ok.
- gofmt -l clean; GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./... and go vet ok.
- go test internal/routes, internal/gateway, internal/provider,
  internal/cli, internal/tui, plugins/rotation: ok; internal/gui's
  TestCoreScriptBudget ok (core 1,532,816 of 1,533,105).
- GUI: routing-*, builtins, gateway-model*, model-chip*, i18n-keys,
  gui-* and codex-credits-last in both engines: 2211 tests, 68 red,
  none new: model-chip-steady 20 (#4388), gui-ja's {agent} string
  (#4580), and 11 routing-* files under load (#4585, #3789, #3799).
  The same 11 files run alone at cdfdb62c6 were 32 of 116 red, and 26
  with the stack, the same tests but rule-remove, whose red languages
  vary run to run (9 cases, then 5). model-chip-steady was 20 of 20 red
  at cdfdb62c6 alone.
Earlier, at f811bf291 with the stack: go test -timeout 45m ./... had 82
packages ok, internal/gui red only on
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
TestMainWindowCorners/macOS_26_SDK (#3949). The whole GUI suite had 301
of 16930 red in 52 files. Those 52 files rerun had 272 red with the
stack and 276 at f811bf291 alone, the same tests.
2026-11-01 09:53:50 +08:00
yetone 699ddf1524 gateway: a Codex account can spend its credits only after every other account, key and fallback (gokoshiki on Discord)
gokoshiki wants a Codex subscription first, then an OpenAI API key, then
the subscription's credits. Until now an account at 100% that holds
credits either kept its place and spent them there (on) or was held
(off). This adds a third way per account, "last":

- settings: CodexCreditsLast []string, empty by default, so a setting
  saved before it keeps its order. provider.CodexCreditsLast,
  CodexCreditsMode and SetCodexCreditsMode(user, on|last|off);
  SetCodexCredits(on) still means "in its place" and clears last.
- gateway: candidate.creditsLast is true for such an account once a
  window for the model is used up and it is going on its credits (a
  call ChatGPT counts in no window stays in its place). restLast orders
  ready, then resting, then those, and marks Weighed.CreditsLast.
  restLast runs over the asides too, so such an account goes behind a
  provider's reserves (Accounts at once, 2c6b7c063) as well.
  lastBehind keeps In turn's next turn (after), a new conversation's
  spread (leastHeld) and a subagent's lead (readyForNew) from bringing
  it forward, and a kept conversation moves off it to one not on its
  credits (Affinity.Why "credits").
- CLI: magpie quota credits <account> [on|last|off]; alone it lists
  accounts set off and last.
- API: POST /api/settings/codex-credits takes {user, on, last?}.
- GUI: under a Codex account's Use credits, while on, a second switch
  "Only after every other account, key and fallback", in the Usage
  page's card and the tray panel's (both wrap it to its own line at 360
  to 900px), and the panel's folded brief says "On, after everything
  else". The Routing page's trace says why such an account is behind
  (aside, the kept conversation's why, the row tag). zh, zh-TW, ja, de.
  creditsButton and the new switch share creditsSwitch, and the Codex
  options' comments in app.js were cut, so the core budget holds with
  no raise (1,532,664 of 1,533,105).
- docs: reference.md (quota credits) and gateway-routing.md.

Tests:
- gateway: TestCodexCreditsLastAfterTheOthers (two accounts, In order:
  the one at 100% on its credits goes behind, the trace says so, and
  back in place when turned on), TestCodexCreditsLastAfterTheFallback
  (both accounts at 100% and set last: the API key the provider falls
  back to answers before either one's credits; with the credits in
  their place an account answers on them, as before),
  TestCodexCreditsLastNotKept (a kept conversation moves off it).
  All three red with creditsLast and lastBehind forced false.
- provider: TestCodexCreditsLastMode.
- gui: settings_keep_test carries CodexCreditsLast;
  tests/codex-credits-last.test.cjs (Chromium and WebKit, en zh zh-TW
  ja de; Usage at 900 and 440, the panel at 440 and 360, the folded
  brief, the Routing page's aside and why, every key in I18N). Red on
  the old assets (no .ar-credits-last).

Run at this change on origin/main c76bcaea7, on mote (pushed on fd70def82, whose
one commit since, fd70def82, changes only the Providers poll's Go
files in internal/gui):
gofmt clean; go vet of gateway, provider, gui, cli and settings ok;
their tests ok but internal/gui's #4514 and #3949, both on main. The
8 commits between d6aa9cdf6 and c76bcaea7 touch none of this
change's files.

Run at this change on origin/main d6aa9cdf6, Go 1.26.8:
- mote: gofmt -l clean; go vet ./..., and GOOS=linux and GOOS=windows
  go vet -tags nogui ./...: ok. go test -count=1 -timeout 45m ./...:
  85 packages ok; internal/gui red only on TestSettingsSaveKeepsWhatIt
  DoesNotSend's SearchAll (#4514), TestMainWindowCorners (#3949) and
  TestColdTurnsTaken (#4510), all three on main. TestCoreScriptBudget
  passes.
- WSL magpie-desktop, Playwright 1.62.0, both engines: codex-credits*,
  i18n-keys, gui-ja, gui-zh-tw, panel-options-fold, provider-at-once and
  every routing-* file: 2127 tests, 2064 pass. Every codex-credits and
  codex-credits-last test passed (26). The red files (gui-ja, 19 routing
  files) run again at this tree and at d6aa9cdf6, alike: 200 tests, 61
  and 57 red. gui-ja is #4580; the routing reds are timeouts and
  waits, on both. The one file red at this tree only,
  routing-request-model (WebKit 420px "the model is cut"), is 5 of 5
  green alone at both, and with six copies at once red at both (29 and
  27 of 30 here, 28 and 27 of 30 at d6aa9cdf6): a fixed 150ms wait
  after a resize, filed as #4650. Nothing this change adds to Routing
  draws unless an account is set last (fixtures don't).
- Earlier, at 3564eb04b (this change on 7428f3229), WSL: the whole GUI
  suite beside two other sessions' suites, 16944 tests, 16496 pass;
  its 102 red files again at that head and at 7428f3229, 444 and 425
  red. The files red at the head only, run alone: view-open-wheel,
  usage-accounts, add-button, usage-ledger-open-settled 0 red;
  view-wheel-after-click, view-wheel-unheard and context-map (#3488)
  red alone at 7428f3229 too. mote, the credits and i18n files: 172 of
  174, the two #4580 and a click timeout in quota-curve at load 148
  (alone 30 of 30).

Not tried: a real ChatGPT account at 100% with credits beside a real
OpenAI key; the order is shown with the gateway's fake Codex backend.
2026-11-01 09:08:07 +08:00
yetone 2c6b7c0632 gateway, provider, gui: Accounts at once keeps the first N accounts taking requests, the others in reserve
01huadalang on Discord (#feedback 1566170404542742740): three ZCode
accounts used at once from one address got the address refused with a
405; two were served. They asked for one account to be used until it
runs out, then the next. Even under "In order", ZCode's maxConcurrency 3
spilled a full lane onto the next account (laneMate) and rests spread
the load, so every account was in use at once.

A provider's MaxAccounts (the editor's Advanced → "Accounts at once",
beside Concurrency; `magpie provider at-once <id> [n|off|default]`) is
how many of its accounts or keys take requests at the same time.
provider.AtOnce() is the user's own value, else what its plugin
declares (maxAccounts on the auth hook or package.json magpie, read by
host.js atOnceOf), else no limit; the user's 0 is no limit over the
plugin's. perKeyBarred keeps the first N in the user's own order
(rank), preferring ones not resting, and keepAtOnce puts the rest after
everything as asides with candidate.reserve (Weighed.Reserve). So in any
routing mode a reserve is asked only once the kept ones failed or rest,
and a kept one that rests gives its seat to the first reserve next time.
Guards: laneMate never spills onto a reserve; a full queue (laneErr)
drops the provider's reserves (dropReserves) and turns the request away
with the 429; session affinity moves a conversation off a reserve once
the kept ones can take it (affine "reserve"; Strict still holds).
Routing says "in reserve · {n} at once" on the row and why in the
request's story. zcode 0.1.40 (plugins 26864ec, on npm) declares 2, and
its mover min is raised to 0.1.40 two commits on.

Known leak, in docs/subsystems/gateway-routing.md: a failure that rests
nobody (a 5xx on one try) still passes that one request to the reserve,
as it does to any next candidate.

Tests: TestAtOnceKeepsFirstInUserOrder (every routing mode, a dragged
order, a resting key handing over its seat), TestAtOnceFullLaneWaitsForTheKept,
TestAtOnceReserveTakesOverAndGivesBack, provider TestAtOnce, plugin
host maxAccounts (hook and package.json), gui TestAtOnceSave, cli
TestAtOnceCmd, provider-at-once.test.cjs (both engines, five languages,
900 and 360px).

Broken by hand, each red then restored: laneMate's reserve guard
removed (FullLane times out); affine's reserve case removed
(ReserveTakesOver answers on k3); keepAtOnce disabled (all three red);
dropReserves disabled (FullLane gets no reply); the Routing row's
reserve branch removed (provider-at-once's Routing test red in all 10
engine/language runs).

Core budget: the field adds ~530 bytes to app.js; the neighbouring
editor comments are cut to fit, so TestCoreScriptBudget passes with no
raise.

Run on mote, Go 1.26.8:
- full suite, -timeout 45m, at a7d4c662d (on origin/main e4384fc3c):
  gofmt and vet clean; every package ok but internal/gui, whose reds are
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
  (#3949) and TestColdTurnsTaken (#4510), each red on that main too, and
  TestCoreScriptBudget, fixed by the comment cut above.
- at this tree on bbdd9eb55 (the pushed head less 51f2f22ce and
  73b957069, gateway and provider): gofmt, go vet (darwin, and
  linux and windows with -tags nogui), and internal/gateway, provider,
  gui, cli, plugin and settings: all ok but internal/gui's
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
  (#3949), both red on main; TestCoreScriptBudget passes
- at the pushed head (on 51f2f22ce): go vet of gateway and provider,
  and -run AtOnce|Nameless|ModelAPI|Reserve|FullLane over gateway,
  provider, gui and cli: ok
GUI, Playwright 1.62.0, both engines:
- the whole suite on Linux (WSL) at an earlier head; every red file run
  again at head and at main on mote, the same reds on both (filed:
  #4641 is new, the rest open already, e.g. #4600, #4461, #4082, #4210).
- at a7d4c662d on WSL: every editor-*, provider-* file, i18n-keys,
  gui-ja and seven routing files, 1185 pass, 34 red; all but four red
  on main e4384fc3c too (#4580, #3292, #4394 to #4397, #4600). The four:
  routing-many-keys (#4082) is red on main in two of three reruns as
  well; provider-gemini webkit ja's thumb (#4210) was red in 2 of 3 runs at head beside
  other files (318px off), 0 of 3 at main; alone, 4 of 4 green at both.
  The test reads the thumb 350ms after a click, a fixed wait (#4210,
  numbers added there).
- provider-at-once.test.cjs: green in both engines, five languages, at
  900 and 360px; editor-advanced-align 20 of 20 alone with the next
  commit.

Not tried: real ZCode accounts (none used, per the task) and a real 405,
so whether two at once always stays under ZCode's limit is the
reporter's finding; the user can set 1.
2026-11-01 07:39:08 +08:00
yetone 5a56bc7d73 gateway: a CI job trades its OIDC token for a short-lived key (#4531)
xazaj on X asked for GitHub OIDC: a GitHub Actions job should get a
gateway key without a long-lived magpie key in the repository's secrets.

A rule (magpie gateway-key oidc add --key <id> --repo owner/name
[--ref …] [--environment …] [--claim k=v] [--ttl 1h] [--issuer URL]
[--audience a]; oidc list, oidc remove) names an issuer (GitHub Actions'
by default, any https issuer), an audience (magpie-<rule id> by default,
so a token asked for one rule opens no other, and the workflow needn't
know the gateway's address), claims (exact or path.Match globs) and the
gateway key the keys are issued under, which must be let issue. A GitHub
rule names the repository or its owner with no wildcard, or every
repository on GitHub could get in. No rule, no exchange.

POST /v1/magpie/keys/oidc with Authorization: Bearer <token> and an
optional {"ttl","models"} verifies the token (RS256 only, keys from the
issuer's discovery document's https jwks_uri, exp required, nbf/iat with
a minute's leeway, the rule's aud and claims, a jti traded once) and
issues a key through access.IssueKey under the rule's key, named
repo@ref (run N), living no longer than the rule. Everything issued keys
guarantee holds: bounded by the issuer's models and accounts, its spend
counted against the issuer, stopped when the issuer is turned off.

- A token is judged only against rules naming its iss, so it can't make
  magpie fetch from a URL of its choosing.
- Keys are cached an hour per issuer, read by one request at a time with
  no lock held across the fetch, asked again for an unknown kid at most
  every 10s, and kept while the issuer is down; with none ever read,
  nothing is let in.
- The route is lanGuard's one exemption from remoteKeyed (that exact
  path, POST, no gateway key): only while shared, past the allow list,
  and a refused token counts against tooManyAuthFails (429 past the
  burst). A read-only key is refused it.

The issue's open questions, decided: rules are generic from the start
(the GitHub repository rule applies to GitHub's issuer); rules are CLI
and file only for now (oidc-rules.json), no GUI.

Docs: docs/subsystems/gateway-routing.md (Trading an OIDC token for a
key, routes table) and site/public/docs remote in en, zh and ja, with
the workflow snippet.

Tests: TestOIDCTokenTradedForKey (no rule, a traded key that works on
chat with its TTL capped and its name, a model past the issuer, another
branch, no token, 51 bad tokens -> 429, issuer turned off, a token on a
model route, loopback, not shared -> 403); TestMatchEachCheck (14 bad
tokens, list aud, replay, the refusal naming the claims);
TestKeysCachedAndKept (8 concurrent tokens one fetch, rotation, a made-up
kid inside and past the gap, the issuer down 2h later, an unnamed issuer
never fetched); TestUnreadKeysLetNothingIn; TestAddRefuses;
TestGatewayKeyOIDCCLI; TestReadOnlyKeyEveryRoute with the new route.
A JWKS from an httptest TLS server, never the network.

Broken by hand, each red then restored: the signature check, the claims
match, the jti check, the exp check, the refetch gap, the GitHub scope
rule, the lanGuard exemption, the throttle and the TTL cap.

Run at this head (rebased on 6a7a690be), on mote: go test ./internal/oidc/...
./internal/cli (whole packages) and go test -run 'OIDC|ReadOnlyKeyEveryRoute|
KeysEndpoint|IssuedKey|AuthThrottle|Route' ./internal/gateway: ok; gofmt -l
clean. At the 13aa33eac base: go vet (darwin, GOOS=linux -tags nogui,
GOOS=windows): ok; node --test site/*.test.mjs: 63 pass.
Full suite (-tags nogui -timeout 45m ./...) on the Linux box at the
13aa33eac base, still running when this was pushed (mote had two other
sessions' suites at load 291); so far every package ok except
internal/agent's TestInstalledVersion, TestGrokInstalled,
TestCopilotFolderFromAnIDEPluginIsNotTheCLI and TestOmpDetectedWithPiDir,
the WSL box's fake-binary reds filed as #4033 and #3548. The rest of the
run goes on #4531.

Not tried: a real GitHub Actions run against a shared magpie; a
connection open when an exchanged key expires.
2026-11-01 05:39:02 +08:00
yetone 323159f1cc usage: a Codex reset's confirmation picks which of the account's resets is used (01huadalang)
01huadalang on Discord: resets were used only automatically, or by hand
the one that runs out first. Which account was already the user's to pick
(each account's card has its own Use); which of its resets was not.

- Usage card's "Use a reset" and the menu bar panel's "Use one...": when
  the account holds two or more resets listed with their ids, the
  confirmation has a "Reset to use" pop-up (the app's menu, not <select>),
  soonest first and picked unless another is. Once another is picked it
  names the account and that reset ("The one used is me@'s reset that
  runs out ..."), and says the sooner one is kept and lost if unused.
  Escape closes the open menu first, not the confirmation.
- POST /api/usage/codex-reset takes an optional credit. The server reads
  the account's resets again and spends that credit only if it is still
  held; a gone one is refused and no other is spent in its place. With no
  credit it is as before (the soonest). Auto-use is unchanged.
- ResetCard carries the credit id; `magpie quota reset --card n` is the
  CLI's sibling, its prompt naming the reset.
- askReset's dialog moved out to resetask.js, imported when Use is
  pressed (like signsheets.js), so the core's scripts are 1,530,733 bytes,
  under the 1,533,105 budget with no raise (the pick alone took it 2,068
  over). Five keys in zh, zh-TW, ja, de.

Run on mote (mote-run), at the base 2597c9636:
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok.
- go test -tags nogui ./internal/provider ./internal/cli ok;
  ./internal/gui: only TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestColdTurnsTaken (#4510) red, both filed and the same on main;
  TestCoreScriptBudget ok after the move.
- GUI, Chromium and WebKit, 78/78 each: reset-pick-card (new: en, zh,
  zh-TW, ja, de; Usage at 900 and 390px, panel at 440px), codex-resets-used,
  account-every-reset, codex-reset-lead, reset-each-title, reset-providers,
  reset-reminder, panel-usage, old-webkit, i18n-keys, codex-auto-reset,
  codex-auto-reset-settings, warm-reset-asleep, quota-credits,
  usage-accounts.
- Red on the old code: reset-pick-card against origin/main's assets fails
  at "an account with three resets offers the pick"; TestUseCodexResetCard
  and TestCodexResetsCounted fail without the change.
- Broken by hand, each red then restored: the chosen credit ignored
  (spent [soon]); the held check skipped (a used credit spent); ids dropped
  from each; the credit left out of the POST; the Escape guard removed.

Again at the pushed head (rebased on 88372a39d): go vet ./... ok;
provider, cli ok; gui only #4514 red (TestColdTurnsTaken passed this
time); reset-pick-card, old-webkit, i18n-keys in Chromium 15/15.

Not run: the full go test ./... and the whole GUI suite. mote had two to
three other full Go suites and several whole GUI suites running the whole
time (load 120 to 250), and the WSL box too; one suite per machine.
Not tried: a real account's reset spent (none was, by design: fakes only),
so that Codex's consume takes a credit_id other than the soonest is
inferred from it being the same field the soonest is sent in.
2026-11-01 04:51:55 +08:00
yetone 0e90572274 browser: Magpie Browser, agents use the user's own browser and its sign-ins
The owner asked for a browser-use MCP of magpie's own, so an agent's
browser keeps working when Claude Code switches accounts, and asked that
it act in the browser the user uses every day: a fresh Playwright
profile is signed in to nothing.

Magpie Browser is an MV3 extension (internal/browserext, ID
dmlhojidlfnkgamkekjhacgkpanbkeko, pinned by its key) that the user loads
once in Chrome, Edge, Arc, Brave or another Chromium browser. It holds a
WebSocket to the gateway's /v1/magpie/browser/extension and carries out
each tool call with chrome.debugger (the DevTools protocol) in the user's
own tabs. The socket is taken only from this computer, with a loopback
Host (no DNS rebinding) and the extension's own Origin; a page or another
extension that connected in its place would be handed every call.

Agents reach it at /mcp/magpie/browser (Streamable HTTP) or through
`magpie mcp browser` (stdio), and the Library's MCP market lists it as
Magpie Browser, opt-in. Like the image server it is magpie's own, but it
is never served to another computer, shared and with a key or not, and
never to a web page, since it acts as the user wherever they are signed
in. 17 tools: navigate (url, back, forward, reload), snapshot (an
accessibility tree with refs, interactive-only on ask), click, type,
press, select, hover, drag, upload, scroll, wait (text, gone, seconds),
dialog, evaluate, text, screenshot (page, full page, element; JPEG or
PNG), console and tabs (list, new, select, close). Each agent session
goes on in its own tab; a link that opens a tab is followed, and a
dialog a click opens is said in the reply.

The Library's sheet for it has Set up the extension…, which writes the
extension to ~/.config/magpie/browser-extension pointed at this gateway
and shows the folder, the three steps to load it, and whether the
browser is connected, polled while the sheet is open.

Run:
- TestBrowserToolsInARealBrowser: the extension magpie writes, loaded in
  a real Chrome for Testing 141 (Playwright's chromium-1234, headless=new)
  with --load-extension, connects, and all 17 tools act in a real tab of
  a fixture site. Green on mote (macOS 27), on xiaomi-gpu (Windows 11,
  win-run) and in magpie-desktop (Ubuntu 24.04, wsl-run). Under a test
  HOME Chrome needs --use-mock-keychain / --password-store=basic, or the
  extension's storage waits on a keychain and it never connects.
- go test ./internal/gateway -run 'Browser|ReadOnly|Image', ./internal/
  browserext, ./internal/browsermcp, ./internal/library, ./internal/gui
  -run 'Library|Browser', ./internal/cli on mote.
- GUI: library-browser-setup.test.cjs (new) in Chromium and WebKit, en,
  zh, zh-TW, ja, de, at 1100 and 420 wide: 22/22. With i18n-keys and
  every library*.test.cjs: 915 pass, 1 fail, i18n-keys' "Unmarked",
  red on main since 5787d758a (#4524, fixed in the next commit).
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
  go vet ./... on mote.
- Again at this commit, rebased on 2e9df9b1b: gofmt -l, the vet trio,
  ./internal/gui -run 'Budget|Size', ./internal/proc (exec guard),
  ./internal/usage, ./internal/browserext, ./internal/browsermcp, and
  i18n-keys (0 fail with the next commit). The full go test ./... runs
  in magpie-desktop (Linux) as this is pushed; mote had another
  session's suite running.

Broken by hand, each red, then restored:
- browser_click's dispatch in background.js turned into a no-op: the
  E2E test is red at "clicked Ada".
- the extension socket's Origin check, its loopback-Host check and
  local(): TestBrowserExtensionOnlyFromItsOrigin red for each.
- browserMCP's local()/fromBrowser() guard: TestBrowserMCPGuarded red.
- a tool dropped from background.js: TestBrowserToolsAreTheExtensions red.
- the sheet's steps left shown once connected: the GUI test is red.

Not tried: loading it by hand (Load unpacked) in the owner's own daily
Chrome or Edge and driving a site they are signed in to; Arc, Brave and
Edge themselves (only Chrome for Testing); Firefox and Safari, which
have no chrome.debugger and are not supported. Chrome shows its "is
debugging this browser" bar while a tab is being driven; that is
Chrome's and cannot be hidden.
2026-11-01 02:29:55 +08:00
yetone 64cdb68035 accounts: import claude reads claude-swap's export (#4532)
StringKe (#4532) is moving from claude-swap (cswap 0.29.0) to magpie,
and `magpie accounts import claude` didn't read cswap's export. It does
now: parseLoginImport takes cswap's format-1 envelope ({version: 1,
swapVersion, encrypted, accounts: [...]}, read from cswap 0.29.0's
transfer.py) and cswapEntry reads each account's
credentials.claudeAiOauth and config.oauthAccount: email, account and
organization uuid, and the organization's name. The tokens are kept as
the file has them; magpie asks Anthropic nothing.

Refused, each with what to do: an encrypted export (decrypt with gpg -d
first), another format version, a Codex entry, and an API-key entry
(added as a key instead). An entry with no refresh token is accessOnly,
as for every other file. cswap's alias becomes the account's name in
magpie (importNames) when the account was added or updated, has no name
yet, and no other account is called that or signed in as it, so the
name stays a selector for one account (the previous commit's rule).

testdata/cswap_0.29.0_export.json is claude-swap 0.29.0's own `cswap
export` output, made from its source in a sandbox HOME in WSL with two
accounts and fake tokens (cswap's add step asked Anthropic once with
the fake refresh token, which it called dead; no real account was
involved).

Run (mote unless said):
- At this commit's tree (on origin/main 47173f593):
  gofmt -l clean; GOOS=linux go vet -tags nogui ./... and GOOS=windows
  go vet ./... ok; go test -timeout 45m ./internal/provider (ok 100.7s),
  ./internal/cli (ok 31.8s), ./internal/gui: red on 11 real-window
  AppKit tests killed at their deadline on mote over ssh (#4125, #2645)
  and TestSettingsSaveKeepsWhatItDoesNotSend's SearchAll, red on main
  (#4514); none touches accounts.
- Rebased on origin/main 7aa67e9e5 (4 commits, none in accounts), then
  at the pushed tree: go test ./internal/provider (ok 163.5s),
  ./internal/cli (ok 55.8s), ./internal/gui -run 'Budget|I18n|Key'
  (ok), gofmt -l clean.
- TestImportCswapExport, TestImportCswapRefusals. Broken by hand, each
  red: no cswapEntry, no importNames, the taken-name check off (red on
  "the team seat took pro's name"), the encrypted check off, no
  organization name.
- CLI in a sandbox HOME in WSL: import of the fixture adds max@x.com and
  team@x.com, a second import says both are in magpie already, the alias
  "work" is team's name, `accounts forget claude work` picks it;
  `accounts import --help`, a missing file and an unknown agent each say
  what's wrong.
- On mote over ssh the same import added one account and failed the
  other on the Keychain ("Unable to obtain authorization", no GUI
  session there), and the failed one was still saved, so the second
  import called it "in magpie already". That's addLogin writing
  logins.json before signing Claude Code in, the same for every import
  and sign-in, not this change; not changed here.
- GUI: login-import in Chromium and WebKit on Linux (WSL), green.

Not tried: an export from a real cswap install with real accounts,
Claude Code running on an imported account, or cswap's encrypted export
decrypted and imported. A cswap account's plan (subscriptionType) isn't
carried: magpie reads it on the first usage read, as for CLIProxyAPI.
2026-10-31 18:22:02 +08:00
yetone 149e763e9e accounts: a name you gave an account picks it wherever an email does (#4532)
StringKe (#4532): `magpie accounts switch claude work` failed when "work"
was the alias; accountNamed matched the email only.

provider.AccountByName resolves a name (magpie accounts alias) among an
agent's accounts. It refuses a name two accounts share, and a name that
is another account's email or email part, so a name never picks the wrong
account. It is used by:
- accountNamed: accounts switch/on/off/remove/alias/cap and the rest
  that take <email>;
- provider pool --accounts;
- accountRef (GUI and account-cap): the exact email first, then a name,
  so another account's alias never shadows an email;
- account-cap's display, through AccountRefOf (it filtered by email).

Run (mote, at this commit):
- go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok
  (104.9s, 33.2s).
- TestAccountsAliasPicksTheAccount, new: switch, alias, pool --accounts
  and account-cap by name; a shared name and another account's email
  refused. Red with each part removed by hand: the accountNamed call,
  pool's resolution, the clash check, the shared-name check, accountRef's
  name step.

Not run: the GUI suite (no GUI file changed); real accounts.
2026-10-31 18:18:37 +08:00
yetone 15b83901ac accounts: switch to the next account with room, or the one with the most left (#4532)
StringKe (#4532), comparing magpie with cswap 0.29.0: there was no "switch
to the next account", and when every account was past its line the
automatic switch stayed on the spent one, where cswap moves to the account
with the most room left.

- `magpie accounts switch <claude|codex> next` (provider.NextInOrder) takes
  the other accounts that are on in magpie, from the one after the account
  the agent is on, wrapping round: the first whose allowance is known and
  has room, else the one with the most room left, and says it is past its
  line. A saved Claude account not read yet is read first (readSpare), as
  the automatic switch's spares are. With no reading of any it refuses
  rather than guess; for any other agent it asks for the account by name.
- NextLogin (shared by Codex and Claude Code): when the account the agent
  is on is spent and every spare is past its line too, it moves to the
  spare with the most room left (roomLeft: the fullest stopping window's
  distance below the switch share, or the account's own cap when lower),
  when that has at least roomMargin (1 point) more than the one it is on,
  so two all but even accounts don't trade the agent each look. A held,
  failed or unknown reading is never moved to. One model's own window
  still counts for nothing, as before.
- docs: reference.md (the automatic switch and `next`; its "a Claude
  account magpie knows nothing of is not moved to" was stale since
  readSpare), providers-accounts.md's Used-up switch row, the en/zh/ja
  start pages' command table, `magpie help`.

Run (on mote, sandbox HOME through the packages' TestMain):
- go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok
  (144s, 44s), at this change's tree before the next commit's edits.
- TestNextLoginTakesTheMostRoomWhenAllArePast and TestNextInOrder, each
  over codex and claude with three accounts: green; red with the fallback
  taken out of NextLogin (the two "most room" cases, both agents) and with
  NextInOrder not starting after the signed-in account ("the one after
  it", both agents). The "none has more by the margin" case fails without
  roomMargin.
- Built the nogui binary and ran in a fresh sandbox HOME on mote:
  `accounts switch claude next --help` (prints the accounts help),
  `switch claude next` and `switch codex next` with no accounts ("has no
  other account that is on"), `switch gemini next` (asks for a name),
  `switch claude nxt` (no such account), `switch claude` (usage).
- gofmt -l clean. Cross-OS vet: run at the head of this stack.

Not tried: a real switch between real Claude or Codex accounts; the CLI
`next` with real saved accounts (the provider tests cover the choice).
2026-10-31 18:18:37 +08:00
yetone 0ac26fb52d update: a magpie a package manager installed leaves updating to it (shuhai on Discord, AUR magpie-bin)
shuhai (Arch) installs magpie from the AUR's magpie-bin, which puts the
desktop build at /usr/bin/magpie. magpie's own updater saw a folder it
can't write and pkexec on the machine, so it downloaded the release and,
on restart, replaced the package's file as root. pacman's database then
no longer matched the file, and the next `yay` upgrade (magpie-bin lags
the releases, 0.1.2342 against 0.1.2357 today) put an older magpie back.
The two updaters fought each other.

Now magpie asks first who owns the binary it runs from
(update.PackagedBy): pacman's local database, dpkg's .list files, rpm
(`rpm -qf`, only where /var/lib/rpm exists), a Homebrew Cellar path or
/nix/store. Only a system path counts (/usr but not /usr/local, /bin,
/sbin, /opt), with merged-/usr aliases, and packages named magpie* are
looked at first. A packaged binary:

- GUI: the update is shown as available with "pacman installed magpie
  (magpie-bin), so pacman updates it, not magpie: yay -S magpie-bin"
  (apt, dnf, brew likewise; Nix with no command). Nothing is downloaded,
  there is no Download or Install, the Update pill isn't lit, and
  /api/update/install does nothing (state available, stuck "package").
- `magpie update` says the same and exits 1 before downloading. This
  takes the place of the Homebrew-only check it had.

An unpackaged magpie (~/.local/bin, /usr/local/bin, a file pacman doesn't
list in /opt) updates itself as before.

Run:
- mote: go test -tags nogui -run 'Packaged|Homebrew|NotWritable|InContainer'
  ./internal/update ./internal/gui ./internal/cli ok; full
  go test -tags nogui -count=1 -timeout 45m ./... at b1a1b950f: 81 ok, 3
  red. Two are on main and filed: TestNoCommandBypassesProc (claudetui,
  #4491) and TestSettingsSaveKeepsWhatItDoesNotSend (SearchAll, #4514).
  The third, TestCoreScriptBudget, was this change: app.js is now 460
  bytes more (its comments cut to one line, one helper call per path),
  and both budgets are raised by exactly that, with no room added. After
  the rebase on bb5e68cea: TestCoreScriptBudget and the Packaged,
  NotWritable, InContainer and Homebrew tests ok on mote.
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build for darwin, linux (nogui), windows.
- WSL magpie-desktop (Ubuntu 24.04), real package: built a 0.1.2300
  nogui magpie, packaged it as a .deb (magpie-aurpk-test) at
  /usr/bin/magpie, dpkg -i. `magpie update` as the user, through
  /bin/magpie, and as root each printed "magpie 0.1.2355 is out" and
  "this magpie was installed with apt (package magpie-aurpk-test), which
  updates it, not magpie: sudo apt install --only-upgrade
  magpie-aurpk-test", exit 1; the file's sha256 was unchanged and
  dpkg -V clean. Package removed after. An unpackaged copy in ~ still
  checked and offered the update.
- WSL GUI, both engines: every update-* file, i18n-keys, gui-de/ja/zh-tw,
  whats-new*, about-*: 390 pass. Reds: i18n-keys "Unmarked" (#4524, on
  main) and update-check's WebKit ResizeObserver notice (the previous
  commit). Rerun of every update-* file after it: 294 pass, 4 red, all
  timing reds filed as #4554 and #4555, none in update-stuck. After
  app.js was cut down, after the rebase: update-stuck, update-auto,
  update-hide and i18n-keys, both engines: 93 pass, 1 red (#4524).

Broken by hand:
- placeExe's and the CLI's package check turned off:
  TestUpdatePackagedLeavesItToTheManager red ("a packaged binary is to be
  replaced"), TestUpdatePackagedSaysTheManager red (it went on to the
  download).
- origin's app.js: the new update-stuck case times out (no text); only
  the pill condition reverted: red in WebKit.

Not tried:
- A real pacman/Arch install: the omarchy VM didn't answer ssh (banner
  exchange timed out twice), so pacman detection is from the database
  layout in tests only.
- rpm and Nix on a real system; Homebrew only through the existing path
  test.
- The whole GUI suite.
2026-10-31 17:28:37 +08:00
yetone 33a284497e plugin options: a switch a provider plugin declares is saved where the plugin reads it (plugins#550)
`magpie plugin options cursor '{"wire_trace": true}'` wrote the entry's
options in plugins.json (a middleware's ctx.options), while a provider
plugin's switches (auth.options, the editor's Plugin options) are read
from settings' PluginOptions (input.magpie.option). The command said
"options set" and Wire trace stayed off.

Now a key that the plugin declares as a switch for one of its providers
(from the providers last listed, else asked of the plugin host) goes to
PluginOptions for that provider, through settings.EditPluginOptions, and
a running host is handed it (SetProviderOptions, 5s, best effort). Only
true or false is taken for a switch. The other keys go to plugins.json
as before; set with switches only, a middleware's options stay, less a
switch written there before. `off` puts every switch back to the
plugin's default and clears plugins.json's options. Shown with no value,
each switch is listed with its value. docs/reference.md and the plugins
page (en, zh, ja) say so.

Run at this head on mote: go test ./internal/cli ./internal/settings
./internal/plugin ok; gofmt -l clean; go vet darwin and GOOS=windows ok;
Linux go vet -tags gtk3 in WSL (magpie-desktop) ok.
Broken by hand: no key read as declared, and both new tests went red
(PluginOptions empty, the old switch left in plugins.json).
Not tried: the real CLI against a running magpie with the Cursor plugin
installed; a plugin not listed yet (the host path) is not in a test.
2026-10-31 16:46:14 +08:00
yetone 7b09d2c951 provider: a model can be listed by an id of the user's at its provider, asked for by its own
zeewell on X (tweet 2116404121930432888): relays serve one model under
ids of their own (deepseek-v4.1-flash-1017, grok-4.6@500k). They want to
give each one their own id at the provider layer. magpie then lists,
routes, groups and finds groups by that id, and the upstream request
still carries the vendor's id.

Choice: a new per-model map, settings' ModelIDs
("<pid>/<local>": "<own id>"), served through the wire names that
already exist. ModelSameAs was not widened. It means "same as another
vendor's model": it lends specs and joins found groups. Making it rename
models everywhere would change every existing user's ids and refs.
ModelWires was not reinterpreted either, for the same reason. ModelIDs is
ModelWires turned round: a wire keeps magpie's id and changes the one
sent, and this keeps the one sent and changes magpie's. Settings.Wires()
merges each entry in as a wire name (wrapped by a "<pid>/*" wire). Every
place that sent a ModelWires name (gateway, usage ledger, request page,
UpstreamName, UpstreamNameAs) reads Wires(), so the upstream id needs no
new path. An explicit ModelWires entry for the same id wins.

- Listed by the local id: Available, liveIDs/liveByID, Serving and
  ListPrice translate through OwnModelID. /v1/models, agents' lists,
  Resolve, routing groups and found groups (auto/<local>, merged with
  every other provider serving that id) all see the local id.
- Only a provider of the user's own (Account == nil) takes one. An
  account's or a plugin's request is built from its list's id, which no
  wire reaches.
- Two variants of one provider given one id: the latest given it wins,
  and the earlier one is listed by its own id again. The CLI names it.
  The editor refuses two rows given one id in one save. A model of the
  provider's own id that a variant is listed by (plain grok-4.6 beside
  grok-4.6@500k) is not listed while the variant has it.
- The user's values are never overridden. SetModelID moves picks,
  contexts, fallbacks, groups' members/rules/fast/placed/off/weights/
  classifier/pick, the pickers' lists, every per-model setting
  (Settings.MoveModel) and gateway keys' models (provider.ModelMoved,
  set by access) to the new id, but only where nothing is under the new
  id yet. Agents' own files are not rewritten: an old provider/<own id>
  still resolves and is sent as it is. Group match patterns and key
  patterns stay as written.
- Key limits: a key held to either id passes for both (modelAllowed:
  the ref, OwnModelID, ListedModelID). Group members use the same check.
- Usage: model = the listed id, served = the vendor's id from its reply.
  The price is the own id's first.

CLI: magpie model id <provider/model> [<id>|--reset], magpie model ids.
GUI: Providers > a provider's editor > Names & levels > "Listed as",
beside Same as. It is staged with the editor's Save and taken back by
Restore default, in zh, zh-TW, ja and de. Accounts have no box.
Docs: providers-accounts.md, gateway-routing.md, and site start.html in
en, zh and ja.

Run (mote-run, at this tree rebased on 841326709):
- go test -tags nogui of internal/gateway, provider, settings, access,
  usage and cli: ok. internal/gui: ok but for
  TestSettingsSaveKeepsWhatItDoesNotSend's SearchAll, red on main since
  b09349d17 (#4514, yiqiui's patch); its ModelIDs case passes.
- TestAutoVisionDoesNotBuildListsAgain: 457 allocations with 4 models,
  458 with 400 (main 459), searcherModel within its 50. Reading
  Shared() per list cost 3041; SharedModelIDs parses only modelIDs once
  per file change, the settings path is built again only when what it is
  built from changes, and Serving looks up the own id only when a key is
  listed to some model.
- TestCoreScriptBudget: raised by 1,178 bytes for the Listed as box,
  with a note.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet ok.
- GUI: provider-listed-as (en, zh, zh-TW, ja, de), provider-same-as,
  provider-detect in Chromium on mote and WebKit on the Linux box (mote's
  WebKit launch hangs, #4125): 9 of 9.
Broken by hand, each red: the wire name (wires), the list (list), a key
held to the own id (keyown), the key move hook (hook), liveIDs, liveByID,
moving refs (moverefs) and moving per-model settings (movemodel).
Not tried: a red for ListPrice's or Serving's own-id lookup; a real relay
with variant ids; Match patterns are not rewritten to the new id. The
full Go suite and the whole GUI suite are still running and their reds
get their own issues.
2026-10-31 15:04:44 +08:00
yetone ceeb73a0f1 app: the desktop app writes its log to app.log; magpie log and Settings › About › Log find it
rayem1w on X (0.1.2330, macOS) was asked for ~/Library/Logs/magpie/serve.log
while chasing a Codex "hit a snag" through the gateway, and had no such
folder. Only the launch agent (magpie daemon install, written by launchd)
and a gateway magpie tui left running wrote a log; the app opened from the
Finder, the Dock or the Start menu logged to a stderr nobody reads, on
every system.

Now runGUI and runPanel (magpie, app, tray, panel, a window view, a
magpie: link) call applog.Start before gui.Run. It sends the standard
logger (the gateway, the plugin host, providers and Wails' error handler
all log through it) to app.log as well as stderr, and points
debug.SetCrashOutput at it so a panic's trace is there too:

  macOS    ~/Library/Logs/magpie/app.log
  Windows  %LOCALAPPDATA%\magpie\logs\app.log
  Linux    $XDG_STATE_HOME/magpie/app.log, else ~/.local/state/magpie/app.log
  portable data/logs/app.log

app.log, not serve.log: on a Mac launchd writes serve.log for the service,
another process. The file is 0600. At 5 MiB it becomes app.old.log (two
files at most); when another magpie (an update's new process) rotated it
already, it is only opened again; when it can't be moved it is emptied.
stderr goes first, through a writer that never fails, since io.MultiWriter
stops at a failed writer and an app opened from Explorer has no stderr.

Secrets: the log calls name header names and paths without queries; no
key or token was found logged (grep of log.Print* in gateway, provider,
plugin, gui, agent). scrub masks bearer/basic credentials, key/token query
parameters and sk-, AIza, gh?_ and JWT shapes anyway.

How a user finds it: Settings › About › Log, with the path, Copy and an
Open that shows its folder (POST /api/settings/log/reveal; the row is
hidden in magpie web, which writes no file). magpie log prints where every
log is (the app's, app.old.log, the service's, the tui's background
serve.log); --path the app's alone, -n N its last lines, -f follows it
across a rotation. Docs: reference.md, gui-shell.md, site start (FAQ "Where
is magpie's log?" and the CLI table) and privacy (files on your computer),
en/zh/ja.

Run:
At 227ce6074 on origin/main fbb1b36d1:
- mote: go test ./internal/applog ./internal/appdir ./internal/cli ok;
  -run TestCoreScriptBudget ./internal/gui ok; GOOS=windows go vet
  ./internal/... and GOOS=linux go vet -tags nogui ./internal/... ok;
  gofmt -l clean. GUI, chromium: about-log (5 languages x 1100/420, and
  no row without a log), about-website, i18n-keys: 24 of 25, the one red
  "a plugin's words are its own" ("Unmarked") is the same at origin/main
  fbb1b36d1 (#4524).
- WSL (magpie-desktop), webkit: about-log and about-website 21 of 21.
- Windows (win-run): applog, appdir, tui ok; cli ok but
  TestLibraryMCPHub's TempDir cleanup (#4140, mcp-npm, not this change).
- WSL full go test -tags nogui -timeout 45m ./... at the previous base
  03f609e3f: every package ok but reds that fail the same at origin/main
  03f609e3f alone: TestSettingsSaveKeepsWhatItDoesNotSend (#4514),
  TestNoCommandBypassesProc (#4491), internal/agent's install-detection
  tests (#4033, #3548), and TestCoreScriptBudget, which was this change
  (app.js 321 over): its comment is cut to one line and both budgets
  are raised by the remaining 124 bytes, with no room added.
- Broken by hand: with startLog left out of runGUI, TestTheAppWritesItsLog
  is red ("app wrote no log: open .../Library/Logs/magpie/app.log: no such
  file or directory"); with proc.UserPath taken out of openApp,
  TestGatewayStartsGetUserPath is red ("runGUI doesn't call
  proc.UserPath"). The guard now follows a start into a function or func
  var of this package, since the Wails start sits behind openApp for the
  test.
- Real use on mote: the GUI build, magpie app in a sandbox HOME, wrote
  ~/Library/Logs/magpie/app.log (0600) with its "started" line; magpie
  log and magpie log -n 3 printed it.
Not tried: the app opened from Windows Explorer or a Linux desktop
launcher for real (the paths are unit-tested per OS, the writer on
Windows and Linux); the full GUI suite (running on WSL after the push,
reds filed if they fail at origin/main too).
2026-10-31 14:45:22 +08:00
yetone fbb1b36d1f provider: the Claude keep-alive keeps off accounts, its reading, and its turn (#4532)
stringke read b48881f50 and 42c49e74d and left three notes on #4532
(issuecomment-6540015427). All three hold against the code:

1. Only accounts that were on were kept alive (claudeKeptAlive needed
   l.On). An account switched off as a reserve is still a sign-in the
   user kept for later, and Codex's keep-alive already renews saved
   ChatGPT sign-ins on or off. A run of Claude Code's /usage every eight
   days costs one local run and asks Anthropic nothing magpie doesn't
   already ask, so off accounts are kept too. Setup-token and signed-out
   accounts still aren't. The keep-alive never switches an account on.

2. The run's /usage reading was dropped (`_, err :=
   readSavedClaudeUsage`). The run now goes through the account's
   reading, the way a card's refresh reads a saved account:
   renewClaude forgets the account's minute-cached reading and calls
   loginReading with a keepingAlive ctx (asked, so nothing is held).
   claudeWindows runs Claude Code for it as for savedRefresh, past the
   30-second floor (the keep-alive is an hour apart at most), and keeps
   it in claudeUsage. loginReading keeps it beside the account and on
   disk (keepReading), and the new keepCardRead puts it on the account's
   card in the Usage cache with its history and the menu bar told, the
   way refreshCards does. A card the Usage page doesn't have isn't added.
   The run's own error comes back through the ctx, not the kept reading,
   so a failure is still told apart from a reading kept from before. This
   path doesn't bump the global ask generation, so Claude Code's own
   account isn't read again because of it.

3. A failed run held the hourly slot: still due, and with one renewal a
   look, the accounts after it never had theirs. A renewal that fails, for
   Claude and for Codex (the same loop had the same gap), now waits
   keepAliveRetry (6 hours, in memory) before the hourly look tries it
   again, and doesn't take the look's turn meanwhile. `magpie accounts
   refresh` (every 0) still tries it at once. A success clears it.

The help text, refreshAccounts' comment and providers-accounts.md say so.

Run on mote at 82b45888a plus this change: go test -timeout 45m
-count=1 ./internal/provider/... ./internal/cli/... ok; go test -race
-count=10 -run 'TestRenewLogins|WeeklyOnly|TestClaudeUsage'
./internal/provider ok; gofmt -l clean; GOOS=linux go vet -tags nogui,
GOOS=windows go vet and go vet of ./internal/provider/...
./internal/cli/... clean.

Broken by hand, each on mote:
- l.On put back in claudeKeptAlive: TestRenewLoginsKeepsSavedClaudeSignedIn
  ("renewed what wasn't due" with team@ missing), TestRenewLoginsKeepsClaudeReading,
  TestRenewLoginsFailedWaitsItsTurn and TestRenewLoginsLeavesClaudeSetupToken
  fail.
- renewClaude back to `_, err := readSavedClaudeUsage(...)`:
  TestRenewLoginsKeepsClaudeReading fails ("the account's reading: false").
- renewWaiting taken out of the loop: TestRenewLoginsFailedWaitsItsTurn
  fails at look 2 (the failed account took the turn again).

Not tried: real accounts and real Claude Code (fake runner, sandbox
HOME). The back-off is in memory, so a restarted magpie tries a failed
account on its first look. Codex's back-off is covered only through the
shared loop; there's no Codex-specific test for it.
2026-10-31 14:40:03 +08:00
yetone b48881f507 provider: keep idle saved Claude accounts signed in, by Claude Code itself (#4532)
#4532: a saved Claude account switched on but not needed for weeks
(switch-only) had nothing run on it, its refresh token sat idle, and it
was found signed out when the switch wanted it. Codex's saved sign-ins
already had a keep-alive (RenewLogins, every 8 days, one account an
hourly look).

The same loop now takes saved Claude accounts that are on, not Claude
Code's own, not added by setup-token and not already signed out
(claudeKeptAlive). For one that is due it has real Claude Code run
/usage in the account's own CLAUDE_CONFIG_DIR, the path a card's
refresh takes (readSavedClaudeUsage, inSavedClaudeDir), and
syncSavedClaude keeps whatever sign-in Claude Code refreshed. magpie
asks Anthropic nothing itself: no OAuth or usage endpoint, as removed in
9bf6d43527. A run that went through marks Renewed, so the account is not
run again for 8 days whether or not Claude Code rotated the token. A
refusal goes through NoteClaudeSignInFailure (and syncClaudeDir for an
emptied sign-in), so the row says to sign in again the way a request's
refusal does, and the keep-alive runs nothing more on it. A network
failure marks nothing. Anthropic's refresh-token idle lifetime is not
known, so the interval is Codex's conservative 8 days. The reading
itself is not kept as the card's cache.

`magpie accounts refresh` and its help say the Claude ones are renewed
too; providers-accounts.md describes it.

Run on mote at 93b31f5b7 (this tree): go test -timeout 45m -count=1
./internal/provider/... ./internal/cli/... ok; go test -race -count=10
-run 'TestRenewLogins|WeeklyOnly' ./internal/provider ok; gofmt -l
clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet of
./internal/provider/... ./internal/cli/... clean. The new tests also
passed with TZ=UTC and TZ=Pacific/Kiritimati.
Rebased onto origin/main 847f0c470 (a GUI-only change) and run again
at that tree on mote: provider and cli tests, gofmt, Linux and Windows
vet, all ok.

Broken by hand: with the Claude branch taken out of the loop's filter,
TestRenewLoginsKeepsSavedClaudeSignedIn and
TestRenewLoginsClaudeEmptiedSignIn fail ("renewed what wasn't due: []",
"emptied: []"); with the NoteClaudeSignInFailure call removed, the
refused case fails (Lapsed false).

Not tried: real accounts and real Claude Code; the tests use the
fake Claude Code runner and a sandbox HOME. Whether a /usage run makes
Claude Code refresh a token that is not near expiry is not known; the
run counts as the renewal either way. Left out (per #4532's scope):
per-model windows in the switch and caps, CLI commands, reset cards.
2026-10-31 14:15:52 +08:00
yetone 2eac916170 gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue
xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.

A gateway key can now expire (Key.Expires) and can be issued under
another key (Key.Issuer). It lives from 1m to 30d. It can be held to a
set of models, a set of accounts, tokens or cost over its whole life
(one "hours" limit as long as its life), and read-only.

- POST /v1/magpie/keys {"ttl":"1h"|3600, name, models, accounts, tokens,
  cost, readOnly} answers 201 with the secret once, no-store. GET lists
  the caller's keys, masked. DELETE /v1/magpie/keys/{id} revokes one.
- magpie gateway-key issue --ttl 1h [--name] [--models] [--accounts]
  [--tokens] [--cost] [--read-only] [--from <id>] [--json] prints the key
  alone. gateway-key issuer <id> on|off lets a key issue keys. list shows
  until/expired/issued by.

Who may issue:
- a key the user let issue (Issues), from wherever that key is let in,
  so a container or CI can;
- with no key, a request that profileRefused passes: loopback, no
  forwarding header, no Origin/Sec-Fetch/Mozilla marks, a loopback Host.
  Such a request can already use every model with no key and run the CLI,
  so it gains nothing.
Never: a page, another computer without such a key, a key not let issue,
an issued or expiring key, or a read-only key (readOnlyGuard).

An issued key never outlives or exceeds its issuer. IssueKey clamps its
expiry and refuses models and accounts the issuer can't use. On every
authentication (access.Check, under Authenticate and On), identityOf
folds the key into its issuer as the issuer is now: models, accounts,
read-only, quotas and expiry. An issuer that is off, removed or expired
refuses its keys. Spend counts against the issuer too: the new usage
field callerIssuerId, budget.read/Append counting both keys, and Reserve
reserving on both. /v1/magpie/limit answers expires and issuerLimits.

An expired or refused key gets 401 with why ("… expired at …: ask for a
new one") on every route, from loopback too. Otherwise a held sandbox
whose key ran out would be let in as no key. Expired keys are pruned
after an hour (every 10 minutes while serving, and on each issue).
rowText packs CallerIssuerID: without it, usage.Visit returned the field
empty and the issuer's limit counted none of its keys' calls.

Docs: gateway-routing.md has "Short-lived gateway keys" and the
/v1/magpie stats API table. site/public/docs remote has "Short-lived
keys" and "Stats API" in en, zh and ja. GitHub OIDC is filed as #4531.

Run at base 07a3312c5 (origin/main, fetched just before):
- mote: go test -count=1 -timeout 45m on access, budget, gwbudget,
  usage, cli, gateway, davsync, agent: ok.
- mote: internal/gui fails TestCoreScriptBudget (#4526),
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and ten AppKit window
  tests killed at their deadline (#4125, #2645). The first three fail the
  same at origin/main 07a3312c5 on mote. This change touches no GUI file.
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; node --test site/*.test.mjs (49
  pass).
- win-run: access and budget ok. usage fails TestDesktopSessionAccountMetadata
  the same at origin/main (#1356). cli's TestLibraryMCPHub failed once on
  TempDir cleanup (#4140) and passed alone.
- Real binary on mote, sandbox HOME, port 47811: issued a 1m key with
  curl, read its limit, listed it, saw `gateway-key list` show "until",
  had a page's Origin refused 403, and after 62s /v1/models answered 401
  "the gateway key "sandbox-1" expired at …".

Broken by hand, each restored:
- no expiry check in Check: TestIssuedKeyExpires and
  TestIssuedKeyExpiresOnEveryRoute go red.
- no 401 for a refused key on loopback: TestIssuedKeyExpiresOnEveryRoute
  goes red (the expired key let in as no key).
- budget not counting CallerIssuerID: TestIssuedKeysSpendTheirIssuersLimit
  goes red (5 calls reached the upstream).

Not tried: a Responses WebSocket open across the expiry. The GUI shows
no expiry or issuer yet (issued keys look like plain keys until pruned).
A held issuer's /v1/magpie/usage shows its own rows, not its keys'. The
refused-key 401 doesn't count toward tooManyAuthFails. Issued keys sync
through davsync like other keys, with their expiry.
2026-10-31 13:44:29 +08:00
yetone 07a3312c53 library: sync and backup files carry the subagents
xixi_Sean_ on X asked why Sync leaves the Library's subagents out. There
was no reason: the library part of a bundle now carries them.

- library.Bundle.Subagents (*[]*Subagent): name, description, prompt,
  the skills and MCP servers named, the agents ticked. Collect always
  sets it, empty too. Applied.Subagents (which files magpie wrote here
  and their hashes) stays out: each computer writes the files into its
  own agents on the sync Put runs and records its own, so a file the
  user edited there, or one of theirs by the same name, stays theirs.
- Put replaces the subagents with the bundle's, so one taken out on one
  computer goes from the others. A nil list (a bundle from a magpie
  before this) is unknown and keeps this computer's.
- check refuses a subagent whose name isn't one (it is a file name in
  every agent) or comes twice; agent ids are carried as they come, so a
  newer magpie's tick for an agent this one can't give subagents to
  stays and writes nothing here.
- davsync: an empty list hashes as before the field, so upgrading with
  no subagents syncs nothing.
- backup files go through the same Collect/Put; the CLI's backup line
  counts subagents. The GUI's sync/export/import ticks say "instructions,
  MCP servers, skills and subagents" in every language.
- webdav-settings-refresh's "Agents" tick locator also matched the
  library tick's "subagents": it now asks for "Agents' models".
- library.md and sync-backup.md updated. Hooks still aren't carried.

Run (rebased on 0bf5adb11; Go runs at e0c57ffe2, same diff):
- mote: go test -tags nogui ./internal/backup ./internal/davsync
  ./internal/cli ok; ./internal/library -run 'TestCarry|TestSubagent|
  TestLocalServer|TestPutKeeps|TestPutSame|TestRestoreKeeps' ok
- wsl-run (Linux): ./internal/library ./internal/backup ./internal/davsync
  whole packages ok
- win-run (Windows): the same three, -run 'Subagent|TestCarry|TestLibrary|
  TestSyncLibrary' ok
- go vet -tags nogui for darwin, GOOS=linux and GOOS=windows on the four
  packages ok; gofmt -l clean
- GUI (wsl-run, Chromium + WebKit, every language): i18n-keys,
  github-sync, s3-sync, sync-auto-restore, sync-not-backup,
  sync-other-kind, sync-sign-in, sync-spin, sync-usage-error,
  webdav-settings-refresh, library-backups-top, gui-de, gui-ja,
  gui-zh-tw, settings-search, settings-sections: 170/173, then
  webdav-settings-refresh green after the locator fix. The one red left,
  i18n-keys "a plugin's words are its own" ("Unmarked" in
  plugins/routing/i18n.js), is on main already: #4524.
  mote ran five other GUI suites at load 18, where every WebKit
  github-sync case timed out at launch, so the GUI run moved to Linux.

Broken by hand: with Collect not setting Subagents and Put ignoring
them, TestCarrySubagents, TestCarrySubagentKeepsUsersFiles,
TestCarryNewerSubagents, TestBackupFileCarriesSubagents,
TestSyncSubagents and TestNoSubagentsHashAsBefore went red; with Put
treating a missing list as empty, TestCarryOldBundleKeepsSubagents and
TestBackupFileCarriesSubagents went red.

Not tried: a real WebDAV/S3/GitHub remote between two real computers;
the fake DAV server carries it between two sandbox HOMEs.
2026-10-31 13:14:16 +08:00
yetone e6b851b0fe update: magpie update in a terminal restarts the app with its gateway handed over
gaubeebangeel on X has an agent run the magpie upgrade at 4am and had
to give that agent its own provider: magpie couldn't serve it through
the upgrade.

Cause: `magpie update` put the new version in and printed "quit and
reopen magpie to use it" (a .app) or "updated to X" (a binary). The
running app never restarted, so the agent (or the user) had to restart
it by hand, and a plain restart closes the port and drops streams.

Measured before, on mote, a sandbox HOME `magpie serve` with a fake
upstream streaming 61 chunks at 100ms, restarted by SIGTERM + start:
- the stream was cut at chunk 15 of 61 (unexpected EOF); SIGTERM to exit
  took ~18ms, no drain;
- requests during the restart: 289 answered, 5 refused over 87ms.

Now `magpie update`, once the new version is in, POSTs it to the
running app's /v1/magpie/restart (gateway/restart.go). It is answered
only to a program on this computer over loopback; a LAN caller, a page
(Origin / Sec-Fetch) and another Host get 403. The updater's
restartBeside (gui/update_beside.go) restarts only when its own exe was
the one replaced (replaced() now also compares a .app's binary,
bundleExe), takes the version as ready without the feed, and runs the
same restart as Settings' AutoRestart: at once when it cuts nothing
short, else through waitIdle. On macOS and Linux that restart is the
existing SCM_RIGHTS handover, so the port never closes and in-flight
streams finish in the old process. The command prints what happened:
restarting (handing the gateway over), waiting for N requests, another
copy (current), magpie serve (unsupported), not running, or too old
(404: the first update into this version still needs a manual
restart).

Tests:
- TestUpdateInATerminalRestartsTheAppWithoutCuttingIt (darwin, linux):
  a stream through the gateway, the exe rewritten, magpie update's ask
  answered "restarting" with handover; the successor serves a request
  while the stream runs, the stream ends whole, the old one quits only
  after it. Red by hand with the route removed ("magpie update's ask:
  404").
- TestUpdateOfAnotherCopyLeavesTheAppBe, TestRestartAskedOnlyFromThisComputer
  (refused cases never reach the restarter), TestUpdateAsksTheRunningMagpieToRestart
  (each reply, a 404 magpie, none running).

Run at this tree:
- rebased on bdc1617be, at this head on mote: gofmt -l clean;
  GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...;
  go test -run 'TestUpdate|TestRestartHandsTheGatewayOver|TestHandoverNotMade'
  ./internal/gui ./internal/cli and -run 'TestRestartAsked|TestReadOnlyKey'
  ./internal/gateway: ok
- before the rebase (88ecae173), mote: go test -count=1 ./internal/gui ./internal/cli ./internal/gateway:
  gateway ok (535s), cli ok; gui FAIL only on filed reds: the real-window AppKit
  tests killed at their deadline on mote (#4125, #2645) and
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514), both red the same
  run alone at 88ecae173, and TestColdTurnsTaken (#4510, a race in
  full gui runs, not touched here)
- wsl-run (magpie-desktop, -tags nogui): TestRestartHandsTheGatewayOver,
  TestUpdateInATerminal..., TestUpdateOfAnother...: ok
- mote: gofmt -l clean; go vet gui/gateway/cli; GOOS=linux go vet -tags
  nogui ./...; GOOS=windows go vet ./...: ok

Not tried: the real GUI app end to end with a real `magpie update`
against a published release; Windows (no handover there: the restart
waits for an idle gateway and the port closes while the new version
starts, #4521); `magpie serve` / the daemon, which has no handover and
says to restart it the way it was started.
2026-10-31 11:39:04 +08:00
yetone 88ecae1738 routing: By weight spreads a subscription's requests over its accounts
rubbzha on X (tweet 2116346330625036794): a Claude Max account and a Pro
one signed in to one subscription should share its requests by how much
each allows. The provider editor's Routing now offers By weight for
subscription accounts as it does for keys. With it picked, each account
in use shows "Weight N · S%" beside its name, the key weight's chip, and
a click edits it in place (POST /api/provider/accountweight {id, account,
weight}). CLI: `magpie provider account-weight <id> [account [n|default]]`.

The weight is kept per account by its lower-case name
(Provider.AccountWeights), and is moved with a rename (moveAccountSettings).
The gateway's keyWeight reads it from the candidate, with no file read, so
the smooth weighted pick treats accounts as it treats keys: Stays keeps a
conversation on its account, and a resting account is passed over while
the others share its requests. The default is 1. Nothing is prefilled from
the plan, and 1 is stored as no entry, so a value the user set is never
overridden.

Re-derived: ROUTINGS' weight text and routingsOf (the editor), the Routing
page's MODES, provider-row options and its "why first" text for an account,
the routing and accounts subsystem pages, the start docs (en, zh, ja), and
i18n in zh, zh-TW, ja and de (i18n.js and plugins/routing/i18n.js).
app.js is 74 bytes smaller than before (a long comment cut, keyWeight
reused), so neither script budget is raised.

key-weight.test.cjs read #status before accountAction's second round trip
(/api/state) had written it. The same race is now waited on in both tests:
with a 400ms delay injected on /api/state, the old read is red and the
new one is green.

Run (rebased on 03f3e1528; then on ef8dfaa46, where the budget, i18n and
own tests were run again and passed: Budget|I18n|Weight Go tests,
account-weight, key-weight and i18n-keys GUI files 10/10):
- New tests, each red on the old code: TestSetAccountWeight,
  TestAccountWeightMovesWithRename (red with the moveKey line removed),
  TestAccountWeightSharesRequests (6/2 for weights 3/1; alternating with
  keyWeight forced to 1), TestAccountWeightCmd, and
  account-weight.test.cjs (chromium + webkit, widths 1000/560 and web 390,
  en/zh/zh-TW/ja/de; red on 3e5aa1151's assets: no By weight for accounts).
- account-weight, key-weight, routing-weight-chip, account-row-line GUI
  files on the Linux box: 24/24 after the status wait (23/24 before, the
  race above). On mote, 13 of 24 timed out launching a browser at load 24
  with 116 Playwright processes from other sessions (#4125).
- mote `go test -timeout 45m ./...`: every package ok except
  internal/proc's TestNoCommandBypassesProc (claudetui on main, #4491) and
  internal/gui's ten real-window AppKit tests killed at their deadlines
  under load (#2645, #4125). Neither touches this change.
- gofmt -l clean; go vet ./... (darwin), GOOS=windows go vet ./... and
  GOOS=linux go vet -tags nogui ./... ok on mote.
- Whole GUI suite on the Linux box: still running at push; reds are filed
  after.

Not tried: real Max and Pro accounts through the gateway; the Routing
page's own account row under By weight has no GUI test; the whole GUI
suite on macOS WebKit (mote was saturated by other sessions' suites).
2026-10-31 11:03:35 +08:00
yetone 3e5aa11519 provider: Qwen Cloud, Alibaba's international Qwen platform, is a preset with its regions and Token Plan (judi0713)
judi0713 on Discord (v0.1.2288) asked for Qwen Cloud (qwencloud.com).
Its keys are its own, made at home.qwencloud.com, and serve neither
DashScope's nor Bailian's hosts, so none of magpie's Qwen presets took
them.

Two presets, the way Alibaba's other pay-as-you-go/Token Plan pair is
modelled, because each key gets 401 at the other's host:

- qwencloud: pay as you go, sk-ws- keys, at
  https://{region}.maas.qwencloudapi.com/compatible-mode/v1 (Chat) and
  /apps/anthropic (Messages), in six regions named by their ids as
  Alibaba's docs name them: ap-southeast-1 (the default), us-east-1,
  eu-central-1, ap-northeast-1, cn-hongkong, cn-beijing. Catalog alibaba.
- qwencloud-token-plan: sk-sp- keys, token-plan.maas.qwencloudapi.com,
  Singapore only, with the plan overview's text models.

Endpoints, regions, key prefixes and the plan's models are from
docs.qwencloud.com ("Regions and endpoints" and the Token Plan
overview), not guessed. Responses is left out, as in the other
Qwen presets.

The gateway's dashScope() now knows both presets and the
*.maas.qwencloudapi.com hosts, so a Qwen Cloud stream gets the same
enable_thinking handling a DashScope one does. Import (presetAt), the
CLI's region= and magpie://import?preset=qwencloud&region=... map to it.
docs/reference.md, the CLI help and the site's import page (en, zh, ja)
name them. Region names are ids, so no string is new to i18n.js and
nothing in the GUI changed.

Run (mote, at 708213f65 on c272e5582; after it the commit was rebased on
876d477d7, which touches none of these files, and the new helpers' comment
was moved above bedrockRegions' doc comment, no code changed; at the pushed
head the provider tests below ran again, ok):
- gofmt -l: clean.
- go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -tags nogui ./... -timeout 45m -count=1: every package ok
  (gateway 804s, provider 205s) except two reds already filed, in files
  this doesn't touch: internal/proc TestNoCommandBypassesProc
  (claudetui/child_unix.go's exec.Command, #4491) and internal/update
  TestRelaunchOpenTriedAgain (TempDir cleanup not empty, #3881).
- At the pushed head: go test ./internal/provider -run
  'TestQwenCloud|TestQwenTokenPlan|Preset|TestParseImport': ok.
- No GUI change, so no GUI run.

Broken by hand:
- Preset ids renamed: TestQwenCloud red ("no preset qwencloud-token-plan").
- gateway.go's dashScope() back to main: TestDashScopeHosts red on the 5
  new Qwen Cloud entries; the maas.qwencloudapi.com.example case stays
  not-DashScope.

Not tried:
- No real Qwen Cloud key: no request went to qwencloudapi.com.
- The decision model (decide.go's bailianDecides hosts) doesn't know
  Qwen Cloud, and image models on these presets are the next commit's.
- The site isn't deployed by this commit.
2026-10-31 09:58:04 +08:00
yetone fdf5e2c65f cli: claude-tui-helper ends on a signal its own way, not of magpie's handler
magpie's process-wide handler (endProbesOnSignal) re-raises SIGTERM. In
claude-tui-helper it killed the helper (exit -15) before the shim's own
handler could stop its Claude Code and remove what it wrote, so a run the
gateway aborted left them behind. The helper's command now lets go of
those signals (leaveSignals) before claudetui.Run.

Run: go test ./internal/claudetui ./internal/cli on mote (macOS) and in
WSL magpie-desktop (-tags nogui), ok; go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./..., go build on mote, ok.
Broken by hand: without leaveSignals, SIGTERM to a real helper in the
sandbox gateway exited -15 and left its temp folder; with it, exit 1 and
the folder removed (termimg.py).
Not tried: SIGHUP from a closed terminal.
2026-10-31 05:00:39 +08:00
yetone e647a1fd54 plugins: an npm registry of the user's own is used for installs and lookups (timwangdev on X)
timwangdev asked on X for plugins to take a custom npm registry. Zero-config
first: Registry() (internal/plugin/registry.go) takes, in order, the one set
in magpie (settings npmRegistry: `magpie plugin registry <url>|default`, or
Plugins › Discover's new npm registry row), BUN_CONFIG_REGISTRY /
NPM_CONFIG_REGISTRY / npm_config_registry in magpie's environment, then the
login shell's (cached probe only, proc.LoginEnvKnown, never waits on a
shell), install.registry in the plugins folder's or the user's .bunfig.toml,
registry= in the plugins folder's or ~/.npmrc, then the 国内镜像 switch's
npmmirror, then npm's own. The switch no longer puts npmmirror over a
registry the user named: before, bun was handed BUN_CONFIG_REGISTRY=npmmirror
whenever it was on, over the user's .npmrc. bun is told the registry only
where it wouldn't find it itself (magpie's setting, the shell's, the
switch's). magpie's own npm questions (latest version for the market,
Update and the hourly check, README, search) go to the same registry, a
package's @scope:registry= to that scope's, with the .npmrc's
//host/path/:_authToken (${VAR} expanded, longest prefix) sent to that host
alone, dropped on a redirect to another host, never logged or shown.
Download counts stay npm's. Only http(s) with a host, no userinfo, query
or fragment is taken; anything else is refused and not saved, and a bad
value hand-written into settings.json is passed over. /api/plugins says
which registry is in use and where it came from.

The GUI row is in registry.js, imported when Discover draws it, so the
core script budget isn't raised (plugins.js is 292 bytes smaller than
before, one long comment there condensed).

Left out: bunfig [install.scopes] for magpie's own lookups (bun reads them
for installs), .npmrc _auth and username/password, NPM_CONFIG_USERCONFIG
and npm's global npmrc, and internal/agent/cliupdate.go's agent CLI update
lookups, which still ask npm's own.

Run (mote and wsl-run). First at this change on 2ac423f4f:
- go test ./internal/plugin/ ./internal/source/ ./internal/gui/
  ./internal/proc/ ./internal/cli/ ./internal/settings/ -timeout 45m:
  plugin, source, cli, settings ok. gui: only the real-window AppKit tests
  killed at their deadline on mote (dock, panel, titlebar, tray; #2645,
  #4125), TestCoreScriptBudget and TestSettingsSaveKeepsWhatItDoesNotSend
  green after the fixes in this commit. proc: TestNoCommandBypassesProc red
  on origin/main itself (internal/claudetui/tui.go:183), filed as #4491.
- gofmt -l internal: clean. GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: ok.
- GUI (wsl-run, magpie-desktop): plugin-registry.test.cjs in Chromium and
  WebKit, 5 languages each, 980px and 380px; i18n-keys, old-webkit and
  plugin-market (WebKit): 19/19 pass. On mote the browser runs timed out
  launching (#4125).
Again at this tree rebased on fa5e86cf2 (upstream changed app.js and
i18n.js): go build ./...; go test ./internal/gui/ ./internal/cli/
./internal/plugin/ ./internal/settings/: cli, plugin, settings ok, gui only
the same ten AppKit window tests killed on mote (#2645, #4125), the core
budget green; gofmt clean; plugin-registry (Chromium, WebKit), i18n-keys
and old-webkit on WSL: 22/22 pass.
Rebased once more on 45de2ddb9 (app.js and i18n.js again): gofmt clean,
go vet of gui and plugin ok, TestCoreScriptBudget and
TestSettingsSaveKeepsWhatItDoesNotSend ok, i18n-keys 4/4.

Broken by hand, each red, then restored:
- A: old registryEnv (npmmirror whenever the switch is on):
  TestBunTakesTheUsersRegistry red.
- B: lookups always to npm's own: TestLookupsAskTheUsersRegistry red.
- C: no URL check: TestSetRegistryRefusesWhatIsntOne red.
- D: the switch before the user's registry: Precedence, BunTakes and
  Lookups red.
- E: no token sent: Lookups red.
- F: scopes ignored: Lookups red.

Not tried: a real private registry (Verdaccio, GitHub Packages, Nexus) with
a real token; a real bun install through one; Windows (the login shell
probe is a no-op there, so only env, bunfig and .npmrc apply).
2026-10-31 04:24:59 +08:00
yetone 45de2ddb96 provider: a provider the user counts free goes first under Free first (jiabubu on Discord)
jiabubu asked on Discord #help for a way to mark a provider, model or key
as free, so that Free first routing spends it first. Their example is
ModelScope, which has a free daily quota. Until now routes.Seat.Free
came only from the vendor catalog's Free flag, and there was no way for
the user to set it.

Provider.CountFree ("Free for me" in the provider editor's Advanced fold,
`magpie provider set <id> free=yes|no` in the CLI) makes FreeModel true
for every model of that provider. Routing therefore treats it like a
vendor's free model: Free first uses it before paid ones, and Cheapest
first weighs it at nothing, because PriceAt, which only routing reads,
returns 0 for a free model. Prices shown (ListPrice and the model list)
and the costs Usage counts (EffectivePrice) are unchanged. The mark says
what to spend first, not what a call cost, and a quota that runs out
still bills at the listed price. Key and account (subscription)
providers both carry it, through withPicks, the account literal and the
copy merge.

Tests:
- internal/gateway TestFreeFirstSpendsTheProviderTheUserCountsFree:
  - a Free first group [paidv/m, mine/m] sends its first call to mine
    once mine is marked, and the trace row says Free;
  - EffectivePrice is still the listed 3/15;
  - Cheapest picks mine first;
  - unmarked, paidv goes first again.
- internal/gui TestProviderSaveKeepsCountFree: the preset and typed-in
  providers save the mark and clear it, and /api/providers reports it.
- internal/cli TestProviderSetFree: free=yes and free=no work; the value
  shows in `provider <id>`; free=maybe, an empty value and --help are
  refused and change nothing.
- GUI internal/gui/tests/provider-count-free.test.cjs covers the
  ModelScope preset, a custom provider saved with the mark, and a Codex
  account. It runs chromium and webkit, in en, zh, zh-TW, ja and de, at
  widths 900 and 440. It checks the Advanced fold, the check and save
  POST bodies, that the row fits with no sideways scroll, and that each
  string has a translation in I18N.

Core script budget: rebased on fa5e86cf2, the core's scripts came to
1,538,236 bytes, 880 over coreScriptBudget, which TestCoreScriptBudget
caught. The budget is not raised. countFreeField's comment and five
long comments on the editor's helpers (proxyPicker, concurrencyField,
priceRateField, pluginOptionsField) are cut down, so app.js ends 212
bytes smaller than before this change.

Run (mote via mote-run, at this change's tree on base 8ee75adbf):
- go test of internal/gateway (-run FreeFirst|InOrder), internal/gui,
  internal/cli and internal/provider: ok.
- GUI test: chromium 30/30 on mote. WebKit could not launch on mote at
  all at the time (a bare webkit.launch probe timed out at 60s, and
  other sessions' WebKit launches were stuck there too). WebKit was run
  on Linux instead (wsl-run, magpie-desktop): 30/30.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./... ok; go build for darwin, linux (nogui) and
  windows ok.
- At the pushed head (rebased on fa5e86cf2, comments cut): go test of
  internal/gui, internal/cli, internal/provider and internal/gateway
  -run FreeFirst|CountFree ok (internal/gui was red only on
  TestCoreScriptBudget before the cut); node --check app.js ok; the GUI
  test in chromium 30/30.
- The full Go suite (go test -tags nogui -timeout 45m ./...) is still
  running on mote at ship time, per the owner's ship-at-once rule. Any
  red it finds gets a follow-up commit. The whole GUI suite was not run:
  mote's WebKit cannot launch and the Linux box was running other
  sessions' GUI suites.

Broken by hand:
- With the CountFree line taken out of FreeModel, all three Go tests
  went red, e.g. 'Free first went to "paidv" (free false) first'.
- With `pr.CountFree = in.CountFree` taken out of the preset save
  branch, TestProviderSaveKeepsCountFree went red ("the preset's mark
  wasn't kept").

Not tried:
- A real ModelScope account; the tests use fake upstreams.
- A per-model mark (optional in the request); the mark is
  provider-wide.
- The TUI editor (the CLI setter covers the terminal).
2026-10-31 04:21:21 +08:00
yetone 333e7f573b gateway: gateway keys are dragged into the order you want, kept with the keys (alextjy on Discord)
alextjy asked on Discord whether gateway keys can be reordered. They
could not: the Gateway page listed them in the order caller-keys.json
held them, and nothing changed that order.

- access: a "move-key" action puts one key at a place in the list,
  under the same file lock as every other key change. Nothing else
  about the key changes, and the sharing key's mirror in settings is
  left alone (its pointer would otherwise land on another key).
- GUI: the Gateway page's key rows are dragged the way search APIs'
  rows are (shared dragRows, a grip shown on hover only, Alt+Up/Down,
  the existing "Drag to reorder" title). A refused move puts the list
  back from the server. New strings in zh, zh-TW, ja and de.
- CLI: `magpie gateway-key move <id> <place>` (from 1); list already
  prints the stored order.
- Usage > Requests: the key filter lists keys in the user's order,
  removed keys after. The Overview stays a ranking by use.

Run (worktree at 14b451c11, then rebased on origin/main):
- gofmt -l clean; go vet (darwin) on access, cli, usageapi, gui;
  GOOS=linux -tags nogui and GOOS=windows go vet on access, cli,
  usageapi (mote).
- go test access, cli, usageapi: ok (mote). internal/gui: every test
  ok except the real-window AppKit tests #4125 lists
  (TestCoveredWindowStaysUp, TestPanelCloseHidesIt and 7 more), killed
  at their deadlines with pboard not running on mote.
- Broken by hand: with move-key removed, TestMoveKeyKeepsOrder,
  TestGatewayKeyCLIMove and TestLedgerKeyFilterInKeyOrder go red; with
  the mirror exclusion removed and the filter left unsorted,
  TestMoveKeyKeepsOrder ("the sharing key's mirror moved") and
  TestLedgerKeyFilterInKeyOrder go red.
- GUI (WSL): gateway-key-arrange 20/20 (chromium and webkit; en, zh,
  zh-TW, ja, de; 1100 and 420px). Red by hand: no arrange (20 red),
  grip always shown (chromium 10/10 red), drop commits nothing (webkit
  10/10 red).
- GUI (WSL), the 68 files the change can reach (every caller-keys
  fixture user, gateway-*, search-*, usage-ledger*, i18n-keys, gui-ja,
  gui-de, gui-zh-tw, key-page, phone-rows, api-key-*): 900/923. The
  reds were run again at origin/main 43966a53f and fail the same there
  (api-key-theme webkit, gateway-key-limit webkit, gateway-key-models
  webkit, search-first, usage-ledger-open-settled, usage-ledger-ttft,
  usage-ledger), each filed: #3307, #3523, #4081, #3795, #4262,
  #3104/#1876, and #4489 (usage-ledger-ttft, new). phone-rows,
  search-keys and connect-snippet-shell reds of the first run passed
  when run again at the head. usage-ledger's "zh: request routing
  links" went red once at the head (Usage view position on return) and
  passed in the first run.

At the rebased head (on 2ac423f4f): TestCoreScriptBudget and the
other Budget/I18n/Asset tests in internal/gui ok (mote);
gateway-key-arrange, i18n-keys and gateway-caller-keys 27/28 in WSL.
The red is gateway-caller-keys webkit en "wider than 560 right after
the resize" (#3797, red alone on main). A probe of that file, printing
the page width and any element past it, read 560/560 with nothing
wider in both engines, in two runs beside the arrange file.

Not tried: dragging in the real app (WebKitGTK, WKWebView, WebView2),
the full Go suite (started after the push).
2026-10-31 03:48:27 +08:00
yetone 43966a53fb claude: a subscription's run is Claude Code's interactive mode, -p only as the fallback
The owner (10-31): a Claude subscription ran `claude -p`, whose
requests Anthropic labels sdk-cli and counts at about twice the
interactive mode's cli (anthropics/claude-code#97074). Running the real
interactive Claude Code is what its terms describe and uses the plan as
a person does. Wanted inside magpie, on by default, with a way off.

`magpie claude-tui-helper <claude> <-p args>` (internal/claudetui)
stands where `claude -p` stood and speaks the same stream-json. It
turns the -p arguments into the interactive mode's (no -p, no
--dangerously-skip-permissions: --permission-mode default with only
mcp__magpie, and the WebSearch -p was given, allowed; --no-chrome;
--session-id or the --resume given), starts Claude Code in a
pseudo-terminal of its own (no tmux), pastes each message into its
prompt and presses Enter, and tells the session's transcript back as
-p's lines: whole assistant messages, an API error as the turn's error
result with its rate_limit_info, turn_duration as the result. Nothing
sets CLAUDE_CODE_ENTRYPOINT, and the user's ~/.claude and
~/.claude.json are never written. The folder-trust question is
answered only for magpie's own folder or a saved account's config
directory (MAGPIE_CLAUDE_TUI_TRUST).

A Claude Code that doesn't start or show its prompt in 45s becomes
`claude -p` on the same pid, its input still unread, so the turn is
answered all the same; that is remembered for 30 minutes
(<cache>/magpie/claude-tui-broken). An untrusted folder goes to -p
without the mark.

claudeTUI keeps -p for Windows and WSL, Settings › Models › Replies ›
Claude Code's interactive mode Off (claudePrintMode), safeguards,
client cache marks, a JSON schema, images and a first message over
400KB. A TUI run ends instead of taking an image turn, a rewind or an
effort change, and letGo doesn't take one back. The gateway's tests
run with claudeTUIRuns off: their binary has no claude-tui-helper.
docs/subsystems/claude-subscription-bridge.md has the section.

The core's scripts grow 725 bytes with the setting's row;
coreScriptBudget is raised to the exact size, 1,537,356, with no room
added.

Run (rebased on f2eb56c6b and its budget fix):
- mote: go vet of claudetui, gateway, cli, settings on darwin;
  GOOS=windows of claudetui, gateway, cli; GOOS=linux of claudetui,
  gateway; gofmt -l clean.
- mote: go test ./internal/claudetui: TestShimTurnsInteractive (a fake
  interactive Claude Code in the PTY: two turns, a /help pasted as
  words, the arguments it was given), TestShimFallsBackToPrint (failed
  start marks broken; untrusted folder doesn't), TestShimTrustsWhenTold,
  TestPasteable, TestTranslatorAPIError.
- mote: go test ./internal/gateway -run TestClaudeTUIChosen (plain,
  off, WSL, safeguards, cache marks, schema, image, long prompt),
  TestClaudeLean*, TestCleanClaudeEnv.
- mote: go test -timeout 45m ./internal/claudetui ./internal/cli
  ./internal/settings ./internal/gateway: all ok (gateway 524s).
  go test -run Budget ./internal/gui: ok after the raise below.
- Linux (magpie-desktop): go test ./internal/claudetui ok natively,
  the PTY's Linux ioctls among it. GOOS=linux go vet -tags nogui of
  cli, gateway, claudetui, settings ok.
- Linux box, Playwright 1.62, chromium and webkit: claude-tui-setting
  16/16, claude-lean-prompt-setting 16/16, i18n-keys 4/4, mobile-web
  30/30 against 74f1df869's tree. mote's WebKit didn't launch (other
  sessions' GUI suites, running 11-16h, held ~108 WebKit processes),
  so the GUI ran there instead.
- Real Claude Code 2.1.314 on a real Claude account's magpie config dir,
  haiku, through the built helper with the bridge's exact -p arguments
  (an MCP server named magpie with one tool, --tools "",
  --system-prompt-file, --thinking disabled, --effort low,
  --thinking-display): the tool was called without a permission prompt
  and its answer used; the system prompt's end token in every reply;
  a second turn on the same run; a later run with --resume remembered
  the first. All 18 transcript rows say "entrypoint":"cli". Startup to
  init 0.7–1.5s, a haiku turn 1.4–4s. Two messages sent at once are
  one turn, as Claude Code queues them.

Broken by hand:
- each claudeTUI condition taken out in turn (WSL, safeguards, cache
  marks, schema, images, the setting, the 400KB bound): its case red.
  The WSL case first passed with the check gone (its claudeCLI had no
  path); given one, it is red without it.
- the trust check taken out of ready(): TestShimTrustsWhenTold red
  (the run went to -p).

Not tried: a turn through a running gateway into the helper on a real
account (a sandbox HOME would copy the sign-in into a new keychain item
and refresh it apart from the live one); a ~400KB paste; Linux with a
real Claude Code; an API error from the real service (the translator
is tested on its rows). The full go test ./... did not run (mote was held by those suites);
the four packages this touches ran whole.
2026-10-31 03:20:45 +08:00
yetone b62fa332f3 provider: Send requests unmasked for subscriptions and plugin providers too (isee1_1)
isee1_1 on Discord uses a community translation plugin as a provider and
asked why "Send requests unmasked" (请求不脱敏) isn't offered for it.
698da36f3 (lc) left a signed-in account, a plugin's provider and another
magpie out because the switch was then for local addresses only, and none
of those is local. 380032cda (AcMilan) made it the user's word at any
address, with a caution while on for one not local, but kept the
exclusion. Nothing still stands behind it for a subscription or a plugin:
the setting lives with the account's model picks, and every route reads
SkipsRedaction. Another magpie stays excluded, as it masks on its own side.

- provider.SkipsRedaction: an account (subscription or plugin) skips when
  set; another magpie never. Save keeps Unredacted in the picks record,
  withPicks applies it (AlsoOn accounts too).
- gateway: serve, count_tokens, embeddings, Jev and the plugin's fetch
  already go by unredactedRoute (every fallback and group member must be
  set too). The Codex relay on a ChatGPT sign-in masked always: it now
  sends the turn whole when the Codex subscription is set
  (codexRouteUnmasked; only for the ChatGPT backend, not the Codex API
  key route), codexMaskRoute stands aside then, and ChatGPT web search
  (alphaSearchOn) goes unmasked only when every provider it is on is set.
  Speech and video stay masked whatever the switch (maskTextHits), as
  before, for every provider.
- GUI: the editor's Redaction row is shared (unmaskRow); a subscription
  or plugin provider has it too, its caution naming the provider while
  on, since its vendor is never local; saved with the account's body.
  Another magpie has none. No new strings; app.js stays in its budget.
- CLI help/show text, gateway-routing.md and the masking docs (en, zh,
  ja) say so.

Run (mote, through mote-run):
- go test ./internal/provider ./internal/cli: ok
- go test -timeout 45m ./internal/gateway: ok (676s)
- go test -run 'Budget|Redact|Unmask|I18n' ./internal/gui: ok
  (TestCoreScriptBudget at +45 bytes)
- GOOS=linux go vet ./internal/gateway ./internal/provider, GOOS=windows
  go vet ./internal/gateway ./internal/provider ./internal/cli: clean
  (GOOS=linux vet of internal/cli fails in wails without cgo, as on main)
- node --test provider-unmasked (chromium): 36/36; i18n-keys: 4/4.
  WebKit on mote can't launch (#4125); WebKit ran through wsl-run:
  the whole file in chromium and webkit, 72/72. At 440 in Linux WebKit
  the list's sticky foot covers the last row (another magpie's), so the
  test clicks that row as an event (#4484).
- gofmt -l: clean

Broken by hand:
- SkipsRedaction's account branch back to false: TestSkipsRedaction
  (an account, a plugin's provider), TestPluginProviderUnmaskedSwitch/set
  and TestCodexSignInUnmaskedSwitch/set go red.
- Unredacted dropped from Save's account whitelist: the plugin test's
  "saved as" goes red.
- codexRouteUnmasked forced off: TestCodexSignInUnmaskedSwitch/set red.
The unset and falls-back-to-a-vendor cases stay masked in each.

Not tried: a real plugin provider or a real Codex/Claude account with
the switch on (fakes only: the fake bun plugin and a fake ChatGPT
backend); the Claude bridge path; the full Go and GUI suites run after
the push.
2026-10-31 02:56:49 +08:00
yetone 7bc602236b library: the MCP hub is called the MCP router
The owner asked why it was a "hub". Composio calls the same thing a Tool
Router; "router" says what it does (one server that routes each call to
the right one), and "gateway" is taken by magpie's LLM gateway. Only
the words change: MCP router / MCP 路由 / MCP 路由 / MCP ルーター /
MCP-Router, "Router address", and the CLI's `magpie library mcp router
on|off`, where `hub` still works. The URL /mcp/magpie/hub, the mcpHub
setting, the servers/hub API and the Go names stay, so nothing a user
or an agent config holds changes. docs/subsystems/mcp-hub.md moves to
mcp-router.md and the pages that link it follow.

#4382's new words follow too: "Through the MCP router", "Not through
the router" and their hints in every language, and the CLI's
`magpie library mcp router <name> shared|direct` (`hub` works there
too; library_hub_test.go says router for direct, hub for shared).

Run at e2583df31 (this stack on 86fef947e), on mote: gofmt -l clean;
go vet for darwin, linux (-tags nogui) and windows; go build ./...;
go test -tags nogui ./... -timeout 45m, 81 packages ok, 0 FAIL;
library, gateway, imagemcp, sessions, cli and gui again alone, ok;
site's node --test, 49 of 49. GUI on xiaomi-gpu (Windows; mote's
browsers crashed under other sessions' suites): library-*, image*,
mcp-hub-direct, i18n-keys, list-sort and plugin-tools, both engines and
every language, 1055 of 1056: i18n-keys found "{name} is given to each
agent directly" dropped from the library's strings in the rebase. Put
back in the first commit; at the pushed head i18n-keys, mcp-hub-direct
and library-mcp-hub are 48 of 48. That is the only difference from
e2583df31.
Broken by hand at e2583df31: imagemcp ignoring magpie/roots fails
TestHubCallSavesInTheCallersProject; the router asking anything but
roots/list fails TestHubAsksTheAgentItsRoots and TestHubRootsUnasked;
inHub leaving magpie-image out fails TestHubGivesMagpieImage.
The CLI's TestProviderAddressMovesALocalServer red at -count=3 was
the same on origin/main 380032cda and is fixed in 65c792410.
Rebased once more onto 2570efb5f, which changed library-mcp-hub,
list-sort, mcp-hub-direct and gateway-routing.md. Run at the pushed
head: go build; gateway, library, cli and imagemcp tests ok; the GUI
budget tests ok; on xiaomi-gpu i18n-keys, mcp-hub-direct,
library-mcp-hub and list-sort, 51 of 54. The three reds were WebKit
420px library-mcp-hub cases with no Connect sheet after a reload.
origin/main d77da5bff goes red the same way (de 420px, 9 of 11). In a
second run of library-mcp-hub on WebKit at this head, 11 of 11 passed.
Filed as #4483.
2026-10-31 02:49:08 +08:00
yetone a45a0f1c5d signin: Settings can keep sign-in pages out of the default browser (max2020)
max2020 on Discord signs in from a separate, fingerprint browser so the
vendor never sees their default one. Every waiting sign-in already shows
its link with Copy link (since 52c8e838d), but magpie still opened the
page in the default browser first.

Settings › Privacy › Sign-in pages › "Open sign-in pages in the browser",
On by default, so nothing changes unless it is turned off. Off
(settings.SignInLinkOnly) opens nothing: /api/signin and
/api/plugin-signin go through openSignIn, which skips the open and
answers linkOnly; a web tab skips window.open on linkOnly, after an
install step too; the box says the page wasn't opened and its button
reads Open, not Open again. `magpie accounts add` and a plugin's
command-line login print the link without opening it. A plugin whose own
CLI opens the page (Grok Build on macOS and Windows, opened) still does.

Callbacks, by flow: Claude Code's login, Codex (localhost:1455), ChatGPT
API, Gemini/Antigravity and localhost plugins come back to this machine,
so another browser on it finishes them, and the pasted final address
covers one whose proxy keeps it off loopback. Copilot, Grok and other
device-code flows work from any browser.

Run:
- TestSignInLinkOnlyOpensNothing (new; built-in and plugin sign-in, the
  setting on and off) with TestPluginSignIn*, TestSettingsSave*,
  TestCoreScriptBudget and TestI18n* on mote: ok. Budget holds with no
  raise (app.js 1,313,244 of 1,315,316).
- signin-link-only.test.cjs (new; every language, Chromium and WebKit,
  900 and 360px), signin-link and account-discovery on WSL: 42/42 and
  the neighbours green.
- Full Go suite on WSL (go test -timeout 45m ./...): every package ok
  except internal/agent's TestInstalledVersion, TestGrokInstalled,
  TestOmpDetectedWithPiDir and TestZedAppPath, red the same on
  origin/main 387e8572a there (#4033, #3548); root, internal/cli and
  internal/gui need gtk4 there and were run with -tags nogui: ok.
- gofmt; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
- The whole GUI suite (both engines) is still running on mote at push
  time; reds it shows that aren't on file get issues.

Broken by hand: openSignIn ignoring the setting made the Go test red
("built-in: kept to its link, its page was opened 1 times"); dropping
startSignIn's linkOnly check made the GUI test red ("no page opened",
12 of 42).

Not tried: a real vendor sign-in from a fingerprint browser; Grok on
macOS/Windows still opens its own page; MCP server sign-ins unchanged.
2026-10-31 01:02:24 +08:00
yetone 3b5dccd527 accounts: a plugin account goes by its usage's name, not its id (#4416)
A Huawei Cloud CodeArts account is kept by its accountId, an IAM id
(iam::<domain>:user:<name>), and every list showed that id while its
quota card showed the masked phone the plugin's usage() names it by.
Display only: an account now reads as the name the user gave it, else
the `user` its plugin's last usage read gave (PluginUserOf: the
in-memory read, else quotas.json), else its id. The id stays the key
everything is kept by; nothing stored changes or migrates. A read that
fails keeps the last good name; nothing read yet is the id, never blank.

One rule in provider (AccountShown, AccountShownOf, AccountLabelOf),
used by every list: cards' Alias (Usage page, tray panel,
/v1/magpie/quotas, magpie quota), magpie accounts, magpie providers,
the TUI's Providers rows and quota titles, usageapi's Account filter,
the quota alert. The GUI gets it as /api/providers' accountUsers
(accountShownOf in app.js): the editor's account rows (the id in the
tooltip), the per-account proxy lines, Routing's userShown, the
Providers search, Hide accounts. app.js's account lookups share one
helper, so the core stays in its budget (1,536,561 of 1,536,586), with
no room added.

Run:
- go test ./... -timeout 45m on mote at 2f5a3f1c0 + this change: all ok
  but internal/agent TestPiModelsAskedOnTheirNativeAPI (fixed on main
  by 7474a86f1, green there; this is rebased onto it),
  internal/update TestRelaunchOpenTriedAgain (#3881, green alone x3),
  and internal/gui's real-window AppKit tests (TestPanelCloseHidesIt,
  TestMainWindowCorners, TestTrayCellClickReleasedPanel red the same
  on origin/main 99ad38b7c; #2645, #4125, #1936).
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of the
  touched packages; gofmt -l clean.
- TestPluginAccountShownByItsUsageUser (new, real plugin host and fake
  plugin): id before a read, phone after, phone after a restart from
  quotas.json, phone kept over a failed read, own name wins, id when
  nothing is known. Red on the old code.
- GUI on the Linux box (mote's Chromium segfaults on these pages on
  origin/main too, #4125): account-plugin-user (new),
  routing-account-name (extended) and account-alias, Chromium and
  WebKit, every language, 34/34; the new checks red on the old code;
  the whole suite (make test-ui on the Linux box) was still running at
  push: 417 files in, 5 reds, none on a page this changes
  (account-models' row-moved check in WebKit, 81 vs 79px, and
  agent-models-all-hidden), not yet compared with origin/main; any
  that are new get an issue once it ends.
- At the rebased head (3bce283df): go test of provider, cli, tui,
  usageapi, plugin, agent -run TestPi, gui -run
  Budget|Provider|Quota|Account: all ok. Core scripts 1,535,513 of
  1,536,586.

Broken by hand: dropping the quotas.json fallback turns the test red
at "after a restart".

Not tried: a real Huawei CodeArts account (none here). A plugin whose
windows are all model pools isn't kept in quotas.json, so after a
restart it shows its id until its first read.
2026-10-31 01:01:49 +08:00
yetone 0621e70fb9 routing: leave a provider out of the groups magpie finds
chenxiang0010 on Discord asked to keep a provider or a model out of the
auto-created routing groups. A model could already be kept out (remove
its found group; magpie keeps it removed), but a provider could only be
turned off per group or everywhere. Now Routing -> Groups, under "Find
groups on their own", has "Leave out a provider..." (app menu, saved
when it closes) and `magpie group auto skip <provider>...|none`. The
providers chosen (providers.json autoGroupSkip) join no found group; a
group the user made or changed keeps them, a found group left with one
provider goes away, and a request for it is served by AutoStandIn from
a provider still in, and agents on it are reseated (agent.Reseat). A
rename carries the id along. en, zh, zh-TW, ja, de.

Run at 383947fce (this change on origin/main 2ff75161d):
- go test -timeout 45m ./... on mote: 80 packages ok; internal/gui red
  only in its real-window AppKit tests (TestDockJoinLeadsCommandTab,
  TestPanelCloseHidesIt, TestMainWindowCorners, ...), which fail the same
  on fresh origin/main 2f65a33aa on mote (#4125, #2645).
- gofmt -l clean; go vet ./... on Windows (win-run) clean; on Linux
  (wsl-run) clean with -tags nogui (the WSL distro has no gtk4).
- GUI: group-found-skip (new) and group-found-off, all five languages,
  1100px and 390px, Chromium and WebKit on Linux (wsl-run): 24/24. On
  mote every WebKit launch times out (#4125), Chromium 12/12 there.
- The routing files the full run flagged (concurrency 6) rerun alone on
  wsl-run, here and at fresh origin/main 380032cda: click-scroll's
  WebKit case and group-morph's WebKit 420px cases fail the same on
  origin/main. group-duplicate's de case was mine: the found groups'
  new "Anbieter ausnehmen..." line made German taller than the test's
  420x1200 window, which it assumes needs no scroll; it now uses 1400
  and passes 10/10 in both engines.
- Whole GUI suite on wsl-run, concurrency 6: still running at push time
  (5092 ok, 170 not ok so far, mostly in files this change doesn't load:
  account-*, agent-*, connect-*, gui-de/gui-ja's "{agent}" placeholder
  string). They are compared against origin/main after the push.

Broken by hand: foundGroups without unskipped -> TestAutoGroupSkip and
TestGroupsSkip red. Test calls before the fix to groupCmd's args ->
TestGroupAutoSkip red.

Not tried: the real app with real providers; a model-level skip (a
model is kept out by removing its found group, as before).
2026-10-31 00:57:21 +08:00
yetone 65c7924108 cli: TestProviderAddressMovesALocalServer adds LM Studio in a folder of its own
The test added lmstudio in the package's shared config folder, so a
second run (-count=2 and up) found it there, added "LM Studio 2"
instead, and read the old provider back at localhost🔢 red on
origin/main 380032cda at -count=3, runs 2 and 3. It now gets its own
HOME, USERPROFILE, XDG_CONFIG_HOME and XDG_CACHE_HOME, as the other
provider tests in the package do. HOME alone was tried first and stays
red: the config folder comes from XDG_CONFIG_HOME, which testenv sets
for the whole package.

Run at this head, on mote: go test ./internal/cli -count=2 ok (53.8s);
-run TestProviderAddressMovesALocalServer -count=5 ok; gofmt -l clean.
2026-10-31 00:53:27 +08:00
yetone 380032cda1 providers: Send requests unmasked is the user's switch at any address, with a caution while on for one not local (AcMilan)
AcMilan (Discord) runs a vLLM at http://llm.corp.lan:8000, and the
editor never offered "Send requests unmasked": the switch showed only
for a localhost, *.local or private-IP address. Asked, he said the
choice should be the user's for each provider.

provider.SkipsRedaction is now: Unredacted, no signed-in account, not
another magpie, and at least one address. Nothing is looked up on the
request path. The editor shows the row for every provider but an
account or remote magpie. While it is ticked, an amber caution under it
names an address not on this computer or the local network (awayHost).
A name of the user's own DNS is asked about, only while ticked, through
POST /api/local-hosts (provider.LocalHost -> netproxy.LocalName: every
address loopback, private or link-local, 400ms lookup, kept 1 minute).
That answer only words the caution. CLI help and `provider show` say
the same. The 'away' i18n line is in zh, zh-TW, ja and de. To stay
inside the core script budget, a few nearby editor comments were cut
down (no raise).

Run (logs in the worktree's logs/):
- Full Go suite on mote at base 024393fbb (go test ./... -timeout 45m).
  Every package is ok except internal/gui. Its reds are the AppKit
  window tests (#4125, #2645, #1936, #3949, #3178) and
  TestRestartHandsTheGatewayOver (#4167), plus TestCoreScriptBudget,
  which was mine and is fixed. At the pushed head (rebased on
  995f84a0f): the gui, provider, netproxy, gateway and cli tests for
  this area, with TestCoreScriptBudget and TestI18n: ok.
- GOOS=linux go vet -tags nogui ./internal/... and GOOS=windows go vet
  on the touched packages: ok. gofmt -l is clean.
- provider-unmasked.test.cjs and decide-endpoint-label.test.cjs: 34/34
  in Chromium and 34/34 in WebKit (Linux, wsl-run), on the final app.js.
- The 155 GUI files that open a provider editor, both engines (WebKit
  on Linux, Chromium on mote). Each file red there was rerun on Linux
  beside the base 024393fbb. The one red this change caused was
  decide-endpoint-label: a /api/local-hosts fetch cut off by navigation
  showed as a console error. That is why names are now asked only while
  the switch is on. The rest are red on the base too and have issues
  (#4431 and others). mote's browsers were crashing (#4125), so
  Chromium was compared on Linux.

Broken by hand:
- The old local-only gate put back in SkipsRedaction: TestSkipsRedaction
  (lan name, vendor, public IP, own proxy) and
  TestLANNameUnredactedProvider went red.
- awayHost returning "": 12 caution tests went red.
- The "only while on" guard removed: 4 "nothing is asked while the
  switch is off" tests went red.

Not tried: a real LAN DNS server, or AcMilan's own setup; WebKit on
macOS (mote's WebKit can't launch, #4125); the Windows app; the whole
GUI suite beyond the provider-editor files.
2026-10-31 00:44:59 +08:00
yetone 995f84a0f9 codex: how early an expiring reset is used is a setting
A Codex reset card that would run out unused was spent 30 minutes before
it expired, a fixed resetExpiryLead. Now the lead is codexResetLead in
settings.json (minutes, 15 to 1440). Unset, out of range or unreadable
reads as 30m, never 0, and magpie never writes it unless the user does.

- settings: CodexResetLead and Settings.ResetLead(); the menu's values
  are 15m, 30m (default), 1h, 2h, 3h, 6h, 12h, 24h.
- provider: the spend (expiringResetSpent) and routing
  (Allowance.Restarts, through nextResetLook) read the same resetLead(),
  so they still agree (#717, #718). The "near" look cadence follows it:
  lead + 30m, at least 1h, so a look lands inside a long lead.
- GUI: Settings > Usage, under the Codex auto-use rows, a row "Codex:
  how early before one expires" with an app menu (no <select>), and the
  sub text says spending earlier loses what the windows have left. The
  four "before it expires" strings say the chosen lead. POST
  /api/settings/codex-reset-lead; the general save keeps the field.
  en, zh, zh-TW, ja, de.
- CLI: magpie quota auto-reset lead [30m|3h|<minutes>|default].
- app.js budget: the auto-use rows moved out to lazy autoresetown.js
  (painted in the same draw once loaded), so app.js and the core script
  stay under their budgets with no raise. The button sizes to its widest
  label (a grid of every label), so picking one never rewraps the row.

Run (all on mote through mote-run):
- go vet: darwin, GOOS=linux -tags nogui, GOOS=windows; nogui build.
- go test -tags nogui -timeout 45m ./... at 3955adccf (this change
  before the paint and sizer fixes, which touch only GUI assets): 81 ok.
  go test ./internal/gui at this head: ok.
- GUI, Chromium: codex-reset-lead, codex-auto-reset,
  codex-auto-reset-settings, segs-press-redraw, i18n-keys: 62/62.
  WebKit: every case of those files failed at browserType.launch
  (180s timeout) before a page loaded, both runs; mote's browser
  launches hang under #4125 (load ~26), so WebKit is not run.
- Rebased onto f7f2d75f2 (old-webkit's lazy list now has traywindows.js
  too): go build ./..., go vet -tags nogui ./internal/..., go test
  internal/gui (budgets included), cli, settings, gateway: ok. provider:
  ok but TestQuotaSpanCarriesEveryWindowField, red on main since
  7d4a63148 (#4457, fixed in ccbefe2a2). GUI old-webkit, i18n-keys,
  codex-reset-lead in Chromium: pass.
- Rebased again onto 62a1dcdd7 (clean): go test internal/gui (budgets)
  and internal/provider: ok; i18n-keys and Chromium codex-reset-lead
  12/12 pass; old-webkit 9/10, its Safari 15.0 case a WebKit launch
  timeout (#4125).

Broken by hand, each went red:
- resetLead() pinned to 30m: all 3 provider tests.
- resetExpiryNear pinned to 1h: the long-lead look test.
- ResetLead's range check turned into m == 0: TestResetLeadUnreadIsDefault.
- GUI resetLeadMinutes returning 30: codex-reset-lead in every language.
- The button without the sizer: de at 420px, "no click moved the page".

Not tried: a real Codex account spending a card at a non-default lead;
Windows and Linux runs (vet only). The whole GUI suite in Chromium on
mote has ~45 tests in 31 files crash with "browser has been closed" on
untouched origin/main c84c3e1c0 too (reducedMotion files, #4458).
2026-10-31 00:41:29 +08:00
yetone b889ffe813 library: a server can stay each agent's own entry with the MCP hub on (#4382)
cuipengcx90's #4382, Option A's first step (nifengfanpan asked on
Discord): with the MCP hub on, every Library server went behind magpie's
one entry, so a server that reads its project from the folder it starts
in, or keeps a session's state, resolved the wrong repository or shared
state across agents. A server now has a hub policy, Server.Hub ("hub" in
library.json): "" (shared, the default, so nothing changes for existing
users; "shared" is saved as "") or "direct". A direct server is left out
of the hub through inHub, the test that already keeps magpie's own image
server out, so each agent given it keeps its own entry written as with
the hub off, beside the hub's entry for the rest. An agent whose every
server is direct gets no hub entry. The hub neither lists nor runs a
direct server, at /mcp/magpie/hub either, and hubPrune ends one it held.
Switching goes through change(), so the agents are written again at once
and the entry from the other policy is removed. An unknown policy is an
error.

- GUI: with the hub on, the server editor has a "Through the MCP hub"
  switch (role=switch, not a <select>; not shown with the hub off or for
  the image server), a direct server's row has a "Not through the hub"
  tag, and the hub's line and the Connect sheet name the direct servers
  with the image server as given directly. Strings are in zh, zh-TW, ja
  and de ("MCP 聚合" as the core uses it).
- CLI: magpie library mcp hub <name> shared|direct (ServerHub), and
  magpie library marks a direct server.
- TUI: an edit keeps the policy.
- Not done: Option B (per-roots/project backends behind the hub, keying
  hubPool by roots). It is left for later; #4382 stays open for it.

Run:
- TestHubDirectServer (internal/library) and the extended
  TestLibraryMCPHub (internal/cli) on mote. Broken by hand: inHub back to
  !isSelf(s) makes TestHubDirectServer red ("codex with the hub on:
  [magpie], want [index magpie]").
- Real configs in a sandbox HOME on mote (fake claude on PATH, the real
  binary built from this tree): mcp add index + web for claude and codex,
  hub on, hub index direct, shared, then both direct. The direct index
  entry was in .claude.json and .codex/config.toml beside magpie's; with
  every server direct both files were byte-for-byte as with the hub off
  (json.tool diff and diff); shared again removed the index entry.
- Full Go suite (-tags nogui -timeout 45m ./...) on mote at this tree
  rebased on origin/main 72ed121fd: 81 packages ok. Before the rebase
  the only red was TestQuotaSpanCarriesEveryWindowField (#4457, fixed by
  ccbefe2a2). GOOS=linux and GOOS=windows go vet clean, gofmt clean.
- GUI on WSL (magpie-desktop; mote's GUI is broken, #4125), both engines,
  every language: the new mcp-hub-direct.test.cjs (1100 and 390 wide,
  hub on and off), library-mcp-hub, mcp-local-server, i18n-keys: 88 pass.
  Broken by hand: not sending hub in the save makes mcp-hub-direct red
  (11 of 11 in chromium).
- The 54 library/mcp/i18n GUI files at --test-concurrency=4 on WSL at load
  ~160: 978 of 988 pass. Red: library-chip-fan (webkit, fan positions),
  library-mcp-tools (chromium ja 420, "the click scrolled the page") and
  mcp-oauth-app (chromium de 390). None of them touch the hub switch or
  the editor's new field. They are being rerun alone, here and on
  origin/main, after this push; a red that only this change has is fixed
  next, and a red on main too is filed.

Not tried: the whole GUI suite (1028 files); a real cwd-sensitive
server in a real agent session; the live app window.
2026-10-31 00:34:45 +08:00
yetone 4f2d5fc7e0 routing: a group can put its cheapest member first, by each one's price at that hour
liyuanzheng (#general) and lam_em (#feedback) both asked for the same
thing. Off-peak, DeepSeek's own API should come first for deepseek-flash.
At DeepSeek's peak (weekdays 01-04 and 06-10 UTC, billed 2x since
v0.1.2173), another provider should come first, Ollama say. A schedule
editor would make the user copy DeepSeek's hours into magpie. Instead,
a group gets one more routing, "Cheapest first" (`cheap`). Each request
sorts the members by what they cost right then: input + output price per
million, at the peak rate when it is peak hours. A tie goes to the lower
cache-read price. Free models count as 0. A member with no known price
keeps its listed place after the priced ones. Prices come from the same
priceOf the usage ledger bills with, so the user's own ModelPrices,
list prices and maker prices all count, and so does a provider's rate
windows.

- routes: Seat carries Priced/Cost/CacheCost; Strategy.ByPrice; Cheapest
  is a stable sort, so equal prices keep the user's order.
- gateway: weighRouted prices each seat at priceClock() (time.Now; a test
  holds it) through the new provider.PriceAt. The trace's Weighed row
  gets a price (input/output/cacheRead/peak) so Routing can say why.
- It is a group's alone, like Manual. A provider saved with it drops it,
  and `magpie provider set … routing=cheap` refuses it. Groups take it in
  the GUI menu (one more item, no new controls), the TUI and
  `magpie group set <id> routing=cheap` (aliases cheapest, price, cost).
- Routing's mode line says why the first one is first, e.g. "Cheapest
  first: deepseek-v4-flash costs least on ollama-cloud now — $0.150 in,
  $0.600 out a million tokens.", with peak and unpriced variants.
  en/zh/zh-TW/ja/de.
- Docs: gateway-routing, plugin-runtime, reference (it also points at
  Time window and Pause rules for a fixed schedule) and the site's start
  pages (en/zh/ja).

Run, at f7f2d75f2 (this change rebased onto it):
- Red on the old code: TestCheapestFirstGroupFollowsPeakHours (deepseek
  vs ollama with ModelPrices, priceClock held at 14:00 UTC off-peak and
  02:00 UTC peak) and TestCheapestOrdersByPriceNow did not compile
  without Cheapest. TestCheapestFirstIsAGroupsOnly checks that a provider
  drops it and a group keeps it.
- Broken by hand: without `pr = pr.In(at)` the gateway test is red ("at
  DeepSeek's peak ... went to deepseek"). With Cheapest returning the
  order unchanged, both the routes test and the gateway test are red.
  Both were restored.
- Full Go suite on mote (-count=1 -timeout 45m ./..., log kept): every
  package ok except two. internal/provider had
  TestQuotaSpanCarriesEveryWindowField, which is red on origin/main (#4457,
  fixed since in ccbefe2a2). internal/gui had ten AppKit window tests
  killed at their 20-40s deadlines (TestPanelCloseHidesIt,
  TestMainWindowCorners and others). Three of them are red the same way
  on a fresh origin/main f7f2d75f2 copy, under #2645/#4125 (mote has
  several GUI suites running). After the rebase, go vet and the Cheapest,
  SpeedFirstGroup, ParseRouting, ApplyGroupPairs and ProviderRouting tests
  are ok. go vet darwin, GOOS=linux -tags nogui and GOOS=windows are ok,
  and gofmt is clean.
- GUI on WSL (Linux, chromium + webkit): routing-cheapest-first (new,
  3 scenes x en/zh/zh-TW/ja/de x 2 engines), routing-group-strategy,
  builtins, i18n-keys and routing-speed-first gave 95 of 96. The one red,
  routing-group-strategy "webkit en light ... the pick moved nothing", is
  a wheel-scroll timing red. It fails 3 of 3 on origin/main and 1 of 3 here
  (#4459). Core-script budget ok (app.js +9 bytes).
- The whole GUI suite (1025 files) was started on WSL at this tree and
  was still running when this was pushed, at load ~160.

Not tried: real DeepSeek or Ollama accounts, and a real request during
DeepSeek's peak hours. Ollama Cloud's price here is the catalog's, not
checked against a bill.
2026-10-30 23:59:31 +08:00
yetone d99e213f5b codex: an account switch restarts nothing while Codex's provider takes no ChatGPT account
danzi002 on Discord: with requires_openai_auth = false on Codex's provider,
switching the Codex account in magpie still restarted the Codex app's
app-server and said the app and daemon were left on the old account.

Codex's provider with no requires_openai_auth = true goes by no ChatGPT
account: codex-rs ModelProviderInfo::account_state answers no account, and
resolve_provider_auth sends the table's key, never auth.json. So which
account auth.json holds is nothing a running Codex uses.

- provider.CodexNoAccount (set to agent.codexNoAccount): the config's top
  model_provider is not openai, has a [model_providers] table, and the table
  doesn't say requires_openai_auth = true. A profile, the built-in provider,
  no table or an unreadable config count as false (may use the account).
- codexAppStep forgets a switch (and a spent switch) while it holds, so the
  app-server is left running; a route change still restarts it.
- CodexAppStale / CodexDaemonStale say nothing, and `magpie accounts`'
  switch line says nothing needs restarting.
- Kept: route-change restarts (model_provider, openai_base_url,
  model_catalog_json, base_url, catalog hash: read only as the app-server
  starts) and the daemon's model-list restarts; and switch restarts when
  magpie writes requires_openai_auth = true (ChatGPT sign-in with room).

Run (mote-run; full suite at this change on e0ad48641):
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./..., go build for darwin/linux(nogui)/windows: ok.
- go test -tags nogui -timeout 45m ./...: 81 packages ok, no FAIL.
- New tests: TestCodexNoAccountSwitchRestartsNothing (provider),
  TestCodexNoAccountFollowsRequiresOpenAIAuth and
  TestCodexNoAccountOfEachConfig (agent).
- Broken by hand: codexNoAccount returning false in provider made
  TestCodexNoAccountSwitchRestartsNothing red (ended the app-servers);
  agent's codexNoAccount returning false made both agent tests red.
- Real codex-cli 0.165.0 in a sandbox CODEX_HOME with a provider table at
  requires_openai_auth = false: app-server account/read and getAuthStatus
  answered no account before and after auth.json was switched from a@x to
  b@x, and `codex exec` against a loopback capture server sent
  `Authorization: Bearer <the table's key>` with no chatgpt-account-id for
  both accounts.

After rebasing onto origin/main (2 commits: gateway desktop probe,
usage purposes): go vet ./... and go test of internal/agent, provider,
cli, usage and gateway at the pushed head: ok.

Not tried: the real Codex desktop app (macOS or the Windows MSIX) through
a switch; a daemon with live sessions through a switch; the GUI suite
(no GUI asset changed; the switch notice reads CodexAppStale).
2026-10-30 21:01:09 +08:00
yetone 0804f2d97d search: Tencent Cloud's Yuanbao Search (wsa) is a built-in search API (plugins#509)
chenjiangzi asked for Tencent Cloud's WSA SearchPro (元宝搜索). It is added
as vendor "wsa", following Doubao Search (dca3e2d71), from Tencent's
own docs:
- API-key method (cloud.tencent.com/document/product/1806/130615):
  POST https://api.wsa.cloud.tencent.com/SearchPro with
  Authorization: Bearer <key> and a JSON body {"Query", "Cnt": 10}.
  Keys come from console.cloud.tencent.com/wsapi/index (KeysURL).
- SearchPro (121811): Response.Pages is an array of JSON strings, each
  with title, url, date, passage and content. The text is passage, or
  content when passage is empty or only the title. Tags are stripped.
- Errors (121818/121820, 130615): HTTP 200 with Response.Error{Code,
  Message}. AuthFailure*, UnauthorizedOperation and ResourceNotFound are
  turned away (403); ResourceUnavailable (欠费), LimitExceeded and
  ResourceInsufficient are out of credit (402); RequestLimitExceeded* is
  rate limited (429); others are plain errors, with the key masked.

The fixtures in testdata are the docs' two example replies. 130615's is
shown with its quotes escaped twice, which isn't JSON; they were
unescaped once and nothing else changed. The GUI's picker is built from
SearchVendors, so no GUI file changes. README (en, zh), the CLI help and
gateway-routing.md name it.

Run on mote (mote-run), at the rebased head:
- go test -run 'SearchAPI|WSASearch|Volcengine|Search' ./internal/gateway/
  ./internal/gui/
  ./internal/provider/ ./internal/cli/: ok
- go vet -tags nogui darwin/linux/windows: ok; gofmt -l clean
- GUI (no GUI file changes; the picker reads SearchVendors):
  search-api.test.cjs in Chromium 4/4 ok. Its WebKit cases and
  searcher-pick timed out at browserType.launch (180s) on mote,
  where ~57 WebKit pw_run launches from several sessions hang. Not
  a result about this change; WebKit not run.

Broken by hand, each made TestWSASearchAPI red: the wsaSearchError call
removed, and Cnt dropped from the body.

Not tried: the real API. No WSA key was available, so the request,
reply and error mapping rest on Tencent's docs only. The full go test
./... is to follow.
2026-10-30 14:56:01 +08:00
yetone acbd6b11ab search: a search API's URL given with the path magpie adds is its base, never …/search/search (plugins#509)
chenjiangzi set Tavily's url to https://api.tavily.com/search, and magpie
appended /search again. Each vendor now names the paths magpie puts after
its base (SearchVendor.Paths). A url that already ends in one of them,
with or without a trailing slash and in any case, is cut back to its base.
This happens when it is saved (SetSearchAPI) and again when it is read
(SearchAPI.Base), so an entry saved before this change works too, and so
does Tavily's quota URL built on the same base. Every vendor is covered:
tavily, brave, exa, firecrawl, you (both paths), deepseek, volcengine,
searxng, and wsa in the next commit. A path of the user's own
(/my-search) is left alone. The url= help and gateway-routing.md say so.

Run on mote (mote-run), at the rebased head:
- go test -run 'SearchAPI|WSASearch|Volcengine|Search' ./internal/gateway/
  ./internal/gui/
  ./internal/provider/ ./internal/cli/: ok
- go vet -tags nogui for darwin, GOOS=linux and GOOS=windows on
  provider, gateway, cli (and gui on darwin): ok; gofmt -l clean
- GUI (no GUI file changes; the picker reads SearchVendors):
  search-api.test.cjs in Chromium 4/4 ok. Its WebKit cases and
  searcher-pick timed out at browserType.launch (180s) on mote,
  where ~57 WebKit pw_run launches from several sessions hang. Not
  a result about this change; WebKit not run.

Broken by hand: ownBase returning the URL unchanged made
TestSearchAPIBaseURLWithItsPath red ("asked /relay/tavily/search/search,
want /relay/tavily/search").

Not tried: a real Tavily request; the full go test ./... (to follow).
2026-10-30 14:56:00 +08:00
yetone 70a0c387cb agent: a provider named magpie written by hand is the user's, not connected (JFunfunfun on X)
Pi set up by hand on a provider of its own named magpie (magpie/<model>
at the gateway) read as connected in magpie: every catalog change wrote
magpie's list over that provider, RenameProvider rewrote its refs, Drift
offered Reconnect, and Disconnect took the provider out.

0911a65e7 (yyddbds, MiMo) already holds a ListOnly agent's sync until
it is Wired; that still let a hand-written config that names a magpie
model (JFunfunfun's Pi) read as Wired. Both gates now apply.
Its test's last case said a magpie model picked by hand on MiMo's own
magpie provider connects it; that is JFunfunfun's case, so it now
stays the user's until connected in magpie (listonly_test.go, and the
doc's ListOnly line says so).

An agent whose magpie is a provider of its own config (Spelled, not
Native) is now connected only when magpie set it up (setUp): a field in
applied.json, the new applied.Kept that Keep leaves instead of deleting
the record, or the <id>.connect.was stash Connect has written since
10-03. Otherwise (handWired) it isn't Wired, has no Drift, and
SyncCatalog, RenameProvider and renameRefs skip it; Disconnect is a
no-op as it is for any unwired agent. Connecting it in magpie takes it
on as before; Disconnect after that skips putting back "was" values
that were themselves magpie's (dsh errored on them). RenameLegacy
records the dial/ -> magpie/ values it writes, and moveEfforts (the
Cursor/Antigravity effort ids, at start-up) leaves a hand-written
magpie/<ref> alone. Aside keeps its own
key-based ownership. OpenCode's own-gateway-provider test now connects
through Apply as `magpie opencode` does.

Run (on mote, at this head, rebased on f2c6831a3): go test -tags nogui
-count=1 ./internal/agent ./internal/cli ./internal/library
./internal/gui; go vet darwin/linux/windows of internal/agent and
internal/cli; gofmt -l. internal/agent again after the ListOnly test
change: ok. Pushed on ceef9e943, whose five commits since touch usage,
sessions, library, provider movers and gui only.
New tests: TestPiHandWiredMagpieProviderIsTheirs (pi's literal
settings.json/models.json in a sandbox HOME, files byte-identical after
SyncCatalog, RenameProvider and Disconnect), TestPiConnectedBefore-
StaysConnected (applied record, gone model, connect.was, applied then
Keep), TestHandWiredMagpieProviderSiblings (29 Spelled agents). All fail
on the old code.
Tests that wrote a connected agent's files by hand (Pi, OpenCode,
Hermes, omp, dsh, the Kilo plugin, Cursor efforts, and the cli's
save-then-sync test) now also mark it as Connect leaves it
(setUpInMagpie, the connect.was stash); without it they read as
hand-written, which is what this change is about.

Broken by hand, each red: the Sync gate, the rename gates, the Drift
gate, Keep deleting the record, the was-skip in Disconnect, the
moveEfforts gate (TestMoveCursorEfforts' hand-wired case).

Not tried: a real pi binary against the gateway. Users connected
between 09-23 and 10-03 who pressed Keep (record deleted before this)
read as not connected; one Connect brings them back and pi keeps
working meanwhile. Agents without Spelled (Claude Code, Codex, Gemini
and others) decide by their own checks and are unchanged.
2026-10-30 14:45:56 +08:00
yetone f2c6831a31 gateway: a read-only gateway key reads quotas and usage and uses nothing (Steven on Discord)
Steven's ESP32 desk display polls magpie (Docker, on his LAN) every 15s
on GET /v1/magpie/quotas and /v1/magpie/usage and never sends a model
request. Only a key held to nothing was told the usage summary, so the
key kept in the device's flash had to be one that could spend every
account.

A gateway key can now be read-only (access.Key.ReadOnly):
- `magpie gateway-key add <name> --read-only`, `magpie gateway-key access
  <id> [read-only|full]` (`gateway-key --help` lists it; `list` has an
  ACCESS column), and "Make read-only" / "Give full access" in the key's
  menu in Gateway -> Gateway keys, with a "Read only" tag on its row.
- readOnlyGuard (internal/gateway/readonly.go), after callerGuard and
  before withCaller/keyLimited, judges the pattern ServeMux.Handler routes
  the request to. A read-only key is answered GET /, /v1, the quotas,
  their history and cards, the usage summary and its requests, its limit
  and the concurrency. Every other route is refused with 403
  gateway_key_read_only: every model route, count_tokens, the Responses
  WebSocket's upgrade, every MCP server, Codex's and Gemini's backends,
  /v1/models and the Ollama routes, the catch-all, the trace and route,
  debug profiles, and every write (usage ingest, quotas refresh). It is
  default deny, so a route added later is refused until it is classified.
- The key is held to nothing else, so heldKey leaves it alone: it reads the
  usage summary and every account's quotas, as a key held to nothing does.
  None of those routes holds a key's secret.
- The sharing key can't be made read-only, since magpie gives it to its own
  agents (LANSecret). Update refuses it, and the GUI item is off with why.

Older versions: a magpie from before this commit doesn't know `readOnly`
and treats such a key as a full one, so downgrading magpie widens the key.

Tests:
- TestReadOnlyKeyEveryRoute (internal/gateway/readonly_test.go) takes the
  patterns from the router itself (routes() records each HandleFunc). It
  fails when a pattern is in neither readOnlyRoutes nor its refused list.
  It sends every refused pattern, by each method it takes, from
  192.168.1.9 and from loopback, plus a WebSocket upgrade and an unclean
  chat path, and expects 403 gateway_key_read_only with the upstream never
  reached. It checks that every allowed route answers, that no body holds
  any key's secret or the upstream key, that the usage summary names the
  other key's use, and that a full key and a key made full again still
  reach the model.
- TestReadOnlyKey (access) covers add-key and access-key on and off,
  Authenticate, List, and the sharing key refused.
- TestGatewayKeyCLIReadOnly covers --read-only before and after the name
  and beside --key, access, the list column, bad values, and --help.
- gateway-key-readonly.test.cjs runs Chromium and WebKit, 1100 and 420px,
  in en/zh/zh-TW/ja/de. It covers the tag, both menu items and what they
  post, the status line, the sharing key's item off with its why, no
  scroll on click, no sideways scroll, no select, and no left stripe.
  gateway-card.test.cjs now expects the menu's 4th item.
- TestClientPathCoversHandler takes the patterns from routes() instead of
  parsing Handler's source, which moved into routes().

Broken by hand:
- readOnlyGuard passing everything: TestReadOnlyKeyEveryRoute red (103
  lines, /v1/models 200 onward).
- A new `POST /v1/new-thing` route in routes(): red, "in neither
  readOnlyRoutes nor readOnlyRefused".
- The GUI item not off for the sharing key: gateway-key-readonly red 10 of
  10 in Chromium.

Run at the pushed head (on origin/main 0911a65e7), on mote: TestReadOnly*,
TestHeldKey*, TestClientPathCoversHandler, TestGatewayKey*, TestCaller*
in access, cli and gateway ok; TestCoreScriptBudget ok; on Linux
(wsl-run, both engines) gateway-key-readonly, gateway-card, i18n-keys,
gateway-caller-keys and gateway-key-quotas 68/68.

Full Go suite on mote (macOS) at the same change on origin/main
dca3e2d71 (94630237d), -timeout 45m: 78 packages ok; internal/gateway
red only on the four TestAntigravityTurned* and
TestCodexSpentGrokFailingIsTold (red the same at origin/main, #4362);
internal/gui red only on ten AppKit window tests that hit their 30s
bar while mote's launchd throttled every app launch (#4125).

Run on mote (macOS) on origin/main dca3e2d71:
- go test ./internal/access ./internal/cli ./internal/gateway: access ok;
  cli red only on TestLibraryMCPHub's TempDir cleanup (#4140); gateway
  red only on the four TestAntigravityTurned* and
  TestCodexSpentGrokFailingIsTold, red the same at origin/main (#4362).
  TestReadOnly*, TestHeldKey*, TestClientPathCoversHandler,
  TestGatewayKeyCLIReadOnly pass.
- TestCoreScriptBudget ok (no budget raised). gofmt clean; go vet
  darwin (access, cli, gateway), GOOS=windows ./... and GOOS=linux
  -tags nogui ./... clean.
- GUI, earlier at 807048470 on mote: gateway-key-readonly,
  gateway-key-quotas, i18n-keys, gateway-card, api-key-theme,
  gateway-connect-keys and gateway-caller-keys 34/34 in both engines.
  At this tree mote's WebKit hung at launch for every test (#4125), so
  the 43 gateway-*/key-*/api-key-*/caller-*/menu-*/i18n-* files ran on
  Linux (wsl-run, both engines): 501 of 514. The reds in api-key-theme,
  gateway-key-limit, gateway-key-models, key-replace and menu-input-scroll
  are red the same at origin/main e8d42c02d (#4120, #3523, #4081, #4126,
  #3402); gateway-keys-empty's WebKit wait was red 1 in ~13 runs here and
  0 in 4 at main, filed as #4383 (this change doesn't touch its path).
- Full Go suite on Linux (wsl-run, at 807048470 with this change): reds
  only where Linux can't build the GUI (no gtk4/webkitgtk) and in
  internal/agent's install tests (#4033) and the gateway reds above,
  each red the same at origin/main dca3e2d71; plus
  TestClientPathCoversHandler, which parsed Handler's source and is now
  read from routes() (fixed here).

Not tried: a real ESP32 or Docker magpie; a remote client against a
running gateway (only httptest through lanGuard/Handler); the Windows
test runs (vet only); the whole GUI suite (mote's WebKit hung, #4125).
2026-10-30 14:33:01 +08:00
yetone 0911a65e7d agent: a catalog sync leaves a magpie provider the user wrote alone while the agent isn't connected
yyddbds on Discord: in Xiaomi MiMo they added a custom provider pointing
at magpie and picked a few models by hand. MiMo's switch on the Agents
page was off, yet after an update the provider held every one of
magpie's models. SyncCatalog runs at each start and update and on every
catalog change, and MiMo Code's Sync (openCodeLike) brought any
provider.magpie block up to the catalog whether magpie wrote it or not.
magpie's default went over a list the user set.

An Agent whose Sync does nothing but keep a block of magpie's name up
to the catalog is now ListOnly, and SyncCatalog runs it only while the
agent is Wired, which is what the Agents page's switch shows. The same
sync was in every sibling, so ListOnly is on all of them: openCodeLike
(OpenCode, MiMo Code and their WSL forms), piLikeKeyed (Pi and forks),
Goose, Crush, Air, AtomCode, Command Code, Droid, Fx, jcode, Kimi,
MiniMax, Mothx, omp, OpenChamber, OpenClaw, OpenPencil, Penguin, Qwen
Code and T3 Code. Left out on purpose: Codex, Claude, Grok and Hermes,
whose Syncs also repair while not connected (Hermes keeps its bots'
magpie provider current) and have their own gates.

Trade-off: a list magpie wrote while connected doesn't follow the
catalog while the agent runs a model of its own (switch off); it does
again once a model of magpie's is picked. Users whose list was already
written over: magpie keeps no copy of the old list, so it stays full;
from this release on it is left alone, and they trim it once by hand
(or connect the agent in magpie and use its model list's Pick).

Tests: TestCatalogSyncLeavesAHandWrittenMagpieBlock (MiMo, Pi and Crush
with a hand-written magpie block stay byte for byte; connected, MiMo's
list follows the catalog; disconnected and written by hand again, left
alone; a magpie model picked in MiMo, followed again).
TestListOnlyAgentsReadConnected: every ListOnly agent magpie connects
reads as Wired (n >= 15), so none of them loses catalog updates.
Fixtures of TestSyncCatalogRewritesAgentLists,
TestModelNameAndLevelsReachAgentFiles, TestSuffixModesReachAgentFiles
and TestPiKeepsTheirKeysInMagpiesProvider, and internal/cli's
TestSaveAnswersBeforeTheAgentsSync (its Pi settings were {}), now have
Pi connected (settings.json defaultProvider magpie), as a block magpie
wrote implies.
docs/subsystems/agent-wiring.md says the rule.

Run (mote, sandbox HOME via the tests' syncHome/codexHome):
- old code + the new test: red (MiMo, Pi, Crush written over; after
  Disconnect written over).
- broken by hand: ListOnly dropped from openCodeLike: red on MiMo
  (lines 52, 82); the Wired gate in SyncCatalog replaced with true: red
  on all three.
- go test -tags nogui -count=1 ./internal/agent: ok.
- gofmt -l clean; go vet ./... for darwin, GOOS=linux and GOOS=windows:
  ok.
- full suite, go test -tags nogui -count=1 -timeout 45m ./... at base
  3bebc3839 (logs kept in the worktree): every package ok but
  internal/cli (TestSaveAnswersBeforeTheAgentsSync, mine, fixture fixed
  above, then ok alone) and internal/gateway: TestAntigravityTurned*,
  TestAntigravityTurnsCodexsGPT5ThreadAwayOnce and
  TestCodexSpentGrokFailingIsTold, red the same on a fresh origin/main
  b26fa0903 copy, filed as #4362.
- rebased on e8d42c02d: vet (darwin, linux, windows) of internal/agent and
  internal/cli, and go test of internal/agent, internal/cli,
  internal/library and internal/gui: all ok. Pushed on 764a032f6,
  whose three commits since touch gateway, usage, provider and chat only.

Not tried: the real Xiaomi MiMo desktop app (the fixture is the OpenCode
shape MiMo Code writes; whether the reporter's provider id is literally
"magpie" is unconfirmed: a provider of another id was never touched).
Lists already written over are not restored.
2026-10-30 14:25:38 +08:00