Commit Graph
16 Commits
Author SHA1 Message Date
ggbdpq 339ff564e6 fix(gateway): skip a nested group's effort classifier when the group above picked (#4358)
A group reached through a parent group runs its own classifier when it is
effort=auto, even after the parent's classifier already picked the turn's
reasoning: the request goes out at the parent's pick (the outermost pick
stands, gateway.go), so the group in it pays for an answer the turn throws
away. On one reporter's day the group in it answered 27 of 28 such turns,
2-8 s each, and 14 of the 28 parent picks discarded the answer.

ruleFor now takes the pick a group above it already made: with one standing,
the classifier is not asked for the effort again. The intents, when the
group's rules have them, are still asked — they are the group's own routing.
The trace says why nothing was asked. The fallback keeps working: the group
in it is asked as before whenever the group above gave no pick.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-02 07:40:21 +08:00
yetone 9162277b91 routing: Until used up stays on the next account once the first is used up (dzxx0496)
dzxx0496 on Discord: with free accounts one after another, the first used
up, requests went to the second; when the first renewed they went back to
it ("如果第一个恢复了,它又优先用第一个了"). No routing did what they asked:
In order and Smart both put the first back first.

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

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

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

Run on mote (macOS) at origin/main 699ddf152 with this commit and its
two neighbours (nb5p chip, dzxx0496 renewal, dzxx0496 Until used up).
Pushed on b2145eac1, whose five commits since change app.css and app.js
only for a key row's chips; at the pushed tree gofmt, the gui, routes
and gateway vets (Linux nogui, Windows), TestCoreScriptBudget (core
1,532,891), the Drain Go tests and 11 GUI files (gateway-model-chip-
height, routing-drain, routing-renews-stay, routing-behind-why,
routing-group-strategy, routing-save, builtins, i18n-keys, gui-de,
gui-zh-tw, key-row-chips-fit) were run again: 190 of 190 ok.
- gofmt -l clean; GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./... and go vet ok.
- go test internal/routes, internal/gateway, internal/provider,
  internal/cli, internal/tui, plugins/rotation: ok; internal/gui's
  TestCoreScriptBudget ok (core 1,532,816 of 1,533,105).
- GUI: routing-*, builtins, gateway-model*, model-chip*, i18n-keys,
  gui-* and codex-credits-last in both engines: 2211 tests, 68 red,
  none new: model-chip-steady 20 (#4388), gui-ja's {agent} string
  (#4580), and 11 routing-* files under load (#4585, #3789, #3799).
  The same 11 files run alone at cdfdb62c6 were 32 of 116 red, and 26
  with the stack, the same tests but rule-remove, whose red languages
  vary run to run (9 cases, then 5). model-chip-steady was 20 of 20 red
  at cdfdb62c6 alone.
Earlier, at f811bf291 with the stack: go test -timeout 45m ./... had 82
packages ok, internal/gui red only on
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
TestMainWindowCorners/macOS_26_SDK (#3949). The whole GUI suite had 301
of 16930 red in 52 files. Those 52 files rerun had 272 red with the
stack and 276 at f811bf291 alone, the same tests.
2026-11-01 09:53:50 +08:00
yetone 0621e70fb9 routing: leave a provider out of the groups magpie finds
chenxiang0010 on Discord asked to keep a provider or a model out of the
auto-created routing groups. A model could already be kept out (remove
its found group; magpie keeps it removed), but a provider could only be
turned off per group or everywhere. Now Routing -> Groups, under "Find
groups on their own", has "Leave out a provider..." (app menu, saved
when it closes) and `magpie group auto skip <provider>...|none`. The
providers chosen (providers.json autoGroupSkip) join no found group; a
group the user made or changed keeps them, a found group left with one
provider goes away, and a request for it is served by AutoStandIn from
a provider still in, and agents on it are reseated (agent.Reseat). A
rename carries the id along. en, zh, zh-TW, ja, de.

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

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

Not tried: the real app with real providers; a model-level skip (a
model is kept out by removing its found group, as before).
2026-10-31 00:57:21 +08:00
yetone 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 df9376592d routing: a group's member may offer several reasoning levels for the agent to pick among
Garydesu on X: "能不能让路由组里的模型设置多个可选推理强度,现在只能选一个或者整个
路由组的". A member was one fixed `:effort` or followed the group's levels.

A member's suffix may now join several levels with "+",
`provider/model:low+xhigh`, kept lowest first, each once. provider.MemberLevels
splits it into Member.Levels and leaves Effort empty, so the member isn't
fixed; one level is a fixed effort as before. The whole stays the member's
id, so rules, fast, off, weights, share and the CLI key it as any member.
The gateway fits the agent's ask to the member's own levels (groupLevels
returns the candidate's levels first; ofMember, the quiet check and the
trace see them), and the group lists them to agents (buildGroupEntries),
intersected with the other members' as usual. In the Routing page's group
editor the member's reasoning menu has "Several levels…", a menu that stays
open with each level ticked or not; a fixed level picked from the first menu
replaces the old one as before. i18n in zh, zh-TW, ja, de; CLI help and
docs/subsystems/gateway-routing.md say it.

Run on mote (mote-run). Rebased on efb55b5c9 (past e1721d640, which
changed the group editor) and run again there: provider, gateway, cli ok;
gofmt clean; GUI group-member-levels, group-member-fast,
group-member-weight, group-from-model-add and i18n-keys 53 of 54, the red
being i18n-keys' "masking…" from e296211b8, red on main (#4053). Linux
and Windows vet were clean at 7fe98c2af. Earlier, at the first base:
- go test -tags nogui -timeout 45m ./internal/provider ./internal/gateway
  ./internal/cli ./internal/tui ./internal/gui: all ok (gateway 525s).
  internal/cli again after the help wording below: ok.
- gofmt -l: nothing.
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go vet
  ./...: clean (darwin prints cgo warnings only).
- Whole GUI suite (node --test "internal/gui/tests/*.test.cjs", both
  engines, load 140 at its peak): 13,931 tests, 119 red in 31 files. One
  was this change: i18n-keys' "a plugin's words are its own", because the
  CLI help said "the agent picks among them" too; reworded the help, and
  i18n-keys passes. The other 30 files, run alone at --test-concurrency=4
  at this tree and at its parent e8c7dddcb: the same files red on both
  (97 and 100 cases, the routing-rule ones a random subset each run, all
  waiting on clicks), each with an open issue (#3527 lists the pattern;
  segs-press-redraw #3922, routing-story-shrinks #3954).
  group-from-model-add, account-*, login-import and signin-* pass alone.
- group-member-levels.test.cjs: 30 of 30 (5 languages, both engines,
  1100px and 420px); group-member-fast.test.cjs 4 of 4.

Broken by hand:
- groupLevels without the member's levels: TestMemberSeveralLevelsFollowAgent
  red (asked high, sent high, not xhigh).
- buildGroupEntries without the member's levels: TestMemberSeveralLevels red
  (offered all four, not low and xhigh).
- main's routing client.js: group-member-levels red 3 of 3 (chromium en).

Not tried: a real agent picking among a member's levels against a real
vendor; the TUI (its reasoning toggle cycles a "low+high" member back to
following the group, unchanged code).
2026-10-28 18:52:39 +08:00
yetone ca8a6f346a agent: a renamed routing group moves its agents, and the Codex app reloads a changed catalog
lucis0116 on X: renaming a provider or a group in magpie didn't reach
every agent.

Display names already reached the agents' files: store and SaveGroup
drop the catalog, and SyncCatalog writes the new "<model> · <name>" and
"<group> · routing group" labels into Codex's model_catalog_json, Claude
Code's picker, OpenCode and Pi (checked in a sandbox HOME). Two gaps
were left:

- A routing group given another id (Routing page, `magpie groups
  rename`, TUI) left every agent on group/<old>, which magpie no longer
  has. The CLI even said "agents set to group/from need group/to now".
  agent.RenameGroup now moves each agent field on group/<old> to
  group/<new>, spelled as the agent spells it. It goes through
  renameRefs, the move RenameProvider already made, now shared by both,
  then SyncCatalog. The GUI, CLI and TUI call it in place of
  provider.RenameGroup.
- The Codex app's own app-server reads model_catalog_json only as it
  starts, and KeepCodexAppOnItsProvider restarts it only when
  codexAppRoute changes. The route named the catalog's path, not what
  the file holds, so a renamed provider or group, or a model added,
  stayed on the old list until the user quit the app. The route now
  carries a hash of the catalog's bytes (codexCatalogTag, read again
  only when the file's size or time changes). The restart goes through
  the existing idle gate: no Codex request in flight, 10s idle, no turn
  open. A write of the same bytes is no change.

Run, in a sandbox HOME only:
- TestRenameGroupMovesTheAgentsOnIt (new): Codex, Claude Code, OpenCode
  and Pi on group/smart, renamed to clever: each said moved and each
  file on group/clever, none naming group/smart.
- TestCodexAppRouteFollowsTheCatalog (new): the route changes when a
  renamed provider rewrites the catalog, and stays put when the same
  bytes are written again.
- Broken by hand: RenameGroup's match turned off makes the first test
  red (no agent moved, every file on group/smart). The catalog line
  dropped from codexAppRoute makes the second red ("a provider renamed
  left the Codex app's route as it was").
- At aded9beea (base ad3833512): go test -tags nogui -timeout 45m
  ./internal/agent ./internal/cli ./internal/gui ./internal/tui
  ./internal/provider -count=1: cli, gui and tui ok. agent red on
  TestFolderVarsAreListed (#3884, red on main since e4552cca9) and
  TestCodexDisconnectStaysWithAccountsOn/login=api, which passed 3 of 3
  alone and isn't on this path (filed #3891). provider crashed in
  TestUnreadLoginsWriteErrorsKeepCredentials with "close of synctest
  channel from outside bubble" in filememo.Forget (#3632, open on main).
- Rebased on 56de2d192 (a312bf3e3 adds a switched account's app-server
  to the same stale set; no overlap): go test -tags nogui -count=1
  ./internal/agent -run 'Rename|CodexApp|Sync|Group|Codex|Hermes' ok
  at this head; ./internal/provider -run
  'CodexApp|Group' ok at a312bf3e3 + this change. The disk was full (other sessions' suites), so the
  whole of each package wasn't run again at this head.
- GUI: group-id-dots, group-morph, agent-model-groups and i18n-keys,
  32 of 32. No GUI script changed, and the GUI tests answer the API in
  memory.
- gofmt -l clean. go vet -tags nogui on agent, cli, gui and tui for
  darwin, linux and windows: ok.

Not covered:
- Claude Desktop reads the gateway's model list only as it starts. It
  still needs its Restart button (AppBehind) after a rename, as after
  any other catalog change.
- Pi, omp and StepCode enabledModels: RenameRefs renames magpie/<old>/
  provider entries only. A group's magpie/group/<old> entry goes as
  scope-gone, and the pick of group/<new> is added again. Not checked
  entry by entry.
- Codex signed in beside magpie (models_cache.json aged by the catalog
  tag) was not run again here.
- No real Codex app restart was watched. The reporter's agent isn't
  named.
2026-10-27 18:22:29 +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 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
keeuu 75e769a9f9 routing: Free first spends the models that cost nothing before the ones that spend (#3054)
A provider or group can be routed `free`. Seats whose model the vendor
serves at no cost to the allowance or credits go first, in listed order.
The rest follow, also in listed order. Free means the vendor's own
catalog.Model.Free word, or else a $0 list price on every count
(provider.FreeModel). A pool with no free model behaves as In order.

routes.Seat gains Free and Strategy gains ByFree. weighRouted works Free
out only for a strategy that weighs by it, so other routings never read
a model list for it.

It is wired through every list a routing appears in:
- both save whitelists;
- plugins/rotation's Builtin;
- app.js's ROUTINGS (appScriptBudget 1,269,000 → 1,271,000 for the
  description) and the Routing page's options, hints and trace text;
- zh-TW, ja and de strings;
- the TUI's routings;
- the CLI's aliases (free, free-first).

Written by keeuu (issue #3054, three commits), squashed onto dee5c9d75
and reviewed:
- the harm checks were clean;
- FreeModel runs only for ByFree, so its Available() walk costs nothing
  for other routings;
- accounts can list different models, so Free first means something for
  a provider's own accounts too, not only for groups.

Run at this head:
- gofmt -l: clean.
- go vet: darwin (internal/routes, provider, gateway, cli, tui, gui);
  GOOS=windows ./internal/...; GOOS=linux -tags nogui ./... — all clean.
- go test ./internal/routes ./internal/provider -run
  'Free|Routing|Strateg|Builtin' ok; ./internal/gateway -run
  'FreeFirst|Weigh|Routing' ok.
- Broken by hand: with FreeFirst returning paid before free,
  internal/routes' Free tests and
  TestFreeFirstGroupSpendsTheFreeMemberFirst go red. Restored, green.
- go test ./... -count=1 -timeout 45m, at load average ~460 from other
  sessions: 62 packages ok, 3 red:
  - internal/gui TestMainWindowCorners (#1936/#2645, AppKit window
    killed at its deadline under load);
  - internal/gateway TestClaudeAccountsSpentFallBackToCodex ("no
    answer"): ok alone in 46s;
  - internal/agent timed out at 45m inside TestSnowSmallModel (1s in):
    the package is ok alone in 1519s.
- GUI, both engines (node --test, playwright 1.62.0), 23 files:
  account-arrange, builtins, context-text, context-scroll-end,
  context-window, group-member-weight, key-weight, rate-limited-sink,
  routing-reset-deadline, routing-compaction, routing-key-windows,
  routing-save, routing-sealed-task, routing-weight-chip, search-keys,
  i18n-keys, panel-routing-pick, panel-routing-providers, panel-routing,
  routing-columns, gui-de, gui-ja, gui-zh-tw. 230 of 236 pass.
  routing-save (the 6/7 counts), routing-columns, i18n-keys and the three
  language files are green.
  - account-arrange "every mode" (#2200): red in both engines, alone,
    and on origin/main dee5c9d75 too.
  - builtins chromium "Plugins › Built-in" (#2960): a 5s wait for the
    Plugins page. Red alone and on dee5c9d75 too; the webkit run checks
    the new Routing strategies subtitle and passes.
  - context-window and context-text, single cases in different
    language/engine pairs on each run: 5s waits under load (#1544,
    #2900). Untouched by this change.

Co-authored-by: keeuu <159448501+keeuu@users.noreply.github.com>
2026-10-20 20:08:25 +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 3f913b3de6 plugins: a JS gateway plugin serves routings (strategies) and watches usage rows (onUsage); plugins/middleware is "JS gateway plugins" (P4)
A plugin's gateway module (magpie.middleware, or its alias magpie.gateway,
or a *.gateway.js file) may now export, besides onRequest/onEvent/onResponse:

- strategies: {name: (pool, seats, options) => order}. Each is a routing
  "<short name>/<name>", registered with routes.Register while the plugin is
  on and loaded and removed when it goes off or reloads. Seats are
  routes.Seat in camelCase JSON. 20ms each; it fails open: a throw, a timeout
  or a result that isn't an order of the seats means the listed order. The
  failure is counted and logged, rate-limited. A file's name is made into a
  routing-safe prefix.
- onUsage(row, options): gets an allow-listed usage row (no bodies, prompts,
  error text, sessions or request ids). The rows come from a bounded queue
  (1024) with one worker, off the request path; a full queue drops the row
  and counts it, and a request never waits. 250ms each.

plugins/middleware is renamed "JS gateway plugins", with a new Sub
(en/zh/zh-TW/ja/de). It registers usage.Observe(middleware.Points()). Off,
no JS hook, strategy or onUsage runs. InUse is unchanged.

providers.json keeps a routing of the form <plugin>/<name> as saved
(provider.PluginRouting) in provider and group Save, whether or not a
plugin serves it now. Before this, `group set g routing=pick/last`
stored nothing.

GUI: the settings state carries jsRoutings. Provider and group routing
pickers offer the served ones, marked data-feature=middleware. A saved
routing that no plugin serves now shows as it is, with a hint. The
Plugins page's line shows routings, how often they were asked, onUsage
rows and dropped rows. The CLI accepts `group set <id> routing=<plugin>/<name>`.
`magpie plugin` lists a module's routings and onUsage; a strategy-only
module had printed nothing after "gateway middleware".

Docs: docs/subsystems/gateway-middleware.md (Routings and usage rows,
limits, verification) and plugin-runtime.md (P4: community plugins at
every point). site/public/docs plugins.html in en, zh and ja has an
example: internal/middleware/testdata/spread.gateway.js, which
TestDocsExample runs.

What was run (worktree on 4df1ba0c6, -p 2):
- gofmt -l: clean. go vet on internal/{middleware,cli,gui,plugin,provider}
  and plugins/...: darwin, GOOS=linux -tags nogui, GOOS=windows; all
  clean, run after the last Go change.
- go test, after the last Go change: internal/middleware ok,
  plugins/middleware ok, internal/provider ok (210s), internal/cli ok
  (203s). Earlier in the work: internal/plugin ok (385s), internal/pluginrt
  ok, internal/gui (Go) ok (320s), and plugins/... ok. The first
  plugins/... run printed a bare FAIL line that `tail` cut off before its
  cause showed. The rerun was all ok; the cause is unknown.
- GUI, both engines (routing-*, group-*, builtins, i18n-keys, gui-de/ja/zh-tw,
  plugin-middleware): 1220 tests, 1204 pass, 16 fail.
  - routing-manual (4): mine. A group's own "manual" was offered a second
    time as a routing no plugin serves. Fixed in client.js withJS. The
    coordinator is rerunning routing-manual, keys-fold, group-fold,
    intent-entry and routing-js alone in both engines, so that rerun is
    not recorded here.
  - routing-model-rest: red alone too, and red on untouched 4df1ba0c6
    (3/20). It is #2115; I commented there with the webkit cases.
  - group-member-weight webkit de 420 is #2387.
  - group-from-model-add webkit zh: it passes alone 2 of 2. Under load it
    waits a fixed 2s for the save post. Filed as #2388.
  - routing-keys-fold (webkit zh/ja/de), routing-group-fold (goto timeout)
    and routing-intent-entry (browser launch timeout 180s) are load
    timeouts. The coordinator is rerunning them alone.
- routing-js.test.cjs (new) passed in chromium en and zh, before the full run.

Broken by hand, each test went red, then restored:
- the permutation check: TestStrategyFailsOpen;
- the queue's non-blocking send: TestOnUsageNeverBlocks ("Ledger waited
  2.04s");
- the allow-list: TestUsageRowAllowList;
- unregister on off: TestStrategiesServedWhileOn and
  TestStrategiesStopWithServe;
- the CLI pattern: TestParseRoutingStays;
- Observe in plugins/middleware: TestOnServesStrategies;
- PluginRouting in provider.go and in group.go: TestPluginRoutingKept;
- the prefix sanitizing: TestRoutingFromFileName;
- the CLI list line: TestPluginListSaysMiddleware;
- the GUI's data-feature mark and its unserved-saved entry: routing-js.

Real use: a sandbox HOME, the gateway served on 127.0.0.1:3682 by a
-tags nogui build, a fake vendor on 3681, and providers fa (key ka) and
fb (key kb) in group g. pick.gateway.js has strategy last (reverse) and an
onUsage that logs.
- `group set g routing=pick/last` stored it.
- A request to group/g reached the vendor with Bearer kb, and the
  "usage-row fb m in=5 keys=17" line was logged.
- `plugin off pick.gateway.js`: Bearer ka (listed order), no onUsage,
  routing still pick/last.
- `plugin on`: Bearer kb and onUsage again.
- `plugin builtin off middleware` says "in use and stays on", as InUse
  should.
- Not tried: the GUI against that gateway, or a real vendor account.
2026-10-15 22:36:59 +08:00
yetone 8ef14be3e6 gateway: an effort=auto group leaves a turn the agent sent with reasoning none alone and asks no classifier, so its pick and what went out agree (#2247, sryimnoob123)
The classifier's pick was recorded but never applied when the agent asked for none, costing a classifier call per turn. The outer effort in the routing record is what the agent asked; the effort sent is tries[].effort on the try marked picked:true, which the groups help now says. Thanks to ggbdpq for the reproduction.

Run at this head (on 6485056e1, with the #2245/#2246/#2247 fixes together): gofmt -l clean; go vet ./... for darwin and windows, and linux -tags nogui; the full go test ./... in a sandbox HOME, all green. The new test fails on the old code and passes with the fix.
2026-10-15 04:46:57 +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
yetone eba7187368 gateway, provider, cli, gui: a group can route By weight, each member's share set beside it (#1910, DD on Discord)
DD asked for weighted round robin as a group routing, next to In turn.
A provider's keys could already route by weight (#841). Groups could not.

What changes:
- provider: Group.Weights maps a member's spelling to its weight, 1 to
  1000. A member left out, or set to 0, weighs 1. SaveGroup accepts
  routing "weight". It also cleans weights the way it cleans fast and
  off: it strips :fast, drops weights of members that are gone and of
  members weighing 1, and refuses a weight below 0 or above 1000.
  Weights follow a member when it is renamed (RenameMember, Rename,
  RenameGroup) and survive Share/Import.
- gateway: planLevel treats each member of a weight-routed group as one
  unit: a model with its keys in its provider's order, or a nested group
  routed its own way. weightedUnits orders the units by smooth WRR on a
  round per group ("group/<id>"), sharing wrrPick with the keys. The
  round's pick goes first and the rest stay in member order for
  failover. A unit whose head is resting leaves the round. When a
  conversation is kept on another member (session/turn/cache/strict),
  the charge moves to that member (wrrSeat, wrrMove).
- cli: routing=weight (also weighted, wrr). weight=<model>=<n>[,...]
  sets weights and keeps the rest; weight= on its own clears them. The
  group view shows "· weight N" for each member.
- tui: By weight is in the group routing list.
- gui: the group editor offers By weight. Each member then shows
  "Weight N · S%", its share among the members that are on. Clicking it
  edits the number in place: Enter or blur keeps it, Escape cancels,
  and a value outside 1 to 1000 shows a warning. The trace header uses
  group wording for a weight-routed group. Strings are added in zh,
  zh-TW, ja and de.
- docs: reference.md, gateway-routing.md, and site start pages in en,
  zh and ja.

Run:
- go test -tags nogui ./internal/provider ./internal/cli ./internal/tui:
  ok.
- ./internal/gateway: ok in 988s with -timeout 45m. The first run hit
  the default 10m timeout at load average ~170. The test running at
  that moment had been running for 2s; it was not a hang.
- go vet -tags nogui on those packages, for darwin, GOOS=linux and
  GOOS=windows: clean. gofmt -l: clean.
- New group-member-weight.test.cjs: 8/8 in Chromium and WebKit, en and
  zh at 1100, en and de at 420. The WebKit de 420 case also passed six
  runs at once.
- gui-zh-tw, gui-ja, gui-de, i18n-keys, routing-*, group-*,
  panel-routing*, settings-groups and agent-model-groups: all green
  except two.
  - routing-steady (WebKit) is #1804. It is red 2/3 alone on origin/main
    e1b70c13d too.
  - routing-save-blank (chromium en) was red under load only, and 3/3
    green alone. The overshoot in its wheel loop is filed as #1924.

Broken by hand, each red, then restored:
- byWeight forced false:
  --- FAIL: TestWeightedGroup (weighted_group_test.go:69 its turn ...)
- cleanWeights call skipped:
  --- FAIL: TestSaveGroupWeights (groupweight_test.go:39 weights map[...
  an/claude-opus-5-5:0 ... oa/gpt-6.1-sol:high:fast:3 ...])
- CLI weight case renamed:
  --- FAIL: TestGroupWeightCLI (unknown field "weight")
- GUI chip not appended: group-member-weight chromium en 1100 timed out
  on the weight button.
- Not red: the test's "moved nothing" check. A scroll forced on click,
  or padding added above, did not turn it red, because the view's own
  scroll guard and scroll anchoring hold the clicked row in place. It
  only shows that the row stays under the pointer.

Not tried: real accounts through a running gateway. The routing is
proven by the plan-level test with synthetic providers only.
2026-10-13 13:10:30 +08:00
yetone 908c910931 gateway, gui: Stays: Strict keeps a conversation on the account or key that answered it, even past its cap, and passes its error on rather than moving it (#1797)
miniers asked that a conversation never move to another account: a
move changes the account a vendor sees mid-conversation and loses its
prompt cache. Session affinity keeps the account while it can answer,
then moves on.

The new affinity mode "strict" (Stays: Strict) does what session does
for a new conversation. Once one has an account, strictKeep asks that
account alone (its other models too) and no other account, key or
provider:
- one resting or spent is still asked, and its error (429, 402, 5xx)
  goes to the agent rather than to the next candidate;
- one over a user cap is asked past it (plan's capped candidates,
  capHeldOnly);
- one held for credits answers 429 naming Stays: Strict rather than
  moving;
- one removed, turned off, barred or not allowed for the key counts as
  gone, and the conversation is routed as usual.
A last try that fails verification is not rested for a strict
conversation that had nowhere else to go.

Set in the provider editor and the Routing page's pool row (GUI, all
five languages), `magpie groups ... stays=strict` (strict-session,
never-move), and the TUI ("stays strictly"). Documented in
gateway-routing.md, reference.md and the site's start pages (en, zh,
ja).

Run:
- go test -tags nogui ./internal/gateway (-timeout 30m under load ~150),
  ./internal/provider ./internal/tui ./internal/cli: ok. The three
  TestStrictAffinity* tests fail on the code before this commit (200
  where 429 was expected, acct-2 answering).
- GUI: stays-strict.test.cjs, chromium and webkit, 900 and 560px, en,
  zh, zh-TW, ja, de: 30 of 30. On the assets before this commit it
  fails 15 of 15 in chromium. routing-*.test.cjs pass but for
  routing-steady's webkit 1.69px shift, which fails on the old assets
  too: filed as #1804.
- gofmt -l, go vet (darwin, linux, windows), full go test ./... before
  the push.

Not tried: a real agent conversation held on a real rate-limited
account.

Known and left: planLevel doesn't merge a nested group's sub.held, as
before this commit.
2026-10-12 23:16:54 +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