Commit Graph
53 Commits
Author SHA1 Message Date
yetone 6e03b746be gui: plugin pages load on Windows again, their sandboxed frame kept in the window's process (Mute06162 on X)
Mute06162 on X (0.1.4066, Windows): every plugin page (用量速览, 对话,
模型指纹, GPT号池) showed "This page stopped working / <page> didn't
answer", and Codex found "Worker request cancellation setup: The
parameter is incorrect" and "Resuming Windows asset request: The
parameter is incorrect" in the log. Both are Wails' own lines
(request_cancellation_windows.go, v3.0.0-beta.24).

Cause, reproduced on xiaomi-gpu (WebView2 157.0.4341.46): WebView2 runs
the plugin page's frame (sandbox="allow-scripts") in a process of its
own (Chromium's IsolateSandboxedIframes; CDP lists it as an "iframe"
target). Wails registers its WebResourceRequested filter with
AddWebResourceRequestedFilter, and that isn't raised for this process's
requests: the frame got its index.html (a navigation), but bridge.js,
app.js and style.css went to the network as http://wails.localhost/...
and failed with net::ERR_CONNECTION_REFUSED. The bridge never said
hello, so after 10s the page was broken. Wails' request cancellation
auto-attaches the frame's target, takes it for a worker, and its setup
on that session fails with E_INVALIDARG: that is the log line.

Fix: windowsOptions starts WebView2 with IsolateSandboxedIframes
disabled (sharedFrameProcess), merged into the one --disable-features
with the user's own, unless the user enables it in
WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS. This is app-wide, so it covers
every sandboxed frame magpie makes: plugin pages and plugin panels
(pluginpages.js, the only two), in the main window and the tray panel.
The frame keeps its sandbox: an opaque origin (its context's origin is
"://"), its CSP, messages only.

Run:
- Real repro on xiaomi-gpu, sandbox HOME (C:\Users\yeton\magpie-wvf),
  testdata/page-plugin (magpie-usage-glance, the reporter's 用量速览),
  `magpie app` started in the console session by a one-shot scheduled
  task, driven over CDP:
  - origin/main 077421733: the page shows "This page stopped working /
    Usage glance 的页面没有响应"; the frame target's three subresources
    fail ERR_CONNECTION_REFUSED; err.log has "Worker request
    cancellation setup: The parameter is incorrect." on every open.
  - origin/main with --disable-features=IsolateSandboxedIframes set by
    hand in WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: the frame stays.
  - this change: the card draws (screenshot: "Today, 0 calls, 0 tokens,
    $0.00, Hide cost", so the bridge and usage:summary read work), and
    no Wails line is logged.
- TestWebView2KeepsPluginFramesInTheWindowProcess (new): win-run
  `go test -run WebView2 ./internal/gui` ok on xiaomi-gpu. Broken by
  hand (sharedFrameProcess not called): red on Windows, "disabled 0
  times". TestWebView2ArgsMergeTheUsers and
  TestWebView2ArgsSurviveWailsInit updated for the new default.
- mote: go test ./internal/gui ok (158s).
- mica: go vet ./internal/gui for GOOS=windows, GOOS=linux -tags nogui
  and darwin ok; gofmt -l clean.

Not tried: an older WebView2 runtime (when the runtime turned the
isolation on is not proven; 157 has it), the reporter's other three
plugins (they are frames like this one), Wails' own fix (registering the
filter for every request source kind), and the whole internal/gui
package on Windows.
2026-11-13 23:17:31 +08:00
yetone 466cd4809f gui: a plugin page's Copy picture works where navigator.clipboard is missing (nivekxft on X)
The day card's copy button showed "Cannot read properties of undefined
(reading 'write')" in magpie web opened over plain http (a LAN address) or in
a webview with no async Clipboard API: pageshare.js called
navigator.clipboard.write unguarded. It now tries the API when it exists,
else copies the picture as a selected <img> with the copy command, else
throws a message that says to save it instead (translated in zh, zh-TW, ja,
de). The desktop window was not affected: it already hands the PNG to
/api/plugin-pages/image. app.js's text copy already falls back (/api/copy,
writeText, execCommand), so no sibling is left on the raw API.

Run on mote: page-image-no-clipboard.test.cjs (new, chromium and webkit, en
and zh, navigator.clipboard removed), 4 of 4 red on the old pageshare.js and
green after; plugin-page.test.cjs and i18n-keys.test.cjs green.
go test ./internal/gui: only TestCoreScriptBudget red, on main already
(#5918); pageshare.js and i18n.js are not counted in it.
Not tried: a real http LAN page pasting the image into another app; the
execCommand path was observed selecting the PNG, not read back from the OS
clipboard.
2026-11-11 21:03:00 +08:00
yetone 55dff77b4d gui: plugin pages load behind a proxy that signs in by cookie (xuanwo on X)
A plugin page's frame is sandboxed (opaque origin), so its stylesheet and
scripts are cross-site requests that carry no SameSite=Lax cookie. Behind
Cloudflare Access they were redirected to the sign-in page and the page
said it "didn't answer" (Day card). index.html's manifest link also
fetched without credentials.

In magpie web the page's HTML now comes as one document (pageinline.go):
classic scripts (bridge included) and url()-free stylesheets are written
in, scripts allowed by sha256 in the policy, deferred ones moved to the end
of body. A script the page adds later is fetched by the window (asset call,
folder-checked, window carries the cookie) and loaded from a data: address
(WebKit finds no blob made in a sandboxed frame). The manifest link has
crossorigin="use-credentials". Modules, url() stylesheets, images and
fonts loaded by the page itself still ask the proxy.

Run on mote at this tree: go test -run PluginPage ./internal/gui; node
--test plugin-page, plugin-page-idle, plugin-page-cookie-proxy in
chromium and webkit; gofmt; vet. Broken by hand: inlining off turns
TestPluginPageWebComesAsOneDocument red, the bridge shim off turns the
cookie-proxy test red in both engines.
Not tried: a real Cloudflare Access tunnel; images/fonts behind a proxy.
2026-11-11 19:11:55 +08:00
yetone 745d209dcf usage:day takes a from: a week, a month or all time in one read (HeheLi29136651 on X)
HeheLi29136651 asked for the Day card's weekly, monthly and total bill. The
read only answered one day, so the plugin had nothing to draw. usage:day
now takes {from: "YYYY-MM-DD" | "all"} beside date: the days from there to
date, with the same totals, agents, models and days list (usageapi.SpanOf;
DayOf is SpanOf with no from). "all" starts at the first day with calls:
the ledger keeps old calls in wider buckets that start before the first
call, so From is taken from the first day the heatmap lists. A from after
date, or a date after today, is an error. Answers carry `from`, which is how
a plugin tells a magpie that has spans from one that ignores the param.

Run, on mote:
- TestSpanOf (week, month, all, all up to an earlier date, day alone,
  bad inputs) with calls 300 days back, where the bucket starts before the
  first call: red when the From correction is removed (From 2026-01-12 for
  a first call on 01-15), green with it.
- TestPluginPageReadsADay gains from "2000-01-01", from "all" and a from
  after the day.
- go vet (darwin, windows, linux -tags nogui), usageapi and internal/plugin
  tests ok.
- The plugin side (page-day-card 0.3.0) reads it: seen in the sandbox web
  instance in chromium and webkit, empty ledger only.

Not tried: a ledger with real calls end to end in the page (the plugin's
test covers the card from a made-up read), and a magpie from before this
change opening the 0.3.0 page (the code path throws "usage:day from" when
there is no `from`, and says to update).
2026-11-11 17:38:42 +08:00
yetone a94468ea5e gui: a plugin page behind a proxy that keeps no Host still loads its scripts (xuanwo on X)
xuanwo's Day card was blank in magpie web behind a reverse proxy. The
frame's CSP named the page's folder under r.Host (https:// and http://),
and a proxy that keeps no Host (nginx's default proxy_pass) hands magpie
its upstream's own address, so the policy named nothing the browser used
and every script was blocked.

A browser's page now names its own origin in the frame's address
(_o=, framed() in pluginpages.js; the frame sends no Referer, its
referrerpolicy is no-referrer, so a Referer can't carry it), and
ownSources adds it (browserOrigin: http(s) only, no user info, a plain
host). The desktop window's scheme is unchanged.

Run, on mote:
- TestPluginPagePolicyBehindProxyHost: red on the old code (policy names
  only the upstream host), green now; also checks that a junk _o
  (javascript:, user info, a path) adds nothing.
- Real repro: a sandbox `magpie web` behind a Node proxy that rewrites Host
  to the upstream's, opened at http://localhost:3495/?view=plugin-day-card
  in Playwright chromium and webkit. Before: a broken frame (webkit
  screenshot 52KB, no card). After: the card draws in both, the frame's
  address carries ?_o=http%3A%2F%2Flocalhost%3A3495.
- go vet (darwin), GOOS=windows and GOOS=linux -tags nogui for internal/gui,
  usageapi; go test internal/plugin, internal/usageapi and internal/gui
  -run 'PluginPage|Page|Day'; plugin-page*.test.cjs in both engines: 8 of
  10 pass. The 2 reds are plugin-page-foreign-error ("own: the frame
  opened"), red on origin/main too before this change (#6117).

Not tried: nginx itself (a Node proxy that rewrites Host stands in), Cloudflare
Tunnel, and the desktop window on Windows. The whole GUI suite is started
after the tag.
2026-11-11 17:38:42 +08:00
yetone 623e797fde plugin pages: read a day's usage and share a picture they drew
A plugin's page can now read one day's usage and share an image it
drew. This is for the day card (JungleyYeh on X asked for a "daily AI
statement"); the card itself is an optional community plugin,
@magpie-community/page-day-card.

- A page that asks for the "usage:day" read gets that day as
  magpie.read("usage:day", {date, tz}): totals, each agent and its
  models, the streak and the average active day (usageapi/day.go,
  gui/pageday.go). The Plugins page names the read before it is granted.
- magpie.image.copy(png) and magpie.image.save(png, name) share a PNG
  of at most 16 MB. In the window they go through
  POST /api/plugin-pages/image (pageimage.go): copy puts the picture on
  the clipboard (clipimage.go: osascript PNGf on macOS, PowerShell
  PNG + Bitmap on Windows, wl-copy or xclip on Linux), and save writes
  it to Downloads under a name made safe. In magpie web, the browser
  saves or copies the picture itself.
- The window's side, pageshare.js, is imported the first time a page
  shares a picture. The core grows by its one call only, paid for by
  comments cut, so the budget is not raised.

Tests:
- New: TestDayOf, TestPluginPageReadsADay, TestPluginPageSharesAPicture,
  TestPageImageName and TestClipImageCommand. plugin-page.test.cjs
  covers the bridge, both engines and a refused SVG.

What was run (mote):
- gofmt, plus go vet on darwin, linux and windows: clean.
- Full go test ./... at the pre-rebase base: 369 packages ok, 3 FAILs.
  - TestEveryRouteHasACommandOrIsNamed and TestCoreScriptBudget were
    this change's own reds. The new route now has a parity entry, and
    the share code moved into lazy pageshare.js with no raise.
  - TestGatewayModeStatsNameTheGatewaySessions is #5690, the red in the
    first hour of the day (it ran at 00:32).
- GUI suite (affected and plugin files, both engines): 1160 of 1179
  passed. Every red is filed and none touches this change:
  - i18n-keys "a plugin's words are its own": #5332, #5426, #5482.
  - page-width-steady: #5013.
  - plugin-card-update in WebKit: #3079.
  - plugin-move-unserved "Try again": #4410.
- At this head, after the rebase on bc8b01d60:
  - gofmt clean; go vet ./internal/... on darwin, linux (nogui) and
    windows ok.
  - internal/usageapi, internal/plugin and internal/cli ok.
  - internal/gui: TestCoreScriptBudget, the TestPluginPage* tests and
    the TestPageImage/TestClipImage tests pass.
  - plugin-page and old-webkit (both engines): 12 of 12.

Real use:
- A sandbox HOME with a copy of real usage, through the real GUI
  server, in Chromium and WebKit, light and dark, en/zh/zh-TW/ja/de, at
  420 and 1100 px. The card showed 87.9M tokens, $9.85 and 4076 calls
  with a 22-day streak.
- Picking an earlier day and WebKit's Copy ("Copied") worked, with no
  page errors.
- Not tried at push: Chromium's Copy (its headless clipboard was
  denied) and magpie web's Save as a captured download. A second real
  run that grants both was still queued on mote's suite lock.
- Clipboard: checked live on macOS (osascript) and Windows
  (PowerShell). Not tried live on Linux: WSLg had no display.
2026-11-09 23:19:14 +08:00
yetone ff7d84b9b2 gui: a built-in's switch, settings and page lead to each other (netube99 on X)
netube99 (X, 2119721422918742222): masking is switched on in Plugins ›
Built-in, set in Settings › Privacy and seen in Insights › Masking, and
none of the three leads to the others. Web search had the same split.
One pattern for every built-in whose switch, settings and page are apart:

- pluginrt.Manifest.SetAt ("privacy #redactList") says where Settings has
  its settings: redact, search, gateway and otel set one. builtins.go
  sends setAt and page (its nav.page Part).
- Its Built-in row (featGo): "Settings › <tab>" and, while on, its page
  ("Masking"). No settings link while off when those settings hide with
  the plugin (Observability).
- Its settings, while off (featOff): a first row "Off in Plugins ›
  Built-in", what being off means, and Turn on. Privacy and Web search
  use it; search's own off row went.
- Insights › Masking's head: "Settings › Privacy", unless Turn off
  already goes there. At 600px and under its buttons wrap below the title.
- docs/subsystems/plugin-runtime.md documents SetAt.

Proposal for the owner, not built: give each feature one home with its
switch, settings and page together. This commit only links the three.

Core budget: no raise. +~1.9KB of code is paid for by shortening six
app.js comments (logo mask shelf, copy, sidebar, account models,
fitSend, the hold room).

Run on mote at fe672ce69's tree (origin/main 2b22425b4 + these two):
- go vet ./internal/gui ./internal/pluginrt ./plugins/...;
  GOOS=linux -tags nogui and GOOS=windows vet of gui and plugins: clean.
  gofmt -l: clean.
- go test -run 'TestBuiltin|TestCoreScriptBudget|Translated'
  ./internal/gui ./internal/pluginrt: ok (budget passes after the cuts).
- node --test builtin-places, websearch-places, builtins, i18n-keys,
  i18n-en-no-cjk: 235 pass, 1 fail. The fail is i18n-keys "a plugin's
  words are its own" on plugins/usage "View routing", red on origin/main
  too (#5332, #5426, #5482).
  builtin-places and websearch-places cover en, zh, zh-TW, ja and de in
  Chromium and WebKit, at 1100 and 420 wide, nothing past the edge.
Broken by hand: featGo and featOff made to return at once, and 40
builtin-places subtests went red (42 fails with their parents). Round 1's
files reverted made websearch-places 102 of 142 red.

Queued, not waited for (owner: push each verified fix at once): the full
`go test -timeout 45m ./...` then `make test-ui` on mote behind
~/suite.lock; log at
~/workspace/projects/magpie-wt/websearch-surfaces-scratch/full.log. Any
red gets an issue.
Not tried: the real app on Linux/Windows; warm-ups have no SetAt (their
settings moved into the provider editor).
2026-11-09 17:58:11 +08:00
yetoneandreyoung 4314f4b776 otel: export the gateway key's name as magpie.gateway_key.name (#5751)
reyoung (#5751) shares one magpie through several gateway keys and wants
requests in Langfuse or another collector told apart by key. The ledger
row already had CallerKeyName, but the OTLP allow-list dropped it, and
the observer's root and attempt records never carried it.

Ported from reyoung's 9d82162aa (reyoung/magpie feat/otel-gateway-key-name),
applied unchanged onto current main:
- observeRequest takes access.Caller(r).KeyName when observing begins
  and puts it on every End and Attempt record (CallerKeyName), so the
  root span and every try (failures, retries, fallbacks) carry it with
  no lookup at export time.
- otlp's allow-list grows by this one attribute, on generation and
  ledger spans (otelAttributes, so the duration and token histograms
  too) and on the root span. Omitted when the name is empty. The key's
  id and secret are never sent; provider account names stay out.
- docs/reference.md, plugin-runtime.md and the en/zh/ja privacy pages
  say the name goes to the user's collector.

Added on top: docs/reference.md says each key name multiplies a
metric's series, and that keys sharing a name are counted together.

Review of the fork (read every line; run only on mote): no new address,
dependency or credential; the name is read from the auth context at
request time, the same source appendUsage uses for the ledger row;
reported rows (another computer's) already have the caller key cleared
and never reach observers; session spans of local transcripts have no
key. READMEs (en, zh) mention OTLP only as a feature, with no list of
what is sent, so they are unchanged.

Run on mote (lockf ~/suite.lock), at base c7ebb6f8d plus this change:
- gofmt -l internal/gateway internal/otlp: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: ok.
- go test ./internal/otlp ./internal/gateway -run 'TestOTel|TestObserve':
  ok.
- go test -count=1 -timeout 45m ./internal/otlp ./internal/gateway
  ./plugins/otel: ok.
- go test -count=1 -timeout 45m ./... (macOS): every package ok (92),
  exit 0.

Rebased onto 136178803 after that run (5 commits; gateway.go and
prev_response.go, nothing in observe.go, otel*.go or internal/otlp).
The touched packages' run at the pushed head is queued behind mote's
suite lock and was not done before the push.

Broken by hand (each on mote, then restored):
- observeRequest without the name (o := &observed{}):
  TestOTelExportsGatewayKeyName/true red, "span 0: gateway key name ""
  seen 0 times".
- gatewayKeyAttr returning before adding the attribute:
  TestOTelBatchWireAndPrivacy red (attributes lack
  magpie.gateway_key.name) and TestOTelExportsGatewayKeyName/true red.

Not tried: a real Langfuse collector; Windows and Linux runtime runs (vet
only); the site pages are not deployed by this commit.

Co-authored-by: reyoung <728699+reyoung@users.noreply.github.com>
2026-11-09 17:21:48 +08:00
yetone 80ae904c23 routing: routing groups get a page of their own, beside Routing
The owner asked for the groups to leave the Routing page (11-06): under
the live stage and every request they were a long scroll down, and New
group with them. The design was reviewed before this was built.

- New page, Routing groups (#view-groups), drawn by the routing plugin's
  same script (routingPage), so the editor, its dirty/discard and every
  group action are unchanged. Toolbar: filter, "N groups · M on",
  Templates, Import, Select, and New group as the filled button. The list
  is right under it, and a Settings section under the list holds Found
  groups (with Exclude providers…) and Names in agents' lists.
- No Export button: each group already has its own Copy to share.
- Routing keeps the live stage and the requests. A request's group opens
  the groups page at its row.
- The sidebar has a Routing groups tab right after Routing (from 1024
  points). The header's row has no room for one: at 860px the extra tab
  pushed the logo out (brand.test). There the tab is hidden, Routing's
  tab is lit for both pages (markNav), and Routing's head has a
  "Routing groups ›" button, hidden beside the sidebar.
- Every way in now goes to the groups page: the guide's Open routing
  groups, the panel's and the provider editor's Make a routing group
  (window/main?view=groups&newgroup=…). mainView still takes
  view=routing&newgroup from an older panel.
- Words: "Routing groups", "Open routing groups", "Once saved, make a
  group of them in Routing groups.", and the editor's names note now says
  the setting is under the list, in zh, zh-TW, ja and de. "Open Routing"
  stays for the Agents page's button.
- Docs: providers-accounts, gateway-routing, plugin-runtime, gui-shell
  and reference say "Routing groups page" where they mean the groups.
- Core budget: the core's scripts are 1,533,774 of 1,533,802, paid for
  by three show()/setGatewayMode comments cut in app.js. No raise.

Tests: routing-groups-page.test.cjs (new) covers the page in Chromium and
WebKit, en/zh/zh-TW/ja/de, at 1280, 640 (window) and 420 (web): no
groups on Routing, the tab or the head's button by width, the lit tab,
toolbar order, New group primary and in sight, list then Settings, no
sideways scroll, no native select, no left-border accent; a request's
group to its row; quotas redrawn with an open editor left alone. The
trace tests (routing-compact, -pause-folder, -rule-models, -folder) open
Routing, then show the groups; routing-editor-foot and
name-suffix-where-named scroll by wheel, as the scroll guard lets a
reader; builtins expects the groups tab beside the sidebar only.
Removed: routing-groups-jump (the head's "Routing groups ↓" that scrolled
down to them, gone with them), routing-pointer-pin and routing-steady
(the groups kept in place under requests streaming in above them: no
request is above them now). Their guarantee that what redraws leaves an
open editor and its typing alone is routing-groups-page's quotas case;
Routing's own lists keep their keepInView.

The groups page's jump: a request's group, or a pool's "Several keys"
chip, opened the groups page and scrolled the row to the centre, and the
next frame show()'s backAfterLoad put the page back where the reader
last left it, then brought the focused segment in by "nearest": in
WebKit the pool sat half under the window's foot (routing-mode-goes, 9
of its 10 WebKit cases). goRouting now jumps at once on a page it opens and
marks it arrived(). The wheel in routing-many-keys turns over the keys:
at the page's foot, now shorter, the mouse rested over the requests list
(.rt-reqs, overscroll-behavior: contain), which took every wheel up, and
the test stopped with 2 keys in sight. That is #4082's cause.
routing-days-fit's fixture has 12 requests, a day that fills the window,
since the day bar held needs room under it.

Run on mote (macOS 27, load 25 to 65), Playwright 1.62.0:
- Go: go vet, gofmt -l and go test ./... at the rebased head (650bf8412
  base) ok except TestMainWindowCorners (#3949); internal/gui again
  after the last edits: the same, TestCoreScriptBudget ok (1,533,773 of
  1,533,802, no raise).
- GUI, the 262 files a change here can reach, at the head and at the
  base: the reds at the head are the base's, with their issues:
  menu-input-scroll #3402, provider-mask #5109, context-fold and
  order-unknown (webkit) #3479, header-centre #3479, i18n-keys
  #5332/#5426/#5482, account-eye #5052/#4244, call-headers webkit de
  #5045, codex-predictions #2624, codex-auto-reset webkit de #4790,
  routing-* under load #5088, and zero-priced-free, last-page,
  reasoning-speed, routing-row-swap/-tag-whole/-story-shrinks/-steps-cap
  and routing-intent-entry, red at the base the same way.
- After the last edits: the 11 files with a way to the groups page or
  its scroll (group-*, routing-groups-page, routing-mode-goes,
  routing-groups-off, routing-provider-off, routing-many-keys,
  click-scroll), 175 of 176; the one red is routing-many-keys webkit's
  wire at the foot, red at the base in 8 of 12 (#5543). brand,
  gateway-mode-sessions, header-zoom-fit, header-centre,
  inner-scroll-contain and mobile-web: the same 11 reds at the head and
  the base (mobile-web compares with origin/main through git, which a
  mote-run copy hasn't).
- Rebased on ecc26a339, again: gofmt -l, go vet ./internal/gui and
  TestCoreScriptBudget ok; 10 GUI files (i18n-keys, routing-groups-page,
  routing-mode-goes, sidebar, brand, menu-first-second, library-bar-more,
  click-scroll, name-suffix-saved, unlisted-models) 211 of 212, the one
  red i18n-keys' "a plugin's words are its own", red the same at
  ecc26a339 (#5332/#5426/#5482).
- Broken by hand: without the groups page's CSS rule, brand and
  routing-groups-page go red (32 fails); with the old goRouting,
  routing-mode-goes is red in 9 of its 10 WebKit cases.

Not tried: the whole GUI suite on Linux (WSL magpie-desktop) at this
head; a run at an earlier head is under way and has the Linux reds
#4120/#4121 name. Not tried in the real macOS app, only Playwright's
WebKit.
2026-11-06 23:11:43 +08:00
yetone 10f1e97883 search: a GLM Coding Plan searches its own models with the plan's web search MCP
young02036 on Discord asked for the GLM Coding Plan's Web Search MCP in
magpie's web search. The plan's key is given for that server, so magpie
now asks it with the provider's own key, with nothing to set up: a
Streamable HTTP session at <host>/api/mcp/web_search_prime/mcp
(open.bigmodel.cn or api.z.ai, docs.bigmodel.cn/cn/coding-plan/mcp/
search-mcp-server and docs.z.ai/devpack/mcp/search-mcp-server), the key
as a Bearer, initialize, one tools/call of webSearchPrime with
{"search_query"}, then the session's DELETE.

- provider.ZhipuCodingSearch: only a provider or key on the plan's
  /api/coding/paas/v4 (Zhipu's or Z.ai's host, or the zhipu/zai preset).
  A pay-as-you-go key isn't served by the server and never asks it.
  ZhipuSearches reads p.Keys itself, since KeysOn is counted per list and
  searchesOwn runs on every request. ZhipuSearchKeys lists the plan's
  keys, which are asked in turn.
- searchesOwn/ownSearch: the plan's own models search there first, as
  with Kimi Code and WorkBuddy, and fall to magpie's searcher and the
  search APIs when it fails. This happens only while Settings names no
  searcher (glmSearches): a searcher the user named still searches for
  every model, which is a value the user set.
- It is not offered as a searcher for other providers' models. A plan
  with the Responses base (/api/v1) already searches natively there
  (searchHosts, #660), and making it a no-model service would change the
  searcher those users have now.
- The reply's text is read as a list of results, a list in a JSON
  string, or a list under search_result/results/items/data. isError, or
  words with no results, is an error with the key masked. The query is
  masked as Settings > Privacy says (maskedQuery). Each ask is a request
  log row (logOwnSearch).
- No GUI change: the setting has no switch, the same as WorkBuddy's.
- docs/subsystems/gateway-routing.md has a section on it, and the
  searchesOwn lists there and in plugin-runtime.md name it.

Run (mote, at this tree):
- go test -count=1 ./internal/provider ./internal/settings
- go test -count=1 -run 'Search|GLM|Zhipu|Kimi|LoopGuard|Docs|Guard|WorkBuddy'
  ./internal/gateway: ok
- GOOS=linux and GOOS=windows go vet ./internal/gateway ./internal/provider:
  ok
- gofmt -l: clean

The tests use a fake server only and never reach the network:
- TestGLMCodingPlanSearchesForItsModels: Claude Code's literal WebSearch
  request to a plan's model. The fake gives an event-stream reply with
  a progress notification before the result, and a double-stringified
  result. Then a refusal, an unnamed versus a named searcher beside a
  search API, and a pay-as-you-go key.
- TestReadGLMSearch: each reply shape, and prose.
- TestZhipuCodingSearchAddress: hosts, presets, a plan key beside a
  pay-as-you-go one, a key that's off.

Broken by hand:
- With the old searchesOwn/ownSearch, TestGLMCodingPlanSearchesForItsModels
  is red: the model had no search, 400 "no search tool".
- With glmSearches ignoring a named searcher, the test is red at the
  named-searcher step: the MCP was asked and the named searcher wasn't.

Not tried:
- No real GLM Coding Plan key was available, so nothing was sent to the
  real open.bigmodel.cn or api.z.ai server. The docs give neither the
  tool's argument names nor its reply's shape. search_query and the
  result fields come from Zhipu's Web Search API and a third-party npm
  wrapper (web-search-zaimcp 0.1.2). If the real reply differs, a search
  falls to magpie's other searcher or the search APIs and says why.
- The plan's MCP quota, and how a spent quota is worded.
- A GUI hint in Settings > Web search.
2026-11-05 11:44:31 +08:00
yetone 083821dc96 plugins: a search entry can use the plugin's own sign-in, with its own rests
Asked for by axelburks on Discord. A plugin's search hook entry can name
a provider its own auth hook signs in to, `auth: "<provider id>"`. It then
takes no key. The host picks an account, renews it under `fresh` (the wait
counts within the search's time), runs the hook in `inScope`, and gives it
`ctx.getAuth()`, which returns that account's sign-in. A token the hook saves
with client.auth.set goes to the same account.

The gateway (askSearchSignedIn) asks one account at a time. It takes the
accounts that are on, in the order the provider's model requests take them
(accountsOn, now shared with fallback.go), and puts an account resting from
a search refusal last. A refusal rests only that account's search
(restSearchKey "account <key>"), never its models' rest (restingUntil). Every
attempt gets its own request-log row. An entry without `auth`, or naming a
provider the plugin doesn't sign in to, is a keyed entry as before, with no
getAuth. In Settings → Search, a bound entry shows "Signs in with {name}" in
place of the key field, and the row says whether it is signed in and how
many accounts are on (every language).
Docs: reference.md (with an example), plugin-runtime, plugin-tools and
provider-plugins.

Run on mote at f44fa2ef6 + this change. After rebasing on acd789d45 (an
unrelated responses_ws change), go build ./... and -run "Search|Budget"
on plugin, gateway and provider are ok again at this tree.
- gofmt -l clean; go vet ./internal/... ok; Linux and Windows vet of
  plugin/gateway/provider/gui ok
- go test -count=1 -timeout 45m ./internal/plugin ./internal/provider
  ./internal/gateway ./internal/gui: plugin, provider and gateway
  ok; gui red only in TestMainWindowCorners/macOS_26_SDK, mote's
  macOS 27 title bar, already filed as #3949
- node --test on 15 GUI files: search-signs-in, search-api, search-keys,
  search-order, search-all, search-first, search-instead, searcher-pick,
  searcher-then, provider-search, settings-search, i18n-keys, gui-zh-tw,
  gui-ja, gui-de. 207 of 207 pass (chromium and webkit, 980/420px, en/zh).

Broken by hand. Each break made its test red:
- B1, no ctx.getAuth: plugin TestPluginSearchSignsIn "ctx.getAuth is not a
  function"
- B2, no renewal: "searched as due@seek acc-due", "the renewal never began"
- B3, gateway with no auth branch: gateway TestPluginSearchSignsIn "signed
  in: k9 undefined"
- B4, a refusal that also rests the model account: "a search's rate limit
  rested a@seek for its models"
- B5, getAuth handing out the provider's first account: "as the second
  account: a@seek acc-a"
- B6, the hook run outside inScope: "a token saved while searching as b: a
  rotated-b@seek"
- B7, getAuth given to every entry: "keyed: k9 function"
- settings.js showing the key field for a bound entry: search-signs-in red
  in every engine, width and language

Not tried: a real search vendor or Axel's own plugin; real accounts; runs
on the Windows or Linux boxes; the full GUI suite. The full go test ./...
runs after the push.
2026-11-04 20:55:42 +08:00
yetone 00d8aac596 routing: Free quota by expiry spends the soonest-lapsing free quota first (wowbbs)
wowbbs (and shamen_xiaohong) keep check-in free accounts in one group:
WorkBuddy CN x2, MiniMax Code, TraeCode CN and Qoder CN. They asked that
the group spend the free quota that lapses soonest first, go on to the next
when one is used up or has lapsed, and use a paid account only when no free
quota is left.

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

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

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

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

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

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

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

Not tried: no real account of any vendor. WorkBuddy, MiniMax, Trae and
Qoder check-in accounts were not routed live. The order was tested on
fabricated allowances shaped as their plugins report them. The full
`go test ./...` runs after the push.
2026-11-04 17:11:55 +08:00
yetone 75e30625f5 plugin: a command that serves no pages moves a page's service off the app's port (#5187)
MYCF711 (#5187, Windows, 0.1.2901): magpie plugin update run while the
app runs hung with no output. Its host loads every plugin, and
page-chat's service waits for port 3477, which the app's host holds:
each CLI command that starts a host waited ~6s on it, then kept trying
the port every second in the background, so it could take 3477 from
the app's host when that restarted after the update.

Now magpie run with a command that serves no pages (anything but the
app, tray, tui, web, serve, a bare magpie or a magpie: link opened in
the app; servesPages) sets plugin.ServePages(false), and its host hands
a plugin whose magpie.page.service names an option a free port of its
own in that option (hostOptions). The plugin's other parts load at once
and the app's port is left alone. plugins.json is not changed, and a
service no option moves is started as before. The class, not
page-chat: any plugin page service declared with an option.

Run, at base 0ee424e3e plus this change:
- mote: go vet ./internal/plugin ./internal/cli (darwin), GOOS=linux go
  vet -tags nogui and GOOS=windows go vet of both, GOOS=linux nogui and
  GOOS=windows builds, go test -count=1 ./internal/plugin ./internal/cli:
  ok (280s, 65s). gofmt -l clean.
- Broken by hand: hostOptions handing options unchanged makes
  TestHostServingNoPagesLeavesHeldPort red (the load "didn't finish in
  10s") and TestHostOptionsMoveOnlyTheService red; servesPages returning
  true makes TestServesPages red on daemon, autostart, providers.
- Windows (xiaomi-gpu, win-run): the new tests and TestServesPages ok.
  Sandbox with page-chat and the reporter's git plugin
  (KevinFX-code/magpie-wps-lingxi), nogui builds:
  - 3477 held by bun, magpie plugin update: 13.9s before (page-chat
    "被占着" then "每秒试一次"), 10.6s after (page-chat "listening on
    127.0.0.1:51493").
  - beside magpie serve's host on 3477: 13.98s before, 12.4s after;
    serve's host keeps 3477.

Not tried / not reproduced: the reporter's literal no-output hang. Before
this change, update finished on 0.1.2909 in every setup tried (nogui
CLI with 3477 held, beside nogui serve, beside the release GUI exe in
the interactive session: 6-20s), so this removes the wait and the
port contention seen, not a hang reproduced. Not tried on Linux or the
macOS app.
2026-11-04 16:25:02 +08:00
yetoneandreyoung 83bdfe70d2 otlp: OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME name the server a trace or metric came from (#5167)
Several magpie servers exporting to one collector or to Langfuse all sent
the same resource, service.name=magpie alone, so nothing said which server
an event came from. Both signals' resource now merges the standard
OTEL_RESOURCE_ATTRIBUTES over that default, and OTEL_SERVICE_NAME over
that (otelResourceAttributes in internal/otlp/otel_resource.go). Nothing
about the machine is looked up; only what the user set is sent. Neither
variable turns export on.

Ported from reyoung's 7ed03b819 (feat/otel-resource-attributes, base
4ca55c6b6), reviewed line by line; nothing in it reached past its goal.
Changed from it:
- service.name precedence. The resource SDK spec makes code-supplied
  attributes win over OTEL_RESOURCE_ATTRIBUTES, but magpie's "magpie" is
  the fallback in the role the spec gives unknown_service, not identity
  the user supplied, and magpie's default never overrides a value the
  user set (code standards). So a service.name in the variable wins, and
  OTEL_SERVICE_NAME, which the spec's env table puts over the variable's,
  wins over both. An empty service.name or blank OTEL_SERVICE_NAME counts
  as unset (the spec's "empty value = unset"), so the resource never
  carries service.name="".
- Bytes that aren't UTF-8 once decoded (%FF) are a decoding error and
  discard the variable; before, json.Marshal sent U+FFFD.
- The variable was parsed and, when bad, logged on every flush of each
  signal. It is now parsed once per value and logged once, naming the
  entry by position (never its contents).
- otlp tests clear both variables in otelConfig, so a developer's shell
  can't change what the existing wire tests see.
Kept: whole variable discarded on any invalid entry (no '=', empty key,
bad escape, empty entry such as a trailing comma), as the spec says;
keys and values trimmed and percent-decoded with PathUnescape ('+' stays
'+'); last repeated key wins; values are strings.

Docs: reference.md's OTLP export, plugin-runtime.md's internal/otlp row,
and the privacy pages (en, zh, ja) now say the resource carries what the
user sets there.

Verified:
- TestOTelResourceAttributes reads the resource a test collector gets on
  /v1/traces and /v1/metrics, 17 cases. On the old otelEnvelope it FAILs
  (server, override and duplicate, encoding and empty, unencoded UTF-8,
  OTEL_SERVICE_NAME cases: "traces resource attributes =
  map[service.name:magpie]", same for metrics). Broken by hand one at a
  time, each went red: UTF-8 check off (not_UTF-8_once_decoded), no
  OTEL_SERVICE_NAME (3 cases), empty service.name kept (empty_service_
  name_is_unset), valid entries kept from a bad variable (missing equals,
  trailing comma, empty key, ...), and the per-value cache off
  (TestOTelResourceAttributesLoggedOnceWithoutContents: "logged 4 times,
  want once"). All green restored.
- On mote: go test -tags nogui ./internal/otlp ok; go test -race -count=3
  -run TestOTel ./internal/otlp ok; go vet, GOOS=linux go vet -tags nogui,
  GOOS=windows go vet (internal/otlp); go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build; node --test site/*.test.mjs; gofmt -l
  empty.
- Full suite: run after the push (go test -tags nogui -timeout 45m ./...
  on mote); reds, if any, filed separately.

Not tried: a real collector or Langfuse; Windows/Linux runs of the
package (the code has no OS-specific path).

Co-authored-by: reyoung <728699+reyoung@users.noreply.github.com>
2026-11-04 13:50:09 +08:00
yetone 1747559d02 plugin pages: name the scheme in a browser's policy, and the service's 'self' (#4198)
In `magpie web`, iOS Safari (18.7) loaded none of a plugin page's
scripts: pagePolicy named the page's folder as a scheme-less host-source
(host/_magpie/plugin/<tok>/), a sandboxed frame's origin is opaque, and
that WebKit took the missing scheme from it, so the bridge never said
hello and the page was broken at 10s (orinsid; YangHonghang on v0.1.2681,
young02036 on Discord).

- pagePolicy: a browser's policy now names the folder under both
  https:// and http:// (ownSources). Behind nginx or Cloudflare TLS ends
  before magpie and nothing magpie trusts says which scheme the page came
  over, so X-Forwarded-Proto is not read; both name the same host, port
  and folder, and an https page can't load http:// files anyway. The
  desktop window keeps its own transport alone (wails://, http:// on
  Windows, #2501).
- The second layer (YangHonghang): a page's local service sends its own
  policy, `connect-src 'self'`, and what it sends runs under magpie's
  `sandbox allow-scripts`. In WebKit, 'self' there didn't match the
  service page's own fetch of api/x. servePageService now names the
  service's root (/_magpie/plugin/<tok>/_magpie/service/) under both
  schemes after each 'self' in a CSP header the service sends, plus ws://
  and wss:// in connect-src and default-src (serviceSelf). 'self' stays,
  so nothing allowed before is taken away. A <meta> policy isn't
  rewritten; the plugin docs (en, zh, ja) say to write whole sources.

Run at f0a723d4c's tree (rebased on c74b932c8), on mote:
- go test ./internal/gui/: every test ok but TestMainWindowCorners, red
  the same at an origin/main e7185daeb copy (#3949, macOS 27). The real
  WKWebView test TestPluginPageLoadsItsFilesInTheWindow (desktop
  wails:// path) passes.
- gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet:
  clean.
- node --test plugin-page, plugin-panels, plugin-page-idle (chromium and
  webkit): 14/14.
- win-run: TestPluginPage*, TestServiceSelf, TestPluginPanel* ok on
  Windows 11 (the window's http:// scheme).
- A scratch test (not committed) served the real pluginPageRoutes(web)
  and a fake service with "default-src 'self'; connect-src 'self'" over
  http and https (httptest TLS), framed sandbox=allow-scripts, in
  Playwright Chromium 151 and WebKit 26.5. At origin/main WebKit refused
  the service's fetch ("Refused to connect to .../_magpie/service/api/x
  because it does not appear in the connect-src directive", the
  reporter's words); with this change it fetched, and Chromium did both
  times. The page's bridge said hello in both engines both times.

Broken by hand: ownSources back to the scheme-less source and
serviceSelf skipped: TestPluginPageWebPolicyNamesItsScheme,
TestPluginPageServedShutIn, TestPluginPanelsServedShutIn,
TestPluginPageWindowPolicy and TestPluginPageServiceProxied go red.

Not tried: a real iPhone. Playwright's WebKit is not iOS Safari, and it
loads the scheme-less source fine, so the first layer is fixed on the
reporters' evidence and the CSP rule, not seen fail and pass here. Not
tried behind a real nginx or Cloudflare, nor a service WebSocket.
2026-11-02 15:27:15 +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 c30d3b7b63 plugin pages: a page the reader left is told, and let go after 10 minutes unless it keeps itself
A plugin's page kept its frame, with its scripts, timers and
connections, for as long as the window was open once it had been
looked at: show() only hid its view, and a frame in a hidden view isn't
hidden to itself (its visibilityState doesn't change), so a page
couldn't even pause on its own. Asked by the owner: is that by design?
Only the lazy first load was.

- The kernel's leave hook now reaches the page part: the page is told
  {event: "visibility", data: {visible}} as the reader leaves and comes
  back. The bridge has magpie.visible and magpie.onVisibility(fn); hello
  carries visible, for a page left before it said hello.
- A page left 10 minutes (IDLE_MS) has its frame removed and loads again
  when next opened. Back sooner, it is the same frame. Its hello timer is
  cleared, so nothing says it broke.
- magpie.page.keepAlive: true (plugin.PageSpec.KeepAlive, keepAlive in
  /api/plugin-pages) keeps a page however long, for one that works while
  no one looks at it. Anything but true is false, read as raw JSON so a
  wrong type never drops the package's page.
- plugin-runtime.md's page row says so.

Run on mote. The Go suite and most GUI files ran at this change on
557f51dbf. After rebasing onto 30cd39f19 (none of these files changed
upstream), the budgets, TestWindow* and the page GUI files ran again
at this tree:
- plugin-page-idle (new), plugin-page and plugin-panels, chromium and
  webkit: 14/14 at 557f51dbf. At the rebased tree, the first run was
  13/14: plugin-page's chromium "draws in its frame, shut in" was red
  once, and its assertion wasn't kept (#4589). After that: 42/42 over
  3 runs, then 16/16 chromium over 4.
- i18n-keys, plugin-actions, plugin-kinds-discover, plugin-kernel,
  plugin-replaced, plugin-proxy-page: 51/52. The red is i18n-keys'
  "Unmarked", the same on origin/main e0eb74987 (#4524).
- go test -timeout 45m ./...: every package ok except three reds, none in
  code touched here:
  - TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
    TestMainWindowCorners (#3949) fail the same on origin/main e0eb74987.
  - TestUnroutedHeldReportSaved (#4300) failed in the full run only.
    Alone, -count=5, it passes.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./..., go build ./..., gofmt -l: clean.

Broken by hand: with the leave hook taken out of the page part, the new
test is red in both engines.

Not tried: a real plugin page in the desktop app or WebKitGTK. The
IDLE_MS length (10 minutes) is a judgement, not measured.
2026-10-31 22:39:37 +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 ec789445db gui: Settings' session rows are the sessions plugin's settings.js; app.js back under its budget
af8f3a939 (session reads, RustCats on X) added Settings › Privacy's
Agents' session history to app.js and took it to 1,314,299 bytes, over
its 1,311,735 budget, and the core scripts to 1,535,027, over 1,532,459:
TestCoreScriptBudget red on main.

Moved, not raised: renderSessionReads and loadSessionReads (Privacy's
Agents' session history) and renderSessionTerminal (General's Session
terminal, data-feature="sessions") go to plugins/sessions/settings.js,
loaded after app.js like plugins/gateway and plugins/search's settings.js
and drawn whether the plugin is on or off. The code is moved as it was;
app.js calls them by name as before. app.js is 1,310,042 and the core
1,530,770, both under budgets left as they are. Docs: gateway-sessions.md
and plugin-runtime.md name the new file.

Run on mote at this tree (on af8f3a939):
- go test -count=1 ./internal/gui: TestCoreScriptBudget ok; red only
  TestMainWindowCorners/macOS_26_SDK, the same on main (#3949, open).
- GUI, Chromium and WebKit: i18n-keys, sessions-reads (5 languages,
  390-900 wide), session-terminal, account-discovery, settings-general:
  every case ok.

Not tried: the real app.
2026-10-30 00:14:37 +08:00
yetone f6263439af gateway: serve OpenAI's text to speech, POST /v1/audio/speech
liuyuexue2020 on X (tweet 2115742181734445238) wanted audio models
(Mistral among them) behind magpie, and the gateway had no
/v1/audio/speech.

POST /v1/audio/speech (and the bare /audio/speech) takes OpenAI's JSON
body and goes through serveRetrieval, as transcriptions (#2053) and
embeddings do: routed (a group's members, a provider's keys and
accounts, pause rules, key limits), metered against MaxRPM, recorded
(usage operation "speech", Routing, recent calls). Only "model" is
rewritten to the provider's own id; every other field goes as sent, so
Mistral's voice_id and ref_audio pass too.

The answer is never held whole: a speech request's 2xx answer is left
unread by the new retrieveOpen (retrieveAs now wraps it) and copied to
the client as it comes, flushed per read, in the vendor's own
Content-Type: audio (mp3/opus/aac/flac/wav/pcm), SSE for
stream_format=sse, or a vendor's JSON (Mistral answers
{"audio_data": base64}). No Accept: application/json is sent for it.
The usage in SSE's speech.audio.done event is counted from the last
16KB. A vendor's error is read and passed on as before, and a failing
member still falls over to the next.

Masking: "input" and "instructions" are masked as the settings say,
as text (maskTextHits), each where it sits; nothing else in the body
is (voice, formats, a voice-cloning clip are no text of the user's).
Nothing is put back: the answer is audio, so a masked value is read
aloud as its placeholder (docs/reference.md says so).

Mistral: its API has POST https://api.mistral.ai/v1/audio/speech
(voxtral-mini-tts-3-0), at the OpenAI path but not OpenAI's shape:
voice_id instead of voice, and JSON {"audio_data": base64} back, not
raw audio. Both pass through as sent; a client must speak Mistral's
shape to it. OpenAI, Groq and other OpenAI-style TTS vendors (vLLM-Omni
included) are served as they are.

Also: the 404 message's list, /v1's "apis", remote_magpie's suffix
list, cors_test and lan_test route lists, docs/reference.md,
gateway-routing.md, plugin-runtime.md, site remote.html (en/zh/ja).

Run (mote-run, at this commit):
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build ./...: ok; gofmt -l clean
- go test -timeout 45m -count=1 ./internal/gateway ./internal/provider at 7bc52d44e^{tree} (= this tree, origin/main 65bd4e4f7): gateway ok 497.9s, provider ok 88.7s
- go test ./internal/gateway -run 'Speech|Transcri|Embedding|Rerank|CORS|LAN|ReplyHeaders': ok

Broken by hand (mote-run, each red, then restored):
- the two mux lines removed: all five TestSpeech* red
- streams() false (answer read whole): TestSpeechStreamsAsItComes red
  (first event never reached the client while the vendor held the rest)
- "instructions" left out of the masked fields: TestSpeechInputMasked red

Not tried: a real vendor (OpenAI, Groq, Mistral) through a sandbox
magpie; only the fake upstream in speech_test.go. Not run on the
Windows or Linux boxes (vet only).
2026-10-29 19:25:40 +08:00
yetone 5eab14a8cc plugin pages: magpie web reaches a page's local service on its own address, so the chat page works from another computer
aigcfree (Discord DM) runs `magpie web --addr 0.0.0.0:3430` on an Ubuntu
server behind nginx and opens it from a Windows PC. Plugins -> 对话
(@magpie-community/page-chat) showed "127.0.0.1 refused to connect": the
page sends its frame to the chat server on 127.0.0.1, which in that
browser is the Windows PC.

A plugin now declares its page's service (package.json
magpie.page.service {port, option}: the port, or the plugin option that
holds it, from its plugins.json options; plugin.ServiceSpec). Served to a
browser (isWeb), /api/plugin-pages gives the page `service`:
_magpie/service/ under its token, and the bridge hands the frame
magpie.service as an absolute address. The desktop window and slot pages
get none, and the routes answer 404 there, so the local path is as before.

servePageService reverse-proxies /_magpie/plugin/<token>/_magpie/service/…
to 127.0.0.1:<port>. The service stays on loopback. The way in is the
page's own: the per-run token that only a signed-in /api hands out,
behind AllowGuard. Nothing is weakened:
- Host is set to 127.0.0.1:<port>, which the service's rebinding check
  wants.
- The window's cookie is taken off.
- Origin must be absent or null (403 otherwise).
- Set-Cookie is dropped.
- Every reply is sandboxed (sandbox allow-scripts; frame-ancestors
  'self'), with Referrer-Policy no-referrer and nosniff.
- The gateway's own port is never served, since a request from this
  server is loopback and the gateway takes that without a key.
- Event streams flush as they come (FlushInterval -1, X-Accel-Buffering:
  no for nginx). webCompressed no longer gzips text/event-stream, which
  held a stream back until gzip's buffer filled.
- A redirect to the service's own address is made relative.
- The entry starts the plugin host as the page's HTML does (pageHost).
- A service not up yet answers its frame with a 502 page that tries
  again in 2s.

page-chat 0.1.2 (magpie-community/plugins 4a46212, on dist) declares the
service, goes to magpie.service when given one (else 0.1.1's path:
127.0.0.1 on loopback, the SSH-tunnel note from elsewhere), and asks
api/… by relative address.

Docs: plugin-runtime.md P4 (the page row), gui-shell.md (no gzip for event
streams).

Tests: TestPluginPageServiceListedToBrowserOnly, TestPluginPageServiceSpec,
TestPluginPageServiceProxied (through webHandler: Host, cookie, Set-Cookie,
CSP, escaped path and query, foreign Origin 403, made-up token 404,
redirects, SSE first event before the end and not gzipped),
TestPluginPageServiceDown, TestServiceLocation; plugin-page.test.cjs
checks magpie.service in a browser page and its absence in a slot.

Run at 276683d85, this change on origin/main e61e10535. It was rebased
since onto c1660481c, a one-line WorkBuddy mover min in internal/provider.
181fd0a68
(another session's proxy, path _service/, {portOption}) is reverted
there by 3870ddf0a, and nothing of it is left:
- go test ./internal/gui/ ./internal/plugin/ -timeout 45m, native on the
  Windows box: every new test ok. 8 reds, none in code this touches:
  - 6 fail the same at origin/main c1660481c, run there by name:
    TestGatewayHeldByAContainer, TestLodyImportHandoff,
    TestImportStatusUnreadableIsUnknown, TestAionUiImportRow,
    TestUpdateThatWontStart, TestPiPackage. All are in #4115.
  - TestLoadConcurrentWithSavesAndEdits is red 2 of 3 alone here and red
    at c1660481c too (a rename "Access is denied"); it is in #1827.
  - TestDesktopSessionTitlesOnPages passes alone (3 of 3). In the package
    run it listed the box's real WSL Codex session. Filed as #4185.
- Earlier, at bc247a8cc, on mote: the new Go tests, and go vet of both
  packages.
- Not run at this tree: the full go test ./... . mote was at load 300+
  with three other sessions' full suites, and the Linux box had one. A
  run at an older base (fa5ff2fec) had 25 packages ok, internal/agent
  among them, and none red when it was stopped for the rebase.
- gofmt -l: clean. go vet ./internal/gui ./internal/plugin: darwin on
  mote, native Windows on xiaomi-gpu. A Linux vet from mote fails in wails'
  cgo files, and in WSL for lack of gtk4/webkitgtk-6.0 headers, both
  unrelated to this change; CI vets Linux with its headers.
- plugin-page.test.cjs on the Windows box, both engines: WebKit 3/3.
  Chromium's first test is #4180, which fails the same on origin/main
  f463a8aaf. The next commit fixes #4180 at its cause.
- Real: a sandbox magpie web on mote (0.0.0.0:3561, sandbox HOME,
  MAGPIE_WEB_KEY, the real chat package from a folder, a fake gateway).
  Playwright on the Windows box opened Plugins -> chat over the LAN in
  Chromium and WebKit. The frame went to
  http://mote.local:3561/_magpie/plugin/<tok>/_magpie/service/?theme=…
  with origin null. Its fonts.css and style.css came through the proxy. A
  sent message streamed back "remote chat works", and the fake gateway
  logged both POSTs.
  - From the Mac over the LAN: /api/plugin-pages without the cookie
    gives 401. A made-up token gives 404. A foreign Origin gives 403.
    POST api/chat without the chat token gives 403 (the service's own
    check). mote.local:3563 directly is refused (loopback only).
  - Before bun was reachable in the sandbox, the frame got the 502 retry
    page.
- Broken by hand, each red then restored:
  - Without the event-stream exclusion, the stream arrives gzipped.
  - Without the Host rewrite, the cookie strip or the web gate, each
    assertion is red.
  - With the bridge's service dropped, plugin-page.test.cjs is red in
    WebKit ("magpie.service").

Not tried:
- A real nginx in front.
- A WebSocket through the proxy (httputil handles the upgrade; the chat
  page uses none).
- TLS (--tls-cert).
- The desktop app with page-chat 0.1.2: its fallback is 0.1.1's path,
  covered by the plugin's launcher tests.
2026-10-29 14:28:24 +08:00
yetone 3870ddf0a2 Revert "plugin pages: magpie web forwards a page's local service under the page's address"
This reverts commit 181fd0a68. Another session has the fuller version of the
same feature on branch plugin-page-remote (pageservice.go, its contract
magpie.page.service {port, option} and an absolute magpie.service), which
page-chat 0.1.2 on the community dist already speaks; two contracts for one
feature would only confuse plugin authors.
2026-10-29 13:40:21 +08:00
yetone 181fd0a682 plugin pages: magpie web forwards a page's local service under the page's address
A page whose plugin runs a service on 127.0.0.1 (the community chat page)
sent its frame there, which works only in a browser on magpie's machine:
opened from another computer through magpie web it was refused (Discord DM:
AIGCFREE). magpie.page.service names the port (or the option holding it);
/_magpie/plugin/<token>/_service/ forwards to it with the page token as the
key, without magpie's cookies, and the bridge tells the page (magpie.service).
2026-10-29 13:38:49 +08:00
yetone 3959192e94 gui: Settings' web search rows move out of app.js to plugins/search/settings.js (#4133)
TestCoreScriptBudget was red on main: the context map's tile wording
(a4e929212) and Cindy's Add magpie (628ac36fc) took the core to
1,531,531, over its 1,530,861, and 0ee31d473 then raised both budgets
by its own 1,969 bytes. Settings › Models › Web search (renderSearch,
renderSearcher, the search APIs' keys) is Settings' page, drawn only in
the window, so it moves into the search plugin's settings.js beside
the gateway plugin's, loaded by index.html after it. Both budgets go
back to 1,311,735 and 1,530,861, with no raise: app.js is 1,292,527
and the core well under.

docs: gui-shell.md and plugin-runtime.md name the new file.

Run at this head (rebased on 0ee31d473):
- go test -count=1 -run 'Budget|Script|Asset|Index' ./internal/gui/ on
  Windows (win-run): ok. mote's ssh timed out; Linux can't build the
  gui package (no gtk4/webkitgtk-6.0 there).
- gofmt -l internal/gui: clean.
- account-models, add-partners-shine and api-key-theme GUI files on
  Linux (WSL), Chromium and WebKit: 5 WebKit reds, the same 5 at
  origin/main 0ee31d473 (run twice there; api-key-theme's one passed
  the second time), all listed in #4120.

Run before the rebase (at 449231c19 + this change):
- The internal/gui Go tests on mote: ok except
  TestPluginPageLoadsItsFilesInTheWindow, mote's AppKit pasteboard
  (#4125), which uses its own fake page.
- The whole GUI suite on Linux, about a third through at push time.
  Its reds so far besides those above: chromium en "a Codex account is
  kept for some models" and "the Partners heading lights once an
  opening" (ja 440), both green when their files run alone at this
  head. The rest of the run is checked after the push.

Not tried: the Settings › Web search page by hand in the real app.
2026-10-29 11:49:07 +08:00
yetone ca499953e7 gui: a plugin page with a host part starts the host when it opens
guesssssssswhat on X: the Magiczerowxy/magpie-chat page ("对话") sits
on its loading text and never opens. The page says hello and then
navigates its frame to http://127.0.0.1:3477, a server the plugin's
index.mjs starts inside the Bun host. The host was started only by a
call: at launch while providers are first read, and after a Restart
(a plugin installed, updated or set, a Bun update) or a crash only once
something asked a plugin again. With the host down, WebKit (the macOS
window's WKWebView, WebKitGTK) leaves a frame whose navigation is
refused on its old document with no error, and the hello had already
cleared the 10s broken timer, so the page waits forever. Chromium shows
chrome-error instead.

Now serving the entry HTML of a page or panel whose plugin is not
page-only starts the host if none is up (plugin.Warm), waiting at most
7s, then serves the page. Page-only plugins, and the page's other files
and the bridge, don't touch the host.

Reproduced on mote (sandbox HOME, magpie web on a free port, plugin
0.1.16 from GitHub): with its 3477 listener killed, old main's page
stays on "正在连接到本地对话服务…" in Playwright WebKit (chrome-error
in Chromium); the fixed build restarts the host on open and the chat UI
loads in both engines. In the real macOS app (wails://) the frame
reaches 127.0.0.1 (seen by a logging server). TestPluginPageStartsItsHost
is red with the pageHost call removed by hand.

Run at this head (84a6a2c42 + this), on mote: gofmt -l clean; go vet,
GOOS=linux go vet -tags nogui, GOOS=windows go vet; go build,
GOOS=linux go build -tags nogui, GOOS=windows go build; go test ./...
-timeout 45m: every package ok except internal/gui's
TestMainWindowCorners/macOS_26_SDK, red on macOS 27 and filed as #3949
(titlebar, untouched here). plugin-page.test.cjs and
plugin-kinds-discover.test.cjs, Chromium and WebKit, 14/14 each.
Rebased on 29181eb78 (usage, gateway; no file here), then go vet and
go test ./internal/gui/ ./internal/plugin/ again: same, only #3949 red.
Pushed on b586fdf1e, whose two commits (app.css, usage pricing) weren't run with this.
win-run: go test -run 'TestPluginPage|TestWindowPage' ./internal/gui/
./internal/plugin/ ok.

Not tried: the reporter's OS and magpie version; the real Windows and
Linux app windows (wsl-run can't build internal/gui: no gtk4 or
webkitgtk-6.0 dev packages in magpie-desktop, internal/plugin ok); a
real Restart in the background (simulated by killing the host); the
full GUI suite (no asset changed). magpie-chat 0.1.9 to 0.1.13 had no
main or exports, so they are page-only and no host ever starts them;
0.1.14 restored main, and that's for the plugin to tell its users.
2026-10-28 21:27:47 +08:00
JoeyWu-tech 6f0e40572c gui tests: a plugin's words are its own when said as words (#3897)
yetone (#3897): i18n-keys' "a plugin's words are its own" is red on main
since 7f827b3b0, with 'plugins/library/i18n.js "Runs as":
internal/cli/claude_code_cli.go says it too'. claude_code_cli.go doesn't
say Library's "Runs as": 7f827b3b0's comment "// fetchClaudeRuns asks
the gateway at base for its Claude Code runs" holds it, across a
function's name and the next word, and the check took a key found
anywhere in a file's text, inside a longer word too, as said there.
internal/gateway/claude_runs_test.go's "listClaudeRuns asks" holds it
as well.

The check now counts a plugin's word where it stands as words: a
letter, digit or _ just before a key that starts with one, or just
after a key that ends with one, makes it part of a longer word. A key
said in a string, a comment or markup counts as before, and goes back
to i18n.js. docs/subsystems/plugin-runtime.md says so.

What was run (tree 26d67096, on origin/main e056779a, Node 22.22.1):
- i18n-keys (Node's test runner, no browser) at e056779a, twice: "a
  plugin's words are its own" red with #3897's line, the other three
  tests ok. Here, 6 runs: 4 of 4 each.
- Broken by hand in claude_code_cli.go, a line added and then removed:
  - "// Runs as the gateway asks.", the key said as words: red, with
    'plugins/library/i18n.js "Runs as": internal/cli/claude_code_cli.go
    says it too'.
  - "// fetchClaudeRuns as the gateway asks." and "// Runs asks the
    gateway.", the key glued to a longer word before it or after it:
    4 of 4.
- No Go file is changed and no other test reads this file, so the Go
  suite was not run for it.

Taken from JoeyWu-tech's patch on #3897 (fd49dcc0f; the format-patch
sha256 matches the one posted there), cherry-picked as is onto origin/main
7dcc0aedc. Run again on mote at that head: i18n-keys 4 of 4; with
"// Runs as the gateway asks." added to claude_code_cli.go by hand, red
with #3897's line.
2026-10-28 12:01:47 +08:00
yetone 8bade6c5e2 provider: a plugin's usage window can be a prepaid wallet's balance (#3950)
SuperMagic's accounts (mycf_711's magicrew plugin) are prepaid wallets of
points with no total. A plugin can now send a usage window as
{name, balance: 6291, unit: "积分"} with no used or limit.

- host.js passes a finite balance on (at least 0), anything else as null.
  plugin.UsageWindow.Balance and provider.QuotaWindow.Balance are *float64.
- quotaOfPlugin keeps the figure and does not make the window Text or
  Aside, so routing knows the account with no Used invented. allowanceOf
  copies it into Limit.Balance; an empty wallet counts as used up.
  Allowance.Left(model) is the least balance of the windows that count
  the model.
- weighRouted fills routes.Seat.Left and Seat.LeftIn (the account's
  provider and unit). Smart, pace and usage (least used) put the seat
  with more left first where they would otherwise tie (byLeft), only
  when every seat with a balance shares one LeftIn: balances in two
  units or two providers are never compared. Tiers still come first.
- The Usage card, the Routing page (Weighed.Balance: the small row's
  text, no bar, a why sentence, the account list), magpie accounts and
  the status line show the figure, "6,291 积分 left", never a share.
- Docs: provider-plugins (new section), gateway-routing,
  providers-accounts, plugin-runtime, host.js typings and the site's
  plugins page (en, zh, ja).

Run, at base f13aafa87, on mote:
- go test -tags nogui -timeout 45m ./...: 72 packages ok; red were
  TestQuotaSpanCarriesEveryWindowField (this change's: its fixture now
  sets Balance, green after), and on the unchanged base too
  TestWSLColdPlaceOpensNothing (#3924), TestFetchAsksASharedBaseOnce and
  two siblings (#3854), TestTUIFetchesSubscriptionModels (#3919), all
  fixed on main since and run again after the rebase; and
  TestPluginStreamsPastTheBudgetWait (#3946), green alone on both.
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/..., go
  build ./..., gofmt -l: clean.
- New tests: TestPluginWalletBalanceIsAReading, TestAllowanceLeftIsTheLeastBalance,
  TestPluginHostPassesABalanceOn (through real Bun and host.js),
  TestWalletsGoByWhatTheyHaveLeft, TestWalletLeftWithinItsTier,
  TestWalletWithMoreLeftGoesFirst, TestQuotaCell's balance cases;
  usage-wallet-balance.test.cjs and routing-wallet-balance.test.cjs,
  34 of 34 in Chromium and WebKit, en zh zh-TW ja de, 1100/900/420/390px.
- GUI: every quota*, usage*, panel*, routing*, i18n* and tray* file (220
  files, 2928 tests), concurrency 4: 130 red, in 21 files. Those 21 files
  run again on an unchanged base copy and on this change, concurrency 2:
  the same 19 files red on both (126 and 131), the differing subtests
  being routing-rule-remove / rules-line / intent-entry flaps that go
  both ways. Each is filed (#3679, #2115, #3410, #3404, #3411, #3897,
  #1905, #3096, #3593, #3408, #3409, #3799, #3789, #3412, #3947, #3415,
  #3414, #1345); routing-story-shrinks had none and is #3954.

After rebasing on origin/main 833f51adc, on mote: Linux and Windows vet,
go build, gofmt clean; go test -tags nogui of internal/routes, provider,
gateway, cli, plugin, gui (the script budgets), agent and tui: all ok;
the two wallet GUI files and i18n-keys: 37 of 38, the red being
i18n-keys' "Runs as" (#3897, not this change).

Broken by hand, each red then restored: quotaReport's Balance copy
removed (TestQuotaSpanCarriesEveryWindowField red); byLeft always nil (routes and
gateway tests red); host.js's balance line removed (host test red);
quotaOfPlugin's balance copy removed (provider tests red); app.js and
client.js at base (both GUI files 34 of 34 red, "0% used" / "已用 0%").

Not tried: a real SuperMagic account or the magicrew plugin (it isn't
in the community repo; it needs to send balance), Windows and Linux
GUI apps, and the WebKitGTK app.
2026-10-28 08:28:56 +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 05eeb4e1b9 gui: a recorded call's body viewer moves from app.js to the Gateway plugin's script
callBodyPanel and what only it uses (the JSON tree, the stream's events
and reply, sseView/sseShown) move whole, unchanged, from app.js to the
end of plugins/gateway/client.js. Nothing in the core called them: the
Gateway page's recent calls, Usage's ledger and Routing's trace do, and
every plugin's script is loaded by index.html whether the plugin is on
or off, before any of them runs. app.js goes from 1,320,558 to
1,304,307 bytes; the budgets are not changed here. This makes room for
the per-account eye in the next commit without raising a budget.

Checked that the moved block is closed: none of its 12 names (and
sseView, sseShown) is used in app.js outside it, or in context.js,
plugins.js, kernel.js, pluginpages.js or start.js, and none is declared
in another script. docs/subsystems/plugin-runtime.md says where it is.

Run at this commit (Chromium + WebKit, NODE_PATH playwright 1.62.0):
json-tree, recent-call-bodies, request-archive-usage, request-archive,
routing-bodies, sse-body and i18n-keys: 58 pass, 0 fail.
go test ./internal/gui -run 'TestCoreScriptBudget|TestBuiltinClientsLoaded': ok.
The whole GUI suite and go test ./internal/gui ran with the next commit
at the pushed head (see its body).
2026-10-26 18:18:18 +08:00
yetone f21dd99f5a privacy: every masking is recorded, and Settings › Privacy shows it
What was masked is now kept, so the user can see it. Settings › Privacy
opens on a summary card: how many values were kept from vendors over 1,
7 or 30 days, by kind, by finder (rules, your words, the local model,
known values) and by where they went, with a day strip. The page is
grouped into What to mask, How it's found (rules and the local model are
layers, not a toggle: the model adds names and addresses rules can't
see) and Sharing. A records view lists each masked request: its kinds,
finders, placeholders and, while magpie runs, the line around each
value. Gateway › Recent calls and the Routing log carry a masked-N badge
that opens the record.

Originals never go to disk. internal/maskrec writes day files under
~/.config/magpie/masking (0600, 30 days, 100MB at most) holding kinds,
finders, placeholders, a first character or key prefix and a length.
The lines around values are kept in memory for the last 400 records
only, and /api/masking/value answers only while the masker remembers a
placeholder. Nothing is written under MAGPIE_TEST_SANDBOX.

A masker says what it masked through gwmw.Teller (JSONHits, TextHits,
Value); a plugin masker that doesn't is counted only, so older redact
plugins keep working. Every route that masks notes it: chat, Responses,
Codex backend and search, embeddings, images, video, transcription,
decide and the search MCP query. Masking still fails closed: a masker
that panics on any path refuses the request (TestMaskingOnAndOff's fake
now panics on JSONHits and TextHits too, since the gateway asks a Teller
through those).

app.js grows to 1,314,432 bytes, so its budget rises to 1,335,000 and
the core's to 1,528,800 (+1.5%): Settings is the core's own page.

Run at this head (rebased on origin/main a3ebed202):
- go vet clean on macOS, GOOS=linux -tags nogui and GOOS=windows;
  go test ./internal/gateway ok (561s).
- On origin/main c922225f1 (one commit back, the packages either side
  touches): agent, gateway, gui, gwmw, maskrec, provider, redact ok.
- On origin/main 592899467: go test ./... -timeout 45m, 65 packages ok;
  agent and gateway hit the 45m timeout under load ~26 (each mid-way
  through a short test, not a hang) and pass alone with -timeout 100m
  (1133s, 890s).
- GUI, on 592899467, the 42 files this change or main's new commits reach (privacy-*,
  redact-*, masking-records, settings-*, gateway-*, routing-bodies,
  routing-request-metrics, routing-log-icons, account-discovery,
  click-scroll, i18n-keys, old-webkit), both engines, every language:
  475 tests, 475 pass. routing-bodies is green here since 2543fb2c1.

Run on the previous base, origin/main c84864ffc (the whole suites):
- go test ./... -timeout 45m: every package ok (66), exit 0. An earlier
  run found TestMaskingOnAndOff/panics (its fake, above) and
  TestCoreScriptBudget (the budget, above); both fixed.
- gofmt -l clean; go vet on macOS, GOOS=linux -tags nogui and
  GOOS=windows clean; node --check on the changed scripts.
- GUI suite, both engines, every language, --test-concurrency=6:
  11533 tests, 11483 pass, 50 fail. Each failing file rerun alone here
  and on origin/main:
  - red the same on main, filed: codex-predictions (#2624),
    usage-checkin (#2549), usage-agents-hide (#2276), usage-fold
    (#2163), s3-sync (#2448), quota-count-wrap and
    quota-name-translated (#2228), routing-request-metrics (#2571),
    routing-bodies (#2559: red at its "second request pressed" step;
    this change's badge checks before and after it pass),
    routing-rule-remove (#3096, filed now: 0 2 1 alone here, 0 0 2 on
    c84864ffc).
  - load, pass alone: group-member-weight (#2387), routing-model-rest,
    context-tune (Chromium didn't launch in 180s at load average ~45;
    0 0 0 alone on both). An earlier whole run's library-chip-fan red is
    #3072 (filed), plugin-card-update #3079, lightweight #2638,
    segs-glide #2683.
  - mine, fixed: old-webkit, three ":hover, :focus-visible" lists
    Safari before 15.4 drops; split, 6/6.
- Broken by hand, each went red: masked values kept on disk
  (TestNoValueOnDisk), a snip that runs past an escaped quote
  (TestSnipStaysInItsString), the shared-line dedup in the records view
  (masking-records, 10 of 12).
- Real app in a sandbox HOME with the local model on: the summary card,
  flow, chips and records view in light and dark; persons and
  addresses, Chinese names among them, recorded by=model; a grep of the
  masking folder and the sandbox config for the masked values found
  none.
2026-10-21 06:12:37 +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 f73378365f gui: a filter a click set on Usage's Requests goes when they are left (TJHHHH on Discord)
TJHHHH: after a jump to Codex's requests on the Usage page, every later
visit listed only Codex's. The Requests' filters are module state in
plugins/usage/page.js and nothing ever reset them, so a click on Codex in
the ranking split by agent stuck for the app's lifetime.

Now a filter a click lent the Requests (a ranking click on an agent,
provider, model or gateway key, a chart day, the address's ?agent= and
the like, a route from Routing) is remembered in ledLent and given back
by ledLeave when the reader leaves the Requests: for another Usage tab
(renderUsageTab), or another page through a new page hook, `leave`, that
show() calls on the page it leaves. A filter picked in its own menu or
typed in the search stays, as a menu choice does in a Mac app. A route's
saved filters keep their lent marks, and leaving with a route on gives
back the route too. Docs: plugin-runtime.md's Usage hooks.

Siblings judged and left: the tray panel's Usage tab ranking (its own
view, not the page's Requests), the Sessions reveal (per agent, no "all"), the KPI
failed/retried jumps (shown in the status segment, read as own picks).

Test: tests/usage-ledger-leave.test.cjs, chromium and webkit, en zh
zh-TW ja de: ranking click leaves for a page and for a tab, menu pick
stays, ?agent= goes, a route goes. On the old app.js/page.js/client.js
it is red, 20 of 25 in chromium ("back from another page: last asked
period=today&agent=codex"); only the menu-pick case passes there.
Green with the fix, in both engines.

Run at 5b267fbd8 (load 200-400):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- go test -timeout 45m ./...: 60 ok; internal/agent, gateway, library
  past 45m (#2544, #2870, #2853), internal/gui
  TestSetAnswersWhileDevinAndProvidersHang 13s (#1375). All filed, none
  touch these files.
- Whole GUI suite (node --test --test-concurrency=4, both engines):
  i18n-keys was red on my comment saying "View usage" (routing's word);
  reworded, i18n-keys green. codex-auto-reset, codex-auto-reset-settings
  and codex-predictions red in the full run; rerun alone: codex-auto-reset 20/20 and codex-auto-reset-settings 22/22
  green (load); codex-predictions 7 of 20 red at 420px, the same as
  #2624 on main. usage-ledger-leave 52/52 alone. The whole suite was
  still running at commit time (load ~400); its reds so far are these.
2026-10-19 21:59:40 +08:00
yetone d783df46cb plugin: a plugin's page adds items to a provider's and an agent's row menu (P6)
package.json's magpie.actions: [{id, menu, title, titles}] puts items in
the row menus magpie draws, after its own: a provider row's (right-click)
and an agent row's (its handle, or right-click). Picking one opens the
plugin's page and posts it {event: "action", data: {id, provider|agent:
{id, name}}}, nothing else of the row; the bridge's magpie.onAction(fn)
gets it, and an action picked before fn was given waits for it.

- plugin.Window reads them (page.go): menu one of ActionMenus (provider,
  agent; a session's menu is left out, its title is user content), id
  ^[a-z0-9][a-z0-9-]{0,39}$, an id given twice is the first's, 8 at most,
  none for a plugin with no page.
- /api/plugin-pages carries them on the page; a missing title is the
  page's, in each language (pluginpage.go).
- pluginpages.js: magpie.actions(menu, context) gives the row menu's
  items; openRowMenu draws a plugin's name as written (literal), not
  through t().
- The Plugins page says which menus a plugin adds to (actionsLine),
  translated in zh, zh-TW, ja and de.
- Docs: plugin-runtime.md's P6 section and verification; the site's
  plugin docs (en, zh, ja) gain "Items in magpie's menus".
- The core's budget (TestCoreScriptBudget) is not raised (#2710): with
  P6 the core came to 1,447,648 bytes, 648 over. pluginpages.js's header
  now says P5's and P6's part in one paragraph and points to
  plugin-runtime.md, which says it in full, and plugins.js's panels and
  actions lines share whereLine: 1,446,845, 155 under.

Run:
- Full: this series (P5, the Plugins dot, the probe test, P6, and a
  built-ins-on commit since dropped for main's own 5a2414acd) was run
  together, at load 200-660.
  At the pushed tree, 88dfab2d3 on origin/main 5380114da (rebased
  from 210bc2b77, no conflicts; its GUI assets and tests are the same
  bytes as the tree the GUI runs below used, diff -rq): gofmt clean,
  vet darwin/linux nogui/windows ok, TestCoreScriptBudget ok
  (1,446,845 of 1,447,000). go test -timeout 45m ./... at load
  193-278: 62 packages ok, red in TestMainWindowCorners (#1936) and
  TestPluginStreamLargeReplies JSON_fast (client timeout; alone 1 of
  3 red here, 0 of 3 on 5380114da side by side at load ~280; the
  series doesn't touch the stream path; #2551 reopened with the
  output, taken). Two earlier runs at this tree are discarded: one
  stopped when the disk filled, one when another session's go clean
  -cache emptied the build cache mid-run. The whole GUI suite at
  this tree was not finished (the disk filled); the files the series
  reaches ran (1318 tests, 124 red), and the 39 red files ran again
  at concurrency 1 on both trees: here 148 ok 120 red, origin/main
  135 ok 127 red. Both sides' reds are page.goto/launch timeouts
  under load (66 here, 71 there) and the same assertions:
  title-bar-tools' and settings-proxy-auth's "access control checks"
  on a cut-off /api/providers read (#2740, taken next), sidebar's
  "the list unrolls" and WebKit "#prefs pressed darkens" (#2684;
  alone, 1 red here, 3 on main), side-toggle (#2732); plugin-move
  red on main only. Six files again one by one on both trees:
  plugin-actions red 1 of 6 here, a 5s goto of ?view=plugins at load
  260; plugin-clash red on both; plugin-own-icon, plugin-gateway,
  plugin-checkin ok on both; settings-proxy-auth ok here, 3 red on
  main.
  At 976c9893a (on origin/main 6f950653f): go test -timeout 45m ./...
  red only in TestMainWindowCorners (#1936, the window's process
  killed at its deadline) and TestSetAnswersWhileDevinAndProvidersHang
  (#1375, 3 of 3 alone). The whole GUI suite, both engines: 10834
  tests, 237 red in 73 files, 184 of them a 180s browser launch. Those
  73 files run again at concurrency 2: 52 green, among them every
  plugin-* and agent-* file and plugin-actions; the 21 still red were
  run at origin/main f191d6423 and are red there too: codex-predictions
  (#2624), lightweight (#2638), segs-glide (#2683), usage-agents-hide
  (#2276), provider-advanced-fold (#2552), routing-bodies (#2559),
  routing-model-rest and rest-try-now (#2115, #2564), routing-keys-fold
  (#1612), routing-wb-restricted (#1905), routing-request-metrics
  (#2571), quota-count-wrap and quota-name-translated (#2228), s3-sync
  (#2448), usage-checkin (#2549), usage-ledger-abort (#2700),
  tencent-access-key (#2733), usage-range (#2734); side-toggle's WebKit
  motion red 1 of 3 on main, 0 of 3 here (#2732); usage-fold green alone.
  Rebased onto origin/main 717b69f78 (60725faa1, no conflicts): gofmt
  clean, vet darwin/linux nogui/windows ok; go test -timeout 45m ./...
  red in TestSetAnswersWhileDevinAndProvidersHang (#1375) and agent and
  gateway at the 45m alarm with tests still moving at load 400+, both ok
  alone (1173s, 1167s); 105 GUI files the series reaches (plugin*,
  sidebar*, side-*, settings*, title*, header*, agent-*): 1322 tests,
  23 red, run alone 214 of 218 ok, the 4 left in sidebar and
  sidebar-overlay-scrollbar (WebKit), red on 717b69f78 too (#2684,
  #1863). The whole GUI suite was not run again after the rebase.
- gofmt -l clean; go vet darwin, linux (-tags nogui) and windows ok;
  TestCoreScriptBudget ok.
- go test -run 'TestWindowActions|TestPluginPageActions' ok: duplicate,
  malformed and session-menu ids dropped, 12 actions kept to 8, none
  without a page, an off plugin's not served.
- plugin-actions.test.cjs: chromium and webkit, en zh zh-TW ja de, at
  1100 and 420: no page adds nothing; the agent menu ends with Hide then
  the plugin's item; the provider menu's item is in the window's
  language; a pick opens the page, which gets exactly {id, provider|
  agent: {id, name}} once, in one frame, though it calls onAction 400ms
  late. The Plugins row says which menus.
- Broken by hand, each red then restored: the bridge not holding an
  action picked before onAction (the late-registering fixture), the
  provider's whole row posted in place of {id, name} (the exact-data
  check), any id and any menu accepted (TestWindowActions).
- Neighbours in both engines: plugin-page, agent-cli-missing,
  agent-disconnect, group-bulk-remove, model-test-why and provider-find
  ok; plugin-panels red before P5's fixture fix (padding, in that
  commit), ok after.
- Real use: a dev build (-tags dev) in a sandbox HOME with a
  local plugin of two actions; WebKit on its dev UI picked "Inspect
  agent" on Claude Code and "Inspect provider" on a local provider, and
  the page logged {"id":"about-agent","agent":{"id":"claude","name":
  "Claude Code"}} then {"id":"about-provider","provider":{"id":
  "local-try","name":"Local Try"}}, one frame. Not clicked in the
  WKWebView window itself; the frame's loading there is
  TestPluginPageLoadsItsFilesInTheWindow's.
2026-10-18 07:13:12 +08:00
yetone b9f790d37b plugins: panels in magpie's pages, a page that replaces a built-in one, titles in the window's language, and a look that matches
P5 of the plugin runtime (docs/subsystems/plugin-runtime.md):

- Panels (magpie.panels): a plugin draws a frame into a slot of a
  built-in page (a provider's editor, Settings, Usage); magpie.context
  says where it is, and the frame is as tall as what it draws.
- A page can replace a built-in one (magpie.page.replaces); show() opens
  it in that page's place, and the sidebar row goes to it.
- page.titles and a panel's titles name it in the window's language
  ({"zh": …}); a malformed map is dropped, the title kept
  (TestWindowTitles).
- main's #2501 already names wails:// in the policy of a page in the
  desktop window (through ownWindow), which is why the usage page drew as
  bare HTML from v0.1.1259. TestPluginPageLoadsItsFilesInTheWindow loads
  a page through ownWindow in a real WKWebView, which Playwright on http
  can't; the subsystem page says how.
- The bridge adds magpie's look for what a page leaves unstyled, every
  rule in :where() so any rule of the page's wins, and the theme's
  colours as --magpie-* variables.

One commit: the panels, the replacing pages and the titles share hunks
in page.go, pluginpage.go, pluginpages.js and the docs, and couldn't be
split cleanly.

Run:
- Full: this series (P5, the Plugins dot, the probe test, P6, and a
  built-ins-on commit since dropped for main's own 5a2414acd) was run
  together, at load 200-660.
  At the pushed tree, 88dfab2d3 on origin/main 5380114da (rebased
  from 210bc2b77, no conflicts; its GUI assets and tests are the same
  bytes as the tree the GUI runs below used, diff -rq): gofmt clean,
  vet darwin/linux nogui/windows ok, TestCoreScriptBudget ok
  (1,446,845 of 1,447,000). go test -timeout 45m ./... at load
  193-278: 62 packages ok, red in TestMainWindowCorners (#1936) and
  TestPluginStreamLargeReplies JSON_fast (client timeout; alone 1 of
  3 red here, 0 of 3 on 5380114da side by side at load ~280; the
  series doesn't touch the stream path; #2551 reopened with the
  output, taken). Two earlier runs at this tree are discarded: one
  stopped when the disk filled, one when another session's go clean
  -cache emptied the build cache mid-run. The whole GUI suite at
  this tree was not finished (the disk filled); the files the series
  reaches ran (1318 tests, 124 red), and the 39 red files ran again
  at concurrency 1 on both trees: here 148 ok 120 red, origin/main
  135 ok 127 red. Both sides' reds are page.goto/launch timeouts
  under load (66 here, 71 there) and the same assertions:
  title-bar-tools' and settings-proxy-auth's "access control checks"
  on a cut-off /api/providers read (#2740, taken next), sidebar's
  "the list unrolls" and WebKit "#prefs pressed darkens" (#2684;
  alone, 1 red here, 3 on main), side-toggle (#2732); plugin-move
  red on main only. Six files again one by one on both trees:
  plugin-actions red 1 of 6 here, a 5s goto of ?view=plugins at load
  260; plugin-clash red on both; plugin-own-icon, plugin-gateway,
  plugin-checkin ok on both; settings-proxy-auth ok here, 3 red on
  main.
  At 976c9893a (on origin/main 6f950653f): go test -timeout 45m ./...
  red only in TestMainWindowCorners (#1936, the window's process
  killed at its deadline) and TestSetAnswersWhileDevinAndProvidersHang
  (#1375, 3 of 3 alone). The whole GUI suite, both engines: 10834
  tests, 237 red in 73 files, 184 of them a 180s browser launch. Those
  73 files run again at concurrency 2: 52 green, among them every
  plugin-* and agent-* file and plugin-actions; the 21 still red were
  run at origin/main f191d6423 and are red there too: codex-predictions
  (#2624), lightweight (#2638), segs-glide (#2683), usage-agents-hide
  (#2276), provider-advanced-fold (#2552), routing-bodies (#2559),
  routing-model-rest and rest-try-now (#2115, #2564), routing-keys-fold
  (#1612), routing-wb-restricted (#1905), routing-request-metrics
  (#2571), quota-count-wrap and quota-name-translated (#2228), s3-sync
  (#2448), usage-checkin (#2549), usage-ledger-abort (#2700),
  tencent-access-key (#2733), usage-range (#2734); side-toggle's WebKit
  motion red 1 of 3 on main, 0 of 3 here (#2732); usage-fold green alone.
  Rebased onto origin/main 717b69f78 (60725faa1, no conflicts): gofmt
  clean, vet darwin/linux nogui/windows ok; go test -timeout 45m ./...
  red in TestSetAnswersWhileDevinAndProvidersHang (#1375) and agent and
  gateway at the 45m alarm with tests still moving at load 400+, both ok
  alone (1173s, 1167s); 105 GUI files the series reaches (plugin*,
  sidebar*, side-*, settings*, title*, header*, agent-*): 1322 tests,
  23 red, run alone 214 of 218 ok, the 4 left in sidebar and
  sidebar-overlay-scrollbar (WebKit), red on 717b69f78 too (#2684,
  #1863). The whole GUI suite was not run again after the rebase.
- plugin-panels' tall panel (body{margin:0}) measured 220, not 180,
  after the look above gave an unstyled body 20px of padding; the
  fixture now sets padding:0 too, as a page that wants none would.
  plugin-panels ok in chromium and webkit after.
- gofmt -l clean; go vet darwin, linux (-tags nogui) and windows ok.
- GUI: plugin-page and plugin-panels in chromium and webkit, en zh zh-TW
  ja de, wide and narrow, ok.
- Broken by hand, each red then green: titled() in pluginpages.js
  (the "draws in its frame" test), the wails:// scheme in pagePolicy
  (the WKWebView test, before the rebase onto #2501), titles' parsing
  (TestWindowTitles).
- Real use: the published @magpie-community/page-usage 0.1.1 in a
  sandbox magpie window, its tiles styled.
2026-10-18 07:13:09 +08:00
yetone 5a2414acdd plugins: every built-in plugin starts on, a new install's too
The owner (10-17): "所有的内置插件默认都应该是开启的", "尤其对新用户来说……
不然新用户都不知道有哪些功能". Since 3ccbe6bc1 (10-13) a new install was
written plugins.yml with the Essentials preset, which left Sessions, the
Library, routing groups, warm-ups and Observability off for every new user
(origin/main's binary, fresh sandbox HOME: those five "off").

- pluginrt.Settle() writes All when there is no plugins.yml, new install or
  not; settings.RanBefore, which only told the two apart, is gone.
- plugins.yml gets `settled: 1`. A file below it is brought up once on
  start: an Essentials preset becomes All, the user's own rows kept (a
  plugin they turned off stays off). Every write (Set, SetConfig,
  SetPreset) sets it, so `magpie plugin preset essentials` picked
  afterwards stays the user's. An unreadable or unparsable file is left
  alone, as before.
- Docs (plugin-runtime.md) and comments that said a new install starts
  with Essentials.

Run (origin/main 72ed518bc + this):
- gofmt -l internal: clean; go vet pluginrt, cli, gui, settings: clean.
- go test ./internal/pluginrt/ ./internal/settings/: ok. New
  TestSettleBringsUpAnEssentialsInstall; TestSettleAndSet and
  TestBuiltinSwitch now check a new install has all 14 on.
- Broken by hand (Settle writing Essentials, the bring-up skipped):
  TestSettleAndSet, TestSettleBringsUpAnEssentialsInstall and
  TestBuiltinSwitch go red; restored, green.
- Real binary, sandbox HOME: a new install lists all 14 on and writes
  `preset: all, settled: 1`; a plugins.yml of `preset: essentials` with
  otel off comes up `preset: all`, groups/library/sessions/warmups on,
  otel off.
- go test -count=1 -timeout 45m ./...: every package ok but internal/cli
  (TestPluginLoginTakesTheLapseOff, passes 5/5 alone here and on
  72ed518bc; filed #2748) and internal/gui (TestMainWindowCorners, #1936).
- GUI: builtins.test.cjs 4/4 (chromium + webkit; a first try under load
  ~445 had chromium's page.goto time out at 5s, #2542),
  routing-groups-off.test.cjs pass. Only comments changed in those two.
2026-10-17 22:54:38 +08:00
yetone b6533893a7 plugins: Discover lists tools and page plugins, and the intro links to the plugin docs
Every kind of plugin magpie runs now has its place on the Plugins page, so
someone looking to extend magpie finds what exists and how to write one:

- Discover has "Tools for agents" (market kind "tools") and "Pages" (kind
  "page") sections beside Subscriptions, Gateway middleware and Agents,
  each card with its own chip (a new Tools chip, the Page chip). Before,
  both kinds fell under Subscriptions as Providers.
- A GitHub repository tagged magpie-plugin whose package.json has
  magpie.page.file is a Page, and that file must be committed, as a
  provider's entry must (TaggedRepos).
- An installed plugin that only gives tools wears the Tools chip.
- The intro says what a plugin can be (provider, gateway middleware,
  routing strategy, tools, an agent, a page) and its "Write a plugin" link
  opens usemagpie.ai/docs/plugins in the window's language (zh and zh-TW
  to zh/, ja to ja/), outside the window.
- The docs' Publishing section lists the "tools", "page" and "agent"
  registry kinds and the community package names for each, in en, zh, ja.

Run at the reviewed head (on origin/main cf21b71ff):
- go test ./internal/plugin: ok. Broken by hand: without the page case,
  and with the page's entry not checked, TestTaggedRepos goes red.
- plugin-kinds-discover.test.cjs (new): 5 languages x 980/420 x chromium
  and webkit, green. Broken by hand, each red: the old plugins.js (11/11
  fail), no "tools" kind (11/11), no ja/zh-TW docs link (3), no Tools chip
  on an installed row (11/11).
- plugin-middleware.test.cjs's intro test now checks the new copy and link;
  it still checks the click scrolls nothing.
- Every plugin*.test.cjs and i18n*.test.cjs, both engines: 505 pass, 0 fail.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: 0.
- go test -timeout 45m ./...: all 66 packages ok (full=0).
2026-10-16 01:48:45 +08:00
yetone 206dc24cd5 gui: with the Sessions page switched off, a latest session on Usage unfolds its details, not a click that does nothing (#2311, betacatZ)
Usage › Sessions' latest sessions open on the Sessions page. With that
page switched off in Plugins › Built-in (the reporter's screenshot has no
"All sessions" beside the search, which is hidden the same way), the row
still looked like a link, with a chevron and a pointer, and a click
returned without doing anything.

Now, with Sessions off, the row is a button (aria-expanded) that unfolds
the session's details in place, as a top session's do: time, folder,
session id, the resume command, what each model spent, the file. One is
open at a time, Enter and Space fold it, and nothing scrolls. With the
page on, a row still opens there.

Run: internal/gui/tests/sessions-usage-off.test.cjs (new, 12 cases:
Chromium and WebKit, en and zh, 900 and 420px) passes; with page.js put
back to HEAD its 4 Chromium "off" cases fail and the "on" cases pass.
sessions-usage-open, sessions-paging, sessions-in-range,
sessions-overview and builtins pass (84). Go tests not run here (disk
under 6G free); no Go file changed.

Full suite: SUITE_LINE
2026-10-15 23:08:01 +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 64b0f3a201 plugins: a community plugin's own page in magpie's window, shut in a sandboxed frame (P4)
A plugin's package.json may declare magpie.page {title, file, icon} and
magpie.permissions.reads. While the plugin is on, its page gets a tab in a
"Plugins" group after the built-in pages, drawn in an iframe sandboxed to
allow-scripts only (an opaque origin: no cookie, no storage, no parent).
Its files come from /_magpie/plugin/<token>/ (HMAC of the spec with a
per-process secret) under a CSP with connect-src 'none' and
frame-ancestors 'self'; a path that leaves the page's folder, a symlink
out, or an off plugin's token is refused. The window's postMessage bridge
answers only that frame (event.source checked) with theme and language,
the plugin's own options.get/set (throttled), and the reads it declared;
any other read is refused in the window and again by the server, and no
read carries a secret. /api refuses Origin: null and frame/iframe
fetch-dest requests (noFramedAPI), so the frame never reaches the GUI's
API even with the cookie. A page that throws or never says hello shows
the kernel's broken-page state with Try again. The Plugins page shows the
page and what it reads before the plugin is turned on.

Docs: gui-shell.md, plugin-runtime.md (P4 section), site docs en/zh/ja
with an example plugin; i18n zh, zh-TW, ja, de; fixture in
internal/gui/testdata/page-plugin.

Run (worktree at base 4df1ba0c6, -p 2, one package at a time):
- go test -count=1 -timeout 45m: internal/gui ok, internal/plugin ok,
  internal/pluginrt ok, plugins/... (budget groups middleware otel redact
  rotation search) ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.
- Playwright (chromium + webkit, 5 languages, narrow widths): plugin-page 4/4,
  plugin-kernel 4/4, builtins 4/4, i18n-keys, gui-de, gui-ja, gui-zh-tw 3/3,
  plugin-middleware 24/24, plugin-own-icon 22/22, plugin-options 22/22,
  plugin-local 8/8, plugin-agent 22/22, click-scroll 22/22.

Broken by hand, each went red: CSP without connect-src; apiFramed always
false; the server's read check removed; the noFramedAPI wrap removed from
api.go (red through the real Handler); inside() letting every path
through; CORP same-origin re-added; in JS the client read check removed,
the ev.source check removed, and allow-same-origin added to the sandbox.
Without the Array.isArray guard on /api/plugin-pages, plugin-kernel,
builtins and plugin-middleware/own-icon/options went red (their mocks
answer a non-list) - that was found by the run, then fixed.

Real use: built magpie, `magpie web` on 127.0.0.1:3472 (gateway 3471) in a
sandbox HOME with the example plugin added. curl: the page file loads
with the CSP and no cookie, traversal and a bad token are 404, /api with
Origin: null or Sec-Fetch-Dest: iframe is 403 even with the cookie, an
undeclared read 403, a declared one 200. Chromium and WebKit at 1100 and
420: the page draws its declared read, the probe's fetch/absolute
fetch/top access/undeclared read are all refused, an <img> of /api is
refused, no page errors. Real use found that a
Cross-Origin-Resource-Policy: same-origin header blocked the frame's own
files (its origin is opaque); it is gone and a test guards it.

Not tried: the desktop (Wails) window. Market cards of plugins not yet
installed don't show a page's reads. The Playwright suite mirrors the
CSP in a mock route rather than the Go server (the Go tests and real use
cover the server).
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 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