plugins: an add from the dist branch drops a leftover too (CHENGJIAHEGOXIS on X)

CHENGJIAHEGOXIS (Windows) still couldn't install GoAnyAPI from Plugins
after v0.1.4205's leftover fix:

  bun add @magpie-community/tools-goanyapi@latest: exit status 1: ...
  error: GET https://registry.npmjs.org/@magpie-community%2ftools-goanyapi - 404
  (and from the community repo's dist branch: bun add
  ./dist/magpie-community-tools-goanyapi-0.1.1.tgz: exit status 1:
  Unexpected: failed copying files from cache to destination for package
  agency-agents
  installed @magpie-community/tools-goanyapi@./dist/...-0.1.1.tgz
  Failed to install 2 packages)

GoAnyAPI isn't on npm (its first version waits for an owner's publish,
as 77 other community packages do), so the add goes to the dist branch.
ec97a4d7b's drop-and-retry ran only after the npm add, whose 404 names no
broken package; installDist's bun add had none. And the dist error was
wrapped with %v, so othersFailed read only the npm try's output and
failed an add whose own package had gone in ("installed ..."). The
"Unexpected:" wording was already matched by bunFailed.

Fix:
- bunAdd does the drop-and-retry itself (dropBroken, then once more), so
  every bun add has it: npm's and the dist tarball's (which keeps the
  package's name, its spec being a path).
- The dist error wraps both tries (%w), and failedOf reads every
  bunRunError in the tree, so othersFailed sees what Bun said from dist.
- depsState.undo loses its gone list: a dropped dependency isn't in
  package.json when undo reads it, so the list never changed anything.
- Fake bun: MAGPIE_FAKE_BUN_NPM404 (Bun 1.4.4's 404, nothing written),
  ./dist/*.tgz adds, MAGPIE_FAKE_BUN_BUSY_SAYS (the reporter's literal
  Bun output).
- docs/subsystems/provider-plugins.md says so.

Tests: TestLeftoverDoesNotFailADistAdd, TestAnotherPluginsFailureDoes
NotFailADistAdd (reporter's bytes), TestBunFailed (+ the literal output,
LF and CRLF).

Run:
- Both new tests red on origin/main's store.go/leftover.go/dist.go
  (the reporter's error, word for word), green with the fix (mote).
- mica-run at this tree: go vet ./internal/plugin/...,
  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 ./internal/plugin/...: ok (150s).
- win-run go test ./internal/plugin/: only TestPiPackage red (fixture
  spawns `sh`), the same alone at origin/main 6256d9956; filed in #4115.
- mote-run go test -tags nogui -timeout 45m ./... at this tree (base
  6256d9956): 100 packages ok, internal/gateway red on
  TestKeyLimitReservationsStayInTheirWindow account/* only, red alone at
  6256d9956 too: filed #6706.
- gofmt -l: nothing.

Not tried: a real Windows bun with a held agency-agents copy (the
reporter's machine state); npm side needs an owner (no NPM_TOKEN secret,
trusted publishing can't create a package).
This commit is contained in:
yetone
2026-11-15 04:36:29 +08:00
parent 6256d9956a
commit ab08a9e7c1
6 changed files with 180 additions and 27 deletions
+1 -1
View File
@@ -287,7 +287,7 @@ A `@magpie-community` package npm doesn't give is installed from the community r
A plugin on the list whose package isn't in `plugins/` is installed again from its own spec, switched off or not, by `plugin.InstallMissing`. `KeepUpdated` runs it 30 seconds after start and then hourly, before `CheckUpdates`. Nothing else did this. An update skips a plugin with no installed version, so the host said `no such plugin: …\node_modules\…` at every start until the user removed the plugin and added it again (#2002, Windows, after an update). Every bun command that changes `plugins/` runs one at a time under `installMu`: `install` (with the first `package.json` it writes, through temp and rename), `reinstall`'s `bun update`, and `Remove`'s and `add`'s `bun remove`, each after `mendPackageJSON` and then `mendDist`, which reads `package.json`. At start, `KeepUpdated` and `keepMovedCurrent` both run `bun add`. Two at once each read `package.json` before either writes it, so one change was lost (reproduced with Bun 1.4.3 on Windows), and a git plugin whose dependency was dropped can't be found. `TestMissingPluginsInstalledAgain` and `TestBunCommandsOneAtATime` in [`plugin_missing_test.go`](../../internal/plugin/plugin_missing_test.go) cover both.
Every `bun add`, `bun update` and `bun remove` installs every dependency in `plugins/package.json` again, and Bun writes a package it adds there before it installs and exits 1 with it there. So a dependency no plugin is installed as, which Bun then can't install, failed every install of any plugin after it: CHENGJIAHEGOXIS on X (v0.1.4178, Windows) couldn't install GoAnyAPI over agency-agents, a repository with no `package.json` left by an add that failed, with "EBUSY: failed copying files from cache to destination for package agency-agents" (a file of its copy in `node_modules` held open, reproduced with Bun 1.4.2 on Windows), and nothing on the page named it. [`leftover.go`](../../internal/plugin/leftover.go) now: a package Bun says it couldn't install (`bunFailed`: "failed … for package <name>", "while installing <name>") that no plugin is installed as (`needed`: an entry on the list, on or off, an add in flight, pi's agent beside a pi plugin) is taken out of `package.json` and `node_modules` and the command run again (`dropBroken`, in `install` and `runBun`); a failed `install` puts back the dependencies and `bun.lock` it found (`depsState.undo`); an add whose own package is in while another listed plugin's failed is done (`othersFailed`), that plugin's row saying what is wrong; `Remove` and `add`'s clean-ups take the dependency out by hand when `bun remove` fails (`removeDep`). What is left from before (`plugin.Leftovers`) is listed under Installed as "Not used by any plugin", each with a Remove (`/api/plugins` `leftovers`, `POST /api/plugins/leftover`, `pmLeftovers` in `plugininstalled.js`, imported when Plugins first draws). With `plugins.json` there and unreadable nothing is a leftover. The fake bun's `MAGPIE_FAKE_BUN_BUSY` and `MAGPIE_FAKE_BUN_NOREMOVE` stand in for the Windows failure: `TestLeftoverDoesNotFailAnotherAdd`, `TestFailedAddLeavesNoDependency`, `TestAnotherPluginsFailureDoesNotFailAdd`, `TestRemoveTakesDependencyOutWhenBunFails`, `TestLeftoversListedAndRemoved`, `TestNoLeftoversWhenListUnreadable` and `TestBunFailed` in [`leftover_test.go`](../../internal/plugin/leftover_test.go), `TestPluginLeftoversReachThePage` in internal/gui, and `plugin-leftover.test.cjs` (both engines, every language, 980px and 420px).
Every `bun add`, `bun update` and `bun remove` installs every dependency in `plugins/package.json` again, and Bun writes a package it adds there before it installs and exits 1 with it there. So a dependency no plugin is installed as, which Bun then can't install, failed every install of any plugin after it: CHENGJIAHEGOXIS on X (v0.1.4178, Windows) couldn't install GoAnyAPI over agency-agents, a repository with no `package.json` left by an add that failed, with "EBUSY: failed copying files from cache to destination for package agency-agents" (a file of its copy in `node_modules` held open, reproduced with Bun 1.4.2 on Windows), and nothing on the page named it. [`leftover.go`](../../internal/plugin/leftover.go) now: a package Bun says it couldn't install (`bunFailed`: "failed … for package <name>", "while installing <name>") that no plugin is installed as (`needed`: an entry on the list, on or off, an add in flight, pi's agent beside a pi plugin) is taken out of `package.json` and `node_modules` and the command run again (`dropBroken`, in `bunAdd` and `runBun`, so the dist branch's add of a package npm doesn't have gets it too: on v0.1.4205 the same reporter's GoAnyAPI, on no npm, failed from dist over agency-agents with Bun 1.4.4's "Unexpected: failed copying files … for package agency-agents", as only the npm add was cleared); a failed `install` puts back the dependencies and `bun.lock` it found (`depsState.undo`); an add whose own package is in while another listed plugin's failed is done (`othersFailed`, reading what Bun said at both the npm and the dist try: `failedOf` walks every wrapped error), that plugin's row saying what is wrong; `Remove` and `add`'s clean-ups take the dependency out by hand when `bun remove` fails (`removeDep`). What is left from before (`plugin.Leftovers`) is listed under Installed as "Not used by any plugin", each with a Remove (`/api/plugins` `leftovers`, `POST /api/plugins/leftover`, `pmLeftovers` in `plugininstalled.js`, imported when Plugins first draws). With `plugins.json` there and unreadable nothing is a leftover. The fake bun's `MAGPIE_FAKE_BUN_BUSY` and `MAGPIE_FAKE_BUN_NOREMOVE` stand in for the Windows failure: `TestLeftoverDoesNotFailAnotherAdd`, `TestFailedAddLeavesNoDependency`, `TestAnotherPluginsFailureDoesNotFailAdd`, `TestLeftoverDoesNotFailADistAdd`, `TestAnotherPluginsFailureDoesNotFailADistAdd` (with `MAGPIE_FAKE_BUN_NPM404` and the reporter's Bun output in `MAGPIE_FAKE_BUN_BUSY_SAYS`), `TestRemoveTakesDependencyOutWhenBunFails`, `TestLeftoversListedAndRemoved`, `TestNoLeftoversWhenListUnreadable` and `TestBunFailed` in [`leftover_test.go`](../../internal/plugin/leftover_test.go), `TestPluginLeftoversReachThePage` in internal/gui, and `plugin-leftover.test.cjs` (both engines, every language, 980px and 420px).
A name the user types is resolved before anything is installed (`resolve` in [`resolve.go`](../../internal/plugin/resolve.go)), in `plugin.Add`, which the CLI's `magpie plugin add`, the Plugins page's field (`/api/plugins/add`) and the movers all go through. A bare name that one of the community's listings goes by, case aside, is that package at the version given: its package or that without the scope, its short name (`workbuddy`, `think-tags`), its shown name (`WorkBuddy`, `Command Code`), a provider id it serves or the subscription it replaces, and a retired subscription's id through its mover (`qoder-cn`, `plugin.SubscriptionPlugin` = `MovePackage`). A name two listings go by, or one no listing goes by that isn't an npm name, is refused with the community plugins named. A name no listing goes by is npm's own package (`opencode-gemini-auth`) only when the list was fetched within the six hours: when the fetch fails, the copy kept or built in may not name a newer plugin, so the name is refused with why, and `npm:<name>` installs npm's package as written. Before, `WorkBuddy` failed as no npm name, and `workbuddy` installed npm's unscoped `workbuddy` (Atlas on Discord, 10-25). Scoped names, paths and git specs are kept as written, and a backup's or a sync's plugins are installed by their own spec (`plugin.AddExact`), never resolved. `TestResolveCommunityNames`, `TestResolveRefusesWhatItCantName`, `TestResolveListUnread` and `TestAddByCommunityName` in [`resolve_test.go`](../../internal/plugin/resolve_test.go) cover these.
+1 -1
View File
@@ -350,7 +350,7 @@ func installDist(ctx context.Context, bun, name, version string) error {
os.Remove(tmp.Name())
return werr
}
return bunAdd(ctx, bun, "./dist/"+file)
return bunAdd(ctx, bun, "./dist/"+file, name)
}
// pruneDist takes out the tarballs in plugins/dist that neither
+27 -9
View File
@@ -282,13 +282,30 @@ func (e *bunRunError) Error() string { return e.err.Error() }
func (e *bunRunError) Unwrap() error { return e.err }
// failedOf is the packages err, a bun command's failure, says Bun
// couldn't install.
// couldn't install: at every try it wraps (an add from npm, then from the
// dist branch).
func failedOf(err error) []string {
var be *bunRunError
if errors.As(err, &be) {
return bunFailed(be.out)
var names []string
var walk func(error)
walk = func(err error) {
switch e := err.(type) {
case nil:
case *bunRunError:
for _, n := range bunFailed(e.out) {
if !slices.Contains(names, n) {
names = append(names, n)
}
}
case interface{ Unwrap() []error }:
for _, w := range e.Unwrap() {
walk(w)
}
case interface{ Unwrap() error }:
walk(e.Unwrap())
}
}
return nil
walk(err)
return names
}
// depsState is plugins/package.json's dependencies and bun.lock before
@@ -314,9 +331,10 @@ func depsNow() depsState {
// undo puts back what a failed bun add wrote: a dependency it added is
// taken out with its folder, one it changed goes back to the spec it had,
// and bun.lock to what it was. One known to be broken (gone) since stays
// gone. installMu held.
func (s depsState) undo(gone []string) {
// and bun.lock to what it was. One taken out since (a leftover Bun
// couldn't install) isn't in package.json now, and stays out. installMu
// held.
func (s depsState) undo() {
if !s.ok {
return
}
@@ -331,7 +349,7 @@ func (s depsState) undo(gone []string) {
switch {
case !had:
added = append(added, n)
case was != v && !slices.Contains(gone, n):
case was != v:
back[n] = was
}
}
+65
View File
@@ -134,6 +134,69 @@ func TestAnotherPluginsFailureDoesNotFailAdd(t *testing.T) {
}
}
// goanyapi is CHENGJIAHEGOXIS's plugin: not on npm yet, so it is added
// from the community repo's dist branch.
const goanyapi = "@magpie-community/tools-goanyapi"
// goanyapiBusy is what Bun 1.4.4 said adding GoAnyAPI's dist tarball on
// the reporter's Windows (v0.1.4205's error, its lines as Bun prints
// them): "Unexpected:", not "EBUSY:", and GoAnyAPI itself installed.
const goanyapiBusy = "bun add v1.4.4 (38afee6c8)\nResolving dependencies\nResolved, downloaded and extracted [1]\n" +
"Unexpected: failed copying files from cache to destination for package agency-agents\n\n" +
"installed @magpie-community/tools-goanyapi@./dist/magpie-community-tools-goanyapi-0.1.1.tgz\n\n" +
"Failed to install 2 packages\n[38.00ms] done\n"
// goanyapiSandbox is depsSandbox with npm having no GoAnyAPI and the dist
// branch its 0.1.1, and Bun failing over busy as the reporter's did.
func goanyapiSandbox(t *testing.T, deps map[string]string, list, busy string) {
t.Helper()
depsSandbox(t, deps, list)
npmHasNothing(t)
fakeDist(t, map[string][]string{goanyapi: {"0.1.1"}}, false)
t.Setenv("MAGPIE_FAKE_BUN_NPM404", goanyapi)
t.Setenv("MAGPIE_FAKE_BUN_BUSY", busy)
t.Setenv("MAGPIE_FAKE_BUN_BUSY_SAYS", strings.ReplaceAll(goanyapiBusy, "agency-agents", busy))
}
// The reporter's case on v0.1.4205: GoAnyAPI isn't on npm, and its add
// from the dist branch failed over the leftover, which only the npm add
// was cleared of. Every add has it: the dist branch's too.
func TestLeftoverDoesNotFailADistAdd(t *testing.T) {
goanyapiSandbox(t, map[string]string{agency: "github:msitarzewski/agency-agents"}, `{"plugins":[]}`, agency)
const spec = goanyapi + "@latest"
if _, err := AddExact(ctxMinute(t), spec); err != nil {
t.Fatalf("add from dist failed over a leftover no plugin needs: %v", err)
}
d := depsOf(t)
if _, in := d[agency]; in {
t.Fatalf("the leftover is still a dependency: %v", d)
}
if d[goanyapi] != "./dist/magpie-community-tools-goanyapi-0.1.1.tgz" {
t.Fatalf("GoAnyAPI isn't a dependency at its dist tarball: %v", d)
}
if !slices.ContainsFunc(Load().Plugins, func(e Entry) bool { return Name(e.Spec) == goanyapi }) {
t.Fatalf("GoAnyAPI not listed: %+v", Load().Plugins)
}
}
// Another listed plugin's package Bun can't install fails no add from the
// dist branch either, once the add's own package went in ("installed
// …"): what Bun said there is read, not only the npm try's 404.
func TestAnotherPluginsFailureDoesNotFailADistAdd(t *testing.T) {
const other = "opencode-other-auth"
goanyapiSandbox(t, map[string]string{other: other + "@1.0.0"}, `{"plugins":[{"spec":"`+other+`@1.0.0"}]}`, other)
if _, err := AddExact(ctxMinute(t), goanyapi+"@latest"); err != nil {
t.Fatalf("add from dist failed over another plugin's package: %v", err)
}
d := depsOf(t)
if d[other] != other+"@1.0.0" {
t.Fatalf("a listed plugin's dependency was taken out: %v", d)
}
if d[goanyapi] == "" {
t.Fatalf("GoAnyAPI isn't a dependency: %v", d)
}
}
// Removing a plugin takes its dependency out though bun remove fails
// (which installs every other dependency again, and one of them can fail
// it): ignored, it stayed, a leftover.
@@ -210,6 +273,8 @@ func TestBunFailed(t *testing.T) {
"\x1b[31merror\x1b[0m: failed copying files from cache to destination for package <b>@scope/pkg<r>\n": {"@scope/pkg"},
"EACCES: Permission denied while installing opencode-x-auth\nEBUSY: failed copying files from cache to destination for package agency-agents": {"opencode-x-auth", agency},
"error: GET https://registry.npmjs.org/x - 404": nil,
goanyapiBusy: {agency},
strings.ReplaceAll(goanyapiBusy, "\n", "\r\n"): {agency},
} {
if got := bunFailed(out); !slices.Equal(got, want) {
t.Errorf("bunFailed(%q) = %v, want %v", out, got, want)
+64
View File
@@ -1,6 +1,8 @@
package plugin
import (
"archive/tar"
"compress/gzip"
"context"
"encoding/json"
"errors"
@@ -105,6 +107,34 @@ func fakeBun(args []string) error {
return nil // as bun: the lock's commit stays
}
}
// a package npm doesn't have, as Bun 1.4.4 says it: nothing written
if n := os.Getenv("MAGPIE_FAKE_BUN_NPM404"); n != "" && !IsPath(spec) && Name(spec) == n {
fmt.Println("bun add v1.4.4 (38afee6c8)")
fmt.Println("Resolving dependencies")
fmt.Println("Resolved, downloaded and extracted [1]")
fmt.Println("error: GET https://registry.npmjs.org/" + strings.Replace(n, "/", "%2f", 1) + " - 404")
return errors.New("exit 1")
}
// a tarball of plugins/dist (installDist): the package it holds
if IsPath(spec) && strings.HasSuffix(spec, ".tgz") {
name, v, err := fakeTarball(spec)
if err != nil {
return err
}
at := filepath.Join("node_modules", filepath.FromSlash(name))
if err := os.MkdirAll(at, 0o755); err != nil {
return err
}
b, _ := json.Marshal(map[string]string{"name": name, "version": v, "main": "index.js"})
if err := os.WriteFile(filepath.Join(at, "index.js"), []byte("export default async () => ({})\n"), 0o644); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(at, "package.json"), b, 0o644); err != nil {
return err
}
deps[name] = spec
break
}
if !IsGit(spec) {
name := Name(spec)
at := filepath.Join("node_modules", filepath.FromSlash(name))
@@ -167,7 +197,12 @@ func fakeBun(args []string) error {
// as bun does on Windows with a file of a package's copy held open:
// package.json written, then every command fails over that package
// while it is a dependency (CHENGJIAHEGOXIS's agency-agents)
// ($MAGPIE_FAKE_BUN_BUSY_SAYS: Bun's whole output instead)
if n := os.Getenv("MAGPIE_FAKE_BUN_BUSY"); n != "" && deps[n] != "" {
if says := os.Getenv("MAGPIE_FAKE_BUN_BUSY_SAYS"); says != "" {
fmt.Print(says)
return errors.New("exit 1")
}
fmt.Println("bun add v1.4.2 (fake)")
fmt.Println("EBUSY: failed copying files from cache to destination for package " + n)
return errors.New("exit 1")
@@ -175,6 +210,35 @@ func fakeBun(args []string) error {
return nil
}
// fakeTarball is the name and version of the package in the tarball at
// path.
func fakeTarball(path string) (name, version string, err error) {
f, err := os.Open(path)
if err != nil {
return "", "", err
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
return "", "", err
}
tr := tar.NewReader(gz)
for {
h, err := tr.Next()
if err != nil {
return "", "", fmt.Errorf("%s has no package/package.json: %v", path, err)
}
if h.Name != "package/package.json" {
continue
}
var p struct{ Name, Version string }
if err := json.NewDecoder(tr).Decode(&p); err != nil {
return "", "", err
}
return p.Name, p.Version, nil
}
}
// fakeFetch clones spec's repository and puts the package in it at
// node_modules/<its name>.
func fakeFetch(spec string) (name, commit string, err error) {
+22 -16
View File
@@ -784,17 +784,6 @@ func install(ctx context.Context, spec string) error {
mendDist(ctx, bun)
before := depsNow()
err = bunAdd(ctx, bun, spec)
// Bun writes the dependency into package.json before it installs, and
// exits 1 with it there when any package fails, this one or another.
// One no plugin is installed as (a failed add's, before this was
// put back) failed every add after it: taken out, and the add tried
// again
var gone []string
if err != nil {
if gone = dropBroken(err, spec); len(gone) > 0 {
err = bunAdd(ctx, bun, spec)
}
}
// a @magpie-community package or version npm doesn't have (a new
// one waits for an owner to publish it there) comes from the
// community repo's dist branch; one Bun's minimumReleaseAge holds
@@ -803,7 +792,8 @@ func install(ctx context.Context, spec string) error {
var ue *BunUnstartableError
if name, version, ok := distWanted(spec); ok && err != nil && !minAge.MatchString(err.Error()) && !errors.As(err, &ue) {
if derr := installDist(ctx, bun, name, version); derr != nil {
err = fmt.Errorf("%w (and from the community repo's dist branch: %v)", err, derr)
// both wrapped: what Bun said at either try is read (failedOf)
err = fmt.Errorf("%w (and from the community repo's dist branch: %w)", err, derr)
} else {
err = nil
}
@@ -817,7 +807,7 @@ func install(ctx context.Context, spec string) error {
if err != nil {
// nothing of a failed add stays: a dependency left in package.json
// is installed again at every bun command, and no plugin lists it
before.undo(gone)
before.undo()
return err
}
pruneDist()
@@ -825,9 +815,25 @@ func install(ctx context.Context, spec string) error {
return nil
}
// bunAdd adds spec to plugins/ with bun, its scripts left unrun.
// installMu held.
func bunAdd(ctx context.Context, bun, spec string) error {
// bunAdd adds spec to plugins/ with bun, its scripts left unrun. keep
// are more packages the add is for (a dist tarball's: its spec is a
// path). installMu held.
//
// Bun writes the dependency into package.json before it installs, and
// exits 1 with it there when any package fails, this one or another. One
// no plugin is installed as (a failed add's, before that was put back)
// failed every add after it: taken out, and the add tried again. Here, so
// every add has it: the dist branch's too (CHENGJIAHEGOXIS on X, v0.1.4205:
// GoAnyAPI, not on npm, failed from dist over agency-agents).
func bunAdd(ctx context.Context, bun, spec string, keep ...string) error {
err := bunAddOnce(ctx, bun, spec)
if err != nil && len(dropBroken(err, append([]string{spec}, keep...)...)) > 0 {
err = bunAddOnce(ctx, bun, spec)
}
return err
}
func bunAddOnce(ctx context.Context, bun, spec string) error {
out, err := bunCommand(ctx, bun, Dir(), "add", "--ignore-scripts", spec).CombinedOutput()
if err != nil {
if hint := missingLibs(string(out)); hint != "" {