Commit Graph
58 Commits
Author SHA1 Message Date
yetoneandrecih 171475905f plugin: a reply's head that arrives with its completion is read, not dropped (#7017)
headRead checked the queue, found it empty, and then found the call's
result: a head the plugin queued between those two checks was lost, and
the reply was read as headless ("the vendor ended early"). The result
branch now takes a head queued meanwhile, as the c.done branch already
did. body.Read is not affected: it loops back to the queue after taking
the result.

From recih's branch (68bdf17e6), ported as its own commit.

Run: TestHostHeadArrivesWithCompletion passes on origin/main without
help (the window is narrow); with a 2ms sleep injected between the pop
and the result check it is red on origin/main ("completed reply's head
= {...}, the vendor ended early") and green with this change.
The full stack's run, on mote at e4506887c (this stack on origin/main 7300be4d0):
go test -timeout 45m ./...: 101 packages ok, 2 FAIL, both open issues
that fail the same at 7300be4d0 on mote, where an ssh session forwards
127.0.0.1:3425 to a real magpie: internal/cli's
TestHealthcheckFindsTheRunningGatewayWithoutMagpieAddr,
TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr and
TestUpdateFindsAMagpieThatWroteNoRecord (#6223), internal/gui's
TestLaneLimitRoutes (#5150). On mica: gofmt -l clean; go vet ./...,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go
build, GOOS=linux go build -tags nogui, GOOS=windows go build all ok.
go test -race -count=2 of the new and touched tests in internal/gateway,
gui, plugin, tui ok on mote.

Rebased since. At dc507aefd on mote: go vet (darwin, GOOS=linux
-tags nogui, windows) ok; go test of internal/cli, tui, plugin,
gateway, gui, claudebridge ok but for the same #6223 and #5150 reds.
At 939fe31b6 (on origin/main 78b6d47cc) on mote: gofmt -l clean, the
three vets ok, the stack's tests with TestClaude* and
TestCoreScriptBudget ok in all six packages. Pushed on b400566f9 after
a clean rebase; the commits between touch no Go file this stack does.

Co-authored-by: recih <240406+recih@users.noreply.github.com>
2026-11-18 23:06:38 +08:00
yetone ceeae93e67 plugin: a plugin added by its path is loaded again when its files change
A plugin added by its path (the user's own folder or file, as its author
has it while writing it) was loaded by the host as it was when the host
started, and an edit reached it only once magpie was quit and opened
again (yansheng1003 on X: "每次改了需要重新magpie"). checkList, which
runs on every call to a plugin, now compares the files of every enabled
path plugin too (names, times, sizes; node_modules and dot folders left
out, 2000 files at most, walked at most once a second), and a change
starts the host again as a plugins.json change already did. The
middleware already reloaded its own files this way.

Run (mote): go test ./internal/plugin -run
'TestPathPluginEdit|TestPathsLookedAt|TestTerminalUpdateRestarts' ok.
Broken by hand: checkList back on listStamp alone, and
TestPathPluginEditRestartsTheHost is red at "the plugin's own code was
edited". The full suite runs with the restart change that follows.
2026-11-18 12:58:37 +08:00
yetone 1c59acd36d plugin: a fetch whose head never comes is given up on; Devin min 0.1.45 (wu_chong4136 on X)
wu_chong4136 on X: with the Devin plugin a session sometimes hung for
10 to 20 minutes with no reply, until the effort or the context was
changed. The Devin plugin returns its fetch's head only once Devin sends
the reply's first content, and the host's headRead waited for that head
with no bound, while the gateway kept the agent alive on keepalives. A
request Devin took and never answered therefore hung silently. The body
already had bodyIdleWait (30m between bytes, #4934); the head had none.

- host.go headRead: the same bodyIdleWait bounds the wait for the head.
  On it the fetch ends with "the plugin sent no reply in 30m0s; that
  fetch was given up on", Fetch settles the call, and the host writes
  "abort", so the plugin's fetch signal ends its vendor request too. The
  gateway answers the agent its retryable 502 (an SSE error event on a
  stream). This holds for every plugin fetch, not only Devin's.
- ReplyWaitForTest lets the gateway test shorten the wait.
- Devin mover min 0.1.45 (on npm, `npm view --prefer-online`): the
  plugin itself gives up after 5 minutes of quiet from Devin (no head,
  or no frame between reads) with a retryable 504. A real probe saw
  Devin's first frame at 2.5s and at most 13s between frames.
  (magpie-community/plugins e30f8ed0)
- provider-plugins.md says so.

Tests:
- TestHostHeadWaitEndsAFetchNeverAnswered: a head that never comes ends
  in "sent no reply", the host is sent "abort", and the call is
  released; TestHostHeadWaitSparesAHeadInTime: a head in time is kept.
- TestPluginHeadNeverSentEndsInAnError (gateway, through the fake
  plugin in Bun): a vendor that reads the request and never answers
  gives the agent the error on a stream and on a whole reply, and every
  vendor request the plugin made is closed afterwards (asked 30, open 0).

Run:
- mote: the three tests above, ok.
- Broken by hand (headRead without the timer case): the host test fails
  ("held its reader for ever") and the gateway test hangs to its 60s
  timeout in io.ReadAll.
- mica: gofmt -l clean; go vet for darwin, GOOS=linux and GOOS=windows
  on internal/plugin, internal/gateway, internal/provider: ok.
- mica: go test -tags nogui -timeout 45m ./... at this tree (rebased on
  ac4a4cf84): 101 packages ok; internal/gateway FAIL on
  TestImageMCPKeepsDrawingsOffTheHeap alone ("the heap grew by 31 MB"),
  which passes 3 of 3 alone at the same tree and reads the whole
  process heap; filed as #6890.

Not tried: a real Devin request that goes quiet (it can't be made to
happen on demand).
2026-11-17 00:39:50 +08:00
yetone 30de93e9e9 plugins: a request whose Bun is still downloading fails at once and fails over (#6735)
hixonchan (kyrierekkok123-del on GitHub): with magpie's own Bun missing
and its download stalled, every plugin-served request hung with zero
bytes, nothing in the log, no timeout and no failover, and `magpie
plugin` hung too. The host's lock (hostMu) was held across Bun's
download, which had no bound on the whole, so every caller waited on it
whatever its context said.

Now:
- Bun is downloaded in the background, once at a time per Bun
  (bunready.go). The host waits for it up to 10s from when it began
  (bunReadyWait); then each call ends with BunNotReadyError, "Bun
  runtime not ready: downloading Bun 1.4.2 (12s so far)…" or "… failed:
  <why>", logged, and the gateway goes on to the group's next member.
- A failed download is said at once for a minute, then tried again;
  installs (plugin.Bun) still wait as long as their context lets.
- hostMu is a channel lock that a caller's context can end (LockCtx);
  the gateway's TryLock polling loops use it.
- When the download fails, a Bun on PATH or in ~/.bun/bin is taken if
  magpie would run it itself: at least BunVersion, not set aside, passing
  the try a new release gets. It is copied in as magpie-bun (#1048).
  magpie's checksummed build stays first; the user's own Bun is better
  than no plugins, and it is what the reporter fell back on by hand.
- Each stage is logged: download started, failed after N, downloaded in
  N, the PATH Bun taken or refused and why.
- Every route through the host gets it: fetch, loader options, sign-in,
  the plugin listing (CLI and GUI). `magpie plugin` prints the list and
  the not-ready reason within ~10s.

Self-restart and env (the reporter's point 4): Reexec, RelaunchBinary and
StartBeside pass os.Environ; only the Mac's bundle relaunch (open -n)
starts with LaunchServices' env. Filed as #6757, not changed here. With
this change MAGPIE_BUN isn't needed.

Tests (each red on the old code with a shim for the new test hooks, logs
kept):
- TestHostWhileBunDownloadStalls: old code, "a caller whose context
  ended still waits on the stalled Bun download"; now not-ready at 2s,
  the 100ms caller returns, then the host starts on the download, asked
  once.
- TestHostAfterBunDownloadFailedSaysWhy: old code, a plain 500 error,
  not BunNotReady; now the 500 is said twice with one ask, Bun() retries.
- TestBunOnPathAfterDownloadFailed: old code failed; now 1.4.2 taken,
  1.0.0 refused.
- TestPluginWhoseBunIsNotReadyFailsOver (gateway, real Handler): old
  code, "group/mixed still unanswered after 20s"; now 200 from the next
  member in 0.84s, and the plugin's own model answers 502 "Bun runtime
  not ready" after ~300ms.

Run on mote at 923cc8747 + this commit (rebased since onto d7cda856a,
a GUI-only library change): gofmt -l clean; go vet ./...,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go
build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok.
go test -tags nogui -count=1 -timeout 45m ./...: every package ok
(plugin 219s, gateway 1001s) except two untouched by this change:
- internal/usage TestWholeKeptAcrossReset: red on origin/main d7cda856a
  too, 4 of 5 at -count=5 (#6760).
- internal/provider TestRemoveListedAccountLeavesHiddenNamesake: red
  once in the full run, 5 of 5 alone (#6761).
The four new tests pass on Linux (WSL magpie-desktop) and, the two that
run there, on Windows (xiaomi-gpu).

Not tried: a real magpie binary with a really blocked GitHub download
(the gateway test runs the real handler with a stalled release server),
and the Mac relaunch.
2026-11-15 21:26:33 +08:00
yetone 58fb070953 settings: named proxies, chosen as inherit, direct or a saved one anywhere a proxy is (@tsingchao on X)
Settings > Network keeps named proxies (name, address, optional login)
with a Test that says reachable and the latency. Everywhere a proxy can be
chosen (global, plugin downloads, a provider, a key, a Claude account) now
has a Saved mode beside the others; the value is "@<id>". Addresses typed
before are read exactly as before, nothing is migrated or overridden.
netproxy.Parse/Resolve/Redact/EnvWith/Dispatch resolve a reference at the
lowest layer, so a proxy edited once reaches the gateway, usage reads,
sign-ins and the plugin host at the next request; Claude Code's
settings.json env (a snapshot) is rewritten by provider.ProxyEdited.
A reference this computer lacks fails closed (DeadProxy), says the proxy's
name in the request error and as "Proxy missing: {name}" on the provider
row, and never goes direct. The password lives in settings.json (0600), is
never read back by the page, logged, or put in Settings sync. The list
rides with the providers part of a sync (Bundle.Proxies, MergeProxies by
id, passwords only with keys). A proxy in use can't be deleted (409).
The saved list's page code is in proxies.js, loaded when Settings draws it;
app.js grew by Saved-mode helpers only, paid for by 16 long comments cut
(core budget unchanged, no raise).

Run (mote refused ssh all session, so Go and GUI went through win-run on
xiaomi-gpu, Windows 11; gofmt and darwin/linux-nogui/windows go vet were
clean on mote before it went down, at the pre-sync tree):
- go test settings, netproxy, backup, settingsapi, davsync: ok on Windows
  (earlier on mote: also gui, provider, plugin with real Bun, gateway).
- saved-proxies.test.cjs 20 of 20 (chromium+webkit, en zh zh-TW ja de,
  420px) twice more on Windows; provider-proxy-missing.test.cjs 20 of 20.
  One webkit de 420px run of saved-proxies failed once under 4-way
  concurrency and passed 3 of 3 alone; not reproduced.
- TestCoreScriptBudget ok after the move (it was 3.4KB over before).
Red on this tree and on origin/main alike (Windows run, not mine):
settings TestSharedCheckedReadsOnceAndKnowsUnknown; provider
Codex keychain/Git tests; plugin TestHostRunsAsMagpieBun, TestPiPackage;
gui TestGatewayHeldByAContainer and others; old-webkit "compat.js is the
first" (headerpresets.js) and ":has() (Safari 15.4)" on origin/main 245f07b19.
Broken by hand: restore skipping Proxies (TestSavedProxiesTravelWithProviders
red), Parse returning nil for a dangling ref (netproxy tests red), the
Proxy-missing badge disabled (provider-proxy-missing 0 of 20), and the Claude
env snapshot failing open (found by reading, test added).
Not tried: real vendors, the real Claude Code, a real two-computer sync, the
macOS suite and the whole GUI suite on this final tree (mote down; the whole
suite ran to test ~3700 on the earlier tree with reds owned by others).
A proxy missing whose sender never had it is named by its id.
2026-11-11 12:26:43 +08:00
yetone 4011873001 catalog: models.dev unreachable falls back to the last copy or a shipped one, retried in minutes (creeksuen on X)
Where models.dev can't be reached (a network in China), the catalog that
gives prices, context windows, reasoning levels and names degraded:

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

Now:

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

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

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

Not tried: the real app started with models.dev blocked; the full suite
(started after the tag).
2026-11-10 19:26:13 +08:00
yetone 7cce4b4d78 plugin: a host holding over 512 MiB is replaced by a new one
A headless magpie on a small Linux server had its shared plugin host at
783 MiB after 2h25m (main process 117 MiB), and the kernel OOM-killed it.
Four plugins went through it (cursor, kiro, qoder, workbuddy). Nothing
bounded the host: no heap cap, no collection when idle, no restart.

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

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

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

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

Not tried: a real signed-in Cursor, Kiro or Qoder account's requests and
background work (sign-in renewal, usage, model lists) under load; the
reporter's server itself.
2026-11-08 21:43:52 +08:00
ggbdpq 3da58c3dfc fix(plugin): end ordinary RPCs' plugin work when their caller leaves (#4678)
A plugin model list's deadline and an ordinary RPC's cancellation released
only the caller. inTime raced the hook without stopping it, and host.go
marked only gatewayRequest cancellable, so a cancelled usage or providers
call never told the host: the plugin's task kept running, the host's
pending count kept it, and repeated reads left task after task alive past
their callers. Reported with an offline host-script reproduction that
shows abort reaching none of three pending usage tasks and five model
tasks outliving their deadlines.

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

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

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

Refs #4678

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

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

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

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

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

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

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

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

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

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

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

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

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

Not tried: the reporter's own machine and store (what put the cross
copy in their ROOT store is a guess from the error; the host's new log
line will show NODE_EXTRA_CA_CERTS, and the file is in the cache's bun
folder); Bun 1.4.4 (the reporter's; 1.4.2 here); macOS keychain copies
(rootsFirst applies to systemRoots there too, untried with a real cross
copy); Linux takes the distribution's bundle as it is, unchanged.
2026-11-05 16:58:34 +08:00
yetone 75e30625f5 plugin: a command that serves no pages moves a page's service off the app's port (#5187)
MYCF711 (#5187, Windows, 0.1.2901): magpie plugin update run while the
app runs hung with no output. Its host loads every plugin, and
page-chat's service waits for port 3477, which the app's host holds:
each CLI command that starts a host waited ~6s on it, then kept trying
the port every second in the background, so it could take 3477 from
the app's host when that restarted after the update.

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

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

Not tried / not reproduced: the reporter's literal no-output hang. Before
this change, update finished on 0.1.2909 in every setup tried (nogui
CLI with 3477 held, beside nogui serve, beside the release GUI exe in
the interactive session: 6-20s), so this removes the wait and the
port contention seen, not a hang reproduced. Not tried on Linux or the
macOS app.
2026-11-04 16:25:02 +08:00
yetone 90bf96a23d search: a plugin can give a web search API (its search hook)
treeman on Discord #help asked for web search to be pluggable so users can
add search vendors. A plugin's `search` hook, {search: {<id>: {name, keysURL?,
keyOptional?, url?, execute({query, count, key, url}, ctx)}}}, adds an API to
Settings > Models > Web search as `<plugin>:<id>`. It is added, keyed, ordered,
switched off and removed like Tavily or Brave. The built-in APIs stay built in.

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

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

Reported by treeman.
2026-11-04 08:37:21 +08:00
yetone f4c664a09c plugin, gui: magpie web ends its plugin hosts, waited for, before it runs the new version (#3285)
The second way acezan's 57 <defunct> magpie-bun (v0.1.2819, a Linux
systemd service, 47 hours) pile up: magpie web's restart to update
(AutoRestart) runs the new version with syscall.Exec in the same pid.
The running plugin host was the old image's child, and the old image's
host.read held the only Wait for it. After the exec nothing waits for
it, so it ends on stdin EOF and stays <defunct> under that pid, one per
restart to update. skygunner reproduced it and AAEE86 counted 22 zombies
for 23 images under one pid (#3285). With about a hundred releases a
day, an AutoRestart service makes about one a hour, as acezan's did.

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

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

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

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

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

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

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

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

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

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

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

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

Reported by acezan on Discord.
2026-11-03 17:58:31 +08:00
yetone 441a2b6b16 plugin: a cancelled sign-in saves nothing, and a failed authorize says why (#5016)
Found reviewing magpie-community/plugins#658 (AStudio's and Agnes Code's
sign-ins wait up to 5 minutes for the vendor's desktop app).

Cancel didn't end a plugin sign-in. The window's Cancel (and the sign-in's
timeout) ended plugin.Finish's context, but "callback" was not a
cancellable call, so the host never heard: the plugin's wait went on, and
a session file written after Cancel still saved the account. Now
authorize, callback and apiKey are cancellable as gatewayRequest is
(host.go `cancellable`): magpie writes `abort`, host.js (`signInSteps`)
drops whatever the plugin answers after it, so nothing is saved, and
counts the call done at once. The plugin's wait is told too: every fetch
it makes for the sign-in carries the sign-in's signal
(`whileSigningIn`), and magpie's hook passes the signal as
callback(code, { signal }) / authorize(inputs, { signal }), which OpenCode
doesn't, so a plugin can stop polling a file. A plugin that ignores the
signal keeps running until its own deadline, but its answer is dropped.

An oauth method's authorize that returned { type: "failed", error } (no
callback) was stored and its missing callback called, so the user saw
"s.a.callback is not a function". host.js now answers that, or any result
with no callback, as the sign-in's failure, and plugin.Authorize returns
ErrFailed with the plugin's reason, for auto and code methods; an api
method's authorize already did. The GUI's start shows it as its failure,
`magpie plugin login` prints it.

Docs: provider-plugins.md, and the plugin guide (en, zh, ja) on failing
from authorize and the signal.

Not changed: #3083's timeout field, #4678's model/usage task lifetime.

Tests (testdata/signinend, no network; the vendor is testenv.FakeVendor):
TestCancelledSignInSavesNothing, TestCancelledSignInEndsThePluginsWait,
TestCancelledSignInEndsItsFetch, TestSignInFailsWithThePluginsReason
(internal/plugin), TestCancelledPluginSignInSavesNothing
(internal/provider, through StartPluginSignIn/CancelSignIn).

Run on mote (macOS 27), at this change on d73f2254d (the new tests and vet of both packages again after the rebase on 897e88d7e, which touches neither):
- go test -count=1 -timeout 45m ./internal/plugin/ ./internal/provider/:
  ok (134s, 145s); the new tests -v: all PASS.
- ./internal/cli ok; ./internal/gui FAIL only in
  TestMainWindowCorners/macOS_26_SDK, #3949 (macOS 27 on mote; this
  change touches no GUI code).
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok;
  gofmt -l: nothing.
- GUI (Chromium + WebKit): plugin-signin, plugin-signin-no-url,
  plugin-signin-opened (en, zh, zh-TW, ja, de), plugin-signin-scrolls,
  plugin-keyless-signin, plugin-moved-signin, signin-paste-plugin,
  signin-close, i18n-keys: 108/108.

Red on the old code (origin/main's host.js, host.go, providers.go): all
four plugin tests (an account saved after Cancel; the plugin's wait and
its fetch not ended, timed out; methods 2/3/4 said "s.a.callback is not
a function"), and TestCancelledPluginSignInSavesNothing.
Broken by hand: host.go's `cancellable` back to gatewayRequest only, all
three cancel tests red; the whileSigningIn line out of the fetch wrapper,
TestCancelledSignInEndsItsFetch red.

Not tried: the real AStudio and Agnes Code plugins (plugins#658) against
this host; the site's plugin guide isn't deployed by this commit.
2026-11-03 13:40:20 +08:00
ggbdpq 0bffc1c5db fix(plugin): a silent stream's read gives the fetch up after thirty minutes (#4934)
What changed: a reply body's Read now ends bodyIdleWait (five minutes)
after the last byte the plugin sent, gives the fetch up and says so,
when nothing more comes. The wait is between bytes, not the reply's
whole length: every chunk resets it, so a stream a slow model keeps
fed goes on however long it talks.

Why: a network drop mid-stream can leave a local proxy's socket open
but soundless, and a plugin body's read ended only on a chunk, an
answer, a close, a cancelled ctx or the host's death — none ever came,
so the request hung until the client cancelled it, with no error frame
and no retry (#4934). The gateway's relay already ends a stream whose
read fails with a protocol-valid error event; what the plugin leg
lacked was any read that fails. Five minutes is the silence the
gateway itself holds a client through (keepaliveLongest) before
leaving a stuck stream to a timeout; this is that timeout for a
plugin's reply. The wait for the reply's head is another wait and
stays as it was — this issue is a stream already past its first token.

Run: the new TestHostBodyIdleEndsASilentStream failed before the fix
(a read held for ever) and passes after; TestHostBodyIdleSparesAFedStream
locks the between-bytes reading. go test ./internal/plugin/
./internal/gateway/ ./internal/provider/ -tags nogui, the host tests
under -race, gofmt, go vet and go build all pass, with pre-existing
failures on this machine only (TestHostToldTheGatewayAddress, also red
on a clean upstream/main; TestCodexPoolSaysTheClientsVersion, the known
flake, green on a rerun).

Review, changed from ggbdpq's patch: the wait is thirty minutes, not
five. Five minutes cut replies that are silent for their whole
generation and come in one burst at the end (a model at its highest
effort, a relay that buffers its reply): those run past ten minutes,
and the gateway already keeps a translated reply's client alive
through thirty (translatedQuietLongest). A dead connection's read now
ends at that bound instead of never; the reporter's 4m52s case still
waits on the client to cancel first, which is the trade. The text
above that says five minutes and keepaliveLongest is the patch's
first version.

Broken by hand at the reviewed head: the idle timer (its start and
its reset) set to 1000h, TestHostBodyIdleEndsASilentStream red after
its 5s bar; restored, green. TestHostBodyIdleSparesAFedStream guards
against a whole-reply deadline, not a mutation of this code: with the
reset taken out it stays green (a stopped timer never fires).

Run at the pushed tree (this stack of nine on origin/main 3c2dceb34),
on mote (macOS arm64, Go 1.26.8):
- go test -count=1 -timeout 45m ./internal/catalog/...
  ./internal/plugin/... ./internal/davsync/... ./internal/gateway/...:
  catalog, plugin and davsync ok; gateway red on one test only,
  TestCodexPoolSaysTheClientsVersion, the open #4807 (another test's
  Codex identity reaches it in a full package run). It passes run
  alone at this tree, 3 of 3.
- go vet ./... (darwin); GOOS=linux and GOOS=windows go vet -tags
  nogui ./...: ok. gofmt -l on every tracked .go file: clean.
- The hand breaks above ran on this stack before its rebase onto
  3c2dceb34. That commit changed member.go only, nothing these tests
  reach.
Not tried: the GUI suite, since no GUI file changed. Windows and Linux
test runs (the Claude bridge tests use a shell fake and skip on
Windows). No real vendor, Claude Code or network was used; every
case runs against fakes.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-03 07:43:18 +08:00
yetone 276c806db2 plugins: a plugin's own requests are counted; a provider plugin's options get the editor (plugins#592)
zelong77 asked for two things once Devin 0.1.30's cache keep-alive
worked: its pings were invisible in magpie, and the interval and ping
count could only be edited in plugins.json. The owner decided pings are
shown as counted usage and the two numbers are edited in the GUI.

- host.js gives plugins input.magpie.usage(provider, call) and
  input.magpie.account(provider). usage validates the call (kind
  [a-z0-9_-]{1,40}, a model id, whole-number tokens from 0, status at
  most 999, error clipped to 500) and sends an unasked "usage" event;
  host.go hands it to plugin.OnUsage in the background.
- internal/usage/plugin_calls.go writes each one as a row of agent
  magpie on the plugin's provider (provider.PluginID) and account
  (provider.PluginAccountUser), with its kind. It is counted, priced
  and in every total, not a probe. Kind cache_keepalive is in the
  purpose catalog as "Cache keep-alive" (five languages), so the
  request log names and filters it. The ping itself still goes straight
  to Devin, never through the gateway, which would break the cache.
- /api/plugins reads every plugin's package options example, not only a
  middleware's or request hook's, and the Installed row offers the same
  Options JSON editor for a provider or agent plugin that suggests or
  has options (not while it is off). Clear's confirm no longer calls
  them a middleware's options.
- The Devin mover's min is 0.1.31, which reports each ping and gives
  its two settings' defaults (285 s, 6) to the editor. npm has 0.1.31
  (published 10:03Z); the plugins publish run is red only for
  think-tags' known E404 (plugins#180).
- docs: provider-plugins.md (the API, the options editor),
  gateway-sessions.md (the counted row beside probes).

Run at this tree (rebased on origin/main 85e37162e):
- mote (mote-run): go test -count=1 -timeout 45m ./internal/plugin
  ./internal/usage ./internal/gui ./internal/provider: plugin, usage,
  provider ok; gui red only in TestMainWindowCorners/macOS_26_SDK, the
  macOS 27 red already filed as #3949 (not this change's code).
- mote: GOOS=linux and GOOS=windows go vet of plugin, usage, provider ok;
  gofmt -l clean.
- mote: plugin-provider-options.test.cjs (new, 5 languages, 980/420px,
  Chromium + WebKit), plugin-gateway.test.cjs and i18n-keys.test.cjs:
  28 of 28 pass.
- The whole GUI suite (make test-ui) on WSL magpie-desktop (mote was at
  load ~100 with other sessions' suites, #4125), at the 8f804396f base:
  cut off after 498 test entries, when the session's background jobs
  were killed; 495 ok, 3 red, none on a page this change touches. Run
  again alone at origin/main 85e37162e, the same files are red there
  too: account-eye webkit (#4244), agent-expand-steady webkit 980px
  (#2935), add-button zh's 3000ms waitForFunction (filed #4792). The
  rest of the suite was not run.
Broken by hand (each red, then put back):
- host.go dropping the "usage" event: TestPluginReportsOwnUsage fails.
- plugins.go reading optionsExample for middleware/hooks only:
  TestProviderPluginOptionsExample fails.
- purpose.go without the Cache keep-alive kind:
  TestPluginKeepaliveIsCounted fails (purpose {}).
- plugins.js without ownOpts: plugin-provider-options.test.cjs times
  out waiting for the Options button in every language.
Not tried: a real Devin account's keep-alive ping reported into a real
magpie (needs a live Devin conversation idle for 285 s); a plugin can
report a row for any provider id, as magpie.load can.
2026-11-01 22:14:19 +08:00
yetone 8d8df06399 plugin, gateway: a plugin reports its models' load, and busy models can go last (axelburks on Discord)
axelburks (Discord #feedback): an in-house vendor queues requests to
its busy models, and the plugin could only put the load in the model's
name, which changed only when magpie re-read the list.

- A provider plugin calls input.magpie.load(provider, {"<model id>":
  0-100 | null}) whenever it likes, from its own timer. host.js
  (reportLoad) clamps each number to 0-100, null clears a model, every
  other value is dropped, at most 1000 a call, and it returns the count
  taken. A provider that isn't a string or loads that isn't an object
  throws a TypeError. It goes to Go as an unasked {event:"load"}.
- internal/plugin/load.go keeps each by provider and lowercased model
  id. ModelLoad answers unknown once a load is older than LoadFresh
  (5 minutes), never idle. model@size falls back to its model.
- The provider editor shows it by the model as a grey ctx badge
  ("87%", titled "87% busy now, as its plugin says").
- Settings > Network and sharing > Busy models last (settings.BusyLoad,
  POST /api/settings/busy-load, Off by default, over 50/70/80/90% or
  1-99 by hand): restLast puts a model reported over it behind the
  ready candidates, ahead of the resting. The trace row has busy:<load>.
  At a new turn affine moves a conversation off it (Why "busy",
  busyBehind); within a turn it stays. after, readyForNew and leastHeld
  skip it. Unknown load, a lone candidate, or all busy: nothing moves.
- Docs: site plugins page (en, zh, ja) "Model load" section and input
  table; docs/subsystems provider-plugins.md and gateway-routing.md.

Run, all on mote via mote-run at a42736807's tree rebased on
origin/main b683f1c0e:
- go test ./internal/plugin ./internal/gateway -run
  'ModelLoad|TestBusy' -v: TestPluginReportsModelLoad,
  TestModelLoadGoesStale, TestBusyModelGoesBehind,
  TestBusyModelNotKeptAtNewTurn pass.
- Broken by hand, each red: host.js not sending the event
  (TestPluginReportsModelLoad "the plugin's loads never arrived"), the
  busy case off in restLast (TestBusyModelGoesBehind order), the affine
  "busy" case off (TestBusyModelNotKeptAtNewTurn "kept true, why
  session").
- go test ./internal/gui -run Budget: ok. No budget raised. app.js
  +86 bytes, two comments trimmed to fit. The settings row lives in
  plugins/gateway/settings.js.
- node --test model-load, i18n-keys, bare-ids, model-rate: 69/69 pass.
  model-load is Chromium and WebKit, 420 and 900 wide, en zh zh-TW ja
  de.
- gofmt -l: empty. go vet ./... (darwin), GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./..., go build: ok.

Not run before the push (owner: push and tag first): go test ./...
-timeout 45m and the whole GUI suite. mote and the WSL box were each
running another session's full suite. Both run next, and any red gets
its own commit.
Not tried: a real plugin and vendor reporting load. The plugin side is
tested through the real Bun host with a plugin written in the test.
2026-11-01 13:45:40 +08:00
yetone 602ad84adc plugin: the host is told the gateway's address (MAGPIE_ADDR), so a page's own service reaches it on any port
yuesh1_ on X (reply to 2115451149633626237) opened the community chat
page (Magiczerowxy/magpie-chat, @magpie-community/page-chat 0.1.16) and
got "127.0.0.1 拒绝了连接". That is Chromium's frame error: the plugin's
chat server on 127.0.0.1:3477 wasn't listening. Before v0.1.1905
(ca499953e) nothing started the host when the page opened (the WebKit
form of it is magpie-chat#2), so that symptom is most likely an older
magpie; it doesn't reproduce at main.

What does still fail at main is the next step. The chat server finds
the gateway from MAGPIE_ADDR, else http://127.0.0.1:3425, and magpie
never put MAGPIE_ADDR in the host's environment. With the gateway on
any other port (Settings, portable builds: magpie-chat#1) the page
opens with an empty model list and "Unable to connect".

hostEnv now sets MAGPIE_ADDR to hostAddr(): magpie's own MAGPIE_ADDR,
moved onto 127.0.0.1 when it listens on every interface, else Settings'
port on loopback (settings.SavedAddr). The running host records the
address it got, and proxyMoved replaces it once that differs, as it
already did for a moved proxy. plugin.Warm (called when a hosted page
opens) now goes through get() for a running host too, so opening the
page is the call that picks up a changed port.

Run:
- TestHostToldTheGatewayAddress (new): a probe plugin writes the
  MAGPIE_ADDR it was given. Settings port 3591 -> 127.0.0.1:3591; port
  moved to 3592, Warm -> 127.0.0.1:3592; MAGPIE_ADDR=0.0.0.0:4999 ->
  127.0.0.1:4999. Passes on mote and on Windows (win-run, -count=3).
- Broken by hand, each red: the old host.go ("with Settings' port 3591
  the plugin was told MAGPIE_ADDR=unset"); the addr check taken out of
  proxyMoved, and Warm's old Running() short cut, both ("after the port
  moved to 3592 ... told MAGPIE_ADDR=127.0.0.1:3591").
- Real use, sandbox HOME, real page-chat 0.1.16 from GitHub (7dbf8ff),
  gateway port set in Settings: at main its /api/bootstrap said
  gateway http://127.0.0.1:3425 with "Unable to connect" on mote and on
  Windows; with this change gateway http://127.0.0.1:3686 (mote) and
  :3591 (Windows), no error. Changing the page's options restarts the
  host and 3477 comes back, at main and here.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...; go build for darwin, linux (nogui) and
  windows: all on mote.
- Full suite on mote: go test -tags nogui -timeout 45m ./... at base
  fc6f1d5e8, 77 packages ok, no FAIL. Rebased onto b69f8e96a (one
  usage commit), then go vet ./internal/... and internal/plugin,
  internal/usage and internal/gui again: ok. Pushed on 298bfce59, whose
  one line (Cursor's mover min in migrate_side.go) touches nothing here
  and wasn't run again with it.
- Windows, go test ./internal/plugin: TestPiPackage and
  TestLoadConcurrentWithSavesAndEdits red, both also red on origin/main
  b69f8e96a there (run alone, the latter 3 of 3); both are in #1827.

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

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

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

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

Not tried: the reporter's OS and magpie version; the real Windows and
Linux app windows (wsl-run can't build internal/gui: no gtk4 or
webkitgtk-6.0 dev packages in magpie-desktop, internal/plugin ok); a
real Restart in the background (simulated by killing the host); the
full GUI suite (no asset changed). magpie-chat 0.1.9 to 0.1.13 had no
main or exports, so they are page-only and no host ever starts them;
0.1.14 restored main, and that's for the plugin to tell its users.
2026-10-28 21:27:47 +08:00
yetone f8cd964aec plugin: a fetch past the host's 128 streams waits for one, not a local 502 (#3890)
The plugin host holds streamBudget/streamWindow = 128 streaming calls'
windows. begin(true) failed the 129th at once with errTooManyCalls, before
anything reached the plugin child, and the gateway counted it as a 502
try and sent the request again. The reporter's 192 concurrent MiniMax
streams through one plugin all came back 200, but over 298 local 502
tries that never reached MiniMax (65 requests retried).

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

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

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

Not tried: 192 real concurrent streams against a vendor (the reporter's
MiniMax setup); the full gateway package (only its Plugin tests).
2026-10-28 00:58:50 +08:00
yetone afc99490f2 plugin: a fetch's body goes to the host in one line made for it (#3472)
Each plugin request was copied several times before it reached the
plugin:
- pluginFetch read the body with io.ReadAll, which grows from 512
  bytes, so a 1 MB body was some 3 MB read. It now reads into a buffer
  of the request's Content-Length.
- Fetch marshalled a map holding the FetchRequest and the body as
  []byte, so encoding/json base64'd the body into its own buffer and
  then copied it into the line, and enqueueOwned appended the newline
  in another copy. fetchLine now marshals the request without the body
  (FetchRequest.Body is json:"-") and appends the base64 body and
  window into one slice sized for the whole line; enqueueLine sends it
  as is.

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

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

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

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

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

Run at this head (base origin/main e5dd86965), sandbox HOME, caches
pinned:
- TestStuckPluginLoadHoldsNoOther and TestStuckModelListHoldsNoOther
  (testdata/stuck): red on origin/main's host.js ("Plugins = [],
  starting plugins: context deadline exceeded" after 30s; "Providers
  = [], context deadline exceeded" after 15s), green here (2.1s each).
- go test -count=1 -timeout 45m ./internal/plugin/: ok (165s).
- go test ./internal/provider/: ok with
  -skip TestUnreadLoginsWriteErrorsKeepCredentials, which crashes with
  "close of synctest channel from outside bubble" in filememo.Forget,
  filed as #3632 and not touched here.
- go test -run Plugin ./internal/gateway/: ok.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags
  nogui on internal/plugin: ok.
Not run before the push: the whole go test ./... (run after it); not
tried with the reporter's own plugin, which wasn't named.
2026-10-26 15:09:09 +08:00
yetone 5774c790bd plugin: a reply's chunk frame is read by its fixed shape, not through encoding/json
Each chunk of a plugin's streamed reply (up to 64 KB of base64 a frame)
went through json.Unmarshal into message. encoding/json scanned every
byte twice (validating, then decoding the string) and cost far more than
decoding the base64 itself. chunkFrame reads the one shape host.js's
chunkLine writes, {"id":N,"event":"chunk","data":"..."}. Any other line,
or one whose data holds a quote or a backslash, still goes through
json.Unmarshal. push checks the data is base64 of a frame's size either
way, as before.

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

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

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

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

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

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

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

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

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

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

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

Not tried: a benchmark against a real many-agent load, or the
reporter's machine. The count of builds per request is the measure.
2026-10-16 20:05:11 +08:00
yetone 6641e1b0ac provider: a plugin sign-in drops what a request holds at once (#2449)
TestPluginLoginInstallsItsCLIFirst went red on macOS CI (run
38798393584) with "not signed in after the install: []". cli's run()
sets catalog.Changed = agent.SyncCatalog, and a sync left going from an
earlier step holds the catalog (provider.Hold), plugins and their
sign-ins among it, for up to a second. The host's "auth" event dropped
that only through catalog.Touched, told in the background, so on a busy
runner provider.Logins right after the sign-in read the snapshot taken
before it.

plugin.OnChangeNow registers hooks run before changed() or listed()
returns, i.e. before the host's reply after the event is read; provider
registers dropHeld there. Changed() is filememo.Forget + dropHeld.

Reproduced by injecting a pause where SyncCatalog holds (patch kept
outside the tree): without the fix red 3/3 with the CI message; with it
ok -count=5. TestHeldGoesWithAPluginChange: red without the fix ("held
from before the change: built 1 times, want 2"), green with it, also
-race -count=20.

Run: -count=20 -run TestPluginLoginInstallsItsCLIFirst ./internal/cli
ok; internal/cli, internal/plugin, internal/provider whole ok; gofmt -l
clean; go vet -tags nogui for darwin, linux, windows on the three ok.
Full suite: go test -tags nogui -timeout 45m ./... at 7fefbc614 with both #2449 commits (this one and the Settle fix after it) (sandbox HOME, macOS): exit 0, 66 ok, 18 no test files, 0 FAIL.
2026-10-16 05:29:20 +08:00
yetone 49639cd162 agents: a plugin signed in to, out of, or listing new models updates the agents' model files (#2373, 18565882223-beep)
After signing in to Trae CN (a plugin's subscription), Pi's models.json
kept the list it had before the sign-in, so Pi's picker had no trae-cn/*
model while settings.json named one. A plugin's sign-in change
(plugin.OnChange) only dropped what the gateway held; catalog.Changed
(SyncCatalog), which a provider saved runs, never ran for a plugin. Now
plugin.OnChange and a new plugin.OnListed (told when the host lists
providers/models other than the list kept, also across a restart) call
catalog.Touched, so every connected agent's own model list follows, Pi's
models.json among them, and a sign-out takes the models out again.

Not reproduced: the report's GUI pick leaving models.json's mtime
unchanged. GUI and CLI picks go through the same Agent.Pick, which writes
models.json in-process here. With this change the file is rewritten when
the plugin lists its models, not only on a pick. PiCode's providers.json
isn't wired by magpie at all; unchanged.

Tests:
- TestPluginSignInReachesPiModels (internal/agent): pick a model, sign
  Trae CN in, models.json lists trae-cn/kimi-k3-max; sign out, gone.
  Broken by hand (hold.go back to plugin.OnChange(Changed)): FAIL
  "models.json hasn't Trae CN's models after its sign-in".
- TestNewListIsTold (internal/plugin): a new list is told once, the same
  list or the one kept on disk is not. Broken by hand (listed() not
  called): FAIL "the first list: told 0 times, want 1".

Run at origin/main 9d97fd073 + this change and the #2373/#2372/#2374 commits beside it (one tree), -tags nogui -count=1
-timeout 45m: internal/plugin, provider, agent, catalog, gui,
gateway ok. gofmt -l clean; go vet -tags nogui ./... for GOOS darwin,
linux, windows clean.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +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
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 b790594074 plugin: Settle waits for the sign-in hook, so TestPluginModelsSayExpired no longer writes into its removed folder (#1935, Nxir; #1543)
The cause: a host's "signIn" event (a models hook saying an account's
sign-in expired) ran provider's OnSignIn hook with a bare go f(...). That
hook writes the account's lapse into logins.json (lastgood.Keep, then the
file, then Changed) under .config/magpie. TestPluginModelsSayExpired
returns as soon as the lapse reads back, and Settle, its cleanup, waited
for refreshes and the change hooks (Told) but not this one, so the rest
of its write could land while TempDir removed the folder: "unlinkat
.config/magpie: directory not empty", seen under load on #1543 and on
Nxir's CI run.

The fix: the sign-in hook runs through the same counted tell() as the
change hooks, so Told, and so Settle, waits for it. Settle then waits for
refreshes and restarts once more, since a hook told before the providers
were read reads them, which can start a host again.

Reproduced by injecting a writer into the hook (300 files in
.config/magpie, 1ms apart, after notePluginSaid): on the old code
TestPluginModelsSayExpired -count=3 failed with the reported "directory
not empty"; with the fix it passed 3 of 3. The injection was removed.
New TestSettleWaitsForTheSignInHook (synctest, as its sibling for change
hooks) goes red with the bare go f(...) put back.

Run: go test -tags nogui ./internal/plugin/ ./internal/provider/
-count=1 in a sandbox HOME (both ok), TestSettle* -race -count=3, gofmt -l,
GOOS=linux and windows go vet ./internal/plugin/.
2026-10-13 15:48:53 +08:00
wei 920d96af55 tests: provider, plugin, gateway, codexcat, gui and tui tests pass in any order and on any -count (#1146)
Squashed from wei's #1146, onto main. Each test now starts from state of
its own instead of what an earlier test (or an earlier -count run) left:

- plugin: changed() counts the OnChange hooks still running; Told waits
  for them, and Settle ends with Told and UseCached(nil), so a change one
  test made isn't told in the next and the next test's plugin list isn't
  read as changed. Only tests call Settle/Told; in production changed()
  only counts. New TestSettleWaitsForTheHooksItTold and
  TestSettleForgetsTheFoldersPlugins.
- provider: isolate forgets Copilot's state, the plans' quota cards and
  balances; the warm-up, Cursor sign-in, hold and moved-plugin tests wait
  for what they started.
- gateway: fresh() forgets refused seals, and TestRouting,
  TestSmartRouting and TestQuotaRestsUntilItsReset start from
  forgetRouting; codexSignedIn and TestForeignReasoningIsLeftOut start
  from fresh.
- codexcat: XDG_CONFIG_HOME under the test's home. tui: costAt reset.
  gui: the fake Cursor account no longer outlives its test. cli: Settle.

Left out as already on main: the cli_identity keepIdentities switch
(9c3772311 keeps the asks in a sandbox via testenv's marker) and the
omarchy reset (main's TestCurrent already resets cached/seen/asked).

Run (darwin, loaded machine):
- On main 043e0cfc7, -count=3: TestRouting, TestSmartRouting,
  TestQuotaRestsUntilItsReset, TestForeignReasoningIsLeftOut,
  TestStandaloneNativeFallback fail; codexcat and tui fail; provider
  -shuffle=1791359851244745000 fails TestCopilotAuto and
  TestCopilotSignAndModels, and -count=2 -shuffle=1791856220860256000
  -run 'Copilot|TestPlanQuotas|TestCachedCardsAskNobody' fails
  TestPlanQuotas and TestCachedCardsAskNobody. With this change, that
  provider run (-shuffle=on, -count=2), the same gateway tests,
  ./internal/codexcat, ./internal/tui and the Settle/Hold/warm-up tests
  in plugin and provider pass -count=3.
- Breaking Settle by hand: without Told(),
  TestSettleWaitsForTheHooksItTold fails; without UseCached(nil),
  TestSettleForgetsTheFoldersPlugins fails.
- gofmt -l; go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows.
Not run: the whole ./... suite at once (the machine's load times it out)
and Windows/Linux test runs.
2026-10-13 09:52:14 +08:00
yetone 23c6e865a7 plugin: a musl Linux (Alpine) runs plugins on Bun's musl build, kept apart from the glibc one (#1877)
emptyteeth found it: bunTarget picked Bun's build from GOOS/GOARCH alone,
so Alpine got bun-linux-x64-baseline, a glibc build whose interpreter
(/lib64/ld-linux-x86-64.so.2) Alpine lacks. exec then said "fork/exec
…/bun/1.4.2/magpie-bun: no such file or directory", which reads as a
missing file, and no plugin could be added or run.

- bunTarget: a musl Linux gets bun-linux-x64-musl-baseline or
  bun-linux-aarch64-musl. The musl check moves out of internal/claudecode
  into internal/libc (libc.Musl, unchanged rule: Anthropic's installer's
  /lib/libc.musl-*.so.1), which claudecode, the plugin host and the CLI
  test that skipped on musl now share.
- bunSums: the two musl builds' checksums, checked against Bun v1.4.2's
  own SHASUMS256.txt (downloaded from the GitHub release; they match the
  issue's numbers).
- Cache: a musl Linux keeps its Buns and state.json under bun/musl, so a
  machine whose C library changed never runs the other build, nor takes
  its state, whose Bad may list versions only the glibc build failed
  (CheckBun on Alpine set aside every newer Bun). glibc, macOS and Windows
  stay in bun/<v>, so a Bun downloaded before is used as it is, with no
  new download.
- A bun on disk that exec can't start with ENOENT says it is a build for
  another C library and names MAGPIE_BUN (cantStart), for the host's start
  and for bun add/bun update. The same for a $MAGPIE_BUN.
- Bun's musl build needs libstdc++ and libgcc, which a bare Alpine lacks:
  the loader then prints "Error loading shared library libstdc++.so.6"
  above ~40 "Error relocating" lines, and bun add cut it off. bun add,
  bun update and a host that died starting now say which library is
  missing and `apk add libstdc++ libgcc` (missingLibs, whyDied).

Decided: a Bun that can't be started at all is not counted as crashed.
The fallback goes to the version before, which is the same build for
this system and fails the same way, and setting the current one aside
would mark a good version bad for good. The libc check happens before the
download instead (the target), so Alpine never fetches the glibc build.

Run:
- docker alpine:3.20 (arm64, and amd64 under emulation), sandbox HOME in
  the container, linux nogui builds. origin/main's binary reproduces the
  report: "bun add …: fork/exec /sbx/.cache/magpie/bun/1.4.2/magpie-bun:
  no such file or directory". This one on bare Alpine downloads
  bun/musl/1.4.2 and says "this system lacks libstdc++.so.6 … apk add
  libstdc++ libgcc"; after apk add, `magpie plugin add
  @magpie-community/opencode-cursor-auth` adds it and `plugin list` starts
  the host and lists cursor (arm64 and amd64), with the old glibc
  bun/1.4.2 left beside it unused. With libstdc++ removed again, plugin
  list says the library; MAGPIE_BUN pointed at the glibc build gives the
  C library message.
- New tests (bunmusl_test.go, libc_test.go), each broken by hand and seen
  red: no musl branch (TestBunTargetForMusl, TestMuslBunKeptApartFromGlibc),
  no bun/musl root (TestMuslBunKeptApartFromGlibc), cantStart returning
  the error as is (TestCantStartSaysCLibrary,
  TestHostOnUnstartableBunSaysCLibrary, which fails with the reporter's
  exact message), host.go without it, no musl sum (TestBunDefaultSums),
  no hint in bun add (TestMissingLibsNamesThem) or in the host's start
  (TestHostOnBunLackingLibsSaysWhich), muslAt always false (TestMuslAt).
  -race -count=20 on them: green.
- gofmt -l; go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows;
  go build for darwin, linux nogui, windows; go test -tags nogui for
  internal/plugin, libc, claudecode, cli in a sandbox HOME, and
  go test -tags nogui ./... (all green). One earlier run of
  internal/plugin with the other three packages went red, and its output
  was lost to a tail; four reruns of it, alone and together, were green,
  and the new tests were green under -race -count=20, so which test it
  was isn't known.

Not tried: a glibc Linux end to end after the change (the unit test
covers that its Bun stays at bun/<v>); a musl Linux other than Alpine
(the detection is unchanged and looks for Alpine's libc.musl-*.so.1).
The old glibc bun/<v> on an Alpine machine stays on disk (~90 MB); it
isn't removed, as a volume shared with a glibc container could be using
it.
2026-10-13 07:25:22 +08:00
CaramelizedCUDAandClaude Code 3f5c3b0553 plugin: the host keeps reading a plugin's stderr after a line over 4 MiB, so the plugin host no longer hangs (Windows) or keeps the unread output in memory (Linux)
The host logged the plugin child's stderr with a bufio.Scanner capped
at 4 MiB. On the first longer line Scan stopped with ErrTooLong, the
goroutine returned, and nothing read the pipe again. host.js sends
console.log and process.stdout.write to stderr, so one long line from
any plugin was enough. Now the reader drains the pipe past an
overlong line and logs what it can, so the output stops being
dropped silently.

Measured on Bun 1.4.2 (Windows and Linux, official binaries, sha256
checked): on Windows the plugin host stopped answering init when a
plugin wrote one long line while loading; on Linux a script writing
200 MiB to stderr with no reader went from 18 MiB to 412 MiB RSS.
Each of those reproduced at HEAD and is gone with this change; the
Linux memory number comes from that Bun-only measurement, since
magpie's own RSS did not differ at this scale.

Run before this commit: go test -tags nogui ./internal/gui
./internal/plugin is ok on Linux (WSL2 Ubuntu 24.04, go1.26.8) both on
HEAD and on this change. On Windows, go test -tags nogui ./... (49
packages): every failing test also fails at 6c1c0a74 and is listed in
#1827; the plugin package's TestLoadConcurrentWithSavesAndEdits fails
at HEAD too.

macOS was not run here; CI's macOS job has no Bun setup step, so the
end-to-end test skips there if bun is not on PATH. The unit test runs
either way.

Reviewed for magpie (CaramelizedCUDA/magpie pr/plugin-stderr-drain at 56120240, cherry-picked onto f340aecab, then rebased onto 6ccf23efa and run again there): with drainStderr's io.Copy removed, TestDrainStderrKeepsTheChildGoing fails on macOS ("the child is still blocked writing stderr after a line over 4 MiB"). On the Windows 11 box (windows/amd64 test binary, Bun 1.4.2 official zip, sha256 checked, USERPROFILE/APPDATA in a scratch folder) both tests fail without it, TestHostStartsPastAnOverlongStderrLine with "starting plugins: context deadline exceeded" after 62s, and both pass with it (0.02s, 1.99s). go test -tags nogui ./internal/gui ./internal/plugin is ok on macOS.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-12 23:33:56 +08:00
yetone e9221e96dd provider, netproxy, gui: allowances can be read only when asked, and a system proxy set after start is taken within seconds (#1518, RooobinYe)
The reporter starts magpie at login with the proxy on "follow system
proxy". magpie comes up before the proxy app. With no system proxy set
yet, netproxy.For gives none, so magpie's own allowance reads went out
direct, from the user's real IP. That reading was then kept for up to
15s. A system proxy that is set but not listening fails the request
("proxyconnect ... connection refused"); it never falls back to direct.

Proxy freshness:
- netproxy.System re-reads a "none" reading after 2s (noneKeep) instead
  of 15s (systemKeep, unchanged for a set proxy).
- The plugin host looks again every 2s while it has no proxy
  (proxyLookNone), so a host started before the proxy app takes it soon.
- Catalog sync, the update check, plugin updates and token refresh all go
  through netproxy.Func / Dispatch, so they use the current proxy too.

Settings -> Allowances -> "Allowance reads": Automatic (default, as
before) or When I ask (settings.QuotaReads = "asked",
POST /api/settings/quota-reads):
- These count as asking (provider.Asked): the Usage page opened or
  refreshed (?asked=1), a card's refresh (RefreshUsage), magpie quota,
  magpie accounts, magpie quota wait and the TUI's quotas.
- Every other read (quotaReading -> holdUnasked) carries netproxy.Hold.
  netproxy.Func, Dispatch's choice proxies and the plugin host's calls
  refuse a held request before it leaves.
- The readers return the last reading, dated (AsOf), or "not read yet".
  That covers routing's Allowances / AwaitAllowance, the used-up switch,
  the menu bar, alerts, Quotas/KeyBalances/PlanQuotas, Codex/Claude/
  Cursor/Grok/Kiro usage and KeyAllowance.
- An account refused for its quota (StaleAllowance) or a key refused
  (StaleKeyAllowance) is still read, once.
- Warm-up and check-in are unchanged.
- Strings are added in zh, zh-TW, ja and de. The docs are updated:
  providers-accounts (Allowance row), provider-plugins (host proxy).

Run:
- go test -tags nogui ./... (sandbox HOME), gofmt -l, and go vet -tags
  nogui on GOOS=linux/windows/darwin for ., netproxy, plugin, settings,
  provider, gui and tui.
- New tests, each seen red by breaking the change by hand:
  - TestSystemProxySetAfterStartIsTakenSoon and TestHeldRequestNeverLeaves
    (netproxy).
  - TestHostWithNoProxyLooksAgainSoon (plugin; red with 15s).
  - TestAllowancesReadOnlyWhenAsked (red without the hold and without
    markStaleRead), TestAllowancesReadByThemselvesByDefault and
    TestKeyReadsOnlyWhenAsked (red without holdUnasked and without
    unheld for a refused key).
- GUI quota-reads.test.cjs in Chromium and WebKit, at 900 and 360px, in
  en/zh/zh-TW/ja/de.
- i18n-keys, gui-ja, gui-de, settings-sections, settings-groups,
  currency, number-units and tray-bird.
2026-10-11 00:20:25 +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 cb406c8425 plugins: a plugin can add an agent magpie has no setup of its own for
Plugins could be subscription providers or gateway middleware. Now a third
kind: an agent plugin, so a user whose agent magpie doesn't ship can still
put it on magpie.

- internal/agentplug: a plugin's magpie.agent module (or a *.agent.js file)
  exports agent = {id, name, config, format?, model, prefix?, bin?, dir?,
  ua?, icon?, notice?} and an optional connect({gateway, model, models,
  agent}) returning the other keys to write. Compiled in moejs, reloaded
  when plugins.json or the file changes; why one didn't load is kept.
- internal/jsmod: module compiling (imports kept inside the plugin), moved
  out of middleware so both share it.
- internal/agent/plugged.go: each becomes an Agent (Plugin set) after
  magpie's own. JSON, YAML and env files are edited key by key, comments
  kept; what each key held is stashed typed under plugin:<id>:<path>, and
  its own model or Disconnect puts every key back. A built-in id is
  refused; a connect that throws writes nothing. Key magpie-<id>; usage
  names it by key or ua (usage.PluginAgents).
- GUI Plugins page: an Agent kind chip and glyph, a Discover "Agents"
  section (market kind "agent"), and an installed row line "Adds X to
  Agents" or why it didn't load. zh, zh-TW, ja, de strings.
- Docs: site Plugins page (en, zh, ja) "Agent plugins", reference.md,
  agent-wiring.md, gateway-middleware.md.

Run:
- go test ./... (all ok); gofmt -l clean; GOOS=linux go vet -tags nogui
  ./... and GOOS=windows go vet ./... clean.
- TestPluggedYAML, TestPluggedJSONUnwire, TestPluggedRefused.
- GUI: plugin-agent.test.cjs 22/22 (en, zh, zh-TW, ja, de; 980 and 420;
  chromium and webkit); all plugin-*.test.cjs, i18n-keys,
  deprecated-subscriptions, filter-ime: 315 pass, 0 fail.
- Real use, in a sandbox HOME: an Aider plugin (~/.aider.conf.yml, prefix
  openai/, connect writes openai-api-base/key) installed in a dev build;
  picking DeepSeek V4.1 Flash on the Agents page wired the file keeping the
  user's comment and keys; real aider 0.86.2 `--message` answered through
  magpie from the real DeepSeek account; usage.jsonl recorded agent aider,
  provider deepseek, 200; Disconnect restored the file byte for byte.
2026-10-10 18:39:47 +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 a8ca790855 plugin: the host takes a proxy set after it started (#1363)
iamyhzhao's moved Grok account reads as signed out after nearly every
reboot. The plugin host (Bun, host.js) reads MAGPIE_*_PROXY once, at its
start, and nothing restarted it when the proxy changed. After a reboot
magpie can start before Clash or another proxy app sets the system proxy,
so the host had no proxy for its life; the Grok plugin renews by running
`grok models`, which got no proxy from the spawn wrapper, couldn't reach
auth.x.ai, and token() said the sign-in had expired. Moving to the
built-in and back installs and removes the plugin, each of which restarts
the host, which is why that worked.

Now the host remembers the proxy it was started with (hostProxy of
env()), and get() replaces a live host whose proxy is no longer what a
new host would get (proxyMoved, looked at no more than every 15s).

Run: new TestPluginHostTakesANewProxy (real host on the cliproxy
fixture: no proxy, then HTTPS_PROXY set, the CLI gets it; unchanged
proxy keeps the same host) passes, and fails with the check disabled.
go test -tags nogui ./internal/plugin ./internal/provider
./internal/gateway in a sandbox HOME: ok. gofmt -l clean; go vet for
darwin, linux and windows on ./internal/plugin: clean.
Not verified: the reporter's proxy setup (Clash with system proxy is the
likely case, not confirmed), a real reboot, a real Grok account.
2026-10-09 09:49:03 +08:00
forever e24b332051 plugin: a failed write to the plugin host ends the host before its caller hears of it, so a call freed by the failure finds the host already gone (TestHostWriterFailureWakesWaiters, red on macOS CI) (#1214) 2026-10-08 06:19:50 +08:00
yetone 2bd49cc545 plugin: magpie plugin update in a terminal restarts the app's plugin host (#952, mxzs123) — the running magpie noticed another magpie's plugin change only by plugins.json, which an update leaves as it was (the spec stays, bun installs a newer version), so the app's host went on answering with the old code (0.1.17 after the update to 0.1.18, still 403) until it was killed. The stamp checkList compares now also covers what is installed: Dir()'s package.json and bun's lockfile; and Restart takes the stamp as it is, so this magpie's own install isn't taken for another's and restarted twice. In a sandbox (serve on 3476 under its own HOME, the Factory plugin at 0.1.17, unpinned spec; a request, then magpie plugin update in another process, then a request): on 2d85a086 the host process stayed the same (58657) with 0.1.18 installed; with this change it was replaced (60004 → 60583) and the old one stopped. TestTerminalUpdateRestartsTheHost is new and fails without the change; go vet and go test -race -tags nogui ./internal/plugin/ ./internal/provider/ under a temp HOME pass. 2026-10-06 08:47:59 +08:00
yetone eebd0b4222 plugin, gateway, gui: a plugin can be gateway middleware — onRequest, onEvent and onResponse run in magpie's gateway on what agents send and get back (moejs) — a plugin could only be a subscription provider, run in the Bun host, a process away from the gateway. A plugin may now declare middleware (package.json magpie.middleware, or a *.middleware.js / .mjs file), run in-process by moejs (pure-Go JS engine): compiled once, one runtime per request from a pool, so every hook of a request shares ctx.state. onRequest(body, ctx) sees the agent's body in its own API before routing; what it returns is the body the next middleware and the gateway get, undefined leaves the bytes as they were, ctx.reject(status, msg) answers with an error in the agent's API's shape. onEvent(ev, ctx) sees each SSE event's JSON (export const events = [...] filters by name; an object changes it, null drops it, undefined passes the bytes through untouched; data: [DONE] is no JSON and passes by). onResponse(body, ctx) sees a whole JSON reply, with ctx.status. ctx has protocol, model, stream, path, agent, the plugin's options and state. A hook that throws, returns a non-object or runs past its limit (250ms request/response, 50ms an event, 1s load; interrupted) leaves the request or reply as it was and is counted and logged (60 lines a minute); a compressed reply passes as-is. Files are reloaded within a second of a change. Only agents' requests run through it (serveAgent at the gateway's agent entry points and the Codex backend), never magpie's own titles, classifier or stand-ins; it sees bodies before redaction. A middleware-only package is skipped by the Bun host. The Plugins page marks a middleware with a chip, its hooks, calls and µs per call (JSON in and out counted), failures in red with the last error, and a load error. en/zh/ja/de; docs/reference.md and usemagpie.ai/docs/plugins#middleware (en/zh/ja) with an alias example. Tested with a real DeepSeek account through magpie web --gateway in a sandbox HOME: an alias middleware served "fast" and named it in message_start, a reject came back as 403 permission_error, a Chat stream uppercased; real Claude Code (sandbox CLAUDE_CONFIG_DIR) did Read, Bash and Glob tool turns through three middlewares with 0 failures: ≈1–1.6µs an event, 0.2–0.7ms an onRequest that parses and rewrites Claude Code's ≈80KB body. Real use found two bugs fixed here: [DONE] parsed as JSON (SyntaxError on every Chat stream) and stats leaving out the JSON time. internal/middleware tests (chain, undefined keeps bytes, reject, fail-open on throw/spin/string with the runtime reused, async hook, load errors, off and Bun skip, reload, split/CRLF/filtered/dropped stream events, [DONE] untouched, whole reply and gzip, 64 in parallel; BenchmarkEvent ≈0.9µs, 11 allocs) and TestMiddlewareThroughGateway (alias routed, events by protocol, redaction still upstream, reject in Anthropic's shape; fails without the change) are new; plugin-middleware.test.cjs (Chromium and WebKit, en and zh: chip, hooks and stats, failures with last error, broken and off, no left border) fails without it. The other plugin GUI tests and click-scroll pass in WebKit. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass (internal/provider failed once under load and passes alone). 2026-10-05 19:14:31 +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
Snowyy fa1e3947f9 plugin: isolate stalled streams and guard GUI refreshes (#664)
* plugin,gui: a stalled stream can't wedge the host, stale reads can't draw, and the browser suite runs in CI

internal/plugin: the host has one reader of the child's stdout, and it handed
each message to its call by sending on that call's channel. A caller that
stopped draining a streamed body (a slow HTTP client on a plugin-backed chat
stream) filled the channel; the reader then blocked, and every other call
through the host -- all plugin providers and accounts, moved built-ins
included -- stopped being dispatched until the stalled stream was drained. A
second call's answer arrived only after the first was drained.

Each call now queues its head and chunks in a bounded backlog (4 MiB of
chunks, 4096 of them) drained by its own reader, so the host's reader never
waits on one consumer; a call whose consumer stops reading is given up on
alone, with the limit as why. Aborts go through a goroutine too (abortLoop),
so a child that stopped reading its stdin can't make an abort wait either.
host_test.go covers the stalled consumer, the bounds and the abort path.

internal/gui: loadUsage() and refreshUsage() both read the Overview's
usage?period=, and neither checked after the await that its answer was still
the newest: a 24 h answer landing after a 7 d one drew the old period's
figures under the new period's name, and leaving the tab could still write the
Overview's cost into the shared header. Both now claim one shared read
generation before the request and draw only when it is still the newest and
the page, tab and period are unchanged. providersWhileFetching() also stopped
for good after one failed poll or reload; it now asks again.

usage-stale-answer.test.cjs and providers-fetching-retry.test.cjs lift the
real functions out of app.js and drive them with a faked api/page/timers, so
they need no browser; usage-refresh-flight.test.cjs gains the browser case for
the same race.

Makefile/.github: `make test-ui` runs every internal/gui/tests/*.test.cjs
through Node's test runner -- auto-discovered, UI_TEST_CONCURRENCY files at a
time (default 2) -- and a new `ui` job in Test runs it on ubuntu-latest with
Playwright's Chromium and WebKit. A missing browser fails the job; it never
skips to a pass. internal/gui/tests/README.md points at `make test-ui` instead
of a hand-kept command line.

Verified: node --test on the two new files 21/21; go test -count=1
./internal/plugin/ ok; go test -race -count=1 ./internal/plugin/ ok; go vet
./internal/plugin/ and go build ./... clean; node --check on the changed JS;
actionlint on the workflow.

Not verified: the full browser suite is not green yet. `make test-ui` is 1641
passed / 70 failed of 1711 across 225 files, and 12 of the 19 failing files
fail the same way on a pristine main (a known baseline: a fixture boots the
page in web mode while asserting the desktop window's narrow behaviour). The
`ui` job will be red until those baselines are dealt with -- nothing is
skipped or masked -- and the job has not yet run on a GitHub-hosted runner.

* plugin: distinguish stalled readers from large responses

* plugin: clarify best-effort abort delivery
2026-10-04 11:22:31 +08:00
Snowyy d62fecd468 plugin: reuse config parsing and avoid request body string copies (#696) 2026-10-03 22:33:49 +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 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
Snowyy 5b602b850a plugin: bound provider refreshes and wait for changes after failure (#552)
* plugin: bound provider refreshes and wait for changes after failure

* plugin: scope listing deadlines and refresh changed state immediately
2026-10-02 20:05:23 +08:00
yetone c3197ac217 plugins: magpie keeps the Bun plugins run on up to date by itself (the user: 我们能否自动去管理一个bun的版本?去自动的下载并维护这个bun的版本到最新版) — plugins ran on the one Bun magpie pinned, or on whatever $MAGPIE_BUN pointed at. Every six hours (first two minutes after start), while there are plugins, magpie now asks GitHub for Bun's newest release and takes it once it has been out two days: downloaded, its SHA-256 checked against Bun's SHASUMS, tried (it says its version, and runs a script with AsyncLocalStorage, fetch and fs), then switched to, the host restarted gracefully so a streaming reply finishes on the old one. BunVersion is the floor; the Bun before stays on disk, and a new one whose try fails, or that the host won't start on, is set aside for the one before and never taken again (bun/state.json). $MAGPIE_BUN is left alone. Plugins' page and magpie plugins show the version in use. TestCheckBunTakesASettledRelease, TestCheckBunWaitsAndKeepsTheFloor, TestCheckBunSetsAsideOneThatFailsItsTry, TestTryBunOnRealBun and TestHostFallsBackWhenTheNewBunDies pass on macOS, Linux and Windows; a real run from 1.3.14 to GitHub's 1.4.2 started the host on all three. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestFetchNewLeavesListedPlugins failed once under load, passes alone). 2026-10-01 19:33:04 +08:00