diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index e1b1382ef..4e31f0823 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4100,6 +4100,7 @@ const I18N = { "{name}: not signed in": "{name}:未登录", "{name} is a subscription of its own; {other} works without it": "{name} 是独立订阅,{other} 无需它也能使用", "{name} updated to v{v}": "{name} 已更新到 v{v}", + "{name} updated to {commit}": "{name} 已更新到 {commit}", "Removing…": "移除中…", "Downloads": "下载量", "License": "许可证", @@ -8436,6 +8437,7 @@ const I18N = { "{name}: not signed in": "{name}:未登入", "{name} is a subscription of its own; {other} works without it": "{name} 是獨立訂閱,{other} 無需它也能使用", "{name} updated to v{v}": "{name} 已更新到 v{v}", + "{name} updated to {commit}": "{name} 已更新到 {commit}", "Removing…": "移除中…", "Downloads": "下載量", "License": "許可證", @@ -12793,6 +12795,7 @@ const I18N = { "{name}: not signed in": "{name}:未サインイン", "{name} is a subscription of its own; {other} works without it": "{name} は独立したサブスクリプションです。{other} はそれなしで動作します", "{name} updated to v{v}": "{name} を v{v} にアップデートしました", + "{name} updated to {commit}": "{name} を {commit} にアップデートしました", "Removing…": "削除中…", "Downloads": "ダウンロード数", "License": "ライセンス", @@ -17164,6 +17167,7 @@ const I18N = { "{name}: not signed in": "{name}: nicht angemeldet", "{name} is a subscription of its own; {other} works without it": "{name} ist ein eigenes Abo; {other} funktioniert ohne es", "{name} updated to v{v}": "{name} auf v{v} aktualisiert", + "{name} updated to {commit}": "{name} auf {commit} aktualisiert", "Removing…": "Wird entfernt…", "Downloads": "Downloads", "License": "Lizenz", diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 4b42e1acf..bc19e7ecc 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -298,6 +298,7 @@ try { await api("plugins/" + op, body); busy.delete(pkg); + for (const e of mine?.plugins || []) if (op === "update" || e.spec === body?.spec) delete heads[e.spec]; // stale once installed (#4802) await refresh(); if (done) done(); } catch (e) { @@ -464,7 +465,11 @@ } else b.title = t("Fetches it from {repo} again", { repo: e.spec }) + "\n" + t("{have} installed, {repo} is at {head}", { have: e.commit, repo: e.spec, head: e.head }); b.onclick = (ev) => { ev.stopPropagation(); - act(pkg, "upgrade", { spec: e.spec }, () => status(npm ? t("{name} updated to v{v}", { name: l?.name || pkg, v: e.latest }) : t("{name} is up to date", { name: shownName(e) }), "ok")); + const was = e.commit; + act(pkg, "upgrade", { spec: e.spec }, () => { + const now = mine?.plugins?.find((x) => x.spec === e.spec)?.commit; + status(npm ? t("{name} updated to v{v}", { name: l?.name || pkg, v: e.latest }) : now && was && !sameCommit(now, was) ? t("{name} updated to {commit}", { name: shownName(e), commit: now }) : t("{name} is up to date", { name: shownName(e) }), "ok"); + }); }; b.onkeydown = (ev) => ev.stopPropagation(); return true; @@ -1198,7 +1203,7 @@ nm.append(c); } else if ((ck?.status === "current" || ck?.status === "update") && e.version) { const c = el("span", "pm-chip soft", t("Up to date")); - c.title = (isGit(e.spec) ? t("{head} is the newest commit of {repo}", { head: ck.head || e.head || "", repo: e.spec }) : t("v{v} is the newest on npm", { v: e.version })) + "\n" + t("Last checked {time}", { time: checkedAt() }); + c.title = (isGit(e.spec) ? t("{head} is the newest commit of {repo}", { head: e.head || ck.head || "", repo: e.spec }) : t("v{v} is the newest on npm", { v: e.version })) + "\n" + t("Last checked {time}", { time: checkedAt() }); nm.append(c); } // built-ins moved onto it, then its other providers if 2+ (#3902) diff --git a/internal/gui/tests/plugin-git.test.cjs b/internal/gui/tests/plugin-git.test.cjs index 172b7618b..01b7bf508 100644 --- a/internal/gui/tests/plugin-git.test.cjs +++ b/internal/gui/tests/plugin-git.test.cjs @@ -8,8 +8,11 @@ // github:yuweihao17/codearts showed Update all the time, and still did // right after updating it): at the same commit there is no Update, nor // Update all; once the repository moves on, Check for updates shows New -// commits and an Update that fetches it again, and after it there is none. -// Its +// commits and an Update that fetches it again, and after it there is none, +// even when the repository moved on again after the check and the update +// installed a commit newer than the one it found (matrix0487, #4802: New +// commits and Update all stayed, and Update said it was up to date; these +// are the reporter's commits). Its // page is the README it was installed with, with no npm link and a Source // link to the repository. A click scrolls nothing. English and Chinese; the // API is faked here. @@ -22,8 +25,9 @@ const { chromium, webkit } = require("playwright"); const assets = path.resolve(__dirname, "../assets"); const SPEC = "github:owner/repo"; -const HAVE = "c594984"; -const NEXT = "8fd2d9a"; +const HAVE = "fdaa691"; +const NEXT = "3b411a5"; // what Check for updates finds +const LATER = "ba898e7"; // pushed after it: what Update installs const README = ["# my-oc-plugin", "", "A plugin installed from its repository."].join("\n"); function server(lang, asked, repo) { @@ -62,7 +66,11 @@ function server(lang, asked, repo) { } if (url.pathname === "/api/plugins/upgrade") { asked.push(["upgrade", body()]); - installed[0].commit = repo.head; // the version in its package.json stays + // bun installs what the repository is at now, and the update asks + // the repository again, as the plugins' own head says; the version + // in its package.json stays + if (repo.after) repo.head = repo.after; + installed[0].commit = installed[0].head = repo.head; return json({}); } if (url.pathname === "/api/open") { asked.push(["open", body()]); return route.fulfill({ status: 204 }); } @@ -75,8 +83,8 @@ function server(lang, asked, repo) { } const L = { - en: { hint: "npm package, GitHub repo (github:owner/repo) or a folder", install: "Install", installed: "Installed", update: "Update", check: "Check for updates", all: "Update all", fresh: "New commits", done: "my-oc-plugin is up to date", source: "Source" }, - zh: { hint: "npm 包名、GitHub 仓库(github:owner/repo)或本机文件夹", install: "安装", installed: "已安装", update: "更新", check: "检查更新", all: "全部更新", fresh: "有新提交", done: "my-oc-plugin 已是最新", source: "源码" }, + en: { hint: "npm package, GitHub repo (github:owner/repo) or a folder", install: "Install", installed: "Installed", update: "Update", check: "Check for updates", all: "Update all", fresh: "New commits", done: "my-oc-plugin updated to " + LATER, source: "Source" }, + zh: { hint: "npm 包名、GitHub 仓库(github:owner/repo)或本机文件夹", install: "安装", installed: "已安装", update: "更新", check: "检查更新", all: "全部更新", fresh: "有新提交", done: "my-oc-plugin 已更新到 " + LATER, source: "源码" }, }; const shot = async (loc, name) => { @@ -152,13 +160,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.match(await bar.locator("button", { hasText: w.all }).innerText(), /1/); await shot(view, `plugins-git-installed-${engine}-${lang}`); const before2 = await scrolls(page); + // the repository moves on again after the check, before Update + repo.after = LATER; await up.click(); - await page.waitForFunction((n) => [...document.querySelectorAll("#view-plugins .pm-row .pm-ver")].some((x) => x.textContent.trim() === n), NEXT); + await page.waitForFunction((n) => [...document.querySelectorAll("#view-plugins .pm-row .pm-ver")].some((x) => x.textContent.trim() === n), LATER); assert.deepEqual(asked.find(([k]) => k === "upgrade")[1], { spec: SPEC }); assert.equal(await scrolls(page), before2, "Update scrolls nothing"); assert.match(await page.locator("body").innerText(), new RegExp(w.done)); // updated: no Update stays behind (it did, before) - assert.deepEqual(await vers(), ["v1.0.0", NEXT]); + assert.deepEqual(await vers(), ["v1.0.0", LATER]); assert.equal(await up.count(), 0, "updated, there is nothing to update"); assert.equal(await row.locator(".pm-chip", { hasText: w.fresh }).count(), 0); assert.equal(await bar.locator("button", { hasText: w.all }).count(), 0); diff --git a/internal/plugin/market.go b/internal/plugin/market.go index 9c3450319..273abbe9d 100644 --- a/internal/plugin/market.go +++ b/internal/plugin/market.go @@ -794,6 +794,9 @@ func Upgrade(ctx context.Context, name string) error { for _, e := range Load().Plugins { if (Name(e.Spec) == name || e.Spec == name) && IsGit(e.Spec) { err := reinstall(ctx, e.Spec) + if err == nil { + settleWaiting() + } Restart() return err } diff --git a/internal/plugin/store.go b/internal/plugin/store.go index b35388a9c..14586001b 100644 --- a/internal/plugin/store.go +++ b/internal/plugin/store.go @@ -490,6 +490,7 @@ func add(ctx context.Context, spec, version string) (Entry, error) { if err := save(l); err != nil { return Entry{}, err } + settleWaiting() Restart() return e, nil } @@ -587,6 +588,7 @@ func Update(ctx context.Context) error { errs = append(errs, fmt.Errorf("%s: %w", e.Spec, err)) } } + settleWaiting() Restart() return errors.Join(errs...) } @@ -967,6 +969,7 @@ func reinstall(ctx context.Context, spec string) error { if err := refreshGitCache(ctx, spec); err != nil { return err } + was := GitCommit(spec) out, err := runBun(ctx, bun, "update", "--ignore-scripts", name) if err != nil { if hint := missingLibs(string(out)); hint != "" { @@ -980,14 +983,17 @@ func reinstall(ctx context.Context, spec string) error { // what the checks saw the repository at (the page's, before the // reader pressed update) is what the update was to install: bun // exiting 0 has meant the old commit stayed before, and the reader is - // to hear so rather than be told the update is done (#2954) + // to hear so rather than be told the update is done (#2954). One + // that moved has installed what bun resolved, newer than the answer + // when the repository moved on after it (#4802): it isn't told it + // stayed because the repository couldn't be asked again. if head := GitHeadCached(spec); head != "" && GitBehind(spec, head) { // the answer stood for a while: the repository may have moved on // again since, so it is asked now before this is reported if now, err := GitHead(ctx, spec, true); err == nil && now != "" { head = now } - if GitBehind(spec, head) { + if GitBehind(spec, head) && SameCommit(GitCommit(spec), was) { return fmt.Errorf("bun update %s left it at %s, though its repository is at %s", name, short(GitCommit(spec)), short(head)) } } diff --git a/internal/plugin/updates.go b/internal/plugin/updates.go index 21d22bea1..3e20ed29e 100644 --- a/internal/plugin/updates.go +++ b/internal/plugin/updates.go @@ -128,24 +128,61 @@ func writeUpdates(b []byte) error { return writeWhole(updatesPath(), b) } +// waitsNoMore is whether an update the last look found waits no more: the +// plugin was updated, removed or switched off since. A git one waits only +// while the commit installed is still the one the look saw installed and +// its repository's commit then is another: the repository may move on +// between the look and the reader's Update, which then installs a commit +// newer than the look's, and that kept the dot and Update all up till the +// next look, an hour later, Update only saying it was up to date +// (matrix0487, #4802: fdaa691 installed, 3b411a5 found, ba898e7 updated to). +func waitsNoMore(have map[string]Entry) func(Waiting) bool { + return func(w Waiting) bool { + e, ok := have[w.Package] + if ok && w.Git { + return e.Off || e.Spec != w.Spec || !GitBehind(e.Spec, w.Latest) || !SameCommit(GitCommit(e.Spec), w.Version) + } + return !ok || e.Off || !update.Newer(w.Latest, Installed(e.Spec)) + } +} + +// installedNow is each plugin on the list by its package. +func installedNow() map[string]Entry { + have := map[string]Entry{} + for _, e := range Load().Plugins { + have[Name(e.Spec)] = e + } + return have +} + +// settleWaiting writes plugin-updates.json again without the updates that +// wait no more, after an install or update: what the reader has just +// updated isn't kept on file as waiting until the next look rewrites it. +func settleWaiting() { + updatesMu.Lock() + defer updatesMu.Unlock() + u := readUpdates() + n := len(u.Waiting) + if n == 0 { + return + } + if u.Waiting = slices.DeleteFunc(u.Waiting, waitsNoMore(installedNow())); len(u.Waiting) == n { + return + } + if b, err := json.MarshalIndent(u, "", " "); err == nil { + if err := os.MkdirAll(settings.Dir(), 0o700); err == nil { + _ = writeUpdates(b) + } + } +} + // PendingUpdates is what the last look found, less what has changed since: // a plugin updated, removed or switched off since waits no more. func PendingUpdates() Updates { updatesMu.Lock() defer updatesMu.Unlock() u := readUpdates() - have := map[string]Entry{} - for _, e := range Load().Plugins { - have[Name(e.Spec)] = e - } - u.Waiting = slices.DeleteFunc(u.Waiting, func(w Waiting) bool { - e, ok := have[w.Package] - if ok && w.Git { - // updated since: the commit installed is the one it was at - return e.Off || e.Spec != w.Spec || !GitBehind(e.Spec, w.Latest) - } - return !ok || e.Off || !update.Newer(w.Latest, Installed(e.Spec)) - }) + u.Waiting = slices.DeleteFunc(u.Waiting, waitsNoMore(installedNow())) if u.Waiting == nil { u.Waiting = []Waiting{} } @@ -268,6 +305,7 @@ func InstallMissing(ctx context.Context) (int, error) { n++ } if n > 0 { + settleWaiting() Restart() } return n, errors.Join(errs...) diff --git a/internal/plugin/updates_settle_test.go b/internal/plugin/updates_settle_test.go new file mode 100644 index 000000000..4ea3e48de --- /dev/null +++ b/internal/plugin/updates_settle_test.go @@ -0,0 +1,190 @@ +package plugin + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" +) + +// the reporter's (matrix0487, #4802): the look found 3b411a5 with fdaa691 +// installed; the repository moved on to ba898e7 twenty seconds later, and +// the reader's Update installed that +const ( + reportSpec = "github:faithleysath/magpie-oh-my-aihub" + reportPkg = "@oh-my-aihub/magpie-plugin" + reportWas = "fdaa691" + reportSeen = "3b411a5" + reportNow = "ba898e7" +) + +// updatesSandbox is a HOME of the test's own. +func updatesSandbox(t *testing.T) { + t.Helper() + dir := t.TempDir() + t.Setenv("HOME", dir) + t.Setenv("USERPROFILE", dir) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache")) + forgetHeads() + t.Cleanup(forgetHeads) +} + +// gitInstalledAt fakes the git plugin spec installed as package pkg at +// commit, as bun leaves it: package.json naming the spec, and the +// package's .bun-tag (owner-repo- for GitHub's). +func gitInstalledAt(t *testing.T, spec, pkg, tag string) { + t.Helper() + if err := os.MkdirAll(filepath.Join(Dir(), "node_modules", filepath.FromSlash(pkg)), 0o755); err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(map[string]any{"dependencies": map[string]string{pkg: spec}}) + if err := os.WriteFile(filepath.Join(Dir(), "package.json"), b, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(Target(spec), ".bun-tag"), []byte(tag), 0o644); err != nil { + t.Fatal(err) + } + b, _ = json.Marshal(map[string]string{"name": pkg, "version": "0.7.0"}) + if err := os.WriteFile(filepath.Join(Target(spec), "package.json"), b, 0o644); err != nil { + t.Fatal(err) + } +} + +// writeWaiting writes plugin-updates.json as a look leaves it. +func writeWaiting(t *testing.T, ws ...Waiting) { + t.Helper() + b, _ := json.MarshalIndent(Updates{Checked: time.Date(2026, 11, 1, 14, 38, 55, 0, time.UTC), Waiting: ws, Updated: []Updated{}}, "", " ") + if err := os.MkdirAll(filepath.Dir(updatesPath()), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(updatesPath(), b, 0o600); err != nil { + t.Fatal(err) + } +} + +// A git plugin updated to a commit newer than the one the last look found +// waits no more: the dot and Update all stayed up till the next look, an +// hour later, because only the very commit the look found counted as +// updated to (matrix0487, #4802). One still at the commit the look saw +// installed waits. +func TestGitWaitingGoneOnceUpdatedPastTheLook(t *testing.T) { + report := Waiting{Spec: reportSpec, Package: reportPkg, Version: reportWas, Latest: reportSeen, Git: true} + for _, c := range []struct { + name, tag string + waits bool + }{ + {"updated past the look", "faithleysath-magpie-oh-my-aihub-" + reportNow, false}, + {"updated to the look's", "faithleysath-magpie-oh-my-aihub-" + reportSeen, false}, + {"not updated", "faithleysath-magpie-oh-my-aihub-" + reportWas, true}, + // installed again some other way: not the one the look saw installed + {"another install", "faithleysath-magpie-oh-my-aihub-1234567", false}, + } { + t.Run(c.name, func(t *testing.T) { + updatesSandbox(t) + if err := save(List{Plugins: []Entry{{Spec: reportSpec}}}); err != nil { + t.Fatal(err) + } + gitInstalledAt(t, reportSpec, reportPkg, c.tag) + writeWaiting(t, report) + if got := PendingUpdates().Waiting; (len(got) == 1) != c.waits { + t.Fatalf("installed %s (look: %s installed, %s found): Waiting = %+v, want waiting %v", c.tag, reportWas, reportSeen, got, c.waits) + } + }) + } + + // a commit pinned in the spec: once installed at the pin it waits no more + t.Run("pinned", func(t *testing.T) { + updatesSandbox(t) + const pinned = reportSpec + "#" + reportNow + if err := save(List{Plugins: []Entry{{Spec: pinned}}}); err != nil { + t.Fatal(err) + } + gitInstalledAt(t, pinned, reportPkg, "faithleysath-magpie-oh-my-aihub-"+reportNow) + writeWaiting(t, Waiting{Spec: pinned, Package: reportPkg, Version: reportWas, Latest: reportNow, Git: true}) + if got := PendingUpdates().Waiting; len(got) != 0 { + t.Fatalf("at its pin, Waiting = %+v", got) + } + }) +} + +// An install or update writes plugin-updates.json again without what it +// updated, rather than leaving the look's answer on file till the next +// look (#4802); an npm one updated past the version the look found too. +func TestSettleWaitingRewritesTheRecord(t *testing.T) { + updatesSandbox(t) + const theirs = "opencode-gemini-auth" + if err := save(List{Plugins: []Entry{{Spec: reportSpec}, {Spec: theirs + "@latest"}}}); err != nil { + t.Fatal(err) + } + gitInstalledAt(t, reportSpec, reportPkg, "faithleysath-magpie-oh-my-aihub-"+reportNow) + installedAt(t, theirs, "1.2.0") + writeWaiting(t, + Waiting{Spec: reportSpec, Package: reportPkg, Version: reportWas, Latest: reportSeen, Git: true}, + Waiting{Spec: theirs + "@latest", Package: theirs, Version: "1.0.0", Latest: "1.1.0"}, + ) + settleWaiting() + if got := readUpdates(); len(got.Waiting) != 0 || !got.Checked.Equal(time.Date(2026, 11, 1, 14, 38, 55, 0, time.UTC)) { + t.Fatalf("on file after settling: %+v, want nothing waiting and the look's time kept", got) + } +} + +// The reporter's sequence through Upgrade and Update all, with the fake +// bun and GitHub: the look finds one commit, the repository moves on, the +// reader updates. Nothing waits after it, on file or in what the page is +// told, without another look; the update is done even when the repository +// can't be asked again after it. +func TestGitUpdatePastTheLookWaitsNoMore(t *testing.T) { + for _, op := range []string{"upgrade", "update", "upgrade, GitHub down after"} { + t.Run(op, func(t *testing.T) { + github, _ := gitSandbox(t) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + repo := newGitRepo(t, filepath.Join(github, "owner", "repo.git")) + const spec = "github:owner/repo" + if _, err := Add(ctx, spec); err != nil { + t.Fatal(err) + } + was := GitCommit(spec) + repo.release("2.0.0") // what the look finds + if _, err := CheckUpdates(ctx); err != nil { + t.Fatal(err) + } + if w := readUpdates().Waiting; len(w) != 1 || !SameCommit(w[0].Version, was) { + t.Fatalf("the look left %+v, want one waiting from %s", w, was) + } + seen := readUpdates().Waiting[0].Latest + repo.release("3.0.0") // pushed after the look + now := repoHead(t, repo) + if op == "upgrade, GitHub down after" { + down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "down", http.StatusServiceUnavailable) + })) + t.Cleanup(down.Close) + githubAPI = down.URL + } + var err error + if op == "update" { + err = Update(ctx) + } else { + err = Upgrade(ctx, "my-oc-plugin") + } + if err != nil { + t.Fatalf("%s: %v", op, err) + } + if c := GitCommit(spec); !SameCommit(c, now) || SameCommit(c, seen) { + t.Fatalf("installed %s, want %s, newer than the look's %s", c, now, seen) + } + if w := PendingUpdates().Waiting; len(w) != 0 { + t.Fatalf("after the %s, the page is told %+v waits", op, w) + } + if w := readUpdates().Waiting; len(w) != 0 { + t.Fatalf("after the %s, plugin-updates.json still has %+v", op, w) + } + }) + } +}