Files
yetone 7d5db0f29a cli: a command that ends ends its plugin hosts, and one that doesn't serve starts none (#7146)
athemeroy (WangYeruo on X) runs `magpie serve` as a LaunchAgent with the
magpie-google-ai-studio browser plugin and 11 accounts. Each
`magpie --version`, `version`, `licenses` or `group <id>` run beside it
left a second magpie-bun host with PPID 1, holding the Chrome profiles
the gateway's host wanted ("Chrome exited before starting WebView").
Their analysis was right on each count:

- plugin.Cached starts a background list of the plugins' providers
  whenever this process hasn't listed them (provGood is in memory), so
  every short command reaching provider.Catalog (startUp's RenameLegacy,
  groups, models, ...) started a host.
- Main ended through os.Exit and never stopped it. A host whose stdin
  closes leaves only once nothing is pending, and a plugin holding a
  browser keeps Bun up meanwhile, so the host outlived magpie, adopted
  by init. SIGTERM (launchd stopping serve) orphaned serve's own host
  the same way.
- --version and licenses were answered after startUp.

Now:
- Cached asks the plugins in the background only when
  plugin.ListInBackground is on; run sets it from servesPages (app,
  web, serve, TUI). Other commands read the list on disk.
- Main ends through exit(), which runs plugin.EndHosts first, on
  success and error; die does too on SIGINT/SIGTERM/SIGHUP, bounded by
  hostsOnSignal (20s, past the 15s a renewing host gets).
- provider test returns exitError instead of os.Exit(1).
- -v/--version/version and licenses answer before any start-up work.

Audit of the os.Exit calls in internal/cli: data_cli.go:135 and the
CheckEnv exit in Main run before anything can start a host;
claudeLetGo already called EndHosts.

Tests (red on the old code, the non-test sources reverted to
14b6b9555, green with the fix):
- TestOneShotCommandsStartNoPluginHost: groups, group fakeco, models,
  providers, accounts each started a host (5 reds); version, --version,
  -v, licenses and agents start none; Cached in a serving magpie still
  lists.
- TestExitEndsPluginHosts: a real host whose stuck usage hook holds it
  up (new STUCK_USAGE_HOLD, STUCK_PID in testdata/stuck), the magpie
  ended by `version`, by an error and by SIGTERM: all three left the
  host at PPID 1 on the old code, none now. 10 of 10 on macOS, 3 of 3
  on Linux (WSL), version/error on Windows (no SIGTERM there).
- TestSessionCommandsSkipStartUp: version/--version/-v/licenses don't
  run startUp (red on the old code for version). Three tests that used
  `version` to reach startUp/makeDirs use `groups`.

Real use, sandbox HOME on mote, a plugin whose provider list takes 90s
holding a timer, signed in with a key, `magpie serve` running:
- old binary: groups, group holdco and models each left a magpie-bun
  at PPID 1; after SIGTERM to serve, serve's host was at PPID 1 too
  (4 left).
- new binary: only serve's host, and none left after SIGTERM. The
  commands take 0.02-0.15s.

Run at the pushed head:
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build: ok (mote).
- go test -count=1 -timeout 45m ./... on mote: 102 packages ok, two
  red, each red the same at the base 14b6b9555 (-count=3/5 there):
  internal/cli TestHealthcheckFindsTheRunningGatewayWithoutMagpieAddr,
  TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr and
  TestUpdateFindsAMagpieThatWroteNoRecord (#6471, #6223: an ssh
  session's forward holds 127.0.0.1:3425 on mote), and internal/gateway
  TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117).
- Rebased on 598bc4534 (it changes internal/cli's update code), at
  the pushed head: go test ./internal/cli ./internal/plugin on mote:
  plugin ok; cli ok but for the same three #6471 reds.

Not tried: the reporter's real Google AI Studio plugin with Chrome, and
a real LaunchAgent stop (launchctl); the repro sends serve SIGTERM as
launchd does.
2026-11-19 10:38:25 +08:00

75 lines
3.2 KiB
JavaScript

// A plugin whose vendor never lets it through, as one whose sign-in is
// answered 401 and tried again for ever: with $STUCK_LOAD set its plugin
// function never returns, with $STUCK_MODELS set its models hook never
// does, and with $STUCK_USAGE set its usage hook doesn't either — but not
// before saying what its caller handed it, and whether an abort reaches it,
// to the file $STUCK_TRACE names (#4678).
const never = () => new Promise(() => {})
import fs from "node:fs"
// traceUsage says what the host handed the hook: a signal it can listen to,
// and, later, that the abort arrived, one JSON line each.
function traceUsage(options) {
const signal = options?.signal
const live = signal && typeof signal.addEventListener === "function"
fs.appendFileSync(process.env.STUCK_TRACE, JSON.stringify({ signal: live ? (signal.aborted ? "aborted" : "live") : "none" }) + "\n")
if (live && !signal.aborted) {
signal.addEventListener("abort", () => fs.appendFileSync(process.env.STUCK_TRACE, JSON.stringify({ aborted: true }) + "\n"), { once: true })
}
}
export const StuckPlugin = async () => {
// with $STUCK_PID set, the process the plugin runs in says who it is,
// for a test that looks for it once magpie has exited (#7146)
if (process.env.STUCK_PID) fs.writeFileSync(process.env.STUCK_PID, String(process.pid))
if (process.env.STUCK_LOAD) await never()
return {
config: async (cfg) => {
cfg.provider = cfg.provider ?? {}
cfg.provider.stuckco = {
name: "StuckCo",
npm: "@ai-sdk/openai-compatible",
api: "https://stuck.invalid/v1",
models: { "stuck-1": { name: "Stuck One", limit: { context: 1000, output: 100 } } },
}
},
provider: {
id: "stuckco",
async models(provider, options) {
if (process.env.STUCK_MODELS_TRACE) traceUsage(options)
if (process.env.STUCK_MODELS) await never()
return provider.models
},
},
auth: {
provider: "stuckco",
methods: [{ type: "api", label: "API key" }],
loader: async () => ({ baseURL: "https://stuck.invalid/v1" }),
usage: async (_getAuth, _provider, options) => {
if (process.env.STUCK_USAGE) {
traceUsage(options)
// with $STUCK_USAGE_LINGER set, an abort ends the hook that many
// ms later, as a hook still saving a renewed sign-in would, and it
// says so first
const linger = Number(process.env.STUCK_USAGE_LINGER)
if (linger > 0 && options?.signal) {
await new Promise((ok) => options.signal.addEventListener("abort", () => setTimeout(() => {
fs.appendFileSync(process.env.STUCK_TRACE, JSON.stringify({ finished: true }) + "\n")
ok()
}, linger), { once: true }))
} else if (process.env.STUCK_USAGE_HOLD) {
// with $STUCK_USAGE_HOLD set, it holds something open while it
// waits, as a plugin driving a browser holds the browser: a
// promise alone keeps no process alive once stdin has closed
// (#7146)
setInterval(() => {}, 1 << 30)
await never()
} else await never()
}
return { windows: [] }
},
},
}
}