Commit Graph
22 Commits
Author SHA1 Message Date
yetone 95d0c97bf9 routing: "Use before expiry" counts credits that expire before the reset (lcyksp)
lcyksp on Discord: the 「重置前用完」 strategy (pace) ranked a WorkBuddy
account by its monthly 500 credits ("积分 0 / 500 · 已用 0% · 28 天后重置").
WorkBuddy spends check-in credits first because they expire sooner
("70.85 积分 将于 2026/11/3 09:28:52 过期"), and the account was ranked as
if nothing would be lost for 28 days.

What changed:
- provider.Allowance.Pace takes a budget window's soonest expiry into
  account (Limit.RunsOut, from QuotaWindow.RunsOutAt, which the
  WorkBuddy plugin and others set on the credits window). When that
  expiry comes before the window's reset, the window's pace is the
  higher of:
  - what is left per hour until the reset;
  - the share that expires (QuotaWindow.RunsOut, now carried as
    Limit.RunsOutLeft) per hour until it expires. When the amount isn't
    told, all that is left counts. A share is capped at 100%, and the
    hours at no less than one.
  The account whose credits are lost soonest per hour goes first.
  Expiry at or after the reset, or already past, changes nothing.
  Zero-config: nothing new to set.
- The trace says DueBy "expiry" when the expiry set the deadline. The
  Routing page's reason then reads "Use before expiry: {who} has the most
  credits expiring per hour until they expire — {n} of its allowance
  expires in {d}."
- Label: "Weekly pace" / 重置前用完 / 週ペース / Wochentempo becomes
  "Use before expiry" / 到期前用完 (zh, zh-TW) / 期限前に使い切る /
  Vor Ablauf aufbrauchen. Product call: the strategy's goal was always
  "lose nothing at the deadline". A reset and an expiry are both such a
  deadline, and "到期" covers both, where 「重置」 names only one. The id
  stays pace, so saved groups are unchanged.
- The descriptions (Routing, Settings, group editor), docs/reference.md,
  docs/subsystems/gateway-routing.md and the site's start page (en, zh,
  ja) say the same.

Go, run on mote at base f95bacdfb:
- gofmt -l internal plugins: clean.
- go test -count=1 -timeout 45m on ./internal/provider,
  ./internal/gateway/..., ./internal/routes, ./plugins/..., ./internal/gui,
  ./internal/tui and ./internal/cli: all ok except three reds that are
  filed and don't touch routing or pace:
  - TestCodexPoolSaysTheClientsVersion (#4807)
  - TestMainWindowCorners (#3949)
  - TestEveryRouteHasACommandOrIsNamed (#4826)
- GOOS=linux and GOOS=windows go vet on the same packages: ok.
- GUI: the touched files (routing-pace-expiry, routing-save,
  routing-group-strategy, routing-reset-deadline,
  routing-wallet-balance, builtins), chromium and webkit: 90 pass, 0
  fail.
- GUI on WSL magpie-desktop (Linux), after the rebase onto 9c58c87e8:
  the 387 files that name routing, i18n, strategy or reason text,
  chromium and webkit: 6211 tests, 6012 pass, 199 fail in 54 files.
  Another session's full suite was running beside it.
- Those 54 files again on mote, with this change and at 9c58c87e8
  without it: 100 and 99 reds. They are the same tests, differing only in
  which language went red. Filed as #4932. routing-group-strategy, whose
  one WSL red was a 9px webkit position, passed both times.
- After the last rebase, onto d29f02d65 (it changed gateway/routing.go,
  i18n.js and app.js), on mote: gofmt clean.
  - go test ./internal/provider ./internal/routes ./plugins/rotation/...:
    ok.
  - go test -run "Pace|Reset|Deadline|Expir|Routing|Weekly|Strategy|Order|Allowance"
    ./internal/gateway: ok.
  - linux and windows vet: ok.
  - GUI routing-pace-expiry, routing-save, routing-group-strategy,
    routing-reset-deadline, routing-wallet-balance, builtins and
    i18n-keys: 94 pass, 0 fail.
- c47fc516a (Tencent Cloud's Token Plan) landed after that run and was
  not run again with this change.

Broken by hand, each red:
- The expiry branch in Pace taken out: TestPaceCreditsExpiring and
  TestPaceGoesByCreditsExpiring.
- dueExpiry left unset: TestPaceGoesByCreditsExpiring's trace check.
- RunsOutLeft not carried: TestAllowanceCarriesRunsOutLeft.
- client.js's expiry reason line taken out: routing-pace-expiry, 0 of 10
  pass in chromium.

Not tried:
- A live WorkBuddy account with check-in credits about to expire. The
  fixtures use lcyksp's numbers (500 monthly, 70.85 expiring).
- The site pages are not deployed by this commit.
2026-11-02 21:52:57 +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 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 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 ef0a03e137 otel: Langfuse is set up from its host and the project's two keys
A user on X asked for Langfuse built in. magpie could already export to
Langfuse over OTLP, but Settings › Observability had the user type the
endpoint .../api/public/otel and a percent-encoded
Authorization=Basic%20<base64(pk:sk)> header by hand.

Settings › Observability now has a Collector row: OTLP or Langfuse.
With Langfuse, the user picks the host (Cloud EU, Cloud US, or
Self-hosted with an address, which also covers Langfuse's JP and HIPAA
regions) and fills in the public and secret keys. Once both keys are
there, magpie saves:
- the endpoint <host>/api/public/otel;
- Authorization: Basic base64(pk:sk), in otel.headers as before, so the
  secret is stored where it was and a backup without keys leaves it out;
- on a first setup, also x-langfuse-ingestion-version: 4, metrics off and
  export on. langfuse.com/docs/opentelemetry/get-started (read 10-26)
  gives the same header for every region and for self-hosted, and says
  that without it OTLP data can arrive up to 10 minutes late.
A Langfuse endpoint set up by hand opens in this view with its keys
decoded into the fields. Opening it saves nothing. Changing a key or the
host keeps the user's other headers, their metrics and export choices,
and an ingestion header they set or left out. Switching from another
collector leaves that collector's headers behind and does not send them
to Langfuse.

The Observability page moved from app.js into the otel plugin
(assets/plugins/otel/page.js, with i18n.js for its words, in Client),
because app.js had 13 bytes of budget left. The app.js and core budgets
are lowered to what is left (1,321,319 and 1,537,645; app.js is
1,321,313 after rebasing on 2620dc319). "Collector" and "Secret key" go
in the core i18n.js because other files use the same words.

Docs: reference.md's Langfuse paragraph (with the env form for magpie
serve) and the en/zh/ja privacy pages.

Run (macOS):
- go test ./... -timeout 45m -count=1 at the pre-rebase head (parent
  e5dd86965): every package ok but internal/provider, which crashed in
  TestUnreadLoginsWriteErrorsKeepCredentials with "close of synctest
  channel from outside bubble" in filememo.Forget. That is #3632, red on
  main since 091153bf7.
- The whole GUI suite (make test-ui, concurrency 4, Chromium and WebKit)
  at the same head: 16 reds. Each red file was run alone here and at the
  parent e5dd86965. The same reds came back at both: menu-input-scroll
  (#3402), old-webkit (#3403) and plugin-card-update's webkit Update
  (#3079). The parent also failed fonts' webkit run. page-width,
  api-key-theme, panel-arrange, panel-balance-order, own-requests,
  library-mcp-health-wsl and plugin-list-error passed alone here: 137
  passes, 7 fails, all of them the three filed above.
- At the pushed head (rebased on origin/main c87a0179b): the budget
  tests; otel, otel-langfuse, i18n-keys, settings-sections, builtins,
  idle-ticks and page-width, both engines, 58 pass; go test
  ./internal/otlp ./plugins/otel ./internal/gui, all ok except
  TestRestartHandsTheGatewayOver (#3451). That test failed 1 of 8 here
  and 1 of 8 on origin/main dce7fe609.
- Before the rebase: otel-langfuse (new: first setup, US, self-hosted,
  hand setup kept, another collector's headers dropped, 5 languages at
  1100/520/360px) with otel, i18n-keys, settings-sections, builtins,
  readable-focus, segs-press-redraw, ux-safety, dialog-backdrop-drag and
  mono-icon-redraw: 113 pass. go vet for darwin, linux and windows on the
  touched packages; gofmt -l clean.
- Broken by hand: with every save treated as a first setup and the old
  collector's headers carried over, otel-langfuse's "set up by hand keeps
  its values" and "another collector's headers" went red.
- New TestOTelLangfuseSetup: settings saved as the page writes them reach
  a fake collector at /api/public/otel/v1/traces with the Basic header and
  ingestion version 4, and nothing on /v1/metrics.
- Real app: a -tags dev build in a sandbox HOME (ports 3461/3462). I
  drove its real Settings page with Playwright: Langfuse, then
  Self-hosted http://127.0.0.1:3463, then both keys. settings.json got the
  endpoint, Basic header, version 4 and enabled. A gateway request then
  reached a local fake collector at /api/public/otel/v1/traces with
  Authorization Basic base64(pk-lf-real-ui:sk-lf-real-ui) and
  x-langfuse-ingestion-version 4.

Not tried: a real Langfuse Cloud or self-hosted project (no account here),
so Langfuse accepting the spans and how they show in its UI aren't checked.
The TUI and magpie serve still have no Langfuse shortcut; serve takes the
env form in reference.md. The Linux app (WebKitGTK) and Windows weren't
tried; the change is form fields and segs, with no motion.
2026-10-26 15:11:37 +08:00
yetone e698a688fd gui: Insights › Masking shows each request as sent, what was masked and how
What masking did moves out of Settings › Privacy into a page of its own
under Insights (plugins/redact: client.js, page.js, redact.css, i18n.js).
Privacy keeps how it is found and what to mask, with a "What was masked"
row that opens the page.

- The top card is Privacy's card, made shorter: the flow animation
  (agents → this computer → providers) with magpie's bird on the centre
  line and "magpie masks it on this computer" under it, so a screenshot
  says who masked it; the count and a 7-day bar. Nothing the list repeats.
- The list: one row per masked request, narrowed by kind, by who found it
  (rules or the local model), by agent or provider, or to held-back
  requests; or by value, each with how often it was put back.
- A request: the message as it went to the vendor beside the original,
  each mask marked, unchanged parts folded; picking a value lights every
  place it was masked; a held-back request offers "Mask it instead".
- Gateway's masked badge and ?view=masking&key=N (trace.go's mainView)
  open one request.
- Classes are msk-: library.css owns mk- (a first cut stacked the flow).
- Budgets lowered to the core's size after the move.
- Not shown: rule names and the local model's confidence; the records
  don't keep them.

Run on f5b1d36ff (rebased since onto 344d11484, which only raised the
budgets and changed a dialog's centring and two unrelated files):
- masking-records.test.cjs: 32/32, Chromium and WebKit, 5 languages,
  1100px and 640px (card, list, filters, detail, put back, held back,
  Gateway badge, deep link, Settings row, no scroll on click), with
  key-import and i18n-keys: 48/48.
- go test ./internal/maskrec ./internal/redact ./plugins/redact
  ./internal/gui ./internal/provider: ok. TestCoreScriptBudget and
  TestMainView ok; gofmt -l clean.
- Before the rebase, on 628e18987: go test ./... -timeout 45m, every
  package ok; GOOS=linux go vet -tags nogui ./... and GOOS=windows go
  vet ./... clean.
- Budgets lowered to the sizes at the pushed head (app.js 1,317,486,
  core 1,524,789), ~26KB under what f35c721c4 raised them to after
  ce5b23cdb's add-key spinner put the core over.

Broken by hand: the bird's href (#bird → #nobird) turns masking-records
red.

Not run at this head when pushed: internal/gateway, which main's newer
commits touched (run right after; the result goes on the release).
Not tried: the whole GUI suite (hours long, and another session's runs
held the machine), the real Linux (WebKitGTK) and Windows apps.
2026-10-24 19:45:03 +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 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 6ac7032b4b plugins: a community plugin's tools reach every agent through magpie's MCP server /mcp/magpie/tools (P4 tool point)
A plugin's OpenCode `tool` hook ({tool: {name: tool({description, args,
execute})}}) used to reach no agent. Now the plugin host collects each
loaded plugin's tools, turns their zod args (v3/v4 shape or object; a
raw JSON Schema is kept) into JSON Schema, and runs one on a `tool`
call: arguments checked against the tool's own zod first (defaults
filled, a wrong one named), execute raced against ToolTimeout (55s,
ctx.abort fires), the answer as text.

The gateway serves them as an MCP server at /mcp/magpie/tools
(tools_mcp.go, guarded by serveMCP as the search one, 4 MiB body):
tools/list names each <plugin short name>_<tool>, at most 64 chars,
a shared name numbered _2; tools/call holds the call to the calling
key's limit through reserveFor and runs it with the calling agent.
The built-in plugin `tools` ("Plugin tools", Essential) serves
gwtool.PluginTools; off, nothing is listed, a call says the plugin is
off and the host isn't asked. InUse counts plugins that are on and
gave tools, from plugin-tools.json, which the host writes after each
load (whole, only on change), so it never starts Bun; the gateway's
KeepFresh watches that note too. Tool answers go to the calling
agent only, so masking doesn't apply (said in the docs).

The Plugins page lists an on plugin's tools by their MCP names, with
descriptions on hover and a button copying the server's address; a
plugin of tools alone has no Provider chip and isn't said to sign in
to nothing. Not done: a Library featured opt-in entry; wiring is the
copied address.

Docs: docs/subsystems/plugin-tools.md (new), plugin-runtime.md's new
"P4: community plugins at every point" section with the tool row, the
README index, usemagpie.ai/docs/plugins#tools in en, zh, ja with an
example. Strings in zh, zh-TW, ja, de. Example plugin:
internal/plugin/testdata/tools.

Run at this commit's tree (base 4df1ba0c6), each package alone, -p 2:
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  over internal/plugin, gwtool, gateway, plugins/..., gui, pluginrt: ok
- go test ./internal/plugin -run Tool; ./plugins/...; ./internal/pluginrt;
  ./internal/gui -run 'Builtin|Plugins'; ./internal/gateway -timeout 45m
  -run 'ToolsMCP|ServingGates|OwnMCPRejects|SearchOnAndOff|KeyLimitsOnAndOff':
  all ok
- GUI, Chromium and WebKit: every plugin-*.test.cjs, i18n-keys,
  builtins: 461/461 pass; plugin-tools.test.cjs (new) covers en, zh,
  zh-TW, ja, de at 980 and 420 px

Broken by hand, each red, then restored:
- tools/list ignoring the gwtool gate -> TestToolsMCPOff
- tools/call ignoring the gate -> TestToolsMCPOff
- reserveFor removed -> TestToolsMCPHeldToKeyLimit (tool ran)
- collision suffix dropped -> TestToolsMCPServesPluginTools
- ToolsOn ignoring Off -> TestPluginTools
- host arg check removed -> TestPluginTools
- host timeout race not listening -> TestPluginTools (answered at
  5.3s by Go's backstop; the test now bounds it at 4s, and the first
  try at this break was a syntax error that proved nothing)
- GUI listing an off plugin's tools -> plugin-tools.test.cjs

Real use: a built magpie in a sandbox HOME (MAGPIE_ADDR 127.0.0.1:3491,
real Bun), the example plugin added with `magpie plugin add`. curl over
MCP: initialize, tools/list (4 tools, schemas), shout "HI HI (for
curl)", a missing argument as isError naming it, add {"sum":6.5}, fail
"it broke", a foreign Origin 403; plugin-tools.json written. Claude
Code (sandbox CLAUDE_CONFIG_DIR) `claude mcp add --transport http` +
`mcp list`: Connected. Not tried: a model calling a tool through a
real agent turn (no model in the sandbox). Binary and HOME removed.
2026-10-15 22:36:59 +08:00
yetone a1f7b8c13f plugin: gateway key limits are the Key limits plugin on the gateway's budget point (P3)
The last P3 point, after observer, router strategy, middleware and tool:
the budget point (internal/gwbudget). A plugin serves a Limiter while it
is on; the gateway asks gwbudget.Limiting before any request of a key held
to a limit goes to a provider (reserveFor: the chat APIs' keyLimited, the
search MCP server and the vision one). A request without a key, or of a
key with no limit, never asks it.

It fails closed. A key with a limit and no limiter served gets 503
gateway_key_limit_off, X-Should-Retry false, nothing sent, and a rejected
usage row. With none served, Limiting first asks the gateway's refresh
(pluginrt.Refresh, at most once a second, never from inside one), so a
limit set a moment ago turns the plugin on for the request that needs it.
A limit reached is the 429 gateway_key_limit with Retry-After and
X-Magpie-Limit-Reset, as before.

plugins/budget serves internal/budget's limiter (budget.Limiter). It is
Essential and in use while a gateway key has a limit, so it can only be
off while none has; a keys file that can't be read is an error, so it
stays on. KeepFresh watches the keys file too. What a key has used and
has left (/v1/magpie/limit, the Gateway page, the CLI) and budget.Append
stay in the core, so the ledger counts a key's use the same either way,
and the key editor's limit fields stay, since setting a limit is what
turns the plugin back on.

The builtins GUI test wheels to the Routing row as it did to Usage's: the
new row puts it below the fold in WebKit, where the page puts back a
scroll that isn't the reader's (scrollOnPurpose).

Run at this head (on origin/main 9d97fd073):
- go test -count=1 -timeout 45m ./... at this head (after two runs cut short by a full disk): 63 ok, 1 red: internal/gui TestMainWindowCorners/macOS_26_SDK killed at its 40s deadline at load ~280 (#1936, no window change here); alone it passed.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, chromium and webkit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw pass
- TestKeyLimitsOnAndOff, TestVisionMCPHeldToKeyLimit, TestKeyLimit*,
  plugins/budget tests

Broken by hand, each test went red: reserveFor ignoring Limiting's error,
Limiting letting a limited key through with none served, the refresh
never asked, Apply serving nothing, InUse counting keys with no limit,
InUse swallowing a read error, the vision and search MCP servers not
reserving, a refusal answered as 503 rather than 429.

Real use (built magpie, sandbox HOME/XDG_CONFIG_HOME, gateway on
127.0.0.1:3594, fake vendor on 3593, two gateway keys):
- no key with a limit: `plugin builtin off budget` turned it off; the
  key's request was 200
- `gateway-key limit <id> day --tokens 3`, then a request at once: 200,
  and the plugin read "on, in use"; the next 200, then 429 "has used 4 of
  its 3 ... tokens for this day"; turning it off was refused, "in use"
- the key with no limit: 200; /v1/magpie/limit answered the spent day
- limit removed: turned off; the key's request 200; a limit set again and
  a request at once: 200, "on, in use"
Not tried: the 503 in real use. With a key limited, the refresh turns the
plugin on before the request is refused (a hand-set `enabled: false` in
plugins.yml read "on, in use"); the 503 is the test's.
2026-10-15 18:41:03 +08:00
yetone 9d97fd0733 plugin: magpie's web search is the Search plugin on the gateway's tool point (P3)
The third P3 point after observer/rotation, groups and middleware: the
tool point (internal/gwtool). A plugin serves a tool by name while it is
on; the process serving the gateway gates on it (Gate in ListenAndServe),
and a process not serving the gateway (CLI, TUI) has every tool, as
before.

plugins/search serves gwtool.WebSearch. Off, magpie offers and answers no
search of its own: the stand-in web_search isn't given to a model that
can't search, the search MCP server and Codex's search in ChatGPT's place
say "turn the Web search plugin on", and neither a search API nor a Kimi
Code plan's own search service is asked. A vendor that searches by itself
is still sent its own web_search. It is Essential and stays on while a
search API is set up or a searcher is picked (InUse); a providers.json or
settings.json that can't be read counts as unknown, so it stays on.

Settings → Models' Web search section stays visible with the plugin off:
the plugin can only be off when nothing is set up there, and adding a
search API there is what turns it back on (as Privacy does for redact).

Run at this head (rebased on origin/main 35aa50cfb):
- go test -count=1 ./... (full suite): 63 packages ok, none failed
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, chromium and webkit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw pass
- TestSearchOnAndOff, TestServingGatesTools, plugins/search tests

Broken by hand, each test went red: canSearch ungated, searchesOwn
ungated, webSearch ungated, no Gate in ListenAndServe, Apply serving
nothing, InUse ignoring the searcher, SearchAPIsSet swallowing the read
error, the gate never released.

Real use (built magpie, sandbox HOME/XDG_CONFIG_HOME, gateway on
127.0.0.1:3592, fake vendor and fake Tavily on 3591):
- on with a Tavily API set: a plain chat model was sent Read + web_search;
  MCP /mcp/magpie/web-search returned the fake's result
- `plugin builtin off search` with the API set: refused, "in use"
- API removed, turned off: the plain model got Read only; a native
  Anthropic provider still got its web_search; MCP answered isError with
  "turn the Web search plugin on"
- API added back: the plugin read "on, in use" and web_search was offered
  again
Not tried: a real search vendor or a real Kimi plan (fakes only).
2026-10-15 16:45:51 +08:00
yetone 8b89b2e36c tests: two waits that went red at load 80–100 leave room: the reasoning relay is timed by the vendor's clock, otel waits a minute for its export
Both went red in full runs of go test ./... on a machine at load 80–100.
Neither is a fault in what they test.

- TestChatReasoningRelayedAsItComes: "first thought after 924ms" against a
  700ms bound from before the request, while the thought still came ~1s
  ahead of the text. The bound timed the gateway's start, not the relay.
  slowThinker now records when it wrote each event. The test checks that
  the first thought reached the client before the vendor wrote the text.
  That is the guarantee, and a slow start no longer counts against it.
- plugins/otel TestOnExportsOffSendsNothing waited 10s for the first export.
  It now waits a minute, as other waits for a plugin's first work do.

Run: go test -count=5 for the relay test, all ok. Broken by hand:
refusesAfterThinking returns true, so the reasoning is held as Claude's is.
The test went red ("reached the client 489µs after the vendor wrote the
text"). Full go test ./... ran with the middleware point commit before this
one (see its body).
2026-10-15 13:40:27 +08:00
yetone 4ac4d9ba99 plugins: the gateway's middleware point; JS middleware and privacy masking are built-in plugins, masking fails closed (P3)
P3's third point (docs/subsystems/plugin-runtime.md). internal/gwmw has two
places, each with its own failure policy:

- Agent: a middleware on an agent's request in its own API and on its reply.
  serveAgent runs each registered one. The JS gateway middleware is the one
  there (middleware.Chain), registered by the new built-in plugin
  `middleware`. Its place, API, limits and fail-open are unchanged. InUse is
  middleware.On(). Off, no middleware runs.
- Masker: what goes to a vendor, masked, and the values back in what comes
  back. The new built-in plugin `redact` serves masking.Masker (in
  internal/masking, since settings imports redact). InUse is masking.Wanted.
  It fails closed: masking asked for with no masker serving, or a masker that
  panics, is a 503 "nothing was sent" at every call site that masked before
  (serve, count_tokens, embeddings and audio, transcriptions, images, video,
  search stand-ins and their queries, the Codex backend).

With no masker, or with no agent middleware while plugins.json has one on,
the gateway asks pluginrt.Refresh, at most once a second. A setting or
middleware added a moment ago serves the request that needs it.
pluginrt.KeepFresh also watches plugins.json now.

Run (on origin/main 95e7c6bcc + this change, with the next commit's two
test waits):
- go test -count=1 -timeout 60m ./...: all ok (gateway 682s, agent 617s)
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, Chromium and WebKit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw. builtins reaches the Usage row by wheel now, since the
  page puts back a scroll that isn't the reader's.

Broken by hand, each went red:
- masking fails open with no masker (TestMaskingOnAndOff)
- a panic isn't recovered (TestSafelyTurnsAPanicIntoAnError, TestMaskingOnAndOff)
- no refresh asked (TestServedRefreshesOnce, TestMaskingOnAndOff)
- the plugins don't register (plugins/redact, plugins/middleware
  TestOnServesOffDoesNot)
- InUse misses redactWords (plugins/redact TestInUse)
- maskedQuery fails open (TestMaskedQueryFailsClosed)
- middleware runs with the plugin off (TestMiddlewareOnAndOff/off)
- no refresh on a middleware miss (TestMiddlewareOnAndOff), want ignored
  (TestAgentsWantedRefreshesWhenWanted)

Real use, sandbox HOME, magpie serve and a fake vendor that echoes:
- redact off with nothing asked: sent as written
- redactWords written, request at once: the vendor got {{TERM_…}} and the
  agent got the word back; `plugin builtin off redact` refused while in use
- `magpie plugin add ./alias.middleware.js`: the next request is rewritten
  (200, was 404). Removed: 404 again.
  The first build left that request at 404 until a restart, since plugins.json
  wasn't watched. That's fixed here.

Not tried: a real vendor account; the Windows box.
2026-10-15 13:40:20 +08:00
yetone b1d02fa612 groups: the user's own routing groups are the groups plugin's, served only while it is on (P3 router strategy)
The groups plugin now owns the user's own routing groups at the router
strategy point. The groups magpie finds (auto-<model>, one model several
providers serve) stay core, as Smart does: a new install has groups off
under Essentials, and taking those would silently drop cross-provider
failover. planGroup and the walk over a group's members stay core too.

- provider.GateGroups / ServeGroups (group_serve.go): the gateway holds
  the gate while it serves; the plugin holds ServeGroups while on. Gated
  with none served, groupsIn drops every group not Auto, so FindGroup,
  GroupFor, the catalog and /v1/models go without them. The CLI and TUI
  are never gated. Nothing derived from groups is cached past a call, so
  a flip is seen by the next lookup.
- Gated and off, a lookup that finds a user group asks the gate's refresh
  (pluginrt.Refresh in the gateway) at most once a second, never
  re-entrantly, then looks again. Without this, `magpie group add` was
  404 for up to 2s until KeepFresh turned the plugin on (seen in the
  sandbox).
- plugins/groups and plugins/routing: InUse is provider.NamedGroups, the
  file's non-Auto, non-hidden groups read past the gate; an unreadable
  providers.json is an error, so the plugin stays on.

Run before rebasing onto 707fbb249:
- go test -count=1 -timeout 40m ./... : all ok (59 packages)
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean
- sandbox, real nogui binary + `magpie serve` + two fake upstreams:
  before add: group/auto-m listed, group/mine 404; right after
  `magpie group add Mine models=pa/x,pb/m`: group/mine listed and 200;
  after `group rm`: 404, auto-m still served.

After the rebase onto 707fbb249: vets (3 OSes) and go test of
internal/provider, internal/gateway, internal/pluginrt and plugins/...
all ok.

Broken by hand, each went red:
- groupsIn filter removed: TestOwnGroupsWaitOnThePlugin,
  TestGroupsOnAndOff/off
- NamedGroups swallowing the read error: TestNamedGroupsUnreadable,
  plugins/groups TestInUse
- Apply not serving: TestOnServesOffDoesNot
- refresh not called / not throttled / asked for Auto groups too:
  TestOwnGroupRefreshesTheGate
2026-10-15 10:42:23 +08:00
yetone af9bd6c3e2 gateway, routes, plugins: the routings besides Smart are the rotation plugin's, on the gateway's router strategy point (P3)
The second P3 extension point (docs/subsystems/plugin-runtime.md). A
router strategy orders one pool of routes: a provider's accounts or keys,
or the heads of a group's members. The gateway still lists the pool and
keeps rests, affinity, rules, pins and failover; a strategy only orders.

- internal/routes: Seat, Strategy{Order, Exact, ByUse}, Register (stacks,
  the last serves), Find, Served, and Apply, which fails open: a strategy
  that panics or answers what isn't a permutation leaves the pool in its
  listed order, logged. Smart is the core's; Ordered, Rotate, LeastUsed,
  Pace and Weighted are routes.Builtin, moved out of the gateway with the
  rotate turns and the smooth weighted round (Round, MoveRound, Forget).
- plugins/rotation (Essential): registers routes.Builtin. InUse counts the
  providers and groups providers.json routes by one of them
  (provider.Routings), an unreadable file is an error, so it stays on. The
  gateway's KeepFresh watches providers.json too.
- Off, a routing no strategy serves is its listed order, and routingOf
  reads it as "order" wherever the core asks (a turn's mark, sinks, a
  rotate group's sessions, a group's heads, weightedKept).
- GUI: the routing pickers (provider editor, Routing page pools and group
  editor) mark the five as data-feature="rotation" (routingSegs), so off
  they offer Smart alone. i18n zh, zh-TW, ja, de.
- Docs: plugin-runtime.md router strategy section, gateway-routing.md
  (also drops a duplicated sentence about a lone key), reference.md.

Run in the worktree at this change (on origin/main fbfb76149):
- go test -count=1 ./... : 57 packages ok (gateway 587s)
- gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows
- GUI: full suite, chromium and webkit, every language: 9805 tests, 29
  red in 6 files. Each red alone the same way on origin/main bc470c6b6
  (just fetched): quota-count-wrap, quota-name-translated (#2228),
  refusal-retries-setting (#2258), routing-held-member (#2252), usage-fold
  (#2163), usage-agents-hide (#2276, from cf455ebd5). routing-save, builtins and
  rate-limited-sink pass in both engines.
- internal/gateway TestMain registers the strategies, so every routing test
  is the parity run with the plugin on; TestRotationOnAndOff turns it off
  (three Rotate sessions start k1,k2,k3 on, k1,k1,k1 off, no turn mark;
  Smart still served).

Rebased on origin/main 2b0037f41: go test ./... again, 56 packages ok at the
default timeout; internal/agent and internal/gateway passed with
-timeout 40m (1093s, 1039s: the machine at load ~17 with other sessions'
suites; the 10m panics stood in TestCodexAPIDisconnectStays and
TestCodexHeardWithinItsIdleTimeout, 1-2s in, no stack waiting on them).
Vets and gofmt clean again; routing-save, builtins, rate-limited-sink,
i18n-keys and the GUI files upstream changed pass.

Broken by hand, each test went red then restored:
- Apply's permutation check off: TestApplyFailsOpen
- Register's remove a no-op: TestRegisterStacks
- the plugin's Apply registers nothing: TestOnServesOffDoesNot
- InUse swallows providers.json's error: TestInUse
- routingOf passes an unserved routing through: TestRotationOnAndOff
- routingSegs not marking data-feature: routing-save.test.cjs "Smart alone"
2026-10-15 09:09:15 +08:00
yetone 9916a94608 gateway, usage, plugins: OTel export is the first plugin on the gateway's observer point (P3)
P3 of docs/subsystems/plugin-runtime.md opens the gateway to plugins. The
observer point is first: it only reads, so it carries the least risk.
With plugins/otel off, the gateway exports nothing and does no observing
work. It keeps no reply whole and adds no request context.

- usage.Observer:
  - Methods: Serve, Bodies, Begin(Request) Watch and Ledger(Record). Watch
    has Attempt and End.
  - Observe(o) registers an observer until its remove is called.
  - ServeObservers is counted, and only Server.ListenAndServe calls it.
  - ObservedBodies takes the most any observer wants.
  - Record.SkipOTel becomes Watched, set by appendUsage for a request an
    observer watched.
- The gateway's otel.go becomes observe.go:
  - observeRequest asks each observer through Begin.
  - attempt and end call each Watch. Bodies are added only when an
    observer asks for them, and the whole reply only for WholeBodies.
- internal/otlp: the exporter (otel*.go) moves out of internal/usage, and
  the gateway's per-request span state moves into request.go. otlp.New()
  is an Exporter, a usage.Observer. What it sends is unchanged.
- plugins/otel:
  - Apply registers otlp.New() and disposes of it when turned off.
  - InUse is 1 while settings.OTelExport says to send. A user who exports
    only through MAGPIE_OTEL_* keeps the plugin on under Essentials.
- pluginrt.KeepFresh: the process serving the gateway refreshes every 2s
  when plugins.yml or settings.json changes. A switch made in the window or
  the CLI reaches a running gateway, or a headless serve, without a restart.
- docs: plugin-runtime.md gets a P3 section, a gateway runtime path and an
  updated failure section; reference.md says the export is the otel plugin.

Run at this tree on origin/main 82f48f093 (rebased onto 52ee84761 after,
which touches only the Linux tray icon):
- gofmt -l is clean. go vet passes on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -count=1 -timeout 25m ./...: ok, 55 packages, none failed.
- New tests:
  - usage: TestObserverServesWithTheGateway and TestObserverLedgerAndBodies.
  - gateway: TestObserverPoint, covering unwatched, no bodies, captured,
    whole and whole streamed.
  - plugins/otel: TestOnExportsOffSendsNothing (on, off, on, with a real
    collector) and TestInUseByEnvironment.
  - pluginrt: TestKeepFreshFollowsPluginsYml.
  - The OTel tests moved with their code to internal/otlp.

Broken by hand, each red, then restored:
- Apply without Observe, and without its dispose.
- KeepFresh refreshing only once.
- InUse reading settings.json only.
- Ledger keeping Watched rows: 3 gateway OTel tests red.
- ObservedBodies taking the last observer's answer.
- Observe not serving a late registration.
- appendUsage not setting Watched.
- Whole bodies never kept.
- Bodies always on with no observer asking.
2026-10-15 05:39:01 +08:00
yetone 3c7ec4ba24 gui: Usage is a plugin's page, its code, markup and words in plugins/usage (P2)
P2 of docs/subsystems/plugin-runtime.md, the fourth page after Sessions,
Library and Routing, and the largest part of app.js.

- The Usage page's code (~3000 lines: the Overview's cards, the
  Requests ledger and heatmap, the Sessions tab, the Agents list) moves
  from app.js to assets/plugins/usage/page.js; its markup, index.html's
  <main id="view-usage">, is client.js's part html. app.js 25756 →
  22675 lines (1,355,376 → 1,198,239 bytes).
- page.js builds on app.js at the top level (its timers, ?view=usage's
  tab and filters), so it is the one plugin script that loads after
  app.js. index.html: kernel.js, the plugins' other scripts, app.js and
  the scripts beside it, each page.js, then start.js, which is app.js's
  old tail (magpie.start(), navHides, OPEN_VIEWS, the first page shown,
  load()), so the first page has its code. TestBuiltinClientsLoaded
  holds that order.
- Hooks: open loads it, refresh(again) is load()'s read of it, reload is
  Refresh now, costs redraws costs on a currency change, tab says the
  tab for focusQuotaCard. app.js calls those through magpie.call. The
  allowance cards, quotasOpened, panelQuotaFocus and panelUseFocus stay
  in app.js: the tray panel draws them too.
- plugins/usage: Essential, Requires window, no InUse. Off, its nav tab
  goes and so do the ways to it (data-feature="usage": the panel's Open
  Usage, Routing's View usage); show("usage") gives way to Agents; the
  panel's Allowances tab stays. builtins.test.cjs switches it off and
  checks each.
- The 173 strings only Usage says move to plugins/usage/i18n.js;
  i18n.js 15032 → 14344 lines. "{n}s" and
  "All sessions" stay: context.js says them too since #1591.
- context.js: with context.js now in before the first page is shown,
  the page's open and load()'s first refresh both reached loadContext,
  and the second drew "Reading…" again over the advice the first had
  just drawn, so its curves never played their entrance (context-tune,
  3 of 3 red). loadContext draws the waiting pane once for the same
  days. Its dead last line, which loaded the tab once context.js came
  in late, goes.
- context-window.test.cjs's "arrives after the state" becomes "loads at
  once though context.js is slow": start.js now waits for it.
  usage-stale-answer reads page.js beside app.js. quota-refresh-order
  (#1630) cut app.js at the period picker's comment, now in page.js; it
  ends at the next comment that stays (5 of 5; without keepRefreshedQuotas'
  call, 2 of 5 red).
- docs: plugin-runtime.md, gui-shell.md.

Run, at this tree on origin/main af27b70b4 (main's keepRefreshedQuotas
and quotaRefresh changes, #1630, stay in app.js beside loadQuotas: the
tray panel draws those cards too):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 ./internal/gui ./internal/pluginrt ./plugins/...: ok
  (-skip TestMainWindowCorners, #1936); gateway and usage as above.
- usage-card-refresh, quota-refresh-order, builtins, editor-picker-clicks,
  context-window, usage-stale-answer: Chromium and WebKit green.
- The full GUI set: see the Routing commit; every Usage red there is the
  same on main or red only under load.
2026-10-15 01:32:13 +08:00
yetone eb7199e120 gui: Routing is a plugin's page, its script, style and words in plugins/routing (P2)
P2 of docs/subsystems/plugin-runtime.md, the third page after Sessions
and Library.

- routing.js and routing.css move to assets/plugins/routing/ (client.js,
  routing.css). Its part's html is the page's head and boxes that were
  index.html's <main id="view-routing">; the rest is drawn by
  routingPage, run at mount since it builds on app.js. It keeps itself
  after that as it did (its own hidden, the language, focus), so its
  hooks are dirty and discard, a routing group being edited, which
  show() and the window's close ask through magpie.call:
  window.routingDirty and discardRouting are gone.
- plugins/routing: Essential, Requires window and gateway, in use while
  the user has a routing group (not Auto, not Hidden), since the page is
  where it is edited. The gateway routes the same with it off.
- With it off, what leads to the page goes too: the nav and panel tabs
  and the panel's section (data-feature="routing"), the guide's Open
  Routing, Providers' "Make a routing group of …", the Usage list's
  View routing and its time as a link, the context card's Latest
  request. A panel left on its Routing tab shows Agents.
- What other pages use of it stays on window: openRoute (context.js),
  kindName, swapWhy, routedWhy (Usage's Requests), newGroupWith
  (Providers), panelRoutingShown (the panel).
- The 505 strings only Routing says move from i18n.js to
  plugins/routing/i18n.js (4 languages); i18n.js 17048 → 15032 lines.
  The plugin's own name and line stay in i18n.js: the Plugins page
  says them with the plugin off (TestBuiltinsTranslated).
- Tests and comments that named routing.js name the new path (gateway's
  antigravity_rest and loop_guard, codeassist.go, usage.go,
  web_compress, group_member_info, assets_revalidate, font-cascade,
  win-fonts, three routing-*.test.cjs). builtins.test.cjs and
  builtins_test.go count seven built-ins and switch Routing off: its
  tabs go, the page shown stays.
- docs: plugin-runtime.md, gui-shell.md, gateway-routing.md.

Run, first on origin/main 3ec45e715, then after rebasing onto af27b70b4
(main's routing.js, css, app.js and i18n.js changes since were carried
into the moved files; its new Routing words, as the rules' conditions,
are in the plugin's i18n.js):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 ./internal/gui ./internal/gateway ./internal/usage
  ./internal/pluginrt ./plugins/...: ok (gateway 1800s under load,
  -timeout 45m; gui with -skip TestMainWindowCorners, #1936).
- All 193 GUI test files, 3 at a time at load ~250, Chromium and WebKit,
  at the Usage commit on 743fcc035: 185 and 186 green. Every red run
  alone here and on a just-fetched origin/main c524bc018:
  - the same on main: routing-model-rest (#2115), routing-wb-restricted
    (#1905), usage-agents-hide (11 of 16 in both, #2211), usage-fold
    (#2163: 12 of 14 here, 9 of 14 on main over 7 runs, the same 4px),
    quota-count-wrap and quota-name-translated in WebKit (#2228);
  - red only under load, green alone on both: routing-flood (#2215),
    routing-log-icons, usage-ledger (#2211), and three plugin-* files
    whose tree was rebased under them mid-run.
- days-fit, failed-open, side-calls and burst-speed, red on main after
  cf455ebd5, are fixed before this commit (#2134, d692b2548).
2026-10-15 01:32:12 +08:00
yetone 8da304767a gui: Library is a plugin's page, its script, style and words in plugins/library
P2 of docs/subsystems/plugin-runtime.md, the second page after Sessions.

- library.js and library.css move to assets/plugins/library/ (client.js,
  library.css). The script registers with the kernel
  (magpie.plugin("library")) and adds its page to the "page" slot. Its
  hooks: open and relang load, redraw, close (its modal), dirty, discard.
  What it set up at load (list scroll and resize, the modal's backdrop
  and Escape, beforeunload, the stuck header, a quiet reload on focus)
  runs in mount.
- app.js calls those through magpie.call instead of window.loadLibrary,
  redrawLibrary, closeLibraryModal, libraryDirty and discardLibrary. It
  no longer lists library in its title map, hide loop or OPEN_VIEWS; the
  kernel's pages are in them.
- index.html: <main id="view-library"> goes, the kernel makes it.
  library.css keeps its place in the cascade.
- The 560 strings only Library says move from i18n.js to
  plugins/library/i18n.js (4 languages). i18n.js: 18826 → 16584 lines.
- plugins/library/library.go lists the client files.
- Tests that read i18n.js for a Library string read strings.cjs (i18n.js
  and the plugins'): 8 library tests and mcp-editor-cancel,
  mcp-oauth-app, mcp-signin-health. font-cascade, win-fonts and
  assets_revalidate_test.go name the new paths.
- "Check again" stays in i18n.js: Library said it alone when the words
  were split, and a5d72a095 (Settings' search keys) says it too since.
  i18n-keys has a new test, "a plugin's words are its own": a key in a
  plugin's i18n.js that any file outside the plugin's folder says fails
  it, naming the file. It was red on this key, and search-keys.test.cjs
  said "Check again" had no zh translation.
- docs: library.md, gui-shell.md, plugin-runtime.md.

Run, at this tree:
- 101 GUI test files touching Library, skills, MCP, the plugins, the
  shell and every language (gui-de/ja/zh-tw, i18n-keys, page-width,
  view-no-sideways, mobile-web, text-size, …): Chromium and WebKit, 4 at
  a time, all green but one. text-size's "zh: 100% picked at the foot"
  failed once in Chromium under load ("scrolled from 160 to 109 (max
  115)"); it passed alone, 6 at once here and on origin/main 8f34bbcd1,
  and at 6× and 12× CPU throttling. It's the Settings page, already
  "fixed" by 50dd39104, so I filed it as #2058.
- After rebasing onto origin/main 75cbc7e1e: i18n-keys, search-keys,
  library-mcp-tools, library-all, gui-de, mono-icon-redraw,
  group-first-token, Chromium and WebKit, green.
- go test ./internal/gui/ ./internal/pluginrt/ ./plugins/...; gofmt;
  go vet on darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
2026-10-14 08:33:25 +08:00
yetone 1eaf1e890a gui: Sessions is a plugin's page, its script, styles and words under assets/plugins/sessions (P2)
The first page of P2 to leave app.js's core. sessions.js and sessions.css
move to assets/plugins/sessions/ (client.js, sessions.css). The page
registers through the kernel as magpie.plugin("sessions"): mount takes its
<main>, which the kernel now makes, open and relang read it again, and
reveal is the Usage page's way in. window.loadSessionsPage and
window.openSessionOnPage are gone. app.js reaches the page only through
magpie.call, and show() takes a page's title from its part. The plugin's
manifest lists i18n.js, sessions.css and client.js.

Words: the kernel's magpie.strings(dict) adds a plugin's words to I18N.
A key that is already there is logged and not taken, since the later one
would silently win. The 65 keys only the Sessions page says (own-keys over
every asset, Go and index.html) move, as written, from i18n.js to
plugins/sessions/i18n.js. tests/strings.cjs reads i18n.js and every
plugin's i18n.js as the page has them. gui-de/ja/zh-tw use it, and
i18n-keys now checks that no key is said twice across files and that a
plugin's words are in every language. TestBuiltinClientsLoaded takes a
.css entry as a <link> in <head>, and a script between kernel.js and
app.js.

Docs: plugin-runtime.md (Words, Pages moved out: Sessions), gui-shell.md,
gateway-sessions.md.

Run:
- go test ./internal/gui/ ./internal/pluginrt/ ./internal/gateway/: ok.
- gofmt clean. go vet darwin, GOOS=linux -tags nogui and GOOS=windows on
  gui, pluginrt and plugins: clean.
- GUI, in both chromium and webkit, 40 files, all green:
  - the sessions-* and sess-* tests, session-identity, routing-sessions,
    account-mask-sessions, usage-session*, gateway-conversations;
  - plugin-kernel, the plugin-move* tests, font-cascade, win-fonts;
  - i18n-keys, gui-de, gui-ja, gui-zh-tw.
- session-terminal's red under parallel load is the same on origin/main
  591ed58b5. It is fixed at its cause in the commit before this one.
2026-10-14 08:33:24 +08:00
yetone 2dcc51417e plugins: the window gets a plugin kernel, and the Gateway page is the first page a plugin draws (P1)
P1 of docs/subsystems/plugin-runtime.md. P0 (3ccbe6bc1) gave built-in
plugins a manifest, plugins.yml and a switch; their pages were still
app.js's own code. Now the window has a kernel a plugin draws its page
through, and the Gateway page moved into plugins/gateway to prove it.

What changed:
- internal/gui/assets/kernel.js (new): window.magpie. A plugin
  registers with magpie.plugin(id, setup); ctx.slots.add("page", part)
  puts its markup where index.html's <template data-slot="page"> is.
  The shell calls its hooks through magpie.call, behind an error
  boundary: a hook that throws, or whose promise fails, is logged and
  its page shows "This page stopped working", what broke and Try
  again, while every other page goes on. ctx.ui is the kit (button,
  switch, the app menu, a settings row) and ui.form draws a plugin's
  settings from their schema. ctx.config / onConfig carry the settings,
  from boot.js before the first paint and from Plugins › Built-in after.
- internal/pluginrt/schema.go (new): a plugin's settings are a Go
  struct (Manifest.Settings); SchemaOf makes the JSON Schema the form
  is drawn from, and Validate is what SetConfig (config.go) takes into
  plugins.yml. Compose drops a hand-edited value the schema refuses.
- plugins/gateway: the Gateway page as a plugin, Essential and in use
  while a gateway key is there. One setting, callsPage (10/20/50/100,
  20 by default). Its client is plugins/gateway/{keys.js,client.js},
  moved out of app.js (and caller-keys.js) unchanged in behaviour.
- internal/gui: builtins.go takes POST {id, config} beside {id, on}
  and lists each plugin's schema and config; boot.js carries
  pluginConfig; /plugins/<id>/… files are served. Plugins › Built-in
  draws a plugin's settings rows under its switch.
- Docs: plugin-runtime.md has "The window's kernel (P1)"; gui-shell.md,
  subsystems/README.md and tests/README.md updated.

What was run:
- go test ./... (sandbox HOME, pinned caches): all packages ok;
  gofmt -l clean; go vet on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- New tests: TestSchemaOf, TestValidate, TestSetConfig,
  TestBuiltinConfig, TestBuiltinClientsLoaded;
  plugin-kernel.test.cjs (a page that throws breaks only itself and
  Try again draws it, at 1100 and 420 in en, zh, zh-TW, ja, de;
  callsPage from boot.js and from Plugins › Built-in), both engines.
- Broken by hand, each turned its test red: the boundary's catch
  removed; Try again not putting the page's markup back; the Gateway
  page's onConfig not re-reading callsPage; boot.js's pluginConfig
  ignored; SetConfig skipping Validate.
- The full GUI suite in Chromium and WebKit (node --test *.test.cjs).
  One red was this change's own. providers-fetching-retry lifts
  providersWhileFetching out of app.js, which now asks providersPage,
  and the lift lacked it. The test now lifts that too, and gains "a poll
  under the Gateway page, a plugin's page that reads with Providers,
  reads". That case goes red with providersPage dropped from the poll's
  guard.
- The reds that were on origin/main a75de4c21 too are fixed in their
  own commits after this one. Two of them came from P0's Built-in tab:
  nav-sub-unroll and plugin-check-github-limit.
2026-10-13 20:39:39 +08:00
yetone 3ccbe6bc15 plugins: a runtime for built-in plugins, and Plugins › Built-in to switch them (P0)
Lxxyx on X (https://x.com/Lxxyx_/status/2109506752656150974): magpie has
too much in it. This is P0 of making magpie's parts plugins, as DeepSeek
Harness does: a runtime, plugins.yml, and the first five built-in plugins
the user can switch off.

- internal/pluginrt: a registry (Register from init), a manifest (API
  caret range, Requires/Provides, Essential, InUse, Apply, Parts,
  Defaults) and Reconcile: the plugins no longer wanted, with whatever
  needs a service they provided, are disposed newest first; the wanted
  ones are applied once their services are there. A plugin that fails or
  panics is failed and the rest run. TestPluginsImportOnlyCore keeps the
  boundary: nothing outside plugins/ imports one, none imports another.
- plugins.yml (appdir.Config()): default → preset (essentials | all) →
  the user's rows → in use. A new install is written Essentials, a magpie
  that ran here before (settings.RanBefore) All, so existing users keep
  everything. Writes are locked, whole and keep a .bak; a file that
  doesn't parse is an error, never empty, and is never written over.
- plugins/groups, library, otel, sessions, warmups. In P0 a plugin off
  is the window's alone: its page, sections and rows (data-feature) leave
  the window; the gateway, TUI and CLI serve the same, nothing is
  deleted. One in use stays on.
- The window: Plugins › Built-in, the first tab, a switch per plugin;
  GET/POST /api/plugins/builtin; boot.js says which are off before the
  first paint. CLI: magpie plugin builtin [on|off <id>], plugin preset,
  plugin dump [--json].
- docs/subsystems/plugin-runtime.md, gui-shell.md.

Run: go test ./internal/pluginrt/ ./internal/settings/ ./internal/gui/;
gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows
go vet ./.... GUI: builtins.test.cjs in Chromium and WebKit, 5 languages,
1100/800/420; list-sort, mobile-web, routing-keys-fold, routing-sessions
pass. By hand under a sandbox HOME: a new install gets essentials, an
existing one all, a broken plugins.yml is refused and kept, dump works.
Full suite results after the rebase are in the push notes.
2026-10-13 16:19:13 +08:00