Commit Graph
62 Commits
Author SHA1 Message Date
yetone c056b7c8c3 provider: a Responses provider's turns may go over the Responses WebSocket (#5781)
A provider the user added with an http(s) Responses address can now send
its Responses turns over the Responses WebSocket that magpie already
speaks to chatgpt.com (codexSocket), with `socket=auto|on|off`:

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

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

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

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

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

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

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

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

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

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

Reported-by: 9won_25273 (Discord)
2026-11-09 18:19:02 +08:00
yetone b0926e81a2 import: a link can say where its key's balance is read (balance=, balance_path=, balance_method=)
A relay's "Add to magpie" link can now name the URL that tells a key its
balance, where the amount sits in the reply, and GET or POST. magpie
takes it only on the host of one of the link's own base URLs, over
https, with no userinfo or fragment, so a link can't send the key
anywhere its requests don't already go; anything else refuses the whole
link. balance_path or balance_method without balance is an error. No
header or token is taken from a link: an account-wide token is worth
more than a key, and a URL stays in browser history.

- provider.ParseImport: linkBalance checks and sets BalanceURL,
  BalancePath and BalanceMethod.
- CLI: the import preview shows the balance URL and doesn't ask it
  before yes (showProviderAsking).
- GUI: the import dialog shows method, URL and field (.imp-bal).
- Docs: docs/import in en, zh and ja (table rows, a note on headers,
  the builder's three fields with the same host check, a security
  bullet); docs/reference.md's parameter table.

Run on mote at this tree (rebased on 8fa3c60f8):
- go test -count=1 ./internal/provider ./internal/gui: ok
  (TestParseImportBalance, TestCoreScriptBudget in it).
- go test ./internal/cli: ok but TestEveryRouteHasACommandOrIsNamed,
  red on main since f418edffc (GET /api/context/session); fixed in the
  next commit, and ok there with -run 'TestEveryRoute…|Import'
  (TestImportPreviewAsksNoBalance).
- GUI import-link-balance, import-link-gemini, i18n-keys: 43/44. The
  red is i18n-keys "a plugin's words are its own", the same three
  strings on an origin/main 8fa3c60f8 copy (#5327, #5426, #5482).
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of provider,
  cli, gui: ok. gofmt -l: clean.

Not tried: a real link with balance= imported into the app and read
against a real relay's balance endpoint.
2026-11-08 18:37:41 +08:00
yetone 37df73b1bb balance: a key holds several credits that expire, each added and removed on its own
tenacious_eagle_96548 (Discord, 11-08) has two promotional credits on one
key, one ending tomorrow and one the day after. v0.1.3305 kept one grant
per key, and its form showed the date only after Enter or a blur, with no
button to confirm.

- OwnBalance.Expiring is now a list (`expirings`, up to 20). Spending
  goes to the grant that ends soonest first (ties by when it was typed),
  and each grant drops out at its day. A write prunes ended grants.
- The pill and the menu say "Expires in N days" per grant, amber from 7
  days. The menu has a Remove item per grant, "Add credit that
  expires…" and "No credit that expires" to clear them all.
- The form shows the amount and the last day together, the day filled in
  30 days ahead, with an Add button; Enter adds, Escape cancels, a bad
  amount or a past day is refused in place. The app's own menu, no
  native select, no stripes. A pill with two or more grants wraps at a
  grant on a narrow row (a class, not :has(), for Safari before 15.4).
- CLI: `--expiring amount@day` can be given several times, `--expiring
  off` clears all, `--expiring-remove [amount@]day` removes one. --help
  prints usage; a day that isn't a date, or is past, is refused.
- /api/provider/keyexpiring adds `{expiring:{amount,until}}`, removes
  `{expiring:{at,until},remove:true}`, clears `{expiring:null}`.

Old data: a v0.1.3305 single `expiring` grant is read as the first grant
and saved as `expirings` on the next write, for every user. An older
magpie reading the new file sees no grants (the balance itself stays).

Run on mote at 1d5b5dc2d plus this change:
- go test -run 'Budget|Balance|Expir|KeyOwn' ./internal/gui
  ./internal/provider ./internal/cli: ok (TestCoreScriptBudget passes,
  not raised). gofmt -l clean. GOOS=linux go vet -tags nogui and
  GOOS=windows go vet on provider, cli, gui: ok.
- GUI (Chromium + WebKit, 900/400px, en zh zh-TW ja de):
  key-balance-expiring, key-own-balance, key-balance-card,
  key-row-steady, key-row-chips-fit, account-rows-fit, old-webkit,
  i18n-en-no-cjk, balance-parts, balance-quota-left: 203/203. A broader
  run (key-*, balance-*, i18n-keys, panel-balance-order) had reds that
  are red on origin/main 04ed05733 too: i18n-keys "a plugin's words are
  its own" (#5332, #5482, #5426) and key-replace WebKit 420px (#4126).
- Real app on mote, sandbox HOME, `serve --web`: the CLI set ¥40 plus
  ¥5 to tomorrow and ¥8 to the day after and printed about ¥53.00 left;
  providers.json has `expirings`. --help, `5@yesterday` and removing a
  credit the key doesn't have each answered as above. In Chromium (en)
  and WebKit (zh) at 900 and 400px: the pill, the menu, the form (day
  2026-12-07), Add ¥3 by Enter, then Remove ¥3 from the menu, each
  checked by text and screenshot.

After a rebase on 437580535, on mote: the same go test
-run (TestCoreScriptBudget included): ok; key-balance-expiring,
old-webkit, key-own-balance: 46/46. Rebased again on 8f6298fb5 (Go
only, no asset changed): the go test -run plus Signin: ok.

Broken by hand, each went red: sorting grants by when typed
(TestTypedBalanceGrantsSoonestFirst); no migration in UnmarshalJSON
(TestTypedBalanceOneGrantMigrated); no Enter handler (GUI en 900); no
wrap rule (GUI en 400, row past the window's edge); Remove sending the
first grant (GUI, at/until mismatch).

Not tried: Full suite: not run at push. No real vendor account (the
grants are typed by the user). The Linux and Windows desktop apps.

Reported-by: tenacious_eagle_96548 (Discord)
2026-11-08 15:27:14 +08:00
yetone c736906b17 providers: part of a key's typed balance may expire on a day
tenacious_eagle_96548 (Discord, #general): some vendors split a balance
into money that stays and credit good until a date. A key's balance typed
by hand can now carry that part (`expiring`: {amount, until, at}, in the
balance's currency, until = the last day it counts).

- Spending order: the expiring part is spent first, as DeepSeek spends
  its granted balance before money topped up. It takes the spend from its
  `at` up to its end (midnight after `until`, local time) or now; only
  what it took after `From` comes off the rest, so a refill or typing the
  balance again doesn't count it twice.
- Left is the whole balance. From its end the remainder counts no more,
  and unspent credit is gone.
- Typing the balance again keeps the part in the same currency and drops
  it in the other, where its amount would mean another sum.
- A balance saved before has no part and reads exactly as it did
  (TestTypedBalanceSavedBeforeExpiring).
- Set from the pill's menu: "Credit that expires…" asks the amount, then
  the last day (a day gone by, or the other currency's sign, refused);
  "No credit that expires" takes it off. GUI route provider/keyexpiring;
  CLI `magpie provider key-balance <id> <key> --expiring amount@yyyy-mm-dd|off`.
- Shown: the pill "≈$100.00 left · $30.00 expires in 30 days", the Usage
  page and panel line "Expires in 30 days ≈$30.00", amber from 7 days;
  TUI and `magpie quota` "($30.00 until Dec 7)". New strings in zh,
  zh-TW, ja and de.

Run (mote):
- go test of internal/provider, internal/gui, internal/cli (with
  TestCoreScriptBudget: the days' lines in app.js are paid for by five
  balance comments cut there, no raise; core 1,533,559 of 1,533,802); the new tests
  again with TZ=UTC and TZ=Pacific/Kiritimati (every clock held);
  gofmt -l clean; GOOS=linux and GOOS=windows go vet of those packages.
- GUI: key-balance-expiring.test.cjs 20/20 (chromium and webkit, 400px,
  en/zh/zh-TW/ja/de), with every balance-*, key-*, i18n-* file: 768
  pass, 6 red, each red the same alone on origin/main 691a10446:
  i18n-keys "a plugin's words are its own" (#5327) and key-replace's
  five webkit 420px cases (#4126, numbers added there).
- A real sandbox (own HOME, -tags nogui binary, ports 3591/3592): set
  $70 + $30 until +30d and ¥40 + ¥5 for +3d through the CLI, then
  through the pill's menu in the real page (¥8 for +6d, then removed);
  a past date shows the part no longer counting; retyping in USD dropped
  the CNY part; `magpie quota` shows the split. No page errors.

Broken by hand, each red:
- Go (TestTypedBalanceExpires): part not spent first; end taken in UTC
  (red under Kiritimati); part kept after its end; part kept across a
  currency change.
- GUI (key-balance-expiring): no soon class; soon only from 2 days; a
  past day accepted; the other currency's sign accepted.

Not tried: a real vendor's spend priced against the part; the GUI on
Windows or Linux. The full Go and GUI suites were queued on mote's
suite lock behind other sessions' and had not run when this was pushed.

Reported-by: tenacious_eagle_96548
2026-11-08 13:39:32 +08:00
yetone ae58ec9b44 providers: a key's provider can have its model list off
axelburks on Discord: Ark's pay-as-you-go list names models that can't
be asked for, and each one is asked by an endpoint id the user made. A
key's provider can now have its list off (Provider.ListOff): nothing
asks its vendor for a list (Fetch, Refetch, List, RefreshLists, a test,
a new key's prefill, a resting key's probe), a list fetched before and
models.dev's are not read, and only the ids added by hand are served.
The editor shows it as "Fetch the model list", ticked by default;
unticked, Fetch models and Forget go. A save that doesn't name listOff
keeps it. CLI: `magpie provider set <id> list=off`. Accounts and plugins
list as their sign-in does, so they don't take it.

Broken by hand: ListAsks returning false for a list-off provider turns
TestListOffAsksNoListAndServesTheIDsAdded red; dropping the keep in the
save turns TestProviderSaveListOff red.

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

Not tried: a real Ark account; the switch was checked against fake
vendors only.

Reported-by: axelburks (Discord)
2026-11-08 11:28:54 +08:00
yetone 0fc3455e2a providers: a key's typed balance may be in yuan and refill each month or week
tenacious_eagle_96548 asked, after v0.1.3281's typed balance, to type it
in RMB and to have it refill (e.g. $10 a month, on the 1st).

- A balance may be typed in yuan ("¥100", "100元", or a bare number while
  Settings shows costs in CNY). What magpie counts spent stays in USD and
  is turned into yuan at fx.Known(): the rate internal/fx last fetched
  (cached 12h, fetched again in the background, never on a request).
  fx.Known never returns fx.Fallback, so with no rate fetched and
  something spent, what is left is unknown (left null; the card says
  why), not a guess.
- An optional refill: monthly on day 1-31 (past a month's end, its last
  day) or weekly on a weekday, at midnight in the user's local time.
  Nothing is stored on a refill: the spend counts from the last boundary
  after the balance was typed. Typing the amount again keeps the refill.
- GUI: the pill's menu gains Refills each month… (a day, in place),
  Refills each week… (the app's menu of weekdays) and Never refills;
  provider/keybalancerefill; keyownbalance takes currency cny. CLI:
  magpie provider key-balance <id> <key> [usd|¥cny|off]
  [--refill monthly[:day]|weekly[:mon…sun]|off]. Strings in zh, zh-TW,
  ja, de. docs/subsystems/providers-accounts.md updated.

Run on mote at this tree (base origin/main 350599a0f):
- go test -tags nogui -count=1 -timeout 45m ./internal/fx ./internal/provider
  ./internal/cli ./internal/gui ./internal/usage: all ok (suite lock).
- GOOS=linux go vet -tags nogui ./... ok; GOOS=windows go vet ./... ok;
  gofmt -l clean.
- key-own-balance.test.cjs 20/20 (chromium + webkit, en zh zh-TW ja de,
  900 and 400px): yuan typed posts currency cny, monthly day (40
  refused), weekly Friday, never. i18n-keys, i18n-en-no-cjk, old-webkit ok.
- Broken by hand, each red: Known returning Fallback
  (TestKnownIsNeverAGuess); refill days taken in UTC
  (TestTypedBalanceRefills, TestRefillDays); refill dropped on retype
  (TestTypedBalanceRefills).
- Full GUI suite still running at push: 3502 ok, 6 red so far, none in a
  file this touches: webkit By weight; webkit de 1100/420 Codex resets
  used by themselves; chromium en named caller keys; chromium zh-TW 420
  a key's several limits; webkit en gateway key held to its models.
  They are run on origin/main next and filed if red there.

Not tried: a live rate fetch (tests stay offline), the real app window,
WebKitGTK.

Reported-by: tenacious_eagle_96548 (Discord)
2026-11-08 09:03:00 +08:00
yetone d32a7a70cb remote magpie: once magpie updates, the Remote magpies it uses update too
nnlrl_75403 on Discord: a magpie used as another's Remote magpie stayed on
its old version after the local one updated, and had to be updated by
hand on the other computer. Now nothing needs setting up:

- provider.KeepRemotesUpdated (started by the app's updater and by
  magpie serve) runs UpdateRemotes 30 s after start and hourly. A
  released build with automatic updates on reads each Remote magpie's
  version (GET /v1) and, when it is older, asks it through
  POST /v1/magpie/update?version=<v> with the provider's key, at most
  once in six hours per version. Off here, or a dev build: nothing asked.
- The remote updates as its own automatic update would: the app
  downloads and restarts once idle (updater.updateAsked → download,
  waitIdle); magpie serve puts the latest in where it runs from, one at
  a time, never elevated, and serveFollow restarts into it. Automatic
  updates or downloads off there: it answers "off" and stays.
- A copy that can't replace itself says why: a container (docker pull
  ghcr.io/yetone/magpie:latest), a package manager's (its command), a
  folder it can't write, a build from source. A magpie from before the
  route answers 404 ("too old"), a read-only or held key is "refused".
  The provider's row on the Providers page adds a short status to its
  line ("updating to v…" for 30 min, or "can't update itself" etc.),
  with the reason and the command in its tooltip. en/zh/zh-TW/ja/de.
- The route replaces the program, so it takes the Codex reset's
  admission: another machine only while shared, never a browser page,
  an enabled key with full access from loopback too (401 without one),
  read-only 403 gateway_key_read_only, held 403 gateway_key_held. It is
  in readOnlyRefused and the CORS route list.

App.js stays under TestCoreScriptBudget by cutting two comments; the
budget is not raised.

Run (on mote, at the tree committed here):
- gofmt -l internal/: clean. go vet of gateway, gui, cli, provider for
  darwin, GOOS=linux and GOOS=windows: ok.
- go test -count=1 ./internal/gui ./internal/cli ./internal/provider
  ./internal/gateway: gui and cli ok but for #5644's two settings tests
  (red on main since 6b7ee4a98, owned); provider and gateway were
  still running at the push, and go in the full run after it.
- Rebased on origin/main c7c05dcf2, again: gofmt, vet, the new tests,
  ReadOnlyKeyEveryRoute, CORS, TestCoreScriptBudget (not raised) and
  both GUI files 32 of 32: ok.
- New: TestRemoteUpdateNeedsAFullKey (no key from loopback, Origin null,
  an app scheme, *.localhost, a rebound Host, a foreign page with and
  without the full key, another machine with none or a wrong key,
  read-only and held keys, then not shared; the updater is never
  called until a full key asks, from LAN and loopback),
  TestRemoteMagpieAskedToFollow (UpdateRemotes against a real gateway:
  dev build, same and newer remote, NoAutoUpdate here, asked once per
  version, container answer kept, read-only key refused, a 404 magpie
  "old"), TestUpdateAskedByAnotherMagpie, TestRemoteUpdateNote,
  TestServeUpdateAsked.
- GUI: remote-update.test.cjs (new) and remote-self.test.cjs, Chromium
  and WebKit, 1100 and 420 wide, en/zh/ja/de: 32 of 32 ok, with every
  key checked in zh, zh-TW, ja and de. i18n-en-no-cjk ok. i18n-keys'
  "a plugin's words are its own" is red, the same on origin/main
  f8525323d (#5327/#5332, #5426, #5482); its other cases ok.

Broken by hand, each red, then put back: the handler's key check
(loopback without a key got 200 updating), its held-key check, the
route itself (404 = the old code), asking a remote that is current,
ignoring NoAutoUpdate here, asking again for the same version, the
app ignoring automatic updates off, the app never waiting to restart,
serve's single flight (2 downloads), serve's container answer.
The handler's own Origin and not-shared checks stay green when removed:
corsGuard and lanGuard refuse those first; they are kept as the Codex
reset keeps them.

Not tried: a real update of a real remote (a Docker magpie and an app
on another Mac) end to end; Windows and Linux runs of the new tests
(vet only); the full suite (run after the push).

Reported-by: nnlrl_75403
2026-11-08 03:13:15 +08:00
yetone f8525323dd providers: a key with no balance URL takes a balance typed by hand, counted down by magpie's own usage
Some API-key providers tell no balance magpie can read (no Balance URL,
no relay query found), so their keys showed none. Now the user types what
the vendor's page says is left, on the key's row in the provider editor
(Set balance) or with `magpie provider key-balance <id> [key [usd|off]]`.
The key's card shows that less what magpie's usage priced the calls it
sent on the key since it was typed (usage.KeySpent, the spend caps'
count), marked as an estimate: "≈$12.50", the pill "≈$12.50 left", its
title saying what was typed, when, and what was counted since. Typing it
again counts from then; No balance takes it off.

A balance the vendor tells always wins: a provider with a Balance URL, a
plan source, Cline's or OpenCode Zen's card takes none typed, and a relay
whose query is found shows its own; when the probe finds none
(errNoBalance) the typed one is shown. A typed balance stays saved as the
user left it: the editor's save keeps it, a key's replaced value carries
it. An estimate is never kept in the balance history and tells routing
nothing (the routing allowances cache is left alone).

keybalance.js is loaded by keyspend.js (itself loaded when the editor
draws a key) for a provider that takes one, so app.js and the core's
script budget are unchanged. Words in zh, zh-TW, ja and de.

Run at this tree (mote):
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... at base 46b10af87; at this tree go vet of
  gui, provider, cli and usage;
- go test -tags nogui -count=1 ./internal/gui ./internal/provider
  ./internal/cli ./internal/usage: provider and usage ok; gui and cli
  red only on #5644 below; TestCoreScriptBudget ok (1,533,747, as main)
- the provider tests under -race -count=3;
- GUI: key-own-balance (new: Chromium and WebKit, en zh zh-TW ja de,
  900 and 400px, 20/20), key-spend-cap, old-webkit, i18n-keys, gui-de,
  gui-ja, gui-zh-tw, balance-found, key-balance-card, i18n-en-no-cjk:
  104 pass, 1 fail, i18n-keys "a plugin's words are its own", red the
  same on origin/main 7a2946caf (#5327, #5332, #5482, #5426).

Broken by hand, each went red:
- estimates kept in the balance history: TestTypedBalanceCountsDown;
- no fallback to the typed balance on errNoBalance:
  TestToldBalanceWinsOverTyped;
- the editor's save dropping KeyOwnBalances: TestKeyOwnBalanceRoutes.

Red on main, not this change: TestSettingsSaveKeepsWhatItDoesNotSend
and TestSettingsCLISetsWhatTheWindowSaves (groupSink, groupFirstToken,
groupPatience from 6b7ee4a98), filed as #5644.

Not tried: a real relay account with no balance URL (the cost counted is
magpie's own estimate, so a vendor pricing differently drifts until the
balance is typed again); the full Go and GUI suites before the push (run
after it, under the suite lock); the GUI in the real Windows and Linux
apps; routing does not use the estimate.

Reported-by: tenacious_eagle (Discord)
2026-11-08 02:54:25 +08:00
yetone abe7b00631 gateway: a key+URL provider is sent the agent's own User-Agent by default, through a remote magpie too
nb5p runs a gateway of their own behind magpie and saw nearly every
request arrive as "magpie/<version>". The agent's User-Agent now goes
on as the agent sent it, wherever magpie isn't itself the client.

What each path sends now:
- Key+URL providers (official vendor keys and custom OpenAI/Anthropic
  compatible ones), on chat, Anthropic, Responses, Gemini,
  count_tokens, embeddings, images and videos: the agent's User-Agent,
  as sent. Before, this was the opt-in passUserAgent (#1851) and the
  default was magpie's. The opt-out is magpieUserAgent:
  `magpie provider set <id> user-agent=magpie`, or untick "Send the
  agent's own User-Agent" in the editor. passUserAgent is no longer a
  field, so a file that set it true reads the same as the new default.
  A provider someone turned back off after opting in can't be told
  apart from one never touched, and now sends the agent's too.
- When the agent sent no User-Agent, and on magpie's own requests
  (classifier magpie-router/1, vision, search, the image tool, model
  lists): magpie's, unchanged.
- A header.User-Agent the user set: still wins over both.
- Subscription accounts (Claude, Codex, Copilot, Google, ZCode…),
  plugins, and OpenCode/Cline/Kilo: unchanged. Their signing sets the
  official client's UA (provider.PassesUserAgent still refuses an
  Account or OwnClient).
- Claude Code and Codex header copies: unchanged.
- Remote magpie: the near magpie still asks as magpie/<v>, because the
  far end trusts X-Magpie-Agent/Via only from that. It now adds
  X-Magpie-User-Agent (passOnUA, on forwardOnce, embeddings, draw and
  video; the classifier's decision request names none). The far end
  takes it only from a magpie/ request (callerFrom) and strips it on
  arrival (withCaller). agentUA/callerUA then hand it to userAgentFor,
  so the far vendor sees the agent's. A client that writes the header
  itself, straight to a magpie, is ignored. magpie's own UAs are never
  relayed (magpiesOwn).

Vendor check: invalid-key requests with magpie/, claude-cli, a Chrome
UA and pi's went to Anthropic, OpenAI, Gemini, DeepSeek, Moonshot, Kimi
For Coding, Zhipu, OpenRouter, xAI, DashScope, MiniMax, Volcengine Ark,
Groq and Mistral. Every vendor gave the same auth error for every UA,
so no edge-level UA gating was seen. Kimi For Coding's agent allow-list
sits behind a valid key, which wasn't tried.

Run (mote):
- go test -run 'UserAgent|RemoteMagpie|ZCode|Blocked' ./internal/gateway: ok
- go test ./internal/provider ./internal/cli ./internal/gui: ok
- node --test provider-user-agent, provider-native-compaction and
  i18n-keys (chromium and webkit; en/zh/zh-TW/ja/de; 900 and 440 wide):
  123 of 124 pass. The red is i18n-keys "a plugin's words are its own"
  (plugins' words said in files this change doesn't touch), already
  filed as #5327/#5332, #5426 and #5482.
- gofmt -l clean; go vet; GOOS=linux -tags nogui and GOOS=windows vet:
  ok at the rebased head (on f13d5f16f). Targeted gateway, provider,
  cli and gui packages (UserAgent|RemoteMagpie|ZCode|Blocked|Budget)
  ok there too; whole packages ran at the pre-rebase base 4461957b9.

Broken by hand:
- PassesUserAgent back to opt-in: TestUserAgentPassedOn/default,
  TestUserAgentFor, TestRemoteMagpieRelaysUserAgent, TestPassesUserAgent
  and TestProviderUserAgentPair go red.
- agentUA's relay off, or passOnUA a no-op: TestRemoteMagpieRelaysUserAgent
  goes red; the far vendor is asked as magpie/dev.
- withCaller's Del(X-Magpie-User-Agent) removed: stays green. Nothing
  copies incoming headers to a vendor today, so the Del only guards
  against that.

Not tried: a real remote magpie on two machines, a real valid-key vendor
request, and nb5p's own gateway.

Reported-by: nb5p on Discord
2026-11-07 17:44:31 +08:00
yetone 8cbaeecae9 providers: errors=pass sends a vendor's error to the agent as it came, asked once
ne9ko9 on Discord wants errors handled explicitly, not by inference, and
a mode that passes them straight through. A custom or API-key provider
(no account, an endpoint of its own, not a subscription) now takes
`passErrors` in its config: "magpie handles" (the default, unchanged) or
"Pass through". Nothing sets it but the user, and an edit that doesn't
send it keeps the saved value.

With it on, for that provider:
- no rewriting: on the client's own API, upstream's status,
  Content-Type and bytes go out (passError); on another API, the
  client's shape is built with the vendor's own type, message and raw
  code and param (a numeric code stays a number). Retry-After and
  *ratelimit* headers go with it;
- no too-long inference, no busy words, no 413 hint, no policy
  rewording (settle never runs: the try is passing);
- no gateway retry: forward()'s Retries loop, refit, firstWait, the
  loop's re-asks, reloop, empties retry and streamTranslated's
  cont.again all stop;
- no fallback and no rest: the candidate loop's one choke point,
  newHoldWriter(…, !pass && …), lets the try pass, so nothing after it
  is tried, and restAfterMarked answers By "off".
magpie's own file-id re-ask (dsRetryGone) still runs, as it fixes
magpie's own upload, not the vendor's answer.

CLI: `magpie provider set <id> errors=pass|magpie`; a bad value is
refused and keeps the old one; an account is refused. `provider show`
says "errors pass".
GUI: Edit → Advanced → Errors, a quiet app-menu picker (openProtoMenu,
no native select) with "magpie handles" and "Pass through", shown only
where takesPassErrors; zh, zh-TW, ja, de. It is drawn by passerrors.js,
imported when the editor draws the row (old-webkit's lazy list names
it), and app.js pays for its few lines by two comments cut, so app.js
is smaller than before and TestCoreScriptBudget's numbers are unchanged.

Tests:
- internal/gateway/pass_errors_test.go: TestPassErrorsAskedOnce (503,
  429, 404 with numeric codes, alone and as a group's first member:
  exact bytes and status, asked once, the second member never asked,
  no rest), TestPassErrorsNotInferred (a too-long 400 byte-for-byte),
  TestPassErrorsOtherAPI (Anthropic 403 code 20031 to a Chat client,
  streamed and not).
- internal/provider/pass_errors_test.go, internal/cli/errors_cli_test.go.
- internal/gui/tests/provider-pass-errors.test.cjs: every language,
  1100 and 420 wide, Chromium and WebKit.

Run, through mote-run at this commit:
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider
  ./internal/cli ./internal/gui (at the parent 19c45d5d4's tree): gateway,
  provider, cli ok; gui red only in TestMainWindowCorners/macOS_26_SDK,
  mote's macOS 27 (#3949). TestCoreScriptBudget ok.
- Rebased on 2f660ca86: go vet of the four packages, the PassErrors,
  Budget, SameAPI and Errors tests and provider-pass-errors (60/60)
  again at this commit: ok.
- GUI on mote: provider-pass-errors 60/60 (both engines), old-webkit
  and provider-pass-errors under BROWSER=webkit 36/36; i18n-keys red
  only in "a plugin's words are its own" (#5332, #5426, #5482).
- The whole GUI suite on Linux (wsl-run, magpie-desktop, --test-
  concurrency=4): 21188 of 21666, 478 red. The 15 provider-editor files
  among the reds (vertex-editor, zero-priced-free, provider-fetch-again,
  provider-picks-stay, model-chip-steady and ten more) were run at this
  commit and at origin/main 2f660ca86 without it: 128 of 236 red on
  both, the same tests. The rest are in files this commit doesn't
  reach.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: ok. gofmt -l clean.
- Full suite: run after the push under the suite lock.

Broken by hand: every PassesErrors() gate set to false: AskedOnce,
NotInferred and OtherAPI red (rewritten body, b asked, rested). The GUI
test on the old code: 0/60.

Not tried: a real vendor account or relay with errors=pass; Windows and
Linux hardware (vet only).

Reported-by: ne9ko9 (Discord)
2026-11-07 00:42:21 +08:00
yetone 8fbf8e0af6 gateway: DeepSeek's own API gets an agent's images once, by file id, not on every turn (#5407)
DeepSeek's API is stateless, so every turn re-sent every inline image in
the history. Now, on api.deepseek.com only (never a relay or another
base), for a model with "flash" in its name (deepseek-flash sees images;
deepseek-v4-pro reads them as "[Unsupported Image]"), each base64 data:
image goes up once through POST /files (purpose=user_data, expires_after
a day) with the candidate's own key, and later turns name it by file id:
- Chat: {"type":"file","file_id":…} (flat, as DeepSeek's vision guide);
- Responses: input_image with file_id in place of image_url;
- Anthropic: source {"type":"file","file_id":…} plus anthropic-beta
  files-api-2025-04-14.
Shapes checked against api-docs.deepseek.com files_api, vision,
responses_api and anthropic_api. The Anthropic guide names the "file"
source type and the beta; the field name file_id is Anthropic's Files
API's, which DeepSeek says it follows. Not confirmed with a real call.

Ids are kept per key hash + image sha256 in deepseek-files.json beside
providers.json (temp+rename, unparseable file moved to .bad), reuploaded
with under an hour left. One upload per image and key however many
requests want it; a request waits at most 8s for its uploads, and what
isn't up goes inline this turn. A failed upload leaves the image inline
and rests that key's uploads for 10 minutes. A 4xx naming a file-api id
or a missing/expired file forgets the ids, uploads again and asks once
more; refused again, the request goes inline. detail:low stays inline.
`magpie provider set <id> image-files=off` turns it off (kept on GUI
save). Doc: docs/subsystems/gateway-routing.md.

Run (mote, at this tree on 498b6419f):
- go test -run 'DeepSeek|DsFileGone' ./internal/gateway: ok; -race -count=3 ok
- go test ./internal/gateway ./internal/provider ./internal/cli: ok
- go test ./internal/gui: TestMainWindowCorners/macOS_26_SDK red, the
  known macOS 27 red on mote (#3949); nothing in gui's code path changed
  but a kept field on save
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok;
  go build ./... and GOOS=linux -tags nogui ok

Broken by hand, each red: host check removed (InlineElsewhere), switch
ignored (ImageFilesOff), singleflight off (FilesOneUpload), breaker off
(UploadFailsInline), key left out of the cache key (FilesPerKey and
others), beta not added (ImagesByFile/anthropic), retry off
(FileGoneUploadsAgain), store not read from disk (FilesKeptOnDisk), the
flash check removed (InlineElsewhere), the 8s wait cap removed
(UploadSlowGoesInline).

Not tried: a real DeepSeek key (none available in the sandbox), so the
exact refusal text for a gone file and the Anthropic file_id field are
unconfirmed against the live API. Not covered: a custom_tool_call_output's
images (walkImages doesn't read it); files aren't deleted (they expire in
a day).
2026-11-06 02:46:46 +08:00
yetone 9d0c9b41ea serve: follow an update put in where it runs from; a replaced magpie.real is magpie
acezan on Discord (Linux 5.15, 0.1.2959 to 0.1.2960): `magpie web` as a
system unit updated /root/.local/bin/magpie.real, and the user unit's
`magpie serve` (`magpie daemon install`) ran on for good from "magpie.real
(deleted)". The panel said an older magpie served the gateway, and its
"close it here" then said the port holder "isn't magpie" and left it.

Why serve stayed old: the app and `magpie web` follow the program they
started from (gui's followReplaced) and restart into an update; plain
`magpie serve` had no such look, and answered `magpie update`'s restart
ask (gateway.RestartPath) "unsupported". Nothing else can restart it
reliably: a system unit doesn't reach the user's `systemctl --user`, and
on a Mac the launch agent's serve (#4335) is the same serve. So serve now
looks itself (internal/cli/serve_follow.go): every 5s it checks its
program with update.Replaced; once replaced, it waits until the gateway
is idle (nothing in flight, 10s since the last end, as gui's idle rule;
after an hour, nothing in flight is enough), ends the plugin hosts and
runs the new program in its own place (update.Reexec: exec in place on
Unix, same PID, so systemd and launchd keep tracking it; a new process
on Windows). The restart ask now answers restarting/waiting/current. A
build that isn't a release never does it.

Why "not magpie": proc.IsMagpie judged the file name, and "magpie.real"
(the program the installer's wrapper script runs) didn't match. It now
trims ".real". And proc.RunsMagpie, used by the takeover and the port
check, also reads Go's build info of the running program (on Linux
through /proc/<pid>/exe, which still reads after the file is replaced)
and calls it magpie when its main package is github.com/yetone/magpie.
A process that isn't magpie is still never ended (the existing
"other-server" case passes unchanged).

Tests, each red on the old code:
- cli TestServeRestartsIntoAnUpdate: a copy of the test binary named
  magpie.real runs `serve` on a free port; a script renamed over it is
  run in its place with the same pid and args, and the old port stops
  answering. Old code: "serve ran on as the old version" after 40s.
- cli TestServeFollowWaitsForIdle: current / waiting / tool-chain gap /
  waitMost with a request in flight / idle / non-release.
- gui TestGatewayFixQuitsAReplacedMagpieReal: a fake older gateway named
  magpie.real, its file removed after start, is quit and the gateway
  served here. Old code: {OK:false Reason:not-magpie}, acezan's case.
- proc TestIsMagpie magpie.real case; TestRunsMagpieByItsBuild: a copy
  named server.real, its file removed, is told by its build (Linux
  /proc/<pid>/exe), and is not magpie with the real main path.

Run: the targeted tests above on Linux (wsl-run, magpie-desktop, -tags
nogui) and macOS (mote-run), all pass. Broken by hand on Linux: dropped
the ".real" trim, made RunsMagpie only IsMagpie, and set serve's follow
to nil; all four new tests went red (output above), restored after.
gofmt -l clean; go vet (darwin, GOOS=linux -tags nogui, GOOS=windows)
and builds on mote.

Not tried: a real systemd user unit or launch agent with a real update;
the Windows restart path (Reexec starts a new process) beyond vet; the
macOS TCC part of #4335 (this restarts the launch agent's serve into the
new bundle path only if that path is where it started from). #4335 stays
open, and ggbdpq's daemon.RestartReplaced patch there is not applied.
2026-11-04 23:55:14 +08:00
yetone 00d8aac596 routing: Free quota by expiry spends the soonest-lapsing free quota first (wowbbs)
wowbbs (and shamen_xiaohong) keep check-in free accounts in one group:
WorkBuddy CN x2, MiniMax Code, TraeCode CN and Qoder CN. They asked that
the group spend the free quota that lapses soonest first, go on to the next
when one is used up or has lapsed, and use a paid account only when no free
quota is left.

This adds `expiring` (provider.FreeExpiring, routes.FreeExpiring). It is a
group's only, picked in the Routing page's group menu, with
`magpie group set <g> routing=expiring` or in the TUI. Nothing changes for a
group or provider that doesn't pick it. A provider keeps refusing it, as it
refuses `cheap`.

- routes: Seat.FreePlan and Strategy.ByPlan. FreeExpiring has three tiers:
  - free seats (Free, a model at no cost, or FreePlan) by Expires, the
    earliest of the window renewals and Lapse, to the hour; an unknown
    expiry goes last and ties keep their listed order;
  - then the paid seats, as Smart orders them;
  - then the spent and resting seats, by when they come back.
- provider.FreePlan reads an account's plan word: free, trial, 免费, 试用,
  体验, 體驗.
- gateway: weighRouted fills FreePlan when the strategy asks. The trace's
  Weighed rows gain `expires`, so the Routing page's story can say "its free
  quota is lost soonest, in 1d 2h". There are also lines for "a free one with
  no expiry told" and "no free quota left, so the paid one".
- GUI: an option in the group menu, the mode line, the story lines, and
  i18n in zh, zh-TW, ja and de. app.js only adds `expiring` to ROTATION,
  paid for by a shorter comment beside it, so the core is 11 bytes smaller
  than at its base.
- docs: gateway-routing.md (order of keys and accounts) and
  plugin-runtime.md (Seat and Strategies).

Plugins whose usage doesn't say when their free quota lapses got issues
rather than edits:
- magpie-community/plugins#718: Trae sums its packs; the soonest end comes
  from any pack, spent or past, and there is no runsOutAt.
- magpie-community/plugins#719: Qoder's plan is the raw userType
  personal_standard, which doesn't read as free, and its add-on, shared and
  dedicated pools have no expiry.
WorkBuddy (Free plan, resetsAt and runsOutAt) and MiniMax (Free, runsOutAt
on credits) already report what this needs.

Run, all on mote via mote-run at this tree (base 0ee424e3e):
- gofmt -l internal plugins: empty. go build ./....
- go vet of routes, gateway, provider, cli and tui; the same with
  GOOS=linux -tags nogui and with GOOS=windows.
- go test ./internal/routes ./plugins/rotation ./internal/tui: ok.
- provider -run TestFreePlan|Group|Routing: ok.
- cli -run Routing|Group: ok.
- gateway -run TestGroupSpendsFreeQuota|Wallet|Free|Cheapest|Routing|Weigh: ok.
- internal/gui -run Budget|Size: TestCoreScriptBudget is red, already red
  at the base (1,534,154 > 1,533,802, #5139). This change takes the core
  down 11 bytes and doesn't raise the budget.
- GUI, node --test in chromium and webkit, en, zh, zh-TW, ja and de, wide
  and 420px:
  - routing-free-expiring (new), routing-group-strategy, routing-cheapest-first,
    i18n-keys, builtins, group-member-free and provider-count-free: 176 of
    176 pass;
  - every routing-*.test.cjs: 2,478 of 2,520 pass. The 42 reds are in ten
    files (routing-rule-remove, rule-drag, rules-line, rule-models,
    row-swap, steady, order-unknown, steps-cap, story-shrinks and
    keys-fold). Run alone at this tree they give 27 reds, and at the base
    0ee424e3e 25, the same tests. They are filed as #5088, #4585, #3096,
    #3789, #3799, #4627, #4628 and #4629.

Again after rebasing on origin/main 0e804be29: gofmt; vet of routes,
gateway and provider; the same Go tests: ok. routing-free-expiring,
routing-group-strategy and i18n-keys: 62 of 62 pass. The core is 1,534,034
here, against main's 1,534,045.

Red on the old code: TestGroupSpendsFreeQuotaSoonestToExpireFirst at
0ee424e3e gives "pro,wb1,wb2,mm,qoder" where it wants
"mm,wb2,qoder,wb1,pro".

Broken by hand: with FreePlan never set, the gateway test gives
"pro,mm,wb2,qoder,wb1" (red). routing-free-expiring.test.cjs reads strings
that exist only with this change. routing-group-strategy's two menu counts
(11) went red with the new option, and they now count 12.

Not tried: no real account of any vendor. WorkBuddy, MiniMax, Trae and
Qoder check-in accounts were not routed live. The order was tested on
fabricated allowances shaped as their plugins report them. The full
`go test ./...` runs after the push.
2026-11-04 17:11:55 +08:00
yetone 6c201095d8 gateway: in Docker, other containers on the host are shown the host's Docker bridge address
jiezhengj (Discord #feedback) runs magpie in Docker on a NAS at
192.168.31.218. The web UI's host address, http://192.168.31.218:3425,
works for other devices. Other containers on the NAS couldn't use it, and
not the container's own 172.17.0.x either. What works for them is the
host's Docker bridge address, http://172.17.0.1:3425. On Linux,
host.docker.internal is there only in a container given extra_hosts.
magpie showed no such address.

- gateway.ContainerHostURL: in a container on a bridge network, the
  gateway of /proc/net/route's default route (172.17.0.1 on the default
  bridge, a compose network's own otherwise), on the gateway's port.
  It is "" outside a container and on the host's network
  (`network_mode: host`, told by the host's
  docker0/br-*/veth*/podman* interfaces). In that case ContainerAddrs is
  false too, since the addresses are the host's own.
- The GUI gets it as /api/providers' gateway.containerHost,
  /api/settings' lanContainerHost and boot's sideGateway.containerHost.
- settings.js lanShown is fed by the new gwLAN(g) for Gateway, Connect,
  the sidebar and the key page. Each case lists:
  - Opened at the host: the host's address first, then the bridge
    address, labelled "Other containers on this host".
  - At localhost: the bridge address alone, with that label, and a line
    that the host's own is MAGPIE_PUBLIC_URL's.
  - No default route: as before.
  The container's own 172.17.0.x is no longer offered beside them. The
  sidebar line and the key page prefer an address other machines reach.
  The scheme comes from the URL, not a hard-coded http. Three new strings
  are in zh, zh-TW, ja and de.
- CLI: `magpie web` and the share banner print "other containers on this
  host <url>".
- docs/reference.md and site docs/docker (en, zh, ja): the log example and a new "Other
  containers on the same host" paragraph.

Run on mote, at this change on d8501848a:
- gofmt -l: clean. node --check: passes.
- Vet: darwin go vet, GOOS=linux go vet -tags nogui and GOOS=windows go
  vet of internal/gateway, internal/gui and internal/cli: ok.
- go test -timeout 45m: internal/gateway ok. internal/gui is red only on
  TestMainWindowCorners/macOS_26_SDK, which is red on macOS 27 at main
  (#3949). internal/cli is red only on TestEveryRouteHasACommandOrIsNamed
  for GET /api/context/reply, red at main (#5026).
- GUI, chromium and webkit: lan-docker (en, zh, zh-TW, ja, de) and the
  40 files on the caller-keys fixture or the LAN paths. 586 tests, 580
  pass. Each red is also red alone at the base d8501848a or af9ac3d25:
  - phone-connect-menu 420, 4 reds (#4706, #4707).
  - gateway-key-models webkit en (#4616, #4081; 4 of 4 at the base).
  - gateway-caller-keys chromium en (#3797; 2 of 3 at the base, 1 of 3
    here).

After the rebase onto 3f1f1882a (187f3e272, the usage page alone, came after): the commits
between touch none of these files. Linux and Windows vet ok. go test -run
'Container|HostNetwork|DefaultGateway|PublicURL|LAN|Boot|Provider' ok in
gateway, gui and cli. GUI lan-docker, i18n-keys, side-gateway-lan and
key-page: 56 of 56, in both engines.

Broken by hand, in a copy:
- defaultGateway reading big-endian: TestDefaultGateway goes red
  ("1.0.17.172").
- The old settings.js, client.js and keys.js: every lan-docker test goes
  red, in both engines and every language.
TestDefaultGateway stubs the in-container check, so it tests the
container path on mote and CI too.

Not tried:
- a real Docker container, on a NAS or anywhere;
- reaching 172.17.0.1 from a container on another compose network on the
  reporter's NAS;
- a published port that differs from the gateway's (MAGPIE_PUBLIC_URL
  sets the host's; the bridge address uses the gateway's own port);
- Podman's rootless networking (slirp4netns, pasta), where the default
  route may not be the host.
2026-11-03 19:41:02 +08:00
yetone e41ef6288c providers: a spend cap on an API key, per day, month or in all (sparkling_lemur_62868)
sparkling_lemur_62868 on Discord: a team's OpenAI key holds granted
credits that other docker services spend from too, and they want magpie
to stop at a share of it. Their workaround was two magpies behind a
gateway-key limit.

What changed
- provider: KeySpendCaps on a provider, keyed by the key's fingerprint
  (key_spend.go): USD over a local calendar day, a local calendar month,
  or in all since it was set. Since is kept while the cap stays one in
  all. SetKeySpendCap and ParseSpendCap refuse an amount outside
  0 < usd <= 1,000,000 and an unknown period, and leave the saved cap
  as it was. Subscriptions are refused, since an account has its own
  usage-window cap.
- usage: KeySpent(keyID, start) is what magpie's own calls on the key
  cost at the Usage page's prices. Turned-away calls and app-reported
  ones are left out. It reads usage.jsonl once per key and start, keeps
  the sum for 5 minutes, and Append counts each new call into it
  (spentNew). A read that a write races is read again.
- gateway: perKeyEvery bars a key at its cap (spendHeld) as a usage cap
  holds an account. The next key serves, then the fallbacks. With none,
  the reply is 429 "spend cap reached: ..." naming each key, what it
  spent of which cap, and how to go on. Retry-After is when the soonest
  period renews; a cap in all gives none. A spend hold is not a usage
  cap: Stop at the caps and strictKeep don't end at it (capHeldOnly).
  The trace's barred row carries the cap, the spend and the period.
- GUI: a pill on each key's row in the provider editor, for example
  "$7.50 of $20.00 today". It opens the app's menu (No spend cap,
  Per day..., Per month..., In all...) and then takes the amount in
  place, as the lane-limit pill does. A key at its cap gets a line
  under its row: "At its spend cap · back in ...". Every string is in
  all five languages. The pill and the line are in keyspend.js, which
  app.js imports when it draws a key's row, so the core's script
  budget is not raised. /api/providers' keyList carries spend, and
  POST provider/keyspendcap sets it.
- CLI: magpie provider spend-cap <id> [key [usd [day|month|total]|off]]
  lists each key's spend and sets or removes a cap.
- docs: providers-accounts.md and gateway-routing.md.

Caveats, also in the tooltips:
- What counts is magpie's priced usage, not OpenAI's bill.
- A model with no known price counts $0.
- Requests already under way when the cap is reached still finish, so
  a key can go a little past it.

Run on mote at the pre-rebase head (3e3196222 + this change):
- go test -count=1 -timeout 45m for internal/provider, usage, cli, gui
  and gateway: provider, usage and gateway ok. Three reds, none from
  this change:
  - cli TestEveryRouteHasACommandOrIsNamed: GET /api/context/reply,
    red on main, #5026.
  - gui TestMainWindowCorners/macOS_26_SDK: macOS 27, #3949.
  - gui TestCoreScriptBudget: from this change. Fixed by moving the
    pill into keyspend.js, then ok on a rerun.
- go vet: plain, GOOS=linux -tags nogui and GOOS=windows -tags nogui,
  all clean. gofmt -l is clean.
- GUI, both engines: key-spend-cap.test.cjs passed 20 of 20 before
  the keyspend.js move, and all of its tests passed again after it.
  It covers en, zh, zh-TW, ja and de at 900 and 400px, a refused
  amount, the set, change and remove posts, and checks for no native
  select, no border stripe and no sideways scroll.
- Also run in both engines: i18n-keys, old-webkit, lane-limit,
  account-cap, key-row-chips-fit, key-weight-fit, key-nourl,
  provider-many-keys, key-switch, key-plan and key-rest-date.
  - key-replace's webkit 420px is red at base 3e3196222 too
    (#4126; base failed 2 of 3 en runs, this change 3 of 3).
  - key-rest-date's webkit zh-TW, ja and de tests time out at
    --test-concurrency=4 with three other files beside it, at base
    too (base 5 reds, this change 7). Run alone at concurrency 2, it
    passes 10 of 10 at base and with this change (#4691).

After the rebase onto 9c51f7fdb, at the pushed head:
- go build ./... and go vet on the five packages: clean.
- go test of the spend tests, TestCoreScriptBudget and the gui
  package's word tests: ok.
- i18n-keys and key-spend-cap in both engines: 24 of 24.

Broken by hand, each red and then restored:
- spentNew taken out of Append: TestKeySpentCountsTheKeysCalls red
  ("after a new call key a spent 3, want 7").
- spendHeld never barring: TestKeySpendCapPassesTheKeyOver red (the
  capped key reached the upstream).
- capHeldOnly keeping spend holds: TestKeySpendCapPassesTheKeyOver red
  (Stop at the caps answered 429 instead of using the fallback).

Not tried:
- a real OpenAI key or real spend;
- the real app window;
- Windows and Linux test runs (vet only);
- the whole GUI suite: mote was running two other sessions' full GUI
  suites at load 250 to 400.
2026-11-03 15:30:44 +08:00
yetone c47fc516a4 provider: Tencent Cloud's Token Plan is at tokenhub.tencentmaas.com/plan (ysm119)
ysm119 (Discord) showed Tencent's docs: Token Plan's OpenAI base is now
https://tokenhub.tencentmaas.com/plan/v3 and the Anthropic one on
tokenhub.tencentmaas.com is the recommended one, with
api.lkeap.cloud.tencent.com marked as going away.

Tencent's current pages (product/1823/130060 个人版 overview, 130070
Claude Code, 130071 Codex, 130119 quickstart, 136601 CC Switch, all
updated 10-15 to 10-22) give 个人版 the same endpoints as 企业版 China
(130659): chat/responses at https://tokenhub.tencentmaas.com/plan/v3,
messages at https://tokenhub.tencentmaas.com/plan/anthropic, one sk-tp-
key for 通用 and Hy plans.

- The tencent-cloud preset's plan region (and the preset default) are
  at those endpoints, with Responses added (Codex's page uses
  wire_api "responses"). magpie tells regions apart by endpoint, so the
  personal and China enterprise regions, now one address, are one:
  "plan", models the union of both lists. "enterprise" stays an alias
  (regionAliases, RegionID): a key saved on it, an import link with
  region=enterprise and `region=enterprise` on the CLI land on plan.
  Singapore 企业版 (enterprise-intl) is unchanged.
- A Tencent Cloud provider saved at the old lkeap /plan/v3 or
  /plan/anthropic is moved to TokenHub at load (moveEndpoints in
  normalize), and gains the Responses endpoint when it had chat. A
  Responses address the user set stays. A provider of no preset (a
  custom one the user typed lkeap into) keeps its address: that is the
  user's value, and lkeap still answers today.
- An app config still at lkeap (Tencent's OpenClaw page, 130062, still
  gives it) imports as tencent-cloud at the new endpoints.
- Usage: DescribeTokenPlan is 企业版's API (api/1823/132270 lists
  enterprise products only), and Guangzhou's endpoint now serves
  个人版 too, so a Guangzhou provider with no SecretId no longer gets the
  card asking for one (tcSharedRegion); Singapore's still does. The
  editor shows the optional SecretId/SecretKey at the plan region, so a
  personal user sees them too.
- docs/subsystems/providers-accounts.md says all of this.

Run at the pushed head's base f3551387c on mote (rebased onto
d29f02d65, which only touches internal/agent's omp; provider and cli
re-run after the rebase):
- go test -timeout 45m ./...: every package ok except three filed reds
  that touch nothing here: cli TestEveryRouteHasACommandOrIsNamed
  (#4826), gateway TestCodexPoolSaysTheClientsVersion (#4807), gui
  TestMainWindowCorners/macOS_26_SDK on macOS 27 (#3949).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean. gofmt -l: nothing.
- GUI tencent-cloud, tencent-access-key, i18n-keys (chromium+webkit,
  en/zh): 24 pass, 4 fail, all "a region clicked right after the strip
  scrolled" (#4321/#4399/#4625; app.js is unchanged here).

Broken by hand, each red then green again:
- normalize without moveEndpoints: TestTencentCloudOldPresetsKeepWorking
  and TestTencentPlanMovedFromLkeap fail.
- the import's movedEndpoints lookup: TestTencentPlanMovedFromLkeap.
- the Guangzhou card skip: TestPlanCardWithoutAccessKey.
- RegionID in ParseImport: TestTencentPlanMovedFromLkeap; in the CLI:
  TestTencentOldRegionAtCLI.

Not tried: no real Tencent key here, so no request reached either host
and no real usage read. Tencent's international personal plan (CodeBuddy
page tencentcloud.com/document/product/1300/81035) is at
tokenhub-intl.tencentcloudmaas.com, a host magpie has no region for; not
added. The 即将下线 label in ysm119's screenshot is not on the pages
fetched, and no retirement date was found (FAQ 130076). The site's
import-link builder still offers "Enterprise plan · China", which now
adds the plan through the alias.
2026-11-02 21:41:56 +08:00
yetone 4dfdd0cd63 provider: a provider switched off is asked for nothing, its plugin's model list included
ChangQiu on Discord switched a provider off long ago, and magpie still
reached it. Routing, fallback, usage and balance reads, warmups,
check-ins and keepalive were already held back (On(), leftAlone,
KeepListsFresh). These were not:

- The plugin host's providers listing ran every plugin's models hook,
  which asks the vendor, and its sign-in renewal (fresh), for every
  plugin provider, on or off. Go now passes the ids switched off
  (plugin.ListingOff, provider.pluginsOff: the provider's id and the
  plugin's own id, read from providers.json alone). host.js lists such
  an id without running a hook (info(..., quiet)), so its row stays and
  keepListed keeps the last list.
- Sync (POST /api/sync, `magpie sync`) fetched every ready provider's
  list. Both now go through provider.RefreshLists, which skips one
  switched off.
- Saving or switching on in the GUI fetched the list even for one left
  off; PrefillNewKeys asked one switched off too.

What still asks one switched off, by the user's own click: the TUI's
refetch, the provider Test button and `magpie provider models <id>`
refetch.

Tests: TestOffPluginProviderAskedNoModels (the fake plugin's models
endpoint counts its hits: 0 while off, the list kept, asked again once
switched on), TestPrefillAsksNoProviderSwitchedOff,
TestPluginsOffNamesThePluginsOwnIDs and
TestRefreshListsAsksNoProviderSwitchedOff.

Run on mote at this head (first at a4916aec1):
- go test -timeout 45m ./internal/provider ./internal/plugin
  ./internal/gui ./internal/cli ./internal/tui ./internal/gateway:
  provider, plugin and tui ok. Three reds, each also red on origin/main
  and filed: gui TestMainWindowCorners/macOS_26_SDK (#3949), cli
  TestEveryRouteHasACommandOrIsNamed (#4826), gateway
  TestCodexPoolSaysTheClientsVersion (#4807).
- After rebasing on ce2e81da1: provider and plugin again, plus darwin
  vet of the four packages. One provider run went red on
  TestClaudeAccountServesModelsListedSinceItsFetch (#3174, full-run
  only). It is green alone 3/3 on this head and on origin/main, and the
  next full provider run was ok on both.
- GOOS=windows go vet of plugin, provider, cli and gui: clean.
  gofmt -l: clean. Linux go vet (WSL magpie-desktop) of plugin and
  provider: clean. cli and gui can't be vetted there: the distro has no
  gtk4/webkitgtk-6.0 headers for wails' cgo.
Broken by hand: with each guard taken out, its test went red ("switched
off, the vendor was asked 2 times", "the vendor asked 2 times",
"pluginsOff = [fakeco onco openai openai-plugin]", "the provider
switched off was asked 1 times").
Not tried: a real plugin provider switched off in the app. Which
provider ChangQiu had switched off isn't known, so his exact case is
not reproduced.
2026-11-02 14:30:45 +08:00
yetone c688211d13 gateway: a ChatGPT (Codex) account gets loaded tools where they were loaded, keeping its cache (#4738)
infinitex233 (#4738, Discord): Claude Code -> magpie -> a Codex account,
and every ToolSearch load dropped cache_read to 0. loadsInPlace sent the
additional_tools item (#2660) only to OpenAI's own API, so for an
account the loaded tool went into the top-level tools and the cached
prefix broke at the tools.

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

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

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

Not tried: the reporter's own setup (Windows, gpt-6.1-terra), a real
Claude Code client (the probe sent its request shape), Copilot or any
other signed-in vendor with the item.
2026-11-01 14:59:44 +08:00
yetone 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 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 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 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 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 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 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 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 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 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 b4267de595 gateway: a provider's fallback can be a routing group, routed as the group
01huadalang on Discord: "还有备用模型增加路由组的选择,现在只能选模型". A
provider's Fallback list held models only; a "group/<id>" entry resolved
to the group's first member alone. Now such an entry is served through the
group, as a request to the group would be:

- plan → planPaused: a fallback naming a group (provider.FallbackGroup,
  the group as routed, Live) hands its members to planLevel
  (planFallbackGroup): the group's own routing, its sink and asides, and
  its pause rules (serve passes provider.PausedOut for the agent's folder).
  Its trace rows are marked Fallback with the group in Via.
- No loop, each provider/model once a round: a member that is the primary,
  a model named earlier, or another fallback group's member is left out
  where it comes second. Groups have no fallbacks of their own and a
  member's fallbacks are not followed, so nothing leads back. A group that
  is gone or off is passed over, as a model none serves is.
- Every sibling that reads p.Fallback now reads a group's members through
  provider.FallbackModels: redaction (unredactedRoute: an unmasked
  provider with a fallback group holding a remote model is masked),
  careful accounts (carefulOf), native compaction, Codex's own turns
  (codexFallsBack) and Claude's auto-mode review (claudeReviewed, which
  moves from provider.Resolve to ResolveRoute, as the gateway reads
  fallbacks).
- CLI: `magpie provider fallback` already took group/<id> (Resolve knows
  groups); its usage and error now say so. Pinned by
  TestFallbackCmdTakesGroup.
- GUI: the provider editor's Fallback picker lists the routing groups
  (providers.gateway.groups) beside the models as chips with the Routing
  fan and a muted "routing group" tell; a picked group's row has the same
  fan and tell, and a gone one says "No routing group {id} now; it is
  skipped". A filter matches a group's name, id and its members'
  providers. New strings in zh, zh-TW, ja and de.
- app.js budget raised 187 bytes on main (1,311,922; core 1,531,060), the core's
  own editor, no room added; the addition was cut from ~900 bytes first.
- docs/subsystems/gateway-routing.md: the Candidates row says all this.

Not done: a fallback group's turn rules (ruleFor/ruleOver, which can ask
a classifier) are not applied. The plan is made before the primary is
tried, so they would cost a classifier call on every request the primary
answers. Its routing order, sink and pause rules are applied.

Run (at f6e7214af; after the rebase, the last bullet):
- gofmt -l: clean. mote: go build ./...; go vet on the touched packages;
  GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...: ok.
- mote: go test -timeout 45m ./...: every package ok except internal/gui:
  TestCoreScriptBudget (fixed above, then ok) and ten AppKit window tests
  (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestMainWindowCorners
  …) killed at their 30s bars while four other sessions' GUI suites held
  mote at load 70-110. Run alone, all ten
  pass (TestDockJoinLeadsCommandTab skips) except TestMainWindowCorners,
  red at base f6e7214af too (#3949); the load kills are #2645.
- GUI: the whole suite (962 files, node --test --test-concurrency=8) on the
  Linux box (WSL magpie-desktop, chromium + webkit): 14,217
  tests, 305 red in 99 files. Those 99 files rerun at base f6e7214af: 156
  red; at this head: 159; the ~20 that differ either way are flakes (the
  head-only ones, key-replace and vertex-editor, rerun twice on each: the
  same reds at base). Filed as #4120.
  fallback-group.test.cjs (new), fallback-more and i18n-keys: ok in
  chromium and webkit on mote and on Linux.
  After the app.js cut, at the final head: the three files 12 of 12 on
  Linux; webkit ok on mote, chromium there failed only at browser launch
  under load.
- Broken by hand, each red, then restored:
  - the group branch in planPaused off: all five gateway group tests red
    (TestFallbackToGroupServedByMember is red on the old code: only the
    first member was tried).
  - the dedup off: TestFallbackGroupWithThePrimaryTriesItOnce and
    TestFallbackGroupSharedModelTriedOnce red.
  - the pause filter off: TestFallbackGroupPauseHolds red.
  - redact.go from origin/main: TestFallbackGroupKeepsMasking red.
  - the GUI's group list off: fallback-group.test.cjs red in all four
    (chromium/webkit × en/zh).
- After the rebase onto 0daf36332 (18 commits, gateway.go among them;
  the budget test conflicted, kept main's and measured again): gofmt -l
  clean; mote: go build ./..., vet of the touched packages, linux and
  windows vet ok; go test internal/provider, internal/cli, internal/agent
  ok, and internal/gateway and internal/gui -run with Fallback, Redact,
  Unredacted, Careful, Compaction, CodexFalls, Budget, Rest and Probe ok; fallback-group, fallback-more, i18n-keys
  and rest-probed 52 of 52 on Linux.

Not tried: a real request through a real group fallback with real
accounts (the tests use fake upstreams); the Windows GUI; the TUI has no
fallback editor.
2026-10-29 05:19:28 +08:00
yetone 08b02cf18c providers: a pool stops at its caps and reads usage again near them (plugins#349)
What was adopted on magpie-community/plugins#349 (1939869736luosi): one
place, in the GUI and the CLI, for a subscription's account pool, and an
opt-in conservative mode.

- Stop at the caps (Provider.CapStop, off by default): once every account
  in use is held at its cap, the request is answered 429 rather than going
  on to the provider's fallbacks (plan returns restLast). Off, as before.
- Check usage again near a cap (Provider.CapCareful, off by default,
  internal/gateway/cap_careful.go): before planning, a capped account's
  usage is read again when its reading is over 15s old within 5 points of
  a cap, or over 5m old at all; the request waits at most 10s, and a
  failed account is asked again at most every 15s. An account whose usage
  was never read, whose last read failed, or whose reading is still that
  old is then held as one at its cap is (capHold "unread", traced as
  Weighed.Unread, named in the 429 with "--careful off"). Generic: it
  goes by provider.UsageRead/ReadUsageNow, so every subscription that
  reports usage windows (Codex, Claude, plugins) gets it.
- provider: usedCache records each account's read state; a failed read
  keeps the last good reading's time. ReadUsageNow no longer reports
  false when the read had already finished on the first ask.
- GUI: under the provider's account list, once an account has a cap (or
  either is on), two ticks for the above, and a note naming the accounts
  in use with no cap ("used to 100% of each window"). Accounts, order and
  caps stay where they were in that list. zh, zh-TW, ja, de added.
  app.js 1,309,658 within its 1,310,460 budget, unraised: addRow and a
  per-row forgetOf replace 3 add-button and 5 Remove-button builds.
- CLI: magpie provider pool <id> [--accounts a,b,…] [--cap percent|off]
  [--stop on|off] [--careful on|off] shows and sets the whole pool.
- docs: gateway-routing.md and providers-accounts.md.

Run (mote, before the rebase at 8bade6c5e + this change):
- go test -tags nogui -timeout 45m ./...: exit 0, 76 packages ok, no
  FAIL (log grepped).
- GOOS=linux and GOOS=windows go vet of cli, gateway, provider, gui: ok.
- pool-ends.test.cjs: 32/32, Chromium and WebKit, en zh ja de, 1100 and
  420 wide.
- The 81 GUI files whose fixtures have accounts or caps, plus i18n*,
  6 at a time at load ~130: 76 pass. i18n-keys is red on the base too
  (#3897). account-mask (#3951), account-alias (#2984),
  signin-closes-sheet and signin-again timed out under load and pass
  run again, as on the base; signin-again filed as #3960.
- Real plugin host: TestPluginCarefulPool runs the fake plugin under Bun
  as Factory with two accounts capped at 90%: a failing usage call gives
  429 with nothing sent upstream while careful is on, the last reading
  is used with it off, a good read sends to A again, and with both at
  their caps the fallback serves unless Stop is on.
- CLI binary in a sandbox HOME on mote: unknown provider, a bad --stop
  value and no id each refuse and change nothing.
At the rebased head (0a7633136 + this): gofmt -l
clean, go build ./..., the new Go tests and the budget tests, and
pool-ends.test.cjs 32/32.

Broken by hand, each seen red, then restored:
- the CapStop line in plan: TestCapStopSkipsTheFallbacks and
  TestPluginCarefulPool red;
- the careful hold in capHeld: the three careful tests and
  TestPluginCarefulPool red;
- careful always on: TestCarefulOffByDefault red;
- readCareful not called: the failed, never-read, stale and re-read
  subtests red;
- a failed read not keeping the good time, or not counted as failed,
  and ReadUsageNow's early return forced false: TestUsageReadAndReadAgain
  red;
- the ticks' onchange emptied: pool-ends.test.cjs 16 of 16 red.

Not tried: a real Factory or any real account (fake plugin only); the
whole GUI suite (932 files, ~5h at this load), only the 81 files that
reach the account list; Linux WebKitGTK and Windows; the 15s/5m/5-point
figures against a real vendor's usage endpoint latency.
2026-10-28 09:29:44 +08:00
yetone 1885c607e2 gateway: Antigravity answers Codex's switched threads and Hermes' old persona with no setup
Antigravity answers some agents' system prompts with a fake 429 "Resource
has been exhausted", whatever quota is left. Jodiezzzzzz on X (10-27): a
Codex thread begun on GPT-5.x and switched to an Antigravity model got 429
again and again. zgoodz on X: "antigravity在Hermes里一样429". v0.1.1625
told the Codex case as a 400 with "start a new chat", which isn't zero
setup.

What Google matches, each tried on a real Antigravity account on 10-27
(in the system instruction, any case):
- "x-anthropic-billing-header:" (Claude Code)
- "built on Anthropic's Claude Agent SDK" ("running within the Claude
  Agent SDK" goes through)
- "You are Codex, an agent based on GPT-5" / "..., a coding agent based
  on GPT-5"
- new: "Hermes Agent, an intelligent AI assistant created by Nous
  Research", Hermes' earlier default SOUL.md, kept by anyone who edited
  their SOUL.md. Hermes' current default ("You are Hermes Agent, built by
  Nous Research") goes through.
Each goes through with a zero-width space after its first letter.
"Y​ou are Hermes Agent, an intelligent..." still fails, so the
break goes inside the matched phrase itself.

Now codeAssistBody puts that zero-width space into each matched line
(antigravityCloak), in the system instruction only, and only for an
Antigravity account. Gemini CLI's account on the same envelope, and
every other provider and protocol, get the prompt as the agent wrote
it. The text added names nothing; it is one U+200B per line.
`magpie provider set antigravity prompt=as-written` (PromptAsWritten,
kept through Save/withPicks and the GUI's save) turns it off. Then the
v0.1.1625/#2156 fallback stands: a 400 with a hint (now one for Hermes
too, in the Routing page's five languages) and Antigravity skipped for
6h in a group.

Default-on, as the community antigravity-cloak middleware's README
says, changes what Google is sent so a request it means to refuse goes
through. That may be against Antigravity's terms. The owner asked for
it ("破解过 antigravity 提示词让其可以在别的 agent 中使用"), and it is
scoped to Antigravity accounts with an off switch.

Run at this tree (rebased on origin/main):
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/provider/
  ./internal/cli/ ./internal/gui/: gateway, cli and gui ok; provider
  died in TestUnreadLoginsWriteErrorsKeepCredentials ("close of synctest
  channel from outside bubble" in filememo.Forget), #3632, red on main
  since 091153bf; with -skip of that test, provider ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok. go build: ok.
- GUI (node --test, Playwright 1.62, chromium and webkit):
  routing-ag-turned-away, i18n-keys, gui-ja, gui-de, gui-zh-tw,
  routing-js, panel-routing: 45 pass, 0 fail.
- Broken by hand: with the cloak skipped, TestAntigravityAnswersHermes
  AndCodexByDefault and TestOnlyAntigravityIsSentThePromptBrokenUp go
  red; without withPicks' line, "prompt=as-written isn't kept".
- Real account, sandbox HOME with only the Antigravity login copied,
  this build on 127.0.0.1:3496:
  - real Hermes Agent (AIAgent, sandbox SOUL.md = the old persona plus
    one line): "OK", 200. With prompt=as-written: 400 with the Hermes
    hint. Back on default: 200.
  - real Codex 0.162.1: a thread begun on gpt-5.5 (against a local
    fake Responses server), then `codex exec resume <id> -m
    antigravity/gemini-3-flash` through this build: "OK". With
    prompt=as-written: 400 with the Codex hint.
  - a synthetic switched Codex Responses thread, with and without
    web_search: 200.
  - opencode, droid, kimi, pi, gemini-cli, qwen, crush, goose, amp and
    openclaw identity sentences: never refused, as written.
Not tried: Claude models on Antigravity (the sandbox account's Claude
quota is spent, so the Claude Code lines were checked on Gemini 3
Flash only); other agents' whole prompts, only their identity lines;
the Windows box; the whole GUI suite.

The plugins repo's antigravity-cloak 0.1.2 adds the Hermes line for
magpies before this one.
2026-10-27 04:16:20 +08:00
yetone d56c14e953 gateway: a single provider's busy or briefly rate-limited reply is waited out, for its own Patience (zoecats)
zoecats on Discord: a request to one provider (not a group) got a local
relay's short 429 straight back in Claude Code once the few same-one
retries were spent. A group would have held the agent and asked again.

A plain provider now takes the group's replan path (patience.go: replan,
pauseAlive, the held writer) once passing's same-one retries are spent:
its accounts take turns as members do, each pause never shorter than the
Retry-After, and a streaming agent gets keepalives past keepHeldAfter.
- Zero-config: unset, it waits singlePatience, PatienceDefault (60s),
  counted from when the agent would have had the error.
- The user's value wins: Provider.Patience, the same values as a group's
  Patience, set with `magpie provider set <id> patience=2m|off|default`
  (at most 4m). The provider editor has no row for it (no new UI), and its
  save keeps it. A group the provider is in keeps the group's own.
- Not retried: a Retry-After past the budget, quota/credit/plan limits,
  401/403, refusals, response protection, didNotStream, and an agent
  that has gone (499, try marked Gone).
- The try is traced with Again alone, so the Routing page tells it as
  "tried again in …".
- codexReset (ChatGPT's 503 for a large request) is left out of the
  plain-provider replan, so Codex still gets its 503 with advice.
- Codex's own one-account relay (codexUpstreamOn) does not join. It is
  relayed outside the candidate loop, and its backend 429 is always the
  plan's usage limit (codexBusy never retries one), so the short rate
  limit this waits out doesn't arise there. Its overloads keep
  lastRetries and then fallbacks.

longestPause became a var so tests can scale it. Tests updated for the
new count (1 + retries + replanRounds when it never clears):
- TestLastOneLeftIsTriedAgain
- TestRateLimitIsWaitedOut
- TestQueuedStreamFailureIsTheStreamsError
- TestOverflowTheVendorDidntSay

New tests, through the server with a fake upstream and injected
durations, waiting on trace state, not a duration:
- TestSingleProviderWaitsOutAShortRateLimit (stream and whole: 200,
  keepalive before the answer, asked twice)
- TestSingleProviderPassesALongLimitThrough (an hour, quota, 401)
- TestSingleProviderAgentGoneInTheWait
- TestSingleProviderOwnPatienceWins (off, shorter and longer than the
  default)
- TestPatiencePair (cli)
- TestProviderSaveKeepsPatience (gui)

Broken by hand, each red, then restored:
- singlePatience fallback 0 for a plain provider: WaitsOut stream and
  whole got 429, and AgentGone never paused.
- replan's budget check off: PassesALongLimitThrough/an_hour, "magpie
  waits to ask again".
- pauseAlive's ctx.Done case removed: AgentGone, "route done false
  status 0".
- The gateway ignoring Provider.Patience: OwnPatienceWins off, shorter
  and longer all red.
- The GUI save not keeping Patience: TestProviderSaveKeepsPatience,
  "patience 0 … want -1 kept".

Run in this tree, before the rebase:
- go test ./internal/gateway ./internal/cli ./internal/gui: ok.
- ./internal/provider: ok with -skip TestUnreadLogins. That test crashes
  with "close of synctest channel from outside bubble", the known #3632,
  in filememo and not touched here.
- gofmt -l: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: all 0.
- go build for darwin, linux (nogui) and windows: ok.

Run again after rebasing on origin/main 39526c069 (17 commits, 22 files
in gateway/provider/cli): gofmt, go build, go vet on the four
packages, the replan, retry, overflow and Codex-reset tests, and every
new test: all ok. The whole gateway package was not run again there.

Not run:
- The full ./... suite: machine load ~150, other sessions' suites
  running.
- A real vendor's 429.
- The GUI suite: no GUI file changed.
2026-10-27 02:26:27 +08:00
yetone d9a8148d7c routing: Speed first sends a request to the provider or key that answered the model fastest lately
joeliu96872540 on X: when one model is reachable through several API
channels, they want an option that sends each request to whichever has
been answering fastest, because they compare channel speeds by hand
today. Speed first (`fast`; `fastest` and `speed` also work) is a new
routing beside Free first. It applies to a provider's keys and accounts
(provider editor › Routing) and to a group of one model on several
providers (Routing page › group › Routing).

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

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

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

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

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

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

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

Not tried:
- A real run against several channels of one model. Speeds come from
  real answers, so the first minutes after a start are in listed order
  plus probes.
- A non-streamed reply is not measured, a sub-millisecond TTFT is not
  counted, and a restart forgets every speed.
- The Windows runtime: only go vet ran for it.
2026-10-27 01:37:38 +08:00
yetone 41b0445ccf provider: a local server's address is a field shown first, and address= on the command line (LM Studio on another computer)
mengxiangziyou on X: "供应商里的LM Studio只能用本地的,怎么用局域网里其他机器
上的LM Studio, baseUrl 不能改". Moving a local preset (Ollama, LM Studio,
oMLX, MLX-Serve) to another host has worked since #1165, but the window
put the Address in a "Server address" fold under the key, while the
Endpoints row showed http://localhost:1234/v1 as plain text. Reproduced
in a sandbox: Add > LM Studio shows the URL and nothing to change it
with unless the small fold is found.

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

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

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

Not run: go test ./... over every package (other sessions' suites on
this machine, load ~60), the whole GUI suite, a real LM Studio on a
second machine, the Windows and Linux apps.
2026-10-25 20:29:22 +08:00
yetone 0152f66966 provider: a Remote magpie's model list follows the other magpie's, fetched every 10m (6igsteven on Discord)
6igsteven (Discord, 10-24/10-25): GLM-5.3-Trial and GLM-5.3-Flash-Trial
are listed on the magpie that runs the ZCode plugin, and not on the
magpie that uses it as a Remote magpie. The trial entries come from the
ZCode plugin once it reads the account's gift (zcode 0.1.26), and the
other magpie's /v1/models lists them as it lists every catalog entry.
But a Remote magpie is a provider of keys: its list was fetched when it
was added and then only when Fetch models was pressed in its editor
(KeepListsFresh asks only providers with a RefreshEvery, FetchNew only
accounts). So anything listed there later (the trial models, a new
provider, plugin or routing group) never reached this magpie.

A Remote magpie with no RefreshEvery now has a 10m schedule
(RemoteMagpieEvery, RefreshSchedule), so KeepListsFresh refetches it
through the same Refetch as Fetch models. `magpie provider refresh-every
<id> off` on a Remote magpie is kept as "off" rather than "" so the
user's off isn't read as unset. CLI show/refresh-every print the
schedule in force. Other providers are unchanged: no schedule means
only when asked.

Run: TestRemoteMagpieListFollowsTheOtherMagpie (new) with
TestKeepListsFreshFetchesWhatIsDue, TestParseRefreshEvery,
TestSaveKeepsTheListsScheduleAndRules: ok, sandbox HOME, Go caches
pinned. Broken by hand: RefreshSchedule returning RefreshEvery alone
(the old behaviour) fails the new test with "asked [], want [office]";
restored, ok. gofmt -l clean.
Then, at this commit: go test ./internal/provider ./internal/cli ok
(140s, 58s); go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows ok; darwin, linux (nogui) and windows builds ok.
Not run: go test ./... - the machine's disk had under 1GB free
(other sessions' work) and load ~200, so a full suite would not fit.
Not tried: a real two-computer setup with a live ZCode gift. A Remote
magpie whose user curated its picks (left a listed model unpicked)
still doesn't take new models by itself (withNewlyListed, by design).
2026-10-25 16:30:48 +08:00
yetone 5b2b3d3f50 providers: a switched-off provider says how to turn it on, after a sign-in too
Atlas (Discord) signed in to WorkBuddy AI with `magpie plugin login
workbuddy-ai`, and `magpie providers` then showed "○ switched off" with
nothing saying why or how to undo it. magpie never sets Provider.Off by
itself; only the user's own switch does, and a sign-in rightly keeps it.
So the setting stays as the user left it, and magpie now says how to
change it:

- `magpie plugin login <id>` and `magpie accounts add <id>` (plugin and
  built-in paths), finishing for a provider that is switched off, print
  "! <Name> is switched off in magpie, so agents aren't given its models
  · turn it on: magpie provider on <id>". One that can't be found says
  nothing (not known to be off).
- `magpie providers` puts "magpie provider on <id>" in the switched-off
  row's last, unpadded column, so the key column keeps its width.
- The TUI's Providers row notes "o switches it on" (its `o` key).
- The GUI row already shows a "Switched off" badge and its own switch,
  and the editor says how to switch it on: left alone.

Run, at this tree (base c9c28aa58):
- TestPluginLoginSaysItIsSwitchedOff (new), TestProvidersShowVertexCredentials
  and TestTUIAddsVertexWithItsProject (extended): red with the source
  changes reverted (no hint in the login output, providers row or TUI
  row), green with them.
- go test -timeout 45m ./internal/cli/... ./internal/provider/... ./internal/tui/...: ok (cli 45.8s, provider 120.1s, tui 21.8s)
- gofmt -l: clean. GOOS=linux go vet -tags nogui ./...: ok.
  GOOS=windows go vet of the three packages: ok. go build: ok.
- Real run in a sandbox HOME with the fake test plugin and real Bun:
  plugin login (on: no line), provider off, plugin login again (the
  line, still off), magpie providers (row shows the command), provider
  on (row back to "signed in", no hint).

Not tried: a real WorkBuddy AI account; the built-in (non-plugin)
`magpie accounts add` path's line has no test of its own (its sign-in
needs a vendor's OAuth); the TUI was checked through its test, not a
real terminal; the full ./... suite was not run.
2026-10-25 13:19:52 +08:00
yetone a3b45eb91e provider: a re: pattern matches in any case, as a glob does (usrname1833 on Discord)
A routing group's patterns (Group.Match) and a provider's auto-include
rules both compile through compilePattern. A glob compiled with (?i)
and a re: pattern without it, so re:gpt-.* missed GPT-5.5 while gpt-*
took it. A re: pattern now compiles as (?i)^(?:…)$; (?-i) inside it
makes case matter again from there on (re:(?-i)gpt-.*).

The Routing page's editor works out a pattern's models in JS
(patternRe in plugins/routing/client.js) and refused what JS can't
read. It now reads re: with the i flag too, and takes Go's leading
flag group ((?-i), (?s), ...) as JS flags, so re:(?-i)OR/B is taken
and matches as the gateway will. A flag group further in is still
refused there (JS has no bare (?-i)); the CLI takes it.

Said in groupmatch.go's comments, magpie group's and magpie provider
auto-include's help, and providers-accounts.md (Routing groups, List
schedule and rules). No GUI hint said a pattern's case, so none
changed and no string was added.

Run:
- TestRegexpPatternIgnoresCase (new): ok. With compilePattern's (?i)
  taken off by hand: FAIL, "re:GPT-.* ~ gpt-5.5: false, want true" and
  three more cases.
- group-patterns.test.cjs, chromium and webkit, en and zh: 4 of 4 ok.
  With patternRe put back to the old re: line by hand: 4 of 4 red,
  "(?-i) keeps case 0 !== 1" (old JS refused re:(?-i)OR/B).
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.
- go test -tags nogui -timeout 45m ./internal/provider ./internal/cli
  ./internal/gateway under a sandbox HOME at 1a956129c's tree: ok,
  ok, ok (380s). go build for darwin, linux (nogui) and windows: ok.
- A full ./... run was started and stopped: the machine's disk was
  full (1GB free), and internal/agent's tests failed on "no space
  left on device" in TempDir, not on this change. No full suite ran.

Not tried: the full suite (above); a real provider's auto-include fetch with mixed-case ids;
the Linux app's WebKitGTK; a (?-i) further into a re: in the GUI.
2026-10-24 07:07:57 +08:00
yetone f5b0157420 gateway: a tool Claude Code's tool search loads goes to OpenAI's Responses API where it was loaded (#2660)
Through /v1/messages translated to a Responses provider, every deferred
tool ToolSearch loaded joined the top-level tools on the next request, so
the prompt changed from its first bytes and the cache missed on each load
(maximia's probe: cached tokens dropped on every request after a load).

Now, where Request.LoadedInPlace is set, a deferred tool (defer_loading,
Tool.Deferred) that a tool_result's tool_reference names (toolRefs,
Part.Loads) goes in an {"type":"additional_tools","role":"developer",
"tools":[...]} item right after the run of tool outputs that loaded it,
once, and not in tools (buildResponses). Parallel results and one result
naming several share one item; a tool named again isn't repeated; the
output's text is as before. A history whose loading result is gone
(compaction, edits) puts the tool back in tools: a new prefix, expected.

Scope (loadsInPlace): OpenAI's own API with a key (api.openai.com,
*.api.openai.com), whose tool search guide documents the item and says
its tools load at the end of the context so the cache is kept; and a
provider the user sets with `magpie provider set <id> additional-tools=on`
(Provider.AdditionalTools, kept by the GUI's save like codexAsSent).
Nothing else: xAI answers the item 422 (#350), the ChatGPT backend has
been seen taking it only for Codex's Responses Lite, Azure, plugins and
relays are untried. An upstream that refuses a request holding the item
with a 400/422 naming additional_tools is asked again with every tool in
tools, logged ("turned away additional_tools ... loaded tools go in tools
from now on") and not sent the item again while magpie runs.

Not handled: a tool a tool_addition block in a system message loads (MCP
late tools, the advisor) stays in tools. Not tried against a real
upstream: no OpenAI key or custom Responses relay was used; the item's
shape and position follow OpenAI's docs, and the fixtures follow
maximia's three-request probe (Claude Code 2.1.302) and the
tool_reference shape Claude Code 2.1.306's binary writes.

Tests: TestLoadedToolsKeepThePrefix (top-level tools and instructions
identical across the three requests, each input a prefix of the next),
TestLoadedToolsInOneItem (parallel, batch, repeat), TestLoadedToolsWhereNotTaken
(unsupported upstream unchanged; compacted; non-deferred),
TestLoadsInPlaceScope, TestLoadedToolsThroughTheGateway (off by default on
a relay, on with the flag, refusal retried without the item and not sent
again), TestAdditionalToolsPair (CLI). Broken by hand: with the
buildResponses placement disabled, the first two and the gateway test go
red; with the refusal retry disabled, TestLoadedToolsThroughTheGateway
goes red.

Run at cff7dc67d (this change on 82fb0702f), sandbox HOME, one suite on
the machine: gofmt -l internal/ clean; go vet ./... (darwin),
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... all clean;
go test -timeout 45m ./... every package ok (gateway 890s, agent 871s,
provider 447s), no FAIL. Rebased onto 52209522a (gui assets, redact and a
gateway-routing.md line of others; no overlap in code): go build ./...,
go vet of gateway, cli and redact, the tests above with TestToolSearch*
and TestCodexAsSent, and go test ./internal/redact, all ok. GUI (playwright) suite not
run: no GUI asset changed (internal/gui/providers.go is Go, in the suite).
2026-10-21 19:58:52 +08:00
yetone 1bd99194ea provider: Claude Code stays listed, signed out, when every saved account's sign-in is gone
LeeHom on Discord: two Claude Pro accounts vanished from Providers, and
signing one in again showed the other as "needs sign in again". While
Claude Code is signed out, the claude provider is built on
claudeStandIn's account. claudeStandIn skips an account whose sign-in
Claude Code let go of (claudeLoggedOut's claudeLogoutLapse) or that is
still Held. With every saved account like that, it returned "", no claude
provider was made, and the subscription and both accounts left the GUI,
the TUI and `magpie providers` at once.

claudeStandInAccount and Logins now ask claudeListed: the stand-in, else
the signed-out account seen last. A Held account is never listed this way,
because the sign-in Claude Code left on disk would then be served
(TestClaudeSignedOut still holds). The listed account's token still fails
with the lapse reason (claudeSavedDir), so nothing is served on it.
claudeStandIn itself is unchanged, since addLogin and logins_on rely on
it.

The app's row already said "{user} is signed out" when every login in use
had lapsed. Provider.SignedOut is that rule in Go. With it, `magpie
providers` says "○ <user> is signed out · sign in again" and the TUI says
"○ <user> is signed out", instead of a green "signed in". The CLI's key
column moved into keyColumn so it can be tested. The providers-accounts
doc row says this.

Tests:
- TestClaudeAllSignedOutStaysListed: signed in, a second account
  logout-lapsed, then Claude Code signed out. It fails on the old code
  ("Claude Code left the Providers list with every account signed out:
  false") and with SignedOut returning false (both broken by hand).
- TestProvidersSaySignedOut, in cli and tui: a signed-out account reads
  as signed out and a signed-in one still reads as signed in.

Run: gofmt -l clean; go vet ./... (darwin), GOOS=linux go vet -tags
nogui ./..., GOOS=windows go vet ./...; go build for all three.

Then go test -timeout 45m ./... under a sandbox HOME at base ba319a758
(load ~25). Every package was ok except two:
- internal/agent timed out with a 2s-old test running (rerun alone: ok
  1866s).
- internal/gateway failed TestRateLimitIsWaitedOut, "an hour away: passed
  on after 1.32s" against its 1s bound. That is #1971, open, a wall-clock
  bound under load and not this change; rerun alone: ok 1433s.

Rebased on d771138c4 (13 commits, including c79400556 in
agent/provider.go). At the pushed head: gofmt clean, go build for darwin,
linux nogui and windows, go vet of provider/cli/tui, and go test
./internal/provider ./internal/cli ./internal/tui all ok. No GUI file
changed, so the GUI suite was not run.

Not tried: a real Claude account signed out in Claude Code. The sandbox
test drives the same files (.credentials.json, .claude.json, logins.json).
2026-10-21 19:00:33 +08:00
yetone 4896fc3ba1 codex: a thread magpie compacted goes on after magpie is quit or disconnected (LukeMa on X)
When magpie answers Codex's compaction itself (a magpie model, Codex's
own models through magpie's accounts, a CC Switch table), the item it
returns carries encrypted_content "magpie1:"+base64(summary). Codex keeps
it in the rollout (a response_item, and the compacted checkpoint's
replacement_history) and replays it with every later turn. Sent to the
ChatGPT backend directly, it is refused: "The encrypted content for item
cmp_magpie_1 could not be verified ... invalid_encrypted_content"
(probed with a real request on gpt-5.6-luna; the same summary as a user
message was answered).

Codex's remote compaction v2 keeps exactly one Compaction item, so magpie
can't answer with a plain message instead. sessions.PortCodexRollouts
writes each of magpie's items in a rollout as the message it stands for
(codexsummary.Message: Codex's summary prefix, a newline and the summary,
as a user message), which is what Codex's own local compaction stores and
what the gateway already sends in its place, so it reads the same through
magpie and goes on without it.

- Only magpie's compaction items change; other lines keep their bytes,
  the file its line count, mode and time. An unreadable one is left out
  of a list with its replacement_history_metadata entry, as Codex's own
  ghost-snapshot strip does.
- Published as Codex publishes a compressed rollout: temp file and
  rename, under thread-writer-locks/.coordination.lock and only with the
  thread's lock free. A thread a Codex has open is left for a later pass.
  A Codex home without thread-writer-locks is left alone.
- .jsonl.zst rollouts are read and written packed.
- Passes: 2 minutes after the GUI or magpie serve starts and every 10
  minutes; on Codex Disconnect (3s); as the GUI quits (3s). The first
  pass reads rollouts written since 2026-09-24; later ones only what
  changed since the last whole pass, plus what was left held
  (codex-portable.json in magpie's folder).

Run at this series' head (on origin/main 0fe039f14):
- Real codex 0.162.1, sandbox HOME/CODEX_HOME, exec </dev/null, against a
  fake upstream. In magpie mode it auto-compacted and the rollout's
  compacted line held magpie1:. In OpenAI mode, `exec resume --last`
  failed with "Error running remote compact task: ...
  invalid_encrypted_content". After PortCodexRollouts on that home, only
  that line changed (42 lines before and after). The same resume exited
  0, and the upstream saw the summary message.
- Broken by hand. With the thread-lock TryLock check off,
  TestPortCodexRolloutsLeavesAnOpenThread went red. With the replacement
  off, TestPortCodexRollouts went red. Both green with the fix restored.
- gofmt -l clean. go vet ./... (darwin) clean, GOOS=windows go vet
  ./internal/... clean, and GOOS=linux go vet -tags nogui ./... clean.
- go test ./... -count=1 -timeout 45m: 64 packages ok, two reds.
  - internal/agent ran out of time at 2706s (load average 25 to 57), the
    known #2723/#2544. Alone, go test ./internal/agent -count=1 is ok in
    901s.
  - internal/provider TestHoldReadsMigrationsOnce: "migrations.json read
    again while held" at 2.70s. It passes alone 5 of 5. I didn't touch
    that package. Filed #3095: heldFor (1s) can run out between the
    test's two reads.

Not tried:
- api.openai.com itself after a port. The refusal was probed on the
  ChatGPT backend, and the resume ran against a fake.
- A Codex in a WSL distro. Disconnect skips it, because its locks can't
  be taken from Windows.
- The Codex app still holding a thread when magpie quits. Its lock is
  held, so the file is left for the next pass, and the thread in that
  app's memory keeps the magpie1 item until it is loaded again.
2026-10-21 03:05:24 +08:00
yetone 81a24cf8fe groups: a found group is listed as auto/<model id as the vendor spells it>
ZeroClover asked on X: Auto Group ids group/auto-<slug> can't be looked
up on models.dev. A found group is now listed and written as
auto/<model>, e.g. auto/claude-opus-5.5: /v1/models, the catalog, agent
configs, the GUI's Routing page and the CLI. Context and output limits
come from the model's metadata as before.

What stays the same:
- The internal id is still group/auto-<slug> (Group.Ref() gives the
  public one). Every old form is still accepted as input forever:
  provider.CanonicalRef turns auto/<model>[:level][[1m]] into it at the
  gateway (validateModel), keys, stats, affinity and usage, so both ids
  route to the same group and count as one.
- A key's model list allows a model by either id, group/* included
  (allows() in key_models.go).
- Hand-made groups stay group/<id>.
- A provider whose stored id is "auto" keeps its models: while one
  exists, found groups are listed by their old id (AutoRefsOn) and
  auto/<x> means that provider's model. Documented in
  docs/subsystems/gateway-routing.md.

Agent configs: SyncCatalog rewrites a field that holds a found group's
old id (renameFoundGroups), but only while the value is still what
applied.json says magpie wrote; a value the user set stays. A pick by
the old id written now is written as auto/<model> (Apply). Hidden,
picked and ordered model lists saved by the old id hold for the new one
(visible.go), and a bare model id still reaches its found group (bare.go).

Claude Code is given a dotted Claude version dashed (ClaudeSpelled), so
auto/claude-sonnet-4.5 sits in its settings as auto/claude-sonnet-4-5.
That routes to the same group, but with found groups off nothing reads
it back dotted, and Reseat took the field for changed and left the agent
on a group that was gone. Reseat now compares a group pick by its
canonical id (samePick). The old ids had no dots, so this is new with
auto/<model>.

Run at this tree (sandbox HOME, caches pinned):
- gofmt -l: clean. go vet ./...: clean on darwin, GOOS=linux -tags
  nogui, GOOS=windows.
- go test -p 4 -timeout 45m ./...: every package ok except agent and
  gateway, whose failures were the tests' expected ids (updated here)
  and two regressions now fixed (bare ids; desktop models hiding groups
  by prefix). Every failing test passes on rerun. Load average was
  ~210-290 from other sessions throughout.
- Reruns: provider, cli, codexcat ok. internal/gui: only
  TestSetAnswersWhileDevinAndProvidersHang fails (set slow/slow-1 took
  10.19s), and it fails the same in a git-archive export of 33dbdcc52.
- agent and gateway in full, -p 2 -timeout 120m: gateway ok (2996s).
  agent failed four tests that still expected the old ids
  (TestOmp/PiModelsAskedOnTheirNativeAPI, TestReseatFoundGroupsOff,
  TestReseatKeepsAFoundGroupWithAProviderOff); updating them showed the
  Reseat bug above. After the fix, go test -count=1 -timeout 120m
  ./internal/agent/: ok (1000s, load ~160-220).
- GUI files the change reaches, chromium and webkit: group-found-off and
  the routing files pass, except routing-bodies, routing-model-rest,
  routing-keys-fold and routing-request-metrics, which fail the same with
  33dbdcc52's JS.

Broken by hand and watched red, then restored: CanonicalRef in
validateModel (both-ids routing test), allows() (key tests both ways),
the Save refusal and AutoRefsOn checks in Ref/CanonicalRef (provider
named auto), catalog.Lists' preference (models.dev lookup of the part
after auto/), renameFoundGroups' applied.json check and its SyncCatalog
call (user values kept), PublicRef in visible.go, the codexcat prefix,
samePick in Reseat (TestReseatFoundGroupsOff: opus left on the gone
group).
TestBareModelIDsShared was red before the bare.go fix.

Not verified: no real agent, vendor or models.dev client run; no run on
the Windows box. Settings pickers (vision, title model) holding a saved
group/auto-... value may show it as saved. codexcat can't tell a stored
"auto" provider apart, so its models lose the "text only" hint. The
pre-existing reds above are not filed.
2026-10-20 00:18:51 +08:00
yetone 0f1666b387 provider: a built-in can be retired, its plugin serving it moved or not, and its unmoved accounts get a Move line
The owner (10-16) wants every deprecated built-in taken out of magpie,
one at a time. This is the ground for that; it retires nothing yet.

- retiredBuiltins / BuiltinRetired(id) in migrate.go name a built-in
  whose code is gone. Only an id with a mover can be retired.
- PluginServes(id) is Moved(id) or retired. Every gate that asked
  Moved(id) asks it now: sign-in, Factory keys, usage, logins, cards,
  forget, accounts, check-ins, plugin sign-in, the CLI's accounts and
  providers, the GUI's account label.
- A retired row's move.state is plugin, and its id is in onPlugins
  once the plugin is installed.
- /api/providers lists a retired subscription's built-in accounts that
  haven't moved in `unmoved` (MoveCandidate, now with the failed move's
  error and why). The GUI shows a quiet line over the Providers list
  for each, with Move / Try again (unmovedLine), in en, zh, zh-TW, ja
  and de.
- AGENTS.md and docs/subsystems/provider-plugins.md say what a retired
  built-in is.

Run at 270aa1c9c with this change:
- go test -tags nogui ./... -count=1 -timeout 90m: 66 packages ok.
- gofmt -l internal: nothing. GOOS=linux and GOOS=windows
  go vet -tags nogui ./...: clean.
- GUI, both engines, en and zh: retired-move (new, 4/4), plugin-move,
  deprecation-notice, deprecated-subscriptions, plugin-move-unserved,
  plugin-movable-review, i18n-keys: 39 pass.
- TestRetiredBuiltinIsThePlugins -count=20 (it picks a mover at random).

The Move line is the Providers list's own, not a page that could be a
plugin. It took the core's scripts to 1,427,218 bytes, which the budget
main raised in 81313b912 (1,447,000, issue 2612) already holds;
TestCoreScriptBudget passes.

Broken by hand: retired-move goes red with unmovedLine not appended;
TestRetiredBuiltinIsThePlugins goes red with BuiltinRetired's Movable
check dropped.
2026-10-17 23:10:59 +08:00
yetone dc8dcc85d1 provider: a custom Balance URL can be asked with POST, for an endpoint that answers only a POST (#2368, yaofeng)
A custom provider's Balance URL was always asked with GET, so a balance
endpoint that takes only a POST answered 405 and the card never showed.

- Provider.BalanceMethod ("" or GET, or POST with no body). It applies to
  the user's own Balance URL only; a vendor magpie knows is asked as
  before. balanceMethodOf refuses any other value before anything is sent.
- CLI: `magpie provider set <id> balance.method=POST` (GET clears it; any
  other value is refused and the saved one kept); `magpie provider <id>`
  shows "from POST <url>".
- GUI: a GET/POST segmented control (segs, not a <select>) beside the
  Balance URL in More endpoints, aria-labelled and titled in en, zh, zh-TW,
  ja and de. Check balance and Save carry it; a preset's save keeps it.
- No vendor preset or name is added. A string amount ("0.94306040") was
  already read by number(), so `$usd_balance` reads as any field does.
- docs/subsystems/providers-accounts.md says it.

Run:
- go test -run TestBalance ./internal/provider/: ok. New TestBalanceMethod:
  a POST-only httptest server, POST (any case) reads $0.94 from a string
  usd_balance, "" and GET are still GET (405 is an error), PUT, DELETE and
  a CRLF value are refused with nothing sent.
- go test -run TestProviderSetBalanceMethod ./internal/cli/: ok.
- Broken by hand: the request always GET turns TestBalanceMethod red
  ("asked GET, want POST"); balanceMethodOf passing any method turns it red
  (PUT and DELETE sent); the CLI taking any value turns
  TestProviderSetBalanceMethod red; the Check balance body without
  balanceMethod turns 20 of 21 balance-method.test.cjs cases red, and
  origin/main's app.js all of them.
- GUI: balance-method.test.cjs 42/42 (Chromium and WebKit, 1100 and 420,
  en, zh, zh-TW, ja, de, saved GET and POST: opens on the saved method,
  named and titled in the language, fits beside the URL with no page
  scroll, the other pick goes in the check and save bodies). Siblings:
  balance-parts, balance-field-default, balance-fix, catalog-hint,
  duplicate-pause, key-balance-card, local-address, provider-base-api,
  provider-auth-header, provider-gemini, provider-search,
  provider-url-each-api, gui-de, gui-ja, gui-zh-tw, i18n-keys: 250/250.
- Real use: the built binary in a sandbox HOME, a custom provider at a
  local server that answers GET 405 and POST {"usd_balance":"0.94306040"}.
  Default: "unavailable 405 Method Not Allowed"; balance.method=post:
  "$0.94 from POST …/api/check-balance $usd_balance", the server saw one
  POST with Content-Length 0 and the Bearer key; balance.method=PATCH
  refused. NanoGPT itself was not asked (no key here).
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
  go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.

Suite run here: HOME=<sandbox> go test -tags nogui -timeout 45m ./...: 62
ok, internal/gui FAIL only on TestSetAnswersWhileDevinAndProvidersHang
(a state took 11.97s, load ~180), open as #1375; it passes -count=2 alone.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone 82f48f0935 gateway, provider, gui: a provider set to compact natively is asked Codex's compaction_trigger as sent and its sealed compaction goes back unchanged; a checkpoint stays with its writer (#1099)
A new per-provider option, off by default. With it on, Codex's
compaction_trigger reaches the provider as Codex sent it, and the
provider's encrypted compaction item goes back to Codex unchanged instead
of magpie's magpie1: summary. Off, nothing changes.

Where it can be on (provider.CarriesCompaction): a provider with a
Responses API (Sub2API and other OpenAI relays, a remote magpie), a
ChatGPT (codex) account, and the built-in GitHub Copilot on its GPT
Responses path. Copilot's Claude models are asked on chat completions, so
they still get magpie's summary (CompactsOn). A group compacts natively
only when every member does.

No silent downgrade:
- A turn carrying a sealed compaction goes only to the key or account that
  wrote it (compactions.json beside affinity.json, 0600, 1024 entries /
  30 days). With none left, Codex gets a 400 saying the conversation was
  compacted natively on <who>, not a summarised or dropped context.
- A provider whose request would have to be translated (not relayed) is
  refused with a 400 instead of losing the item.
- The upstream's own refusal goes back to Codex as it came, one call.
- base_instructions and Codex's identity are untouched.

Turning it on:
- GUI: the provider editor's Compaction row, "Codex compacts on this
  provider" (shown only where the wire can carry it; zh, zh-TW, ja, de).
- CLI: magpie provider set <id> compaction=native|magpie. A provider that
  can't carry it is refused.

Run on origin/main 00501401a, then rebased onto 84f14e555 (no file in
common) and reran gofmt, vet and go test for gateway, gui, provider,
cli, usage and sessions: all ok. Rebased again onto 8d2a4a7da (gateway.go
and codex_backend.go changed on both sides, merged clean) and reran
gofmt, vet (darwin, linux nogui, windows) and go test for gateway, cli,
provider and gui: all ok. Last rebased onto 7a3fed6bb (only
gateway-routing.md shared, merged clean): gofmt, vet on all three OSes,
and go test -run for the native compaction, sink, CORS, rebind and origin
tests in gateway plus the provider tests: ok.
- gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows:
  clean.
- set -o pipefail; go test -timeout 40m ./...: every package ok but
  internal/provider's TestCopilotSecretToolUsername (copilot_cli_test.go:93
  token "", 10.05s), the open load flake #1627; it passes alone -count=5
  and this change doesn't touch it.
- GUI (node --test, chromium + webkit): the provider-editor files, 946
  pass, 0 fail; the new provider-native-compaction.test.cjs runs 5
  languages at 1100 and 420 (60 cases).
- New Go tests: TestNativeCompactionPassesTheTrigger, ...RefusalGoesBack,
  ...StaysWithItsWriter, ...Copilot (gateway), TestCarriesCompaction,
  TestSetNativeCompaction (provider), TestProviderSaveNativeCompaction
  (gui), TestProviderCompactionPair (cli).

Broken by hand, each red, then restored:
1. codexInputAs dropping the trigger even when native: all 4 gateway
   tests fail.
2. checkpoint filter off: StaysWithItsWriter fails.
3. forced relay off: all 4 gateway tests fail (the web_search tool sends
   the turn to translation).
4. GUI save sending nativeCompaction false: the GUI test's first case
   fails.

Not tried: any real upstream (Sub2API, ChatGPT, Copilot). Copilot may
refuse a compacted history holding web_search items; that refusal would
go back to Codex as-is.
2026-10-15 05:20:17 +08:00
yetone 22512cde53 provider, gateway: rest-cap off never rests a provider's keys after an unknown failure (Kismet Alan on Discord)
A relay or account pool fails now and then with errors that say nothing
of why (a 5xx, a dropped connection), and the next request often goes
through. Every such failure rested the key or account a minute, doubling
up to 10, and `rest-cap` could only move that cap (1 minute at least;
`off` read as `default`).

`magpie provider rest-cap <id> off` (provider.RestCapOff, restCap: -1 in
providers.json) now has a failure that says nothing of why (failOther)
rest nobody and not count toward the backoff: restAfterMarked returns a
Rest by "off" with no time left. What says why still rests as before: a
401 or 403, a model not served (restID), an account's window full, a
rate limit (magpie's own 30-minute cap; RestCapOr treats off as unset),
quota, credit, a restriction. `rest-cap <id> 30s` is turned away and names
1m and off (the first rest is a minute already). The Routing page tells a
try rested by "off" as not resting (one new string, zh/zh-TW/ja/de).
No "fail N times before switching" counter: a failed try already moves
the same request on to the next key or member, so a count would only
keep requests on a failing upstream longer.

Run:
- TestRestCapOff (gateway), TestRestCapCmd (cli), TestOwnRestCap: pass;
  each goes red with the change taken out by hand (the early return
  disabled: "#1 500: rests 59.99s by backoff"; restMinutes in place of
  restCapMinutes: "off: <nil> 0").
- routing-rest-off.test.cjs: 20/20 (chromium, webkit; 1100, 420; en zh
  zh-TW ja de); red 10/10 with the "off" case renamed.
  routing-wb-restricted 20/20. rest-try-now and routing-model-rest fail
  a varying few under load average 200-420 here, and fail more on
  origin/main 331c27703 run at the same time; neither reads "off".
- gofmt -l clean; go vet darwin (provider, gateway, cli, gui), GOOS=linux
  -tags nogui and GOOS=windows (provider, gateway, cli).
- go test ./... with pipefail, sandbox HOME: every package ok except
  agent, gateway and library, which hit the 10m timeout under load
  average ~200 (no test hung: each stack shows a different test seconds
  in). Rerun with a longer -timeout: library ok (603s), gateway ok
  (1572s) and agent ok (1457s).
Not tried: a real relay; the change is in the rest bookkeeping only.
2026-10-14 20:49:20 +08:00
yetone ef0c515eb0 provider: a sub2api or new-api account query left without its token asks the key's query instead (lx_78654 on Discord)
The editor's "Use …/api/v1/user/profile" sets the Balance URL to the
sub2api panel's account query, which only the login JWT can ask. Its
Remove button clears the token but not the URL, so the profile query was
then asked with the key, refused with 401, and the Usage card said
"Allowance unavailable" for good.

keyQueryOf now asks the same panel's key query when the Balance URL is
an account query (sub2api /api/v1/user/profile, new-api /api/user/self)
and no token is set: /v1/usage and /api/usage/token, with the key, their
own default field unless the user wrote another. The saved URL is left
as set, so pasting a token again asks the account query again. A
provider whose Headers carry its own Authorization or Cookie is asked as
set. It covers every reader: the Usage page and `magpie quota`
(KeyBalances), the editor's Check balance, routing's key windows
(sub2APIKeyLimits), and `magpie provider <id>`, whose "from" line now
says the query actually asked (BalanceQuery).

Run:
- TestAccountQueryWithoutTokenAsksTheKey (httptest sub2api + new-api):
  JWT, removed, JWT again; new-api without token; custom field kept;
  account query never asked with the key; own Authorization kept.
  With keyQueryOf a no-op it fails with the reporter's 401 card.
- Sandbox CLI (scratch HOME, fake sub2api on 127.0.0.1): old binary,
  after `provider set sub2 balance.token=`, `magpie quota` shows
  "401 Unauthorized…"; new binary shows "$7.25 left", from /v1/usage.
- go test -tags nogui ./internal/provider/ ./internal/cli/ ./internal/tui/,
  and internal/gateway's balance, allowance, quota and key-limit tests.
  The full `go test -tags nogui ./...` passed every other package;
  internal/gateway and internal/agent ran out of time (10m, then 40m)
  with the machine at a load average of ~300-370, the tests running at
  the deadline seconds old, so not a hang; neither run finished.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Not tried: a real sub2api or new-api account; the GUI not clicked
through (no asset changed, it reads the same KeyBalances).
2026-10-14 19:47:16 +08:00
yetone 1a5128747b cli: magpie provider refresh-every and auto-include set a list's schedule and rules (#2135)
`magpie provider refresh-every <id> 6h|1d|off` and
`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'|none` set the
fields the previous commit added; `magpie provider <id>` shows them, and
`magpie provider refresh` prints the models its rules took.

TestRefreshEveryAndAutoIncludeCmds: a too-short or unreadable time and
a plain id as a rule are refused, the rule takes the current matches,
and none/off clear both while keeping the picks. Run with the go test
in the previous commit's body.
2026-10-14 16:40:24 +08:00
yetone d9ca84a2f4 gateway: built-in TLS, magpie serve/web/daemon install --tls-cert --tls-key, reloaded on renewal (RoderickZH)
magpie serve, magpie web and magpie daemon install take --tls-cert <file>
--tls-key <file> (or MAGPIE_TLS_CERT / MAGPIE_TLS_KEY). The gateway and the
web UI on its listener then serve HTTPS to other computers. Without them
nothing changes.

- Half a pair, a file that doesn't parse, or a flag with no value is
  refused at start with a message naming the missing flag.
- The pair is re-read when either file's mtime or size changes (certbot
  renewal), with no restart. A renewal that doesn't parse keeps the
  certificate already served and is logged once.
- Other computers get HTTPS only. Plain HTTP from them gets net/http's
  400 "Client sent an HTTP request to an HTTPS server".
- This computer (loopback, or a peer address equal to the local one) may
  still use plain http on the same port. Its connections are sniffed on
  their own goroutine (a first byte of 0x16 is TLS) for up to 10s, so a
  silent client holds nobody else up. gateway.URL() stays
  http://127.0.0.1:<port>, which agents, MCP servers, ServedBy, the
  healthcheck and daemon status all use, and no certificate covers
  loopback.
- WSL NAT and containers count as other computers.
- ALPN is http/1.1 only (hijacked connections and websockets need it), with
  TLS 1.2 as the minimum.
- Printed links, LAN addresses, publicURL, the serve/web banners and
  daemon install show https:// for other computers' addresses.
- The DNS-rebinding Host checks (foreignPage, rebound, the MCP
  loopbackHost) don't depend on the scheme and are unchanged.
- daemon install carries MAGPIE_TLS_* into the unit or plist. A reinstall
  or `daemon web on` that names no certificate keeps the installed pair,
  and --no-tls removes it.
- Docs: reference.md gets an HTTPS section that names Caddy as the
  alternative, gateway-routing.md gets a TLS row, and docker.html (en,
  zh, ja) gets the env rows.

What was run:
- New tests: internal/gateway/tls_test.go (others HTTPS-only, this
  computer both, a silent local client holds no other, renewed
  certificate served, CheckTLS, addresses, Relisten keeps TLS),
  internal/cli/tls_cli_test.go and daemon TestInstallCarriesTLS (linux
  and darwin, paths with space, %, & and ").
- Each was broken by hand and went red: no wrap in listen, no reload, a
  synchronous sniff, a bad renewal dropping the certificate, http in
  publicURL or the pinned LANURLs, the carried entries removed, and
  keepTLS as a no-op.
- Real use under a sandbox HOME, with a self-signed pair, on
  0.0.0.0:3461:
  - Half a pair, a garbage certificate, a flag with no value, and the
    env set to half a pair each exit 1 with the message.
  - curl -k https://127.0.0.1 and https://<LAN IP>/v1/models with a key:
    200. Plain http on loopback: 200.
  - The cert files were swapped for a second pair while it ran.
    openssl s_client then showed the new CN and serial, and curl
    --cacert with the new pair got 200. A junk key file then kept the
    second pair, logged once.
  - From the Windows box over the LAN: plain http got 400; https with
    the key got 200, and without it 401.
  - magpie web --addr 0.0.0.0:3462: https network links. From Windows,
    http got 400 and https with the key got 303.
- gofmt -l clean. go vet passed on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -tags nogui for ./internal/cli, ./internal/daemon, and the TLS
  tests of ./internal/gateway and ./internal/gui: all pass at the rebased
  head.
- Two reds in the full suite (`go test -tags nogui ./...`) are the same
  on origin/main f074996d9; both are filed:
  - TestGatewayHeldByAContainer failed 2 of 5 there (#2107).
  - The gateway package runs past go test's default 10m under load:
    1208s on main and 1221s here, both passing with -timeout 40m
    (#2108).
2026-10-14 13:36:03 +08:00