Commit Graph
62 Commits
Author SHA1 Message Date
yetone bac5be0677 plugin: one renewal of a sign-in at a time across magpie processes (plugins #331)
Cause: every magpie process that loads plugins runs a plugin host of its
own (the gateway, a CLI quota or usage command, a host restarting while
the old one finishes), and host.js's renew() kept a sign-in's renewal to
one at a time only inside one host (the in-memory renewing map). Two
hosts that found the same sign-in due each called the plugin's
auth.refresh with the same refresh token. A vendor that spends a refresh
token once (MiniMax, and about ten plugins' vendors: cline, codearts,
qoder, trae, workbuddy, raccoon, nous, kiro, factory) turned the second
away with invalid_grant, the plugin threw signIn "expired", renew() sent
it on without looking at the store again, and host.go -> provider's
notePluginLapse marked the account signed out, though the first host
had already saved a good token.

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

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

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

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

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

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

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

Run at the stacked tree (this commit plus #2554 and #2862, on ef6f3749d):
- gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui, and
  GOOS=windows: ok.
- set -o pipefail; go test -count=1 -timeout 45m ./... under the suite
  lock: every package ok (SUITE_EXIT 0).
- GUI: plugin-keyless-signin, account-models, i18n-keys and
  models-select-all-api, chromium and webkit, every language they cover:
  all pass.
Red on the old code: TestPluginKeylessSingleIdentity "keyless metadata lost"; the
GUI test 10/10 red; without signInKey's single line, "single identity
duplicated"; TestPluginEmptyKeyOnlyKeyless red with the Keyless check
replaced by false.
Not tried: a real Zen Free sign-in (needs plugins#205 published).
2026-10-22 20:50:59 +08:00
yetone 9b0f48612b gateway: a plugin's model that searches by itself can be the web searcher
01huadalang (Discord #feedback, 10-20): Settings › Web search offered only
Antigravity; Trae's search model couldn't be picked, "可能也有别的模型能搜索
但是识别不到". partSearcher and modelSearches answer false for every
provider with an account behind it, so no plugin-served provider was ever
offered, and a plugin had no way to say which of its models searches.

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

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

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

Not tried: the Trae plugin itself. It declares nothing about search yet;
marking Trae CN's search_agent there needs a Trae account to try it with,
which this machine doesn't have. No GUI files changed.
2026-10-22 03:18:11 +08:00
yetone f76201a84a plugins: a sign-in page the plugin's CLI opened isn't opened again, Grok's opened twice on macOS (andyfmyth on X)
"magpie里的grok 登录验证 在mac下 似乎每次都会弹两次验证, 在浏览器窗口里".
Grok's plugin signs in through `grok login --device-auth`, and Grok Build
(1.0.50, the webbrowser crate) opens the device page itself, through
NSWorkspace on macOS and ShellExecuteW on Windows. Neither reads $BROWSER;
the macOS binary has no "BROWSER" string. magpie then opened the same URL
from /api/plugin-signin (desktop), startPluginSignIn/followSignIn (a
browser tab) or `magpie plugin login`. Reproduced in a sandbox
HOME/GROK_HOME: grok's device-code tab appeared in Chrome with magpie not
involved, with and without SSH_CONNECTION. Built-in grok is retired
(2927a161e), so the plugin's path is the only one.

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

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

Run at the change (base origin/main 2ceff7370):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean.
- go test -p 4 -count=1 ./... -timeout 45m (load 150-380): every package
  ok except two.
  - gateway: TestVisionWaitIsntTheDescribersTime. It passes alone; filed
    as #2901.
  - gui: TestDockReopenKeepsTheWindowsSpace, TestMainWindowCorners,
    TestMainWindowRightToLeft, TestTrayCellClickReleasedPanel and
    TestCoveredWindowStaysUp, killed at their deadlines. All pass alone
    with TestPluginSignInPageOpensOnce; filed as #2645/#1936.
- GUI, both engines, at most 2 workers: plugin-signin-opened,
  plugin-signin, plugin-signin-no-url, plugin-moved-signin,
  signin-paste-plugin, signin-browser-down, signin-link,
  plugin-password-prompt and plugin-replaced. The run went 126 pass,
  10 fail, all launch or 5s timeouts at load ~380. Alone,
  plugin-signin-opened passes in both engines and password-prompt
  passes. signin-browser-down was red in one case per run, a different
  one each time. plugin-moved-signin (Chromium) is red alone at HEAD's
  app.js too. Both are filed as #2900.
- plugins: bun test packages/grok 49 pass; scripts/check.mjs ok. Its
  publish run is red only for middleware-think-tags's npm trust
  (plugins#180); grok 0.1.17 was published.
2026-10-19 12:42:48 +08:00
yetone ef75a9a2b5 plugin: a streamed reply's chunk frame is joined, not stringified, and its bytes viewed, not copied
Every chunk of a plugin's streamed reply went out as
JSON.stringify({id, event: "chunk", data}), and stringify scanned every
byte of the base64 for something to escape. Base64 has nothing JSON
escapes, so chunkLine joins the line from strings instead. The line is
byte-for-byte the one stringify made. A Uint8Array chunk that isn't a
Buffer (what a Response body hands over) was also copied whole by
Buffer.from before it was encoded. It is now viewed: the bytes are
encoded before the next read, so nothing else touches them.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-authored-by: Tsukikage7 <65526564+Tsukikage7@users.noreply.github.com>
2026-10-16 20:48:51 +08:00
yetone 7ba1b49846 plugin: a plugin's usage resets carry the team's and each window's
ZCode's built-in showed the personal plan's and the team's resets with each
reset's end; a plugin's usage could carry only one. host.js now passes a
plugin's resets.team and resets.each through, and movedCards shows them as
the built-in did. zcode 0.1.19 sends them.

TestPluginUsage's team and each check (plugin_usage_test.go) goes red without it.

Run at 63be47717 with this batch: go test -tags nogui ./... -count=1 -timeout 90m, 66 packages ok, no FAIL (load ~250). gofmt -l clean; GOOS=linux and GOOS=windows go vet of provider, gateway and plugin pass.
2026-10-16 19:38:00 +08:00
yetone e733b0722e plugins: a provider plugin says which service tiers a model serves, and Codex offers them (#2514)
Lovest on Discord (#general, v0.1.1267): a provider plugin had no way to
say a model is served at Fast or Ultrafast, so Codex never offered them for
plugin models, and the host dropped the field anyway.

- host.js keeps m.serviceTiers (tiersOf: string ids or {id} objects,
  trimmed, de-duplicated, anything else dropped) as plugin.Model.ServiceTiers.
- pluginCatalog puts them on catalog.Model.Tiers; CodexTiers offers a
  plugin's tiers when it declares any, so codexcat writes service_tiers
  (priority named Fast) into Codex's catalog and /v1/models.
- forwardTranslated keeps service_tier (OwnTier) for a plugin provider only
  when the request is translated to its Chat or Responses and the tier is
  one the model declares (provider.PluginTiers). A request relayed in its
  own protocol was already sent as the client wrote it; unchanged. Cursor's
  fast flag and #1954's ChatGPT tiers are untouched (#1954 not on main yet).
- Docs: serviceTiers in site/public/docs plugins (en, zh, ja) and a
  "service tiers" section in docs/subsystems/provider-plugins.md.

Tests (internal/gateway/plugin_tiers_test.go, fake plugin FAKE_TIERS):
TestPluginModelServiceTiersListed (fake-1 priority=Fast + ultrafast,
fake-resp ultrafast, fake-claude none) and TestPluginServiceTierReachesFetch
(Responses→plugin Chat and Chat→plugin Responses send a declared tier,
drop an undeclared one; same-protocol relays as before).
Broken by hand: OwnTier branch forced false → 3 translated cases red;
CodexTiers without IsPlugin → listed test red; host.js serviceTiers: [] →
listed test red. Restored → green.

gofmt -l clean; go vet -tags nogui with GOOS=darwin, linux, windows clean.
Not tried with a real vendor plugin that serves ultrafast.
Full suite: go test -timeout 45m ./... at af9e0d6b2 (sandbox HOME, load
average ~408 from other sessions): every package ok except agent and
gateway, which timed out at 45m with no failed test (rerun whole: timed
out again, 0 failures), gui (TestMainWindowCorners killed, #1936),
TestVendorThatStopsMidAnswerIsSaid (filed #2535) and
TestSetAnswersWhileDevinAndProvidersHang (#1375). The reds and the tests
running at each timeout (TestCodexKeptOnChatGPT, TestReplyNamesMember)
pass rerun alone, except TestMainWindowCorners (#1936). CI is the gate.
2026-10-16 18:13:15 +08:00
yetone 6ac7032b4b plugins: a community plugin's tools reach every agent through magpie's MCP server /mcp/magpie/tools (P4 tool point)
A plugin's OpenCode `tool` hook ({tool: {name: tool({description, args,
execute})}}) used to reach no agent. Now the plugin host collects each
loaded plugin's tools, turns their zod args (v3/v4 shape or object; a
raw JSON Schema is kept) into JSON Schema, and runs one on a `tool`
call: arguments checked against the tool's own zod first (defaults
filled, a wrong one named), execute raced against ToolTimeout (55s,
ctx.abort fires), the answer as text.

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

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

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

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

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

Real use: a built magpie in a sandbox HOME (MAGPIE_ADDR 127.0.0.1:3491,
real Bun), the example plugin added with `magpie plugin add`. curl over
MCP: initialize, tools/list (4 tools, schemas), shout "HI HI (for
curl)", a missing argument as isError naming it, add {"sum":6.5}, fail
"it broke", a foreign Origin 403; plugin-tools.json written. Claude
Code (sandbox CLAUDE_CONFIG_DIR) `claude mcp add --transport http` +
`mcp list`: Connected. Not tried: a model calling a tool through a
real agent turn (no model in the sandbox). Binary and HOME removed.
2026-10-15 22:36:59 +08:00
yetone 8947ee7a10 plugin: a plugin's usage window keeps runsOutAt and runsOut through the host, so its credits' expiry reaches /v1/magpie/quotas, the Usage page and Smart routing (#2265, zhenghaowen0967)
usageOf() in host.js rebuilt each window from a list of fields that never
had runsOutAt/runsOut. 6f1b43275 added them to plugin.UsageWindow,
quotaOfPlugin and routing, and tested quotaOfPlugin directly, so nothing
went through the host and every plugin's run-out was dropped on the way:
workbuddy 0.1.14+ sends both on its Credits window, and Smart never saw
which account's credits end first.

The host now passes runsOutAt through when() (ISO or epoch s/ms, "" when
unreadable) and runsOut through num() (0 when not a finite number, never
negative), as the other fields are. Checked against every field of the
Go side's Usage, UsageResets and UsageWindow: these two were the only
ones missing. The auth.usage protocol comment and the plugin docs page
(en, ja, zh) say them, and the docs' usage example now shows
amount/limit/unit too, which it lacked.

Test: TestPluginUsage runs the fake plugin through the real host. Its
Week window says runsOutAt two days on (epoch seconds) and runsOut 80;
its Extra window an unreadable runsOutAt and a string runsOut, which
read as not known. Red on the old host.js ("week runs out <nil>, 0"),
green with it. Confirmed against the plugin source:
packages/workbuddy/index.mjs runsOutOf() returns
{ runsOutAt: ISO, runsOut } merged into the Credits window.

Run, both commits together on 5618ade1e: gofmt -l clean; go vet ./...
for GOOS=darwin and windows clean, GOOS=linux clean on the 68 packages
that don't import Wails (the root, internal/cli and internal/gui need
cgo for Linux, which a Mac cross-vet can't do); set -o pipefail; go test
-p 4 -timeout 40m ./... green (rc 0).
2026-10-15 08:03:20 +08:00
yetone 194b2fd3c5 plugin: the host keeps models.dev's catalog through a half-written refresh, and #1928's start test leaves a loaded runner room (#1928 review)
Review of Totopo27's bfd56fab (the commit before this one), which makes the
plugin host start without waiting on models.dev and read the catalog again
once it is written.

What this changes on top of it:
- host.js mdev(): catalog.Sync writes models.json in place, so a host
  listing providers during a refresh could read it half written. That
  read replaced the catalog it had with {}, and the Go side kept that
  list until its next refresh. A read that fails now keeps what was read
  before (a failed read means unknown) and is tried again next time.
  TestHostKeepsTheCatalogThroughAHalfWrite: red with bfd56fab's mdev()
  ("a catalog read half written dropped the catalog read before"), green
  with this.
- TestHostStartDoesNotWaitOnHangingModelsDev bounded a real bun host start
  by 3s, which a loaded runner can exceed. It now allows 15s within a 25s
  context: the old blocking start still fails it (the hanging sync holds
  the start until the context ends).

What was run at this head (Go 1.26.8, worktree of origin/main 429698f96,
private GOCACHE, sandbox HOME):
- gofmt -l: clean. go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...; go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build: all ok.
- go test -tags nogui -count=1 ./...: every package ok except
  internal/agent and internal/gateway, which hit the default 10m timeout
  at load average ~190, internal/edit's TestTOMLBigFileParsesInLinearTime
  (1.27s against a 1s bound, filed as #2219; passes alone -count=3) and
  gateway's TestIntentClassifierFails (#1829, passes alone -count=3).
  internal/agent, internal/gateway, internal/plugin, internal/catalog
  then ran with -timeout 60m: all ok.
- go test -race -count=20 on the three new plugin tests and on catalog's
  TestSync*: ok. -race -count=10 again with this commit's test: ok.
- A throwaway test dumping goroutines after the start and background-sync
  tests (and their Settle): none of hangModelsDev, syncLock or startOn's
  goroutine left.
- Broken by hand on bfd56fab, each red: forgetProviders() after the
  background sync removed (TestHostBackgroundSyncForgetsProviders);
  SyncIfMissing's Source() re-check removed
  (TestSyncIfMissingSkipsFetchWhenCacheAppearsWhileLocked, 1 request);
  ctx dropped from the lock wait (TestSyncHonorsContextLockWait, in 1s);
  mdev()'s read-once caching put back
  (TestHostReloadsCatalogWhenFileAppears); the blocking 30s sync put back
  in startOn (both subtests, startOn failed on the deadline after 30s).

Not tried: a real models.dev outage end to end in the GUI; the Windows
box. with_sync_in_flight still sleeps 50ms for its Sync to take the lock,
so it may test the "alone" case on a slow runner; it can't go red from it.
2026-10-14 23:52:15 +08:00
Luis Araya 78e337a20e plugin: sync models.dev in background and reload in host when available (#1928)
What:
- In internal/catalog, serialize Sync using a buffered channel (syncCh) so lock acquisition honours ctx.Done(), and add SyncIfMissing to avoid redundant downloads if a catalog appears while waiting for the lock.
- In internal/plugin/host.go, run catalog.SyncIfMissing in the background when starting without a cache, tracked by a WaitGroup and cancellable context so startOn never blocks on models.dev network I/O.
- Always pass catalog.CachePath() to host.js via modelsDevPath when Source() is empty.
- In internal/plugin/host.js, reload models.json in mdev() when the file appears or its modification time (mtimeMs) changes.
- In internal/plugin/providers.go, cancel and wait for in-flight background syncs in Settle() to guarantee clean test teardown.
- In internal/plugin/modelsdev_wait_test.go, install dial hook with sync.Once and an atomic stop channel to eliminate races and goroutine leaks, and add TestHostBackgroundSyncForgetsProviders to verify Cached() reloads upon background sync completion.
- In internal/catalog/sync_ctx_test.go, add TestSyncIfMissingSkipsFetchWhenCacheAppearsWhileLocked.

Why:
- In #1928, startOn blocked up to 30s when models.dev hung.
- Making Sync non-blocking during startup while allowing host.js to hot-reload once background sync completes gives fast startup on offline/slow networks without sacrificing catalog data.
- Context-aware lock acquisition prevents calls from stalling behind an active sync when their deadline expires.

What was run:
- go test -count=1 -tags nogui -v ./internal/catalog/... (PASS)
- go test -count=5 -tags nogui -v ./internal/catalog/ -run "TestSync.*" (PASS)
- go test -count=5 -tags nogui -v ./internal/plugin/ -run "TestHostStartDoesNotWaitOnHangingModelsDev|TestHostReloadsCatalogWhenFileAppears|TestHostBackgroundSyncForgetsProviders" (PASS)
- go vet -tags nogui on windows, linux and darwin (clean)
- gofmt -l (clean)
2026-10-14 23:52:15 +08:00
yetone 2076943915 plugin: a plugin declares its own switches, shown in its provider's editor and read by the plugin (#2038, Vocllum)
Vocllum asked that a plugin can offer the user generic on/off options
without magpie knowing what each one is for. A plugin now declares them
on its auth hook, beside checkin:

  auth.options: [{ key, label, description?, default?, confirm? }]

and reads the user's values through input.magpie.option(provider, key)
or input.magpie.options(provider). Each call reads the current values,
so a change reaches the plugin without a restart. magpie only keeps the
value and hands it over: nothing is scheduled or run when an option
changes. The check-in switch (settings.pluginCheckins) and the check-in
plugins are unchanged.

- host.js: optionsOf keeps a key matching [a-z0-9_-]{1,40} with a
  non-empty label, drops repeats, caps the label at 60 characters and
  the description and confirm at 300, takes default only when it is
  true, and keeps at most 16. The values come at init and through
  setProviderOptions.
- Go: plugin.Option, Provider.Options, OptionOn and SetProviderOptions
  (sent only to a host that is running). settings.PluginOptions is kept
  by the plugin's provider id, then the key. POST
  /api/settings/plugin-option {provider, key, on} checks the key the same
  way and hands the values to the host. The generic settings save keeps
  them, as it keeps PluginCheckins. /api/providers' plugins[].options
  carry each option's resolved `on`.
- GUI: a "Plugin options" field in a plugin provider's editor. Each
  option is a segs Off/On beside the plugin's label and description, put
  in with textContent. A confirm text is asked through confirmAction
  before turning an option on. Changes wait for Save, which posts each
  one before the provider. Strings are added for zh, zh-TW, ja and de.
- Docs: provider-plugins.md (a new section), reference.md, gui-shell.md
  and the tests README.

Run:
- TestPluginOptions (a real host with testdata/options). Red with the
  old host.js (no options listed) and red with setProviderOptions turned
  into a no-op (the plugin still reads the old value).
- TestPluginOptionSetting and TestSettingsSaveKeepsWhatItDoesNotSend.
  Both red with the generic save's PluginOptions line removed.
- plugin-options.test.cjs: 22/22 in Chromium and WebKit, at 1100 and 420
  wide, in en, zh, zh-TW, ja and de. Red on the old app.js (no field).
  The screenshots were looked at: long text wraps and the page has no
  sideways scroll at 420.
- provider-concurrency, plugin-signin, plugin-checkin, provider-price-rate
  and plugin-move-unserved: 68/68.
- go test ./internal/plugin/... ./internal/settings/... ./internal/gui/...
  ./internal/provider/..., gofmt -l, and go vet on darwin, linux
  (-tags nogui) and windows.

Not tried with a real community plugin, since none declares options yet.
The check-in row doesn't take a plugin-declared label or hint; it is
left as it was.
2026-10-14 08:50:41 +08:00
yetone 77f90fd84f gateway: a plugin whose config hook says searches: true is sent the client's web_search as sent (#2027, yudaleng)
A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api
relay whose quota the plugin reads) had no way to say its upstream runs
the hosted web search tool: searchesItself returned at once for any
signed-in account, letting only Codex and Grok through, so Claude Code's
WebSearch and Codex's web_search always went through magpie's own search.

Now a plugin's config hook can set `searches: true` on its provider, as
it sets `decide` (#1514). The host passes it through
(plugin.Provider.Searches), pluginProvider sets the provider's Searches,
and searchesItself honours it for a plugin's provider only, on Anthropic
or Responses and only where the plugin has a model on that API, the same
rule a custom provider's "Searches the web by itself" has (#359). Another
sign-in's Searches is never read; Codex and Grok are unchanged. As with a
relay, searchRank leaves it out, so magpie never picks it to search for
other models; Settings can name it by hand.

Documented in docs/subsystems/provider-plugins.md and the plugin guide
(site/public/docs plugins.html, en/zh/ja).

Verified:
- TestPluginSaidToSearch (new, gateway, through the real fake plugin on
  bun and New().Handler()): with FAKE_SEARCHES the plugin's upstream gets
  web_search_20250305; without it, it gets no search tool; Chat doesn't
  search and searchRank is -1 either way.
- Broken by hand, each red: search.go reverted, plugins.go reverted,
  host.js reverted (each "searches by itself on Anthropic: false"); with
  the searchesItself assertion disabled and search.go reverted, the wire
  check fails "said to search true, the plugin was sent []".
- TestMovedGrokSearchesItself, TestGrokPluginSearchesItself,
  TestWebSearch* pass.
- go test -tags nogui ./internal/plugin ./internal/provider ok, and
  ./internal/gateway (see the run noted on #2027) under a sandbox HOME
  with pinned caches; gofmt -l clean; GOOS=linux and GOOS=windows
  go vet -tags nogui on the three packages clean.
- Not tried with a real CPA/sub2api plugin.
2026-10-14 05:17:31 +08:00
yetone 3a53d06d99 provider, plugin: a subscription's sign-in goes through the proxy its account's requests use, not always the global one (#1663, demystify0137)
What changed: every sign-in started in magpie now leaves through the
account's own proxy (ProxyOfLogin: the account's, else the
subscription's, else the global one). Before, the sign-in's token
exchange and checks went through the global proxy while the account's
later refresh and usage calls went through its own (ViaLogin), so the
vendor saw one account come from two exits.

- signin.go: SignInOptions{Site, Proxy, User}, StartSignInWith; the flow
  picks its proxy (pickProxy, validated with settings.CheckProxy) and
  every request goes through s.via. Each built-in sign-in (Claude,
  Codex/ChatGPT, Grok, Zed, WorkBuddy, Copilot, ZCode, Factory, MiMo,
  Qoder, Command Code, Kiro) uses s.via; Claude Code's own login gets the
  proxy as *_PROXY (netproxy.EnvWith).
- proxy.go keepSignInProxy: a proxy picked for the sign-in is kept as
  the subscription's when the account is its only one, else as that
  account's own entry. "" (global) is refused while the subscription has
  a proxy and other accounts, since nothing could keep it.
- plugin host: authorize and callback run under via.run(proxy), so a
  plugin's sign-in fetches go through the same proxy; plugins_cli.go
  does the same for `magpie plugins login`. PluginAPIKey goes through Via.
- gui: POST /api/signin and /api/plugin-signin take proxy and user.

What was run:
- go test -tags nogui ./... (sandbox HOME), all packages ok.
- gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui on the
  touched packages.
- Red without the change (each broken by hand, then restored):
  TestSignInGoesThroughItsProxy, TestDeviceSignInGoesThroughItsProxy,
  TestPluginSignInGoesThroughItsProxy, TestClaudeSignInGoesThroughItsProxy
  (internal/provider) and TestPluginSignInProxy (internal/plugin) each
  fail with the s.via / EnvWith / via.run / keepSignInProxy removed.

Not tried: a real vendor account through a real proxy. The browser's own
leg of an OAuth sign-in goes through the browser's network, not magpie's.
Devin's CLI probes still use the global proxy.
2026-10-12 02:47:08 +08:00
yetone 1075991f90 gateway: a plugin's fetch is told the folder the agent works in and whether it is a git repository, never seeing magpie's own (plugins #86, Hipple)
A plugin runs in magpie's plugin host, so its process.cwd() is magpie's
folder. The ZCode plugin's Start Plan request said that folder
(C:\Users\<user>\.config\magpie) as the agent's "Primary working
directory", with "Is a git repository: no", and the model looked there.

forwardOnce now calls tellWorkPlace on every request to a plugin's
provider. It reads the request as sent to the plugin with workPlace (the
same reading rules by folder use) and sets two headers on the plugin's
fetch:
- x-magpie-work-dir (provider.WorkDirHeader): the folder, percent-encoded
  (url.PathEscape; decodeURIComponent reads it);
- x-magpie-work-git (provider.WorkGitHeader): yes/no. The agent's own word
  beside the folder (Claude Code's "Is a git repository: true/false",
  OpenCode's "Is directory a git repo: yes/no") wins. Otherwise it is a
  .git in the folder or above it, when the folder is on this computer
  (provider.GitSaid, provider.GitOnDisk in the new workplace.go).
Each is left off when unknown; a folder that isn't on this computer and
that the agent didn't call a repository has no git value, never "no".
host.js's fetch (unsaid) takes both headers off every request a plugin
sends, so a plugin that forwards the headers it was given sends them to
no vendor. Documented in docs/subsystems/provider-plugins.md.

Run: TestPluginToldWhereTheAgentWorks (new) sends the captured Claude Code
and Codex requests, and Pi-style ones from a temp repo subfolder and a
plain folder, through the fake plugin to fake-claude and fake-1. It checks
what the plugin read and that the vendor got neither header. Broken by
hand: without the tellWorkPlace call every case fails; without unsaid in
host.js it fails with "the vendor got X-Magpie-Work-Dir". go test
internal/gateway (-timeout 40m), internal/provider, internal/plugin;
gofmt -l; go vet on darwin, GOOS=linux and GOOS=windows for the three
packages.
2026-10-11 21:51:34 +08:00
yetone 2df2e0886d plugin, provider, gateway: a plugin's model is listed with every kind it takes and gives (audio, video, pdf), not image alone (#1595, tkhs101)
The plugin host read a model's capabilities.input only for "image", and
fromModelsDev hard-coded output to text, so /v1/models listed
opencode-zen-free's muse-spark-1.3-contributor-free (models.opencode.ai:
input text/image/audio/video/pdf) as ["text","image"] with no output.

- host.js: fromModelsDev and the config merge keep modalities.input and
  .output whole; the listing sends inputs/outputs, the kinds the
  capabilities object marks true, in OpenCode's order.
- plugin.Model gets Inputs/Outputs; pluginCatalog puts them on
  catalog.Model's new InputModalities/OutputModalities (input only where
  the plugin said what it takes, as ImageInput already is).
- catalog: models.dev entries and a vendor's live list (now reading
  modalities.output) fill the same fields; Decorate carries the catalog's
  when the live list says nothing, beside ImageInput.
- provider.Entry.Modalities() is what the gateway lists: the source's
  kinds, with "image" still decided by Images, so the user's own
  "takes images" override still wins and the other kinds stay.

Not changed: the 7 models the report lists as having lost their levels
have reasoning_options [] upstream (models.opencode.ai), so "reasoning,
no levels" is what they are; mimo-v2.6-flash turns away levels (#214).
DSH's model kinds and Muse's list still say text/image only.

Tests: TestPluginModelModalities (gateway) with the reporter's literal
metadata: muse-spark's config as opencode-zen-free 0.1.3's configModels
writes it, and mimo-v2.6-flash-free's capabilities as its models hook
lists them; a model said nothing of stays unlisted, and the image
override drops image only. TestFetchedModalitiesKeepEveryKind (catalog).
Broken by hand: host.js without inputs gives the report's [text image]
(red); Entry.Modalities without the Inputs branch (red); Decorate
without the fill (red). Run: go test catalog, plugin, provider, gateway;
gofmt -l; GOOS=linux and windows go vet on the four; go test ./...
green on 76db4c6c2+this; after rebasing on e9b16ca18 the four packages
again: catalog, plugin and gateway green; provider red once in a run of
all four together (the failing test's name was cut off by a tail), then
green 3 runs of 3, two of them concurrent.
2026-10-11 20:56:21 +08:00
yetone 93c5d846ca plugin: a plugin's requests to a host on the user's own network go direct, as magpie's own do (#1572, ggbdpq)
What changed: with a proxy set (magpie's, the environment's or the
system's), the plugin host sent a plugin's requests for a host on the
user's own network - a Remote magpie, an LLM relay on the NAS - through
that proxy, which can't reach it (502 Bad Gateway) or resolve its name.
Go's netproxy.Func leaves such a host direct since #982 (lan.go onLAN);
host.js's proxyFor and its node:http2 sessions (#1035) were that rule's
siblings without it.

- host.js ports lan.go's rule: onLAN takes a private (10/8, 172.16/12,
  192.168/16, fc00::/7), link-local, loopback or CGNAT (100.64/10)
  address, a .local name, or a name every address of which is one of
  those; looked up for 400 ms at most, kept a minute (256 names), a
  failed or slow lookup is "not on the network". It is asked only when
  the global proxy would be taken (after loopback, a provider's own
  proxy or "direct", and NO_PROXY), as Func asks it, so a user without a
  proxy pays no lookup and a provider's own proxy is still taken as is.
  IPv6 is compared on its bytes, so a v4-mapped address in hex form
  (::ffff:a00:1, how URL writes it) is judged as its IPv4 address.
- http2.connect returns its session at once, so tunnel() now takes a
  promise of the proxy and connects when onLAN has answered: straight to
  the host for one on the user's network, through the CONNECT otherwise.
  Unlike the issue's patch, a LAN name that needs a lookup is covered on
  this path too.
- The issue's patch was reviewed, not applied: its lanIP missed loopback
  and hex v4-mapped IPv6, it didn't strip a trailing dot, it never
  cleared its lookup timer, and it left HTTP/2 to LAN names proxied.

New TestPluginLeavesTheUserNetworkDirect (real Bun, a proxy that keeps
every target it is asked): a fetch to this computer's private address
over http:// (absolute form) and https:// (CONNECT; a certificate for
that address via NODE_EXTRA_CA_CERTS), to "localhost." (a name decided by
what it resolves to), and an HTTP/2 session to the private address all
reach the server directly; a public address (203.0.113.5) and a name that
resolves nowhere (vendor.invalid) still go through the proxy.

Run: the new test against the old host.js fails on all three fetches
(proxy asked for each); with only the HTTP/2 check removed it fails on
the session ("h2: proxyconnect tcp: 502 Bad Gateway"); with every host
taken as LAN it fails on the public address and the vendor name. A bun
check of lanIP over 24 addresses (both sides of every range) matched
lan.go. go test ./internal/plugin ./internal/netproxy ok; full
go test -tags nogui ./... ok in every package (the five whose build
hit another session's go-build cache prune were rerun, all ok: ., agent,
gateway, gui, library); gofmt -l clean; go vet -tags
nogui internal/plugin on darwin, GOOS=linux and GOOS=windows clean.
Not tried with a real NAS or Remote magpie behind a real proxy.
2026-10-11 14:07:21 +08:00
yetoneandFourLeafTec 4b2f2ec31e provider, plugin: a plugin can serve System One for its provider, and the models it marks are a routing group's classifier (#1514, FourLeafTec)
A plugin had no way to say its provider answers TypeSafe's System One,
so a free decision model a plugin reaches (mu-zi-lee/magpie-our-free-model)
could only be listed as a chat model.

Now the plugin's config hook sets `decide: true` on the provider, and
`decides: true` on a model, in the config hook or on the models hook's
list. host.js passes both through (plugin.Provider.Decide,
plugin.Model.Decides). pluginProvider sets the provider's Decide to its
own base, plugin://<id>/v1, so System One is asked at {baseURL}/systemone
through the loader's fetch with the account's sign-in: pluginFetch sends
nowhere but the loader's host, so an address the plugin named itself
couldn't be reached. AskSystemOne now sends with Provider.Do, as the
gateway's classifier already did, so the editor's test goes through the
fetch too (Do is client.Do for every provider without an account).

decide.go treats a plugin provider's decision models as the ones it marks
plus Jev's by name (jev-*): kept from agents, refused for chat ("only
decides"), refused as a group member, offered as a group's classifier
(Deciders, DecisionModels, Jev). A mark without `decide` on the provider
changes nothing. Docs: site plugins page (en, zh, ja) and
docs/subsystems/provider-plugins.md.

Thanks to FourLeafTec, whose reference commit (bc0b3fee in their fork)
proposed the two fields and the plugin base; this is written afresh.

Run:
- internal/gateway TestPluginServesSystemOne and
  TestPluginMarksWithoutDecide, through the real bun plugin host with the
  fake plugin (FAKE_DECIDE). Red with host.js, plugins.go and decide.go
  reverted ("Decide = \"\""), with only host.js reverted, and with only
  decide.go reverted (no classifiers, offered to agents, chat to one 200).
- go test -tags nogui ./... (temp HOME): every package ok; internal/gateway
  hit the 10m default at load ~140 in TestLargeRequestEndpoints, then
  passed alone with -timeout 40m (548s).
- gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui on
  internal/plugin, internal/provider, internal/gateway.
- Real use: a nogui build in a sandbox HOME on 127.0.0.1:3612, a local
  plugin declaring decide with judge-x marked, a fake vendor on 3613.
  `magpie group rule add ... classifier=dec1514/judge-x` saved; judge-x
  was not in /v1/models and not accepted as a member; a turn to the group
  asked /v1/systemone judge-x (levels, then intent) with the plugin's key
  and its fetch's own header, then went to chat-b; chat to judge-x
  answered 400 "only decides".
- No GUI change: a plugin's editor is the account editor, which has no
  address fields.

Co-authored-by: FourLeafTec <5875432+FourLeafTec@users.noreply.github.com>
2026-10-11 00:24:08 +08:00
yetoneandggbdpq 89271cd4e8 provider, plugin, settings: accounts left all zero by a crash are read from their last good copy, and every state file is flushed before it is renamed in (#1505, Zhangwier)
Zhangwier's Windows machine went down hard, and logins.json (10783 bytes)
and plugin-auth.json (29926 bytes) came back at full length with every byte
0x00. Every account was gone. The rename had reached the disk before the
data. magpie then read "no accounts", and its next write would have made
that final.

What changed:
- Flushed before rename: steady.WriteFile writes a temp file, fsyncs it,
  then renames it in. A failed write or flush removes the temp file and
  leaves the old file as it was. edit.WriteAtomic, Kiro's writer, the
  Codex session rewrite and the plugin host's writeDurable (host.js)
  flush the same way. So do writePrivate (providers, logins, migrations),
  settings, profiles, plugins.json, plugin-auth.json and mcp-signins.json.
- A last good generation: before each write, lastgood.Keep keeps the
  valid file there as <file>.bak. A file that isn't valid is copied aside
  as <file>.bad-<time>, with -2, -3 when two land in one second (O_EXCL),
  and is never overwritten before that copy exists. The .bak lags one
  write behind on purpose, since a crash zeroes the latest write.
- A failed read is unknown, never empty. On a cold start, logins.json,
  providers.json, migrations.json, settings.json, profiles.json,
  plugins.json, plugin-auth.json (Go and the host) and mcp-signins.json
  are read from their .bak when they don't read. The recovery is logged
  and listed in /api/state's recovered, and the window says it once in
  every language. With no good .bak, a sign-out leaves plugin-auth.json
  and mcp-signins.json as they are (the host's changeAuth no longer
  writes {} over them). magpie's own sign-out returns the error, and a
  sign-in copies the bad file aside before writing.
- caller-keys.json is flushed but never read from a .bak. A key revoked
  in the last write would come back, so a store that doesn't read still
  refuses every key, as its tests require.

ggbdpq's patch (f230bcae) is where the fsync-before-rename in
writePrivate, writeWhole and writeAuth came from. This change puts it in
one shared helper and reaches every other writer of magpie's state. The
JS write cleans up its temp file. The .bak recovery, the .bad copies and
the GUI notice are added here.

What was run:
- New tests, built from the literal case (10783 and 29926 zero bytes):
  - internal/lastgood
  - provider: TestZeroedLogins*, TestZeroedMigrations*,
    TestZeroedProviders*, TestWritePrivateSyncsBeforeRename
  - plugin: TestZeroedPluginAuth* against the real bun host,
    TestPluginAuthSyncedBeforeRename with a plugin that makes fsync fail,
    TestZeroedPluginList*
  - TestZeroedSettings*, TestZeroedProfiles*, TestZeroedMCPSignIns*
  - steady TestWriteFileSyncsBeforeRename, edit
    TestWriteAtomicSyncsBeforeRename
  - gui recovered-file.test.cjs (en/zh/zh-TW/ja/de, Chromium and WebKit)
- Broken by hand, each going red:
  - Without the sync: the steady, edit, writePrivate and host fsync tests.
  - Without the .bak fallback: every TestZeroed* test.
  - The old changeAuth writes "{}\n" over the zeros.
  - The old readLogins default.
  - KeepBad without suffixes fails the one-second test.
  - Without recoveredOnce, the GUI test fails 5/5.
- macOS: go test -tags nogui ./... in a sandbox HOME. The only failures
  were the two access tests (then fixed by not recovering caller keys) and
  TestProvidersCmdSaysUnreadable, which now removes the .bak to test the
  no-backup case. Both packages were rerun and pass. gofmt -l prints
  nothing. go vet, and GOOS=linux and GOOS=windows go vet -tags nogui, are
  clean on the touched packages.
- GUI: recovered-file, whats-new, click-scroll, gui-de, gui-ja,
  gui-zh-tw and i18n-keys pass.
- Windows box (cross-compiled test exes, sandboxed USERPROFILE/APPDATA):
  lastgood, steady, provider, plugin (real bun host), settings, mcpauth,
  edit and access pass. In profile, TestProfileSwitchesModelList and
  TestOldProfileKeepsModelList fail the same on origin/main (filed as
  #1517).

Reported-by: Zhangwier
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-10 22:54:09 +08:00
yetone f0c63264e5 plugin: a Node program a plugin starts takes magpie's proxy, as Node's fetch skips HTTPS_PROXY without NODE_USE_ENV_PROXY=1
larchsis on X (Windows 11, a proxy set in magpie, none in the system):
the "our free model" plugin's sign-in said 原渠道包下载失败. The plugin
downloads its channel pack in a Node program it starts. The host hands
such a program magpie's proxy as HTTPS_PROXY/HTTP_PROXY (since the grok
login fix), but Node's built-in fetch ignores those unless
NODE_USE_ENV_PROXY=1, so the download went direct and failed behind the
wall.

host.js's proxied() now also sets NODE_USE_ENV_PROXY=1 whenever it
hands the program a proxy, unless the plugin's env already names it
(a plugin's own value, 0 included, is kept). It is not lowercased.

Not changed: the Go side's netproxy.Env, which starts npm, Claude Code,
grok and devin. Those read *_PROXY themselves, and the proxy there may be
socks5://, which Node's env proxy does not take.

Run:
- TestPluginNodeTakesTheProxy (new) fails on the old host.js and passes
  now, on macOS and on the Windows box.
- go test ./internal/plugin/... passes.
- GOOS=windows and GOOS=linux go vet pass; gofmt is clean.
- End to end through the real host, on the Mac (Node 22.22) and on the
  Windows box (Node 22.22.2), with a throwaway plugin (not committed)
  that starts `node` to fetch https://raw.githubusercontent.com/ while
  magpie's proxy points at a fake 502 proxy:
  - old host.js: direct200, so it went past the proxy;
  - fixed: fetch failed at the proxy.
2026-10-10 18:11:00 +08:00
yetone 99009b9333 provider: a plugin's model pool counts a bare id with its @sizes, so a routing group's cursor/grok-4.7 is weighed on Cursor Models, not a used-up Other Models (Will on Discord)
Will's routing group keeps cursor/grok-4.7. Cursor's plugin (0.2.2/0.2.3)
lists Grok 4.7 only at its context sizes, grok-4.7@256k and
grok-4.7@500k, and its usage() builds the Cursor Models window's models
and Other Models' notModels from those ids. quotaOfPlugin matched a model
against those lists by the whole string, so bare grok-4.7 (which the
plugin still runs, at its default size) fell into Other Models: used up,
so the Routing page showed it 0% left and weighRouted ranked it last,
while composer-2.5 showed ~84%.

The window's lists are now an idSet: a bare id is in it when one of its
id@size is, and an id@size when its bare id is. Only the trailing @size
is taken off, so distinct models stay apart: another @size of a model,
another family member (grok-4), and other suffixes (ZCode's -Trial) still
match by the whole id. Every route that asks a plugin window whether it
counts a model goes through w.matches -> Limit.applies (routing's For,
Pace, Count, Renewal, fallback's Pooled, CapHeld, QuotaWindow.Counts for
the usage page's holds), so the one change reaches them all. host.js's
contract comment says so for plugin authors.

The plugin's own lists are also fixed in magpie-community/plugins (cursor
0.2.4 adds each listed id's bare name to its pool), for magpie versions
before this one.

Verified:
- TestPluginPoolCountsBareIDOfSizes (the reporter's literal ids) fails on
  the old code: "grok-4.7: used 100, want 16", "the usage page's holds
  count grok-4.7 in Other Models", "grok-4.8@1m: used 100, want 16";
  passes with the change.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags nogui
  on internal/provider and internal/plugin; go build for darwin, linux,
  windows.
- go test -tags nogui ./... green but TestNoCommandBypassesProc, red on
  main since 2da8fbe4 and fixed by b934d64a, which this is rebased on.
Not verified: against Will's real Cursor account.
2026-10-10 10:54:22 +08:00
yetone 7d0e415e62 plugins: two plugins that sign in to one provider are both listed, each row says which serves it, and Use for picks the other (neiko on Discord)
neiko on Discord installed a third-party plugin beside a plugin of their
own, added by its folder. Only the third-party one could be seen. Both
plugins' auth hooks name the same provider id. The host's auths() keeps
the last plugin in plugins.json for an id, as OpenCode does, so the
user's own plugin silently lost it:
- its row read "Signs in to nothing magpie can use";
- its provider was gone from the Add sheet;
- keepUnloaded could list the id a second time, from the
  plugin-providers.json kept before.
A package-name clash and a display-name clash were tried as well. Both
plugins stay visible in those cases, because a folder plugin's name is
its path.

What changed:
- host.js:
  - init gives each loaded plugin the ids it signs in to (provides) and,
    for each id another plugin serves, that plugin's spec (servedBy).
  - auths() honours plugins.json's new prefer map (id -> spec).
  - Only the serving plugin's provider.models hook runs for the id.
- plugin:
  - Clashes() turns provides and servedBy into {id, by, with} per spec.
  - Prefer() records a pick and restarts the host.
  - Remove drops the removed plugin's picks.
  - Re-adding a plugin under a new spec carries its picks over.
  - remove, off, options and prefer find a plugin by its exact spec
    before its package name (indexOf), so acting on one plugin never
    reaches another of the same package.
  - keepUnloaded no longer re-adds a provider from before when another
    plugin serves its id now.
- GUI:
  - /api/plugins rows carry clashes, with the provider's listed name.
  - POST /api/plugins/prefer {spec, provider}.
  - The serving row says "{other} signs in to {name} too; this one
    serves it".
  - The other row says, in amber, "{name} is served by {other}, which
    signs in to it too", with a "Use for {name}" button.
  - New strings in zh, zh-TW, ja and de.
- CLI: `magpie plugin` prints the same lines, with the command that
  fixes it, and `magpie plugin use <name> <provider>` makes the pick.
- Docs: docs/subsystems/provider-plugins.md, docs/reference.md and
  site/public/docs/{,zh/,ja/}plugins.html.

What was run:
- Reproduced under a sandbox HOME with magpie web on 3562: a fake npm
  plugin and a folder plugin, both on id "acme".
  - Old binary: the local row had providers [] and /api/providers
    listed acme twice.
  - New binary: both rows carry the clash; prefer moves acme to the
    folder plugin; remove clears the pick and leaves the other plugin
    serving acme.
- New Go tests:
  - TestTwoPluginsOneProvider, a real Bun host: Prefer, restart,
    off/on and Remove.
  - TestClashes, TestPluginNamedExactlyFirst and
    TestKeepUnloadedLeavesAServedID.
  - TestPluginsClashRows (gui) and TestPluginListSaysClash (CLI).
  - Each fails when its piece is broken by hand: prefer ignored in
    host.js, the keepUnloaded id check removed, name before exact spec,
    Remove keeping picks, no provides, no clashes in the rows, no
    prefer route.
- plugin-clash.test.cjs, in Chromium and WebKit, in en, zh, zh-TW, ja
  and de, at 1100 and 560px: 22/22 pass. It times out on the old
  plugins.js.
- gui-de, gui-ja, gui-zh-tw, i18n-keys and every plugin-*.test.cjs:
  248 tests.
  - 245 passed in the 4-wide run.
  - plugin-moved-signin (webkit) failed once in that run, then passed
    3/3 alone and 26/26 in a smaller 4-wide rerun.
- gofmt -l; go vet ./...; GOOS=linux and GOOS=windows go vet -tags
  nogui ./...; go build ./...
- The full go test -tags nogui ./... under a temp HOME with the caches
  pinned: 44 packages ok, none failed.
- After rebasing onto 05917100 (plugins.css conflict with a3a8e257's
  chip rules, both kept): plugin, gui and the root plugin tests, vet on
  darwin, linux and windows, and the 248 GUI tests above, all green
  (248/248 this time).

Not tried: a real third-party plugin, neiko's own plugins, and Windows
beyond vet.
2026-10-10 00:55:38 +08:00
yetone baecbb1be0 provider, gateway: Cursor moved onto its 0.2.x plugin gets Fast back, in the agent picker (#954) and for a Routing group's member, on the models Cursor has a fast variant of (#1360, loosheng: 插件 0.2.x 后 Cursor 的快速模式不见了,保存 cursor/<model>:fast 报 "has no fast mode magpie can ask for")
Plugin 0.2.x lists Cursor's picker once per context size (claude-opus-5-5@300k, @1m) and no -fast model, so CanFast, which looked for a -fast sibling, said no for every model: FastFor in route.go, canFast in the group editor, SetFastPick and cleanFast all go through it. The plugin itself still ran service_tier priority as the fast variant. opencode-cursor-auth 0.2.2 (magpie-community/plugins fb253f9) now says fast on a model listed at a size Cursor has a fast variant at; host.js passes it on as plugin.Model.Fast, CanFast takes it, and a plugin before 0.2.2 is still read by its -fast sibling. The Cursor mover asks for 0.2.2. On the way a fast request translated for a moved Cursor (Anthropic, Responses, chat not streamed) lost its service_tier: buildChat sets it only for host "cursor", and a moved provider's host is empty; buildHost names it.

Tested: the fake plugin lists sized models with fast on one (FAKE_FAST=tier); TestCursorPluginGroupFast (CanFast per size, @1m:fast refused, a group's @300k:fast sends priority), TestCursorPluginGroupFastSibling (the old -fast list), TestCursorPluginFastPick (moved: picker fast on chat, chat streamed, Responses and Anthropic sends priority, codex's doesn't). Without groupfast.go, host.js's fast or buildHost they fail. go test -race -tags nogui on gateway, provider, plugin, agent, gui; go vet, GOOS=linux/windows vet and build. With the built binary under a temp HOME, the real npm 0.2.2 plugin and Cursor's API answered by a preload (a picker fixture, the agent API's Run caught): /api/state offers fastFor on @300k and composer-2.5, not @1m or grok; /api/groups canFast the same; saving @1m:fast is refused, @300k:fast saved; opencode's picked @300k reaches Cursor's Run with fast=true on chat, Anthropic and Responses, codex's with fast=false. origin/main's binary in the same HOME offers none and refuses @300k. Not tried with a real Cursor account.
2026-10-09 05:32:36 +08:00
yetoneandClaude cdf325f178 plugins: a package that is only a command (an MCP server like magpie-x-search) isn't listed under Unreviewed, isn't added as a plugin, and one added before says what it is instead of a host stack (#1327, congee949)
A repository tagged magpie-plugin whose npm copy (from that repository)
names no file to load (no main, no exports) was listed and installed from
npm without the entry check the GitHub route has; it then failed every
host start with "has no entry" and a stack. Now:

- the Unreviewed list checks npm's copy the same way: one that names no
  file needs the index.js the repository's own route needs (askTagged);
- `magpie plugin add` / the Plugins page refuse a package that names no
  file, has no index file and is neither pi's nor a middleware, take the
  package just installed for it out again, and say it isn't an OpenCode
  or magpie plugin, and, for one with a bin, to add an MCP server under
  Library → MCP servers (notPlugin);
- the host says the same, without a stack, for one already on the list.

Run: TestCommandOnlyPackageIsNoPlugin (magpie-x-search 1.2.0's real
package.json) fails without the change (Add = <nil>; with only host.js
reverted, the stack message), TestTaggedRepos with the real GitHub
package.json and npm latest of cyberElar/magpie-x-search fails without it
(listed), both pass with it; TestNotPluginKeepsPlugins (index.mjs, main,
exports, middleware, pi, a file stay plugins). go test -tags nogui
./internal/plugin under a temp HOME ok; go vet -tags nogui for darwin,
linux, windows. The built binary in a sandbox HOME: `magpie plugin add
magpie-x-search@latest` from real npm prints the new error, and
plugins/package.json no longer lists it.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-08 23:09:25 +08:00
yetone 51d2cf88ea plugin host: a plugin's node:http2 connection goes through magpie's proxy like its fetch does (#1035, cataglyphis: Cursor opus-5-5 high ends after ~148s with "Cursor: 502 Bad Gateway" cursor_error) — the Cursor plugin runs agent.v1.AgentService/Run over node:http2, which Bun connects directly and ignores the proxy that host.js gives every fetch; the built-in sent the same request through s.client, so a user who needs magpie's proxy (setting, env or the system's) to reach Cursor had their sign-in, models and usage proxied but every Run went out directly. host.js now wraps http2.connect: for a URL proxyFor gives a proxy to (provider/account via, global, SOCKS bridged), it opens an HTTP CONNECT tunnel (Proxy-Authorization from the URL) and runs TLS with ALPN h2 over it; "direct", a caller's own createConnection and unproxied URLs keep Bun's connect; a tunnel that fails ends the session with "proxyconnect tcp: …". TestPluginHTTP2TakesTheProxy (an HTTP/2 vendor at an unresolvable host reached only through a CONNECT proxy; direct and a dead proxy fail with the reason) fails without the change ("h2: getaddrinfo ENOTFOUND h2vendor.invalid"; it carried 0) and passes -race -count=10. With the owner's Cursor account in a sandbox HOME and a logging proxy set, Claude Code's captured request on cursor/claude-opus-5-5 high: before, the proxy saw api2.cursor.sh only; after, it also sees agentn.global.api5.cursor.sh and the reply streams. The reporter's 502 wasn't reproduced here (direct runs answer in 4–20s). go test -race ./internal/plugin, the gateway/provider Plugin|Proxy|Cursor tests, gofmt and vet pass. 2026-10-06 22:16:24 +08:00
yetone 87487c5ef0 plugin, provider: a plugin can press its vendor's daily check-in itself (auth.checkin), and magpie runs it as its own check-ins (Lemon on Discord #feedback: provider 每日签到的方法能放到插件里面去做吗; ARNO earlier asked for Qoder's) — the check-ins magpie had (WorkBuddy, Trae CN, MiniMax Code, Qoder) are each written in magpie against the vendor's endpoint, even for a subscription that moved to its plugin, so a plugin author had no way to give their provider one. A plugin's auth hook may now have checkin(getAuth, provider) beside usage: the host lists the provider with checkin: true (plugin.Provider.Checkin) and answers checkin({provider, account}) (plugin.AccountCheckin), refreshing the account as usage does, with {outcome, credit, streak, message}; outcome is claimed, done, ineligible, inactive, captcha or failed, and a throw or an outcome outside these is failed with the reason. internal/provider/plugin_checkin.go runs these through checkin.go's checkiner, as the built-ins are: each signed-in account in use once a Beijing day (first look 2 minutes after start, then every 30), a failure asked again after wbCheckinRetry, every other outcome settled for the day, results kept in plugin-checkin.json by provider|account; a failure is recorded as failed and resets nothing. captcha is new (CheckinCaptcha): the vendor wants a captcha, which magpie never solves, so it is said as "check in in its own app", not as a failure, and not asked again that day. The results mark the account's Usage card (checkinBy "plugin:<provider>", WithCheckins), so the card's check-in row, its Auto check-in and Check in now work for it (POST /api/settings/plugin-checkin {provider, on}, POST /api/usage/plugin-checkin {provider}); Settings → Usage gains a Plugins tab, shown while such a plugin is signed in, a Daily check-in row per provider with Off/On and how each account went; magpie accounts checkin and c on the TUI's Usage page include them (the TUI's "no account" line names check-in plugins). The switch (settings.PluginCheckins, by provider) is off by default; for WorkBuddy, Trae CN, MiniMax Code and Qoder it follows that vendor's existing switch until set on its own, and magpie's own check-in through the plugin's fetch leaves a provider whose plugin checks in to it (pluginChecksIn), so no account is checked in twice. The Settings page's save carries PluginCheckins over (TestSettingsSaveKeepsWhatItDoesNotSend's fixture names it). No plugin declares the hook yet; Qoder's check-in stays magpie's own here. TestPluginCheckinRunsAsTheBuiltinsDo (the fake plugin with FAKE_CHECKIN, five accounts answering claimed, done, captcha, a throw and an unknown outcome: off presses nothing; on, each outcome kept with its vendor; a minute on nothing pressed again; past the retry only the two failures; the next day all five; PluginCheckins and the cards marked; another provider's press asks none) and TestPluginCheckinTakesOverTheVendors (a qoder plugin without the hook leaves magpie's Qoder check-in its account, with it none; PluginCheckinOn's fallbacks) pass -race -count=10, and the latter fails with pluginChecksIn stubbed false; TestTUIChecksPluginsIn passes -race -count=20. plugin-checkin.test.cjs (the card's row with the captcha said, Auto check-in posting {provider, on}, no page move; the Settings Plugins tab at 440px with the row fitting, no sideways scroll, On posting) passes on Chromium and WebKit in en, zh, ja and de; usage-checkin, i18n-keys, gui-ja, gui-de and settings-* pass. go test -tags nogui ./internal/..., go vet, gofmt -l, linux (nogui) and windows builds pass. Not tried with a real plugin or account: no published plugin has the hook yet. docs/subsystems/provider-plugins.md (the hook's contract) and docs/reference.md say it. 2026-10-06 18:40:45 +08:00
yetone bc00ee1df2 plugin, provider: a program a plugin starts has magpie's proxy, and a CLI login with no link says why (𝕏 on Discord)
The Grok plugin's sign-in said only "grok login gave no link to open".
The plugin host has magpie's proxy only as MAGPIE_*_PROXY, so the
`grok login` the plugin runs went out with none, where the built-in's had
it (netproxy.Env); where x.ai is reached only through a proxy, it failed.
host.js's spawn wrapper now gives a started program HTTPS_PROXY and
HTTP_PROXY (the account's own proxy, none for direct, else magpie's) when
the plugin set none.

grok 1.0.46, unable to reach x.ai, prints "Error: error sending request
for url (https://auth.x.ai/oauth2/device/code): …", whose URL the
built-in's runCLISignIn took for the page to open; a line saying error
gives no link, and a login with none ends with the CLI's last line. The
plugin does the same from 0.1.8, which the grok mover now asks for.

plugin_cliproxy_test.go and TestCLISignInSaysWhyNoLink fail before this.
Checked with grok 1.0.46 itself through the plugin host and the published
plugin's code, given a proxy that refuses: the CLI goes through it and the
error names what it said.
2026-10-05 22:25:33 +08:00
yetone 4788cf2bbd plugin, gui: a plugin's account whose model list failed says why, rather than listing Auto alone (gnayiab on X) — with magpie in WSL, Cursor's plugin account offered only Auto: the plugin's models hook couldn't get the account's list and magpie, with no list kept from before, showed the plugin's defaults with nothing saying so, its editor even calling them "vendor list", and Refresh answered "1 models". The host now keeps why a models hook fell back (what it threw, else how its last fetch failed) for the provider and each account; plugin.Cached carries it with the accounts it reads again from the sign-ins; provider.ListError gives it for a plugin's account. The editor says "<provider> couldn't list its models: <why>" under the models (amber, no left border) and no longer calls the defaults the vendor's list, and Refresh fails with it. A list kept from before, or one that comes in, says nothing. en/zh/ja/de. Tried with the real Cursor plugin (0.1.9) in a sandbox: a key Cursor refuses shows "Cursor couldn't list its models: Cursor didn't take this API key" and Refresh says it; the owner's real account lists 72 models with nothing said, and Claude Code -p through the gateway ran a Bash tool on cursor/auto, composer-2.5 and claude-opus-5-thinking. The plugin itself, in WSL (magpie-desktop), listed 254 models and streamed chats with tools. TestFallenBackListSaysWhy (hook returns its defaults, throws, or hands back its own) fails without the change; plugin-list-error.test.cjs (Chromium and WebKit, en and zh) too; TestFallenBackListKeepsTheLastOne, account-models, plugin-signin and click-scroll pass. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass. 2026-10-05 17:39:29 +08:00
Snowyy c38728145b plugin: a slow reader pauses its stream instead of racing a watchdog (#812)
* plugin: a slow reader pauses its stream instead of racing a watchdog

#664 gave a plugin reply a soft watermark (softQueuedBytes 4 MiB, softQueuedEvents 4096) and a 10-second idle watchdog: past the watermark, a reader that made no progress for stallIdle had its call failed with errStalledReader, and hardQueuedBytes/hardQueuedEvents (64 MiB / 65536) cut the reply outright. Both are guesses at how long a reader may take, and both end a reply that reader was still consuming.

The host now hands each fetch a credit window instead. Go grants streamWindow (512 KiB) up front and returns credit as the reader takes bytes, so the child stops producing at the window instead of being timed out; the window is charged per delivered byte plus frameOverhead (2048), so a run of tiny frames cannot fill it with metadata. streamBudget (64 MiB) and maxFrame (64 KiB) bound a whole reply and a single frame, and a child that sends past its window is a protocol violation (errProtocolOverrun) rather than a slow reader.

The plugin side grew the matching gate (makeGate, gate.take/spend/add, waitDrain): a fetch holds at the window until Go credits it, and its pending writes are cancellable. Cancellation and shutdown now have one owner per call - a five-state lifecycle (sending, active, draining, aborting, released) whose single transition helper disposes the queue, detaches the watcher, commits the terminal answer, creates the abort and returns capacity exactly once - so a host failure, a Close, a cancelled context and an already-delivered reply can no longer race each other over who cleans up. A reply the host already delivered keeps its bytes and its vendor outcome when the host dies.

Tests: the JS cancellation cases run the production sections with controlled stdout backpressure (stopped gate, split chunk, terminal suppression, acquired-body cancel, 30,000 cancelled bootstrap waits with no retained waiter or ready reaction); the Go cases drive lifecycle orderings directly (terminal-before-failure, failure-before-terminal, abort acknowledged before capacity returns, blocked enqueue), and the shutdown, body-close and mid-setup-cancel cases block on explicit channels instead of sleeping. TestFlowBigReplyProd reads 100 MiB non-SSE and SSE through the real host and checks lengths and SHA-256, including a 12 s reader pause. CI installs Bun 1.4.2 on Linux and runs that case in its own step, since the plugin sandbox skips when bun is not on PATH.

* plugin: the stream-head credit test waits for the credits before the reply ends (CI, macos-latest: TestHostStreamHeadChunksFinal failed on the macOS runner with "the credits were given back didn't happen", while the same package passed on ubuntu-latest and locally) — the test sent the child's final answer together with its 50 chunks, so the call could be marked stopped and its pending credits dropped before waitFor saw them; a completed fetch needs no credit, so waiting longer could not recover them and the expectation was a race, not a real accounting bug. The final answer is now withheld until io.ReadFull has taken the 140 payload bytes in order and exactly 140 + 49*frameOverhead credits have been observed with frameOverhead still owed, and only then does the child answer and the test assert a zero-byte EOF read. No production code changed.

Tests: go test -run '^TestHostStreamHeadChunksFinal$' -count=500 ./internal/plugin/ and -count=200 -race pass; go test -count=1 and -race -count=1 ./internal/plugin/... pass; gofmt -l and git diff --check clean.
2026-10-05 01:36:20 +08:00
yetone 67092380fb plugin: pi packages run as pi runs them — a program a login starts can't take the host's stdin, a select is answered with its option's id, and the extensions get pi's runner, pi's auth.json and session_start (owner: 都补上,用真实账号测) — tried with real accounts, five pi packages had problems that the fake one didn't show. pi-devin-plus runs devin auth login with stdio "inherit" when it finds no Devin sign-in, and the program read magpie's next requests from the host's stdin as its answer ("Login canceled") while writing over its answers; host.js now gives every program started through Bun.spawn and Bun.spawnSync (all of node:child_process goes through them) nothing to read and stderr to write. pi-zcode asks its region with onSelect and options { id, label }, pi's own shape, and checks the id ("bigmodel"); pi.js answered with the label, so the login said "Login cancelled". Packages read their sign-in back from pi's auth.json (readStoredCredential: pi-zcode for its plans, pi-cursor for its token, pi-provider-qoder through the registry, pi-antigravity syncs its accounts through it) and register what they find on session_start (pi-zcode its plans' models, pi-devin-plus and pi-xai-oauth refresh their catalogs), and a provider registered after loading went into a queue nothing read. Now each package is bound with pi's ExtensionRunner as pi's session binds it (bindCore: no UI, tools or session of magpie's), so a later registerProvider reaches the runtime; each pi provider's first account is kept in $PI_CODING_AGENT_DIR/auth.json as pi keeps it, written when it changes; and a provider newly signed in, and each one signed in when the host starts, is sent session_start, after which magpie lists its models again if they changed. A runner that can't be made leaves the packages registered as before. TestPiPackage now has a select answered with an id, a login that starts a program on the terminal, and a session_start that reads the sign-in from pi's auth.json and adds a model; it fails on the old code (the label answered; the model never listed, auth.json empty) and passes. With real accounts in a sandbox HOME: pi-zcode signed in through Z.ai and lists 11 models (none before); its requests reach ZCode but the account's Start Plan answers 200 {"code":1005,"msg":"exceed quota limit"}, which pi-zcode reads as an empty answer (its bug). pi-provider-qoder signed in through Google, 16 models, tool round trips on Kimi-K3 and Efficient. pi-devin-plus signed in, its catalog refreshed on session_start (53 models), tool round trips on swe-2 and claude-opus-5.5; pi-xai-oauth (grok-4.7) and pi-antigravity (gemini-3.8-flash) tool round trips; @rahularya01/pi-cursor answers text (its agent doesn't call a client's tools, upstream). pi-provider-kiro wasn't signed in: it needs pi's terminal, a Builder ID or an IdC login. go vet, builds (darwin, GOOS=linux -tags nogui, GOOS=windows) pass. 2026-10-03 22:51:24 +08:00
yetone 1baad0d2d4 plugin: pi packages are plugins as OpenCode's are — a pi coding agent package (its extensions) adds providers to magpie: their models, their sign-in, renewals and requests (owner: 我希望全面兼容 pi 插件!!!!!!!!!!) — a package is pi's when its package.json has a "pi" manifest, the "pi-package" keyword, or pi-coding-agent among its dependencies (IsPi, mirrored in host.js). Adding or updating one installs @earendil-works/pi-coding-agent beside it, and the plugin host loads every pi package through pi's own loader (pi.js: discoverAndLoadExtensions and ModelRuntime, with the credentials kept in plugin-auth.json), so an extension's registerCommand, registerTool and pi.on are taken and left unused, and its registerProvider calls become magpie providers. A provider's models keep their context, output, images and the reasoning levels their thinkingLevelMap allows; its OAuth login runs as pi runs it, each onPrompt asked in magpie's sign-in in turn, onAuth's page opened, a later prompt being the code pasted back; a provider with apiKey takes a key; magpie renews through refreshToken and saves the result. Requests arrive as Anthropic Messages and go to pi's stream: system and tools, images, tool results, thinking budgets and effort as the nearest level the model has (and the least it allows when it can't turn thinking off: Antigravity's gpt-oss refused requests without one), max_tokens held to the model's; the answer comes back as Messages SSE or JSON with thinking and its signature, redacted thinking, tool calls (their thought signatures kept for the next turn), usage, and a failure before anything is said as the vendor's status with Retry-After. The Plugins page's search also finds pi packages that bring a provider. Tried with the owner's real Antigravity account through pi-antigravity, next to the Grok OpenCode plugin in the same host: 14 models listed, Gemini streaming with usage, Claude Sonnet thinking with signatures, gpt-oss, tool round trips on gemini-3.8-flash, gemini-3.1-pro and claude-sonnet-4-6, a 400 and Antigravity's 429 passed on with their status. A Claude Code turn didn't get through: Antigravity answers 429 to any system prompt with Claude Code's billing header or its "Claude agent" line, through magpie's built-in Antigravity just the same. TestPiPackage (a fake pi package: models, an OAuth login asking twice with a wrong code then a right one, a key, streaming and JSON answers, thinking and tool signatures back, a 429, a renewal) and TestSearchFindsPiPackages pass. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass but TestClaudeRunEndsWhenTheClientLeaves, TestProvidersAnswerWhileListsComeIn and TestSavedButSignedOutClaudeServed, timing tests that pass alone. 2026-10-03 19:12:19 +08:00
yetone 37809ac722 usage: WorkBuddy's credits are said beside their share — on the Routing page, the Usage page and the menu bar, used or left as the share is (#659)
Moody-Sin: the Routing page showed a WorkBuddy account as "已用 71%" only, which for a plan counted in credits says little. A quota window now carries its own count when the vendor counts in amounts — amount of limit, in unit (QuotaWindow, QuotaSpan for quota --json and /v1/magpie/quotas, and the routing trace's Weighed, from the window its share is of: Allowance.Count). WorkBuddy's built-in fills it from the resource summary, and @magpie-community/opencode-workbuddy-auth 0.1.8 tells it from auth.usage (amount / limit / unit, passed through host.js); the workbuddy mover's min is 0.1.8. The Routing page's stage and its list of what each account did, the Usage page's meter, the menu bar's tooltip and the TUI say "3,550 / 5,000 credits · 71% used", or "1,450 / 5,000 credits · 29% left" with Left on (积分 in Chinese); a window counted in shares alone reads as before.

quota-credits.test.cjs (WebKit, en/zh, used/left, Routing and Usage pages) fails on the old assets and passes; TestQuotaWindowCount, TestAllowanceCount, TestTraceTellsTheCount, TestPluginUsage (the count through the host) and TestWorkBuddyAccounts cover the Go side. Tried with the real WorkBuddy and WorkBuddy AI accounts in a sandbox magpie: moved onto the local plugin, /api/usage/quotas gives 33.29 / 3900 and 13.47 / 2250 credits and the Usage page reads "33.29 / 3,900 积分 · 已用 0.9%", "3,866.71 / 3,900 积分 · 剩余 99.1%" after a click on the count; not moved, the built-in gives the same for WorkBuddy. The Routing page with two real accounts of one provider wasn't tried (one account each). go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass.
2026-10-03 16:45:48 +08:00
yetone 123594489a plugin: a host stopped mid-renewal saves the new token first, and two hosts never write each other's sign-ins away — a stopped host (quit, plugin update, restart) was killed 2 s after stdin closed even while it renewed a sign-in through auth.refresh, after the vendor had spent the old refresh token, so the account was signed out; and while a host restarts the old one and the new one both rewrote all of plugin-auth.json from what each had read, so one host's save could drop the other's accounts or newer token. host.js now tells magpie how many renewals are under way (event "renewing"), and stop gives a host still renewing after the 2 s up to 15 s in all, until the renewal is saved; with none it stops as fast as before. Every change to plugin-auth.json (setAuth, removeAuth, settle, take, auth.set, a renewal's save, and magpie's SignOut when no host runs) is made under plugin-auth.json.lock (O_EXCL, broken when older than 10 s), reading the file afresh and changing only its own accounts; a renewal's save checks under the lock that the stored sign-in is still the one it renewed, so an older host never writes a stale token over a newer one. TestStopLetsARenewalEnd (a 4 s refresh, the host restarted in the middle: old code kept the spent token) and TestTwoHostsKeepEachOthersSignIns (two hosts saving 40 accounts each at once: old code lost 38 of 80) fail on the old code and pass; TestStopWithoutRenewalIsQuick keeps the quick stop. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass but TestProvidersAnswerWhileListsComeIn and TestClaudeSignedOut, timing tests that pass alone and in their packages rerun. Not tried with real plugin accounts. 2026-10-03 15:47:10 +08:00
yetone f0e4a79c06 plugins: auth.refresh — magpie renews a plugin's sign-ins before they run out, once per account at a time (owner: 按你建议的优先级,先做 1 和 2, from the pi plugin study) — each community plugin renewed its own tokens inside fetch, deduping by hand (factory's "two refreshes would spend it twice", minimax's renewing, cline's REFRESH_LEAD, workbuddy's EARLY_MS). A plugin can now give auth.refresh(auth, provider), returning the fields to keep over the old sign-in, and optionally auth.refreshLead (ms, 5 minutes by default). Before an account's loader options, provider.models and auth.usage, the host renews an OAuth account whose expires is that close: requests that find it due share one renewal (vendors that spend a refresh token once never see it twice), waiting up to 15s, and a renewal that takes longer is still saved when it ends (pending keeps the host up). What it gives is merged over the account and saved through setAuth, which clears the loader caches here and in Go, and the account is said renewed; a sign-in replaced or removed meanwhile stands. A throw leaves the account as it was and the request goes with the old token; signIn: "expired" on it marks the account and it isn't tried again until signed in again, any other error is retried after 30s. OpenCode ignores the hook, so plugins keep their in-fetch check for it. Documented in /docs/plugins (#renew, en and zh). TestPluginRenewsSignIns fails without the host change (no renewal). go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-03 03:08:15 +08:00
yetone 33acb6bca0 providers: each model's credit rate shows by it in the provider's model list and an agent's model picker, Qoder's 0.5× and WorkBuddy's 0.03×, a discount's price before it struck through (01huadalang on Discord: qcoder 或者 workbuddy 能不能实时抓取或者按一段时间抓取能展示列表模型的积分消耗倍率,这样不用打开软件查看,能选择到便宜的模型) — magpie read each model's price only to tell free from not: Qoder's price_factor (06584e15) and WorkBuddy's "credits" ("x0.03", wbFreeCredits), so the lists said FREE or nothing, and picking a cheap model meant opening Qoder or WorkBuddy. catalog.Model now keeps the price, Rate (the credits a request costs, as a multiple; 0 is not listed, or Free) and RateWas (the price before a discount running now), and carries both through provider.Entry, agent.Option and the providers page's models. Qoder (and Qoder CN): Rate is the price_factor; RateWas an active promotion's before_promotion_price_factor, else an original_price_factor above the price (Qwen3.8-Flash: free, 0.1× struck through), and a promotion's 0 that isn't free is its price before times its discount_factor. WorkBuddy and WorkBuddy AI (the CodeBuddy plan; both builds read the same /v3/config): Rate is the credits (wbCredits; x0.00 stays FREE, an unreadable or infinite rate is none). A plugin's model gives it as it gives free: rate and rateWas on the model its provider.models hook lists, a number (0.5) or as the vendor writes it ("x0.03", "0.5×"), which host.js reads (rateOf) into plugin.Model.Rate/RateWas and pluginCatalog keeps; the moved Qoder and WorkBuddy users get it once their plugins send it. The badge is small and grey (the context badge's colours, no uppercase), beside FREE where that shows, its title saying what a request costs (每次请求消耗 0.5× 积分;折扣前 / 限时免费,原价). Rates are as of the provider's last list: a built-in's is fetched at start-up when it has none, on Refresh and when its key changes, a plugin's when its plugins are asked again (start-up, a sign-in, a plugin change); nothing asks on a timer. Kiro, Cursor, ZCode and Devin list no per-model rate magpie reads, so they show none. TestParseModelsRate (qoder) and TestWBCreditsRate (provider) are new and don't build without the change; TestFakePlugin now checks a plugin's rate given as a number and as "x0.03" (0 for both with host.js not reading them). model-rate.test.cjs (WebKit, en and zh: the chips' badges and titles, struck-through prices, grey not green, no stripe, a click picks and scrolls nothing, the picker's badges) fails without the change and passes with it; click-scroll, models-free-only, model-pick and favorite-star pass in WebKit. No request was made to Qoder, WorkBuddy or any vendor. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME, go test ./internal/gui pass. 2026-10-02 22:48:45 +08:00
yetone 987d72c133 providers: Max concurrent requests — over it, an agent's requests wait in line and go out in the order they came (Lemon on Discord: 希望 provider 或者插件能够支持一个参数类似 max_concurrency,如果超过上限,放到无界队列里面依序请求; Memo: ChatGPT/Codex subscriptions' risk control trips at about 5-6 requests at once) — the gateway sent every request to its provider the moment it came, so a few agents (or one agent's subagents) on one subscription could have any number out at the vendor at once, and nothing in magpie could hold them to what an account takes. A provider now has maxConcurrency (providers.json; nil or 0 is no limit, a negative one is saved as 0), and a signed-in agent's accounts keep theirs with their picks. The limit is per key or account, as the gateway already tells them apart (candidate.who(): provider#keyid, provider@user, else the provider), so a subscription pooling several accounts lets each one have that many out. Before a try is forwarded it takes a slot in that lane (internal/gateway/concurrency.go); with none free it waits in a FIFO queue with no bound, and is let in, first come first served, as one before it ends. The slot is held for the whole try (attempt reads the vendor's reply to its end or until the agent hangs up, and its body is closed when it returns) and given back once whatever happens (sync.Once), and a lane with nothing out and no one waiting is dropped. An agent that hangs up while waiting leaves the queue at once, is never sent and takes no slot (a slot granted in the same instant is handed on), and goes the way of any canceled request (499, nothing recorded). Waiting is not a failure: a request in line stays for its provider and is not moved on to a fallback or another group member, the account isn't rested, and the time it waited is told in its route's try (Try.Queued, ms). A plugin can say how many each of its accounts takes, as its own field: the auth hook's maxConcurrency, else package.json's magpie.maxConcurrency (a whole number over 0, at most 1000); the user's setting on the provider goes over it. GET /v1/magpie/concurrency (local or shared callers, as quotas) gives each lane's out, waiting and limit. The provider editor (keys, custom, signed-in accounts) has "Max concurrent requests" / 最大并发请求数 under Proxy, "超出时排队,按顺序发出;0 或留空为不限制" below it (with a plugin's own number as its placeholder), refuses anything but a whole number from 0 to 1000 before anything is posted, and an empty field saves none (the plugin's, if it has one); a save that doesn't send the field keeps what the provider had. No coloured left border, and a click in the field leaves the page where it is. TestMaxConcurrency (limit 2, five streams: never more than 2 at the vendor, 3 waiting, let in a..e in order; one canceled while waiting leaves the queue, takes no slot and never reaches the vendor; slots given back when each stream ends and when an agent hangs up mid-stream; the next one served at once) fails without the change (all five reach the vendor at once, no lane), as do TestLanesLimitLifted, TestProviderConcurrency and the updated TestPluginOwnIconAndKeyHint (the auth hook's 3, package.json's 5 when the hook's is 2.5); provider-concurrency.test.cjs (chromium and webkit, en and zh: typed and saved, 2.5 refused with nothing posted, empty saved as null, an account opening on its 5 and saving 0, a plugin's 4 as the placeholder, every string translated, no stripe, no scroll on click) passes. No vendor was asked. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... (under a temp HOME) and go test -race on the new tests pass. provider-proxy.test.cjs's account test fails the same on HEAD without the change (its editor redrawn under it). 2026-10-02 13:38:23 +08:00
yetone 2a6ba1a20f workbuddy: an added account is told from the others by its uid, and the one WorkBuddy is signed in to stays once WorkBuddy moves on (#413: 添加已提前登录的 WorkBuddy 账号会顶掉默认第一个账号) — magpie matched a new sign-in to a listed account by its name, the nickname: another account of the same nickname replaced the one listed, or was taken for WorkBuddy's own and let go with "signed in". And WorkBuddy's own account is only read from WorkBuddy's file, so signing WorkBuddy in to the next account (to pick it on WorkBuddy's page from magpie) renamed that row, the last account gone, and the one picked, being WorkBuddy's own, was let go: one account at a time. A WorkBuddy or WorkBuddy AI sign-in is now matched by its uid (one of the same name whose uid isn't known is still taken to be it, #155); another account of the same name is added as "name (end of uid)"; the same account renews its sign-in where it is listed, and the one WorkBuddy is signed in to becomes magpie's own sign-in of it, first as it was, so it stays when WorkBuddy signs in to another. The sign-in says so: "该账号已在列表中,已更新登录" in the app, "is already listed — its sign-in was renewed" from magpie accounts add. On the plugin, the host no longer takes two sign-ins of one account id for one account when their uids differ. No request header or user agent changes. TestWorkBuddyAddSameNicknameAsOwn, TestWorkBuddyAddSameNicknameTwice, TestWorkBuddyAddWhatWorkBuddyIsSignedInTo, TestPluginSameNameOtherUID and signin-again.test.cjs fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; signin-again, click-scroll, old-webkit pass. 2026-10-01 19:38:36 +08:00
yetone 4f9dcb39e5 plugins: a plugin subscription goes through every path a built-in one does (the user: 要保证插件订阅 provider 跟内置的订阅 provider所有逻辑都要一模一样) — a SOCKS5 proxy on a plugin provider or account now carries its requests: Bun speaks http(s) proxies only, so magpie stands a loopback http proxy in front of the SOCKS one, and a proxy that refuses says so as Go's transport does. A plugin's model list and its loader are asked through the account's own proxy, as a built-in's list is fetched through it. The Grok plugin draws and makes videos at Grok's Imagine API through the plugin, and keeps Codex's namespaced tools, as the built-in does; an official plugin beside its built-in (kiro-plugin, zcode-plugin) counts tokens by estimate as the built-in and the moved plugin do. FetchNew no longer re-lists plugin providers every ten minutes, their list being told by the plugin host; a plugin account's usage is cached under one name whichever way it is asked for; and a fetch hook that throws on its sign-in (a refused refresh) marks the account lapsed, as a built-in's refused refresh does. TestPluginSOCKSProxy, TestPluginModelListThroughAccountProxy, TestGrokPluginDraws, TestPluginBesideBuiltinCountsByEstimate, TestFetchNewLeavesListedPlugins, TestPluginUsageReadOnceWhicheverName and TestPluginFetchSignInExpiredLapses fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (the known load flakes pass alone); internal/plugin, netproxy and the plugin/proxy tests of provider and gateway pass on Linux and Windows. 2026-10-01 19:07:12 +08:00
yetone 8cd520662f plugin: a plugin can say the list it hands back is a fallback, and magpie keeps the one told last, as a built-in does — Command Code's Go accounts and ZCode give a table of their own when their vendor's list can't be had, not the defaults they were given, so magpie couldn't tell it from a list read and a hiccup swapped the models for the table. A models hook's list marked Symbol.for("magpie.fellBack") (OpenCode never sees a symbol's key) now counts as fallen back; commandcode 0.1.7 and zcode 0.1.6 mark theirs. TestFallenBackListKeepsTheLastOne/throws=own fails without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./internal/plugin ./internal/provider pass; internal/plugin passes on Windows and Linux. 2026-10-01 17:06:17 +08:00
yetone ca29a7badd plugin: a plugin whose models hook throws keeps the list it told last, as a built-in does — 9abf441d kept the last list for a hook that gave its defaults back, but Cursor's, Grok's and Devin's hooks throw when their vendor fails, and an account past the first whose hook threw was taken to have all the provider's models; a vendor's hiccup still swapped the list for the plugin's defaults. A hook that throws now marks its listing fallen back, the provider's and each account's, and magpie keeps the list told last in its place. TestFallenBackListKeepsTheLastOne/throws=1 fails without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; internal/plugin passes on Windows, internal/plugin and internal/provider on Linux. 2026-10-01 16:56:41 +08:00
yetone 9abf441dfa plugin: a plugin whose model list can't be fetched keeps the one it told last, as a built-in does (ARNO on Discord: the Command Code plugin lists no Pixel Canary, the built-in does) — a built-in whose fetch fails keeps catalog.Live, the list it fetched last, while Command Code's, Kiro's, Qoder's, WorkBuddy's and Zed's plugins catch the failure and give their short defaults back, so a vendor's hiccup shrank the models. The host now sees a models hook that asked its vendor, had no answer from its last ask and handed back the list it was given, and marks that listing; magpie keeps the provider's and each account's last told list in its place, in memory and from plugin-providers.json after a restart, and the vendor back, its list is told again. TestFallenBackListKeepsTheLastOne fails without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; internal/plugin and internal/provider pass on Windows and Linux. 2026-10-01 15:01:11 +08:00
yetone 7dd809002b accounts: on Linux an account put first is read first at once, and on Windows a file being replaced isn't read as none (goal: 插件订阅 provider 跟内置的所有逻辑都要一模一样, run on Windows and Linux) — the provider tests run on the Windows test box and in WSL found two bugs of magpie's own files. Linux stamps a file's time from a clock a tick (a few milliseconds) coarse, and filememo took same time and size for the same file: two accounts swapped (Devin, Grok, WorkBuddy, ZCode, Claude…) read back in the old order, so magpie kept using the account the user had just moved down, and a moved-back plugin's accounts read as before. A file written within the last two seconds is now also compared by its bytes. On Windows a file being renamed over refuses to open for a moment ("Access is denied"), and one held open refuses to be renamed over: plugin-auth.json, plugins.json and the plugin providers read as nothing (a usage fetch right after a move showed no cards), logins.json failed to save, and host.js, reading plugin-auth.json as {}, would have written the other accounts away on the next sign-in. New internal/steady waits such a read or rename out (half a second at most, Windows only); filememo, edit.WriteAtomic, writePrivate, Kiro's writes and the plugin store go through it, host.js retries its read and rename, and the plugin store writes its files by a rename. Tests: USERPROFILE beside HOME in the test homes, the fake devin (a shell script) skipped on Windows, plugin-auth.json's mode bits unchecked there. TestReadSameSizeSameTick fails on Linux and TestRenameOverAFileHeldOpen/TestReadAFileHeldOpen on Windows without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; on Linux (WSL) the provider and plugin packages pass whole (13 failed before), on Windows the plugin package and the move/plugin/Grok/Devin/usage tests pass 10 times over (TestMoveToPlugin failed one run in a few before); 15 built-in tests that assume Unix (mode bits, Keychain, shell-script CLIs) still fail there, as before. 2026-10-01 13:27:12 +08:00
yetone 4ba51bb627 plugin: a plugin names its own icon and the key field's title and hint (Lemon on Discord) — a plugin's provider took only the market's icon, and an api method's key field always read "<name> API key" with no hint. auth.icon (or package.json "magpie": {"icon"}) as an https URL, fetched once through the public-only icon path, or a data:image URI now comes before the market icon; an api method's label titles the key field as in OpenCode, and a new placeholder hints it, in the window and in magpie plugin login. README has a For plugin authors section. TestPluginOwnIcon, TestPluginOwnIconAndKeyHint and plugin-key-hint.test.cjs (Chromium, WebKit, en/zh) fail without the change. 2026-10-01 11:42:45 +08:00
yetone 77c2ad12fa migrate: a move that fails leaves nothing behind and says why, and a move only goes through on an account the plugin proved works (要保证插件订阅 provider 跟内置的订阅 provider所有逻辑都要一模一样 / 记得把整套迁移逻辑做得丝滑优雅精致优美简单方便易用) — a failed move left the plugin it had installed (a Plugins row saying signed out) and hidden plugin:<id> rows in logins.json, and a move checked only that the plugin loaded, so an account the vendor refused or couldn't be reached through moved as if it worked. The plugin a move installed now goes with a failed move, and with a move back when it serves nothing else; the stray rows go; the check reads each account's usage as well as its models, and an account the vendor refuses is marked and moves untried, as a lapsed one does, while one whose vendor can't be reached at all fails the move with nothing changed. A move with every account lapsed says so before installing anything. Failures carry a code (offline, install, lapsed, unserved, account) for the page to say in its language, with the models named, not their ids. A moved provider shows the built-in's API host (magpie providers showed the plugin's id), and Zed's accounts take their model list with them, so the plugin can serve it until it reads its own. TestMoveNeedsAWorkingAccount, TestMoveTidiesItsPlugin, TestMoveProvesEachAccount, TestMovedShowsBuiltinHost and TestZedMoveCarriesItsModels fail without the change. go vet, go build -tags nogui, go test -tags nogui ./... pass. 2026-10-01 11:15:23 +08:00
yetone 813fdcb2e5 migrate: a moved built-in keeps its models' reasoning levels, its own account's plan and one own row, and the move checks each account through its proxy (要保证插件订阅 provider 跟内置的订阅 provider所有逻辑都要一模一样) — Command Code's, Grok's and WorkBuddy's models their vendor gives no levels for lost the ones the built-in borrowed from their maker; moved, they borrow them again. Devin's own account moved without the plan the Devin CLI says, which the built-in showed. The agent signing in to another account while moved wrote a new own row for the built-in, which came back beside the one set aside as a second own account; nothing is written while moved, and going back keeps the one. And the move's check of an account asked the vendor directly, not through the proxy its requests take. Found walking Command Code, Grok, Devin, ZCode and WorkBuddy through sandbox moves. TestMovedKeepsEfforts, TestMovedOwnRowNotWritten, TestDevinOwnMovesWithPlan and TestPluginProxy fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass. 2026-10-01 07:04:40 +08:00
yetone e86a34fce1 migrate: moving back keeps an account's expired sign-in marked, and one refused while the move lists its models goes along marked (要保证插件订阅 provider 跟内置的订阅 provider所有逻辑都要一模一样) — Zed's, Factory's and MiMo's back write the plugin's sign-in as one just made, so an account the vendor had refused through the plugin came back to the built-in showing signed in until its next refusal; the plugin's mark now goes with it. And a models hook saying a sign-in expired failed the move's strict check, so one refused Zed account stopped the whole move where the built-in would mark it and carry on; it is marked and moves untried, as a lapsed one does. Found walking Zed, Factory and MiMo through a sandbox move and back. TestMoveBackKeepsLapse and TestMoveRefusedWhileListing fail without the change. go vet, go build -tags nogui (GOOS=linux), GOOS=windows go build, go test -tags nogui ./internal/provider ./internal/plugin ./internal/gateway pass. 2026-10-01 06:33:27 +08:00
yetone 78c32292e4 plugins: a models hook can say its account's sign-in expired, as a built-in whose model list the vendor refused marked the account (要保证插件订阅 provider 跟内置的订阅 provider所有逻辑都要一模一样) — a refusal in provider.models was only logged, so an account Zed or Qoder turned away while listing its models stayed unmarked where the built-in marked it. An error thrown with signIn: expired, kept or renewed now tells magpie, which reads it as it does an answer's X-Magpie-Sign-In. TestPluginModelsSayExpired fails without the change. go vet, go build -tags nogui (GOOS=linux), GOOS=windows go build, go test -tags nogui ./internal/provider ./internal/plugin ./internal/gateway pass. 2026-10-01 06:12:11 +08:00