Commit Graph
37 Commits
Author SHA1 Message Date
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
yetone bf25842714 gateway: a provider's own cap on how long a key that keeps failing rests (#2008, Gaudi-XIX)
A key that keeps failing doubles its rest from a minute up to 10 minutes,
and one rate limited again as soon as its rest is over up to 30; both
caps were fixed, so a free key down for hours was asked again every 10
or 30 minutes all the while.

`magpie provider rest-cap <id> 4h` (Provider.RestCap, minutes, at most
MaxQuotaRest, 8 days) sets where both ladders stop for that provider's
keys and accounts (RestCapOr in restAfterMarked's default branch and in
rateRest); `default` gives back the gateway's own. A time the vendor names
still stands over it. Unset, nothing differs. It is kept by the editor's
save, the account copy and normalize.

Run: go test -tags nogui ./internal/provider ./internal/gateway
./internal/cli ./internal/gui (temp HOME). Broken by hand: both ladders
back on the fixed caps fail TestOwnRestCap (rate-long #6: 30m, want 32m);
the GUI keep removed fails TestSaveKeepsQuotaResetAt. Not tried against a
real vendor's outage.
2026-10-14 05:22:40 +08:00
yetone 064cffdbfd gateway: a key out of a daily allowance rests until the time of day it comes back (#2008, Gaudi-XIX)
A free tier's "You've reached today's free-model token quota" says
nothing of when it is back, so it rested 15 minutes (or the provider's
own quota-rest), and was asked again all day. A vendor Retry-After over
an hour was cut to the hour, and that hour then stood over the user's own
longer rest.

- Provider.QuotaResetAt: "08:00" on this computer's clock, or
  "00:00+08:00" on the vendor's. `magpie provider quota-rest <id> until
  08:00` sets it; a number of minutes set after it replaces it, and
  default clears both. normalize drops one that isn't a time of day.
  It is kept by the editor's save and the account copy.
- restAfterMarked's quota branch rests until its next occurrence
  (OwnQuotaRest). A time the vendor names, or a window's end, still
  stands over it; a Retry-After stands unless it was cut to longestWait
  while the user's own rest is longer.
- Defaults are unchanged: nothing set, nothing differs.

Run: go test -tags nogui ./internal/provider ./internal/gateway
./internal/cli ./internal/gui (temp HOME). Broken by hand, each fails:
OwnQuotaRest replaced by QuotaRestFor (TestQuotaRestsUntilTheTimeOfDaySet,
3 asserts), the Retry-After guard removed (the 7200 case), the GUI keep
removed (TestSaveKeepsQuotaResetAt), default not clearing it
(TestQuotaRestUntil). Not tried against a real free-tier vendor.
2026-10-14 05:22:39 +08:00
yetone 80211e7075 provider: a balance field sums, maxes or counts a list's items, and one amount it can't read is "—" (#1993, RicardoWYP)
A relay's /api/subscription/self tells usage per subscription, a list.
A balance path could only name one index (subscriptions.0), so several
active subscriptions read as the first, ".0 + .1" failed whole when only
one existed, and a weekly cap of 0 ("divides by 0") hid every amount of
the field.

Now a path goes through a list's items with "*" (a.*.used), or those
that match with "[key=value]" / "[key!=value]" (a[status=active].used,
also on an object: a.*.subscription[status=active].used). Such a path is
several values, made one by sum(), max(), min() or count(); arithmetic
between two of them goes item by item, so max(a.*.used / a.*.cap) is the
fullest window. Several values left outside a function are an error
naming the functions, not a guessed sum. Within a list an item without
the path, or divided by 0, is left out; max/min of nothing is an error.

In a field of several ";" amounts, one that can't be read shows "—"
(BalancePart.Error says why, as the card's hover on the Usage page and
in the panel) and the others still show; the read fails only when none
can be read. A single amount alone still fails as before.

The GUI hint (zh, zh-TW, ja, de) and `magpie provider` help say the new
syntax.

Run:
- TestBalancePathLists, with the reporter's literal JSON: against the
  old balance.go it fails ("nothing at \"sum\" in the reply", and the
  "—" cases error); passes now. TestReadBalancePath's one case that
  expected a whole-field failure with one bad amount now expects it
  only when every amount fails.
- go test -tags nogui ./internal/provider ./internal/cli ./internal/gui
  under a temp HOME: ok.
- balance-parts, gui-de, gui-ja, gui-zh-tw, i18n-keys in Chromium and
  WebKit: 14 pass. With the title lines removed, balance-parts fails on
  the missing hover text.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on
  provider and cli.
Not tried against the reporter's real relay.
2026-10-14 04:37:43 +08:00
yetone c4e6abf3cc gui, cli: a model id typed with a space in it stays one model, "Opus 5.5" not Opus and 5.5 (#1976)
elonnzhang on #1976: on a Baidu OneAPI relay, typing `Opus 5.5` in the
provider editor's add box (or the add form's Models field) and pressing
Enter added two models, `Opus` and `5.5`. Both read the box with
split(/[,\s]+/), while their hints say "comma separated".

- app.js: one typedIds() for both, split at commas (and line breaks)
  with each id trimmed. chosenIds() (the add box, and an id left in it
  at Save) and the add form's Models field use it.
- CLI siblings, which split the same way: `magpie provider set
  models=` now splits at commas only. A group's models=, models-=,
  fast= and weight= split at commas, and an item with a space that
  names no model the group can have is still split at its spaces, so
  `models=m,b/x a/m` (TestApplyGroupPairs) still works. levels= and
  `magpie visible` (effort levels and family names) are unchanged.
- Tests: the reporter's two GUI assertions in models-add-and-icons
  (from their fork branch). A new model-id-space.test.cjs covers both
  boxes in en, zh, zh-TW, ja and de, Chromium and WebKit, at 1100 and
  420 wide. TestModelIDsKeepTheirSpace covers the CLI. The fork's change
  to provider-add-models.test.cjs is not taken: filling the Models field
  there replaces the picks it holds, so it failed on its own terms.

Run: on the old split, model-id-space fails (4/4 for en and de at 420
in Chromium) and TestModelIDsKeepTheirSpace fails (models = ["Opus"
"5.5" ...]). With the whole-item check forced off, it fails on members.
With the fix: model-id-space 40/40, models-add-and-icons 4/4 and
provider-add-models 4/4 pass. `go test -tags nogui ./internal/cli` is
ok. gofmt is clean, and go vet passes for darwin, linux (-tags nogui)
and windows.
Not tried: a real relay with a spaced model id served end to end.
2026-10-13 18:16:03 +08:00
timonwong 79099d6adb provider, gui, tui: Ollama, LM Studio and oMLX take an address, so a server on another port or computer is the preset's provider (#1165)
The three On this machine presets were pinned to localhost and their
default port: one started on another port, or on another computer on
the LAN, had to be rebuilt as a custom provider or typed URL by URL in
the CLI. They now take an Address (scheme, host and port), and each of
their URLs keeps its own path there (provider.AtAddress, AddressOf; no
scheme means http, only http/https, port 1-65535, a pasted path is
dropped, anything else refused with nothing changed).

- GUI: the add and edit editors have a Server address section under the
  key, folded unless the saved address isn't the preset's, opened and
  focused on a refused one. The Endpoints, Test and Refresh follow what
  is typed; URLs are sent only when the address changed, so ones set
  apart (an import, the CLI) are left alone. zh, zh-TW, ja, de.
- TUI: adding a local preset asks for its address before the key (Enter
  keeps the default), and w edits it.
- CLI: the usage shows provider add ollama url=... anthropic=....
- LM Studio's and oMLX's notes say "port N by default".

timonwong's PR head e63cf18e, merged onto main, which had given oMLX a
decision API (#1641) since: presets.go keeps main's oMLX Decide; app.js
keeps both the Vertex block and the address one; the docs row and -run
list take both.

Run: see the next commit.
2026-10-13 13:47:58 +08:00
AnxForever 6794cccd53 cli: models and visible find a WSL agent by its id, in any case (#271)
`magpie models --agent` and `magpie visible <agent>` turned the typed name
into an agent through usage's AgentOf, which knows the built-in agents
only, so a WSL agent's id (claude@wsl:Ubuntu) was "no agent". Both now
use agent.Find, as every other agent command does, and visible keeps its
key lowered, as VisibleTo looks it up.

Landed from #271 (AnxForever), merged onto main by hand. The test moved
from the repo root into internal/cli, where the code it tests lives, with
one more case added: TestWSLAgentByIDInModelsAndVisible.

Run (merged onto 5b14ebf49): gofmt clean; go vet darwin, GOOS=linux -tags
nogui, GOOS=windows ok; go test -tags nogui ./... ok (agent, gateway,
plugin and provider passed on a rerun with -timeout 45m, after timing out
at 10m under load average ~30). Break-check: with providers_cli.go and
visible_cli.go put back to main's, TestWSLAgentByIDInModelsAndVisible
fails. Not run: a real WSL distro.
2026-10-13 09:56:06 +08:00
yetone 248a68598c gateway, provider, gui, cli: a key+URL provider may be sent the agent's own User-Agent in place of magpie's (#1851)
Every forward went with User-Agent magpie/<version>. A coding plan that
serves only the agents it names (pi, OpenCode, Claude Code…) knows them by
their User-Agent, so it turned magpie away.

What changed
- provider: PassUserAgent (passUserAgent in providers.json), off by
  default. PassesUserAgent takes it only for a key+URL provider: never a
  signed-in account, a plugin's, or a vendor whose own client magpie goes
  as (OwnClient: OpenCode, Cline, Kilo, another magpie). A copy keeps it.
- gateway: userAgentFor in forwardOnce (chat, Anthropic, Responses,
  Gemini, count_tokens) sends the inbound User-Agent unchanged where the
  provider passes it on. It sends magpie's where it doesn't, where the
  agent sent none, and on magpie's own requests (magpiesOwn: magpie/…,
  magpie-router/vision/search, the image tool's "<client> magpie-image/1",
  which is built from MCP clientInfo, not a User-Agent). magpie never
  invents another client's. The claude-cli/Codex header copies, the
  OpenCode/Cline/Kilo overrides and account signing run after it as
  before, and the user's header.User-Agent is put on at signing, so it
  wins.
- gateway: embeddings, images and videos (retrieveFrom, sendWith,
  remoteVideoContent) now stamp the same for a key+URL provider through
  stampUA, from the caller's User-Agent kept on the request ctx
  (caller.ua, withCaller). Before, they went with Go's default
  (Go-http-client/1.1). Account and remote-magpie paths are untouched.
- cli: `magpie provider set <id> user-agent=agent|magpie`, refused for a
  signed-in account; `magpie provider <id>` shows it.
- gui: the provider editor's User-Agent row, "Send the agent's own
  User-Agent", with an explanation, for a provider with a key only (the
  JSON says ownClient for presets and providers); en/zh/zh-TW/ja/de.
  The TUI only adds presets, so it has no field for this.
- docs: reference.md (provider set) and subsystems/gateway-routing.md.

What was run
- gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -count=1 ./internal/gateway ./internal/provider ./internal/cli
  ./internal/gui: all ok (sandbox HOME, private GOCACHE).
- TestUserAgentPassedOn covers 7 routes (messages, count_tokens, chat,
  responses, gemini, embeddings, images) x off / on / on with no UA / on
  with magpie-router/1 / on with the image tool's UA / the user's header
  with it on and off. TestUserAgentAccountUntouched: a Factory account
  with passUserAgent in providers.json is still asked as factory-cli/.
  Also TestUserAgentClaudeCodeAsBefore, TestUserAgentFor,
  TestPassesUserAgent, TestAddCopyPassUserAgent, TestProviderUserAgentPair.
- Broken by hand, each went red: forwardOnce back to magpie's UA (5
  routes red); stampUA removed from embeddings/draw (both red, seen as
  Go-http-client/1.1); PassesUserAgent ignoring accounts/OwnClient;
  magpiesOwn dropped (the internal UAs leaked on all 7 routes); the GUI
  row shown for OpenCode and Save not posting it.
- provider-user-agent.test.cjs: 60/60 in chromium and webkit, en, zh,
  zh-TW, ja, de, at 900 and 440 wide. The provider/editor/add/i18n GUI
  tests in chromium: 244/244.

Not run
- Not tried against a real coding plan that checks User-Agent, nor with a
  real agent through a live gateway. Videos have no test of their own
  (they go through sendWith, which the images test covers).
- The GUI suite was not run in full; the Windows box was not used.
2026-10-13 02:56:34 +08:00
yetone 10d60b1899 provider: a provider saved with Select none serves no models, unlisted or not (#1818)
Select none saved `models: []`, which omitempty wrote as no models key at
all, so the provider read back as "no picks" and served the first 24 of
the vendor's list on /v1/models, in auto groups and on the card, while
the editor said none would be served.

What changed:
- Provider.NoModels (json noModels) records the choice; ServesNone() is
  NoModels with no picks. A file with no models key still serves the
  vendor's list as before.
- Exposed() is empty for it, so the catalog, /v1/models and auto groups
  leave it out; resolveIn refuses an explicit pid/model to it; listedBy
  and Deciders skip it (a decide-only provider is still a decider).
- SetModels and normalize clear NoModels once there are picks.
- GUI: the editor sends noModels on Save, an edit that omits it keeps it,
  the card's exposed count is 0, the hint says nothing is served; with
  unlisted the dashed chips explain they are only for groups. Strings in
  en, zh, zh-TW, ja, de.
- CLI: `magpie provider models <id> none`.
- docs/subsystems/providers-accounts.md describes it.

Decision (owner delegated): Select none means none, whether or not
unlisted is on; unlisted keeps meaning "hide from the list, still
usable by groups that name it".

Run:
- go test ./internal/provider ./internal/gui ./internal/cli -count=1
  (green; second pass ran too) with private GOCACHE and sandbox HOME.
- Broke Exposed's ServesNone check: TestSelectNoneServesNone red
  ("exposed 24"); broke resolveIn's: red ("watched/m0 resolved"); broke
  the GUI keep line: TestProviderSaveSelectNone red ("exposed 24").
- GUI tests chromium + webkit, 5 languages: provider-none-picked 20/20,
  provider-draft-picks 10/10 (red with noneChosen broken), plus 12
  related model/group/editor tests green.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows clean for the
  three packages.

Not run: the gateway package; Codex native model narrowing is unchanged.
searcher-pick.test.cjs fails 3 webkit cases (hover timeout) identically
on the unmodified base 556c01c80, unrelated.
2026-10-12 23:45:06 +08:00
yetone af7d97fa2f gateway: a Responses provider set codex=as-sent gets Codex's requests as Codex sent them, for a relay that checks they are Codex's own (#1758)
A relay that checks a request is Codex's own answered magpie 400
"Codex 客户端请求特征无效" (10014). magpie fits every Codex request
for a Responses backend that isn't OpenAI's: Responses Lite's
additional_tools item is lifted into tools (#350), the tool search
goes as a function, and OpenAI-only fields such as
stream_options.reasoning_summary_delivery are left out. The reporter
found that the relay takes the request when additional_tools is left
as an input item, and that the lifted shape is what it refuses.

The lifting stays the default, because backends that aren't OpenAI's
refuse additional_tools or silently drop it (#350). A provider can now
opt out: `magpie provider set <id> codex=as-sent` (`codexAsSent` in
providers.json; `codex=default` turns it back off). With it on, a
request from Codex (fromCodex: Codex's User-Agent or originator) goes
as Codex sent it, with only its model name swapped. Codex's own
headers go with it as before. A subscription account is never sent
this way, and the GUI's provider save keeps the setting.

What was run:
- TestCodexAsSent: by default the request is still fitted; with
  codexAsSent the upstream gets exactly what Codex sent, with model
  m1, X-Codex-Turn-Metadata and the Responses Lite header. It fails
  on the old gateway.go and passes now. TestAdditionalTools and the
  gateway's Codex tests pass.

Not verified: not tried against the reporter's relay. Their check
was made by hand outside magpie, so which other fields that relay
looks at is not known. There is no GUI control for the setting
(CLI or providers.json only).
2026-10-12 22:42:47 +08:00
yetone ff930886a2 gateway: keys all out of their allowance are answered from their rests with a Retry-After, not asked again on every request, and a key listed twice is asked once (#1772)
A fleet on four Ollama Cloud keys, every one out of its weekly allowance:
each new request asked every key again (the first twice) and answered
429 with no Retry-After, so an agent that waits as told asked again at
once, and the vendor saw four refused requests a turn.

What changed:
- The first key twice: the reporter's providers.json named the first key
  in "keys" as well as "key". KeysOn now lists a key once.
- When every key left for a request rests out of its allowance (a 429 or
  402 that failure() calls quota or credit, keys only), the request is
  answered from the rest without asking: the vendor's own words, "not
  asked again before HH:MM", and Retry-After until the first of them is
  back (quotaHeld, soonestBack). Accounts are left out, so autoReset
  can still spend a reset for them; a 403 or 400 worded as quota is
  asked as before.
- The last key out of its allowance now rests as the ones before it do
  (before, the last one left was never rested), and a 429 the vendor gave
  no Retry-After for gets the soonest rest's end as one.
- A provider can set how long its keys rest when the vendor says nothing
  of when the allowance is back: quotaRest (minutes) in providers.json,
  or `magpie provider quota-rest <id> 7d`; default stays 15 minutes, at
  most 8 days. A time the vendor names (resets_at, Retry-After, a
  window) still wins. A GUI save keeps it.

What was run:
- TestAllRestingAnswersFromRest, TestFirstKeyListedTwiceAskedOnce and
  TestOwnQuotaRest fail on the old code (no Retry-After, keys re-asked;
  "dead-1 dead-1 dead-2 ok-3", the reporter's log); they pass now, with
  TestQuotaHeldOnlyForKeysOutOfAllowance, TestDeadChainWalksEachOnce and
  TestRestMinutes. The mock answers with the reporter's literal 429 body.
- go test -tags nogui ./internal/provider ./internal/gui pass. A gateway
  package run at load ~60 hit its 20m timeout mid-suite with only
  TestMaxRPM* red; those pass 8/8 alone here and on origin/main
  17c12621b (timing under load, filed as #1791).

Not verified: no run against real Ollama Cloud keys; quotaRest has no
field in the provider editor (CLI and providers.json only).
2026-10-12 22:42:46 +08:00
yetone 94aa153973 tui, provider, serve: a signed-in account's models are fetched at start, so Routing offers Cursor's whole list without m (#1789, reyoung)
The terminal and `magpie serve` never called provider.FetchNew, which the
window calls at start: a signed-in Cursor account's list exists only at
Cursor, so the TUI's Routing pickers (and a headless gateway's /v1/models)
offered the fallback cursor/auto alone until the list was fetched by hand
with m on the Providers page.

- tui: Init fetches the new lists (fetchModelsCmd, alongside the catalog
  sync). A model picker open when they arrive (Routing members, the
  classifier, a provider's models, an agent's model field) is filled in
  place through its relist, keeping its filter and the model under the
  cursor. A list left missing (no network) is asked for again a minute
  later (modelsRetry). Built on reyoung's branch and test.
- serve: FetchNew at start, again each minute while a list is missing.
- provider: FetchNew reports whether a list is missing, and waits for a
  CLI asked who is signed in for the first time (awaitIdentities), then
  lists the accounts again. With the real Cursor account in a fresh
  sandbox, `cursor-agent about` answered after a look's 3s firstAsk, so
  FetchNew saw no Cursor account and `magpie serve` still listed 1 model
  with the TUI fix alone. The window's startBackend gets the same wait.
- docs: providers-accounts.md says who fetches the lists and when.

Run:
- internal/tui TestTUIFetchesSubscriptionModels (6 views) and
  TestTUIAsksAgainForAMissingList, -race x3; red with the Init fetch,
  the relist, the cursor restore or the retry tick each removed by hand.
  A first `about` slowed to 12s injected: passes (the test re-asks).
- internal/provider TestFetchNewWaitsForASlowSignIn: red without
  awaitIdentities (no provider "cursor"); TestFetchNewAccount covers the
  missing result.
- Real Cursor account, sandbox HOME with a keychain holding only Cursor's
  two items: TUI on main showed cursor/auto only in Routing; the fix shows
  the full list and "24 models" on Providers. `magpie serve`: main 1
  Cursor model at /v1/models, the fix 24 within 5s.
- gofmt -l, go vet (darwin, GOOS=linux, GOOS=windows), go test ./... in a
  sandbox HOME.

Not tried: Linux and Windows real Cursor CLIs (the fake CLI tests skip on
Windows); Devin's CLI identity goes through the same wait but wasn't
tried with a real account.
2026-10-12 20:49:41 +08:00
yetone 23e764d0e0 cli: magpie's commands move from the root into internal/cli; the root keeps only main.go
The root held 89 .go files (30 commands, 59 tests). They move as they are
to internal/cli (package cli), with git mv so history follows them. The
only code change is main() becoming cli.Main(version): the root's new
main.go keeps `var version` in package main, so -ldflags "-X
main.version=…" in the Makefile, the Dockerfile and magpie-releases, and
every workflow, work unchanged. go-winres's rsrc_windows_*.syso still land
next to package main in the root.

Tests that read testdata by a root-relative path now go up one level
(../plugin/testdata/fake, ../sessions/testdata). Five subsystem doc links
point at internal/cli/.

Run:
- go build ./..., gofmt -l, go vet on darwin, linux and windows (nogui)
- builds with tags production, dev, "production nogui"; windows
  -H windowsgui; linux CGO_ENABLED=0
- make release-cli TARGETS="darwin/arm64 linux/amd64 windows/amd64
  android/arm64" VERSION=9.9.9-tidy: all four built, binary prints
  "magpie 9.9.9-tidy"
- docker build --build-arg VERSION=7.7.7-tidy: container prints
  "magpie 7.7.7-tidy"
- go test ./internal/cli (default and nogui): 152 tests, the same count
  as the root on main
- go test ./...: all packages pass (agent, gateway, library, provider
  timed out at 10m under other sessions' load and passed rerun alone
  with -timeout 40m; none of them changed)
- the built binary in a sandbox HOME: version, help, ls, providers,
  claude, and an unknown command's error
2026-10-12 20:40:22 +08:00