Commit Graph
203 Commits
Author SHA1 Message Date
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
yetone dca3e2d716 search: Doubao Search (Volcengine) as a search API (CyberCaius on Discord)
CyberCaius asked on Discord #help (10-30) for Volcengine's Doubao search
under Settings › Models › Search APIs, or a custom API address. Volcengine's
Doubao Search Custom (豆包搜索 Custom版, once 联网搜索 / 融合信息搜索,
docs.volcengine.com/docs/networked-search/networked-search, the same page
as volcengine.com/docs/87772/2272953) can now be added with its API key:

- provider.SearchVendors: volcengine, "Doubao Search (Volcengine)", at
  https://open.feedcoopapi.com, keys at
  console.volcengine.com/search-infinity/api-key, after DeepSeek. The GUI
  takes its vendors from SearchVendors, so it shows in the Search API
  picker with its Get a key link and base URL field; no GUI file changes.
- askSearchAPI: POST /search_api/web_search, Bearer key (the default, as
  the docs and volcengine/mcp-server's askecho_search_infinity send it),
  body {Query, SearchType: "web", Count: searchHits, Filter: {NeedUrl:
  true}}. The query is cut to the 100 characters the docs allow. NeedUrl
  leaves out its 火山如意 cards, which have no URL to cite.
- readVolcSearch reads Result.WebResults: Summary as the page's text (the
  docs recommend it for models; Content is the whole page, Snippet
  ~200 chars "only for list display"), Snippet when there is no Summary,
  PublishTime as the page's age, a 1970-01-01 time (its image example's
  stand-in) as none, and a result with no Url left out.
- volcSearchError: its errors are in ResponseMetadata.Error, a code the
  docs list, and the docs don't say the HTTP status, so the code decides:
  10401/10403/10409 rest the key as turned away (403), 10406/10408/
  10410/10412 (free searches spent with none paid, no plan, plan spent)
  as out of credit (402), 700429 as rate limited (429). Any other code is
  a plain error, a 200 carrying one included. The key is masked in the
  error as for every vendor.
- A custom address: every search API already takes a base URL (#1580,
  the field under the key in Settings, url= in the CLI), so an endpoint
  that answers as Tavily, SearXNG, Brave, Exa, Firecrawl, You.com,
  DeepSeek or now Doubao Search does can be set there. There is no common
  format across the vendors (each has its own path, body and reply), so
  no separate "custom" vendor was added.
- Siblings: CLI usage (main.go, search_cli.go's api list and empty-state
  hint), README.md, README.zh-CN.md, gateway-routing.md's path list and
  refusal paragraph.

The test's reply is the docs' own web-search response example, byte for
byte (testdata/volcengine_web_search.json); its error replies are the
docs' error example with its "// 该字段为错误码" note taken out (not JSON).
Not tried against the real API: no Volcengine search key in this run.

Run (worktree on origin/main c941e0877, then rebased on d31710c71):
- TestVolcengineSearchAPI (new): red on the old code (no such vendor).
  Broken by hand six ways, each red with its own message: Summary not read
  (Snippet's text), volcSearchError not called (200 10403 read as "no
  Result in it"), query not cut (150 characters went), NeedUrl dropped
  (body {"Filter":{}}), 1970 age kept, 10412 not mapped (plain error, not
  a refusal). Restored: ok.
- go test -run Search ./internal/gateway/, go test ./internal/provider/
  ./internal/cli/: ok, before and after the rebase.
- gofmt -l internal: nothing. go vet -tags nogui ./... on darwin,
  GOOS=linux, GOOS=windows: ok.
- Not run before the push: the full go test ./... . mote had three other
  sessions' full suites running at load 140-230; it runs after the push
  and its result goes on the report.
2026-10-30 13:28:45 +08:00
yetone e887139e7a providers: Best in family serves the newest model of each family a provider lists
Steven on Discord #feedback asked for a provider to serve only the newest
model of each family, so a newer one (Opus 5.6) takes the old one's place
without re-picking.

The provider editor's Models control gets a fourth option, beside
Vendor's list / Picked only / Usage only: Best in family. It is also on the
CLI as `magpie provider models <id> best`. With nothing picked, the provider
serves only the newest model of each family in the vendor's list, up to 24.
A family is the id with its version numbers taken out
(catalog.FamilyOf/BestInFamily in internal/catalog/family.go). A dated
snapshot counts as its alias, and sizes and suffixes (mini, flash, -fast,
-thinking) stay part of the name. Provider.Exposed applies it, and so does
Codex's native list (CodexNativePicked). A provider/model a request names
explicitly is still served, since resolve doesn't go through Exposed. A pick,
Select none or Usage only clears the flag (normalize), and a providers.json
without bestInFamily reads as before, so every existing mode is unchanged.
The editor draws the family's newest as dashed (m.best) before saving. Every
language has the wording (zh, zh-TW, ja, de). The design reference is
docs/subsystems/providers-accounts.md (Model picks).

Tests: family_test.go is a table of real ids, including the models.dev Claude
list in testdata (no network). There are also best_in_family_test.go
(provider), TestProviderModelsBest (cli), provider_save_best_test.go (gui
save keeps/clears), codex_best_in_family_test.go (gateway) and
provider-best-in-family.test.cjs (5 languages x chromium/webkit x 1100/420).

Broken by hand: with the BestInFamily filter in Exposed and in
CodexNativePicked turned off, the 4 new Go tests went red.

Budget: after the rebase app.js went over appScriptBudget. Comments were cut
and the tooltip and hint merged into one string, so app.js is 1,311,399 of
1,311,735. Neither budget was raised.

Run at this head, on origin/main 1027db408, via mote-run (macOS 27):
- gofmt -l clean; go vet clean for darwin, linux -tags nogui and windows
  (at base 05a6087e1, the same Go diff).
- go test -count=1 ./internal/catalog ./internal/provider ./internal/cli
  ./internal/gateway: ok.
- go test ./internal/gui: everything except TestMainWindowCorners/macOS_26_SDK
  (red on macOS 27, #3949; not this change).
- node --test: provider-best-in-family, provider-none-picked,
  provider-picked-only-shows-picks, i18n-keys, gui-de, gui-ja, gui-zh-tw,
  context-map and gateway-key-models, 113 tests, 108 pass. The 5 reds are
  context-map 420px "two tiles overlap" (#3488, #4304) and gateway-key-models
  webkit en (#4304). Both fail the same way on a clean origin/main 1027db408
  checkout run alone (8 of 30 red there).
- The earlier wider GUI run (38 provider/routing files, concurrency 3) had
  the same red files on origin/main deb0b8da7 as at this change's head:
  model-chip-steady, models-works-only, provider-fetch-again and the others
  in #4304. Three with no issue were filed: #4320 (recovered-file),
  #4321 (tencent-cloud), #4322 (warm-now).

Not tried: no real account or real magpie app; the editor was checked
through Playwright screenshots only. Families are read off the id alone, so
a vendor whose ids don't put the version in numbers (or orders them
oddly, e.g. grok-4.20 against grok-4.7 compared numerically) may group
or rank unexpectedly. Bedrock's -v1:0 counts as version digits.
2026-10-30 04:48:17 +08:00
yetone 4054251865 library: an MCP server can be kept to this computer, never synced
huhuy72219405 on X: "能不能把不同设备的mcp区分一下,有些mcp属于本地的,
同步之后其他设备不应该读取到". A server in Library > MCP now has a
"This computer only" switch in its editor (Server.Local; CLI
`magpie library mcp add ... --local` and `magpie library mcp local
<name> on|off`; the TUI keeps it on edit and marks the row).

- Collect leaves local servers out (carriedServers), so neither a sync
  nor a backup file takes one to another computer. Turning a shared
  server local takes it out of what is carried, so the other computers
  drop it at their next sync; the flag itself is never carried.
- Put (sync, join, Restore, Undo, backup file) keeps every local
  server, with its agents, and clears Local on what comes in.
- Another computer's server by a local server's name goes to
  Library.Away: given to no agent, not in the hub, carried on as it
  came, so a push from here never removes it from the computers that
  have it. settleAway (every change) promotes it once the name is gone
  here, and drops it once the name is shared here again.
- The hub serves local servers like any other (it runs here);
  subagents aren't carried, so one naming a local server keeps it.

Docs: docs/subsystems/library.md, docs/subsystems/sync-backup.md.

Run at f5dd4e142 + this change; after rebasing on d3898ca8d (gui/provider only, then 2a1ef15ba, routing), vet, the five new Go tests, mcp-local-server and i18n-keys again, ok:
- mote: gofmt -l clean; go vet of library/backup/davsync/cli/tui;
  GOOS=linux and GOOS=windows go vet -tags nogui of the same; go test
  of TestLocalServerNotCarried, TestPutKeepsLocalServer,
  TestPutSameNameAsLocal (library), TestRestoreKeepsLocalServer
  (backup), TestLocalServerThroughSync (davsync, two computers through
  the fake S3) ok.
- mote GUI, Chromium and WebKit: mcp-local-server.test.cjs (new; every
  language, 1100 and 390 wide, switch saves local true/false, row tag,
  no sideways scroll), i18n-keys, mcp-editor-cancel,
  mcp-startup-timeout, every library-mcp-*, mcp-oauth-app, mcp-signin*,
  library-items, library-servers-bulk, library-subagents,
  library-pick-remove, library-env-refs, library-zed-mcp,
  library-loading: all pass (126 of 126 in the last batch).
- Full Go suite, -tags nogui -timeout 45m, on the Linux box (wsl-run;
  mote had another session's full suite running): every package ok
  but internal/agent, whose TestInstalledVersion, TestGrokInstalled,
  TestOmpDetectedWithPiDir and TestZedAppPath fail the same at
  origin/main 9b4d0bda8 on that box; all four are #4033.
- Real CLI in a sandbox HOME on mote: mcp add --local, local on/off,
  `magpie library` shows "this computer only", library.json has
  "local": true; an unknown name and a bad value are refused.

Broken by hand: putServers not keeping local servers turned
TestPutKeepsLocalServer, TestPutSameNameAsLocal,
TestRestoreKeepsLocalServer and TestLocalServerThroughSync red;
carriedServers carrying local servers turned TestLocalServerNotCarried,
TestPutSameNameAsLocal, TestRestoreKeepsLocalServer and
TestLocalServerThroughSync red.

Not tried: a sync between two real computers; the real GUI app (the
Playwright run fakes the API); the full Go suite on macOS or Windows.
2026-10-30 02:31:08 +08:00
yetone 05a6087e1f access: a key with accounts and no model may use only its accounts' providers' models
Linka on Discord (#feedback): in a gateway key's "Models this key can
use", ticking only an account and no model let the key list and use
every model of every provider.

Cause: Key.Models empty meant "every model", and Key.Accounts (#905)
held only the providers it names, so every other provider stayed open.

Change: access.HeldModels gives a key with accounts and no models the
models "<provider>/*" of each account's provider. Authenticate builds
the Identity with it, so every route's existing model gate narrows:
/v1/models, /v1beta/models, chat, responses, messages, Gemini,
count_tokens, embeddings, images, the Codex backend path, System One,
groups and fallbacks. A key that lists models is unchanged (#905: its
accounts still hold only the providers they name); a key with neither
is unchanged. The CLI's MODELS column and `gateway-key models` say so,
and the GUI editor's hint, the "not used" notes on providers no model
or account reaches, and the save status follow (en, zh, zh-TW, ja, de).

Tests:
- TestGatewayKeyAccountsOnlyHoldTheModels: each route above is 403 for
  the accounts-only key and no upstream call reaches the other
  provider, the decider or the image provider; its own provider, a
  group of it and a key that also lists models work. Red on the old
  code on every route (list showed spare/m2, chat/count_tokens/
  embeddings/systemone 200).
- TestHeldModels (access).
- gateway-key-accounts.test.cjs: hint, notes and status; 4/4 red on
  the old assets, green on the new.
- TestGatewayKeyAccountsListModels / SystemOne / OfANamedProvider and
  TestHeldKeyToldItsOwnQuotas now encode the new rule (the held key is
  told only its own provider's quotas).

Run on mote: gofmt -l clean; go vet darwin, linux -tags nogui, windows
on access, cli, gateway, gui ok; go test -timeout 45m ./internal/access
./internal/cli ./internal/gui ./internal/gateway: ok except gui's
TestMainWindowCorners/macOS_26_SDK (#3949, not this change) and
gateway's TestHeldKeyToldItsOwnQuotas, updated and rerun ok. After the
rebase on 1f03d7546 the key tests ran again ok. GUI: gateway-key*,
i18n-keys, gui-de, gui-ja, gui-zh-tw in Chromium and WebKit: 131 pass.

Not tried: a plugin-served provider (same model gate), a real
account, Windows and Linux test runs (vet only).
2026-10-30 01:25:57 +08:00
yetone af8f3a9399 sessions: a new install reads no agent's session history until the user allows it (RustCats on X)
RustCats on X: a fresh magpie showed every agent's session history on
the Sessions page before anyone agreed to it, and asked for a per-agent
choice instead.

- sessions.Reads(agent) (internal/sessions/access.go) is the one gate,
  from settings.SessionReads {Asked, All, Agents}. Every lister asks it,
  the aggregators (allFiles, callFilesWith, callSourcesWith,
  traceLineFiles, wslFiles, DesktopDataDirs) filter by it again, and
  readers of an already-listed session (TranscriptOf, ContentOf,
  SearchSession, SubagentTranscript, CarryOver, ReadCallSource) return
  ErrNotRead, so a cache from before a switch was turned off goes no
  further. The Sessions list, stats, /api/sessions/overview, the call and
  trace indexes, Usage's agent-file calls and the Codex/Pi title readers
  all pass it.
- SettleReads decides once and saves: an install with sessions.json or
  a calls-v* cache read sessions before and keeps all on; a fresh one
  reads none, not asked. A saved value is never replaced; save, sync and
  restore keep it (KeepOwn); only SetSessionReads writes it. An
  unwritable settings.json reads nothing this run.
- GUI: GET/POST /api/sessions/reads. While not asked, the Sessions page
  shows a consent card: each agent found (by a stat of its folder only)
  with a switch, Allow selected and Allow all. Settings > Privacy >
  Agents' session history has "Agents found later" and a row per agent.
  Strings in en, zh, zh-TW, ja, de.
- CLI: magpie sessions read [on|off all|<agent>...]; magpie sessions
  says on stderr when nothing is allowed yet; the TUI's empty Sessions
  page says how.

Read either way, because none of it lists or shows a session: the
gateway's own usage ledger, its projections and the conversations it
recorded (magpie's own records, so usage and cost keep working); the
agents' config and sign-in files; Claude Code's and Codex's
history.jsonl last-used time and a session file's mtime for a quota's
first use; Codex's newest rollout's last line before magpie restarts
Codex (codexTurnOpen).

Tests: TestFreshInstallReadsNoAgentUntilAllowed,
TestSettleReadsKeepsWhatWasThere, TestSessionReadsRoutes,
TestSessionsRead, TestSessionsNotAskedSaysHow, sessions-reads.test.cjs
(26 cases: consent and Settings in 5 languages, Chromium and WebKit,
390 to 900 wide).

Run on mote:
- full Go suite (gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui,
  GOOS=windows go vet, go build, go test -timeout 45m ./...) at this
  change on 8c63c5b78: 79 packages ok; internal/gui red on
  TestSettingsSaveKeepsWhatItDoesNotSend (mine: SessionReads is written
  by SetSessionReads only, the test now sets it so; green after) and
  TestMainWindowCorners (the same on origin/main c1da9ccda, #3949).
- whole GUI suite (make test-ui, concurrency 2) at this change on
  8c63c5b78: 14985 tests, 276 failed in 44 files. Mine: i18n-keys
  (comments named "Allow all"/"Allow selected"; lowercased) and
  account-discovery (read the last Privacy heading; now the one above
  its list); both green after. The 44 files again on origin/main
  c1da9ccda: 36 red there too (#4304, with #3218, #3412, #3414, #3795,
  #4120, #4125). stays-strict green alone; gateway-key-models webkit red
  1 of 3 alone on main too; plugin-github de 440 red on main (#3218).
- at the pushed head (rebased on cd10dfbe6): go build ./...; go test
  internal/sessions, settings, cli, tui ok; internal/gui
  TestSettingsSave*, TestSessionReads*, TestSessions* ok; i18n-keys,
  account-discovery, sessions-reads: 62 pass, 0 fail.

Broken by hand:
- the aggregator filter off with the leaf gates on: green (the leaf
  gates hold); both off: TestFreshInstall red on List, Agents, Calls,
  CallSources, traces, stats, TranscriptOf and Search.
- consentApplies=false and Settings' old save({all}) without the rows:
  all 13 Chromium cases of sessions-reads red.
- sessNothing's hint removed: TestSessionsNotAskedSaysHow red.

Real binary in a sandbox HOME on mote (removed after): a fresh
`magpie sessions` is empty with the hint on stderr; `sessions read`
says not asked, claude off; `read --help` prints usage and saves
nothing; `read on claude` lists the one session; `read off all`
empties it again.

Not tried: the GUI and real app on Windows and Linux; WSL agents in the
consent list (WSL distros are not looked into; Allow all covers them);
a fresh install of a signed release build.
2026-10-29 23:56:05 +08:00
yetone fd5c631cbe image mcp: generate_image and generate_video take the model to use (XYenon)
XYenon on Discord asked whether an agent can pick the model magpie's
image/video MCP draws with. Both tools now take an optional `model`,
as provider/model:

- The schema lists the models that may be asked (the Settings default
  first, then each on provider's OfferedDrawers or Videomakers), only
  those the calling gateway key may use. Up to 40 of them form an enum;
  past that, the description names three.
- Left out, the Settings default is used, as before.
- A bare id only one provider has, a ChatGPT account's other GPT Image
  name (ListedDrawer), or a newer family model (drawsFamily,
  grokVideoFamily) is accepted. Anything else is a tool error naming the
  models the key may use, and nothing is drawn. It never falls back.
- The chosen model goes into the images/videos request's `model`, so
  the APIs' own key check (keyHolds, keyModelError, #882) refuses one
  the key may not use: the same check /v1/images makes.
- The stdio Magpie Image server copies the gateway's `model` property
  from its tools/list, and asks the hidden JSON-RPC method
  magpie/media_model which model a call means. An older gateway
  (-32601) passes the model through as named.
- `magpie tool generate_image --model ...` works through the schema;
  the usage text says so.

Docs: gateway-routing.md (image MCP section), reference.md.

Run (mote, via mote-run, at this tree):
- gofmt -l: clean.
- go vet ./... for darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/imagemcp/
  ./internal/cli/: ok.
Broken by hand: with `req["model"] = ref` dropped in imageMCPDraw and
imageMCPFilm, TestImageMCPDrawsWithTheModelAsked,
TestImageMCPModelHeldToTheKey and TestImageMCPVideoModelAsked go red
(the default was drawn instead); restored, they pass.
Not tried: a real vendor account. The fakes are easeled's art provider
and the fake Grok. GUI files not run: no GUI file changed.
2026-10-29 22:16:56 +08:00
yetone 3ce2a9819f library: RTK for agents in WSL, with the distro's own rtk (lex on Discord)
lex: Claude Code and other agents in WSL couldn't use the RTK of magpie
on Windows. rtkAgents looked an agent up in rtkSpecs by its whole id, so
claude@wsl:Ubuntu never matched and WSL agents weren't on the RTK page at
all. Even matched, the specs read this machine's home, and Windows' rtk.exe
is no command inside the distro, where the hook runs.

Now an agent is looked up by its kind (rtkKind). One in WSL:
- has its files read and written under the distro's home as magpie opens
  it (rtkClaudeDir, rtkCodexDir, rtkHome), with blocked/version checks
  against the distro's rtk and OpenCode;
- uses the distro's own rtk: rtkDistroOf asks the distro (wsl.exe -d <d>
  -e sh -lc) where rtk is on its shells' PATH, else in ~/.local/bin or
  ~/.cargo/bin (offPath), kept 15s; ReadRTK lists one RTKDistro per distro;
- switching on runs that rtk there (rtk init -g ..., its folder on PATH);
- Install RTK in WSL <distro> (POST /api/library/rtk/install {distro},
  magpie library rtk install <distro>) runs RTK's own Linux installer in
  the distro (curl, or wget).
A distro that isn't running is never started (#3896): its agents are
listed asleep with the switch off, and switching or installing says to
start it. The page has a card per distro (install, off-PATH, asleep) and
uses the distro's rtk for each WSL row's tags and switch; strings in zh,
zh-TW, ja and de. The install route now refuses a body it can't read
instead of installing on this computer.

Run:
- mote (macOS 27), at origin/main ec8fe29b8 plus this: gofmt -l clean;
  go vet darwin, GOOS=linux -tags nogui, GOOS=windows for internal/library,
  internal/gui, internal/cli: ok. go test ./internal/library ./internal/cli
  ok; ./internal/gui: TestMainWindowCorners/macOS_26_SDK red (#3949, open,
  mote's macOS 27), everything else ok; -run Library ok after the route
  change. node --test library-*.test.cjs + i18n-keys in Chromium and WebKit:
  828 tests, 3 red, all library-row-remove (#3099, open; 1 of 2 runs alone
  is red the same); library-rtk-*.test.cjs + i18n-keys at the pushed base:
  180 pass. New library-rtk-wsl.test.cjs: en, zh, zh-TW, ja, de at 980 and
  380px, both engines.
- New TestRTKWSL / TestRTKWSLAsleep (fake wsl.exe runs the real probe
  script with sh, the distro's home as HOME). Broken by hand: the old
  rtkSpecs[a.ID] lookup makes TestRTKWSL red (claude@wsl not on the page).
  Also ok on Windows (win-run) and Linux (wsl-run), -run 'RTK|WSL'.
- Real WSL, xiaomi-gpu with magpie-desktop (Ubuntu 24.04): from Windows,
  through real wsl.exe and the exact rtkWSLScript/rtkWSLProbe/rtkInitWSL
  strings, with HOME set to a throwaway folder in the distro: RTK's
  installer put rtk 1.1.0 in ~/.local/bin, the probe found it (on:0, not
  on that bare PATH), rtk init -g --auto-patch wrote "rtk hook claude" into
  ~/.claude/settings.json, and sp.has read it back over
  \\wsl.localhost\magpie-desktop\.... ReadRTK on Windows lists
  claude@wsl, codex@wsl and pi@wsl:magpie-desktop with an install offered.

Not tried: a real Claude Code session in WSL running a command through
the hook; the install and switch in the distro's real home (only the
throwaway HOME); the real GUI window on Windows; OpenCode, Gemini, agy,
Hermes, OMP in WSL (same code path, not run for real).
2026-10-29 19:58:40 +08:00
yetone c1da9ccda3 library: a stopped WSL distro's agents are listed, and a tick for one is written there once it runs (cybercaius on Discord)
cybercaius: with WSL not started, the Library's MCP page didn't list the
agents in the distro at all, and nothing ticked for them could be kept.
A stopped distro's agents are no targets (#3896: opening their files
starts the distro), so they fell off the page.

While a distro runs, each agent's places and what its MCP file takes are
kept in wsl.json (keepShape, agent.WSLKeep, key library:<kind>). While it
is stopped, Read lists its agents from that (asleepView, asleep: <distro>)
with the library's ticks; one magpie never saw is listed only on rows that
name it, as unseen, its chip disabled and kept by every click (keptOf). A
tick on a stopped agent is kept in library.json (Takes accepts a known
shape, serversAgents judges it by shape.reaches); nothing is opened or run
in the distro. Woken, from KeepLinked's 30s loop, syncs once a distro the
library names goes from stopped to running (wsl.exe -l --running starts
nothing). The page greys a stopped agent's chip and says why in its
tooltip and one line per distro; the MCP hub leaves them out. The CLI says
the same on stderr (AsleepIn). en, zh, zh-TW, ja, de.

Run at this tree (20695ad8b before this message; on adc618bbf):
- mote: gofmt -l clean; go vet -tags nogui for darwin, GOOS=windows and
  GOOS=linux on internal/library, internal/agent, internal/cli; go test
  -tags nogui -timeout 45m ./internal/library ./internal/agent
  ./internal/cli: ok (internal/gui ok too at the 96a703a59 base).
- WSL magpie-desktop: library-wsl-asleep, i18n-keys, library-gone-agents,
  library-items and library-mcp-hub, Chromium and WebKit: 88/88. At the
  96a703a59 base every library-*, mcp-*, skill-* file and i18n-keys:
  1148 of 1164; the reds were library-chip-fan (WebKit),
  library-mcp-tools (chromium ja 420), library-items and
  skill-group-shared (WebKit) beside another session's full GUI suite.
  Alone, library-items and skill-group-shared pass, and chip-fan and
  mcp-tools are red the same on an origin/main 96a703a59 copy (#4120,
  commented).

Broken by hand: asleepView returning nothing made TestWSLStoppedListedAndQueued
("a stopped distro's Codex isn't listed") and TestWSLStoppedUnseen red;
Woken never syncing made TestWSLStoppedListedAndQueued red ("no sync once
the distro ran"); keptOf without unseen made library-wsl-asleep red in
all 10 Chromium cases (Pi's tick dropped by a click on Claude Code).

Rebased onto fa2332976 (gateway, provider and Codex effort commits, nothing
in internal/library, internal/agent/wsl or the Library page) before the
push: go vet of the three packages and go test -run TestWSL
./internal/library ok there; the full packages ran at adc618bbf.

Not tried: a real distro stopped and started. magpie-desktop was running
another session's full GUI suite, which stopping it would have killed, and
the other distros are other people's. The tests use FakeWSL, which counts
every wsl.exe -d command run in the stopped distro (none). Not changed:
the Instructions, Hooks and Subagents pages still leave a stopped
distro's agents out (#4182, #4237, #4238).
2026-10-29 18:34:44 +08:00
yetone 96a703a591 uninstall: magpie uninstall and Settings › Uninstall magpie put every agent back before magpie's files go
Jevik_AI on X (Windows, portable magpie) deleted magpie's folders by hand.
~/.codex/config.toml kept openai_base_url on 127.0.0.1:3425, and every
Codex turn then failed with a 502, with nothing left that knew why.
Deleting magpie's files never puts an agent back, so there is now an
uninstall that does.

- internal/uninstall: Run goes in this order. System removes the
  background service, opening at login, the Start menu shortcut
  (shortcut.Remove, with its App Paths key), the magpie:// links and the
  privacy model's helper. Agents ends Codex's account failover, then runs
  each connected agent's own Disconnect, or its offline disconnect for an
  app that is closed. That is the same code as the Agents page, so a value
  the user changed by hand since Connect stays theirs (e7f21dba5 for
  Codex). It then ports Codex's rollouts and restarts the Codex app's
  app-server (provider.RestartCodexAppWhenIdle, which says whether one was left on
  the old config). Data deletes magpie's folders, but keeps the Library's
  folder while it holds skills, servers or hooks the user's agents use.
  The executable is left where the user put it.
- `magpie uninstall [--yes]`: refuses while another magpie runs, and
  says which one. On a terminal it lists what goes and asks [y/N]; with
  no terminal, only --yes does it.
- Settings › About › Uninstall magpie: POST /api/uninstall runs System
  and Agents. If anything failed, nothing else is removed and the sheet
  offers Try again. Otherwise POST /api/uninstall/finish starts a
  detached `magpie uninstall --data-after <pid>` (Setsid on unix,
  DETACHED_PROCESS on Windows) and the app quits; the files go once it
  has ended, since WebView2 holds its folder open until then. A Codex app
  still on the old config is named before quitting. magpie web refuses
  both routes. Strings go through t() in all five languages.
- --data-after refuses a pid that is no process (0, negative, its own):
  kill(0) counts as alive, and a run given 0 waited out its 2 minutes.

Not done, and why:
- No restore on quit. Quitting keeps agents on magpie by design: the
  service or the next start serves them.
- No Apps & Features entry or Windows uninstall hook. A portable copy
  registers nothing with Windows, and an uninstaller that ran without
  magpie's own disconnect would leave the configs as they are. The
  `# magpie:` note above each line magpie writes (previous commit) is the
  recovery path for a copy deleted by hand.

Run at this head (db75663a0's tree, on 5d24bc6cc), on mote:
- gofmt -l clean; go vet ./... on darwin (-tags nogui), GOOS=windows and
  GOOS=linux -tags nogui: ok.
- go test -tags nogui -count=1 -timeout 45m on ., internal/uninstall,
  cli, gui (TestCoreScriptBudget included), provider, shortcut, edit,
  agent and proc: all ok.
- GUI at this head: mote was at load 100-120 with other sessions' GUI
  runs. Chromium crashed (SIGBUS) mid-file in settings-search and
  settings-sections after their en cases passed, WebKit failed to launch
  within 180s in s3-sync, settings-search and settings-sections, and
  fonts and title-bar-tools went red on unstable elements (#2984 has
  fonts under load). uninstall-settings had not reported when this was
  pushed.
- At the earlier base b3580c72c, on this machine: the full suite
  (-timeout 45m), red only on #3884, #3632 (both since fixed on main) and
  the core budget, which main's later move of Web search out (#4133) has
  room for now. GUI: 104 Settings and i18n files in chromium and webkit,
  uninstall-settings and i18n-keys green in both; the reds were #3797,
  #3876 and the load reds above.

Tried for real, in a sandbox HOME: `magpie uninstall` end to end with
Codex connected and a sandbox Codex app running (config.toml back
without magpie's lines, magpie's data gone, the exe kept, the app's
app-server restarted onto the restored config); codex-cli 0.162.1
reading the noted config.toml. Other agents were covered by tests only.
Not tried: the GUI's Uninstall in a real app window, a real
--data-after run waiting on a live app's pid, and the Windows box.

Broken by hand: --data-after's pid guard removed ->
TestUninstallDataAfterNeedsAProcess red (0, -1 and its own pid
accepted); restored, green.

At the pushed head (rebased on 51f66fe8b; the uninstall call adapted to
EndCodexFailover's (bool, error) on the way), on mote:
- gofmt clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok;
  go build ./... ok.
- go test -timeout 45m: internal/uninstall, edit, shortcut, cli, agent,
  provider ok; internal/gui red only on TestMainWindowCorners/macOS_26_SDK
  (#3949, macOS 27).
- GUI: uninstall-settings and i18n-keys, 30 pass 0 fail.
- WSL (magpie-desktop, CGO_ENABLED=0): uninstall, edit, shortcut,
  provider ok; agent red on TestGrokInstalled, TestOmpDetectedWithPiDir,
  TestZedAppPath, the same at origin/main 51f66fe8b (#4033, #3548).
2026-10-29 17:47:30 +08:00