Commit Graph
206 Commits
Author SHA1 Message Date
yetone d4f1d6480c plugin: a program a plugin starts with no folder runs in plugin-work, not beside magpie's settings
jiakun_zhao on X asked whose page_<hash>.html, magpie_home.html,
magpie_install.sh and magpie_*.md files they had found after using the
chat page plugin (Magiczerowxy/magpie-chat). That plugin starts the
user's MCP servers from the plugin host with node:child_process spawn
and no cwd, and runs their tools for a model. The host runs in magpie's
config folder (~/.config/magpie), so every file such a tool saved by a
relative name went beside settings.json and providers.json, and a tool
told to write "providers.json" would have written over magpie's.

host.js's spawn wrapper (which already hands on the proxy and keeps
programs off the host's stdio) now starts a program that names no
folder of its own in <config>/plugin-work, created on first use, with
PWD to match outside Windows. A folder the plugin gives is kept.

Not the cause of files in the user's home folder: magpie's host never
runs in ~, and no magpie code names a file page_<hash>.html or calls a
user's MCP tool itself. Files in ~ come from a process whose folder was
~: the chat's server started by hand (node serve.mjs) from ~, or
another agent run there. Filed on magpie-chat for the plugin to give
its MCP servers a workspace of its own and tell the model where it is.

Run (mote, macOS):
- TestPluginProgramsRunInTheirOwnFolder (new; testdata/clicwd checks
  child_process spawn, spawn with env, execSync and Bun.spawn, plus an
  own cwd kept): ok. Red with origin/main's host.js put back by hand
  (plugin-work not made; programs ran in the config folder).
- go test ./internal/plugin ./internal/agentplug ./internal/pluginrt
  -count=1: ok (plugin 261s).
- go test ./internal/gateway -run Plugin -count=1 at 581d64b7d: ok.
- Windows (xiaomi-gpu, win-run): TestPluginProgramsRunInTheirOwnFolder,
  TestPluginCLIHasTheProxy, TestFakePlugin: ok.
- gofmt -l: clean.
Not tried: the full go test ./... suite, the real magpie-chat plugin
with a real MCP server and model, Linux.
2026-10-28 22:20:56 +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
yetone ba37e78b4c provider: a plugin model's test is told a queue at once and warms its host first
mingxia_16024 on Discord (v0.1.1862): testing models on Qoder (CN and
international) and WorkBuddy always failed with "qfmodel: context deadline
exceeded", even though agents got answers from the same models.

Cause, checked with the owner's real Qoder account in a sandbox HOME:
- The test already takes the gateway's route: p.Do, then the plugin's
  fetch in the host.
- The Qoder plugin waits out Qoder's free-plan queue (plan queue p3) for
  up to 4 minutes, unless X-Magpie-Fallback is "1". magpie never sent
  that header.
- The probe gives up after 20s. A raw request with no deadline got its
  head after 3m49s.
- The probe's 20s also had to cover the plugin host's cold start and the
  account loader's first run, which can renew the sign-in. A first
  WorkBuddy AI test took 8.4s.

Changes:
- For a plugin provider, probe sends X-Magpie-Fallback: 1, so a queued
  model answers at once with the plugin's queue message.
- It starts the host and runs the account's loader (warmPlugin, through
  the account's proxy) under the caller's deadline, not the probe's.
- A plugin probe waits up to pluginTestWait (60s). The GUI gives a model
  test 3 minutes.
- host.js lists x-magpie-fallback in MAGPIE_ONLY, so no vendor receives
  it.

"Recent calls" lists only the gateway's own calls, for every provider. A
test is written to the Requests page as magpie's own test, timed-out
tries included, so that is unchanged.

The gateway still never sends the header when another candidate follows,
which Qoder 0.2.40 and CodeArts 0.2.3 expect: #4049.

Run (mote-run):
- New tests TestPluginModelTestSaysQueued and TestPluginModelTestColdHost.
  They use the fake plugin's new $FAKE_QUEUE and $FAKE_LOAD_WAIT, with a
  cold host from plugin.Restart.
- go test -tags nogui -timeout 45m ./... at 76218200a: every package ok (77), none FAIL.
- GOOS=linux and GOOS=windows go vet of internal/provider and
  internal/plugin, go build ./..., and gofmt -l.
- Real Qoder account, sandbox HOME, a TestModels of qfmodel:
  - before: failed at 20.00s, twice;
  - after: "Qoder queued the request for qfmodel (this plan's queue: p3);
    try again in 30s" in about 0.5s, twice. One more run got a 200 in
    767ms.

Broken by hand, each red:
- Without the header set: SaysQueued fails with "context deadline
  exceeded" at its 5s wait.
- Without warmPlugin: ColdHost fails with a deadline at 2001ms.
- Without the MAGPIE_ONLY entry: the vendor gets fallback="1".

Not tried:
- WorkBuddy CN with a real account. It reads the desktop app's sign-in,
  which the sandbox doesn't have.
- A cold start on a slow machine or on Windows.
- The GUI button itself. The handler is unchanged.
2026-10-28 18:24:50 +08:00
yetone c48fccfad7 plugin: the dist index is read from GitHub beside jsDelivr's copy, so a plugin npm doesn't have is offered its newer version
star21321321124 on Discord: CodeArts 0.2.3 showed "已自动更新", the page said
every plugin was up to date, and Update did nothing, with 0.2.4 on the
plugins repo's dist branch. npm has neither CodeArts nor River (E404), so
npmAsk's version is the dist index's latest. With the 「国内镜像」 switch on,
index.json was read from jsDelivr first, and a 200 from it was final. A
jsDelivr edge serves the branch as it was when it cached it (s-maxage=43200):
on 10-28 gcore.jsdelivr.net served the index with codearts latest 0.2.3
(age 6631s) while raw.githubusercontent.com, cdn and fastly had 0.2.4. So
the hourly update, Check for updates and Update all saw 0.2.3.

readDistIndex now asks raw.githubusercontent.com beside the mirror (with
the switch on) and merges the two copies: every version either names,
each package's newer latest. Each version keeps the sha512 its own copy of
the branch names, which installDist checks the tarball against as before.
GitHub is waited for 5s (distGrace) past the mirror's answer; unreachable,
the mirror's copy is read alone, as before. Switch off: one read, as before.

River: on dist at 0.1.0 only, nothing newer; the test holds it "current".

Run (mote, at this tree rebased on f20118304):
- go test -tags nogui ./internal/plugin ./internal/source: ok
- go build ./...; go vet (darwin, linux, windows) of both packages: ok
- gofmt -l: clean
Broken by hand: the index read mirror-first again (the old rule) turns
TestDistOnlyPluginUpdatesPastAStaleMirror red in both subtests with
"Status:current Latest:0.2.3", what the user saw. The pure no-mirror case
(npm 404, dist 0.2.3/0.2.4, 0.2.3 installed) already passed on the old code.
Not run: full suite, GUI suite.
Not tried: a real magpie with the switch on against a stale edge (tests
can't reach the network); the stale gcore edge and fresh raw copy were
checked with curl only.
2026-10-28 13:55:16 +08:00
yetone 955cb43812 plugin: Bun reads the system's trust store itself (NODE_USE_SYSTEM_CA)
明霞 (Discord, Windows) behind an HTTPS-scanning box whose root is in the
OS store: every plugin request answered "self signed certificate in
certificate chain" (WorkBuddy AI on Routing), and updating the Qoder
plugin failed with UNABLE_TO_GET_ISSUER_CERT_LOCALLY.

magpie gave Bun only NODE_EXTRA_CA_CERTS, a file of the roots as magpie
read them: on Windows the current user's ROOT view only. Bun's own system
loader (root_certs_windows.cpp, Bun 1.4.2) reads ROOT, CA and
TrustedPeople of the machine, the user, group policy and the enterprise,
server-auth certs only: an intermediate a proxy doesn't send and a root
pushed by policy are there and weren't in magpie's file. bunCommand,
which starts every bun (the plugin host, bun add/update, the dist-branch
install), now also sets NODE_USE_SYSTEM_CA=1. Bun's runtime fetch and
bun add's HTTP client both build their store in us_get_default_ca_store,
which merges the system store when that variable is 1 (checked in
Bun's source at bun-v1.4.2, and by running it). Verification is never
turned off. A NODE_USE_SYSTEM_CA the user set (0 too) is kept; a
NODE_EXTRA_CA_CERTS the user set is kept and Bun takes it beside the
system store. magpie's own file is still given when the user has none,
for an older MAGPIE_BUN without the variable.

Go side unchanged: magpie's own clients (the dist-branch tarball
included) use crypto/x509's platform verifier on Windows and macOS and
SSL_CERT_FILE/SSL_CERT_DIR plus the distribution bundle on Linux; no
RootCAs is overridden anywhere.

Run:
- TestBunTrustsTheSystemsStore (new): a local TLS server signed by a test
  root, sending leaf+root, serving a one-package npm registry; real Bun
  1.4.2 fetch and bun add through bunCommand. Root in neither store:
  both refused. Root in the system store (Linux: SSL_CERT_DIR, the
  machine's store untouched): both get through. Root in the user's
  NODE_EXTRA_CA_CERTS: both get through.
  Linux (wsl-run, magpie-desktop): pass. Old systemca.go: the system-store
  case is red (fetch and bun add both fail), as is TestBunReadsTheSystemsStore.
  Windows (win-run, xiaomi-gpu) and macOS (mote): pass; the system-store
  case is skipped there, since it needs a change to the real trust store.
- TestBunReadsTheSystemsStore (new), TestBunIsGivenTheSystemsRoots: Linux,
  Windows, macOS pass.
- go test -tags nogui ./internal/plugin on mote: ok (116s). Windows
  TestHost* on xiaomi-gpu: ok.
- go build ./..., GOOS=windows and GOOS=linux go vet ./internal/plugin on
  mote; gofmt -l clean.
- On xiaomi-gpu, bun 1.4.2 with NODE_USE_SYSTEM_CA=1:
  tls.getCACertificates("default") 183 (121 bundled + 62 system); without
  it 121. magpie's own ROOT file there loads whole (35 certs).

Not run: full suite.
Not tried: a root actually installed in the Windows or macOS store (the
real trust stores were left alone), and the reporter's antivirus/proxy.
2026-10-28 13:50:41 +08:00
yetone 69626580bc checkin: each account is checked in through its own proxy, not the global one (#2777)
zRain on Discord (Windows, 0.1.1788, Loomy plugin 0.1.4): the global proxy
is a residential entry, the Loomy provider is set to direct. The balance
read went direct, but every check-in, the loop's and a press, went out
through the global proxy and got ECONNRESET. The usage read wraps its ctx
in ViaLogin (loginQuota); no check-in did, so netproxy.Choice was empty
and the plugin host fell back to the global proxy.

The wrap is made once, where checkiner runs an account's do
(checkin.go): ViaLogin(ctx, a.provider, a.User). That covers every
check-in at once: a plugin's own (plugin.AccountCheckin) and magpie's
Trae CN, MiniMax, Qoder and WorkBuddy check-ins, which reach the vendor
through plugin.Fetch(req.Context()). a.provider is the card id the
proxies are kept under (PluginID, as loginProvider gives the usage read),
and a.User the account's label as the accounts list shows it.

Sibling found on the way: Provider.Origin asked the plugin's loader
(LoaderOptions, which can renew the sign-in) with the bare ctx, before
WorkBuddy's search and draw paths put p.Via on it. It now asks through
p.Via(ctx). The other plugin-host entries were read and already carry
the proxy: sign-in (signInFlow.via, Via in PluginAPIKey and the CLI),
the move's Check (ViaLogin), usage (loginQuota), model lists
(listingProxies) and the gateway's fetch (p.Via in the gateway).

The direction is the one #2777 lays out; skygunner's fork wired the same
wrap per runner.

Test: TestPluginCheckinGoesThroughItsProxy. The fake plugin's check-in
asks $FAKE_CHECKIN_URL (http://vendor.invalid/checkin/<key>); the global
proxy (settings.Proxy, set before the host starts) and the account's own
are recording proxies that answer for it. The provider is direct, one
account has its own proxy. The loop and then a press must leave the
global proxy unasked, claim through the account's proxy, and fail the
direct account (vendor.invalid is reachable by no one).

Broken by hand: a.do(ctx) back in checkin.go turns it red as reported:
the global proxy was asked for both accounts, the direct one claimed
through it, and the account's own proxy saw nothing.

Run (on mote, at this tree): go test -tags nogui -count=1 -run
'TestPluginCheckin|TestMovedLoginProxy|TestPluginSignInGoesThroughItsProxy'
./internal/provider ok; full suite
go test -tags nogui -timeout 45m ./...: every package ok (76), at base a05b37353

Not tried: a real Loomy check-in on Windows; the Origin change has no
test of its own (the fake plugin's loader makes no request).
2026-10-28 10:09:51 +08:00
yetone a05b373538 checkin: a plugin's until is when its answer stops holding (Qoder's 10:00 UTC+8)
sdytman on Discord: Qoder's daily credits start at 10:00, can the plugin's
check-in follow it? Qoder's /me/campaigns opens each day's CLAIM_BENEFIT
campaign at 10:00 and closes it at 09:59 the next day, UTC+8 (startAt and
endAt, read with a real account on 10-28; Qoder.app polls the list every 5
minutes). A check-in before 10:00 meets the day before's campaign. Since
#2696 the Qoder plugins are asked again every 30 minutes, so today's was
claimed somewhere between 10:00 and 10:30; a plain plugin was settled for
the Beijing day.

auth.checkin may now answer until (RFC 3339 or epoch ms); host.js passes
it as RFC 3339 (plugin.Checkin.Until), kept as ValidUntil. settled holds
an answer only until then, whatever its outcome; the loop wakes at it
instead of its next 30-minute look; an early done that carries it is not
provisional (#3326), as the vendor said when its day turns. Instants
throughout, so the machine's zone doesn't matter. The Qoder plugins send
until from 0.2.43 (plugins fd40b20): the check-in now lands at 10:01.

Run (mote): TestPluginCheckinAsksAgainAtUntil, minute by minute from
09:27 Beijing to the next day's 10:30, with time.Local UTC, UTC-8 and
Beijing: asks at 09:27, 10:01, 00:00 (the Beijing day), 10:01; a failure
in the 09:59 gap asked at 10:01:00 only. GOOS=linux and windows go vet;
go test -tags nogui -timeout 45m ./... all ok (76 packages). gofmt -l
clean.
Broken by hand, each red: settled ignoring ValidUntil (no 10:01 asks);
tick not waking at it (10:27 instead); provisional ignoring it (asked
every 30 minutes from 00:00 to 10:00); host.js dropping until (ValidUntil
zero).
Not tried: the Qoder plugin's recheck path with until (the fake plugin
is fakeco; the tick and settled it goes through are the same); a GUI
change (none: until isn't shown).
2026-10-28 09:51:43 +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 f6ed2c99bc effort: a vendor's light and extra_high are low and xhigh, in dsh, Pi and the gateway
nianshou5 (Discord) runs Trae's DeepSeek V4.1 Flash through the Our Free
Model plugin (github:mu-zi-lee/magpie-our-free-model). Its variants are
Trae's own names, light, high and extra_high, and dsh offered only
default and high: dshModelLevels (and Pi's piThinkingLevels) matched a
model's efforts to pi-ai's level names only, so light and extra_high
were dropped. The gateway dropped them too: effortOf read "light" as no
effort, and NearestEffort fitted an agent's low or xhigh to the plugin's
high.

catalog.EffortAliases names light as low and extra_high as xhigh
(EffortLevel). NearestEffort places a model's levels by the level they
name and returns the model's own word; the gateway's effortOf reads an
alias as its level. dsh's reasoningEfforts and Pi's thinkingLevelMap map
dsh's low/xhigh to the model's own word (modelEffort), which llm-pi-ai
sends on the wire as written (resolveModelReasoning in dsh-llm-pi-ai
reads each value as "the spelling dispatch sends"). Levels a user kept
are untouched: only the names a model lists are mapped.

Tests: TestDshOffersTraeNamedLevels (agent), TestNearestEffortTakesVendorWords
(catalog), TestPluginThinkingOff's new fake-trae subtests (gateway, a
real plugin host with the fake plugin listing light/high/extra_high).
Broken by hand: modelEffort without the alias, dsh levels [high] (the
report's picker); NearestEffort without EffortLevel, low/xhigh sent as
high; effortOf without the alias, light/extra_high sent as nothing.

Run on mote at this tree (base e4ccf67b1): go build, GOOS=linux and
GOOS=windows go vet -tags nogui ./... ok; go test -tags nogui -timeout 45m
./... : 73 packages ok, three red that are red the same on origin/main
7f32f0ec9 run alone: internal/agent TestWSLColdPlaceOpensNothing (#3924),
internal/tui TestTUIFetchesSubscriptionModels (#3919), internal/provider
synctest crash in TestUnreadLoginsWriteErrorsKeepCredentials (#3632), so
the rest of internal/provider didn't run. No GUI file changed.
Rebased on 7f32f0ec9 (one agent file changed there): go build ./...,
internal/catalog whole and gateway/agent -run Effort|Dsh|Pi|ThinkingOff|Level
ok at this head.

Not tried: a real dsh session against the user's plugin (no Our Free
Model account here); dsh's parsing of a non-pi-ai wire value was read
from its source, not run.
2026-10-28 04:34:45 +08:00
yetone e4ccf67b11 plugin: GitHub's search gets 60s a page, and a mirror is asked without the token (#3923)
MYCF711 (#3923) measured a page of GitHub's search from mainland China:
29-36s straight to api.github.com, 3-7s through gh-proxy. The Plugins
page's GitHub list was empty there, for two reasons:

- askTagged's taggedWait (8s) bounded the search pages as well as the
  wait for the repositories' reads. The first page timed out, the ask
  failed whole, and nothing was cached. Each search page now has its own
  taggedSearch (60s). taggedWait starts after the search and bounds only
  the reads, as before. Through a mirror, candidateContext gives the
  official address half of the 60s and the mirror the rest.
- source.Do never used a mirror for a request carrying Authorization,
  and ghtoken sets it on every api.github.com request when a GitHub
  token is set. With a token in Settings, MAGPIE_MIRRORS did nothing.
  A request to a GitHub host whose only credential is Authorization
  (bare) now goes to the official address with the token and to the
  mirror without it. A cookie, a key header, a token in the query, URL
  userinfo, or any other host still keeps the request official. The
  caller's request keeps its header.
- ghtoken.Do now reads who answered from resp.Request: a mirror's answer
  to the bare request doesn't count as carrying the token, and a 401 from
  a mirror doesn't mark the token refused.

Tests:
- TestTaggedReposSlowSearch: a search answering after 3x taggedWait
  still lists; one that never answers fails at taggedSearch.
- TestDoKeepsCredentialsOfficial, rewritten to the new contract: the
  official address gets the token, the mirror gets none, and the
  caller's request is unchanged. Cookie, query token and npm still stay
  official.
- TestMirrorAnswerIsNotTheToken (ghtoken).

Run on mote:
- go test -tags nogui -count=1 ./internal/source ./internal/ghtoken
  ./internal/plugin ./internal/library: all ok.
- Broken by hand: with the old source.go, ghtoken.go and github.go, all
  three tests went red ("requests = [https://api.github.com/repos/o/r]";
  "token=true"; "context deadline exceeded" at taggedWait).
- Locally: gofmt -l clean; go vet for linux and windows on the three
  packages; go build -tags nogui ./...

Not tried:
- The real network from mainland China.
- A live gh-proxy answer to an anonymous api.github.com search.
- Not changed: the mirror for api.github.com still waits for
  MAGPIE_MIRRORS. Without it, the 60s alone covers the ~30s page.
- No GUI file was run: the page's fixtures fake /api/plugins/github, and
  nothing in the window changed.

Reported by MYCF711.
2026-10-28 03:57:51 +08:00
yetone dc1af8231b ghtoken: a Settings token GitHub refuses is said, and requests go without one (#3926)
A GitHub token in Settings → Network and sharing that GitHub refused
(401, expired or revoked) failed every plugin and skill check, so a
stale token was worse than none. Now it is treated as an environment
token already was: the request is asked again without it, the token
isn't sent again while magpie runs or until the field changes, and the
anonymous answer (60 an hour) is the one taken. This overturns the
package comment and TestSettingsTokenRefusedStaysAnError: the token
being the user's choice is a reason to tell them, not to fail the
check.

The page stays honest about it:
- Settings › Network and sharing still shows the token, masked, with
  Remove, and says in red that GitHub refused it and requests go
  without one until it is replaced (/api/settings githubTokenRefused).
  Before, a refused token simply read as none being set.
- After a Settings token's refusal requests go anonymous, not with
  GITHUB_TOKEN/GH_TOKEN: the user put the Settings one ahead of those,
  and the page says "without one".

Patch by MYCF711 (fix/settings-token-fallback, 7d93f1b5): the ghtoken
change and its tests. Changed from it: the notice is in Settings' row,
where the token lives, instead of the patch's Plugins page note,
which cost ~630 bytes of core script the budget (28 bytes of room at
c54478904) doesn't have; the Library's skill checks reach Settings'
row too. Token() doesn't fall through to the environment; the
library's skill check test (the sibling the patch left red) expects
the anonymous answer; the unreachable new Refused() message is
dropped (Refused's "where" now holds for a refused Settings token).
app.js stays in its budget by shortening renderGitHubToken's comment.

Run at this tree (base c54478904), on mote:
- go test -tags nogui ./internal/ghtoken ./internal/plugin
  ./internal/library ./internal/gui: ok (TestCoreScriptBudget
  included; no budget raised). GOOS=linux and windows go vet, go build
  ./...: clean.
- github-token-refused.test.cjs (new; chromium and webkit, en and zh,
  1000 and 440px): red 8 of 8 against origin/main's assets, green
  with the change. With github-token and i18n-keys: 21 of 22; the red
  is i18n-keys "a plugin's words are its own" ("Runs as"), red at
  origin/main 74dcf40aa alone too (#3897).
- Every GUI file that opens Settings › Network and sharing
  (allow-ips, api-key-theme, bare-ids, browser-access, cors-origins,
  gateway-port, lan-docker, proxy-test, settings-proxy-auth,
  settings-proxy-remember): 126 of 126.
- Broken by hand: Token() falling through to GITHUB_TOKEN after the
  Settings token's refusal turns TestSettingsTokenRefusedGoesWithoutEnvToken
  red; MYCF711 showed TestSettingsTokenRefusedAskedAgainWithout red with
  from == "settings" back in Do.

Not tried: a real revoked token against api.github.com. The Plugins and
Library pages have no notice of their own (Settings' row says it).
2026-10-28 03:50:46 +08:00
yetone f8cd964aec plugin: a fetch past the host's 128 streams waits for one, not a local 502 (#3890)
The plugin host holds streamBudget/streamWindow = 128 streaming calls'
windows. begin(true) failed the 129th at once with errTooManyCalls, before
anything reached the plugin child, and the gateway counted it as a 502
try and sent the request again. The reporter's 192 concurrent MiniMax
streams through one plugin all came back 200, but over 298 local 502
tries that never reached MiniMax (65 requests retried).

Fetch now takes its window through beginStream: when all 128 are held
it waits for one to come free, outside h.mu (the transition that frees
one takes it), while its request's context lives, the host is up, and
for streamWait (1 minute) at most, past which it is errTooManyCalls as
before. RPCs keep their reserve and still never wait; begin(false) and
begin(true) are unchanged for their other callers.

Tests:
- TestHostFetchWaitsForAStreamWindow (internal/plugin): one window;
  a second fetch waits, runs once the first is released, gives up on
  a cancelled context and after streamWait, and leaves no window taken.
- TestPluginStreamsPastTheBudgetWait (internal/gateway, new file): 192
  concurrent streams through the real Bun plugin host to a local vendor
  that holds each open until 128 are live. Every request is 200 on one
  try, the vendor sees 192 requests and never more than 128 at once.

Run at this head (on ff7048dec):
- gofmt -l internal/plugin internal/gateway: clean
- go vet -tags nogui ./internal/plugin/ ./internal/gateway/ for GOOS
  linux, windows, darwin: ok
- go test -timeout 45m ./internal/plugin/: ok (99.0s, before the rebase
  over two usage/provider commits that don't touch plugin or gateway)
- go test -timeout 45m -run Plugin ./internal/gateway/: ok (52.0s, same)
- After the rebase: TestHostFetchWaitsForAStreamWindow,
  TestHostAdmission*, TestPluginStreamsPastTheBudgetWait: ok
- Broken by hand (beginStream returning errTooManyCalls at once, as
  begin did): TestHostFetchWaitsForAStreamWindow fails ("want it
  waiting"); TestPluginStreamsPastTheBudgetWait fails with 960 lines
  of "a try 502 too many plugin calls are in flight".
- Real account: a sandbox HOME with only the ZCode plugin and its
  account, this head's build on 127.0.0.1:3581, 8 concurrent streaming
  zcode/GLM-5.3-Flash requests: 8 of 8 200, each with its [DONE].

Not tried: 192 real concurrent streams against a vendor (the reporter's
MiniMax setup); the full gateway package (only its Plugin tests).
2026-10-28 00:58:50 +08:00
yetone 2b0387574e draw: an OpenAI-compatible plugin's image models draw (SenseNova's sensenova-u1.5-lite)
01huadalang (Discord, #feedback): SenseNova's sensenova-u1.5-lite can
draw, but magpie's image generation picker doesn't list it.
ab546a4ee (v0.1.1707) covered SenseNova added as a key provider. The
SenseNova plugin (aqiu817/magpie-sensenova, @ai-sdk/openai-compatible at
token.sensenova.cn/v1) lists the model from SenseNova's /models too, but
Drawers returned nothing for any plugin provider (p.Account != nil), so
neither the picker nor generate_image could reach it there.

- provider.PluginOpenAICompatible: the plugin speaks the model on
  @ai-sdk/openai-compatible.
- Drawers: a plugin provider's listed model that DrawsID and ImagesAPI
  and is spoken on openai-compatible is a drawer; drawImages sends it to
  /images/generations or /images/edits under the plugin's base, through
  its fetch (pluginFetch maps /v1/... onto the loader's base), in the
  shape ab546a4ee sends SenseNova (b64_json, JSON edits). An image model
  on another package (a vendor's own API) is not listed. Grok's and
  WorkBuddy's drawers are unchanged (checked before this branch).
- Fake plugin: $FAKE_SENSENOVA adds sensenova-u1.5-lite and a flux-2 on
  @ai-sdk/anthropic.
- docs/subsystems/provider-plugins.md says it.

Test: TestSenseNovaPluginDraws (internal/gateway) installs the fake
plugin as "sensenova" in a real Bun host in front of the fake SenseNova
of TestSenseNovaU1Draws: Drawers lists sensenova-u1.5-lite alone, a
generation and an edit come back through the plugin (b64, JSON images,
chat never asked). Broken by hand: without the plugin branch it is red
(drawers []); without the openai-compatible check it is red (drawers
[sensenova-u1.5-lite flux-2]).

Run at this head: gofmt -l, go vet, GOOS=windows go vet, GOOS=linux go
vet -tags nogui on internal/gateway and internal/provider (clean); go
test -tags nogui -timeout 45m ./internal/gateway ./internal/provider
./internal/plugin ./internal/catalog: gateway (716s), plugin, catalog
ok; provider crashes in TestUnreadLoginsWriteErrorsKeepCredentials
(#3632, open), and with it skipped fails TestFetchAsksASharedBaseOnce,
TestFetchAsksOneListOnceForTwoBasesOfIt and
TestFetchUnionsProtocolListsWithoutChat, red the same at the base
a47596ea6 without this change (#3854, open). Neither touched here.
After the rebase onto origin/main b103ed058: gofmt, vet (three OSes),
internal/gateway -run 'SenseNova|Draw|Image|Edit|GrokPlugin|Plugin',
internal/catalog, internal/provider -run Plugin: ok.

Not tried: a real SenseNova account or the real plugin (none here); the
images API shape is from SenseTime's launch post as ab546a4ee read it.
Not run: the full ./... suite and the GUI suite (no GUI file changed).

Reported by 01huadalang (Discord).
2026-10-27 23:45:57 +08:00
yetone f4a575954b plugin: the update check asks npm now, not what it said within the hour
ysm119 on Discord tested Cursor's claude-haiku-5-5-thinking a quarter of
an hour after plugin 0.2.25 was published and magpie updated. CheckUpdates
(30s after start, then hourly) read npm's versions through Info, which
asks npm at most hourly and otherwise answers from its disk cache, so a
magpie started after a community fix was published could find the
version before it and update nothing for up to another hour (two in all
for the hourly look). latestOf now asks npm of every installed package
(infoWithin, age 0); the plugins page keeps Info's hourly cache, and a
package npm doesn't answer for is still what it said last.

Run: go test ./internal/plugin -count=1 -timeout 45m (ok, 305s).
Broken by hand: latestOf back on Info, TestUpdateCheckAsksNPMNow is red
(the check saw 1.2.3 while npm had 1.2.4).
Not tried: a real magpie restart against npm's registry.
2026-10-27 18:43:32 +08:00
yetone 9bfe680481 plugin: a changed plugin option lists the providers again (plugins#430)
WorkBuddy's plugin 0.1.38 adds a "Free models only" switch (a plugin option)
that lists only WorkBuddy's free models and refuses any other before it is
sent. Its list goes by the switch, but SetProviderOptions only handed the
values over: the host cleared its infos while Go kept provCache, so the
Providers page and /v1/models showed the old list until something else
re-read it. SetProviderOptions now forgets the kept providers (whether the
host runs or not), so the next Cached() lists them again. Nothing else runs
on a change. The workbuddy mover's min is 0.1.38 (npm view --prefer-online
at landing: 0.1.38).

Run:
- go test ./internal/plugin ./internal/provider -count=1 -timeout 45m at
  this head (5a3292354 + this): internal/plugin ok (389s); internal/provider
  FAIL on TestUnreadLoginsWriteErrorsKeepCredentials, "close of synctest
  channel from outside bubble" in filememo.Forget, which is #3632 (open, on
  main since 091153bf, nothing here touches it). TestPluginOptions now lists
  a model only while its option is on, and only base-model after it is off.
- Rebased onto 3aead9c62 after the run; its new commits touch only
  internal/provider/codex_daemon*.go and codex_app_server_test.go. go vet
  ./internal/plugin ./internal/provider ok there; a rebuild to test again
  failed to link for a full disk (291MB free).
- gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/plugin
  ./internal/provider ok.
- Real accounts, sandbox HOME, dev build of this tree on 3516/3517 with the
  plugin added by path: POST /api/settings/plugin-option free_only on for
  workbuddy-ai took its list from 26 to 2 (hy3, deepseek-v4.1-flash) within
  2s with no restart; workbuddy kept 19. gpt-5.4 got the plugin's 404 and
  was not sent; hy3 and deepseek-v4.1-flash answered. Off: 26 again, and
  gpt-6-luna and gpt-5.4 answered.
Broken by hand: without forgetProviders in SetProviderOptions,
TestPluginOptions fails ("with beta on, optco lists "base-model"").
Not tried: the switch clicked in the GUI window (the API it calls was);
Windows and Linux apps.
2026-10-27 17:44:02 +08:00
JoeyWu-tech 6cb1cfb794 plugin: a lock behind package.json's dist tarball is mended, its tarballs kept (#3622)
Part 1 of 2, pruneDist (coffemon's first commit):

pruneDist took out every tarball in plugins/dist that
plugins/package.json doesn't name, as encoding/json reads it. Bun
installs a package from the tarball bun.lock's packages has it at, and
that can be one package.json has moved on from: gkd2323c's lock (#3622,
Windows, Bun 1.4.4) had autoclaw, codearts and cloudflare-workers-ai at
the tarballs before the ones package.json names, and those were gone
from plugins/dist, where nothing but pruneDist takes a file out. With
Bun's own copy of such a tarball, every bun command that changes
plugins/ puts the older version back; with none, every add and removal,
of any plugin, fails with "ENOENT extracting tarball from <that
package>" (part 2 has the likely why there was none).

Now a tarball the lock's packages has a package at stays, beside the
ones package.json names. Kept, it is what Bun installs: a package whose
lock is behind package.json stays at the older version without a word,
where 4e5b2ad8, once Bun had no copy, failed every command with ENOENT.
part 2 sends such a lock back to package.json before each bun
command when package.json has the package at a dist tarball too; with
package.json at npm it stays behind (#3720). package.json is read as
text, every dist/<file> in it counting, where encoding/json keeps one
value of a key named twice: Bun 1.4.0 adds a tarball's package a second
time instead of replacing it, the new tarball first, which Bun reads,
and encoding/json reads the second, so 4e5b2ad8 took out the tarball Bun
installs from. No magpie runs plugins on that Bun unless MAGPIE_BUN
names it (BunVersion has been 1.4.2 since 10-03, before plugins/dist
was), so that is how a decoded package.json loses it, not a path a user
is known to have taken. A tarball only the lock's workspaces names goes:
Bun 1.4.2 and 1.4.3 leave the one an add replaced there until their next
command, and nothing installs from it. With no bun.lock, package.json
alone decides, as before; with one that can't be read, nothing goes, as
with a package.json that can't be read.

This keeps the tarballs a lock has from going, and mends no lock: one
behind package.json's dist tarball, the reporter's or one that falls
behind later, is sent back by part 2, its tarball there or
gone.

What was run (tree 8f285445, on origin/main 4e5b2ad8, go1.26.8,
linux/amd64):
- TestDistTarballTheLockNamesStays (new): the reporter's package.json
  and lock, built around the lines #3622 quotes; the package.json real
  Bun 1.4.2 writes for `bun add ./dist/<0.2.6>` over 0.2.1, and the one
  Bun 1.4.0 writes (the package named twice), each with the lock both
  write, and the Bun 1.4.0 one with no lock; no lock; a lock that can't
  be read (a folder in its place). The tarballs the lock's packages or
  package.json name stay, the one only the lock's workspaces name goes,
  and one nothing names goes; with no lock package.json alone decides,
  and with an unreadable one nothing goes. With the change the TestDist
  tests are ok on each Bun. Broken by hand, each put back after, with
  Bun 1.4.2, 1.4.3 and 1.4.4 (outside graftcp, the proxy wrapper this
  box runs commands in, umask 077, logs kept):
  - 4e5b2ad8's pruneDist: the reporter's, both named-twice and the
    unreadable-lock cases red on each ("<tarball> taken out");
  - package.json decoded as 4e5b2ad8 did, the lock still read: the
    named-twice case with no lock red on each ("<0.2.6> taken out");
  - the whole lock read for tarballs instead of its packages: the
    workspaces case red on each ("0.2.1 kept"), and
    TestDistInstallsAPackageNPMDoesntHave red on 1.4.2 and 1.4.3
    (0.1.4's tarball stays after 0.1.3 is pinned: those two leave it in
    the workspaces).
- internal/plugin, -tags nogui, with Bun 1.4.4, the one magpie runs now:
  ok but TestPluginSOCKSProxy, red the same at origin/main 7a60e78c
  (#2207, open, filed for 1.4.3); TestFlowBigReplyProd and
  TestRenewOtherHost skip by their own condition.
- gofmt -l lists nothing; GOOS=linux, windows and darwin go vet -tags
  nogui ./..., GOOS=windows go vet ./..., GOOS=linux and darwin go build
  -tags nogui ./... and GOOS=windows go build ./...: exit 0 each. go vet
  and go build without the tag on linux: exit 1 (no GTK, WebKitGTK or
  fontconfig headers on this box).
- Full suite, -tags nogui (CI's Linux job tags gtk3), outside graftcp
  (systemd-run, umask 077, Bun 1.4.2 first on PATH as on CI, -timeout
  45m, log kept): 64 ok, internal/plugin among them, and 8 red, none in
  what this changes:
  - agent TestCodexDriftReached and TestCodexBehindReverseProxy: #3398;
    TestCursorFolderFromTheEditorIsNotTheCLI,
    TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
    TestOmpDetectedWithPiDir: #3141;
    TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: this box's /tmp/.git,
    #3641.
  - davsync TestSyncTeraCloudStillSeesOtherWrites: #3420.
  - edit TestWriteAtomicReadOnlyHardLink: this box's umask 077, #3640.
  - gateway TestPluginToldWhereTheAgentWorks: this box's /tmp/.git,
    #3675.
  - gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie:
    this box's millions of open fds, #3649.
  - provider: "fatal error: close of synctest channel from outside
    bubble" in TestUnreadLoginsWriteErrorsKeepCredentials, main's CI
    red, #3632; the package's tests after it didn't run.
  - sessions TestAgyTitleLater: a same-size write in the same mtime
    tick, 2 of 200 on main alone, #3708.
  - testenv TestProgram: this box's umask 077, #3640.

Not tried: Windows, where the reporter is (CI's Windows job runs none of
these tests: it compiles them and runs a named few). package.json and
the lock are read for the forward-slash form magpie hands Bun
("./dist/<file>"), which the reporter's Bun 1.4.4 on Windows kept in
both. A tarball they name only with backslashes goes, where 4e5b2ad8 on
Windows kept one package.json named so (it read package.json through
filepath.ToSlash).

Part 2 of 2, mendDist (coffemon's second commit):

The commit before keeps the tarballs bun.lock has packages at, but a
lock behind package.json stays behind: gkd2323c's (#3622, Windows, Bun
1.4.4) had autoclaw, codearts and cloudflare-workers-ai at tarballs
pruneDist had taken, while package.json and the lock's workspaces had
moved on. Bun installs what the lock has, at every command that changes
plugins/. From that tarball, kept now, or from its own copy of it, it
put the older version back without a word; with neither, every install,
update and removal, of any plugin, failed with "ENOENT extracting
tarball from <that package>". Bun keeps its copy of a local tarball in
its install cache as @T@<16hex>@@@1 on 1.4.2 and 1.4.3, and as
@T@sha512-<32hex>@@@1, the start of the tarball's sha512, on 1.4.4, so a
Bun moved to 1.4.4 has no copy of one an older Bun made (magpie takes a
Bun release two days after it is out, bunSettle: 1.4.4, out on 10-22,
from 10-24). pruneInstallCache leaves these copies alone (no package
name before their first @). On Linux, such a lock and copies made by
1.4.2 or by 1.4.3 give an add on 1.4.4 the reporter's error, for both
packages locked at gone tarballs; the same Bun's add succeeds and puts
both back at their older versions.

Now mendDist runs before each bun command that changes plugins/ (in
runBun and install, under installMu): the packages the lock has at a
dist tarball package.json doesn't name, while package.json has them at
one plugins/dist holds, get one `bun update --ignore-scripts` of them
all, which resolves them from package.json again. It comes after
a9242eb6's mendPackageJSON, which cuts what follows package.json's
object (plugins#405): mendDist decodes package.json, and with that tail
there it would return without a mend, leaving the lock behind for the
command. A package.json that names the lock's tarball too, as Bun
1.4.0's names a package twice, isn't behind. Nothing is asked of the
registry: no package on dist has a dependency (its index.json, 42
packages, on 10-26). `bun add` of them doesn't do it on Bun 1.4.2 and
1.4.3, which keep what the lock has, and with no copy of them, an update
of one package alone fails on the others still locked at gone tarballs.
Each mend is logged with the packages it sent back, so a lock that falls
behind again, which nothing here explains, leaves a line saying when.
What it can't mend is left to the command it comes before, as before:
package.json's tarball gone too, or a package.json or bun.lock it can't
read. A lock behind package.json across npm and plugins/dist it leaves
alone, and Bun installs the lock's version (#3720). A lock with nothing
stale costs reading the two files, decoding package.json and a scan of
the lock; a tarball is looked at only where the lock and package.json
name different ones.

A lock already behind, the reporter's among them, is sent back at the
next bun command magpie runs that changes plugins/, as package.json's
tarball is in plugins/dist: pruneDist never takes one package.json
names.

What was run (tree 5ae0b4a1, on origin/main 4e5b2ad8, go1.26.8,
linux/amd64):
- TestDistLockBehindPackageJSONIsMended (new), with real Bun: autoclaw
  and codearts installed from plugins/dist at 0.2.1 and 0.2.0, then at
  0.2.6 and 0.2.1 (the reporter's), and the lock's packages given back
  the entries Bun wrote for the first ones; with Bun's copies kept, with
  them gone, with the older tarballs put back in plugins/dist, as the
  commit before keeps them, and with the copies gone and plugins#405's
  tail after package.json's object. From each state an unrelated
  plugin's add (zcode) and then its removal succeed and leave both
  packages at package.json's versions, in node_modules and alone in the
  lock, and package.json's specs for both as they were; the add's prune
  takes the older tarballs. With the change the TestDist tests are ok on
  each Bun, and the two new ones at -count=10 on 1.4.2 and 1.4.4. Broken
  by hand, each put back after, with Bun 1.4.2, 1.4.3 and 1.4.4 (outside
  graftcp, the proxy wrapper this box runs commands in, umask 077, logs
  kept):
  - no mendDist: every case red on each, the older versions back with
    the copies or the older tarballs kept (`is at "0.2.1", want 0.2.6`),
    the add failing with "ENOENT extracting tarball from" both packages
    with the copies gone;
  - mendDist before install's add only: every case red at the removal on
    each, the older versions back, or with the copies gone package.json
    still naming zcode after Remove;
  - one `bun update` a package: both copies-gone cases red on each, the
    add failing with "ENOENT extracting tarball from" both packages, as
    with no mendDist (each update alone fails on the other's gone
    tarball);
  - `bun add` of package.json's tarballs instead of `bun update`: every
    case red on 1.4.2 and 1.4.3, ok on 1.4.4;
  - the trigger as first written (the lock's tarball gone): the
    tarballs-kept case red on each, the older versions back (`is at
    "0.2.1", want 0.2.6`);
  - mendDist before package.json's tail is cut: in install, the tail
    case red on each at the add, "ENOENT extracting tarball from" both
    packages; in runBun, red on each at the removal, package.json still
    naming zcode after Remove.
- internal/plugin, -tags nogui, with Bun 1.4.4, the one magpie runs now:
  ok but TestPluginSOCKSProxy, red the same at origin/main 7a60e78c
  (#2207, open, filed for 1.4.3); TestFlowBigReplyProd and
  TestRenewOtherHost skip by their own condition.
- gofmt -l lists nothing; GOOS=linux, windows and darwin go vet -tags
  nogui ./..., GOOS=windows go vet ./..., GOOS=linux and darwin go build
  -tags nogui ./... and GOOS=windows go build ./...: exit 0 each. go vet
  and go build without the tag on linux: exit 1 (no GTK, WebKitGTK or
  fontconfig headers on this box).
- Full suite, -tags nogui (CI's Linux job tags gtk3), outside graftcp
  (systemd-run, umask 077, Bun 1.4.2 first on PATH as on CI, -timeout
  45m, log kept): 65 ok, internal/plugin among them, and 7 red, none in
  what this changes:
  - agent TestCodexDriftReached: #3398; TestInstalledVersion,
    TestHowInstalled, TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
    TestOmpDetectedWithPiDir: #3141;
    TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: this box's /tmp/.git,
    #3641.
  - davsync TestSync and TestSyncTeraCloudStillSeesOtherWrites: #3420.
  - edit TestWriteAtomicReadOnlyHardLink: this box's umask 077, #3640.
  - gateway TestPluginToldWhereTheAgentWorks: this box's /tmp/.git,
    #3675.
  - gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie:
    this box's millions of open fds, #3649.
  - provider: "fatal error: close of synctest channel from outside
    bubble" in TestUnreadLoginsWriteErrorsKeepCredentials, main's CI
    red, #3632; the package's tests after it didn't run.
  - testenv TestProgram: this box's umask 077, #3640.

Not tried: Windows, where the reporter is (CI's Windows job runs none of
these tests: it compiles them and runs a named few); the reporter's own
plugins/ folder; the step that left their lock's packages at the
tarballs before while package.json and the workspaces moved on. On Linux
each Bun from 1.4.2 to 1.4.4 writes the packages at the tarball an add
names, so the test makes that state by hand.

Review (macOS arm64, go1.26.8, squashed into one commit per issue, on
origin/main 1cbdda25b), plus the class plugins#405 belongs to, a file
here written over a longer one without truncating:
- bun.lock: real Bun 1.4.4 reads the lock's first object and goes on
  past bytes after it (a lock with an older lock's packages appended:
  `bun install` checked 1 install, no changes, tail left as it was). So
  a tail doesn't stop Bun, but pruneDist's and mendDist's regexp read
  the whole file: the tail's older tarball was kept, and sent to bun
  update before every command. Both now read lockHead, the first
  object, braces and quotes inside strings skipped.
  TestDistLockTailIsntRead (bun update run for a lock whose object is
  behind, not for one whose tail is, nor one with "}\"{]" in a string)
  and a TestDistTarballTheLockNamesStays case (the tail's tarball
  goes). Broken by hand: lockHead returning the whole file turned the
  tail case and both tail subtests red ("0.2.1 kept", "bun update run:
  true"); escapes not skipped turned the braces-in-strings subtest red.
- package.json: every magpie write of it is temp+rename (mendPackageJSON
  since a9242eb68) but the first one install makes, an os.WriteFile;
  that goes through edit.WriteAtomic now. bun's own writes are bun's.
- TestDist* ok on Bun 1.4.2, 1.4.3 and 1.4.4; broken by hand with
  1.4.4: mendDist's calls removed turned
  TestDistLockBehindPackageJSONIsMended red, and the old pruneDist
  turned TestDistTarballTheLockNamesStays red ("taken out").
- internal/plugin whole package ok (144s); gofmt clean; vet ok for
  linux nogui, windows, darwin nogui.
Not tried: Windows, where both reports come from.
2026-10-27 15:57:59 +08:00
yetoneandvincent 65ee8c65c6 gateway: a ZCode Start Plan trial that ended or is spent rests that trial alone, not the account (#3661)
orion-nebula-dev's routing log: GLM-5.3-Flash-Trial and GLM-5.3-Trial,
whose Start Plan trial had ended, were refused by the ZCode plugin with
400 "ZCode has no active limited quota for GLM-5.3-Trial". The word
"quota" made it failQuota, and restAfterMarked rested the account
("zcode@zcode"), so the subscription's GLM-5.3 and GLM-5.3-Flash were
paused with it.

zcodeTrialRefused narrows that rest to the trial entry (restID) when the
candidate is a zcode plugin account, the model ends in -Trial, and the
refusal is the plugin's own words naming that model:
- 400 "ZCode has no active limited quota for <model>" (the trial ended);
- 429 "ZCode's limited quota for <bucket> is exhausted or temporarily
  unavailable", where the bucket is the entry less -Trial (its bucket
  spent). skygunner's patch covered the 400 only and kept this 429 as an
  account rest; it is the trial bucket's, given by the plugin before
  anything is sent, so it rests the entry too.
Another model named, a model without -Trial, the ended words on a 429,
the account's own quota (400 or 429) or key (401), and the same words
from another vendor still rest the account.

The plugin is not changed: zcode 0.1.31 already leaves ended trials out
of its model list and its two refusals are exact, and open plugins PRs
#395 and #421 hold zcode's next version. A member the user kept in a
group is still asked, refused locally, and asked again a minute on (a
guessed quota rest); the Routing page strikes such a member as
"skipped", which the gateway doesn't do: filed as #3805.

Ported from skygunner's e04a1b994 (branch
fix/r25-expired-model-not-account-fault): the test plugin's
FAKE_ZCODE_TRIAL and FAKE_NO_FREE fixture is his; the matcher, the 429
case and the test were rewritten. Reported by orion-nebula-dev.

Run:
- TestZCodeTrialRefusalRestsTheTrialAlone: 12 cases, the reporter's
  literal plugin bodies. Each posts to a group of the trial then another
  provider, checks the try's rest key, then posts to a group of the
  account's GLM-5.3 then another provider: served by the account when
  only the trial rests, by the other provider when the account does.
- Broken by hand: the routing.go hook off -> the four trial cases red
  ("refusal rested \"zcode@api key\", want \"zcode@api key/GLM-5.3-Trial\"");
  the 429 branch off -> "trial spent" red; the zcode-only check off ->
  "another vendor's words" red. Green again after each.
- gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and
  GOOS=windows; GOOS=linux go build -tags nogui ./...
- go test -timeout 45m -count=1 ./internal/gateway ./internal/plugin at
  f34a9f8cf (this change on b7d5a97fe): both ok (436s, 87s).

Not tried: a real ZCode account with an ended Start Plan trial (none to
hand); the full ./... suite (other sessions' suites were running); the
Windows box.

Co-authored-by: vincent <vincent@users.noreply.github.com>
2026-10-27 09:10:09 +08:00
yetone f2aa7fe346 plugin: HasGateway looks at the plugins once a second, not on every request (#3725)
Every agent request asks plugin.HasGateway (gatewayHooks, and
GatewayBegin again when on). It read plugins.json through lastgood and
steady, cloned the list, and stat'ed and read every enabled plugin's
package.json. With 12 plugins installed and none with hooks:

  Windows (Ryzen AI MAX+ 395, Defender on): 457µs, 51KB, 360 allocs
  macOS (M4 Pro):                           251-286µs, 36KB, 260 allocs

per call. It now keeps its answer for a second, keyed on plugins.json's
path and filememo.Gen, as middleware.current does: magpie's own writes
(plugin add/remove/on/off all go through save, which calls
filememo.Forget) are seen at once, another program's within a second.
Now 0.5µs/640B on Windows and 0.3-0.85µs/208B on macOS.

Run at b9ab17231 plus this change:
- go test -count=1 -timeout 45m ./internal/plugin ./internal/middleware
  ./internal/gwmw ./internal/gateway: all ok (gateway 541s).
- TestHasGatewayLooksOnceASecond (new) is red with the cache turned off
  by hand ("the plugins were read again within the second"), green with
  it. It also checks filememo.Forget and an expired look see a change.
- The numbers come from a throwaway benchmark (12 plugin dirs with
  package.json, plugins.json with options) run on this Mac and as a
  windows/amd64 test binary on the Windows box, old and new code.
- GOOS=linux and GOOS=windows go vet -tags nogui on the three packages,
  gofmt.

Not tried: a hooks plugin edited by hand outside magpie in the real app
(the test covers the one-second look).

Rebased onto origin/main 3fd7e1698 (no plugin or filememo change between); go build ./... and go test -count=1 ./internal/plugin ok at the pushed head. Before that, at b5d17b26e: go build ./..., linux and windows go vet -tags nogui ./internal/plugin, and go test -count=1 ./internal/plugin ./internal/middleware ./internal/gwmw all ok.
2026-10-27 01:44:57 +08:00
yetoneandskygunner 51202cd431 plugin: a check-in outcome magpie doesn't know names what the plugin said
A plugin check-in that answered an outcome not in the list, with a
message, became failed with the plugin's message alone, so "the daily
credits were refreshed" read as magpie's own failure reason. The reason
now names the answer first: the plugin answered "yes": <message>. With
no message it stays "the plugin answered no outcome" or the answer.

Split out of skygunner's fix/usage-absent-used branch (#3650), which
carried it beside the usage fix.

Run: go test ./internal/provider -run TestPluginCheckinRunsAsTheBuiltinsDo
ok. Broken by hand: host.js's old line makes it red (Msg was the message
alone). Not tried: a real plugin answering an unknown outcome.

Co-authored-by: skygunner <skygunner@users.noreply.github.com>
2026-10-26 22:42:59 +08:00
yetoneandskygunner 9733ed1b4a usage: a plugin window that doesn't say used is no reading (#3650)
A plugin usage window that leaves out `used` was read as 0 in host.js
usageOf. The card then showed "100% left" (or NaN% once the GUI saw a
missing value), and allowanceOf ranked the account as the one with all
of its allowance left, so smart routing put spent accounts first.

Now a left-out used is null from the host, plugin.UsageWindow.Used is a
*float64, and quotaOfPlugin makes such a window Text and Aside: the card
shows its display (else "No allowance reported"), with no percentage and
no meter, and routing leaves it out. An account whose windows all tell no
share has no allowance and is not known to routing (routedAllowance), as
one never read: not preferred and not rested. A window that says used:0
is a reading at 0, as before.

Ported from skygunner's fix/usage-absent-used (6791aa99). Changed from
the branch:
- lastAllowances (the reading kept on disk) built an empty allowance for
  such an account, which routing read as known with all of it left. Both
  it and Allowances now go through routedAllowance.
- quotaText shows "No allowance reported" for a no-share window with no
  display, rather than a blank.
- A host-level test (the bun host with the fake plugin) and the GUI test
  widened to both engines, every language, 900 and 390px, used and left.
- The branch's check-in wording change is its own commit.
Note: an account whose windows are all aside or text was known with 0%
used before; it is now not known, so loginRoom won't pick it as the
next account with room.

Run at this tree (base 9298d2a7c):
- go test ./internal/provider -run 'Absent|NoShare|PluginUsage|PluginText|
  AllowancePooled|PluginPool|GLMPlan|WorkBuddyCredits|QuotasDedupe'  ok
- go test ./internal/plugin ok; gofmt -l empty; go vet ./...,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... ok
- GUI: usage-no-reading.test.cjs chromium+webkit ok; i18n-keys ok;
  TestCoreScriptBudget ok (budget not raised)
Broken by hand, each red, then restored:
- quotaOfPlugin without the Text/Aside branch: 3 absent tests red
- routedAllowance always ok and allowanceOf not skipping Text:
  TestRoutingKnowsNoAccountThatSaidNoShare red
- host.js's old used line: TestPluginHostPassesAnAbsentUsedOn red
- usage-no-reading on origin/main's assets: red in both engines
  ("12 / 300 · NaN% used")
Not tried: a real Loomy account, a live routed request.

Co-authored-by: skygunner <skygunner@users.noreply.github.com>
2026-10-26 22:42:59 +08:00
yetone afc99490f2 plugin: a fetch's body goes to the host in one line made for it (#3472)
Each plugin request was copied several times before it reached the
plugin:
- pluginFetch read the body with io.ReadAll, which grows from 512
  bytes, so a 1 MB body was some 3 MB read. It now reads into a buffer
  of the request's Content-Length.
- Fetch marshalled a map holding the FetchRequest and the body as
  []byte, so encoding/json base64'd the body into its own buffer and
  then copied it into the line, and enqueueOwned appended the newline
  in another copy. fetchLine now marshals the request without the body
  (FetchRequest.Body is json:"-") and appends the base64 body and
  window into one slice sized for the whole line; enqueueLine sends it
  as is.

The frame is byte for byte what it was: TestFetchBodyWireIsUnchanged
compares it with the old json.Marshal of the map, field order
included (request fields, body, window).

BenchmarkFetchBodyProd B/op, before -> after:
  1 MiB   1,516,234 -> 1,411,609
  8 MiB   14.4 MB   -> 11.2 MB
  16 MiB  29.7 MB   -> 22.4 MB
Through the gateway with the previous commit (probe, 60 requests of
~938 KB, per request including the test's client and fake vendor):
  /v1/chat/completions 21.2 MB -> 17.3 MB (24.4 MB before both, -29%)
  /v1/messages         33.7 MB -> 29.3 MB (39.8 MB before both, -26%)
Server.serve's own share on /v1/messages: 29.1 -> 19.0 MB (-35%).
What is left on top is buildChat's json.Marshal of the outgoing body,
which the upstream byte fixtures pin; not changed here.

Run at this head (base origin/main 1bb8143b3):
- go test ./internal/plugin ./internal/provider -skip
  '^TestUnreadLoginsWriteErrorsKeepCredentials$' (#3632) -count=1
  -timeout 45m: ok (plugin 109s, provider 105s)
- go test ./internal/gateway -skip '^TestZZ' -count=1 -timeout 45m: ok
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui for
  internal/plugin, internal/provider, internal/gateway: clean
- Real account in a sandbox HOME: the Command Code plugin
  (commandcode-plan/claude-haiku-5-5) answered /v1/messages and
  /v1/chat/completions with a ~54 KB history, a tool call and a UTF-8
  tool result: 200 both, the tool's text quoted back exactly.
Not tried: an OAuth plugin (their tokens rotate; not copied into a
sandbox), Windows.

Rebased onto origin/main 6e6aba51c (a providers key change) and run again at the pushed head: go build -tags nogui ./... ok; go test ./internal/provider (same skip) ok 115s, ./internal/plugin ok 110s, ./internal/gateway -run 'Facts|Parse|Plugin|WorkPlace|Fetch' ok 50s. The full gateway run above was at 1bb8143b3.
2026-10-26 21:04:48 +08:00
yetone fed0055da8 plugin: a plugin stuck on its vendor no longer holds up the plugins loaded or listed with it
shualaitianduai on Discord: a plugin whose sign-in kept failing (401)
held up the plugins behind it. host.js loaded the plugins one after
another and answered init only when all were in, so a plugin function
that never returned held every other plugin until init's two-minute
deadline failed the whole host. providers() listed the providers one
after another too, so one stuck models hook held the whole list past
refreshDeadline (30s), and every provider's list went stale.

Now loadPlugins loads every plugin side by side, each given
pluginLoadWait (20s) for its import and plugin function, and each
config hook as long; one still loading is told as not loaded ("the
plugin's load didn't finish in 20s") and init answers with the rest.
Hooks are kept in the list's order, as before. providers() lists every
provider side by side and gives each models hook pluginListWait (20s,
inside refreshDeadline): one that hasn't answered is listed as fallen
back with that as its listError, so magpie keeps the list it had, and
that answer isn't kept for requests (keepInfo). Documented in
docs/subsystems/provider-plugins.md.

Run at this head (base origin/main e5dd86965), sandbox HOME, caches
pinned:
- TestStuckPluginLoadHoldsNoOther and TestStuckModelListHoldsNoOther
  (testdata/stuck): red on origin/main's host.js ("Plugins = [],
  starting plugins: context deadline exceeded" after 30s; "Providers
  = [], context deadline exceeded" after 15s), green here (2.1s each).
- go test -count=1 -timeout 45m ./internal/plugin/: ok (165s).
- go test ./internal/provider/: ok with
  -skip TestUnreadLoginsWriteErrorsKeepCredentials, which crashes with
  "close of synctest channel from outside bubble" in filememo.Forget,
  filed as #3632 and not touched here.
- go test -run Plugin ./internal/gateway/: ok.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags
  nogui on internal/plugin: ok.
Not run before the push: the whole go test ./... (run after it); not
tried with the reporter's own plugin, which wasn't named.
2026-10-26 15:09:09 +08:00
yetone a9242eb68b plugins: a package.json with bytes after its object is mended around each bun command (plugins#405)
klmno1993 (Windows 11, bun 1.4.4, magpie 0.1.1552): plugins/package.json
kept the old file's last 56 bytes after its closing brace once a shorter
one was written over it (244 bytes before and after; zcode-auth had just
left the list). From then on every bun add in plugins/ failed on
"failed to read/parse package.json for workspace ''", whatever the plugin
or source. magpie itself writes package.json only when it is missing, so
the in-place write is likely bun's remove on Windows; not reproduced here.

Now, under installMu, before and after each bun command (runBun and
install's bun add), a package.json that doesn't parse but starts with a
whole object is cut to that object and written through edit.WriteAtomic;
the file as it was is kept as package.json.broken. A file whose start
isn't an object, or one cut short, is left as it is. Users already stuck
are mended on their next install or update, with nothing to do.

Run:
- TestPackageJSONTailIsCut, with the reporter's bytes: red with the write
  pointed elsewhere by hand, green with it.
- go test ./internal/plugin (104s, ok, at e5dd86965), go build ./...,
  gofmt -l, GOOS=linux and GOOS=windows go vet ./internal/plugin; after
  the rebase onto origin/main, the build and the new and Load tests again.
Not tried: a real bun remove on Windows leaving the tail, or the whole
suite.
2026-10-26 15:02:10 +08:00
yetone 091153bf71 idle: the loops following magpie's files wake on its own writes, not a 1-2s poll (#3185)
An idle `magpie serve` (no providers, no requests) woke 12-13 times a
second. A runtime trace showed the wakers were polling loops: the
middleware observer's refresh every 1s, pluginrt.KeepFresh's stat of five
files every 2s, OTel's session watch every 2s and its exporter tick every
5s, all with nothing to do.

Now filememo.Forget, which every write magpie makes of settings,
providers, sign-ins and caller keys already calls, also closes a channel
(filememo.Written). The plugins.json, tools and plugins.yml saves call it
too. The middleware observer, KeepFresh and OTel's session watch wait on
it, and look every filememo.OthersEvery (5s) only for what another
process (the CLI, a second magpie) wrote. Each takes the channel before
it looks, so a write made during a look isn't missed. middleware's
current() also reloads at once when filememo's generation moved, rather
than after its 1s skip. OTel's session watch waits 5s, not 2s, while
sessions aren't exported, and its exporter's timer runs only while a
batch holds something.

Measured: sandbox HOME, MAGPIE_ADDR=127.0.0.1:3481, `magpie serve`,
proc_pid_rusage (idle + interrupt wakeups) over 30s after 40s warm-up,
old (cec54c1d0) and new builds alternated:
  old  13.2 / 13.3 / 12.2 wakeups/s, 0.40 / 0.35 / 0.42 ms CPU/s
  new   7.9 /  8.6 wakeups/s,         0.22 / 0.30 ms CPU/s
What's left is the Go runtime itself, awake.Keep's 5s tick and the 5s
looks for other processes' writes.

Tests: TestKeepFreshFollowsPluginsYml now also runs KeepFresh with a 1h
interval and needs Set to apply at once; TestStrategiesFollowOwnWrite
needs a plugin turned off through plugin.SetOff to stop being served
within 2s, with no refresh by hand; TestWritten. With the Written cases
replaced by a nil channel, both of the first two went red (applied = 1,
want 0; still served 2s after). Run at this head: go test -count=1
-timeout 45m ./internal/filememo ./internal/plugin ./internal/pluginrt
./internal/middleware ./internal/otlp ./internal/settings
./internal/access: all ok. GOOS=linux and GOOS=windows go vet -tags
nogui ./internal/...: clean. gofmt -l internal: clean.

Not run: the full suite and internal/gateway's tests (gateway.go only
changes KeepFresh's interval argument, and it compiles under vet); the
macOS app with its window open (only headless serve was measured).
2026-10-25 23:45:34 +08:00
yetone 2c7f0ac12c plugin: options saved from a hooks package's own page reach its hook
SetPageOptions saved without starting the host again for any package whose
page and panels looked like all it had. Window() only reads main/exports,
so a package with magpie.hooks and a page (magpie-community/plugins#117's
PowerContext) counted as page-only. The host hands each hook the options it
loaded with, so a Service URL or key saved from the page did nothing until
magpie restarted. A gateway hook now goes through SetOptions, as a
middleware and an agent already did.

Run at d2e0ea393 plus this change:
- TestGatewayHookSeesOptionsSavedFromItsPage: red on the old page.go
  ("tag=first after the page saved, want second"), green with the fix.
- go test -tags nogui ./internal/plugin: ok (118s).
- go test -tags nogui -run 'TestAsyncGateway|TestGatewayHook' ./internal/gateway: ok.
- go test -tags nogui -run 'Page|Plugin' ./internal/gui: ok.
- GOOS=linux and GOOS=windows go vet of internal/plugin and internal/gateway; gofmt -l clean.
- The real PowerContext package (PR head 3a6aa8f rebased on plugins main)
  in the real Bun host behind New().Handler(): before the fix a page save
  sent nothing to the new server; after it, the next request resolved,
  prepared and hinted against the new server with the new key.
Not run: the full go test ./... (machine at load ~340).
2026-10-25 19:06:34 +08:00
yetone a2ff7e6cab plugin: add takes a community plugin's name (WorkBuddy, think-tags, qoder-cn)
Atlas on Discord (#help, 10-25, Linux): `magpie plugin add WorkBuddy`
said "isn't an npm package name". Worse, a bare `workbuddy` passed the
npm-name check and installed npm's unscoped workbuddy@latest, not
@magpie-community/opencode-workbuddy-auth.

plugin.Add, which the CLI, the Plugins page's field (/api/plugins/add)
and the movers all go through, now resolves a bare name first
(internal/plugin/resolve.go). Case aside, a name one community listing
goes by is its package, at the version given: the package or its bare
name, the short name (workbuddy, think-tags), the shown name (WorkBuddy,
Command Code), a provider id it serves or the subscription it replaces,
and a retired subscription's id through its mover (qoder-cn; provider
sets plugin.SubscriptionPlugin = MovePackage). The CLI says which
package it picked. A name two listings go by, or none that isn't an npm
name, is refused with the community plugins listed. A name no listing
goes by is npm's own package (opencode-gemini-auth keeps working), but
only when the list was fetched within the six hours: when the fetch
fails, the copy kept or built in may not name a newer plugin, so the
name is refused with why, and npm:<name> installs npm's package as
written. market() now says whether its list is a fresh fetch (marketErr).
Scoped names, paths and git specs are unchanged. A backup's or a sync's
plugins go in by their own spec (plugin.AddExact via addPluginExact),
never resolved, so a restore isn't held by GitHub being unreachable.
Update, Upgrade and InstallMissing use add with stored specs, unchanged.

Tests (fake registry over httptest, fake bun; no network):
TestResolveCommunityNames, TestResolveRefusesWhatItCantName,
TestResolveListUnread, TestAddByCommunityName. TestUpdateAllUpdatesAPinnedPlugin
adds an unscoped third-party name, so it now serves a registry.

Broken by hand: Add without resolve -> TestAddByCommunityName red with
the reporter's own error ("WorkBuddy" isn't an npm package name) and
workbuddy -> workbuddy@latest. The unread-list rule turned off (valid
name goes to npm regardless) -> TestResolveListUnread red.

Real use, sandbox HOME, built binary, real npm and GitHub:
`plugin add WorkBuddy` -> installed @magpie-community/opencode-workbuddy-auth@latest,
listed workbuddy and workbuddy-ai; `think-tags` -> middleware-think-tags;
`opencode-gemini-auth` -> npm's, google-plugin listed; `qoder-cn` with
MAGPIE_PLUGIN_MARKET=off -> opencode-qoder-auth; "Work Buddy Pro" ->
refused with the 38 community plugins listed; `twinz` with the list off
or at a dead URL -> refused, saying why and npm:twinz.

Run at this head (rebased on origin/main 42976f9a0): gofmt -l clean;
go vet (darwin) and GOOS=linux / GOOS=windows -tags nogui vet of
plugin, provider, cli, backup, gui clean; go test -timeout 45m
./internal/plugin ok (120s, after the pinned-update fix),
./internal/provider ./internal/cli ./internal/backup ./internal/gui ok.

Not tried: the full ./... suite; Windows and Linux runs of the tests.
No GUI JS changed: the Plugins page's field goes through the same Add,
and its status still says "<typed name> is installed" rather than the
package picked; the installed list shows the package.
2026-10-25 11:52:02 +08:00
yetone 5b32b7ea80 plugins: a Bun Windows can't load (0xc0000139, before 10 1809 / Server 2019) says so and what to do (zgcwkj on Discord)
zgcwkj runs magpie-cli-windows-amd64.exe as a Windows service (nssm) and
every plugin install failed with "bun add …: exit status 0xc0000139: (and
from the community repo's dist branch: bun add ./dist/….tgz: exit status
0xc0000139: )".

Why: 0xc0000139 is STATUS_ENTRYPOINT_NOT_FOUND, the loader refusing the
exe before it runs. Reading the PE imports (debug/pe) of Bun's
windows-x64(-baseline) zips: 1.3.14 and later, so magpie's floor 1.4.2
and the latest 1.4.4, import kernel32's CreatePseudoConsole,
ClosePseudoConsole and ResizePseudoConsole, which Windows has from 10
1809 (build 17763) / Server 2019 on. 1.3.13 doesn't. Bun's docs say
"Windows 10 version 1809 or later" (bun.com/docs/installation). So
Windows Server 2016 and Windows 10 1507 to 1803 (LTSB 2015/2016) can't
run any Bun magpie uses. 1.4.2's pinned SHA-256 matches the asset.

What changes:
- wontLoad (internal/plugin/bun.go) reads an exit of 0xc0000139 as
  "this Windows" and 0xc000001d or SIGILL as "this processor" (Bun's x64
  build targets SSE4.2), as a *BunUnstartableError whose message says
  which, the versions Bun needs, and MAGPIE_BUN.
- bun add, bun update, cantStart and whyDied (the host's start) wrap it.
- An install no longer tries the dist branch after it: that bun add
  can't start either, and its error read as the dist branch's.
- The GUI's fail() answers it with code bun_unstartable, bunWhy and
  said, an i18n.js key (bunSaid in api.go), which api() in app.js puts
  through t(): en, zh, zh-TW, ja, de, in the window and in magpie web.
  The sentences live in Go so app.js grows one line: with both in
  app.js, TestCoreScriptBudget was 128 bytes over app.js's budget and
  487 over the core's, and no budget is raised here.
  TestBunSaidIsTranslated fails when a language lacks one. The CLI
  prints the English message.
- No fallback to an older Bun: 1.3.13 is below BunVersion and Bun
  doesn't support that Windows, and the -baseline assets are now the
  same binary.
- docs/subsystems/provider-plugins.md says all this.

Run:
- New tests: TestWontLoadSaysWindowsOrCPU (injected NTSTATUS exits, a
  real kill -ILL), TestInstallOnUnstartableBunSaysWhyAndSkipsDist (0
  dist requests), TestHostOnUnstartableBunSaysWhy, TestFailSaysBun
  Unstartable, TestBunSaidIsTranslated, plugin-bun-unstartable.test.cjs (chromium and webkit,
  every language, window and web).
- Real Windows (10.0.26200 box, a sandbox dir of its own): a
  windows/amd64 nogui magpie-cli.exe with a fake magpie-bun.exe that
  exits 0xc0000139, `plugin add @magpie-community/opencode-raccoon-auth`
  printed the new message, and no dist folder was made.
- gofmt -l; go vet darwin, linux -tags nogui, windows; builds of all three.
- Full suite (go test -tags nogui -timeout 45m ./..., through
  suite-lock, at a6399dd49 plus this change with both sentences in app.js):
  every package ok except internal/gui's TestCoreScriptBudget (128
  bytes over app.js's budget, 487 over the core's). After the sentences
  moved to bunSaid: internal/gui and internal/plugin ok, budget
  included (core 1,528,331 of 1,528,525 before scoping the line to the
  code, ~20 bytes more after).
- GUI (chromium and webkit, node --test): i18n-keys, every plugin-*
  file and signin-paste-plugin, 660 of 660 before the move to bunSaid;
  after it 656 of 660 at load ~140: plugin-card-update webkit (#3079)
  and plugin-quota-error chromium ja, whose Chromium launch hit
  Playwright's 180s timeout before the test ran. Both files alone: 16
  of 16, 14 of 16 (which one not kept), 16 of 16, 16 of 16.
- Rebased on ff6090354: TestCoreScriptBudget, the new Go tests,
  plugin-bun-unstartable and i18n-keys again ok; gofmt; windows and
  linux vet of internal/plugin and internal/gui.

Broken by hand (each restored):
- wontLoad always nil: the three plugin tests fail, the install one
  with the reporter's exact "(and from the community repo's dist
  branch: …)" shape.
- the dist skip removed: 1 dist request.
- the whyDied check removed: the host test fails.
- fail()'s block removed: the gui Go test fails.
- app.js's line turned off: the GUI test fails, 16 of 16 (chromium).
- one language's key renamed: TestBunSaidIsTranslated fails (3 of 4).

Not tried: a real Windows before 1809 (the box is Windows 11) and a real
processor without SSE4.2; zgcwkj's Windows version is still unknown.
2026-10-25 05:54:07 +08:00
yetone 3b5a2f612d dsh: Max reaches GLM-5.3 as max, asked adaptively with its level
01huadalang on Discord (10-24): DSH Desktop on magpie-anthropic, zcode
GLM-5.3 at Max; magpie's Routing log showed 77 of 78 requests at low,
one at high, never max.

What DSH sends, from the real app (DSH Desktop 0.2.1-rc.3's app.asar,
pi-ai 1.1.0 and dsh-llm-pi-ai, run read-only through node with
magpie's GLM-5.3 entry): at Max and at High alike, max_tokens 128000
and thinking enabled, budget_tokens 16384. pi-ai's clampReasoning turns
xhigh and max into high before thinkingBudgetForLevel, so no
thinkingBudgets setting can give Max a budget of its own. At Low it
sends 2048; with reasoning off, no thinking field.

What magpie did with it: 16384 is read as high (effortOfBudget) and
sent as output_config.effort high, so Max could never reach max. The
"low" rows were not reproduced: no request DSH builds at Max reads as
low here, and Z.ai refused none of the shapes (live, below), so no
refusal memory lowered it. A 2048 budget (a session or a subagent DSH
runs at Low; dsh-tool-subagent lets the model pick reasoning_effort)
reads as low, and that is the likeliest source. It is asked of the
reporter.

The fix, zero-config: Z.ai's GLM-5.2 and GLM-5.3 (the GLM half of
effortInOutputConfig) are written into dsh's magpie-anthropic route
with compat.forceAdaptiveThinking (gateway.AdaptiveWithEffort, beside
AdaptiveThinking). MiniMax-M3.1-Flash, the other half, is left on its
budget: adaptive wasn't tried on MiniMax (no key), so it is on #3496. pi-ai then sends thinking adaptive and
output_config.effort from magpie's thinkingLevelMap, max as max
(checked against the real asar: low/high/max each go as themselves).
The gateway already passes adaptive thinking with output_config.effort
through for these models (fitted to their levels, withOutputEffort;
TestGLMEffortInOutputConfig pins it), so the gateway only gains
AdaptiveWithEffort. No client name is keyed on, and a budget alone is
read as before. An adaptive-to-budget rewrite in withOutputEffort was
tried first and dropped: TestGLMEffortInOutputConfig pins adaptive
passing through, and Z.ai takes it.

Live, Z.ai GLM-5.3 with the zcode key (sandbox script, key never
printed): adaptive and enabled+effort both accepted; effort max
thought 1237-1427 chars against 426 at high, so max is a real tier.

Run, at this head rebased on origin/main 3be1f14eb (head 7ae044226):
- go build ./...; go vet of gateway and agent for darwin, linux and
  windows; gofmt -l clean.
- go test ./internal/gateway/ ./internal/agent/ ./internal/plugin/
  -timeout 45m at this head: ok (655s, 469s, 187s)
  (an earlier run, with the dropped rewrite, was red on
  TestGLMEffortInOutputConfig only, which led to dropping it).
- Own GOCACHE: the shared one had files trimmed mid-build by another
  run (vet "could not import sort").
- A first run hit "no space left on device" from another session's
  disk use (18G free after); rerun in full.
Broken by hand: with dshKindConfig back on AdaptiveThinking alone,
TestDshMaxReachesOutputEffortModels is red for GLM-5.3 and GLM-5.2. TestAdaptiveOnOutputEffortModelAsksItsLevel (the
gateway end, through a fake zcode plugin) passes on the old gateway
too: it holds that DSH's new shape reaches the vendor and the Routing
log as max, not a gateway change.
Not tried: DSH Desktop itself against this build (the app isn't
installed here; its pi-ai was run from the asar instead); MiniMax with
adaptive (left out, #3496); the whole go test ./... and GUI suite (no GUI change).
Siblings left alone, filed as #3496: Pi and omp hit the same pi-ai
clamp, MiniMax-M3.1-Flash above, and dsh to a DeepSeek model on DeepSeek's host (#3298) still
goes as a 16384 budget, since dsh's compat is per model id.
2026-10-24 23:27:25 +08:00
yetone 63c0c354af gui: Discover is quieter: one unofficial mark, one button style, a reason in your language
Kiko03O1 on X asked for a better-looking Plugins › Discover page
("ui 设计能不能好看点"). Five things on it said one thing twice or said
it raw:

- A GitHub card had an "Unofficial" chip. A GitHub card is only ever
  drawn in the 非官方插件 · GitHub section, so the chip repeated the
  section's head on every card. It is gone from the card; the plugin's
  page keeps its full warning.
- Sign in on a card and on an Installed row is tinted like Install,
  not filled. It stays filled only in the plugin's sheet, so each level
  of action has one look.
- The GitHub line said Go's English in the middle of a zh page ("no
  answer in 8s"). internal/plugin's GitHub read now wraps its timeout in
  ErrNoAnswer; /api/plugins/github passes `why`: "slow" for that or any
  timeout, "limited" for GitHub's rate limit (ghtoken.Limited), and the page says "GitHub 响应超时" (zh, zh-TW, ja, de); the raw
  error is the line's hover. The line is smaller and muted, and Retry
  takes the accent colour.
- The second filter row's All had a count. It always equalled
  Installed + Not installed and the first row's picked count, so
  "全部 · N" showed twice side by side. It has no count now.
- Found on the way, same page: the filter box's placeholder was cut off
  in en at 1280/1100/980 and in de at every width but 420. It fits at
  every width now; the filter bar wraps where it did.

Looked at and left alone: the 8px inset on the borderless Signed in,
and the monospace version numbers.

plugins.js nets -25 bytes (the Unofficial chip's code went), so the
core script budget is unchanged: TestCoreScriptBudget passes at the
pushed head with no raise.

What was run, at this change on origin/main 4b9694c34, and again after
the last rebase onto 0df6a3aba: TestCoreScriptBudget, TestTaggedWhyKind,
gofmt, and the four changed GUI files with i18n-keys in both engines
(80 of 80):
- Red without the change: with the old assets, the four changed GUI
  files (plugin-github, plugin-github-wait, plugin-github-filter,
  plugin-market) went 37 red in Chromium; plugin-market expected the
  tinted colour and got the filled one. TestTaggedWhyKind doesn't
  compile without the change.
- Changed and nearby GUI files (those four, i18n-keys,
  plugin-check-github-limit, plugin-kinds-discover, plugin-page), both
  engines: 124 of 124 pass.
- gofmt clean. go vet clean on darwin, linux (-tags nogui) and windows;
  all three build. go test internal/gui and internal/plugin: plugin ok;
  gui ok on its own, one red in the package run,
  TestMainWindowCorners/macOS_15_SDK killed at its 40s deadline at load
  ~85 (#2645), which passes alone.
- The whole GUI suite (858 files, both engines, concurrency 3) was
  started at 628e18987 and ended early when the disk filled (ENOSPC):
  ~350 files ran, 3108 passed. Its five reds from before the disk
  filled are off the Plugins page, pass alone, and are filed:
  agent-models (#3468), cli-update (#3473), context-picks (#3483),
  deprecated-subscriptions (#3484). The rest failed launching a browser
  with ENOSPC.
- Rerun after space was freed, at d7ad3f2a3 plus this change: every
  library-* file, every plugin-* file, login-import, menu-input-scroll,
  mobile-web, name-suffix-saved and i18n-keys (94 files, both engines):
  1414 of 1426 pass. The 12 reds are all red on an origin/main
  118486258 worktree too, and filed: library-mcp-health-wsl ja (#3350),
  menu-input-scroll (#3402, 0 of 4 on main), plugin-card-update webkit
  (#3079, 0-1 of 3 on main over three runs, same Update-button wait),
  plugin-github chromium de 440 scrolled 1px (#3218, 18 of 18 alone).
- The two files after name-suffix-saved outside plugin-* that open the
  Plugins page, settings-tabs-stick and title-bar-tools, both engines:
  42 of 42 pass.
- Not run: the other ~440 GUI files after name-suffix-saved, and
  go test ./... .

Screenshots, before and after, zh dark and en light, were checked by
eye at 1280.
2026-10-24 22:31:59 +08:00
yetone 7d9165d842 gateway: tests for plugin-served Factory with Standard usage only, 99% caps and order routing (plugins#349)
TestPluginFactoryStandardOnlyCaps runs the fake plugin as factory (marked
moved, two OAuth accounts A then B, order routing, each capped at 99% with
SetAccountCap as `magpie provider account-cap factory <account> 99` does).
The windows are those Factory's plugin 0.1.38 reports with standard_only
on (limitWindows(l, true)): Standard's 5 hours and 7 days with no model
list, Droid Core's and Extra usage aside. The fake plugin gains
$FAKE_WINDOWS, a file of each account's windows read at each usage
reading, so routing reads them through the host and provider.Allowances,
not a stub.

What it holds, today's behaviour, no code change:
- A's 7 days at 99% (its 5 hours at 40%): A is not sent the request; B
  serves fake-1, fake-claude and glm-5.3 (a Droid Core model). The trace
  shows a@fake 99/99 left out with its reset. Core windows at 100% on an
  account below its Standard caps don't hold it.
- Both capped (A's 5 hours 99%, B's week 100%): 429 rate_limit_error,
  "usage cap reached: every account that serves ... - Factory (a@fake) is
  at 99% of a usage window, past its 99% cap, until <time>; Factory
  (b@fake) ...", advice naming magpie provider account-cap, Retry-After
  at the sooner reset (A's 5 hours), nothing sent to the vendor, logged
  "every account at its usage cap".
- A read again below its cap serves again; a kept reading still at 99%
  whose reset time has passed serves too.
- A conversation on A moves to B when A is capped. Once A is back: auto
  affinity with no cache worth keeping goes back to A; with B's cache
  (5000 cached tokens) it stays on B; affinity session stays on B. A new
  conversation goes to A.

Broken by hand, each red at the step it guards: capHeld returning nil
(A served while capped), allowanceOf keeping aside windows (glm-5.3 went
to B while A's Standard windows were below cap), CapHeld ignoring a
passed reset (429 where A should serve).

Run: go test -tags nogui ./internal/gateway -run
TestPluginFactoryStandardOnlyCaps -count=1 -v, ok; go test -tags nogui
./internal/gateway ./internal/plugin ./internal/provider ./internal/cli
-count=1 -timeout 45m at base ed91aa04e: all four ok (gateway 494s,
plugin 217s, provider 191s, cli 88s); rebased onto ef1a203df and the new
test run again there (below). gofmt -l clean; GOOS=linux go vet -tags
nogui and GOOS=windows go vet of ./internal/gateway clean. No full ./...
suite: tests and testdata only, and another session's full suite was
running.

Sandbox HOME, built binary, fake plugin as factory, two accounts signed in
with magpie plugin login factory (browser opener stubbed on PATH):
magpie provider account-cap factory alice@fake 99 -> "capped at 99% of
each usage window", saved as accountCaps in providers.json; --window
"7 days" 95 and default work; an unknown account and 150 are refused.

Not tried: real Factory accounts, the real plugin's own option toggle in
magpie (its own usage.test.mjs covers the switch), the Anthropic
/v1/messages route's 429 body.
2026-10-24 15:33:17 +08:00
yetone 3dc25a6168 tests: a plugin fake's vendor counts only its own test's requests (#3357)
Run 39913278700 at 65e80405b (ubuntu, Race): TestClinePluginPinsDeepSeekAndGLM
"the plugin sent 7 requests" for 6 asks, in 0.33s. #3347 was the same
class: TestPluginToldWhereTheAgentWorks got 2 for 1, in 0.66s.

Cause, as far as it is known. The extra request did not come from the
test's own route:
- not a gateway retry: retryPause is 1s, so a retried ask can't finish
  in 0.33s or 0.66s. #3347's "a first try failed with a 5xx and was
  retried" doesn't fit either run's time;
- not the plugin host: the gateway reaches the host over stdio JSON-RPC
  (no HTTP retry), and host.js fetchAs calls the loader's fetch once;
- a never-reset log of every request the cline test's vendor got showed
  exactly 12 (6 asks x 2 runs), all POST /v1/chat/completions from
  magpie/dev, with nothing in the background.
So the seventh came from outside the test. The likely sender is a late
request from another test, in this shard or another of race-shards.sh's
four processes, reaching a port the kernel handed to this test's
httptest server (the class d0ccbbebc met with a freed port). Which test
sent it is still unknown.

Fix the class: testenv.FakeVendor(t, h) serves a fake plugin's vendor
at $FAKE_BASE and sets $FAKE_RUN to a nonce made for the test. The fake,
renew and renewrace plugins send it as X-Fake-Run. A request without it
gets 421 and is logged with its method, URI, remote address, User-Agent,
Authorization and size, so the next one on CI names its sender. Every
gateway and plugin test that served the fake's vendor with
httptest.NewServer plus FAKE_BASE now uses it (10 gateway, 5 plugin
files). The cline test now counts against the asks' recorded tries, as
65e80405b did for the workdir test: it fails on a real duplicate and
logs each retry's status. No exactly-once guarantee was loosened.

Reproduction by injection, at be002aca0:
- a request to FAKE_BASE from outside the route, with the filter off:
  "the plugin sent 7 requests for 6 asks tried 6 times" (the CI shape);
  with it on, the test passes and logs the 421 line;
- the fake plugin fetching twice for glm-5.3 (a real duplicate) still
  fails: "sent 8 ... tried 6". Both breaks were restored.

Ran at be002aca0 (macOS, -tags nogui):
- gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows ok;
- internal/plugin -race -count=20 ok (157.5s);
- the edited gateway files' tests -race -count=20 ok (93.1s);
Rebased on c8c6e7e23 (it brings TestPluginThinkingOff, on besideFake),
and ran there: gofmt -l clean; vet of the three packages for darwin,
linux nogui and windows ok; TestPluginThinkingOff, the cline and the
workdir tests -race -count=20 ok (18.3s); internal/gateway (363.6s),
internal/plugin (83.9s) and internal/testenv -timeout 45m ok, with no
421 line logged;
- a Linux container run of gateway.race in four shards like CI's,
  -test.v: ok, and no stray was seen.

Not tried: the stray was never caught in the act, here or in the
container, so the sender is a hypothesis. The count=20 run over all 142
besideFake tests hit 45m in TestPluginStreamLargeReplies (sizing, no
FAIL) and was narrowed to the edited files. No product code changed, so
the full ./... suite was not run.
2026-10-23 16:57:33 +08:00
yetone bac5be0677 plugin: one renewal of a sign-in at a time across magpie processes (plugins #331)
Cause: every magpie process that loads plugins runs a plugin host of its
own (the gateway, a CLI quota or usage command, a host restarting while
the old one finishes), and host.js's renew() kept a sign-in's renewal to
one at a time only inside one host (the in-memory renewing map). Two
hosts that found the same sign-in due each called the plugin's
auth.refresh with the same refresh token. A vendor that spends a refresh
token once (MiniMax, and about ten plugins' vendors: cline, codearts,
qoder, trae, workbuddy, raccoon, nous, kiro, factory) turned the second
away with invalid_grant, the plugin threw signIn "expired", renew() sent
it on without looking at the store again, and host.go -> provider's
notePluginLapse marked the account signed out, though the first host
had already saved a good token.

What changed, in internal/plugin/host.js only, for every plugin:
- renew() takes a lock file of the account's beside the store,
  plugin-auth.json.renew-<sha256(key)[:16]>.lock, holding the holder's
  pid and start time, across the plugin's auth.refresh, and lets it go
  in finally. It is separate from plugin-auth.json.lock, which changeAuth
  holds only for a write and never across an await. A lock whose pid
  is gone (process.kill(pid, 0), EPERM counted alive) is taken over at
  once, one older than 60s by anyone; a live holder is waited for with
  an async backoff (10ms to 500ms), never blocking the host's loop, and
  never past 120s. A lock is removed only while it holds the bytes read.
- Under the lock the sign-in is read again from the file (past
  readAuth's stat cache). Changed since the renewal began (another host
  renewed it, or it was signed out or in again), the renewal ends
  without calling the plugin; no longer due, likewise.
- A refresh that throws while the stored sign-in changed meanwhile (a
  magpie from before this lock spent the token and saved the new one)
  is logged, not reported expired.

Tests (internal/plugin/plugin_renew_race_test.go, fixture
testdata/renewrace): a fake vendor on loopback whose refresh tokens are
single-use.
- TestRenewOnceAcrossHosts: two hosts in two processes (this test binary
  and a child running TestRenewOtherHost) on one sandbox store. The
  first host's exchange is held until the second host is renewing too,
  waited on as state. One exchange, neither host says expired, both
  requests go with the new token, the store has it.
- TestRenewLockOfDeadHostAndRefusal: a lock naming a pid that has ended
  is taken over inside the request's wait and removed; a token the
  vendor never gave still says expired and leaves the account as it
  was; one refused after another magpie saved a new token says nothing
  and the next request goes with that token.

Broken by hand, each red:
- no lock (lockRenew returns at once): TestRenewOnceAcrossHosts red with
  exchanges [r1 r1], the other host said [expired], a request sent
  a-old - the issue's symptom; the dead-pid test red (lock left).
- no re-read under the lock (now = was): exchanges [r1 r1].
- the catch's check removed: "a token another magpie renewed meanwhile
  said expired".
- a dead pid counted alive: the dead-pid test red after its wait.
(Removing only the re-read's "changed" branch stays green: the "no
longer due" check under the lock catches the same case.)

Run at c909ca5e4 (on origin/main 84d902ce2): the new tests and
TestPluginRenewsSignIns -count=3, and -race -count=10 for the new ones;
gofmt -l; go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows;
set -o pipefail; go test -tags nogui -timeout 45m ./... tee'd to a
log: all 88 packages pass (69 ok, 19 no test files), none red
(gateway 574s, agent 431s, plugin 265s, provider 246s). origin/main
was still 84d902ce2 at push.

Not tried: a real vendor account racing (MiniMax or another); Windows
and Linux runs of the new tests (process.kill(pid, 0) in Bun on Windows
is expected to work as in Node, not seen); the GUI suite (internal/gui
untouched). Not changed: a plugin that refreshes inside its own loader
(MiniMax's fetch on a 401, or within EARLY_MS) still de-dupes only in
its process; magpie's renewal comes before that window, so it is the
rarer path.

Reported by 1007cordon-ux (plugins #331).
2026-10-23 14:26:43 +08:00
LoKi 5871f02dd6 plugins, provider, gui: a keyless plugin sign-in needs no key, and a single-identity plugin has one account (#2695, LoKi)
LoKi's patch (lokic7123-star), picked onto origin/main ef6f3749d. A plugin's api
method that has an authorize step and no prompts is reported as keyless:
PluginAPIKey accepts an empty key for that method only, the CLI and the
GUI skip the key field, and a plugin marked auth.single signs in again
on its first account instead of adding another one. Zen Free needs
magpie-community/plugins#205 (keyless and single on zen-free), merged and
published, before its users see this.

Added in review (yetone): TestPluginEmptyKeyOnlyKeyless, which checks that
an empty key is refused for a non-keyless api method, an oauth method
marked keyless, an out-of-range method and an unknown plugin.

Run at the stacked tree (this commit plus #2554 and #2862, on ef6f3749d):
- gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui, and
  GOOS=windows: ok.
- set -o pipefail; go test -count=1 -timeout 45m ./... under the suite
  lock: every package ok (SUITE_EXIT 0).
- GUI: plugin-keyless-signin, account-models, i18n-keys and
  models-select-all-api, chromium and webkit, every language they cover:
  all pass.
Red on the old code: TestPluginKeylessSingleIdentity "keyless metadata lost"; the
GUI test 10/10 red; without signInKey's single line, "single identity
duplicated"; TestPluginEmptyKeyOnlyKeyless red with the Keyless check
replaced by false.
Not tried: a real Zen Free sign-in (needs plugins#205 published).
2026-10-22 20:50:59 +08:00
yetone 226551d0d8 gateway: MiniMax M3.1-Flash is sent its effort in output_config (shin4 on plugins#316)
An OpenAI client's reasoning effort (Responses' reasoning.effort, Chat's
reasoning_effort) for MiniMax Code's MiniMax-M3.1-Flash or -Preview, built
into an Anthropic body for the minimax plugin, went as a thinking budget
alone. Under the reporter's 8192 cap medium, high, xhigh and max were all
budget_tokens 7168, so the level was lost before the plugin saw it.

The two models join GLM-5.2/5.3 in effortInOutputConfig: buildAnthropic
sends output_config.effort next to the budget, and an Anthropic client's
budget gets its nearest level there too (withOutputEffort, passthrough).
MiniMax Code's catalog marks M3.1-Flash forced_on at low..max. The budget
stays as it was (the owner's plan on plugins#317); dropping thinking for
the managed-login route, as MiniMax Code 3.1.4 does, stays the plugin's
call. Nothing goes into prompt text. Claude, MiniMax-M3 and other vendors'
models keep the budget alone. MiniMax's public Anthropic API doesn't list
M3.1-Flash (platform.minimax.io text-anthropic-api), so the rule reaches
MiniMax Code's subscription and any relay serving those two models.

Tests (internal/gateway/minimax_effort_test.go, fake plugin $FAKE_MINIMAX):
- TestMiniMaxPluginGetsTheNativeEffort: the reporter's Responses request
  and its Chat form, low..max, both models, on minimax-code and
  minimax-code-global through the plugin host (bun), plus an Anthropic
  client's budget 10000 -> medium; MiniMax-M3 keeps no output_config.
- TestNativeEffortLeavesOthersAlone: claude-sonnet-4-5, kimi-k3 and
  MiniMax-M3 on an Anthropic relay get budget 7168 and no output_config.

Run at e31e3699a + this change, sandbox HOME, pinned caches:
- with the regex change reverted, TestMiniMaxPluginGetsTheNativeEffort
  fails with the reporter's table ("/v1/responses MiniMax-M3.1-Flash
  medium: output_config <nil>, thinking map[budget_tokens:7168
  type:enabled]"); restored, passes.
- the regex widened by hand to minimax|claude|kimi: TestNativeEffort-
  LeavesOthersAlone fails for all three models; restored, passes.
- go test ./internal/gateway -run 'Effort|Adaptive|Think|GLM|MiniMax|
  Budget|Reasoning|Level': ok. go test ./internal/plugin/...: ok.
- gofmt -l: clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.

Not run before this push: the full suite (the machine is at load ~210
with several sessions queued for it; it runs after, in turn). Not tried:
a real MiniMax Code account. Whether MiniMax's subscription endpoint
honours output_config.effort beside a budget (rather than with thinking
left out, as shin4's live run sent it) is not verified.
2026-10-22 19:36:50 +08:00
yetone 9b0f48612b gateway: a plugin's model that searches by itself can be the web searcher
01huadalang (Discord #feedback, 10-20): Settings › Web search offered only
Antigravity; Trae's search model couldn't be picked, "可能也有别的模型能搜索
但是识别不到". partSearcher and modelSearches answer false for every
provider with an account behind it, so no plugin-served provider was ever
offered, and a plugin had no way to say which of its models searches.

A plugin now marks such a model with `searches: true` (in its config
models or the list its models hook gives). host.js passes it on,
plugin.Model carries it, and pluginCatalog makes it WebSearch "native".
partSearcher offers a plugin provider with such a model, with those models
only, at rank 4 (as Command Code's search models); remoteSearch asks it in
plain words, the way it asks Command Code's. A client's own web_search
sent to that model still goes to magpie's searcher (searchesModel is
unchanged): the plugin's upstream takes no web_search tool.

Behaviour change: a marked plugin model ranks ahead of Antigravity and
Google (rank 5) when magpie picks the searcher itself.

Run:
- TestPluginSearchModelIsASearcher (new; a fake plugin's model marked
  searches answers a weather question with a URL): red on the old code
  (the picker offers [], want the plugin's fake-search alone), green now.
- Broken by hand: host.js without the `searches` passthrough; the test
  goes red at the picker.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows on gateway,
  plugin, provider, catalog.
- set -o pipefail; go test -timeout 45m ./... at this tree: 68 ok, no FAIL.

Not tried: the Trae plugin itself. It declares nothing about search yet;
marking Trae CN's search_agent there needs a Trae account to try it with,
which this machine doesn't have. No GUI files changed.
2026-10-22 03:18:11 +08:00
yetone 62a1df8010 provider: a plugin's daily check-in reaches every sign-in, also two that share a display name (plugins#254)
AutoClaw's plugin can hold several sign-ins under one default display name,
which AutoClaw doesn't let the user change. plugin_checkin.go keyed each
account's check-in on "<provider>|<AccountID>", the display name, so
checkinNow's per-key dedupe asked only the first sign-in of each name, by
the loop and by Check in now alike; the others stayed 今日未签 for good,
and Settings showed one row, and one Off switch, per name.

Each sign-in is now keyed on the key plugin-auth.json keeps it under
(pluginCheckinKey: "autoclaw|autoclaw", "autoclaw|autoclaw#x1y2z3").
Two sign-ins never share it; a refresh writes the same key, and signing
in to an account already signed in goes back to its key (host.js
settle). The display name is shown only. Cards, Settings rows,
CheckinOff and Check in now all read the same key, so app.js is
unchanged. An account without an AccountID already had this key.

Upgrade (adoptLegacyPluginCheckins, run when the plugin's accounts are
listed): an entry kept as "<provider>|<display name>" goes
- in plugin-checkin.json, to the first sign-in in use of that name (the
  one the old key's check-in asked) and only to it, and the old entry
  is dropped: it isn't asked again today, and its namesakes, never asked,
  are;
- in settings.CheckinOff, to every sign-in of that name: the user turned
  that name off and none of its sign-ins was checked in since, so the
  upgrade switches none on (settings.EditCheckinOff edits that field
  alone from what the file holds).
A plugin-checkin.json that can't be read or parsed is left as it is and
carried over once it reads; writes go through writePrivate
(temp-and-rename). Known gap: a sign-in made the same day after another
was signed out can take the freed key and that day's result.

The fake plugin's check-in now records a signed-in account as
name@fake/uid so two of one name tell apart in the presses.

Tests:
- TestPluginCheckinTellsSignInsOfOneNameApart: four sign-ins, A/u1, A/u2,
  B/u3, B/u4 (the reporter's case). All four pressed once, none again
  that day, four entries kept, four Settings rows, every card marked;
  with A/u2 off, Check in now the next day presses the other three.
- TestPluginCheckinCarriesOverDisplayNameEntries: a plugin-checkin.json
  with fakeco|A@fake and fakeco|B@fake claimed today plus another
  plugin's entry, and CheckinOff ["workbuddy|123", "fakeco|B@fake"].
  A's check-in goes to its first sign-in only, the old entries go, the
  other plugin's stays, both B sign-ins are off and workbuddy|123 is
  kept; the loop then presses only A's namesake, and a second look
  presses nothing.
- TestPluginCheckinCarriesNothingOverAnUnreadableFile.

Broken by hand, each red:
1. key back on the display name: TellsApart pressed only A@fake/u1 and
   B@fake/u3; CarriesOver kept the old entries.
2. adoption not called: CarriesOver ("A's check-in went to ... ok false").
3. record to every heir: CarriesOver ("carried to both") and Unreadable.
4. Off to the first heir only: CarriesOver (CheckinOff lacks one B).
5. old entry kept: CarriesOver and Unreadable.
6. parse error ignored: Unreadable.

Run at 0f044e944 (origin/main) plus this change, macOS arm64, sandbox
HOMEs from testenv, shared GOCACHE:
- go test -race -count=20 -run TestPluginCheckin ./internal/provider: ok
- gofmt -l on the changed files: prints nothing
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
  go vet ./...: clean
- go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok
- go test -timeout 45m ./...: exit 0, 68 packages ok, no FAIL
- after a comment-only rewrap: go test ./internal/provider
  ./internal/settings: ok
No GUI suite: internal/gui/assets is unchanged.
Not tried with real AutoClaw accounts or a real plugin-checkin.json from
the reporter.
2026-10-21 07:04:19 +08:00
yetone 0f044e9447 plugins: a GITHUB_TOKEN GitHub refuses is dropped for anonymous requests, not shown as an error (till on Discord)
till's Plugins page said "无法连接 GitHub: GitHub refused GITHUB_TOKEN
(no GitHub token is set in Settings → Network and sharing)". ghtoken.Token
falls back to the environment's GITHUB_TOKEN / GH_TOKEN, and a stale one
there made every GitHub read fail, though GitHub serves the same reads
without a token.

ghtoken.Do now sends a GitHub API request with the token. When the token
came from the environment and GitHub answers 401, it remembers that token
as refused for the rest of the process (Token() skips it, so GH_TOKEN is
still tried after a refused GITHUB_TOKEN, and Settings no longer shows it)
and asks once more without Authorization, returning that answer. A token
set in Settings is never dropped: its 401 is still Refused()'s error. An
anonymous rate limit after the drop is said by LimitedBy as before.

Every caller goes through it: plugin fetchJSONFrom (tagged-repo search,
git plugin checks, githubHead) and getURLFrom (Bun), and library apiGet,
skills fetch, skilltree fetchBlob and latestRTK via doGitHub.
internal/davsync/github.go stays strict: its token is the one the user gave
sync to write a private repo, outside ghtoken, and an anonymous retry can't
write there, so it would only hide why sync failed.

Tests (httptest only): ghtoken_test covers an env token refused then asked
again without, not sent again (and GH_TOKEN tried next), a Settings token
refused stays an error, an env token refused then an anonymous rate limit
is reported, and another host untouched. plugin TestTaggedReposStaleEnvTokenDropped
is till's case: TaggedRepos with GITHUB_TOKEN=stale-till lists 7 repos, no
error. github_token_test and library TestGitHubRateLimitSaid now expect the
env token dropped and the Settings token still refused.

Broken by hand, each red: (a) no anonymous retry: every new env test, the
plugin and library tests red, and TestTaggedReposStaleEnvTokenDropped shows
till's exact error; (b) no memory of the refusal: NotSentAgain, the plugin
and library tests red; (c) a Settings token also retried:
SettingsTokenRefusedStaysAnError, the plugin and library tests red.

Run on the commit before the rebase (base 9b04c4e20):
- gofmt -l: clean. go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
- set -o pipefail; go test -timeout 45m ./... at load ~30: 62 packages ok.
  agent, gateway and library ran past 45m while still progressing; gui
  failed TestSetAnswersWhileDevinAndProvidersHang (set took 10.26s, #1375)
  and TestMainWindowCorners (measuring killed, #1936/#2645); provider failed
  TestPluginPicksComeBackWithTheirList (#3051, fixed on main in c922225f1).
- Each rerun alone at load 21-56: library ok 809.7s, provider ok 308.8s,
  gui ok 159.5s, agent ok 1673.3s, gateway ok 780.4s.

After rebasing onto a3ebed202 (main moved 8 commits): gofmt -l clean; go vet
darwin, linux -tags nogui, windows clean; go test -count=1 at load ~57:
ghtoken ok 2.9s, plugin ok 277.6s, library ok 144.2s.
2026-10-21 06:16:31 +08:00
yetone d2c434b5a6 gateway: ClinePass pins glm-5.3-flash through OpenRouter's provider.only (sdytman on Discord)
sdytman (#feedback, 10-20) found that Cline doesn't send every model
through Vercel's AI Gateway: glm-5.3-flash goes through OpenRouter
directly, which ignores providerOptions.gateway.only, so the Upstream
tick (dd70c5e6a) didn't pin it. OpenRouter reads a top-level
provider.only with its own slug, "z-ai" for Z.AI
(openrouter.ai/api/v1/providers; its glm-5.3-flash endpoints list
"Z.AI z-ai/fp8"). deepseek-v4.1-flash and deepseek-v4.1-flash-1017 do go
through Vercel, so they keep providerOptions.gateway.only ["deepseek"].

provider.ClinePin now returns the upstream and whether the model's route
is OpenRouter, from a table whose first entry is glm-5.3-flash by exact
name (glm-5.3-flashx and glm-5.3 stay on Vercel's "zai" as before; which
router Cline uses isn't visible from its feed or either router's model
list, both of which list every one of these models). clinePin appends
"provider":{"only":["z-ai"]} at the body's end for such a model, so the
cached prefix is unchanged, and leaves a body naming provider or
providerOptions itself as sent. Applies to the Cline plugin's provider
too, since magpie writes its requests before the plugin sends them.

Not tried with a real request: there is no Cline account here.

Broken by hand, each red: no glm-5.3-flash entry (gets providerOptions
zai), a client's own provider field not checked (two pin keys), and
providerOptions for every model (flash has no provider.only). Not tried
with a real ClinePass request: no account here.

Run: gofmt -l (none); go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows: clean. `set -o pipefail; go test -timeout 45m ./...` at
1ebda9026 (this batch on 318697dce, movers then at qoder 0.2.21,
workbuddy 0.1.26, no devin raise): 65 packages ok, exit 0. Rebased onto
a9304efe0 (codex images, codex list tag, sessions decoders): gofmt, the
three vets and go test of internal/gateway, internal/provider,
internal/plugin and internal/sessions ok. Then the mover mins were raised
to qoder 0.2.23, workbuddy 0.1.27 and devin 0.1.21 (the only change
since, three strings): gofmt, the three vets of internal/provider and
go test ./internal/provider/ ok at the head of this batch.
2026-10-21 01:11:05 +08:00
yetone a257319963 plugin: an install takes the versions no longer installed out of Bun's cache (#1988)
Bun keeps every package version it ever fetched in its install cache
(~/.cache/magpie/bun/install-cache) and never takes one out. Each
release of a moved subscription's plugin that keepMovedCurrent or the
hourly updates installed added one more: the owner's Mac had 131
versions of the community plugins there, 10M, and it only grows.

After a successful install (beside pruneDist), the cache's
name@version@@registry folders whose version isn't the one in
plugins/node_modules are removed, then the links left to nothing in
each package's folder of links. A package whose installed
package.json can't be read or parsed keeps its versions (unknown, not
"not installed"). @T@ tarball entries and .npm manifests are left as
they are. What is installed is a copy, so a version taken out is only
fetched again if it is asked for again.

Measured on a copy of the live install cache with the live
plugins/node_modules package.json files:
  before: 10M, 131 entries under @magpie-community
  after:  1.0M, 18 entries (9 packages, the installed version each)

Run:
- TestInstallPrunesBunsCache (Bun's real layout, through install with
  the fake bun). With the pruneInstallCache() call commented out:
    installcache_test.go:62: opencode-grok-auth@0.1.16@@registry.npmjs.org@@@1 left in Bun's cache, not installed: <nil>
    installcache_test.go:62: opencode-kiro-auth@0.1.5@@registry.npmjs.org@@@1 left in Bun's cache, not installed: <nil>
    installcache_test.go:72: the link to the version taken out left: <nil>
    --- FAIL: TestInstallPrunesBunsCache (1.51s)
  With it: PASS. Also PASS on the Windows box (windows/amd64 binary).
- macOS, sandbox HOME: go test -count=1 -timeout 45m ./internal/plugin/
  -> ok internal/plugin 2214.050s (load ~250)
- gofmt -l clean; go vet ./internal/plugin; GOOS=linux and
  GOOS=windows go vet -tags nogui ./... clean.
2026-10-20 20:23:51 +08:00
yetone fb101b0d57 plugins: a GitHub list that couldn't be read says why with Try again, instead of the section vanishing (till on Discord)
till (Windows, v0.1.1293, Belarus network) saw no "Unofficial plugins ·
GitHub" section in Plugins › Discover; a magpie in Japan shows it. On
v0.1.1293 the section shows its loading skeleton and then disappears
whenever GitHub can't be read: plugin.TaggedRepos returned the last list
(or nothing) with no error when the topic search failed, and an empty
list with no error when the search answered but every package.json read
from raw.githubusercontent.com failed or timed out. /api/plugins/github
answered 200 {repos:[]}, and the page showed ghFailed only on an HTTP
error, never in a search, and never once a list had been had.

Now:
- TaggedRepos returns the error with what it has. A failed search keeps
  the last list and says why (held a minute, like before); repositories
  the search found but that couldn't be read come back as a
  *TaggedMissing with their count and the last read error.
- /api/plugins/github sends error and missing beside repos; ?again asks
  GitHub again at once when the last answer had an error.
- The page shows the reason and Try again: in place of the section when
  nothing could be read (in Discover and in a search), and as a line over
  the cards when some were read or an older list is kept. Try again keeps
  the cards while it asks. zh, zh-TW, ja and de strings added.

No Windows-only cause was found in the code: the fetch goes through the
same netproxy on every OS (a PAC-only system proxy isn't read anywhere).
The likely cause is the network reaching api.github.com or
raw.githubusercontent.com, or the unauthenticated search limit; the page
now names which.

Run (worktree on ef655acb4, sandbox HOME):
- gofmt -l clean; go vet darwin, linux -tags nogui, windows ok; builds ok.
- go test ./internal/plugin ./internal/gui: ok. Broken by hand (failure
  path returning nil error; missing ignored): TestTaggedRepos ("down:
  <nil>") and TestTaggedReposUnreadable go red; restored, green.
- plugin-github-wait.test.cjs: 18/18 in chromium and webkit, every
  language and width; against the old assets it times out waiting for
  the reason (red). After the rebase: once 16/18 and once 17/18 with
  page.goto's 5s load timing out at load average ~280, then 18/18.
- Whole GUI suite, both engines: all pass except codex-predictions at
  420 (7 cases: Settings' stuck search head takes the click), already
  #2624, untouched by this change.
- set -o pipefail; go test -timeout 45m ./...: every package ok except
  internal/agent, which hit the 45m timeout at load average ~200 with
  other sessions' suites (2769s). Rerun after the rebase with
  internal/plugin and internal/gui: plugin ok (973s), gui ok (550s),
  agent timed out again (2704s, load ~400). Recorded on #2723; this
  change touches nothing in internal/agent.

Not tried on Windows or from the reporter's network.
2026-10-20 02:35:14 +08:00
yetone dd70c5e6ae provider: ClinePass's Upstream tick pins GLM models to Z.ai too (sdytman on Discord)
sdytman (#feedback, 10-19) asked for GLM to have what DeepSeek has: with
Upstream ticked, a cline-pass/glm-* request goes only to Z.ai. ClinePin
now reads a maker table (deepseek -> deepseek, glm -> zai) and appends
providerOptions.gateway.only = ["zai"] for a GLM model, at the body's end
as before so the cached prefix is unchanged. cline-free/ models are never
pinned, other makers are unchanged, and a client's own providerOptions is
kept as sent. The tick stays one control; its label and hint now name
DeepSeek and GLM in en, zh, zh-TW, ja and de.

The slug: Cline routes through Vercel AI Gateway. Vercel's provider table
lists Z.ai as slug "zai" (name "Z.AI", website z.ai), and
ai-gateway.vercel.sh/v1/models/zai/glm-*/endpoints gives provider "zai".
sdytman called the upstream "z.ai", Z.ai's site and shown name; the
routing slug Vercel takes is "zai". Not tried with a real request: there is no
Cline account here, and both gateways answer 401 without a key.

The Cline plugin got the same change in
@magpie-community/opencode-cline-auth 0.1.9 (plugins ff13aac). There is
no cline mover, so no min to raise.

Run at 9b72add51 plus this change:
- gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- go test -count=1 -timeout 45m ./...: every package ok except agent and
  gateway, both red from "no space left on device" (the disk filled
  during the run; 35 ENOSPC lines) and TestQueueRefusalIsInTheUsageLedger
  (#2541, already filed). Rerun with disk free: internal/agent ok; internal/gateway ran 45m
  at load ~270 with no failure (TestQueueRefusalIsInTheUsageLedger and
  both Cline pin tests passed) and timed out in
  TestPluginStreamLargeReplies; the 829 tests from that file on, run
  alone, ok (1318s).
- Broken by hand, each red: no glm entry (both gateway tests), cline-free
  pinned, every maker pinned to zai, the client's providerOptions written
  over (red only after adding the one-providerOptions-key check: gjson
  reads the first duplicate key, so the old check passed).
- GUI, chromium and webkit: clinepass-pin (red against origin/main's
  app.js), gui-de, gui-ja, gui-zh-tw, i18n-keys, add-sheet: 22/22.
2026-10-19 20:58:53 +08:00
yetone f76201a84a plugins: a sign-in page the plugin's CLI opened isn't opened again, Grok's opened twice on macOS (andyfmyth on X)
"magpie里的grok 登录验证 在mac下 似乎每次都会弹两次验证, 在浏览器窗口里".
Grok's plugin signs in through `grok login --device-auth`, and Grok Build
(1.0.50, the webbrowser crate) opens the device page itself, through
NSWorkspace on macOS and ShellExecuteW on Windows. Neither reads $BROWSER;
the macOS binary has no "BROWSER" string. magpie then opened the same URL
from /api/plugin-signin (desktop), startPluginSignIn/followSignIn (a
browser tab) or `magpie plugin login`. Reproduced in a sandbox
HOME/GROK_HOME: grok's device-code tab appeared in Chrome with magpie not
involved, with and without SSH_CONNECTION. Built-in grok is retired
(2927a161e), so the plugin's path is the only one.

- The plugin's authorize result can say `opened: true` (not OpenCode's).
  host.js passes it on as Authorization.Opened, then SignInState.Opened,
  and the desktop handler, the CLI and app.js (both open points) open
  nothing then; the link is still shown.
- opencode-grok-auth 0.1.17 (magpie-community/plugins 47fbf63, on npm per
  `npm view --prefer-online`) says opened on darwin/win32, and elsewhere
  gives grok BROWSER=true, a no-op, so magpie stays the one opener there.
  The grok mover min is raised to 0.1.17.
- No other plugin's CLI opens a page: devin, cursor, kiro and qoder run
  status/refresh commands only.
- docs/subsystems/provider-plugins.md says so.

Tests:
- TestPluginSignInPageOpensOnce: the fake plugin signs in through
  /api/plugin-signin. "cli-opened" opens 0 pages; otherwise 1. Red with
  the old gui/plugins.go ("opened 1 more times").
- plugin-signin-opened.test.cjs: in a browser tab, right away and after
  an install, 5 languages, Chromium and WebKit. Every "opened" case is
  red on HEAD's app.js (23 fail); 42/42 with the change.

Run at the change (base origin/main 2ceff7370):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean.
- go test -p 4 -count=1 ./... -timeout 45m (load 150-380): every package
  ok except two.
  - gateway: TestVisionWaitIsntTheDescribersTime. It passes alone; filed
    as #2901.
  - gui: TestDockReopenKeepsTheWindowsSpace, TestMainWindowCorners,
    TestMainWindowRightToLeft, TestTrayCellClickReleasedPanel and
    TestCoveredWindowStaysUp, killed at their deadlines. All pass alone
    with TestPluginSignInPageOpensOnce; filed as #2645/#1936.
- GUI, both engines, at most 2 workers: plugin-signin-opened,
  plugin-signin, plugin-signin-no-url, plugin-moved-signin,
  signin-paste-plugin, signin-browser-down, signin-link,
  plugin-password-prompt and plugin-replaced. The run went 126 pass,
  10 fail, all launch or 5s timeouts at load ~380. Alone,
  plugin-signin-opened passes in both engines and password-prompt
  passes. signin-browser-down was red in one case per run, a different
  one each time. plugin-moved-signin (Chromium) is red alone at HEAD's
  app.js too. Both are filed as #2900.
- plugins: bun test packages/grok 49 pass; scripts/check.mjs ok. Its
  publish run is red only for middleware-think-tags's npm trust
  (plugins#180); grok 0.1.17 was published.
2026-10-19 12:42:48 +08:00
yetone 5774c790bd plugin: a reply's chunk frame is read by its fixed shape, not through encoding/json
Each chunk of a plugin's streamed reply (up to 64 KB of base64 a frame)
went through json.Unmarshal into message. encoding/json scanned every
byte twice (validating, then decoding the string) and cost far more than
decoding the base64 itself. chunkFrame reads the one shape host.js's
chunkLine writes, {"id":N,"event":"chunk","data":"..."}. Any other line,
or one whose data holds a quote or a backslash, still goes through
json.Unmarshal. push checks the data is base64 of a frame's size either
way, as before.

Measured (64 KB frame, json vs chunkFrame, each followed by the base64
decode push does; -cpu 1, 6 runs, load average ~480, so absolute times
are inflated):
- json.Unmarshal + DecodeString: 7.3-14.0 ms/op, median ~8.7 ms
- chunkFrame + DecodeString: 0.11-2.3 ms/op, median ~0.33 ms

Test: TestChunkFrameReadsWithoutJSON. Frames json.Marshal'd with a \n,
\r\n or no line end must parse and equal what json.Unmarshal makes. It
also refuses 11 other shapes, among them:
- an escape in the data;
- a negative id, or 1e3;
- extra fields or trailing bytes;
- a 20-digit id;
- reordered keys.
Broken by hand (chunkFrame always false), it went red: "a chunk frame as
host.js writes it ... went through encoding/json".

Run (load ~420): go test ./internal/plugin -count=1 -run on the chunk
frame, host, flow, stream, chunk, credit and fetch tests: ok (54.0 s).
The whole package runs with the final checks.
2026-10-19 09:40:46 +08:00
yetone ef75a9a2b5 plugin: a streamed reply's chunk frame is joined, not stringified, and its bytes viewed, not copied
Every chunk of a plugin's streamed reply went out as
JSON.stringify({id, event: "chunk", data}), and stringify scanned every
byte of the base64 for something to escape. Base64 has nothing JSON
escapes, so chunkLine joins the line from strings instead. The line is
byte-for-byte the one stringify made. A Uint8Array chunk that isn't a
Buffer (what a Response body hands over) was also copied whole by
Buffer.from before it was encoded. It is now viewed: the bytes are
encoded before the next read, so nothing else touches them.

Measured in bun, old and new interleaved in one process, medians (load
average 363-413, so absolute times are inflated). The bench asserts the
lines are equal.
- 2032 B frame: 152.8 us -> 12.8 us (78.9 -> 6.6 ms per MB)
- 16 KB frame: 675.8 us -> 69.4 us (43.3 -> 4.4 ms per MB)
- 64 KB frame (MAX_FRAME): 2135 us -> 292.6 us (34.2 -> 4.7 ms per MB)

Test: TestHostFramesChunksCheaply streams Uint8Array parts (one of 70 KB,
so it splits at MAX_FRAME) through host.js's fetch loop in a vm. It
checks:
- 4 chunk frames;
- the bytes come back equal;
- JSON.stringify never sees a chunk;
- Buffer.from never copies a chunk.
Broken by hand twice, red both times:
- the frame built as an object again: "chunk frames are joined, not
  stringified";
- Buffer.from(chunk) again: "chunks are viewed, not copied".

Run (load ~420): go test ./internal/plugin -count=1 -run on the host,
flow, stream, chunk, credit, fetch and auth tests: ok (51.2 s). The whole package runs with the final checks.
2026-10-19 09:40:45 +08:00
yetone 8f37ed57d2 plugin: plugin-auth.json is parsed once per version of the file, not on every request
Every request read and parsed plugin-auth.json in the host two or three
times: accountKey (when no account is named), fresh (is a renewal due),
and the plugin's getAuth from its loader's fetch. Reading and parsing a
20 KB file (12 sign-ins) cost ~0.65-0.97 ms each on this loaded machine.

readAuth now keeps what it parsed while the file has the same mtime,
size and inode, as Go's filememo does. While the file's time is within
2 s of now it also keeps the bytes and compares them, so two same-size
writes inside one tick of a coarse clock (Linux) still read as two. A
file that doesn't parse is never kept, so the .bak recovery path is
unchanged. changeAuth still reads afresh under the lock. The kept
object is shared, so what a plugin is handed (getAuth for loader, usage
and check-in, the models hook's auth, pi.js's readAuth) is a copy of its
own (authCopy).

Measured (load average 360-460, so absolute times are inflated):
- readAuth on a settled 20 KB file, old and new interleaved in one bun
  process, 6 rounds of 5000: old median 970 us (min 841) and 1 file read
  per call. New median 23 us (min 2.3), a stat, and 0 file reads.
- whole fetch (TestPerfScratch, not committed, {} body, 400 fetches):
  host CPU 750-825 us -> 750-775 us per fetch, inside this load's noise.
  A control run without the big file read 875 us at the same load. Host
  RSS 53 MB -> 42 MB.

Test: TestAuthReadOncePerVersion runs host.js's own auth section in node
with readFileSync counted. It checks:
- 100 reads of a settled file read it once;
- a rewrite is read;
- a same-size rewrite with the same mtime is read;
- authCopy's copies are the caller's own.
Broken by hand twice, red both times:
- readAuth made the old uncached read: "a settled file is read once for
  100 reads, read 100 times".
- bytes of a just-written file not kept: "a same-size rewrite in one
  tick is read".

Run (-p 4, load ~470): go test ./internal/plugin -count=1 ok with
TestGatewayHookMixedPiPackage skipped. That test passed alone at 545.6 s
(pinned pi install under load); in a full package run it hit its 4-minute
start deadline ("starting plugins: context deadline exceeded").
2026-10-19 09:40:45 +08:00
yetone e3c09f4f36 plugin: a request is told the provider info built once per account, not built again per fetch
host.js ran info(provider, key) on every fetch, to hand chat.headers
hooks the provider. Each build rebuilt the model list from models.dev and
config, read and parsed plugin-auth.json twice, JSON-cloned the list and
asked the plugin's provider.models hook, which real plugins (cursor, zed
and others) answer by asking the vendor once their own TTL runs out. It ran
even when no plugin had a chat.headers hook.

infoOf(id, key) now keeps the info per account. Any change to the
account's sign-in (setAuth, removeAuth, settle, client.auth.set, renew,
take, reload, all through forgetAccount), new provider options, or a new
models.dev file builds it again, once. providers() seeds the cache with
what it built. The loader, usage and check-in read it too; check's strict
build stays direct. chat.headers gets the shared object, as OpenCode hands
plugins the provider it keeps, and the request asks for it only when a
plugin has a chat.headers hook.

Measured (TestPerfScratch harness, not committed; fake plugin, sandbox
HOME, loaded machine, two runs each):
- {} body, 1-event reply, 400 fetches: models hook asked 400 -> 0 times.
- same, a plugin with 300 config models: 0.995-1.17 ms -> 0.27-0.29 ms
  wall per fetch, host CPU 1.23-1.33 ms -> 0.30 ms per fetch, host RSS
  87-89 MB -> ~54 MB.
- 246 KB body, 2 MB SSE reply, 40 fetches: host CPU 10.25 -> 8.25 ms per
  fetch, models hook asked 40 -> 0 times.
- idle host CPU ~10-20 ms per 10 s before and after.

Tests: TestFetchBuildsInfoOnce counts the fake's models hook (new
FAKE_MODELS_LOG): 20 fetches ask it 0 more times, a new sign-in and new
options each ask it exactly once, and chat.headers and the loader still
see fake-1 and every model. Broken by hand twice, red both times:
returning no cached info ("20 requests asked the models hook 20 more
times, want 0"), and not forgetting it on sign-in ("after a new sign-in
... 0 times, want 1"). host_flow_test's mid-setup case now stubs infoOf
and registers a chat.headers hook for its "info" stage, which red on
this change without it (the stage was never entered).

Run: go test ./internal/plugin -count=1 ok (159.5s);
TestFlowAbortDuringSetup|TestFetchBuildsInfoOnce -count=2 ok.
2026-10-19 09:40:45 +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
yetoneandTsukikage7 9b04c4e20f plugin: async gateway request hooks, run in Bun before routing and after the reply (#2118)
A package's magpie.hooks entry (or a *.hooks.{js,mjs,ts,mts} file) exports
`async onRequest(body, ctx)` and an optional `onResponse(reply, ctx)`. They
run in the Bun plugin host, so a hook can await I/O, for example a context
service like PowerContext, which the sync moejs middleware can't. The
gateway still makes one model request per client request. A hook adds
context to the body; it doesn't register tools or run a loop, so magpie
doesn't become an agent runtime.

Ported from Tsukikage7/magpie#1. Changes from the fork:
- The entry name is magpie.hooks / *.hooks.*. The fork's magpie.gateway /
  *.gateway.mjs is already the middleware's alias, so a hook importing
  node:fs was also loaded as moejs middleware and failed there.
  TestGatewayHookNamesApartFromMiddleware fails if the two sets overlap.
- onRequest is rolled back, and counts as failed with no onResponse, when
  it throws, times out, returns non-JSON, or changes tools, tool_choice,
  function_call, functions, toolConfig, model or stream.
- onResponse gets the client-facing reply, merged through the gateway's own
  stream decoder, collector and renderer (no second merger).
- Codex's native passthrough (/backend-api/codex) runs the hooks too,
  without the sync middleware.
- The run ends with the request handler, not the client connection. Codex
  hangs up on response.completed, and the reply it got is still captured
  as a success. TestGatewayHookSeesReplyAfterClientHangsUp is red on the
  old `r.Context().Err()` check and green with -count=3.
- ctx.origin is host-derived (local / gateway-key / remote). Headers, keys
  and peer addresses never reach the hook.
- Plugins page: a hook package shows a "Request hook" chip, a diagnostics
  line (outcome code, calls, avg ms, bytes, failures; no content), and
  Options. Strings are in en, zh, zh-TW, ja and de.

Docs: docs/subsystems/gateway-request-hooks.md (new), provider-plugins.md,
gateway-middleware.md, and site docs plugins.html in en, zh and ja.

Real use, sandbox HOME on 127.0.0.1:3486 with the owner's real Codex Pro
sign-in. The probe hook adds a codename note and logs both callbacks:
- /v1/responses, /v1/messages, Gemini generateContent: stream and
  non-stream. onRequest's note reached the model (the answer had the
  codename), and onResponse got success=true and the whole reply.
- /v1/chat/completions: with the probe also changing `model`, the change
  was rolled back (the reply came from the asked model) and no onResponse
  ran. Without that change, earlier: stream and non-stream success.
- The real Codex CLI 0.162.1 `codex exec` through openai_base_url ->
  /backend-api/codex: the hook saw origin=local, agent=codex and the
  query; the answer had the codename; onResponse success=true (before the
  hang-up fix it never ran: the context was already cancelled).
- `magpie plugin list` shows only "async gateway hook onRequest" for the
  hook package, no failed middleware.

Tests (base origin/main 63be47717, macbook at load avg 220-340 from other
sessions' suites):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. go build and GOOS=linux -tags nogui
  build: ok.
- go test ./... -timeout 45m: every package ok except:
  - agent, gateway and library timed out at 45m under the load;
  - gui's TestSetAnswersWhileDevinAndProvidersHang (#1375, also red on a
    clean 63be47717 run alone; commented there);
  - library's TestSkillRelinkKeepsUnreadableCopy, which passes -count=2 alone.
  Rerun at -timeout 150m: agent ok (4524s), library ok (2581s). gateway was
  ok except TestVisionWaitIsntTheDescribersTime's 300ms limit (#2444,
  commented), which passes -count=5 alone on this tree and on 63be47717.
- internal/plugin and internal/gateway hook tests: ok.
- GUI (chromium+webkit; en, zh, zh-TW, ja, de): plugin-gateway 12/12 twice.
  It failed earlier at load ~340, chromium only, on page.goto's 5s (#2542).
  All 43 plugin-*.test.cjs files and mobile-web are green except:
  - plugin-move: red on a clean 63be47717 too (#2399, commented);
  - plugin-moved-signin: one 5s waitFor under load, then 6/6 twice.

Rebased onto ea3dee96a (21 commits; main touched host.go, host.js, i18n.js and
the plugin docs; clean rebase), then rerun at the rebased head:
- gofmt, vet (darwin, linux nogui, windows) and build: clean.
- go test: plugin ok, cli ok, gateway -run 'Hook|Middleware|Codex|Plugin' ok.
  gui ok except TestMainWindowCorners, which was killed under load (#1936)
  and passes alone.
- GUI: plugin-gateway 12/12, plugin-middleware 24/24, plugin-tools 22/22,
  plugin-agent 22/22.
- Real account with the rebased binary: every protocol and the real Codex
  CLI gave the same results as above (codename answered, success=true,
  chat's model change rolled back).

Co-authored-by: Tsukikage7 <65526564+Tsukikage7@users.noreply.github.com>
2026-10-16 20:48:51 +08:00
yetone f54e76dbdd gateway: a request builds the providers once, and plugin-auth.json and the discovery setting are parsed once a version (#2502)
XcodeFish (#2502): with several agents at once the gateway sat at
100-350% CPU. Counting provider.AllBuilt around one streamed chat
request gave 3 full catalogue builds per request, and each build re-read
and re-parsed plugin-auth.json and settings.json (AccountDiscoveryOff
called Load() on every provider list).

- holdCatalog wraps the gateway's handler in provider.Hold() and
  filememo.Hold(), so one request builds the providers once and stats
  each file at most once a second. Hold already drops the cache on
  provider.Changed and on magpie's own writes; another program's write
  is seen within the second.
- plugin-auth.json is read through filememo (mtime, size, and the raw
  bytes while the file is under 2s old), so it is parsed once per
  version. A file that doesn't parse falls back to the last good .bak
  through lastgood, as settings does. Auths still hands each caller its
  own decoded map. The host looks at the file again before it reports a
  sign-in it just saved.
- AccountDiscoveryOff reads the setting through filememo with the same
  parse settings.Load uses (now settings.parse), under fileMu.

What was run:
- TestRequestBuildsProvidersOnce: two streamed requests, one build each
  (3 each before). Red with holdCatalog taken out.
- TestAuthParsedOncePerVersion: 100 rounds of Auths, SignedIn and the
  listing proxies parse plugin-auth.json zero more times; a caller's
  edit doesn't leak; a same-size rewrite is read; a zeroed file reads
  the .bak and stays signed in. Red with authRaw reading past filememo.
- TestAccountDiscoveryOffParsedOnce: 100 calls, no parse; a Save is
  read. Red with AccountDiscoveryOff back on Load().
- gofmt -l clean; go vet -tags nogui on darwin, linux and windows ok.
- Full suite, set -o pipefail; go test -p 4 -timeout 45m ./... at this
  pair rebased on 63be47717, machine load average 170-330 from other
  work: 63 packages ok; internal/agent and internal/gateway ran out of
  45m (#2544, #2191, #2108); internal/gui TestMainWindowCorners killed
  at its 40s deadline (#1936). Run alone afterwards, gateway and agent
  ran out of 45m again, and gateway's
  TestQuietCodexStreamKeptAliveThroughReplyWriters/a_middleware got its
  reply unchanged once, the middleware failing open on its time limit
  (filed #2565; 6/6 alone on 63be47717 and here).
- The same two packages on 63be47717 alone, side by side with this
  head under the same load: both ran out of 45m there too, in other
  tests, so the timeouts are not this change.

Not tried: a benchmark against a real many-agent load, or the
reporter's machine. The count of builds per request is the measure.
2026-10-16 20:05:11 +08:00