Commit Graph
302 Commits
Author SHA1 Message Date
yetone 04776ec6cb providers: a plugin subscription imports accounts from a file through its own auth.import, WorkBuddy's from 0.2.32 (marchen_cc on X)
marchen_cc on X: 「从文件导入账号」 took no WorkBuddy sign-in file. The cause
was not WorkBuddy's: magpie's import reached only built-ins (Codex,
Claude, Antigravity, Factory), and a plugin had no way to say it could
read a file. This adds that for every plugin subscription:

- A plugin's auth may have import(texts, {signal}), returning sign-in
  results, with importFrom (and importFroms by language) saying which
  file to choose. The host's importFiles op keeps each one as a sign-in
  is kept (keptAs, saved under signInKey, settled), so an account
  already there comes back "updated"; it is cancellable (signInSteps)
  and takes at most 100.
- /api/signin/import and `magpie accounts import <plugin> <files>` go
  to provider.ImportPluginFiles when PluginImportable(id); the editor's
  「从文件导入账号…」 row and the import sheet show for such a plugin, in
  its own words (importSay), moved subscriptions included (subOf).
- docs/subsystems/provider-plugins.md: "Accounts from a file".
- WorkBuddy's mover min goes to 0.2.32, which reads the desktop app's
  .info sign-in or a JSON credential, and sends a cloud-hosted
  enterprise account (*.sso.copilot.tencent.com, *.copilot.qq.com,
  *.sso.codebuddy.cn, iOA apart) to its enterprise's address (emilochen
  on X), published and checked with npm view --prefer-online.
- TestCoreScriptBudget +468 for the import branch, packed to one
  statement. importSay is read as the Providers rows draw, so it has
  no lazy page; nothing else was moved out (#2710). The budget's
  arithmetic was checked over this tree: 1,267,762, at the new cap.

Run on mote (mica's disk is full; mote over its cores) at this change
on 3f6b1b0c9; ac1702c33 (the library plugin and its GUI test, no core
script) landed after, and the core budget's arithmetic was redone at
this head:
gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
internal/{gui,plugin,provider,cli}; go test -count=1 of those four:
all ok. GUI (chromium + webkit, en and zh): plugin-import,
login-import, factory-key, plugin-moved-signin, i18n-keys: 23 pass, 1 fail: i18n-keys "a plugin's words are its own",
memory_mcp.go's "No folder", red on main since 72facf72e (#6422).
Plugins repo: workbuddy import.test.mjs 6 of 6, bun scripts/check.mjs
ok, root bun test 8534 pass / 1 fail (agy-cli smoke under load, green on a rerun: 8535 pass, 0 fail;
unrelated, plugins #1070).

Broken by hand: without the host's importFiles handler,
TestPluginImportFiles goes red; without importable in pluginSubs,
plugin-import.test.cjs goes red ("WorkBuddy lists no import").

Not tried: a real WorkBuddy desktop .info file or a real enterprise
account on a cloud-hosted domain; the fixtures follow WorkBuddy's own
client source. Not tried on Windows or Linux beyond vet.
2026-11-13 13:32:32 +08:00
yetoneandvincent 363adb3528 plugin: the auth-lock test checks the loop ran while the lock was held, not how often a timer ticked (#5271)
TestAuthLockWaitDoesNotFreezeTheHost counted a 20ms setInterval over a
300ms sleep and wanted 8 ticks. A loaded runner fires the timer late and
counts fewer while the loop is free all the same: 7 of 8 on mote (#5271),
6 on ubuntu CI at f28787b39 (run 43328831902). It measured the scheduler,
not the freeze it is named for.

Ported from skygunner's fork commit 94d8550c8 (on #5271): a setImmediate
registered before changeAuth checks, from the event loop itself, that the
other host's lock is still there and the change not yet written, then lets
the lock go; the test awaits that and the change. A host that waits with
Atomics.wait (#5112) never reaches the check while the lock is held. The
300/600ms sleeps, the tick count and the 5s bound go; the 20 concurrent
changes and the stale-lock takeover are kept as they were.

Run at this tree (origin/main 1e2ce2463 plus this):
- Linux (wsl-run): go vet ./internal/plugin; -count=20 -run of the test: ok.
- macOS (mote-run): the same, ok.
- gofmt -l: nothing.

Broken by hand on Linux: host.js's sleep made a blocking Atomics.wait. The
test went red at 10.1s, "the event loop ran while the other host still
held the lock"; host.js put back.

Not run: the full suite, and Windows.

Co-authored-by: vincent <webmaster@palmit.com.au>
2026-11-13 08:52:12 +08:00
yetone 47b51c8225 plugin: an OAuth sign-in with no refresh token is kept, and one with nothing to keep fails (plugins#998)
host.js keeps an OAuth sign-in only when "refresh" is in the plugin's
result, as OpenCode's CLI does. codearts' "Sign in from CodeArts Agent"
returned an access with no refresh field, so the callback said ok and
nothing was stored: the CLI printed "signed in" and no account showed.
callback now keeps an access with no refresh as an OAuth sign-in with an
empty refresh, and a success with nothing to keep (no refresh, key or
access) fails with "<provider>'s sign-in gave nothing to keep", as
apiKey's "gave no key" already did. The plugin side is fixed too
(codearts 0.3.14, plugins 4e3a7868); this covers any other plugin that
leaves the field out.

TestSignInWithNoRefreshIsKept drives both through the signinend fixture
(methods 8 and 9) and checks the kept record is oauth with refresh "".

Ran on mica: go test -count=1 ./internal/plugin/ ./internal/provider/ ok;
GOOS=windows and GOOS=linux go vet ./internal/plugin/ ok; gofmt -l clean.
Broken by hand: with host.js at its parent, the new test fails on both
cases (nil error, nothing kept).
Not tried: the full suite at this head (one is running on mica for
805e5c29a), a real CodeArts Agent sign-in.

Reported-by: AyakaChen1 <AyakaChen1@users.noreply.github.com>
2026-11-12 11:14:56 +08:00
yetone dd884058e7 plugins: a Discover plugin's README comes from the copy usemagpie.ai keeps, before npm or GitHub (River_WLan on X)
npm's human check answers 200 with a page that isn't the package's entry, so the
README showed "npm didn't answer: unexpected end of JSON input". The community
repo's tagged workflow now keeps each listed plugin's README at readmes/<key>.md
on dist (plugins repo, pushed), usemagpie.ai serves it at /api/plugins/readme
(edge 10 min, jsDelivr stands in for raw), and ReadmeIn asks it (5s an address,
MAGPIE_PLUGIN_CATALOG=off skips) before npm / GitHub; an installed plugin's folder
still comes first. A page that isn't npm's entry now says npm may be asking for
a human check. Only the plain README.md is kept: a language README is read from
npm/GitHub only when the copy is missing.

Run: go test ./internal/plugin ok (wsl); site/worker.test.mjs 40 pass (wsl).
Red on old code: TestReadmeFromTheKeptCopyBeforeNPM fails with "unexpected end of
JSON input" and npm asked 2 times; worker test red with the route removed.
tagged.mjs run on wsl against real GitHub: 369 plugins, 369 READMEs, a second run
re-read none. Not tried: the Actions run itself, the GUI (no GUI file changed).
2026-11-11 16:24:37 +08:00
yetone 14be7f69df plugins: Discover's list comes from a file CI builds, not GitHub from each desktop (River_WLan on X)
Plugins -> Discover read GitHub's topic search plus a package.json, an npm
answer and an entry file for ~400 repositories on every desktop. Where GitHub
is unreachable or rate-limited the page said "Couldn't ask GitHub".

Now the community repo's `tagged` workflow (plugins repo, scripts/tagged.mjs,
every half hour) builds tagged.json on its dist branch, usemagpie.ai serves
it at /api/plugins/tagged (worker, edge-cached 10 min, jsDelivr and the last
whole copy as fallbacks), and magpie asks: usemagpie.ai, the dist branch
(jsDelivr with the China-mirror switch), then GitHub as before. parseCatalog
keeps only entries whose spec is github:<repo> or the package named from it,
and drops a file older than 48h. Degrades: a tagged repo shows within the
hour, not ten minutes; stars/https icons are as of the last build; owner
avatars and https icon URLs still come from GitHub hosts (data: icons work).

Run (wsl-run, mote's disk is full): go vet + go test ./internal/plugin,
node --test site/worker.test.mjs (21 pass), scripts/tagged.mjs against the
real GitHub (367 plugins, 253 with icons, 0 unread; workflow run green and
tagged.json on dist), usemagpie.ai/api/plugins/tagged after wrangler deploy
(200, 4.8MB). Broken by hand: skipping askCatalog turns
TestTaggedReposFromTheBuiltList red. Not tried: a real desktop with GitHub
blocked; GUI suites (no GUI file changed); Windows/darwin vet.
2026-11-11 15:07:54 +08:00
yetone 58fb070953 settings: named proxies, chosen as inherit, direct or a saved one anywhere a proxy is (@tsingchao on X)
Settings > Network keeps named proxies (name, address, optional login)
with a Test that says reachable and the latency. Everywhere a proxy can be
chosen (global, plugin downloads, a provider, a key, a Claude account) now
has a Saved mode beside the others; the value is "@<id>". Addresses typed
before are read exactly as before, nothing is migrated or overridden.
netproxy.Parse/Resolve/Redact/EnvWith/Dispatch resolve a reference at the
lowest layer, so a proxy edited once reaches the gateway, usage reads,
sign-ins and the plugin host at the next request; Claude Code's
settings.json env (a snapshot) is rewritten by provider.ProxyEdited.
A reference this computer lacks fails closed (DeadProxy), says the proxy's
name in the request error and as "Proxy missing: {name}" on the provider
row, and never goes direct. The password lives in settings.json (0600), is
never read back by the page, logged, or put in Settings sync. The list
rides with the providers part of a sync (Bundle.Proxies, MergeProxies by
id, passwords only with keys). A proxy in use can't be deleted (409).
The saved list's page code is in proxies.js, loaded when Settings draws it;
app.js grew by Saved-mode helpers only, paid for by 16 long comments cut
(core budget unchanged, no raise).

Run (mote refused ssh all session, so Go and GUI went through win-run on
xiaomi-gpu, Windows 11; gofmt and darwin/linux-nogui/windows go vet were
clean on mote before it went down, at the pre-sync tree):
- go test settings, netproxy, backup, settingsapi, davsync: ok on Windows
  (earlier on mote: also gui, provider, plugin with real Bun, gateway).
- saved-proxies.test.cjs 20 of 20 (chromium+webkit, en zh zh-TW ja de,
  420px) twice more on Windows; provider-proxy-missing.test.cjs 20 of 20.
  One webkit de 420px run of saved-proxies failed once under 4-way
  concurrency and passed 3 of 3 alone; not reproduced.
- TestCoreScriptBudget ok after the move (it was 3.4KB over before).
Red on this tree and on origin/main alike (Windows run, not mine):
settings TestSharedCheckedReadsOnceAndKnowsUnknown; provider
Codex keychain/Git tests; plugin TestHostRunsAsMagpieBun, TestPiPackage;
gui TestGatewayHeldByAContainer and others; old-webkit "compat.js is the
first" (headerpresets.js) and ":has() (Safari 15.4)" on origin/main 245f07b19.
Broken by hand: restore skipping Proxies (TestSavedProxiesTravelWithProviders
red), Parse returning nil for a dangling ref (netproxy tests red), the
Proxy-missing badge disabled (provider-proxy-missing 0 of 20), and the Claude
env snapshot failing open (found by reading, test added).
Not tried: real vendors, the real Claude Code, a real two-computer sync, the
macOS suite and the whole GUI suite on this final tree (mote down; the whole
suite ran to test ~3700 on the earlier tree with reds owned by others).
A proxy missing whose sender never had it is named by its id.
2026-11-11 12:26:43 +08:00
yetone a982f34130 plugins: async gateway hooks get the request's kind, subagent or not (ahwulv on X, #4655)
GatewayContext had no subagent marker, so OpenViking could not skip memory
recall for Claude Code's subagents. It now carries kind: "subagent" when the
client says so on that request, "" otherwise (main conversation, or a client
that doesn't say). hookKind (internal/gateway/middleware.go) reuses the
gateway's own readings: Claude Code's x-claude-code-agent-id (subOf), and
Codex's x-openai-subagent collab_spawn (callKind + usage.PurposeOf, so a
Codex review or compaction is not a subagent). Headers from #4655's real
Claude Code 2.1.312 capture. It is read per request, so onRequest and that
request's onResponse see the same value and the main turn after a subagent
in the same session is "". Never guessed from the prompt or Agent tool
history. Documented in docs/subsystems/gateway-request-hooks.md.

Before/after: a hook's ctx had no kind; ctx.kind is now "subagent" for such
requests (the OV plugin already reads ctx.kind === "subagent").

Run: TestHookKindFromClientHeaders (claude subagent, claude main in the same
session, codex collab_spawn, codex review, none) and
TestAsyncGatewayHookKindReachesPlugin (real gateway + Bun: main, subagent,
main again; onRequest and onResponse) on mote at the commit before the final
rebase and on a WSL box; with Kind dropped from the context the e2e test
goes red (saw "" want "subagent"). go vet darwin green. Not tried: the real
OpenViking plugin; Claude Code itself against this build; linux/windows vet
was still queued on mote when this was pushed.
2026-11-11 11:50:13 +08:00
yetone 4df5256db8 plugins: a plugin's page shows its README in the UI's language (ahwulv on X)
A plugin that ships README.zh-CN.md still showed README.md on its details
page with magpie in Chinese. GET /api/plugins/page now takes ?lang= (the
page's document language) and plugin.ReadmeIn picks the README named for it:
README.zh-CN.md, README_zh.md, README-zh.md, README.zh-Hans.md, README.CN.md
and the like, any case (readmeTag/pickReadme). Order: the language's own tag,
then its base (zh-TW takes a simplified README over English), then the plain
README.md as before.

Where it reads from: an installed plugin's folder; an npm package not
installed from its files through jsDelivr's file list (the registry entry
holds README.md only), public registry only, never a user's private one;
a GitHub repository not installed from its contents list. Any failure keeps
the old README.md path. The page cache in plugins.js is keyed by package and
language. A package only on the community dist branch still shows the
README its index carries (English).

Before/after: zh UI + a package with README.zh-CN.md showed README.md; now
shows the Chinese one. en UI, no such file, or jsDelivr down: unchanged.

Run: TestPickReadmeByLanguage, TestReadmeInUILanguage (fake npm, jsDelivr,
GitHub, installed folder) on mote at the commit before the final rebase and
on a WSL box; broken by hand (lang forced to "" in ReadmeIn) the test goes
red. GUI plugin-readme-lang (new, chromium + webkit, en and zh) green, red
when &lang= is dropped from the request; plugin-detail-escape green. go vet
darwin green. Not tried: a real npm package with a localized README against
the live jsDelivr; the other plugin GUI files and linux/windows vet were
still queued on mote when this was pushed.
2026-11-11 11:50:13 +08:00
yetone 5068e46fb6 provider: raise ZCode's plugin min to 0.1.58; a coding plan's 1310 leaves the trials (plugins#438)
takomitkm (plugins#438) hit two problems. The busy hold armed with one
account and one agent. A GLM Coding Plan model's weekly or monthly limit
(1310) also rested the whole account, so its -Trial models got the
cached 1310 without being asked. zcode 0.1.58 (ea3573bf in the plugins
repo, on npm) fixes the first in the plugin and lists the -Trial entries
free. magpie's PaidBesideFree then rests only the refused coding-plan
model. Raising the min brings every moved user up to 0.1.58.

TestZCodeCodingPlanLimitLeavesTrials holds both sides. With the trials
free, the 1310 rests GLM-5.3 alone and GLM-5.3-Trial is still sent. With
no free entries, or with another vendor, the same refusal still rests
the account. The fake plugin's $FAKE_ZCODE_FREE marks the trials free,
as 0.1.58 does.

Run (mote): go test ./internal/gateway -run 'TestZCode' -count=1, ok;
go test ./internal/provider ./internal/plugin -count=1, ok; go vet of
the three packages on mote, in WSL (magpie-desktop) and on Windows
(xiaomi-gpu), ok; gofmt -l is clean. All of this at this head, rebased
on origin/main. A whole-tree Linux vet in WSL stops at Wails' cgo
(webkitgtk-6.0 and gtk4 aren't installed there), so it doesn't cover
the GUI.

Broken by hand: with the fake's free mark dropped, the zcode 0.1.58
subtest fails, because the 1310 rests the account key.

Not tried: a real dual ZCode account that has reached its weekly limit.

Reported-by: takomitkm
2026-11-11 04:42:15 +08:00
yetone 13a9f1263a plugins: Discover counts who uses and likes each plugin
Discover showed npm's weekly downloads, which CI, mirrors and magpie's
own keepMovedCurrent updates inflate. Now each card and the hero say
how many people use a plugin, counted by magpie itself, and a plugin's
page has a like.

- The daily stats send (stats.Send) also POSTs usemagpie.ai
  /api/plugins/report with the install id and the installed, switched-on
  plugins Discover lists, by their Discover key: the npm name, or
  github:owner/repo for a repository tagged magpie-plugin
  (plugin.Public). A folder, a private repository or an unlisted
  package is never named. It goes only while "Share the agents,
  providers, models and plugins I use" is on (noUsageStats), and only
  where the day's event goes at all (Count me as a user, DO_NOT_TRACK,
  MAGPIE_NO_STATS, release builds).
- site/pluginstats.js on D1 magpie-plugins: users are the ids that
  reported a plugin in the last 7 days, reports drop after 30 days, a
  caller's address is kept only as a hash for an hour (60 asks an
  hour). /api/plugins/stats carries no id and is cached for an hour.
- A like (POST /api/plugins/like through the GUI's /api/plugins/like)
  is taken only for a plugin installed and on here, can be taken back,
  and is kept in plugin-likes.json.
- "Most liked" sorts by likes once a plugin has 20, below that by
  GitHub's stars.
- plugincounts.js is loaded with the Plugins page, not the core, and
  redraws the cards only when the counts changed.
- The privacy text follows: README.md, README.zh-CN.md, docs/reference.md,
  the site's privacy and start pages in en, zh and ja, llms-full.txt,
  and the Privacy switch's label and description in every language.

Run at this tree (on origin/main 51da6f1f5):
- Windows box (win-run): gofmt -l clean; go vet of internal/stats,
  internal/plugin, internal/gui ok for windows and linux (-tags nogui);
  node --test site/pluginstats.test.mjs site/worker.test.mjs 44 of 44;
  TestCoreScriptBudget, TestPluginCountsAndLikes ok; GUI old-webkit,
  i18n-keys, privacy-usage-stats, plugin-git, plugin-local,
  plugin-github in both engines: 45 of 46, the one red is #5919
  (.side-foot:has, d374168d0).
- mote, one commit before the rebase onto 51da6f1f5 (Go unchanged
  since): go vet darwin ok; TestSendPlugins, TestPublicPlugins,
  TestPluginCountsAndLikes, TestCoreScriptBudget ok.
- Windows, at 7bc7af1d0 (one rebase earlier): go test internal/stats
  ok; internal/plugin and internal/gui red only in TestPiPackage and
  eight gui tests that fail the same at origin/main 72f2deebe on that
  box (#4115, #5928; TestCherryStudioImportRow added to #4115 with its
  cause). Every plugin*, market*, privacy*, i18n*, old-webkit* and
  discover* GUI file (83 files, both engines, concurrency 4): the reds
  left after the fix below match origin/main 6d7862769 on the same box,
  or are flakes red there too under concurrency: plugin-update-button
  (#4500), plugin-proxy-page (#6017, new), privacy-agent-telemetry
  (#6018, new).
- Broken by hand, caught: the first run had `const like = !local && …`,
  so a local plugin's page called false?.sync() every 600ms; 136
  "like?.sync is not a function" errors across plugin-git, plugin-local,
  plugin-github and the sign-in files. Fixed before this commit.
- Live: D1 magpie-plugins created and the worker deployed;
  /api/plugins/stats answers {"plugins":{}}, a bad report or like 400,
  /api/latest and / 200. No test data was written to production.

Not tried: the full Go suite and the full GUI suite. mote had 28 suites
waiting for its lock, and WSL on the Windows box failed with
E_UNEXPECTED while another session uninstalled a distro. Not tried
either: a real like or report from a release build (source builds
never send), so the first real counts come with this release.
2026-11-11 04:28:18 +08:00
yetone 0659dc66fa plugin: the default-budget hook test starts the host before it measures
TestGatewayHookDefaultBudgetStillCuts/10000 was red on macOS CI at
c2c2c82ca (run 42819148533): the hook was cut at 9.3s as "cancelled",
not by its own 10s timer as "timeout". The RPC's 11s (gatewayWait)
counts the host's start too, so a start past a second on a busy machine
lets the RPC's deadline land first. Same class as e39ecfec8's chain test.

Now the fixture's first request returns at once and only starts the
host; the second one is measured, with the host's start out of its
margin. The product is unchanged.

Ran on WSL magpie-desktop, go test -tags nogui ./internal/plugin
-run TestGatewayHook: ok.
Broken by hand:
- a 2.5s top-level wait in the fixture (a slow host start): the old test
  fails ("wasn't cut by its own budget"), the new one passes;
- the 10000 case given 20000: the new test fails ("a hook past its
  default budget was kept").
Not tried: macOS CI itself, until this push's run.
2026-11-10 22:37:28 +08:00
yetone 016763f237 plugins: host.js passes a usage window's pool and family on, so Antigravity's card shows its pools (plugins#935)
mk311 (plugins#935): the Antigravity plugin's Usage card listed every
model's own window (13 rows, each Gemini one at 85.1%, Claude and
GPT-OSS at 100%), then a bare "7 days" and "5 hours" twice. The plugin
(0.1.0) already groups them as the built-in did: each model's window
carries its family and its pool ("Gemini", "Claude & GPT"), each pool's
own 5 hours and 7 days carry the pool. f92c0a2bd taught
plugin.UsageWindow and quotaOfPlugin to read the two fields, but
host.js's usageOf builds each window from a fixed list of fields and
left them out, so nothing reached Go: its test hands quotaOfPlugin a
plugin.Usage directly, past the host. Now host.js passes family and
pool on, and the card, menu bar rings, TUI page (PooledWindows), quota
alerts, caps and routing's pool holds treat the plugin's pools as the
built-in's. Only the antigravity plugin sends these fields (grep of the
plugins repo). The plugin docs (en, zh, ja, llms-full.txt) name them.

TestPluginAntigravityPoolsReachTheCard goes through the real plugin host
(bun, the fake plugin's FAKE_WINDOWS) with the windows the antigravity
plugin's own usage() returns for the reporter's literal figures (each
Gemini model 85.1% left resetting 20:31 +08, Claude and GPT-OSS 100%
resetting 11-11 00:24:47 +08, Gemini 7 days 91.8% left; the Claude & GPT
week isn't in the screenshots and is set to 100% left), kept in
testdata/antigravity-plugin-usage-935.json. The card's lines are then
Gemini · 7 days, Gemini · 5 hours, Claude & GPT · 7 days, Claude & GPT ·
5 hours.

A cap a user set on the plugin's bare "7 days" (two pools under one
name) is now keyed "Gemini · 7 days", as the built-in's was.

Run (mote refused SSH, kex reset; wsl-run in magpie-desktop at this
commit on 6886da1ca):
- gofmt -l: clean; go vet linux, windows, darwin: ok
- go test ./internal/provider, targeted -run with the new test: ok
- go test ./internal/plugin: ok (219s)
- site worker.test.mjs: 38 pass, 0 fail
- GUI quota-pools, quota-pool-model, quota-pool-order, window-cap-pool
  (chromium + webkit, every language): 52/52, also 52/52 at 9c39edb92
  and 4a9142ccd. A first run at 9c39edb92 had one red in window-cap-pool
  (chromium 420 de, each pool's caps); it passed 40/40 alone and on every
  rerun, filed as #5949.
- The antigravity plugin's own usage() (plugins repo, unchanged) run on
  the reporter's figures produced the testdata file.

Broken by hand: host.js with pool dropped: the new test is red with the
reporter's card (13 model rows, then "7 days", "5 hours" twice, no pool).

Not tried: a real Antigravity account through the plugin in the GUI;
macOS and Windows runs (mote down).
2026-11-10 20:32:38 +08:00
yetone f92c0a2bdd plugins: a plugin is told the effort asked, and its usage windows keep their pool and family
What a ported Antigravity needs from the host, kept generic:

- The gateway puts the request's reasoning effort on a plugin's fetch as
  X-Magpie-Effort (provider.EffortHeader), so a plugin that serves one
  model at several levels can pick the level. host.js strips it with the
  other magpie-only headers, so the vendor never sees it.
- A plugin's usage window may name a Pool and a Family; quotaOfPlugin
  passes them through, so PooledWindows names a shared pool
  ("Gemini · 7 days") as it does for the built-in.

Run (WSL magpie-desktop; mote unreachable, kex reset):
- TestPluginToldTheEffort: xhigh, low and none reach the plugin; the
  vendor gets no X-Magpie-Effort. Red with the MAGPIE_ONLY entry removed
  by hand (the vendor saw the header).
- TestPluginWindowsKeepPoolAndFamily, TestPluginToldTheSession: pass.
- Full suite: in the next commit's body (run at the head of both).
2026-11-10 20:16:44 +08:00
yetone e115b96411 plugin: an api sign-in whose prompts ask the key asks no second key
An OpenCode plugin's "api" auth method with its own prompts and an
authorize (inkstone's API key ways, Devin's session token in
magpie-community/plugins#928) asks the key in its prompts and returns it
from authorize(inputs). The GUI asked those prompts and then always showed
a key field of its own, so the user typed the same token twice and the
second entry went nowhere. The host's save() also copied every answer into
the account's metadata, so the token sat there a second time in plain
text.

- host.js marks such a method keyAsked (type api, prompts, authorize).
  The GUI's startPluginSignIn signs in with no key field for it, as for
  keyless, and a rejected answer asks the prompts again on Try again.
  PluginAPIKey and `magpie plugin` login skip the empty-key check for it
  (Method.NoKey).
- save() keeps only select answers (choices, never secrets) beside the
  authorize result's own metadata. A method with no authorize still keeps
  every answer, as OpenCode does.
- An authorize that gives no key, with no key typed, is now an error
  instead of an "ok" that saved nothing.

OpenCode itself differs: its v1 CLI (providers.ts) asks the prompts, then
always asks "Enter your API key", saves result.key ?? the typed key, and
merges the answers into metadata; its TUI never calls authorize for api
methods. magpie-community plugins are written for magpie's flow and read
the key from inputs, so this follows them.

Plugins that read prompt answers back from metadata (grep of
magpie-community/plugins packages): zcode (site, a select), joycode
(tenant) and agnes (keyProfile, consoleToken). None has an authorize, so
none changes. Every api+authorize plugin (inkstone, cloudflare-workers-ai,
sensenova, agnes-code, astudio, sap-aicore, Devin #928) puts what it needs
in its result's metadata itself; sensenova's apiKey: undefined
workaround is now moot.

Run on mote (macOS 27, Go 1.26.8, Playwright 1.62.0) at this change on
origin/main 9c39edb92: gofmt -l clean; go vet of internal/plugin/...
internal/gui/... internal/provider internal/cli, also GOOS=windows and
GOOS=linux -tags nogui: ok. go test ./internal/plugin/...
./internal/gui/... ./internal/provider: ok. ./internal/cli: ok but
TestEveryRouteHasACommandOrIsNamed, red the same alone on 9c39edb92
(POST /api/gateway/pause from e8fbee60e has no command), filed as #5946.
node --test, chromium and webkit, of plugin-api-prompt-key (new),
plugin-keyless-signin, plugin-password-prompt, plugin-signin,
plugin-ask-ways, plugin-key-hint, plugin-other-ways, signin-paste-key,
plugin-signin-opened, plugin-signin-scrolls, plugin-pick-sub,
plugin-two-subs, zcode-site-layout and i18n-keys: 176 of 176 ok. The new
GUI test passed 3 of 3 alone. plugin-signin-no-url is red 22 of 22 at
the base too (987eac0aa); that is #5938, commented with the macOS run.

Broken by hand: GUI back to keyless-only and host without keyAsked ->
TestAPIPromptsKeyAskedAndMetadata and plugin-api-prompt-key 22 of 22 red;
save() copying every answer again -> the Go test red (token kept twice,
the note answer kept).

Not tried: a real plugin sign-in (inkstone, Devin), the CLI path (no
test), a run on the Windows or Linux boxes, the full ./... suite.
2026-11-10 19:53:54 +08:00
yetone 4011873001 catalog: models.dev unreachable falls back to the last copy or a shipped one, retried in minutes (creeksuen on X)
Where models.dev can't be reached (a network in China), the catalog that
gives prices, context windows, reasoning levels and names degraded:

- first run: no catalog file, so every model unpriced, no windows, and a
  plugin's provider listed no models, until a fetch got through;
- a failed fetch: KeepFresh tried again only after an hour, and the app's
  backend waited up to 30s on models.dev before it asked the vendors for
  their lists;
- Sync wrote models.json in place (os.WriteFile), so a reader could catch
  it half written, and a parse failure left no catalog at all.

Now:

- Sync writes the catalog through a temp file renamed over it
  (writeWhole, shared with labs.json). A refused, hanging or wrong answer
  (HTML, cut-off JSON) keeps the last good copy byte for byte.
- The binary ships models.dev's api.json of 2026-11-10
  (internal/catalog/bundled/api.json.gz, 608KB; go:generate refreshes it).
  loadGen reads magpie's copy, then OpenCode's, then the shipped one,
  passing over one it can't parse. Seed (app backend, magpie serve, the
  plugin host) writes the shipped copy into the cache when there is none
  or it is older, dated bundledAt, so the plugin host reads it and Stale
  still has the real one fetched. A test binary has it off (bundledOn).
- The app's backend no longer waits on models.dev before the vendors'
  lists when a catalog is there; KeepFresh fetches beside them, and a
  failed fetch is tried again after 2 minutes, doubling up to the hour.
- The fetch already goes through http.DefaultClient, which
  netproxy.Install routes through the proxy in Settings, *_PROXY or the
  system proxy; there is no models.dev mirror setting to honour.

Run (mote, at the rebased head unless said):
- gofmt -l: clean. go vet darwin (catalog, plugin, cli, gui), linux -tags
  nogui and windows: ok.
- go test ./internal/catalog: ok at the rebased head; ./internal/plugin,
  ./internal/gui, ./internal/cli: ok at the pre-rebase head but for
  TestEveryRouteHasACommandOrIsNamed, red at that older base (a GUI route
  this change doesn't touch) and ok at the rebased head.
- New tests, each fake models.dev on 127.0.0.1 (cut connection, hang,
  captive-portal HTML, cut-off JSON): TestFailedSyncKeepsLastGood,
  TestFirstRunOfflineAnswersFromShippedCopy,
  TestUnreadableCacheFallsBackToShippedCopy, TestSeed,
  TestSyncWritesThroughRename, TestFailedFetchRetriedSoon.
- Windows (win-run): the catalog tests ok, 15 of 15 with -count=15;
  TestSyncWritesThroughRename skips there (it holds the file open).

Broken by hand, each red: Sync back to os.WriteFile
(TestSyncWritesThroughRename); load without the shipped copy
(TestFirstRunOffline…, TestUnreadableCache…); Seed over a newer catalog
and Seed dated now (TestSeed); first retry after the hour
(TestFailedFetchRetriedSoon).

Not tried: the real app started with models.dev blocked; the full suite
(started after the tag).
2026-11-10 19:26:13 +08:00
yetone e39ecfec8d plugin: the hook-chain test leaves the first hook room for the host's start
TestGatewayHookChainStillTenSeconds gave each of two hooks 8s and had
both sleep 6s. On macOS CI at 286e3b6d5 (run 42784088261) the first one
ran past its 8s with the host's start counted and was dropped:
"the chain's 10s changed: {"note":"original"}". The first now sleeps 4s
(4s to spare), the second 7s: inside its own 8s, past the ~6s the chain
has left, so only the chain's 10s cuts it.

Run on magpie-desktop: go test -tags nogui -count=3 -run TestGatewayHook
./internal/plugin ok. Broken by hand (chain budget 20s in host.js and
gateway.go): red, "first":true,"second":true kept.
2026-11-10 17:44:37 +08:00
yetone 86825005e2 plugin: a gateway hook given more than 10s gets up to 30s (#5890)
gatewayTimeoutMs was capped at 10000 and the Go side cut every hook RPC at
11s, so a recall hook (Nowledge Mem) asking for 15s was cut at 1s (any
value over 10000 fell back to the default) and could never finish.

- host.js: gatewayTimeoutMs takes integers 100-30000; a value outside is
  clamped to the nearer bound, a non-integer gets the 1000 default.
  gatewayBudget() is the old chain budget (sum, clamped 2-10s) or the
  longest hook's own timeout, whichever is larger. With no hook over 10s
  nothing changes.
- gateway.go mirrors both (gatewayTimeout, gatewayBudget, cached with the
  HasGateway scan). GatewayBegin's request RPC, Finish's completion RPC
  and GatewaySignIn now wait the budget plus 1s, never less than the old
  11s; host startup and the lock wait stay bounded at 11s. Caller
  cancellation still reaches the hook at once, a failing hook still
  rolls back, and the request-state limits are unchanged.
- Docs: gateway-request-hooks subsystem page, plugins docs (en, zh, ja).
  site/public/llms-full.txt regenerated with `node llms-full.mjs`; it was
  already stale on origin/main (OpenCode 2 keys, billion-context tab,
  data-folder move, vendor presets, group rule), so those docs pages'
  text lands in it too.

Run on mote at this tree (base 03a800ac6; origin/main has one newer
commit touching none of these files):
- gofmt -l internal/plugin internal/gateway: clean
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: rc 0
- go test -tags nogui -count=1 -timeout 45m ./internal/plugin/...
  ./internal/gateway/...: ok plugin 161.6s, ok gateway 897.0s
- site: node --test worker.test.mjs: 38 pass (llms-full red before the
  regeneration)
New tests (internal/plugin/gateway_budget_test.go): a 12s onRequest and
onResponse with gatewayTimeoutMs 15000 both land (24.2s); the default and
10000 are still cut with outcome "timeout"; two 8000ms hooks still share
10s; 130000 is clamped, not dropped; cancelling a 15000ms hook's request
stops its fetch at once (0.07s); the Go mirror matches host.js.

Broken by hand, each red:
- A host.js as on main: SlowRecall red at 1.10s, Clamps red
- B Go RPC kept at 11s: SlowRecall red at 11.04s, Mirror red
- C chain capped at 10s: SlowRecall red at 10.13s
- D default per-hook 30000: DefaultStillCuts/default red
- E caller signal off the begin chain: LongBudgetCallerCancellation red
- F chain budget 30s for every config: ChainStillTenSeconds red

Not tried: a real Nowledge Mem server; the full ./... suite; GUI tests
(no GUI change); a Windows or Linux runtime run (vet only).

Reported-by: aboat0625-cpu
2026-11-10 15:31:01 +08:00
yetone e4197144a8 perf: every package's package-level regexps compile on first use
v0.1.3516 made gateway's and redact's patterns lazy. The other 299
package-level regexp.MustCompile calls, in 148 files across agent,
provider, gui, library, codexcat, sessions, usage, plugin and the rest,
now go through lazyre.New too, so a launch that never reaches them
(`magpie statusline`, run by Claude Code on every message) doesn't
compile them. Fields, maps and params that held them are *lazyre.RE.

Measured on mote (M5 Pro), sandbox HOME, v0.1.3516-equivalent build
(t42) against this one (t43):
- GODEBUG=inittrace=1 sum: 7.39 MB / 69,837 allocs -> 4.62 MB / 46,765
- `magpie statusline`, 3 runs each: instructions retired ~212M -> ~176M,
  peak memory footprint 19.2-19.4 MB -> 16.8-17.0 MB

Run: go vet ./... (darwin) ok; GOOS=windows go vet on each of the 30
changed packages ok; GOOS=linux go vet ok except ., internal/cli and
internal/gui, which stop in wails v3's cgo files when cross-compiled
(the same at main). New TestAllLazyPatternsCompile at the root compiles
all 574 registered patterns (ok), so a bad pattern fails a test rather
than a first use.
Not run before push: the changed packages' own test suites; they run
on mote after it.
2026-11-10 12:54:39 +08:00
yetone 84a6d6a813 usage: Cursor calls made outside magpie are counted on the Usage page (WaiooT on X)
WaiooT asked for Cursor's usage to be counted. The quota card was there
already (the plugin's auth.usage); what was missing was the calls the
account made in Cursor's own editor and cursor-agent, which never pass
magpie's gateway.

The Cursor plugin (0.2.44, magpie-community/plugins f73ba656) gains
auth.calls: it reads Cursor's own usage list,
DashboardService/GetFilteredUsageEvents (the call cursor.com's Usage
page makes), keeps the signed-in user's events (owningUser = GetMe's
userId), and leaves out the conversations it sent itself for magpie.

magpie side:
- host.js: a provider says `calls` when its plugin has auth.calls; a
  `calls` RPC normalises the reply (a call without an rid or time is
  dropped, cost only when a number >= 0).
- plugin.AccountCalls / plugin.OutsideCall.
- usage.ReadOutsideCalls, run by the gateway a minute after the start
  and every 10 minutes: each account's calls since its mark go in as
  reported calls (IngestReported, request id "cursor:<usageEventId>", so
  each is written once across restarts), by agent "cursor", provider
  cursor, with Cursor's own cost. The first reading goes 30 days back,
  but never before the gateway's last call to that provider, which older
  plugin versions couldn't tell apart. A failed reading keeps its mark;
  each later one starts 30 minutes back for events listed late.
  Marks are kept in plugin-calls.json beside usage.jsonl.
- Cursor's mover min 0.2.43 -> 0.2.44 (npm view --prefer-online: 0.2.44).
- docs/subsystems/provider-plugins.md: "Calls an account made outside
  magpie".

Run (mote, at this head):
- go vet for darwin, GOOS=linux -tags nogui and GOOS=windows on
  internal/usage, internal/plugin, internal/gateway, internal/provider: ok.
- gofmt -l: clean.
- go test -count=1 -timeout 45m ./internal/usage ./internal/plugin
  ./internal/provider ./internal/gateway: all ok (usage 36s, plugin 129s, provider 152s,
  gateway 937s), at 96d9b9ccd before the rebase onto origin/main (2
  commits, none touching these files).
- Plugin: the cursor package's whole suite (410 pass) and
  scripts/check.mjs on mote; a real-account auth.calls read returned 43
  calls with models, tokens and cents.

Broken by hand:
- lastThrough's start removed: TestOutsideCallsStartAfterTheGateway red.
- RequestID left empty: TestOutsideCallsCounted red (rows written again
  after a restart).
- host.js's rid/time filter removed: TestPluginOutsideCalls red ("4
  calls, want 2").
- Plugin: owningUser and own-conversation filters removed: calls.test.mjs
  red.

Not tried:
- A full magpie gateway with the plugin installed reading a real
  account end to end (the plugin read was real; the magpie side ran
  against the fake plugin and stand-ins).
- A team account (teamId), and the Cursor editor itself (none installed
  here); the editor's and cursor-agent's calls are one list, both shown
  as the Cursor agent.
- Two computers running magpie on one Cursor account each count the
  other's gateway calls as made outside magpie.
- No GUI change: the rows use the reported-row path the Usage page has.
2026-11-10 12:22:53 +08:00
yetone 4bfac12683 plugins: downloads take a proxy of their own, apart from the vendors' (JonahFu on X)
JonahFu on X: GitHub is unreachable without a proxy, while API requests
may go direct, so plugin downloads' proxy should be set apart from the
one model requests take.

Before: plugin downloads already followed the global proxy (fetches
through http.DefaultClient and netproxy.Func, bun add and git through
netproxy.Env), so nothing ignored it; there was only no way to give
them a different one.

Now Settings › Network has a Plugin downloads row under Proxy: Same as
above (the default, unset: downloads follow the global proxy as
before), Direct, or Custom with its login, remembered as
pluginProxyCustom as Proxy's Custom is. The CLI takes it as
`magpie settings set pluginProxy <url|direct|"">`. It covers the plugins
list and Discover's lists (fetchJSONFrom), a user's own npm registry
(fetchRegistry), Bun's download (getURLFrom), bun add/update/remove and
the git commands of GitHub-installed plugins (dlEnv). The plugin host
(bun run) keeps the global proxy: its requests are the vendors'. Both
fields belong to this computer (KeepOwn) and are left out of
auto-backups, since a proxy URL may hold a password. Settings' Proxy
row and the new one are drawn by one helper (proxyRow); the core's
script budget is met by cutting the proxy rows' comments, no raise.

Run (mote, through mote-run): gofmt -l clean; go vet of the touched
packages (darwin), GOOS=linux -tags nogui ./..., GOOS=windows of the
touched packages; go test -count=1 internal/settings, settingsapi,
backup, netproxy, plugin, gui, cli all ok (gui after the comment cut;
its first run had TestCoreScriptBudget 1,352 bytes over). GUI, chromium
and webkit: settings-plugin-proxy (new, 5 languages x 2 widths),
settings-proxy-remember, settings-proxy-auth, proxy-test,
settings-sections, proxy-login-fields and the i18n files: 102 pass, 0
fail. plugin-proxy-page, proxy-own-wording, account-proxy,
provider-proxy, routing-proxy, provider-many-keys-proxy and
signin-proxy: 104 pass, 2 fail, both signin-proxy's "a subscription
with no proxy offers the global one" at 380px in Chromium, red the same
way on origin/main b596da773 (filed #5866).

Again at this commit, rebased on b596da773: gofmt, the three go vets,
the seven packages' go test (all ok, TestCoreScriptBudget included) and
settings-plugin-proxy, -remember and -auth (50 pass, 0 fail).

Broken by hand: fetchJSONFrom without netproxy.Downloads ->
TestPluginDownloadsTakeTheirOwnProxy red (the list went direct and hit
testenv's offline guard); bunCommand always taking env() -> red (bun
add's HTTPS_PROXY ""); the GUI row saving key "proxy" ->
settings-plugin-proxy 10 of 10 red in chromium.

Not tried: a real install behind a real proxy with GitHub blocked; the
Library's (skills, MCP) downloads and plugin icons (loaded by the
webview through usemagpie.ai) still follow the global proxy; Windows.
2026-11-10 11:44:17 +08:00
yetone 9309e28ced plugins: a plugin's provider in front of a vendor's API is that vendor to the gateway (songlairui on X, #5462, #5464)
A plugin whose provider's `api` is on a vendor's preset host (a Mistral
Vibe plugin's https://api.mistral.ai/v1) got none of what magpie does for
that vendor, since its Host() is the plugin's id. An earlier turn's
thinking went to the plugin's fetch as reasoning_content, and Mistral
turned the whole request away (422 extra_forbidden); the plugin had to
rewrite the body itself.

provider.VendorHost and VendorPreset now resolve a plugin's declared `api`
host to the preset that names it (every Chat, Responses and Anthropic base
of every preset and region; local and remote magpie presets excluded, and
an api on loopback, a private address, .local or .localhost names no
vendor). For every other provider, and a moved subscription, they are
Host() and Preset as before. The gateway's vendor checks read them: 38
p.Host() sites, Mistral's, OpenRouter's, DeepSeek's, Kimi's and
DashScope's preset checks. Host() stays the plugin's id where calls are
kept and shown; requests still go only to the plugin's fetch. Search and
the video plan check are unchanged. No community plugin's api is on a
preset host today (checked at plugins 7b52e3fc), so none changes.

Any plugin gets this with no new field; documented in
docs/subsystems/provider-plugins.md and the plugin docs (en, zh, ja).

Run (mote): go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows;
go test -count=1 -timeout 45m ./internal/provider ./internal/plugin
./internal/gateway: ok (provider 209s, plugin 182s, gateway 1002s). gofmt -l clean.
Broken by hand: pluginVendor resolving nothing (the old behaviour) turns
TestPluginVendor red, and TestPluginInFrontOfMistralIsMistral red on both
halves: the translated Claude Code turn is answered Mistral's 422
extra_forbidden, and the relayed Chat request carries reasoning_content.
Not tried: a real Mistral Vibe key through the reporter's plugin; Windows
and Linux runs of the tests (no OS-specific code).
2026-11-10 10:01:59 +08:00
yetone 16dcfa504a plugin: a models hook that refused a sign-in isn't asked again for it at once (JZGiVvkSOA75376 on X)
Two dead Zed sign-ins were listed ~30 times a minute, each listing
asking Zed for a model token and getting 401 again. A models hook that
throws with signIn "expired" is now held for that sign-in (its access,
refresh or key): the listing falls back as it did, with the same error,
and the hook isn't asked until the same backoff as a failed renewal
(30s doubling to 30 minutes) has passed. Signing in again asks at once.
This is in the host, so it holds for every plugin, not only Zed.

Run: go test -run 'TestRefusedListIsNotAskedAgain|TestFetchBuildsInfoOnce|
TestPluginRenewsSignIns|TestRenewRetryBacksOff' ./internal/plugin on
mote: ok.
Broken by hand: skipping the hold makes TestRefusedListIsNotAskedAgain
red (3 listings asked 3 more times).
2026-11-10 09:38:45 +08:00
yetone 6e2dcc4a10 plugin: a sign-in that won't renew is asked again later and later, not at once (JZGiVvkSOA75376 on X)
Two dead ima accounts (magpie-ima-auth 0.3.0) were renewed ~80 times a
minute: its auth.refresh catches ima's "sign in again", warns and gives
back undefined, and the host took that as "nothing to do" without noting
a failure, so every request, models listing and usage read asked again.

A refresh that gives nothing back while the sign-in is due now counts as
a failed renewal. A failed renewal of the same sign-in waits 30s, then
doubles each time up to 30 minutes, for every plugin; a new sign-in
starts afresh, and one the vendor turned away for good is still never
tried again.

Run: go test -run 'TestPluginRenewsSignIns|TestRenewRetryBacksOff|TestAuthLock'
./internal/plugin on mote: ok.
Broken by hand: dropping the failure note on an empty refresh makes
TestPluginRenewsSignIns red (r-none renewed three times); a flat 30s
retry makes TestRenewRetryBacksOff red.
2026-11-10 09:35:32 +08:00
yetone ab3710de3a hooks: onSignIn tells a request hook of an account to sign in again
shannnnnks on X: with several Codex accounts behind the gateway, one is
now and then signed out, and they want the notify plugin to push it.

The magpie that serves the gateway now looks every 2 minutes (first
after 1) at the same sign-in states the desktop alert reads
(provider.WatchSignIns' checkSignIns, so every provider: Claude, Copilot
and plugin accounts that lapsed, and built-ins whose mark says the
sign-in expired or must be done again, Codex's revoked and refused
refreshes among them; accounts in use only). Each account to sign in
again, and each Claude sign-in ending within days, goes to every hooks
file that exports onSignIn, once until the account works again, kept in
signin-hooks.json beside the desktop alert's own file. The event is
{provider, providerName, account, state: "signed-out"|"ending", endsAt?}:
the account is its display label; no token and no vendor reason text.
It is fire-and-forget in the Bun host (gatewayRequest operation
"signIn"), each hook under its own timeout, one that throws doesn't stop
the next. With no hooks file nothing is looked at or marked. A hooks
file may now export onSignIn alone, without onRequest.

Docs: gateway-request-hooks.md (Sign-in notification),
providers-accounts.md, site plugins.html en/zh/ja.

Run on mote at d939dd699 (on origin/main 835439ebf; then rebased on
3d49ac069, whose three commits touch only GUI assets, GUI tests and site):
- gofmt -l internal: clean. go vet of internal/plugin, gateway and
  provider for darwin, linux and windows: ok.
- go test -count=1 ./internal/plugin ./internal/gateway: ok (123s, 950s).
- ./internal/provider: crashed in TestCodexAppWorkspaceSwitchReadsEachWorkspace
  (concurrent map writes in its fake server, #5800, not this change);
  run again with -skip WorkspaceSwitch: ok (130s).
- Red on the old code: with origin/main's host.js both new tests fail
  (TestGatewaySignInHook: "magpie.hooks exports no onRequest";
  TestRevokedAccountToldToHooksOnce: the hook never heard of it).
- Broken by hand: without the HasGateway gate, the gateway test fails
  with "told with no hook".

Not run: the full ./... suite (queued behind ~10 suites on mote's
suite.lock). Not tried: the real app with a real revoked Codex account;
the GUI suite (no GUI file changed).
2026-11-10 01:44:24 +08:00
yetone 623e797fde plugin pages: read a day's usage and share a picture they drew
A plugin's page can now read one day's usage and share an image it
drew. This is for the day card (JungleyYeh on X asked for a "daily AI
statement"); the card itself is an optional community plugin,
@magpie-community/page-day-card.

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

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

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

Real use:
- A sandbox HOME with a copy of real usage, through the real GUI
  server, in Chromium and WebKit, light and dark, en/zh/zh-TW/ja/de, at
  420 and 1100 px. The card showed 87.9M tokens, $9.85 and 4076 calls
  with a 22-day streak.
- Picking an earlier day and WebKit's Copy ("Copied") worked, with no
  page errors.
- Not tried at push: Chromium's Copy (its headless clipboard was
  denied) and magpie web's Save as a captured download. A second real
  run that grants both was still queued on mote's suite lock.
- Clipboard: checked live on macOS (osascript) and Windows
  (PowerShell). Not tried live on Linux: WSLg had no display.
2026-11-09 23:19:14 +08:00
yetone ddd6c649b3 draw: a plugin's model that says it gives images alone is an image model
maonekone (Discord #feedback, 11-09): a plugin can't say which of its
models draw; magpie took a plugin's image model only by its name
(DrawsID and ImagesAPI words). Now a model the plugin lists with
modalities.output ["image"] (no text), on its openai-compatible API, is
listed among the drawers and drawn at the images API through the
plugin's fetch, whatever its name. A model that answers in text and
images still chats.

Run (mote): TestPluginDeclaredDrawerDraws red on the old code ("drawers
[]"); with only the listing change, red again (the draw went to chat
completions); green with both. go vet ./internal/gateway ok; go test
-run "Draw|Image|SenseNova|Loomy|Plugin" ./internal/gateway ok (74s).
Not tried: a real plugin declaring such a model; the full suite.

Reported-by: maonekone (Discord #feedback)
2026-11-09 22:39:41 +08:00
yetone 22ffd4db69 plugin: a provider's models come from the plugin that serves it
Two plugins can sign in to one provider id. On the owner's MacBook Air,
tianpeng-dev's opencode-doubao-work-auth 1.1.6 was installed before
@magpie-community/opencode-doubao-work-auth 0.1.2. Both name
doubao-work. The third party's config hook ran first and wrote
cfg.provider["doubao-work"] with models: {}. Ours writes its entry with
??=, so it added nothing. Ours served the id, being the last to name it,
but info() read the shared config.provider entry: the provider showed
the other plugin's name and api and 0 models.

The config hooks still share one config object. Before each hook runs,
every provider it signs in to is set to the user's own entry, or to
this plugin's entry from the last load, never to another plugin's.
What the hook leaves there is kept as that plugin's (ownConfig).
info() reads the serving plugin's entry (providerConfig), so Prefer
moves the name, api and models with the provider.

Run (mote, at c056b7c8c plus this change):
- go test ./internal/plugin/ ./internal/provider/ ./internal/gateway/
  -count=1 -timeout 45m: ok (plugin 136s, provider 159s, gateway 879s)
- GOOS=linux and GOOS=windows go vet ./internal/plugin/: ok
- gofmt -l: clean

Broken by hand:
- With host.js as at c056b7c8c,
  TestServingPluginsConfigIsTheProviders is red with the Air's case:
  served by mine, but named "Theirs", with theirs' api and no models.
- With info() alone back on config.provider[id], it is red after
  Prefer(theirs): theirs serves, but with mine's name and models.

Not tried: the Air itself, before the release reaches it.
2026-11-09 19:16:48 +08:00
yetone 5611e7274e plugin: a plugin's sign-in words show in the window's language when it gives them
mahiro233 on Discord (v0.1.3372, Kiro plugin 0.1.34): in a Chinese
window, the Kiro sheet's "Choose a sign-in method" and its choices read in
English, while the rest of the sheet is Chinese. magpie showed a plugin's
method labels, questions and choices only as the plugin wrote them, and no
plugin had a way to give them in another language.

A plugin may now give them by language, magpie's own fields beside
OpenCode's English, as a page gives its titles: a method's labels, a
question's messages, a select option's labels and hints, each
{"zh": "…", "zh-TW": "…", "ja": "…", "de": "…"}. host.js passes them on
(byLang: string values, codes of 1-16 characters, at most 16, empty ones
left out); plugin.Method and plugin.Prompt carry them; the app shows the
window's language, then its first part, else the English (inLang), on the
way picker, a question, its choices and their hints, a key's field and
the site step's other ways. `magpie plugin login` stays English. Kiro
0.1.35 gives its words in all four (plugins 588b3611).

Tests: TestPluginSignInWordsByLanguage (a plugin's words reach magpie as
given, bad ones left out, none for a plugin that gives none);
TestPluginOwnIconAndKeyHint compares a Method with reflect.DeepEqual now
that it holds a map. The GUI side is checked by plugin-ask-ways.test.cjs
in the next commit.

Run on mote at this tree: gofmt -l empty; go vet ./internal/plugin
./internal/provider ./internal/gui (darwin), linux -tags nogui, windows:
ok; go test -count=1 ./internal/plugin ./internal/provider ./internal/cli:
ok. Broken by hand: with origin/main's host.js the new test fails (no
labels, messages or hints reach magpie). Not tried: a real Kiro sign-in
(no keys or passwords entered anywhere); the full suite is queued on mote
under suite.lock after the push.
2026-11-09 18:29:55 +08:00
yetone a6a99717e0 gateway: thinking with no signature never goes to Claude
citricdu (Discord, 0.1.3356): Claude Code auto-compacted a session on a
Smart group that had moved to Cursor's Grok 4.7, then the group went
back to Kiro's Claude Opus 5.5. The compacted history kept a thinking
block Grok made, which magpie hands a Messages client signed "", and
Kiro answered 13 times in a row with a bare invalid_request_error. The
same request without the block was answered.

withoutForeignThinking dropped only DeepSeek's UUID-signed blocks and
kept an empty signature on purpose ("a block with no signature Claude
takes"), and Kiro's refusal names nothing boundRefusal reads, so
refuseBoundThinking never mended it. Now every thinking block whose
signature is empty, blank or missing is left out for an upstream
serving Claude (api.anthropic.com, or a claude- model: relays, Bedrock
and Vertex ids, a plugin's fetch such as Kiro's), on every route
forwardOnce takes (relayed, translated, plugin, count_tokens), and
refuseBoundThinking runs it too. Text, tool_use and tool_result stay;
Claude's own signed thinking and redacted_thinking are untouched. A
model that learned thinkingBackNeeded (DeepSeek under another name)
keeps its unsigned blocks. Chat and Responses translated into Messages
already dropped unsigned thinking in anthropicBody.

Tests: TestUnsignedThinkingNotSentToClaude builds the reporter's shape
(the compaction summary, then two tool turns opening with Grok's
thinking signed "") against a fake Kiro that gives the same bare 400,
relayed and through the fake plugin's fetch (FAKE_KIRO model added).
TestGrokThinkingThenClaude runs the switch itself: a group answered by
a Chat Grok, then moved to Claude mid tool loop.
TestWithoutForeignThinking adds an unsigned block, Bedrock and Vertex
ids, a missing and a blank signature.

Run (mote, at this head rebased on 136178803):
- gofmt -l: clean; go vet ./internal/gateway: clean
- go test -run 'TestUnsignedThinkingNotSentToClaude|TestGrokThinkingThenClaude|TestWithoutForeignThinking|TestDeepSeekThinkingThenClaude|Bound|TestPluginBoundThinkingLeftOut|ThinkingBack' ./internal/gateway: ok
Broken by hand: the old predicate (DeepSeek signatures only, the
"signature" precheck only) put back: TestWithoutForeignThinking,
TestUnsignedThinkingNotSentToClaude/relayed and
TestGrokThinkingThenClaude fail (Kiro relay 400 "Improperly formed
request."). The plugin subtest passes on the old code too.
Not run before push: the full suite and the Linux/Windows vet; they
are queued behind other sessions' suites, and their result follows.
Not tried: a real Kiro or Anthropic account; Kiro's exact error text
is the reporter's description, not captured bytes.

Reported-by: citricdu (Discord)
2026-11-09 17:24:09 +08:00
yetoneandggbdpq 8a7f77cb71 provider, plugin: a sign-in whose refresh token rotates is never carried (#5583)
With Sign-ins ticked in Sync, a MiniMax Code sign-in went to both of the
reporter's computers. MiniMax spends a refresh token once: each computer
renewed it as it came due, the loser got invalid_grant 400 and was
signed out for good, with no newer generation anywhere in the sync path
to come back from. Qoder spends its refresh tokens once too.

The safest rule is that such a credential has one owner: it is never
carried. The auth hook declares `rotating` beside keepAlive and
refreshLead; the host passes it in the providers' row (Provider.Rotating),
and the carry path honours it: CollectSignIns leaves such sign-ins out of
what a backup or sync carries, and records() leaves out one an older file
carried, so MergeSignIns neither takes one in nor sends one up, and
RestoreSignIns writes none. Since the plugins don't declare it yet, and
the plugin host's list may not be read when a sync runs at start, magpie
also knows MiniMax Code (minimax-code, minimax-code-global) and Qoder
(qoder, qoder-cn) as rotating (rotatesKnown, read from their sources).
Nothing is deleted: local sign-ins stay, and a copy already on the server
falls out of the carried set by the usual removal.

The tradeoff, on purpose: each computer signs in to these itself. The
reporter's "relay" (carry one generation chain, re-read the store before
declaring a sign-in dead) would keep cross-computer sync for them; it is
a design of its own, not this fix, and stays open on the issue.

Ported from ggbdpq's patch on the issue, with rotatesKnown added so the
rule holds now and before the host lists its providers.

Run:
- TestCollectSignInsLeavesARotatingSignInOut,
  TestMergeSignInsDoesNotTakeARotatingSignInIn,
  TestRestoreSignInsLeavesARotatingSignInOut and
  TestKnownRotatingSignInsStayWithNoPluginListed (new): all four red on
  the old signins_carry.go ("a rotating sign-in is carried", "put in
  here", Added:1, "minimax-code's rotating sign-in is carried"), green
  after.
- go test -tags nogui ./internal/provider/ -run 'SignIns|Rotating' on mote.
- gofmt -l on the changed files: nothing.

Not tried: the two-computer race with real MiniMax Code or Qoder accounts.

Reported-by: skalitz-wolf (yetone/magpie#5583)
Reported-by: gua2100 (Discord)
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-09 12:04:20 +08:00
yetone 7cce4b4d78 plugin: a host holding over 512 MiB is replaced by a new one
A headless magpie on a small Linux server had its shared plugin host at
783 MiB after 2h25m (main process 117 MiB), and the kernel OOM-killed it.
Four plugins went through it (cursor, kiro, qoder, workbuddy). Nothing
bounded the host: no heap cap, no collection when idle, no restart.

The host now checks its RSS every minute, from ten minutes after it
started. Past 512 MiB it runs a full collection (Bun.gc(true)), and if it
is still past, it says so ("heavy"). magpie then retires it as a plugin
update does (Restart): the calls it is answering finish on it, and the
next call starts a new host.

What was measured (host RSS; bench driver = host.js run as magpie runs
it, a fake vendor, 4 requests at a time, every 5th a JSON reply, every
7th cancelled mid-stream):
- fake plugin, 200KB bodies, 4000 requests: macOS 25 -> 115 MiB flat,
  Linux (WSL) 47 -> 55-77 MiB flat.
- through an HTTPS CONNECT proxy, 600KB CJK bodies, 3000 requests:
  macOS 138 -> 156 MiB, flat from ~1000.
- WorkBuddy's real fetch (gzip path) through the proxy, cursor, kiro,
  qoder and workbuddy loaded with models.dev's 5.9MB catalog, 3000
  600KB CJK requests: macOS 101 -> 218 MiB (creeping ~7KB a request),
  Linux 92 -> 131 MiB, 84 idle. --smol: macOS 236, Linux 92 idle: no
  better, so it is not used.
- Bun's node:http2 client (Cursor's transport), 1500 sessions opened
  and closed: 58-60 MiB flat.
- 2000 provider listings with all four plugins: 64 -> 130 MiB flat.
None of these reach 783 MiB, so the cause in the report was not found;
the bound leaves 2x room over the largest of them. A plugin made to keep
each request's body grew the old host to 1048 MiB with nothing said; the
new host said "heavy" at 512 MiB (Linux).

Tests: TestHeavyHostIsReplaced (a 1 MiB bound: the host is replaced and
a call after it is answered) is red on the old code (not replaced 30s
on) and green now; TestLightHostIsKept checks a host under the bound is
left alone through fifty checks.

Run at this tree: gofmt -l (nothing); go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./..., go build for darwin,
linux (nogui) and windows on mote; go test ./internal/plugin/ on mote
(ok, 117s); the two new tests -count=3 on mote (-race), WSL and Windows
(ok). Not run before this push: the full suite (go test -tags nogui
-timeout 45m ./...), queued on mote behind five other sessions' suites
on its suite lock; pushed now, as the owner asked fixes not wait on it.

Not tried: a real signed-in Cursor, Kiro or Qoder account's requests and
background work (sign-in renewal, usage, model lists) under load; the
reporter's server itself.
2026-11-08 21:43:52 +08:00
yetone e484b4ff26 update: a slow download still moving is never ended by a total time; Bun, Claude Code and pf-serve too
#5572: since 80a47abba a silent download is broken off after 30s and
tried again, but the update's download still had a 10-minute total
(the update client's Timeout, the GUI run's ctx, `magpie update`'s ctx).
A download under ~140 KB/s, still receiving bytes, failed the 83 MB
Windows exe at 10 minutes part way. The stall timer is what ends a dead
one now; nothing ends one that is still moving.

- internal/update: fetch downloads through fileClient, the client without
  its Timeout. The feed and notes keep the 10-minute client. fetch's stall
  timer runs from the ask to the last byte, so a server that never answers
  still ends at stallAfter (30s), and download's retries stay bounded
  (len(retryWaits)+1 = 6 tries), so a connection that keeps going silent
  ends in about 4 minutes.
- internal/gui (Mac Stage, Windows/Linux StageBinary): run's 10 minutes
  (checkWait, a var for tests) bound only LatestIn; the download runs
  under a ctx with no deadline.
- internal/cli `magpie update` (Mac Stage, Windows/Linux ReplaceBinary):
  the same split.
- Siblings with the same fixed cap:
  - new internal/stall: Start(ctx, after) gives a ctx that ends with
    ErrStalled once `after` goes by with no byte read through w.Reader.
  - Bun (internal/plugin getURLOnce): watched with a 60s stall;
    KeepBunUpdated's 10-minute ctx around CheckBun is gone.
  - Claude Code (internal/claudecode downloadOnce, ~200 MB): watched with
    a 60s stall; keepOnce's 30-minute ctx around install is gone.
  - pf-serve (internal/pii upgrade): its 10-minute ctx is gone; get
    already had a 60s stall and the client a 60s header timeout, as the
    model's download (no total) does.
- Left as they are: plugin installs and npm updates (KeepUpdated's 10
  minutes) run `bun install`, whose network is Bun's own, small tarballs;
  rtk (5 min client), skills (2 min client), skilltree and market reads
  are small files; Grok CLI install has no cap of its own (its caller's
  ctx). None of them carries a large download behind a wall-clock total.

Run on mote (mote-run), at 49f207c78 + this change; the targeted
set again after rebasing on d4a221f79 (ok):
- go test ./internal/stall ./internal/update ./internal/claudecode
  ./internal/pii -run 'Stall|Slow|Silen|TestDownload|TestInstall|TestKeep';
  go test ./internal/plugin -run Bun; go test ./internal/gui -run
  TestUpdate: ok
- new: TestSlowButMovingIsReadWhole, TestSilenceIsAStall (no answer, part
  way), TestDownloadSlowButMovingOutlastsTheClientTimeout (client Timeout
  300ms, body ~1.2s: one try, no retry), TestUpdateSlowDownloadOutlastsTheCheckBound
  (checkWait 200ms, body ~600ms: ready), TestDownloadThatGoesSilentIsAStall
  (claudecode), TestBunDownloadThatGoesSilentIsAStall. The silent server
  after its retries stays covered by TestDownloadStallEveryTimeSaysSo
  (6 tries, errStalled).
- go test -race -count=3 ./internal/stall ./internal/update -run
  'Stall|Slow|Silen': ok
- win-run (Windows 11): ./internal/stall ./internal/update
  ./internal/claudecode ./internal/plugin with the same -run, and
  ./internal/gui -run 'TestUpdateSlowDownload|TestUpdateDownloadSaysStepAndSpeed': ok
- wsl-run (Ubuntu 24.04), -tags nogui: the same packages and ./internal/gui
  -run TestUpdate: ok
- gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; GOOS=linux go build -tags nogui;
  GOOS=windows go build: clean
- Full suite: run after the push under the suite lock.

Broken by hand: fetch back on `client` fails
TestDownloadSlowButMovingOutlastsTheClientTimeout ("broke off ...
Client.Timeout or context cancellation while reading body"); the GUI's
download back under the check's ctx fails
TestUpdateSlowDownloadOutlastsTheCheckBound (state error, "context
deadline exceeded"); stall's reader not putting the timer off fails
TestSlowButMovingIsReadWhole (50 of 120 bytes); Bun's and Claude Code's
downloads unwatched fail their silent tests at the 20s bound ("context
deadline exceeded").

Not tried: a real update over a slow or throttled link, on any OS; a real
Bun or Claude Code download over one. The Mac's unpack and signature
check now run with no deadline (they had the 10 minutes before).

Fixes #5572
2026-11-07 06:09:42 +08:00
yetone 1fd0bb9670 update: a download whose HTTP/2 transfer broke off tries again over HTTP/1.1
biubiu8802 on X (tweet 2118719081872540038): behind their proxy every
update failed with "download broke off, a network problem", while the
same proxy carried ordinary downloads. Confirmed in the code: download()
retried up to 5 times with Range, but each try went through
netproxy.Dispatch over HTTP/2 again; Dispatch moves a host to HTTP/1.1
only on a TLS record error (recordError: bad record MAC and kin), and
"unexpected EOF" or a stream reset is not one. So a proxy that cuts
HTTP/2 streams part way cut every try the same way.

- netproxy: OverHTTP1(ctx) sends every request under ctx through
  Dispatch's HTTP/1.1 copy (route.h1), kept through With.
  BrokeOff(err) says a transfer broke off (net.Error, unexpected EOF,
  HTTP/2 stream error / GOAWAY / lost connection, a reset; not a
  context that ended). AgainOverHTTP1 runs a download once more over
  HTTP/1.1 after such a failure.
- update: the tries after a broken one go over HTTP/1.1, and still
  resume with Range from the bytes kept.
- Siblings, the other big downloads through Dispatch's client: the
  masking model and pf-serve (pii.fetch, one more try over HTTP/1.1
  from what is on the .part file), Bun's zip (plugin getURLFrom),
  Claude Code's binary (claudecode.download) and the Grok CLI
  (grokDownload) each try once more over HTTP/1.1.
- docs/subsystems/providers-accounts.md names it.

Run (mote, Go 1.26.8, at this tree, base 80ae904c2 = origin/main fetched
just before push):
- TestDownloadBrokenOverHTTP2TriesHTTP1 (httptest TLS HTTP/2 server
  that resets each HTTP/2 stream after 100KB, serves HTTP/1.1 whole):
  red with the update.go line taken out, all six tries over HTTP/2
  ("stream error: ... INTERNAL_ERROR"); green after, asked
  ["HTTP/2.0 ", "HTTP/1.1 bytes=102400-"].
- TestOverHTTP1EveryHost, TestAgainOverHTTP1, TestBrokeOff: green.
- go test ./internal/netproxy ./internal/update ./internal/pii
  ./internal/claudecode ./internal/plugin ./internal/provider: ok.
- go test ./... -count=1 -timeout 45m: 86 ok, gateway 795s and agent
  303s ok; internal/gui red only on two AppKit tests already filed for
  mote's macOS 27: TestMainWindowCorners/macOS_26_SDK (#3949) and
  TestPanelHiddenByWailsMarksPageOutOfSight (#5322). Nothing in gui is
  touched here.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of the touched
  packages clean.

Not tried: a real proxy that cuts HTTP/2 (the reporter's); the retry of
pii, Bun, Claude Code and Grok against a real host (unit-covered by
AgainOverHTTP1 only); Windows/Linux test runs.
2026-11-06 23:44:58 +08:00
yetone 3cbb7e0429 plugin host: a plugin's redirect to another origin is sent none of its key headers (#5508)
Bun follows any redirect anywhere and, on a hop to another origin, drops
only Authorization and Cookie. Checked on Bun 1.4.2 before the change:
x-api-key, x-goog-api-key and a custom header reached a second local
server on each of 301, 302, 303, 307 and 308. So a vendor (or anything
answering at its URL) that redirected elsewhere got a plugin's key
headers, and an https vendor's redirect to http was followed.

host.js now applies provider.KeepsCredentials' rule (c57a5f7f5) at the
one place every plugin fetch leaves, `sent`:
- `followed` sends each hop with redirect "manual" and follows a 3xx
  itself only to the first request's origin (scheme, host, port), or
  http to https on the same host and default ports (`sameOrigin`, a
  port of provider.SameOrigin), at most 10 ("stopped after 10
  redirects", as Go's). Any other 3xx is given back to the plugin as it
  came, Location included.
- A bare request (no body, only accept/user-agent-like headers,
  BARE_HEADERS) still follows a redirect anywhere, as a download handed
  to a CDN does; it carries nothing of the plugin's.
- 301/302 on POST and 303 become GET with the body and its headers
  dropped; 307/308 send the body again, and a stream body that can't be
  sent twice makes the 3xx the answer.
- A fetch asked with redirect "manual" or "error" (mimo, cursor,
  gcp-ai and others do) goes out as it was asked.

Paths this covers, all of which reach globalThis.fetch and so `sent`:
- the gateway's request to a plugin account: Provider.do → the
  account's transport → plugin.Fetch → host "fetch" → fetchAs → the
  loader's fetch, or the host's fetch when the loader has none. A 3xx
  the host gives back reaches the caller as the vendor sent it.
- plugin.Fetch from the check-ins (MiniMax, Qoder, Trae, WorkBuddy) and
  the models/usage/check/decide reads through plugins.go.
- the plugin's own hooks: sign-in authorize/callback, models, usage,
  checkin, chat.headers, gateway request hooks, and pi.js's extensions
  (its watchFetch wraps the host's fetch).
- proxied ones: a provider's or account's own proxy (via / init.proxy),
  magpie's global proxy, the SOCKS bridge (netproxy.ForBun) and the LAN
  direct rule. Each hop is sent by `hop` (the old `sent`), so each picks
  its own proxy for its own host.
Not covered, filed as #5520: Bun.fetch (read-only and non-configurable
in Bun 1.4.2, so it can't be wrapped; no community plugin calls it), and
a library on node:http that follows redirects itself. node:http,
node:http2 and WebSocket follow none. The Go side needs nothing more:
Provider.do already hands a plugin account's request to its transport,
which doesn't follow.

Docs: provider-plugins.md (the rule, what isn't covered, the test) and
gateway-routing.md's list of what follows KeepsCredentials.

Test: TestPluginRedirectKeepsTheKeyAtItsOrigin (internal/plugin) drives
a real host with the fake plugin, sending x-api-key, x-goog-api-key, a
cookie, x-own and the loader's Authorization: 307 and 302 to a second
local server are the answer and that server gets nothing; an https
vendor's 307 to http on its own host and port is the answer; a
same-origin 307 is followed with every header and its body; a 303 is a
GET without Content-Type; a loop stops after 10; the usage hook's bare
GET follows a 302 elsewhere.

Broken by hand, on mote:
- `sent` passing every fetch to `hop` (Bun's follow): red. away307 and
  away302 answered 200 {"stolen":true}, and the other server got
  x-api-key, x-goog-api-key and x-own (not Authorization or Cookie:
  Bun's own drop).
- sameOrigin ignoring the scheme, and bare() always false: red. The
  https vendor's redirect to http was followed (400 "Client sent an
  HTTP request to an HTTPS server"), and the bare usage GET got the
  302's body instead of "cdn".
Restored, green.

Run on mote at this tree on origin/main 77bda84a6 (the docs' #5520
reference added after; no code changed since): gofmt -l clean; go vet
./..., GOOS=windows go vet ./... and GOOS=linux go vet -tags nogui ./...
clean. go test -tags nogui -count=1 -timeout 45m ./internal/plugin
./internal/gateway ./internal/provider: all ok (144s, 852s, 163s), no
red. No host.js node tests exist. The full ./... suite was not run.

Not tried: a real vendor's redirect (none known to redirect its API
elsewhere), an http to https upgrade on default ports (the test can't
bind 80/443), redirect "manual"/"error" from a plugin in a test (the
fake plugin's loader doesn't set one; the code passes such a fetch to
`hop` untouched), and Windows/Linux runs of the new test.

Rebased on 483b131ef (483b131ef browser, 6302f88bf sessions;
neither touches this change's files). At the rebased head, on mote:
gofmt -l clean, go vet (darwin, GOOS=windows, GOOS=linux -tags nogui)
ok, go test -tags nogui -count=1 -run TestPluginRedirect
./internal/plugin ok. The three package runs above were at 77bda84a6.
2026-11-06 20:16:44 +08:00
yetone 92f5fc8fe0 plugin: Cached parses plugin-providers.json once for each version of it
While the host hasn't listed the plugins' providers (just started, or it
can't: offline, or a plugin that fails), Cached read and decoded the whole
plugin-providers.json on every call. The window's 15s drift poll asks it
for each look at a plugin's model (pluginOfAgent, PluginOf,
pluginAccounts), so on a real config copy it was 31.7MB of the 47MB the
poll allocated in two minutes (Unmarshal 21.8MB, ReadFile 9.45MB).

savedProviders reads it through filememo, parsed once per version of the
file. What it gives is shared; Cached's loop copies each provider before
setting its accounts, as it already did with provCache. A file that only
partly decodes keeps what decoded, as before.

Run (mote, at origin/main 773902a77 + this):
- TestCachedReadsSavedProvidersOnce: ok. Broken by hand (the per-call
  decode back): red, 3657 allocations for a 300-provider file, want <=100.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -count=1 -timeout 45m ./...: 86 packages ok;
  internal/gui red only in TestMainWindowCorners/macOS_26_SDK, #3949
  (that test on macOS 27, untouched here).
- Drift poll on a real config copy (8 calls in 2 minutes): plugin.Cached
  gone from the profile, Values 34.4MB -> 14.9MB, Drift 45.4MB -> 37.9MB.
2026-11-06 13:17:22 +08:00
yetone 3c516556bb plugin: TestStopLetsARenewalEnd waits for the renewal to start and the stopped host to end, not for 300ms and Restart (#2743)
The test was red on main two ways, each from a timing assumption:

- "the renewal never started" (line 54, 60s): the load call that starts
  the renewal had a fixed 300ms context. When the call is not written to
  the host within those 300ms (a slow get, a busy writer), it is given up
  on before it is sent, the plugin never reaches auth.refresh, and no
  wait helps. Now the call's context is cancelled only once the
  renewal's log shows it started.
- "kept ... not the renewed token" (line 61, CI at 84ad780b6): a
  given-up call keeps its slot until its abort is written to the host
  (callAborting). If Restart runs before that write, the host is busy,
  retire stops it in the background, and Restart returns at once; the
  test then read plugin-auth.json while the renewal was still running.
  The product is right: the background stop still lets the renewal end
  and saves the token. The test now waits on the stopped host's dead
  channel. It also waits until magpie has heard the host's "renewing"
  event, so a host output read late can't count as no renewal.

No product code changes.

Run on mote at base origin/main d2c29abe7 (no internal/plugin change since; rebased onto 640825b09 and the three stop tests rerun there, -race -count=3: ok):
- injected (not committed) a 500ms sleep in callWithTimeout before a
  "load" call is sent, and a 1.5s sleep in pumpCtrl before an abort is
  written. Old test, go test -race -failfast -count=20: red with each, the
  abort delay at line 61 ("after stopping 0s in, kept ... access:old"),
  the send delay at line 54 ("the renewal never started", 60.03s).
  New test, -race -count=20: ok with no injection (83.3s), with the
  abort delay (83.5s) and with the send delay (93.8s).
- broke by hand: stop no longer waiting for a renewal (the
  h.renewing loop off): the new test is red, "after stopping 2.004s in,
  kept ... not the renewed token".
- gofmt -l internal/plugin: nothing; go vet ./internal/plugin, with
  GOOS=linux and GOOS=windows too: ok; go test -tags nogui -race
  -count=1 ./internal/plugin: ok (165.2s).
- the full suite runs after the push, through the suite lock; its reds
  are filed as issues.

Not tried: Windows and Linux runs of this test; the change is in the
test only.
2026-11-06 11:51:38 +08:00
ggbdpq 3da58c3dfc fix(plugin): end ordinary RPCs' plugin work when their caller leaves (#4678)
A plugin model list's deadline and an ordinary RPC's cancellation released
only the caller. inTime raced the hook without stopping it, and host.go
marked only gatewayRequest cancellable, so a cancelled usage or providers
call never told the host: the plugin's task kept running, the host's
pending count kept it, and repeated reads left task after task alive past
their callers. Reported with an offline host-script reproduction that
shows abort reaching none of three pending usage tasks and five model
tasks outliving their deadlines.

The cancellation path a fetch and a gateway request already take now
carries ordinary RPCs too:

- host.go marks every call but init cancellable, so a caller whose
  context ends has the host told (the existing callAborting write), the
  way it already tells it of a stopped fetch. init is left alone: a start
  that overruns is stopped whole.
- host.js registers each ordinary RPC's AbortController; an aborted
  RPC's answer, nobody's then, is not sent.
- the handler is handed the signal: usage passes it to the plugin's
  auth.usage hook as its own options, and a model list's hook options
  carry it, with the listWait deadline aborting the same controller, so
  vendor I/O that supports stopping stops at the deadline or when the
  caller leaves, whichever comes first.

Sign-in renewal and its persistence are untouched: fresh() runs before
the hooks, and an aborted RPC's handler still finishes what it saves.

Refs #4678

Generated-by: GLM-5.3-Flash (ZCode)

Reviewed and ported, narrowed: an aborted ordinary RPC is no longer
answered "Aborted" at once and dropped from pending. It stays pending
until its handler ends, as on main. host.go's stop() closes the host's
stdin and then gives a renewing host up to stopRenewing to save the
rotated token; with the early done(), host.js's own `pending === 0 &&
closed` exit ended the process at once under a cancelled call whose
handler was still renewing or saving (keepSignedIn, set, signOut, a
usage hook mid-refresh). The Go side needs no answer: an aborted call
is released once its abort is written. The signal to the usage and
models hooks, and the listWait deadline aborting the models hook, are
kept as the patch had them.
TestCancelledCallKeepsTheHostTillItsHookEnds is new: a usage hook that
ends 600ms after its abort, then Settle() closing the host's stdin; the
hook's end must reach its trace.

Run on mote (darwin arm64, Go 1.26.8, Bun via testenv): go test -tags
nogui -count=1 ./internal/plugin/... ok 102.8s; -run Plugin
./internal/gateway/ ok 52.1s and ./internal/provider/ ok 13.3s.
Broken by hand: host.js and host.go at main, tests kept:
TestOrdinaryCallCancelTellsTheHost FAIL "the host was told of the
cancellation didn't happen", TestCancelledUsageReachesThePlugin FAIL
"the plugin's usage hook was handed a signal didn't happen",
TestModelListDeadlineTellsTheHook FAIL "the models hook was handed a
signal didn't happen". host.js as the patch had it (early answer):
TestCancelledCallKeepsTheHostTillItsHookEnds FAIL "the host left
before the hook ended; trace: {"signal":"live"}...".
Not tried: the reporter's replay.py against the built host, and a real
plugin's usage hook that passes the signal to its fetch. The reporter's
"host lives on after stdin closes with a task pending" row is unchanged
by design: that is the renewal safeguard.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 05:53:23 +08:00
yetoneandbaijiu666 5055349922 plugin: a host ended ends what its plugin started, at any depth (#5402)
A plugin host was ended with cmd.Process.Kill(), the host alone. A
plugin that starts a browser or a daemon (magpie-magicrew-auth's
headless Edge behind a WAF) left it running with no parent: 620
msedge.exe (6.8GB) and 382 temp profiles (57GB) in an hour on one
Windows machine. Bun's own job ends its direct children with it on
Windows, but lets their children out, so Edge's gpu/renderer processes
lived on. On macOS and Linux nothing ended them at all.

The host now starts as a proc.Tree (new Output.StartTree): a session of
its own on Unix, a job (kill on close) on Windows. host.kill kills the
tree; stop (after stopWait, so EndHosts, Restart, a moved proxy, an
update) and the line-too-long path both use it. A host that ends by
itself is swept by the tree's Wait: the Unix group is killed, the
Windows job closed. Nothing outside the host's own session or job is
signalled, so magpie's own process group is never reached.

Ported from baijiu666's fix/plugin-host-tree (a8172a1), which called
proc.End then Process.Kill. Reviewed against it:
- macOS/Linux: proc.End is SIGTERM to the host pid alone, followed at
  once by SIGKILL; host.js has no SIGTERM handler and the host was in
  magpie's own process group with no session of its own, so nothing it
  started was ended. Red on mote and WSL, same as main.
- Windows: endTree walks living parents, so it covers the killed host
  but not a host that ends on its own (crash, process.exit) or one that
  leaves when its input closes; those were red on Windows too.
- Its test was Windows-only and checked a direct child, which Bun's job
  already ends: the new test checks a grandchild, through a real host.

Run (TestHostEndedEndsWhatItsPluginStarted: a real Bun host whose
plugin starts a child that starts another; subtests stop / killed /
own end):
- origin/main 125fd93ec: red 3/3 on macOS (mote), Windows (win-run) and
  Linux (wsl-run).
- baijiu666's host.go: red 3/3 on macOS and Linux; on Windows red on
  stop and own end, green on killed.
- this change: green 3/3 on all three; -race green on mote and WSL with
  TestEndHostsLeavesNoChild, TestHostReapedWhileItsChildHoldsStdout and
  TestHostRunsAsMagpieBun.
- go test ./internal/plugin ./internal/proc: ok on macOS and Linux; on
  Windows ok except TestPiPackage, red the same at 125fd93ec (no `sh`
  on PATH there; #4115).
- go vet: darwin, linux, windows (./internal/... for windows). gofmt -l
  clean.
Broken by hand: the old and baijiu666 trees above are the fix taken out.
Not tried: a real headless Edge plugin (magpie-magicrew-auth) on
Windows; a plugin reading /dev/tty (the host has no controlling
terminal now, as every proc.Tree child).

Co-authored-by: baijiu666 <198813975+baijiu666@users.noreply.github.com>
2026-11-06 00:34:42 +08:00
yetone 331f201faf plugin: a cross-signed root copy in Windows' ROOT store no longer shadows Bun's own root (youyo.p_10001)
youyo.p_10001 (Discord #feedback, magpie 0.1.2993 windows/amd64, Bun
1.4.4, Clash Verge on 127.0.0.1:7897): every MiniMax plugin request to
agent.minimaxi.com failed "unable to get issuer certificate", while the
same chain verified outside the plugin host.

Cause: magpie hands Bun the user's Windows ROOT store as
NODE_EXTRA_CA_CERTS. Bun (BoringSSL) builds the chain up through the
first trusted certificate with the subject it wants, the extra file's
ahead of its own bundle, and stops when that one's issuer is missing.
A ROOT store holding USERTrust RSA's copy cross-signed by AAA
Certificate Services (agent.minimaxi.com's chain goes leaf, WoTrus DV,
USERTrust RSA) gave Bun that copy ahead of the self-signed root it
ships, and AAA is in neither. Node, curl and Schannel go on to the
self-signed one, so outside magpie it worked.

Fix: rootsFirst writes the self-signed roots first and keeps another
certificate only when its issuer is in the file too. Bun never ends a
chain on one that isn't self-signed (no partial chains), so one left
out could only stand in front of a root. NODE_USE_SYSTEM_CA=1 stays: the
system store Bun reads itself comes after its bundle and shadows
nothing (tried, below).

Also, for the next report like it:
- the host logs its network settings when it starts, and when the
  proxy (or the gateway's address) moves, old to new: the proxy without
  user and password (netproxy.Redact), NO_PROXY, NODE_EXTRA_CA_CERTS,
  NODE_USE_SYSTEM_CA, SSL_CERT_FILE/DIR (netLine);
- a fetch Bun refuses for the certificate keeps Bun's words and its
  code and cause, and adds "(UNABLE_TO_GET_ISSUER_CERT: the plugin
  host's TLS didn't verify agent.minimaxi.com's certificate chain
  against the roots it trusts)", so it doesn't read as the vendor's
  fault (throwTLS in host.js).

The plugin side, a China-site account call that can't reach
agent.minimaxi.com going once to agent.minimax.cn, is
opencode-minimax-auth 0.2.3 (magpie-community/plugins#757).

Run:
- Reproduced on xiaomi-gpu (Windows 11, Bun 1.4.2) with the real host
  and the real ROOT store: the real cross-signed USERTrust RSA (valid to
  2028) imported into LocalMachine\Root, then a scratch test through
  bunCommand (NODE_USE_SYSTEM_CA=1 included) fetching
  https://agent.minimaxi.com/: the file as before ->
  UNABLE_TO_GET_ISSUER_CERT, rootsFirst's -> 200. Certificate removed
  after (checked); without it both 200. Also as NODE_EXTRA_CA_CERTS
  alone: cross copy -> UNABLE_TO_GET_ISSUER_CERT; self-signed then cross
  -> 200; cross then self-signed -> UNABLE_TO_GET_ISSUER_CERT; cross with
  AAA either order -> 200. The cross copy in CurrentUser\CA with
  NODE_USE_SYSTEM_CA=1 -> 200 (no shadowing from the system store).
- New tests: TestRootsFirstPutsTheSelfSignedCopyAhead,
  TestBunGetsPastACrossSignedRootCopy (a synthetic cross chain through
  Bun), TestPluginTLSRefusalSaysWhose (through the fake plugin's fetch;
  Bun's message there is the reporter's "unable to get issuer
  certificate"), TestNetLineSaysNoSecret. Green on mote (macOS, Bun
  1.4.2) and on xiaomi-gpu via win-run, with the systemca tests beside
  them.
- Broken by hand on mote: rootsFile without rootsFirst ->
  TestBunGetsPastACrossSignedRootCopy/the_cross-signed_copy_first red;
  throwTLS rethrowing as is -> TestPluginTLSRefusalSaysWhose red
  ("err = unable to get issuer certificate").
- mote, at this tree: gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui, GOOS=windows go vet of internal/plugin ok; go test
  ./internal/plugin ok (111.7s). xiaomi-gpu: go test -run
  'Proxy|CA|TLS|Roots|NetLine|LAN|Network' ./internal/plugin ok.

Not tried: the reporter's own machine and store (what put the cross
copy in their ROOT store is a guess from the error; the host's new log
line will show NODE_EXTRA_CA_CERTS, and the file is in the cache's bun
folder); Bun 1.4.4 (the reporter's; 1.4.2 here); macOS keychain copies
(rootsFirst applies to systemRoots there too, untried with a real cross
copy); Linux takes the distribution's bundle as it is, unchanged.
2026-11-05 16:58:34 +08:00
yetone ed7aeb052f plugins: a package that declares magpie.agent is an agent, with a main or without (plugins#737)
miaocell's magpie-agent-deva ships a Bun module as its main beside its
moejs agent file (deva.agent.js), because the agent needs a runtime. The
market's GitHub list decided the kind by whether a main was there, so it
listed the package under Providers, and the Installed row wore a Provider
chip and a provider logo though the module serves no provider.

Now readTagged gives Kind "agent" to any package that declares
magpie.agent; middleware, page and hooks still need no main to be that
kind. The file looked for in the repository is still the module Bun
loads (its main), or the agent file when there is no main. The Installed
row of an agent plugin wears Provider only when its module serves a
provider, and its logo is the agent glyph unless it does. The moejs
descriptor contract is unchanged. The community registry.json already
gives kimi-desktop and reasonix-desktop (both with a main) kind agent;
the plugins repo's check now fails an agent package listed as any other
kind.

Docs: docs/reference.md, docs/subsystems/provider-plugins.md, and
site/public/docs plugins.html in en, zh and ja say an agent that needs a
runtime keeps its agent file and adds a Bun main, and is listed as an
agent either way.

Run (on mote, at this head rebased on b047cfe73):
- TestTaggedAgentWithMain (new; the reporter's real package.json,
  index.mjs and deva.agent.js in testdata): go test -run
  'Tagged|PkgEntry|Readme|GitHub' ./internal/plugin ok. Red with
  github.go at its parent: kind "".
- plugin-agent.test.cjs (new rows: an agent with a main and no
  provider, one switched off, one that serves a provider), chromium and
  webkit, en, zh, zh-TW, ja, de: ok. Red at origin/main b047cfe73: the
  deva row's chips were [Agent, Provider].
- Every plugin*.test.cjs plus i18n-keys, both engines: 1090 of 1094 ok.
  The 4 reds are plugin-move-unserved "Try again takes the models
  unticked" (Model 1 folded behind "Show the other 29"), red the same
  at origin/main b047cfe73; filed as #4410.
- gofmt -l, go vet ./internal/plugin ./internal/gui, GOOS=linux and
  GOOS=windows go vet ./internal/plugin, go test -run 'Budget|I18n'
  ./internal/gui (TestCoreScriptBudget, budget not raised): ok.

Not tried: installing magpie-agent-deva from the real GitHub list in a
running app (the list is read from the test server); Windows and Linux
runs of the GUI tests.
2026-11-05 03:54:41 +08:00
yetone 79477604a5 providers: a plugin option that says placement "top" sits under the accounts, above Routing (#5269)
mycf_711 (#5269): WorkBuddy Pro's plugin-level "panel" switch was drawn in
Plugin options, under the whole model list, so it took a scroll every time.
An option in auth.options may now say `placement: "top"`: the provider's
editor draws those in a Plugin options block right under the accounts,
above Routing, and the rest under the models as before. The note that the
plugin reads them goes with the first block. host.js keeps placement only
when it is "top" (anything else is left out, so the option goes under the
models), and plugin.Option carries it to /api/providers. A plugin that says
no placement is drawn exactly as before, and an older magpie ignores the
field. Documented in docs/subsystems/provider-plugins.md and
docs/reference.md.

Run (mote, through mote-run):
- new internal/gui/tests/plugin-option-placement.test.cjs: chromium 31/31,
  webkit 31/31 (1100 and 420 wide, en/zh/zh-TW/ja/de; mixed, top only,
  none or an unknown placement; the top switch posted on Save).
- plugin-options.test.cjs 11/11 and plugin-option-words.test.cjs 21/21,
  i18n-keys 4/4, each in chromium and webkit.
- go test ./internal/plugin ok (TestPluginOptions checks "top" kept and
  "sidebar" left out); go test -run Budget|Script|Asset ./internal/gui ok.
- gofmt -l internal/plugin empty; go vet ./internal/plugin ./internal/gui
  ./internal/cli, GOOS=linux -tags nogui and GOOS=windows vet of
  internal/plugin ok.

Broken by hand:
- app.js put back to its parent: the placement test fails "mixed" and
  "top" in both engines (blocks under the models), "none" still passes.
- host.js's placement line removed: TestPluginOptions fails
  "second = {... Placement:}".

Not tried: a real WorkBuddy Pro plugin (Gitee, private) with the field;
the full go test ./... and the whole GUI suite run after the next commit.
2026-11-05 00:55:36 +08:00
yetoneandMYCF711 cbb09383fb plugin: a GitHub-tagged package's card says its own name and summary (#3608, plugins#394)
MYCF711's #3608 (and plugins#394): a repository tagged magpie-plugin
outside the community's list showed its repository's name and GitHub's
description on its card under Discover → Unofficial, on GitHub, whatever
its package.json said of itself. Ported from MYCF711's 1cc337001.

Now readTagged keeps package.json's magpie.name (ownName, as main's row
already does since d8cf4f74f) and magpie.summary (ownSummary, by
language), and npm's copy's when the card installs from npm and it says
them. The card shows them in place of the repository's, with an "Its
own words" chip whose tip says nobody reviewed them; no community badge,
and they never resolve a name. GitHub's description stays the English
line for a package whose summary has none.

Changed from 1cc337001, reviewed line by line:
- ownSummary also refuses control and format characters (a bidi
  override, a zero width space) and bad UTF-8, as main's ownName does.
- magpie.summary is read as raw JSON: in 1cc337001 a summary that isn't
  an object of strings ("summary": "text") failed the whole package.json
  parse, and readTagged then left the repository out of the list.
- npm's copy's words win over the repository's when npm's is the one
  installed; 1cc337001 read them from npm only for the NPM type, which
  no card shows.
- Left out: the row chip and InstalledName/ownName on /api/plugins (main
  has them from d8cf4f74f), NPM.Name/Summary (no page reads them), and
  the core budget raise: the card's code is paid for by cutting three
  comments in plugins.js, 1,533,388 of 1,533,802.

Run (mote, at this tree on 538026e62):
- go test -count=1 ./internal/plugin ./internal/gui: internal/plugin ok
  (145s); internal/gui red only in TestMainWindowCorners/macOS_26_SDK,
  filed as #3949 (macOS 27)
- go vet ./internal/plugin ./internal/gui, GOOS=linux -tags nogui and
  GOOS=windows: clean; gofmt -l: nothing.
- node --test internal/gui/tests/plugin*.test.cjs,
  plugins-more-discover and i18n-keys, Chromium and WebKit: 1028 of
  1032; the 4 reds are plugin-move-unserved's "Try again takes the
  models unticked" (en, zh, both engines), filed as #4410 and #4392
- plugin-own-words.test.cjs: en, zh, zh-TW, ja, de at 980 and 420, both
  engines, 22 of 22; with main's plugins.js 0 of 22 ('magpie-officeace'
  for 'OfficeAce').
After the rebase on 823e7c250 (mote): TestCoreScriptBudget ok, go test
  -run 'OwnWords|Tagged' ./internal/plugin ok, plugin-own-words,
  i18n-keys and plugins-more-discover 32 of 32.
Broken by hand:
- npm's words not taken: TestReadTaggedOwnWords red (name "OfficeAce
  dev").
- summary read as map[string]string: TestReadTaggedOwnWords red (the
  package with "summary": "text" not kept).
- ownSummary without the character check: TestOwnWordsBounds red (two
  lines, tab, bidi override, zero width).
Not tried: a real repository with magpie.summary (none tagged has one);
the desktop window itself.

Co-authored-by: MYCF711 <323101370+MYCF711@users.noreply.github.com>
2026-11-04 22:47:11 +08:00
yetone 083821dc96 plugins: a search entry can use the plugin's own sign-in, with its own rests
Asked for by axelburks on Discord. A plugin's search hook entry can name
a provider its own auth hook signs in to, `auth: "<provider id>"`. It then
takes no key. The host picks an account, renews it under `fresh` (the wait
counts within the search's time), runs the hook in `inScope`, and gives it
`ctx.getAuth()`, which returns that account's sign-in. A token the hook saves
with client.auth.set goes to the same account.

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

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

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

Not tried: a real search vendor or Axel's own plugin; real accounts; runs
on the Windows or Linux boxes; the full GUI suite. The full go test ./...
runs after the push.
2026-11-04 20:55:42 +08:00
yetone 75e30625f5 plugin: a command that serves no pages moves a page's service off the app's port (#5187)
MYCF711 (#5187, Windows, 0.1.2901): magpie plugin update run while the
app runs hung with no output. Its host loads every plugin, and
page-chat's service waits for port 3477, which the app's host holds:
each CLI command that starts a host waited ~6s on it, then kept trying
the port every second in the background, so it could take 3477 from
the app's host when that restarted after the update.

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

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

Not tried / not reproduced: the reporter's literal no-output hang. Before
this change, update finished on 0.1.2909 in every setup tried (nogui
CLI with 3477 held, beside nogui serve, beside the release GUI exe in
the interactive session: 6-20s), so this removes the wait and the
port contention seen, not a hang reproduced. Not tried on Linux or the
macOS app.
2026-11-04 16:25:02 +08:00
yetone cd83c3147f plugin: a hook's auth.set doesn't sign in again an account signed out while it ran (#5126, #5119)
Cause: a plugin hook that saves a sign-in through client.auth.set (a
models list spending a rotating refresh token) wrote it into
plugin-auth.json unconditionally. A listing that began before a
sign-out, or before a failed move's putBack took the accounts back out
of the plugin (plugin.Take), landed after it and wrote the account in
again. TestMoveToPlugin's reset signs fakeco out, but a background
listing set off by the step before spent a@fake's "rot-a" token again
(rot-a+++++ seen in the file right after the sign-out), so the next
Move saw a@fake as the plugin's own (movedAccount.Was), restored it on
failure, and "the plugin kept an account of a failed move".
TestMoveCutShort (#5119) fails the same way: the account Take removed
came back through the same write. Not a leak between runs: the race is
inside one run, and more runs only gave it more chances. It is a real
bug for users too: signing out of a rotating-token account while its
models are listed brought it back.

Fix: inScope in host.js notes whether the account was signed in when
the call began (had); auth.set skips the write under the file's lock
when it was and is gone now, as renewLocked already does for renewals.
Sign-in steps (signingIn) are not held to it, their account is new.

Test: TestSignOutOutlastsRunningHook holds the fake plugin's models
hook (new FAKE_MODELS_HOLD: marker file in, release file out) across a
SignOut in a real host and checks the account stays gone, and that a
hook not raced still keeps the token it saved.

Run (all at this tree):
- mote-run go test -count=30 -run 'TestMoveToPlugin$|TestMoveCutShort$'
  ./internal/provider: ok. Before the fix the same run on mote failed
  3 TestMoveToPlugin + 9 TestMoveCutShort of 30 each; -count=15 of
  TestMoveToPlugin alone failed 2 to 4 of 15.
- wsl-run go test -count=20 of the two plus the new test: ok. Before
  the fix: 4 + 17 of 20 failed on Linux.
- mote-run go test -count=5 -run TestMoveToPlugin$: ok.
- mote-run go test -count=5 TestSignOutOutlastsRunningHook: ok.
- mote-run go test -timeout 45m ./internal/provider ./internal/plugin:
  ok (provider 171.6s, plugin 160.4s).
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet of both
  packages: ok.

Broken by hand: host.js reverted with the test kept:
TestSignOutOutlastsRunningHook red 3 of 3 ("the hook signed the account
in again"), and the provider tests red as above.

Not tried: a real vendor's rotating-token plugin signed out mid-listing
(the fake plugin's rot- sign-ins stand in for it); the full ./... suite
runs after the push.
2026-11-04 13:23:28 +08:00
yetone 90bf96a23d search: a plugin can give a web search API (its search hook)
treeman on Discord #help asked for web search to be pluggable so users can
add search vendors. A plugin's `search` hook, {search: {<id>: {name, keysURL?,
keyOptional?, url?, execute({query, count, key, url}, ctx)}}}, adds an API to
Settings > Models > Web search as `<plugin>:<id>`. It is added, keyed, ordered,
switched off and removed like Tavily or Brave. The built-in APIs stay built in.

How: host.js collects the hook's entries (id [a-z0-9-], an execute) into
Loaded.Searches and runs one with the `search` op (timeout from ctx, an error
with a numeric status comes back as a refusal). The host notes them in
plugin-searches.json (internal/plugin/search.go); provider.AllSearchVendors
adds the noted ones of plugins that are on to SearchVendors, so Ready, check,
the CLI and the GUI list see them. askSearchAPI hands a plugin vendor to
askPluginSearch below askSearchAPIKeys, so keys, rest on 401/402/403/429,
order, the masked query and the request-log row are the built-ins' own.

Run (mote, on this tree, whose base df7c94bdf was just fetched):
- go test -timeout 45m ./internal/plugin ./internal/provider ./internal/gateway
  ./internal/cli: ok.
- go vet native; GOOS=windows go vet plugin, provider, gateway, cli: ok;
  GOOS=linux go vet plugin, provider, gateway: ok. gofmt -l: empty.
- internal/gui: TestCoreScriptBudget and TestMainWindowCorners fail in a
  full run. This change touches no script (only api.go's loop), so the
  budget red is the base's (re-checked after the rebase, below);
  TestMainWindowCorners is AppKit on mote (macOS 27).
Broken by hand: skipping off plugins in NotedSearches turns TestPluginSearch
red; the refusal mapping removed turns TestPluginSearchAPI red.
Not tried: a real plugin against a real vendor's API; the GUI JS suite (no
GUI script changed); a Linux or Windows window; site/public/docs (en, zh, ja)
do not describe the hook yet. A plugin just added is listed once the host has
loaded it; RestoreSearchAPIs drops a plugin's entry on a machine without it.
The community README has the template (magpie-community/plugins 3ec42d4).

Reported by treeman.
2026-11-04 08:37:21 +08:00
yetone 7aff42d863 plugin host: the sign-in lock and file waits no longer freeze the event loop (#5112)
pause() was Atomics.wait, which blocks Bun's one thread. lockAuth spun on
plugin-auth.json.lock with pause(5) for up to 2 x AUTH_LOCK_STALE (20s),
and writeDurable and readFileSteady waited up to 500ms each, so one
plugin's renewal storm stalled every plugin's requests, model lists and
check-ins (499s while the port still answered). Reported by mycf_711.

- pause() is gone; sleep() is an awaited setTimeout.
- lockAuth, writeDurable, keepAuth, writeAuth and changeAuth are async,
  and so are their callers (setAuth, removeAuth, settle, save, apiKey,
  staleAccess, import/take/signOut, pi.js modify/delete).
- changeAuth takes in-process changes one at a time (authQueue) before
  the file lock, so a host's own changes don't poll against each other;
  the lock poll backs off 5ms to 50ms. Stale-lock takeover (10s) and the
  change being made on a fresh read under the lock are unchanged.
- The sync readFileSteady (readAuth, hot path) no longer waits: it retries
  twice at once, and readAuth keeps the last good read when the OS still
  refuses (a failed read is unknown, not none). Under the lock the wait
  is async (readFileSteadyAsync, 50 x 10ms as before).

Test: TestAuthLockWaitDoesNotFreezeTheHost holds the lock 600ms and checks
a timer keeps ticking while changeAuth waits, 20 concurrent changes lose
none, and a lock 11s old is taken over. On the old host.js it fails
("the lock is still held at 300ms": the loop froze 10s). Verified by
putting the old host.js and pi.js back.

Run (mote, at this tree): go test ./internal/plugin ./internal/gateway
./internal/provider all ok; gofmt, GOOS=windows/linux go vet of
internal/plugin clean. Not run: full go test ./..., a real Windows host
under a renewal storm. The serial-fallback total budget is #5113.
2026-11-04 01:53:46 +08:00
yetone 4c0c6c02b8 plugin: keep idle plugin sign-ins alive in the background (#5080)
A plugin with auth.refresh had a sign-in renewed only when something
used the account (a request, its models, usage or check-in) within its
refreshLead of expiry. An account left idle past its token's life
lapsed. OrcaTerm's WeChat token lives two hours, and after that its
refresh answers SESSION_EXPIRED for good, so the user had to sign in
again (orinsid, magpie-community/plugins#675).

The gateway now renews each such sign-in as it comes due
(provider.KeepPluginsSignedIn, started beside KeepPluginsListed):

- Due times come from plugin-auth.json through filememo
  (plugin.RenewAt: expires less the lead the host reckons, now listed
  as Provider.Renews/RenewLead). Nothing is asked, and no host started,
  until an account is due. The loop sleeps until the next one, at most
  5 minutes, and renews them one after another.
- A due sign-in goes through the host's own renewal (host.js
  keepSignedIn, which shares renewal() with fresh()). It is one at a
  time per account whoever asks: a request arriving meanwhile waits
  for the same promise, under the cross-process lock file, through the
  account's proxy.
- Kept: accounts switched on and not marked, of a plugin provider not
  switched off, hidden (leftAlone) or being moved.
- A failed renewal marks nothing. It is held back for 1m, doubling to
  at most 30m, for that sign-in only. Only the plugin's
  signIn:"expired" marks it, as at a request.
- A plugin can opt out with auth.keepAlive: false. None in the plugins
  repo needs to: no refresh costs quota, the ones rotating single-use
  refresh tokens (Cline, Factory, Nous, SenseNova, CodeArts, Qoder,
  MiniMax) rotate at use already, and kimi-work's reference accounts
  and Raccoon's desktop reuse never refresh another app's token.

Docs: provider-plugins.md "A sign-in nothing uses"; leftAlone list in
providers-accounts.md.

Run at the pushed head, on mote (mote-run), -tags nogui:
- go test -count=1 -timeout 45m ./internal/plugin ./internal/provider
  ./internal/gateway: ok (109s, 119s, 637s), rebased on origin/main
  6cfe78635. Rebased again on b088fd0f0 (gateway.go, prompt.go
  changed): go build ./..., go vet of the three packages and the new
  tests plus TestLivePrompt*: ok.
- the new tests on Windows (win-run) and Linux (wsl-run): ok.
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...,
  go vet ./...: ok. gofmt -l: clean.

Broken by hand, each red, then restored:
- keepSignedIn refreshing by itself, not through renewal()/the lock:
  TestKeepSignedInRenewsIdleSignIns red (r-ok-busy renewed twice
  beside concurrent requests).
- keepAlive:false ignored: red (stayco listed as renewed).
- a network failure reported as gone: red (down: Gone true).
- Go backoff removed: TestKeeperBacksOffAFailedRenewal red.
- the On, Lapsed and leftAlone filters each dropped:
  TestKeptSignInsAreTheOnesSwitchedOn red.
The new tests don't compile on the old code (no KeepSignedIn).

Not tried: a real OrcaTerm account idling past its 2h token with the
gateway running; Windows/Linux runs of the new tests (vet only); a
magpie with many plugin accounts beyond the unit test's look.
2026-11-03 21:01:27 +08:00
yetone f4c664a09c plugin, gui: magpie web ends its plugin hosts, waited for, before it runs the new version (#3285)
The second way acezan's 57 <defunct> magpie-bun (v0.1.2819, a Linux
systemd service, 47 hours) pile up: magpie web's restart to update
(AutoRestart) runs the new version with syscall.Exec in the same pid.
The running plugin host was the old image's child, and the old image's
host.read held the only Wait for it. After the exec nothing waits for
it, so it ends on stdin EOF and stays <defunct> under that pid, one per
restart to update. skygunner reproduced it and AAEE86 counted 22 zombies
for 23 images under one pid (#3285). With about a hundred releases a
day, an AutoRestart service makes about one a hour, as acezan's did.

- plugin.EndHosts (host.go) stops every host started and not yet
  reaped, including the retiring ones, waits until each one has been
  waited for, and refuses to start another (errHostsEnded). startOn
  starts the host and records it under one lock (live), so a host that
  starts during EndHosts isn't missed.
- Web.Wait calls it right before update.Reexec.

Run at 72bc741ef (on origin/main 40a287b21, after the previous commit):
- mote (macOS): gofmt -l clean; go vet ./internal/gui ./internal/plugin,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.
  go test -count=1 -timeout 45m ./internal/plugin: ok; -run Web
  ./internal/gui: ok.
- WSL magpie-desktop (Linux): ./internal/plugin ok, including
  TestEndHostsLeavesNoChild and TestHostReapedWhileItsChildHoldsStdout
  with a real Bun host; -race -count=3 of both: ok; go vet -tags nogui
  and -run Web of ./internal/gui: ok.

Both commits were then rebased onto 0acba61a3, which changes only
app.js and plugin-checkin.test.cjs; no Go file these runs built moved,
and they were not run again there.

Broken by hand: EndHosts returning at once makes
TestEndHostsLeavesNoChild fail on Linux ("children left once EndHosts
returned: [16459 S bun]").

Not tried: a real magpie web restart to update (a downloaded update
exec'd in the same pid) on Linux. The test covers EndHosts, not the
exec. Not changed: anything else alive at the exec (pii's helper,
awake's caffeinate, #4188) still outlives it the same way.

Reported by acezan on Discord. Diagnosed in #3285 by skygunner and
AAEE86.
2026-11-03 17:58:31 +08:00
yetone a9a8f11e7f plugin, proc: a plugin host is waited for when it ends, not when its stdout does
acezan on Discord (v0.1.2819, Linux x86_64, a systemd service): after
47 hours, 57 <defunct> magpie-bun children of magpie, growing toward the
unit's TasksMax until a restart.

One cause: the plugin host's only cmd.Wait ran in host.read after its
stdout reached EOF. A program a plugin started that kept a copy of the
host's stdout (Bun.spawn given Bun.stdout, which host.js's spawn guard
doesn't catch, #5063; a daemon left behind) held that pipe open past the
host's end, so EOF never came, Wait never ran, the host was never marked
dead, and every host stopped (Restart, a moved proxy, hostStale) stayed a
zombie until magpie quit. Reproduced on Linux (WSL magpie-desktop,
Bun 1.4.2): one more Z-state bun under the test process per Restart,
1, 2, 3, 4 over four rounds. The other cause, magpie web's restart to
update leaving the running host behind its exec (#3285), is the next
commit.

- proc.Output (new, internal/proc/output.go) gives a command's stdout and
  stderr pipes of magpie's own and waits for the command the moment it
  ends. Its readers then have OutputGrace (2s) to read the last lines;
  the pipes are closed after that, which ends a read held up by a
  grandchild. startOn uses it, and a reap goroutine fails the host when
  its child ends. host.read no longer calls Wait. The tests' fake hosts
  (no child) keep cmd.Wait.
- Every other start that wasn't waited for now goes through
  proc.StartReaped (Start, then go cmd.Wait()). Process.Release doesn't
  reap on Unix: codexrelay.Start (a relay that can end while magpie
  runs), tui serveInBackground, uninstall's startAfter, update's
  runAfterExit and OpenBeside (no Wait at all), and Windows' Reexec.
- TestEveryStartedCommandIsWaited (internal/proc) parses every non-test
  .go file. In each function, an x.Start() on a command needs an
  x.Wait(), or x handed on (a call's argument, a struct field), and
  .Process.Release() is refused. It found exactly the sites above.
- docs/subsystems/provider-plugins.md says how the host is reaped.

Checked and left as they are (each waits): the StartTree callers
(provider/install, library mcp_run and mcp_check, gateway claude_warmup
and claude_subscription), pii/serve, provider grok and claude_signin,
claudetui child_unix and wslread, awake, every other bun start (bun.go,
bunupdate, store, dist use Output/CombinedOutput).

Run at 82460a2f9 (on origin/main 40a287b21):
- mote (macOS): gofmt -l clean; go vet on the touched packages,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.
  go test -count=1 -timeout 45m ./internal/plugin ./internal/proc
  ./internal/codexrelay ./internal/tui ./internal/uninstall
  ./internal/update: all ok. -race -count=3 of the new proc tests: ok.
- WSL magpie-desktop (Linux): the same six packages ok, including
  TestHostReapedWhileItsChildHoldsStdout with a real Bun host; -race
  -count=3 of it and the Output tests: ok.
- Windows (xiaomi-gpu), at the tree before the rebase (base 5ee5274bd):
  proc and codexrelay ok. plugin and update had TestPiPackage,
  TestLoadConcurrentWithSavesAndEdits and TestPackagedByDpkg red; each
  fails the same at untouched origin/main 40a287b21 on that box, 3 of 3,
  and is filed (#4115, #1827, #4603).

Broken by hand, each red:
- host.go back to StdoutPipe with Wait only after EOF:
  TestHostReapedWhileItsChildHoldsStdout fails on Linux ("the host isn't
  marked ended 15s after Restart").
- Output.Start waiting for the readers before Wait:
  TestOutputWaitsPastWhatHoldsIt fails (not waited for in 10s).
- codexrelay back to Process.Release: TestEveryStartedCommandIsWaited
  names relay.go:89 and :92.

Not tried: a full go test ./... (mote and WSL were each running other
sessions' package runs, load 39 and 110); a real magpie serve or web
running for hours on Linux; the host test on macOS (no /proc; the
Output test runs there). Not changed: killing what a host left behind
(its process group) when it is stopped; an orphan like the sleep above
stays in the service's cgroup until it ends on its own.

Reported by acezan on Discord.
2026-11-03 17:58:31 +08:00