plugins: a dependency no plugin needs no longer fails another's install
CHENGJIAHEGOXIS on X (v0.1.4178, Windows) couldn't install GoAnyAPI from Plugins: "agency-agents" failed with 从缓存复制到目标目录失败, and it was on no plugin's row, so nothing could remove it. Cause: every bun add/update/remove installs every dependency in plugins/package.json again, and a failed `bun add` writes its package there before exiting 1. agency-agents (a repository with no package.json) was left by such an add; on Windows a file of its copy in node_modules is held open, Bun fails "EBUSY: failed copying files from cache to destination for package agency-agents", and so every later install failed over a package nothing used. Fix (internal/plugin/leftover.go, store.go): - A package Bun says it couldn't install that no plugin is installed as (on the list, on or off, an add in flight, pi's agent) is taken out of package.json and node_modules and the command runs again: install() and runBun, so add, update, check and remove all get it. - A failed install puts back the dependencies and bun.lock it found. - An add whose own package went in while another listed plugin's failed succeeds; that plugin keeps its dependency. - Remove and add's clean-ups drop the dependency by hand when bun remove fails. - What is left from before 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), in every language. - plugins.json there and unreadable: nothing is a leftover. - Core script budget +51 for the one call left in plugins.js (reason in core_budget_test.go). Run: - mote-run: go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok. go test ./internal/plugin (169s) and ./internal/provider (148s): ok. - mica-run go test -count=1 ./internal/gui with the leftovers drawing moved into plugininstalled.js: ok (133s); main since touches none of internal/gui's core scripts, internal/plugin or plugins.go. - win-run go test -run 'Leftover|FailedAdd|AnotherPlugin|RemoveTakes| BunFailed' ./internal/plugin on xiaomi-gpu: ok. - Reproduced the EBUSY with Bun 1.4.2 on xiaomi-gpu (a file in node_modules/agency-agents held open, then bun add another package). - Red on the old store.go: TestLeftoverDoesNotFailAnotherAdd, TestFailedAddLeavesNoDependency, TestAnotherPluginsFailureDoesNotFailAdd, TestRemoveTakesDependencyOutWhenBunFails. - GUI: plugin-leftover.test.cjs 42/42 (chromium + webkit, en zh zh-TW ja de, 980/420px, with and without a plugin); old plugins.js: 21/21 chromium red. - mote-run, rebased onfdf42299e: plugin-leftover + i18n-keys 46/46; every other plugin*.test.cjs, old-webkit and i18n-en-no-cjk: 255 ok, reds only in old-webkit (#6030, #5919), plugin-move-unserved (#4392), plugin-option-placement (#6559) and plugin-page-foreign-error (#6117), each red the same on a clean origin/mainfdf42299echeckout. Not run: the full go test ./... and the whole GUI suite (mote over its cores, mica running another session's full suite; one per machine); a real Windows install through the magpie app.
This commit is contained in:
@@ -287,6 +287,8 @@ 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).
|
||||
|
||||
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.
|
||||
|
||||
A plugin added from a git repository is reinstalled by `reinstall`'s `bun update`, which re-resolves its branch or tag where `bun add` keeps the commit `bun.lock` has. Bun resolves a git spec through its own bare clone of the repository, kept in the install cache (`installCacheDir` in [`installcache.go`](../../internal/plugin/installcache.go)), and a fetch there moves `FETCH_HEAD` but not the clone's `refs/heads`, so every resolve after the first named the first install's commit again: an update of a plugin added as an unfixed `git+https://…` URL said it had installed while the plugin, `bun.lock` and the clone all stayed at the old commit, and an uninstall followed by an add again resolved it too (#2954). `refreshGitCache` ([`gitrev.go`](../../internal/plugin/gitrev.go)) now fetches the clone's branches and tags before `install`'s `bun add` (best-effort: a remote that can't be reached leaves the install to what the cache has) and before `reinstall`'s `bun update` (an error: an update that didn't happen is not reported as done); a spec that names a commit (`#<sha>`) is left alone, for nothing is resolved for one and its pin stands. When `bun update` exits 0 but the plugin is still behind the commit the checks saw the repository at, `reinstall` says so rather than claiming the update. `TestGitUpdateInstallsTheBranchsCommitNow` and `TestGitUpdateKeepsACommitPin` (on the bun on PATH, against a local `git+file://` repository) and `TestGitUpdateSaysWhenItDidnt` (with the fake bun keeping the lock's commit, as Bun's stale cache did) in [`plugin_gitupdate_test.go`](../../internal/plugin/plugin_gitupdate_test.go) cover these.
|
||||
|
||||
@@ -4875,6 +4875,7 @@ const I18N = {
|
||||
"Install a subscription or a middleware from Discover; a subscription signs in from here.": "在「发现」中安装订阅或中间件;订阅在这里登录。",
|
||||
"Discover plugins": "发现插件",
|
||||
"Plugins run on Bun {v}": "插件运行在 Bun {v} 上",
|
||||
"Not used by any plugin": "没有插件在用",
|
||||
"Update all ({n})": "全部更新({n})",
|
||||
"Plugins updated": "插件已更新",
|
||||
"v{v} out": "v{v} 可用",
|
||||
@@ -10141,6 +10142,7 @@ const I18N = {
|
||||
"Install a subscription or a middleware from Discover; a subscription signs in from here.": "在「發現」中安裝訂閱或中介軟體;訂閱在這裡登入。",
|
||||
"Discover plugins": "發現外掛",
|
||||
"Plugins run on Bun {v}": "外掛執行在 Bun {v} 上",
|
||||
"Not used by any plugin": "沒有外掛在用",
|
||||
"Update all ({n})": "全部更新({n})",
|
||||
"Plugins updated": "外掛已更新",
|
||||
"v{v} out": "v{v} 可用",
|
||||
@@ -15432,6 +15434,7 @@ const I18N = {
|
||||
"Install a subscription or a middleware from Discover; a subscription signs in from here.": "「発見」からサブスクリプションやミドルウェアをインストールします。サブスクリプションはここからサインインします。",
|
||||
"Discover plugins": "プラグインを探す",
|
||||
"Plugins run on Bun {v}": "プラグインは Bun {v} で動作します",
|
||||
"Not used by any plugin": "どのプラグインも使っていないもの",
|
||||
"Update all ({n})": "すべてアップデート({n})",
|
||||
"Plugins updated": "プラグインをアップデートしました",
|
||||
"v{v} out": "v{v} 公開",
|
||||
@@ -20735,6 +20738,7 @@ const I18N = {
|
||||
"Install a subscription or a middleware from Discover; a subscription signs in from here.": "Installieren Sie unter Entdecken ein Abo oder eine Middleware; ein Abo meldet sich hier an.",
|
||||
"Discover plugins": "Erweiterungen entdecken",
|
||||
"Plugins run on Bun {v}": "Erweiterungen laufen auf Bun {v}",
|
||||
"Not used by any plugin": "Von keiner Erweiterung verwendet",
|
||||
"Update all ({n})": "Alle aktualisieren ({n})",
|
||||
"Plugins updated": "Erweiterungen aktualisiert",
|
||||
"v{v} out": "v{v} verfügbar",
|
||||
|
||||
@@ -37,3 +37,36 @@ window.pmInstalled = function ({ es, st, everything, entryOf, kindOf, srcOf, nam
|
||||
pop: srcs.length > 1 ? originButton(st.src, null, (v) => { st.src = v; drawBody(); }) : null,
|
||||
};
|
||||
};
|
||||
|
||||
// what a failed install left in plugins/ that no plugin is installed as:
|
||||
// Bun installs each again with every plugin, and one it can't install
|
||||
// failed them all (agency-agents, CHENGJIAHEGOXIS on X). Each can be
|
||||
// removed here, below Installed's list, empty or not.
|
||||
window.pmLeftovers = function (body, mine, logo, act, busy) {
|
||||
const ls = mine?.leftovers || [];
|
||||
if (!ls.length) return;
|
||||
const box = el("section", "pm-sec pm-leftovers");
|
||||
const h = el("div", "pm-sechead");
|
||||
h.append(el("h3", "", t("Not used by any plugin")));
|
||||
const list = el("div", "list pm-list");
|
||||
for (const x of ls) {
|
||||
const r = el("div", "row pm-row");
|
||||
r.dataset.leftover = x.name;
|
||||
const who = el("div", "who");
|
||||
const nm = el("div", "name");
|
||||
nm.append(el("span", "", x.name));
|
||||
if (x.version) nm.append(el("span", "pm-ver", "v" + x.version));
|
||||
who.append(nm);
|
||||
const val = el("div", "val");
|
||||
const key = "leftover:" + x.name;
|
||||
const rm = el("button", "text quiet", busy.get(key) === "leftover" ? t("Removing…") : t("Remove"));
|
||||
rm.title = x.spec;
|
||||
rm.disabled = busy.size > 0;
|
||||
rm.onclick = () => act(key, "leftover", { spec: x.name });
|
||||
val.append(rm);
|
||||
r.append(logo("", false), who, val);
|
||||
list.append(r);
|
||||
}
|
||||
box.append(h, list);
|
||||
body.append(box);
|
||||
};
|
||||
|
||||
@@ -1032,7 +1032,7 @@
|
||||
// the search field keeps its focus: only the body is redrawn while
|
||||
// typing, and the GitHub section's field is kept in it
|
||||
if (tab === "installed" || tab === "builtin" || !listings) body.replaceChildren();
|
||||
if (tab === "installed") return drawInstalled();
|
||||
if (tab === "installed") return drawInstalled(), window.pmLeftovers?.(body, mine, logo, act, busy);
|
||||
if (tab === "builtin") return drawBuiltin();
|
||||
if (failedList && !listings) {
|
||||
body.append(el("p", "pm-empty", t("Couldn't load the plugins: {error}", { error: failedList })));
|
||||
|
||||
File diff suppressed because one or more lines are too long
+11
-1
@@ -236,6 +236,10 @@ type pluginsJSON struct {
|
||||
// Registry is the npm registry plugins are installed from and npm's
|
||||
// answers asked of, and where it came from (plugin.Registry)
|
||||
Registry plugin.RegistryInUse `json:"registry"`
|
||||
// Leftovers are plugins/'s dependencies no plugin is installed as (a
|
||||
// failed install's, from before magpie took them out), each with a
|
||||
// Remove: Bun installs every one again at every install
|
||||
Leftovers []plugin.Leftover `json:"leftovers"`
|
||||
}
|
||||
|
||||
// registryJSON is plugin.Registry with its file's path as the page shows it.
|
||||
@@ -248,7 +252,10 @@ func registryJSON() plugin.RegistryInUse {
|
||||
}
|
||||
|
||||
func pluginsState(ctx context.Context, w Windows) pluginsJSON {
|
||||
s := pluginsJSON{Plugins: []pluginEntryJSON{}, Bun: plugin.HasBun(), BunVer: plugin.BunInUse(), Movable: provider.MoveCandidates(), Picker: w != nil && !isWeb(w), Mirror: settings.Shared().ChinaMirror, Registry: registryJSON()}
|
||||
s := pluginsJSON{Plugins: []pluginEntryJSON{}, Bun: plugin.HasBun(), BunVer: plugin.BunInUse(), Movable: provider.MoveCandidates(), Picker: w != nil && !isWeb(w), Mirror: settings.Shared().ChinaMirror, Registry: registryJSON(), Leftovers: plugin.Leftovers()}
|
||||
if s.Leftovers == nil {
|
||||
s.Leftovers = []plugin.Leftover{}
|
||||
}
|
||||
l := plugin.Load()
|
||||
errs := map[string]string{}
|
||||
names := map[string][]string{}
|
||||
@@ -594,6 +601,7 @@ var (
|
||||
removePlugin = provider.RemovePlugin
|
||||
updatePlugins = plugin.Update
|
||||
upgradePlugin = plugin.Upgrade
|
||||
dropLeftover = plugin.RemoveLeftover
|
||||
)
|
||||
|
||||
func pluginRoutes(mux *http.ServeMux, w Windows) {
|
||||
@@ -783,6 +791,8 @@ func pluginRoutes(mux *http.ServeMux, w Windows) {
|
||||
err = plugin.SetOptions(in.Spec, in.Options)
|
||||
case "prefer":
|
||||
err = plugin.Prefer(in.Spec, in.Provider)
|
||||
case "leftover":
|
||||
err = dropLeftover(ctx, in.Spec)
|
||||
default:
|
||||
http.NotFound(rw, r)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// What a failed install left in plugins/ that no plugin is installed as
|
||||
// reaches the page (leftovers), and its Remove (/api/plugins/leftover)
|
||||
// asks for that name: nothing showed agency-agents, so nothing could take
|
||||
// it out (CHENGJIAHEGOXIS on X).
|
||||
func TestPluginLeftoversReachThePage(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
t.Setenv("MAGPIE_PLUGIN_MARKET", "off")
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
if err := os.MkdirAll(plugin.Dir(), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(plugin.Dir(), "package.json"), []byte(`{"dependencies":{"agency-agents":"github:msitarzewski/agency-agents"}}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), []byte(`{"plugins":[]}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := dropLeftover
|
||||
t.Cleanup(func() { dropLeftover = old })
|
||||
var asked []string
|
||||
dropLeftover = func(ctx context.Context, name string) error { asked = append(asked, name); return nil }
|
||||
|
||||
s := pluginsState(context.Background(), nil)
|
||||
if len(s.Leftovers) != 1 || s.Leftovers[0].Name != "agency-agents" || s.Leftovers[0].Spec != "github:msitarzewski/agency-agents" {
|
||||
t.Fatalf("leftovers = %+v", s.Leftovers)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
pluginRoutes(mux, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, httptest.NewRequest("POST", "/api/plugins/leftover", strings.NewReader(`{"spec":"agency-agents"}`)))
|
||||
if rec.Code != 200 || strings.Join(asked, ",") != "agency-agents" {
|
||||
t.Fatalf("POST leftover: %d %s, asked %v", rec.Code, rec.Body, asked)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// What a failed install left in plugins/ that no plugin is installed as is
|
||||
// listed on Installed, each with a Remove (CHENGJIAHEGOXIS on X:
|
||||
// agency-agents, left by a failed add, failed every install after it with
|
||||
// "failed copying files from cache to destination", and nothing on the page
|
||||
// named it). It shows with no plugin installed too, the empty state's case,
|
||||
// and its Remove asks /api/plugins/leftover for that name.
|
||||
// No backend here: the API is faked.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const HOME = "/Users/aimer";
|
||||
const LEFT = "agency-agents";
|
||||
const lib = {
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [], instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [],
|
||||
};
|
||||
|
||||
function server(lang, state) {
|
||||
return async (route) => {
|
||||
const req = route.request();
|
||||
const url = new URL(req.url());
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
|
||||
if (url.pathname === "/api/library") return route.fulfill({ json: lib });
|
||||
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
|
||||
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
|
||||
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
|
||||
if (url.pathname === "/api/plugins/leftover" && req.method() === "POST") {
|
||||
state.asked.push(JSON.parse(req.postData() || "{}"));
|
||||
state.plugins.leftovers = [];
|
||||
return route.fulfill({ json: state.plugins });
|
||||
}
|
||||
if (url.pathname === "/api/plugins") return route.fulfill({ json: state.plugins });
|
||||
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { head: "Not used by any plugin", remove: "Remove" },
|
||||
zh: { head: "没有插件在用", remove: "移除" },
|
||||
"zh-TW": { head: "沒有外掛在用", remove: "移除" },
|
||||
ja: { head: "どのプラグインも使っていないもの", remove: "削除" },
|
||||
de: { head: "Von keiner Erweiterung verwendet", remove: "Entfernen" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": what a failed install left is listed and removable", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const errors = [];
|
||||
t.after(async () => {
|
||||
if (errors.length) console.log(errors);
|
||||
await browser.close();
|
||||
});
|
||||
for (const lang of Object.keys(words)) {
|
||||
for (const width of [980, 420]) {
|
||||
for (const installed of [false, true]) {
|
||||
await t.test(`${lang} ${width}px ${installed ? "with a plugin" : "no plugin"}`, async () => {
|
||||
const w = words[lang];
|
||||
const state = {
|
||||
asked: [],
|
||||
plugins: {
|
||||
plugins: installed ? [{ spec: "opencode-copilot-auth", providers: ["GitHub Copilot"], named: true, version: "0.1.0", moved: [] }] : [],
|
||||
bun: true, bunVersion: "1.4.2", picker: false, mirror: false,
|
||||
leftovers: [{ name: LEFT, spec: "github:msitarzewski/agency-agents" }],
|
||||
},
|
||||
};
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 800 } });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.pluginTab", "installed"); } catch {} });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, state));
|
||||
await page.goto("http://magpie.test/?view=plugins");
|
||||
const v = page.locator("#view-plugins");
|
||||
const sec = v.locator(".pm-leftovers");
|
||||
await sec.waitFor();
|
||||
assert.equal((await sec.locator("h3").innerText()).trim(), w.head);
|
||||
const row = sec.locator(`[data-leftover="${LEFT}"]`);
|
||||
assert((await row.innerText()).includes(LEFT), "the row names it");
|
||||
const rm = row.locator("button");
|
||||
assert.equal((await rm.innerText()).trim(), w.remove);
|
||||
// the row fits the page: its Remove is on screen
|
||||
const box = await rm.boundingBox();
|
||||
assert(box && box.x >= 0 && box.x + box.width <= width, `Remove off screen at ${width}px: ${JSON.stringify(box)}`);
|
||||
assert.equal(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), true, "no sideways scroll");
|
||||
await rm.click();
|
||||
await sec.waitFor({ state: "detached" });
|
||||
assert.deepEqual(state.asked, [{ spec: LEFT }]);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// A leftover is a dependency of plugins/package.json that no plugin on the
|
||||
// list is installed as. Bun keeps every dependency there and installs each
|
||||
// one again at every bun add, update and remove, so one that can't be
|
||||
// installed fails all of them, whatever plugin they are for
|
||||
// (CHENGJIAHEGOXIS on X: agency-agents, a repository of subagents with no
|
||||
// package.json, added from Plugins and never a plugin, failed every
|
||||
// install after it with "EBUSY: failed copying files from cache to
|
||||
// destination for package agency-agents" on Windows, a file of its copy
|
||||
// in node_modules held open). It got there by a bun add that failed: Bun
|
||||
// writes the dependency into package.json before it installs, and exits 1
|
||||
// with it there. Nothing listed it, so nothing could take it out.
|
||||
|
||||
// Leftover is a dependency of plugins/ no plugin is installed as, as the
|
||||
// Plugins page lists it with a Remove.
|
||||
type Leftover struct {
|
||||
Name string `json:"name"`
|
||||
// Spec is what package.json has it at
|
||||
Spec string `json:"spec"`
|
||||
// Version is the one in node_modules, "" when none is there (or
|
||||
// none that says, as a repository without a package.json)
|
||||
Version string `json:"version,omitempty"`
|
||||
// Missing is whether node_modules has no copy of it at all
|
||||
Missing bool `json:"missing,omitempty"`
|
||||
}
|
||||
|
||||
// adding are the specs an add is installing, not on the list yet: what a
|
||||
// concurrent install would otherwise take for a leftover.
|
||||
var (
|
||||
addingMu sync.Mutex
|
||||
adding = map[string]int{}
|
||||
)
|
||||
|
||||
// beingAdded marks spec as being installed for the list until done is
|
||||
// called.
|
||||
func beingAdded(spec string) (done func()) {
|
||||
addingMu.Lock()
|
||||
adding[spec]++
|
||||
addingMu.Unlock()
|
||||
return func() {
|
||||
addingMu.Lock()
|
||||
if adding[spec]--; adding[spec] <= 0 {
|
||||
delete(adding, spec)
|
||||
}
|
||||
addingMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// pkgDeps is plugins/package.json's dependencies; an error when it can't
|
||||
// be read or parsed (then nothing is a leftover: unknown, not none).
|
||||
func pkgDeps() (map[string]string, error) {
|
||||
b, err := os.ReadFile(filepath.Join(Dir(), "package.json"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pj struct {
|
||||
Dependencies map[string]string `json:"dependencies"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &pj); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pj.Dependencies, nil
|
||||
}
|
||||
|
||||
// needed is which of deps a plugin is installed as: one on the list (on
|
||||
// or off), one being added, and pi's agent while a pi plugin is listed
|
||||
// (ensurePi installs it beside them). also are more specs to count. ok is
|
||||
// false when plugins.json is there and can't be read: every dependency
|
||||
// may be a plugin's then, and none is taken for a leftover.
|
||||
func needed(deps map[string]string, also ...string) (need map[string]bool, ok bool) {
|
||||
if _, err := lastgood.Read(listPath(), lastgood.JSON); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, false
|
||||
}
|
||||
specs := slices.Clone(also)
|
||||
pi := false
|
||||
for _, e := range Load().Plugins {
|
||||
if IsPath(e.Spec) {
|
||||
pi = pi || IsPi(Target(e.Spec))
|
||||
continue
|
||||
}
|
||||
specs = append(specs, e.Spec)
|
||||
}
|
||||
addingMu.Lock()
|
||||
for s := range adding {
|
||||
specs = append(specs, s)
|
||||
}
|
||||
addingMu.Unlock()
|
||||
need = map[string]bool{}
|
||||
for _, s := range specs {
|
||||
if IsPath(s) {
|
||||
continue
|
||||
}
|
||||
for n, v := range deps {
|
||||
if v == s {
|
||||
need[n] = true
|
||||
}
|
||||
}
|
||||
if !IsGit(s) {
|
||||
need[Name(s)] = true
|
||||
}
|
||||
}
|
||||
for n := range deps {
|
||||
if need[n] && !pi && n != piAgent {
|
||||
pi = IsPi(filepath.Join(Dir(), "node_modules", filepath.FromSlash(n)))
|
||||
}
|
||||
}
|
||||
if pi {
|
||||
need[piAgent] = true
|
||||
}
|
||||
return need, true
|
||||
}
|
||||
|
||||
// Leftovers are plugins/'s dependencies no plugin is installed as, by
|
||||
// name.
|
||||
func Leftovers() []Leftover {
|
||||
deps, err := pkgDeps()
|
||||
if err != nil || len(deps) == 0 {
|
||||
return nil
|
||||
}
|
||||
need, ok := needed(deps)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
var out []Leftover
|
||||
for n, s := range deps {
|
||||
if need[n] {
|
||||
continue
|
||||
}
|
||||
l := Leftover{Name: n, Spec: s}
|
||||
at := filepath.Join(Dir(), "node_modules", filepath.FromSlash(n))
|
||||
if _, err := os.Stat(at); err != nil {
|
||||
l.Missing = true
|
||||
} else if v, known := installedVersion(n); known {
|
||||
l.Version = v
|
||||
}
|
||||
out = append(out, l)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out
|
||||
}
|
||||
|
||||
// RemoveLeftover takes the dependency name out of plugins/, refused
|
||||
// while a plugin is installed as it: bun remove, and when that fails
|
||||
// (it installs every other dependency again, and one of those can fail it
|
||||
// as well) the dependency is taken out of package.json by hand, with its
|
||||
// folder.
|
||||
func RemoveLeftover(ctx context.Context, name string) error {
|
||||
if !slices.ContainsFunc(Leftovers(), func(l Leftover) bool { return l.Name == name }) {
|
||||
return fmt.Errorf("%s isn't left in plugins/ without a plugin", name)
|
||||
}
|
||||
bun, err := Bun(ctx)
|
||||
if err != nil {
|
||||
installMu.Lock()
|
||||
defer installMu.Unlock()
|
||||
return dropDeps(name)
|
||||
}
|
||||
return removeDep(ctx, bun, name)
|
||||
}
|
||||
|
||||
// removeDep takes the dependency name out of plugins/ with bun remove,
|
||||
// and by hand when bun fails: a dependency left in package.json is
|
||||
// installed again at every bun command after.
|
||||
func removeDep(ctx context.Context, bun, name string) error {
|
||||
out, err := runBun(ctx, bun, "remove", "--ignore-scripts", name)
|
||||
deps, derr := pkgDeps()
|
||||
if err == nil && derr == nil {
|
||||
if _, still := deps[name]; !still {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("plugins: bun remove %s: %v: %s; taken out of package.json instead", name, err, lastLines(string(out), 3))
|
||||
}
|
||||
installMu.Lock()
|
||||
defer installMu.Unlock()
|
||||
return dropDeps(name)
|
||||
}
|
||||
|
||||
// dropDeps takes names out of plugins/package.json's dependencies and
|
||||
// their folders out of node_modules. Bun's lock follows package.json at
|
||||
// its next command. A folder that can't be removed (a file in it held
|
||||
// open on Windows) stays; with no dependency naming it Bun never copies
|
||||
// it again. installMu held.
|
||||
func dropDeps(names ...string) error {
|
||||
pj := filepath.Join(Dir(), "package.json")
|
||||
b, err := os.ReadFile(pj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal(b, &obj); err != nil {
|
||||
return err
|
||||
}
|
||||
var deps map[string]json.RawMessage
|
||||
if raw, ok := obj["dependencies"]; ok {
|
||||
if err := json.Unmarshal(raw, &deps); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
changed := false
|
||||
for _, n := range names {
|
||||
if _, ok := deps[n]; ok {
|
||||
delete(deps, n)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
raw, err := json.Marshal(deps)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
obj["dependencies"] = raw
|
||||
out, err := json.MarshalIndent(obj, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := edit.WriteAtomic(pj, append(out, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var errs []error
|
||||
for _, n := range names {
|
||||
if n == "" || strings.Contains(n, "..") {
|
||||
continue
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Join(Dir(), "node_modules", filepath.FromSlash(n))); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
if len(errs) > 0 {
|
||||
log.Printf("plugins: %s out of package.json; its folder stays: %v", strings.Join(names, ", "), errors.Join(errs...))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// bunFailedPkg is a package Bun says it couldn't install: "EBUSY: failed
|
||||
// copying files from cache to destination for package <name>", "EACCES:
|
||||
// Permission denied while installing <name>".
|
||||
var bunFailedPkg = lazyre.New(`(?m)(?:failed [a-z /]+ for package|while installing) (@?[A-Za-z0-9._~-]+(?:/[A-Za-z0-9._~-]+)?)\s*$`)
|
||||
|
||||
var ansi = lazyre.New(`\x1b\[[0-9;]*m|</?[a-z]>`)
|
||||
|
||||
// bunFailed is the packages out says Bun couldn't install.
|
||||
func bunFailed(out string) []string {
|
||||
out = ansi.ReplaceAllString(out, "")
|
||||
var names []string
|
||||
for _, m := range bunFailedPkg.FindAllStringSubmatch(out, -1) {
|
||||
if n := strings.TrimRight(m[1], "."); !slices.Contains(names, n) {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// bunRunError is a bun command's failure, with all it said.
|
||||
type bunRunError struct {
|
||||
err error
|
||||
out string
|
||||
}
|
||||
|
||||
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.
|
||||
func failedOf(err error) []string {
|
||||
var be *bunRunError
|
||||
if errors.As(err, &be) {
|
||||
return bunFailed(be.out)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// depsState is plugins/package.json's dependencies and bun.lock before
|
||||
// a bun add, to put back what the add wrote when it failed.
|
||||
type depsState struct {
|
||||
deps map[string]string
|
||||
ok bool
|
||||
lock []byte
|
||||
// hadLock is whether bun.lock was there
|
||||
hadLock bool
|
||||
}
|
||||
|
||||
func depsNow() depsState {
|
||||
s := depsState{}
|
||||
var err error
|
||||
s.deps, err = pkgDeps()
|
||||
s.ok = err == nil
|
||||
if b, err := os.ReadFile(filepath.Join(Dir(), "bun.lock")); err == nil {
|
||||
s.lock, s.hadLock = b, true
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if !s.ok {
|
||||
return
|
||||
}
|
||||
now, err := pkgDeps()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var added []string
|
||||
back := map[string]string{}
|
||||
for n, v := range now {
|
||||
was, had := s.deps[n]
|
||||
switch {
|
||||
case !had:
|
||||
added = append(added, n)
|
||||
case was != v && !slices.Contains(gone, n):
|
||||
back[n] = was
|
||||
}
|
||||
}
|
||||
if len(added) > 0 {
|
||||
log.Printf("plugins: a failed install left %s in package.json; taken out", strings.Join(added, ", "))
|
||||
_ = dropDeps(added...)
|
||||
}
|
||||
if len(back) > 0 {
|
||||
_ = setDeps(back)
|
||||
}
|
||||
if s.hadLock {
|
||||
_ = edit.WriteAtomic(filepath.Join(Dir(), "bun.lock"), s.lock)
|
||||
}
|
||||
}
|
||||
|
||||
// setDeps sets dependencies of plugins/package.json to the specs given.
|
||||
// installMu held.
|
||||
func setDeps(to map[string]string) error {
|
||||
pj := filepath.Join(Dir(), "package.json")
|
||||
b, err := os.ReadFile(pj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal(b, &obj); err != nil {
|
||||
return err
|
||||
}
|
||||
deps := map[string]json.RawMessage{}
|
||||
if raw, ok := obj["dependencies"]; ok {
|
||||
if err := json.Unmarshal(raw, &deps); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for n, v := range to {
|
||||
deps[n], _ = json.Marshal(v)
|
||||
}
|
||||
raw, err := json.Marshal(deps)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
obj["dependencies"] = raw
|
||||
out, err := json.MarshalIndent(obj, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return edit.WriteAtomic(pj, append(out, '\n'))
|
||||
}
|
||||
|
||||
// dropBroken takes out of plugins/ the dependencies err says Bun couldn't
|
||||
// install that no plugin is installed as (also: specs being installed
|
||||
// now), and says which: each would fail every bun command after. installMu
|
||||
// held.
|
||||
func dropBroken(err error, also ...string) []string {
|
||||
failed := failedOf(err)
|
||||
if len(failed) == 0 {
|
||||
return nil
|
||||
}
|
||||
deps, derr := pkgDeps()
|
||||
if derr != nil {
|
||||
return nil
|
||||
}
|
||||
need, ok := needed(deps, also...)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
var gone []string
|
||||
for _, n := range failed {
|
||||
if _, in := deps[n]; in && !need[n] {
|
||||
gone = append(gone, n)
|
||||
}
|
||||
}
|
||||
if len(gone) == 0 {
|
||||
return nil
|
||||
}
|
||||
log.Printf("plugins: Bun couldn't install %s, which no plugin is installed as; taken out of plugins/", strings.Join(gone, ", "))
|
||||
if dropDeps(gone...) != nil {
|
||||
return nil
|
||||
}
|
||||
return gone
|
||||
}
|
||||
|
||||
// othersFailed is whether err, a failed bun add of spec, is only another
|
||||
// package's failure, spec's own package installed: the add of it is done,
|
||||
// and the plugin Bun couldn't install says so in its own row.
|
||||
func othersFailed(err error, spec string) bool {
|
||||
failed := failedOf(err)
|
||||
if len(failed) == 0 {
|
||||
return false
|
||||
}
|
||||
name := Name(spec)
|
||||
if name == spec && IsGit(spec) || slices.Contains(failed, name) {
|
||||
return false
|
||||
}
|
||||
if deps, derr := pkgDeps(); derr != nil || deps[name] == "" {
|
||||
return false
|
||||
}
|
||||
v, known := installedVersion(name)
|
||||
return known && v != ""
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// agency is CHENGJIAHEGOXIS's leftover: a repository with no package.json,
|
||||
// in plugins/package.json from an add that failed, on no plugin's entry.
|
||||
const agency = "agency-agents"
|
||||
|
||||
// depsSandbox is offSandbox with plugins/package.json's dependencies and
|
||||
// node_modules as given (a folder each, with a package.json for those
|
||||
// with a version), and plugins.json as list.
|
||||
func depsSandbox(t *testing.T, deps map[string]string, list string) {
|
||||
t.Helper()
|
||||
offSandbox(t)
|
||||
if err := os.MkdirAll(Dir(), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := setDeps(deps); err != nil {
|
||||
// no package.json yet: setDeps reads one first
|
||||
if err := os.WriteFile(filepath.Join(Dir(), "package.json"), []byte(`{"name":"magpie-plugins","private":true}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := setDeps(deps); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for n, s := range deps {
|
||||
at := filepath.Join(Dir(), "node_modules", filepath.FromSlash(n))
|
||||
if err := os.MkdirAll(at, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if IsGit(s) {
|
||||
// agency-agents: markdown, no package.json
|
||||
if err := os.WriteFile(filepath.Join(at, "README.md"), []byte("# agents\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
v := strings.TrimPrefix(strings.TrimPrefix(s, n), "@")
|
||||
if err := os.WriteFile(filepath.Join(at, "package.json"), []byte(`{"name":"`+n+`","version":"`+v+`","main":"index.js"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(at, "index.js"), []byte("export default async () => ({})\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
writeList(t, list)
|
||||
}
|
||||
|
||||
func depsOf(t *testing.T) map[string]string {
|
||||
t.Helper()
|
||||
d, err := pkgDeps()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func ctxMinute(t *testing.T) context.Context {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
t.Cleanup(cancel)
|
||||
return ctx
|
||||
}
|
||||
|
||||
// The reporter's case: a dependency no plugin is installed as, which Bun
|
||||
// can't install again (a file of its copy held open on Windows), failed
|
||||
// every add after it. It is taken out, and the add goes on.
|
||||
func TestLeftoverDoesNotFailAnotherAdd(t *testing.T) {
|
||||
depsSandbox(t, map[string]string{agency: "github:msitarzewski/agency-agents"}, `{"plugins":[]}`)
|
||||
t.Setenv("MAGPIE_FAKE_BUN_BUSY", agency)
|
||||
const spec = "opencode-goany-auth@1.0.0"
|
||||
if _, err := AddExact(ctxMinute(t), spec); err != nil {
|
||||
t.Fatalf("add failed over a leftover no plugin needs: %v", err)
|
||||
}
|
||||
if !slices.ContainsFunc(Load().Plugins, func(e Entry) bool { return e.Spec == spec }) {
|
||||
t.Fatalf("%s not listed: %+v", spec, Load().Plugins)
|
||||
}
|
||||
d := depsOf(t)
|
||||
if _, in := d[agency]; in {
|
||||
t.Fatalf("the leftover is still a dependency: %v", d)
|
||||
}
|
||||
if d["opencode-goany-auth"] != spec {
|
||||
t.Fatalf("the plugin isn't a dependency: %v", d)
|
||||
}
|
||||
if l := Leftovers(); len(l) != 0 {
|
||||
t.Fatalf("leftovers after: %+v", l)
|
||||
}
|
||||
}
|
||||
|
||||
// A failed add takes out what Bun wrote into package.json for it: else it
|
||||
// is a leftover that every bun command installs again.
|
||||
func TestFailedAddLeavesNoDependency(t *testing.T) {
|
||||
depsSandbox(t, map[string]string{}, `{"plugins":[]}`)
|
||||
t.Setenv("MAGPIE_FAKE_BUN_BUSY", "opencode-broken-auth")
|
||||
if _, err := AddExact(ctxMinute(t), "opencode-broken-auth@1.0.0"); err == nil {
|
||||
t.Fatal("an add Bun failed succeeded")
|
||||
}
|
||||
if d := depsOf(t); len(d) != 0 {
|
||||
t.Fatalf("a failed add left %v in package.json", d)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(Dir(), "node_modules", "opencode-broken-auth")); !os.IsNotExist(err) {
|
||||
t.Fatalf("its folder stays: %v", err)
|
||||
}
|
||||
if len(Load().Plugins) != 0 {
|
||||
t.Fatalf("listed: %+v", Load().Plugins)
|
||||
}
|
||||
}
|
||||
|
||||
// Another plugin's package Bun can't install fails no other add once that
|
||||
// one is in: the other plugin keeps its dependency (it is listed), and
|
||||
// its own row says what's wrong with it.
|
||||
func TestAnotherPluginsFailureDoesNotFailAdd(t *testing.T) {
|
||||
const other = "opencode-other-auth"
|
||||
depsSandbox(t, map[string]string{other: other + "@1.0.0"}, `{"plugins":[{"spec":"`+other+`@1.0.0"}]}`)
|
||||
t.Setenv("MAGPIE_FAKE_BUN_BUSY", other)
|
||||
const spec = "opencode-goany-auth@1.0.0"
|
||||
if _, err := AddExact(ctxMinute(t), spec); err != nil {
|
||||
t.Fatalf("add 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["opencode-goany-auth"] != spec {
|
||||
t.Fatalf("the plugin added 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.
|
||||
func TestRemoveTakesDependencyOutWhenBunFails(t *testing.T) {
|
||||
const p = "opencode-gone-auth"
|
||||
depsSandbox(t, map[string]string{p: p + "@1.0.0", "opencode-kept-auth": "opencode-kept-auth@1.0.0"},
|
||||
`{"plugins":[{"spec":"`+p+`@1.0.0"},{"spec":"opencode-kept-auth@1.0.0"}]}`)
|
||||
t.Setenv("MAGPIE_FAKE_BUN_NOREMOVE", "1")
|
||||
if err := Remove(ctxMinute(t), p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := depsOf(t)
|
||||
if _, in := d[p]; in {
|
||||
t.Fatalf("still a dependency after Remove: %v", d)
|
||||
}
|
||||
if d["opencode-kept-auth"] == "" {
|
||||
t.Fatalf("another plugin's dependency went too: %v", d)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(Dir(), "node_modules", p)); !os.IsNotExist(err) {
|
||||
t.Fatalf("its folder stays: %v", err)
|
||||
}
|
||||
if l := Leftovers(); len(l) != 0 {
|
||||
t.Fatalf("leftovers: %+v", l)
|
||||
}
|
||||
}
|
||||
|
||||
// Leftovers lists what no plugin is installed as, and RemoveLeftover takes
|
||||
// out only that.
|
||||
func TestLeftoversListedAndRemoved(t *testing.T) {
|
||||
const p = "opencode-kept-auth"
|
||||
depsSandbox(t, map[string]string{agency: "github:msitarzewski/agency-agents", p: p + "@1.0.0"}, `{"plugins":[{"spec":"`+p+`@1.0.0","off":true}]}`)
|
||||
l := Leftovers()
|
||||
if len(l) != 1 || l[0].Name != agency || l[0].Spec != "github:msitarzewski/agency-agents" || l[0].Missing {
|
||||
t.Fatalf("leftovers = %+v", l)
|
||||
}
|
||||
if err := RemoveLeftover(ctxMinute(t), p); err == nil {
|
||||
t.Fatal("removed a plugin's dependency (one turned off) as a leftover")
|
||||
}
|
||||
// Bun can't copy it again either: the remove goes on by hand
|
||||
t.Setenv("MAGPIE_FAKE_BUN_BUSY", agency)
|
||||
t.Setenv("MAGPIE_FAKE_BUN_NOREMOVE", "1")
|
||||
if err := RemoveLeftover(ctxMinute(t), agency); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := depsOf(t)
|
||||
if _, in := d[agency]; in || d[p] == "" {
|
||||
t.Fatalf("dependencies after = %v", d)
|
||||
}
|
||||
if l := Leftovers(); len(l) != 0 {
|
||||
t.Fatalf("leftovers after = %+v", l)
|
||||
}
|
||||
}
|
||||
|
||||
// plugins.json there and unreadable: which dependencies are plugins is
|
||||
// unknown, and none is a leftover (none taken out, none offered).
|
||||
func TestNoLeftoversWhenListUnreadable(t *testing.T) {
|
||||
depsSandbox(t, map[string]string{"opencode-kept-auth": "opencode-kept-auth@1.0.0"}, `{"plugins":[`)
|
||||
if l := Leftovers(); len(l) != 0 {
|
||||
t.Fatalf("leftovers with plugins.json unreadable = %+v", l)
|
||||
}
|
||||
if err := RemoveLeftover(ctxMinute(t), "opencode-kept-auth"); err == nil {
|
||||
t.Fatal("removed a dependency with plugins.json unreadable")
|
||||
}
|
||||
if gone := dropBroken(&bunRunError{err: os.ErrInvalid, out: "EBUSY: failed copying files from cache to destination for package opencode-kept-auth"}); len(gone) != 0 {
|
||||
t.Fatalf("dropped %v with plugins.json unreadable", gone)
|
||||
}
|
||||
}
|
||||
|
||||
// Bun's words for a package it couldn't install, as 1.4.2 prints them
|
||||
// (colour codes and its <b>/<r> tags too).
|
||||
func TestBunFailed(t *testing.T) {
|
||||
for out, want := range map[string][]string{
|
||||
"EBUSY: failed copying files from cache to destination for package agency-agents": {agency},
|
||||
"\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,
|
||||
} {
|
||||
if got := bunFailed(out); !slices.Equal(got, want) {
|
||||
t.Errorf("bunFailed(%q) = %v, want %v", out, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package plugin
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
@@ -143,6 +144,9 @@ func fakeBun(args []string) error {
|
||||
lock[name] = commit
|
||||
}
|
||||
case "remove":
|
||||
if os.Getenv("MAGPIE_FAKE_BUN_NOREMOVE") == "1" {
|
||||
return errors.New("error: lockfile had changes, but lockfile is frozen")
|
||||
}
|
||||
for _, n := range args[2:] {
|
||||
delete(deps, n)
|
||||
delete(lock, n)
|
||||
@@ -157,7 +161,18 @@ func fakeBun(args []string) error {
|
||||
return err
|
||||
}
|
||||
b, _ = json.Marshal(lock)
|
||||
return os.WriteFile("fake.lock", b, 0o644)
|
||||
if err := os.WriteFile("fake.lock", b, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
// 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)
|
||||
if n := os.Getenv("MAGPIE_FAKE_BUN_BUSY"); n != "" && deps[n] != "" {
|
||||
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")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fakeFetch clones spec's repository and puts the package in it at
|
||||
|
||||
+49
-10
@@ -22,6 +22,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"maps"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -88,7 +89,13 @@ func runBun(ctx context.Context, bun string, args ...string) ([]byte, error) {
|
||||
mendPackageJSON()
|
||||
defer mendPackageJSON()
|
||||
mendDist(ctx, bun)
|
||||
return bunCommand(ctx, bun, Dir(), args...).CombinedOutput()
|
||||
out, err := bunCommand(ctx, bun, Dir(), args...).CombinedOutput()
|
||||
// a dependency no plugin is installed as that Bun couldn't install
|
||||
// fails every command: taken out, and the command run again
|
||||
if err != nil && len(dropBroken(&bunRunError{err, string(out)})) > 0 {
|
||||
out, err = bunCommand(ctx, bun, Dir(), args...).CombinedOutput()
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
// mendPackageJSON cuts what follows plugins/package.json's object off. Bun
|
||||
@@ -415,6 +422,7 @@ func add(ctx context.Context, spec, version string) (Entry, error) {
|
||||
if spec == "" {
|
||||
return Entry{}, errors.New("no plugin given")
|
||||
}
|
||||
defer beingAdded(spec)()
|
||||
// the package each plugin is before the install, which may take a git
|
||||
// one's name over (one repository in place of another, or of npm's)
|
||||
was := map[string]string{}
|
||||
@@ -453,12 +461,18 @@ func add(ctx context.Context, spec, version string) (Entry, error) {
|
||||
// installed just now for this, and nothing loads it: taken out again
|
||||
if !IsPath(spec) && !slices.Contains(slices.Collect(maps.Values(was)), Name(spec)) {
|
||||
if bun, berr := Bun(ctx); berr == nil {
|
||||
_, _ = runBun(ctx, bun, "remove", "--ignore-scripts", Name(spec))
|
||||
_ = removeDep(ctx, bun, Name(spec))
|
||||
}
|
||||
}
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := ensurePi(ctx, Target(spec)); err != nil {
|
||||
// nothing loads it without pi's agent: taken out again, as above
|
||||
if !IsPath(spec) && !slices.Contains(slices.Collect(maps.Values(was)), Name(spec)) {
|
||||
if bun, berr := Bun(ctx); berr == nil {
|
||||
_ = removeDep(ctx, bun, Name(spec))
|
||||
}
|
||||
}
|
||||
return Entry{}, err
|
||||
}
|
||||
listMu.Lock()
|
||||
@@ -622,8 +636,10 @@ func Remove(ctx context.Context, name string) error {
|
||||
return err
|
||||
}
|
||||
if !IsPath(e.Spec) {
|
||||
if bun, err := Bun(ctx); err == nil {
|
||||
_, _ = runBun(ctx, bun, "remove", "--ignore-scripts", Name(e.Spec))
|
||||
// another entry of the same package (a folder's spec aside) still
|
||||
// needs it
|
||||
if bun, err := Bun(ctx); err == nil && !slices.ContainsFunc(l.Plugins, func(x Entry) bool { return !IsPath(x.Spec) && Name(x.Spec) == Name(e.Spec) }) {
|
||||
_ = removeDep(ctx, bun, Name(e.Spec))
|
||||
}
|
||||
}
|
||||
Restart()
|
||||
@@ -766,7 +782,19 @@ func install(ctx context.Context, spec string) error {
|
||||
// before (#2954)
|
||||
_ = refreshGitCache(ctx, spec)
|
||||
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
|
||||
@@ -775,15 +803,26 @@ 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 {
|
||||
return fmt.Errorf("%w (and from the community repo's dist branch: %v)", err, derr)
|
||||
err = fmt.Errorf("%w (and from the community repo's dist branch: %v)", err, derr)
|
||||
} else {
|
||||
err = nil
|
||||
}
|
||||
}
|
||||
// another plugin's package Bun couldn't install, and this one in: the
|
||||
// add is done, and that plugin's row says what is wrong with it
|
||||
if err != nil && othersFailed(err, spec) {
|
||||
log.Printf("plugins: %s installed; Bun couldn't install %s: %v", spec, strings.Join(failedOf(err), ", "), err)
|
||||
err = nil
|
||||
}
|
||||
if err == nil {
|
||||
pruneDist()
|
||||
pruneInstallCache()
|
||||
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)
|
||||
return err
|
||||
}
|
||||
return err
|
||||
pruneDist()
|
||||
pruneInstallCache()
|
||||
return nil
|
||||
}
|
||||
|
||||
// bunAdd adds spec to plugins/ with bun, its scripts left unrun.
|
||||
@@ -797,7 +836,7 @@ func bunAdd(ctx context.Context, bun, spec string) error {
|
||||
if ue := wontLoad(bun, err); ue != nil {
|
||||
return fmt.Errorf("bun add %s: %w", spec, ue)
|
||||
}
|
||||
return fmt.Errorf("bun add %s: %v: %s", spec, cantStart(bun, err), lastLines(string(out), 6))
|
||||
return &bunRunError{fmt.Errorf("bun add %s: %v: %s", spec, cantStart(bun, err), lastLines(string(out), 6)), string(out)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user