diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 045f5d2e4..e728c18e8 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -80,9 +80,7 @@ // npm has the versions of a package: not a folder's, nor a git one's const onNPM = (spec) => !isPath(spec) && !isGit(spec); // a git one is out of date when its repository is at another commit than - // the one installed, whatever version its package.json says (ARNO on - // Discord: github:yuweihao17/codearts showed Update all the time, and - // still did right after updating); an abbreviated sha names the full one + // the one installed, whatever its version (ARNO); a short sha names the full one const sameCommit = (a, b) => !!a && !!b && (a.length > b.length ? a.startsWith(b) : b.startsWith(a)); const gitBehind = (e) => isGit(e.spec) && !!e.commit && !!e.head && !sameCommit(e.commit, e.head); // the providers a plugin signs in to, as the add sheet knows them @@ -205,6 +203,7 @@ } // what npm says of the plugins suggested and those installed: drawn // when it comes, never waited on + let npmTries = 0; async function askNPM(only) { const names = [...new Set([...(listings || []).map((l) => l.package), ...(mine?.plugins || []).filter((e) => onNPM(e.spec)).map((e) => name(e.spec))])] .filter((n) => !only || !npm[n]); @@ -214,8 +213,10 @@ Object.assign(npm, r.npm || {}); } catch {} merge(); - // one npm said nothing of, now or ever: as one it doesn't have - for (const l of listings || []) if (!l.npm) l.npm = { weekly: 0 }; + // one npm said nothing of: unknown (Install), asked again + let u = 0; + for (const l of listings || []) if (!l.npm || l.npm.u) u = l.npm = { weekly: 0, u: 1 }; + if (u && npmTries++ < 4) setTimeout(() => askNPM(true), 15000); drawBody(); } @@ -491,7 +492,7 @@ return b; } if (!e) { - if (listed && !listed.github && !listed.npm?.version) { + if (listed && !listed.github && !listed.npm?.version && !listed.npm.u) { b.textContent = t("Coming soon"); b.disabled = true; b.title = t("Not on npm yet"); diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index 59346adba..5030477ea 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -548,8 +548,13 @@ func pluginMarketState(ctx context.Context, w Windows) pluginMarketJSON { info := plugin.Info(ctx, names) m := pluginMarketJSON{Listings: []pluginListingJSON{}, State: st} for _, l := range ls { - n := info[l.Package] - m.Listings = append(m.Listings, pluginListingJSON{Listing: l, NPM: &n}) + j := pluginListingJSON{Listing: l} + // npm not answered for (or the dist branch unread) is unknown: + // no npm, not an empty one that reads as Coming soon + if n, ok := info[l.Package]; ok { + j.NPM = &n + } + m.Listings = append(m.Listings, j) } listingIcons(m.Listings, 3*time.Second) for i, e := range m.State.Plugins { diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index e319de136..06beb1f48 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -372,6 +372,12 @@ why one didn't load, updates one and removes one. The add sheet's "look for a plugin" link lead there. English and Chinese, Chromium and WebKit, with the API faked. +`plugin-npm-unknown.test.cjs` checks that a suggested plugin npm said +nothing of (npm or the dist branch not read in time) offers Install, not +Coming soon, and that the page asks again and then shows its version, +while one npm said it doesn't have still reads Coming soon. Every +language, Chromium and WebKit, wide and narrow, with the API faked. + `plugins-more-discover.test.cjs` checks that the add sheet's "More in Plugins" row and its "look for a plugin" link open Plugins on Discover, after Built-in or Installed was the tab open last (outloudvi on Discord). diff --git a/internal/gui/tests/plugin-npm-unknown.test.cjs b/internal/gui/tests/plugin-npm-unknown.test.cjs new file mode 100644 index 000000000..11c582151 --- /dev/null +++ b/internal/gui/tests/plugin-npm-unknown.test.cjs @@ -0,0 +1,101 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A suggested plugin npm said nothing of (npm, or the community repo's +// dist branch, not read in time) is unknown: its card offers Install, not +// a disabled Coming soon nothing confirmed (zhudabao8433 on Discord: +// PowerContext, only on the dist branch, installable the day before, read +// Coming soon). The page asks again, and the answer that comes shows its +// version. One npm said it doesn't have still reads Coming soon. Every +// language, both engines, wide and narrow; the API is faked here. +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 PC = "@magpie-community/gateway-powercontext", QODER = "@magpie-community/opencode-qoder-auth"; +const listings = [ + { package: PC, name: "PowerContext", kind: "middleware", community: true, summary: { en: "Recall from your PowerContext service." } }, + { package: QODER, name: "Qoder", icon: "qoder", providers: ["qoder"], community: true, summary: { en: "Your Qoder subscription." }, npm: { weekly: 0 } }, +]; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const state = { bun: true, bunVersion: "1.4.2", plugins: [] }; + +const L = { + en: { install: "Install", soon: "Coming soon" }, + zh: { install: "安装", soon: "即将上线" }, + "zh-TW": { install: "安裝", soon: "即將上線" }, + ja: { install: "インストール", soon: "近日公開" }, + de: { install: "Installieren", soon: "Demnächst" }, +}; + +function server(lang, asks) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/plugins") return json(state); + if (url.pathname === "/api/plugins/listings") return json({ listings }); + if (url.pathname === "/api/plugins/market") return json({ listings, state }); + if (url.pathname === "/api/plugins/npm") { + const names = (url.searchParams.get("names") || "").split(","); + asks.push(names); + // the first ask: the dist branch not read in time, nothing said of + // PowerContext; the next: the branch read, its 0.2.0 + return json({ npm: asks.length > 1 && names.includes(PC) ? { [PC]: { version: "0.2.0", weekly: 0 } } : {} }); + } + if (url.pathname.startsWith("/api/")) return json({}); + if (!/^\/[\w./-]*$/.test(url.pathname)) return route.fulfill({ status: 404, body: "" }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a plugin npm said nothing of offers Install, not Coming soon", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of Object.keys(L)) for (const width of [980, 420]) { + await t.test(lang + " " + width, async () => { + const w = L[lang]; + const ctx = await browser.newContext({ viewport: { width, height: 820 } }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], asks = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.clock.install(); + await page.route("**/*", server(lang, asks)); + await page.goto("http://magpie.test/?view=plugins"); + const act = (pkg) => page.locator(`#view-plugins .pm-card[data-pkg="${pkg}"] .pm-act`); + await act(PC).waitFor(); + // npm's first answer, with nothing of PowerContext, has come + for (let i = 0; i < 100 && !asks.length; i++) await sleep(50); + assert.equal(asks.length, 1, "npm asked once"); + await page.waitForFunction(([sel, word]) => document.querySelector(sel)?.textContent === word, + [`#view-plugins .pm-card[data-pkg="${PC}"] .pm-act`, w.install]); + assert.equal(await act(PC).isDisabled(), false, "Install can be clicked"); + assert.equal(await act(QODER).innerText(), w.soon, "one npm said it doesn't have is still Coming soon"); + assert.equal(await act(QODER).isDisabled(), true); + const box = await act(PC).boundingBox(); + assert.ok(box && box.x >= 0 && box.x + box.width <= width, `Install fits: ${JSON.stringify(box)}`); + + // asked again, the branch now read: its version shows + await page.clock.fastForward(16000); + for (let i = 0; i < 100 && asks.length < 2; i++) await sleep(50); + assert.ok(asks.length >= 2 && asks[1].includes(PC), "npm asked again of PowerContext: " + JSON.stringify(asks)); + await page.locator(`#view-plugins .pm-card[data-pkg="${PC}"] .pm-ver`).waitFor(); + assert.match(await page.locator(`#view-plugins .pm-card[data-pkg="${PC}"] .pm-ver`).innerText(), /0\.2\.0/); + assert.equal(await act(PC).innerText(), w.install); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/plugin/dist_unread_test.go b/internal/plugin/dist_unread_test.go index dbc2cdc82..8fd640123 100644 --- a/internal/plugin/dist_unread_test.go +++ b/internal/plugin/dist_unread_test.go @@ -120,3 +120,44 @@ func TestDistReadFailedIsntMissing(t *testing.T) { t.Fatalf("npmAsk of a package neither has: %v; want errNotFound", err) } } + +// A "not on npm" an older build kept (one that took a cut-off dist read +// for the branch having nothing) is unknown once it is an hour old and +// the branch still can't be read: neither the listings (InfoCached) nor +// Info give it, so the page offers Install rather than Coming soon +// (zhudabao8433 on Discord: PowerContext, installable the day before). +// One said within the hour still stands. +func TestStaleMissingIsUnknownWhileDistUnread(t *testing.T) { + sandbox(t) + const pkg = "@magpie-community/gateway-powercontext" + const fresh = "@magpie-community/opencode-nothing-auth" + npmHasNothing(t) + var fail atomic.Bool + fail.Store(true) + open := gatedDist(t, pkg, []string{"0.2.0"}, &fail) + open() + wait := distWait + distWait = 0 + t.Cleanup(func() { distWait = wait }) + npmEach, npmAll = 5*time.Second, 10*time.Second + + npmMu.Lock() + npmCached()[pkg] = npmEntry{NPM{}, time.Now().Add(-2 * time.Hour)} + npmCached()[fresh] = npmEntry{NPM{}, time.Now().Add(-time.Minute)} + npmMu.Unlock() + + if info, ok := InfoCached([]string{pkg})[pkg]; ok { + t.Fatalf("listings give an hours-old \"not on npm\" as %+v; want it unknown", info) + } + if info, ok := Info(context.Background(), []string{pkg})[pkg]; ok { + t.Fatalf("with the dist branch failing the market says %+v from an hours-old answer; want it unknown", info) + } + if _, ok := InfoCached([]string{fresh})[fresh]; !ok { + t.Fatal("a \"not on npm\" said a minute ago was dropped; it stands for the hour") + } + fail.Store(false) + distSettled(t) + if info := Info(context.Background(), []string{pkg})[pkg]; info.Version != "0.2.0" { + t.Fatalf("once the dist branch answered the market says %+v; want its 0.2.0", info) + } +} diff --git a/internal/plugin/market.go b/internal/plugin/market.go index 0116de6cd..9c3450319 100644 --- a/internal/plugin/market.go +++ b/internal/plugin/market.go @@ -156,13 +156,24 @@ func InfoCached(names []string) map[string]NPM { c := npmCached() out := map[string]NPM{} for _, n := range names { - if e, ok := c[n]; ok { + if e, ok := c[n]; ok && !e.missingStale(time.Hour) { out[n] = e.Info } } return out } +// missingStale is whether e is "not on npm" said over age ago: unknown +// now, not missing. A package only the community repo's dist branch has +// was kept as missing by builds before v0.1.2413 whenever the branch's +// read was cut off (zhudabao8433 on Discord: PowerContext, installable the +// day before, read Coming soon), and an ask that still can't read the +// branch leaves that answer standing; a page told "unknown" offers +// Install instead of a Coming soon nothing has confirmed. +func (e npmEntry) missingStale(age time.Duration) bool { + return e.Info.Version == "" && time.Since(e.At) >= age +} + func marketCache() string { return filepath.Join(appdir.Cache(), "plugin-market.json") } func parseMarket(b []byte) ([]Listing, error) { @@ -344,7 +355,10 @@ func infoWithin(ctx context.Context, names []string, age time.Duration) map[stri asked[n] = true e, hit := cache[n] if hit { - out[n] = e.Info // what it said last, until it says otherwise + // what it said last, until it says otherwise + if !e.missingStale(time.Hour) { + out[n] = e.Info + } if time.Since(e.At) < age { continue }