diff --git a/internal/gui/assets/plugininstalled.js b/internal/gui/assets/plugininstalled.js new file mode 100644 index 000000000..5b34217dd --- /dev/null +++ b/internal/gui/assets/plugininstalled.js @@ -0,0 +1,39 @@ +// Installed narrowed as Discover is (WJaunita45604 on X): the same strip of +// kinds and the same Origin menu, over what is installed. Each plugin is +// put where Discover puts it: its card's kind and origin (kindOf, srcOf), +// and for one the market doesn't list, the same read from what it is: its +// chips' kind, a git one on GitHub, a @magpie-community package the +// community's, else another author's. plugins.js imports this when its +// page is first drawn, so it weighs nothing on the core; until then the +// list is drawn whole. st holds the picks; the strip and the menu show +// only where there are two or more to pick from. +window.pmInstalled = function ({ es, st, everything, entryOf, kindOf, srcOf, name, isGit, ORDER, SOURCES, kindStrip, originButton, drawBody }) { + const card = new Map(); + for (const l of everything(() => true)) { const e = entryOf(l.package); if (e && !card.has(e)) card.set(e, l); } + const sorted = es.map((e) => { + const l = card.get(e); + if (l) return { e, kind: kindOf(l), src: srcOf(l) }; + const kind = e.middleware || e.isMiddleware || e.gateway || e.isGateway ? "mw" : e.agent || e.isAgent ? "ag" : e.tools?.length && !e.providers?.length ? "tl" : e.page && !e.providers?.length ? "pg" : "pv"; + return { e, kind, src: isGit(e.spec) ? "gh" : name(e.spec).startsWith("@magpie-community/") ? "ours" : "third" }; + }); + const kinds = ORDER.filter((k) => sorted.some((x) => x.kind === k)); + const srcs = SOURCES.map(([v]) => v).filter((v) => v && sorted.some((x) => x.src === v)); + if (!kinds.includes(st.kind) || kinds.length < 2) st.kind = ""; + if (!srcs.includes(st.src) || srcs.length < 2) st.src = ""; + const base = sorted.filter((x) => !st.src || x.src === st.src); + const shown = base.filter((x) => !st.kind || x.kind === st.kind).map((x) => x.e); + let none = null; + if (!shown.length) { + // a pick that leaves nothing says so, with the way back + none = el("div", "pm-ghnone"); + const every = el("button", "text", t("Show all")); + every.type = "button"; + every.onclick = () => { st.kind = st.src = ""; drawBody(); }; + none.append(el("span", "", t("No plugin matches")), every); + } + return { + shown, none, + strip: kinds.length > 1 ? kindStrip(kinds, (k) => base.filter((x) => !k || x.kind === k).length, st.kind, (k) => { st.kind = k; drawBody(); }) : null, + pop: srcs.length > 1 ? originButton(st.src, null, (v) => { st.src = v; drawBody(); }) : null, + }; +}; diff --git a/internal/gui/assets/plugins.css b/internal/gui/assets/plugins.css index 0b275f7fd..97605c5d1 100644 --- a/internal/gui/assets/plugins.css +++ b/internal/gui/assets/plugins.css @@ -262,6 +262,8 @@ body.window .pm-manual { --bleed-l: 16px; } /* Installed */ .pm-listhead { margin: 0 0 -10px; padding: 0 2px; } +/* with Discover's kinds and Origin (plugins.js drawInstalled): wraps when narrow */ +.pm-listhead.pm-bar { height: auto; min-height: 26px; } /* the plugins with an update, above the list: the sidebar's dot, named */ .pm-updates { display: flex; align-items: center; gap: 10px; margin: 0 0 12px; padding: 9px 10px 9px 12px; border-radius: 10px; background: var(--accent-soft); font-size: 12px; line-height: 1.35; } .pm-updates .grow { flex: 1; min-width: 0; overflow-wrap: anywhere; } diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 0cd82d777..65fcd510f 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -648,6 +648,7 @@ // a long list draws only the rows near the view (plugingrid.js); until // that has come, and for a short list, every card is drawn let vg; + const inst = { kind: "", src: "" }, iload = () => iload.p ||= import("./plugininstalled.js").then(drawBody, () => {}); const vload = () => vload.p = vload.p || import("./plugingrid.js").then(() => vg = pmVirtualGrids(page, card, () => body, drawBody), () => {}); function cardGrid(list) { const g = el("div", "pm-grid"); @@ -800,23 +801,31 @@ b.onclick = (ev) => { ev.stopPropagation(); open(b); }; return b; } - function browseBar(all, base) { - const bar = el("div", "pm-bar"); - const kinds = ORDER.filter((k) => all.some((l) => kindOf(l) === k)); - if (kindPick && !kinds.includes(kindPick)) kindPick = ""; - const n = (k) => base.filter((l) => !k || kindOf(l) === k).length; + // the strip of kinds, each with how many n(kind) says: Discover's, and + // Installed's over what is installed + function kindStrip(kinds, n, now, onPick) { const ids = ["", ...kinds]; - const pick = segs(ids.map((k) => [k, k ? t(SHORT[k]) : t("All")]), kindPick, (k) => { kindPick = k; drawBody(); }); + const pick = segs(ids.map((k) => [k, k ? t(SHORT[k]) : t("All")]), now, onPick); pick.classList.add("pm-kinds"); pick.setAttribute("role", "group"); pick.setAttribute("aria-label", t("Kind of plugin")); [...pick.querySelectorAll(".opt")].forEach((b, i) => b.append(el("em", "", String(n(ids[i]))))); - bar.append(pick, el("span", "grow")); + return pick; + } + // the Origin menu: SOURCES, and Discover's "Not installed only" (extra) + function originButton(now, extra, onPick) { + const srcName = (now ? t(SOURCES.find(([v]) => v === now)[1]) : t("All")) + (extra?.ticked ? " · " + t("Not installed") : ""); + return popButton(t("Origin"), srcName, (b) => openProtoMenu(b, + [...SOURCES.map(([v, name]) => ({ v, name, note: "" })), ...(extra ? [{ v: "\x01", name: "Not installed only", note: "", ticked: extra.ticked }] : [])], + now, onPick, "Origin", "pm-srcmenu", "right")); + } + function browseBar(all, base) { + const bar = el("div", "pm-bar"); + const kinds = ORDER.filter((k) => all.some((l) => kindOf(l) === k)); + if (kindPick && !kinds.includes(kindPick)) kindPick = ""; + bar.append(kindStrip(kinds, (k) => base.filter((l) => !k || kindOf(l) === k).length, kindPick, (k) => { kindPick = k; drawBody(); }), el("span", "grow")); if (ghLooking()) bar.append(ghLook()); - const srcName = (srcPick ? t(SOURCES.find(([v]) => v === srcPick)[1]) : t("All")) + (onlyNew ? " · " + t("Not installed") : ""); - bar.append(popButton(t("Origin"), srcName, (b) => openProtoMenu(b, - [...SOURCES.map(([v, name]) => ({ v, name, note: "" })), { v: "\x01", name: "Not installed only", note: "", ticked: onlyNew }], - srcPick, (v) => { if (v === "\x01") onlyNew = !onlyNew; else srcPick = v; drawBody(); }, "Origin", "pm-srcmenu", "right"))); + bar.append(originButton(srcPick, { ticked: onlyNew }, (v) => { if (v === "\x01") onlyNew = !onlyNew; else srcPick = v; drawBody(); })); bar.append(popButton(t("Sort"), t(SORTS.find(([v]) => v === sortPick)[1]), (b) => openProtoMenu(b, SORTS.map(([v, name]) => ({ v, name, note: "" })), sortPick, (v) => { sortPick = v; drawBody(); }, "Sort", "pm-sortmenu", "right"))); return bar; @@ -1005,6 +1014,7 @@ let body = null; function draw() { vload(); + iload(); const scroll = page.scrollTop; // the body is made once, so the GitHub section's field stays in the page body = body || el("div", "lib-body pm-body"); @@ -1205,17 +1215,22 @@ bar.append(up); body.append(bar); } + // narrowed by Discover's kinds and origins (plugininstalled.js), the + // list drawn whole until that has come + const f = window.pmInstalled ? pmInstalled({ es, st: inst, everything, entryOf, kindOf, srcOf, name, isGit, ORDER, SOURCES, kindStrip, originButton, drawBody }) : (iload(), { shown: es }); // by name, in the order the reader picked (#481), not the order they // were installed in const list = el("div", "list pm-list"); - const fill = () => list.replaceChildren(...[...es].sort(byName(sortOf("plugins"), shownName)).map(installedRow)); + const fill = () => list.replaceChildren(...[...f.shown].sort(byName(sortOf("plugins"), shownName)).map(installedRow)); if (es.length > 1) { const h = el("div", "row-head pm-listhead"); - h.append(el("span", "grow"), sortBy("plugins", NAME_SORTS, fill)); + h.append(...[f.strip, el("span", "grow"), f.pop, sortBy("plugins", NAME_SORTS, fill)].filter(Boolean)); + h.classList.toggle("pm-bar", !!(f.strip || f.pop)); body.append(h); } fill(); body.append(list); + if (f.none) body.append(f.none); const foot = el("div", "pm-foot"); foot.append(el("span", "", mine.bun ? t("Plugins run on Bun {v}", { v: mine.bunVersion }) : ""), el("span", "grow")); // npm has versions to ask for, and a git one's repository commits; a @@ -1232,6 +1247,7 @@ body.append(foot); } + // an installed plugin's name as its row shows it: the market's, else the // one its package.json gives itself (magpie.name, #4558), else the // package's or the folder's diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 45aa37cf8..fe200c66e 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -177,14 +177,14 @@ test("compat.js is the first of the page's own scripts", async () => { // codexprojects.js when the open Codex app shows fewer projects; // pipecheck.js when Settings draws Models; // addfloat.js when the Providers page's add sheet first opens; - // plugingrid.js when Plugins first draws; + // plugingrid.js and plugininstalled.js when Plugins first draws; // rotfig.js when a routing's In turn is first shown; // ompadvisor.js when an omp's settings first show; // claudemagpie.js when Claude Desktop's twin button or Advanced fold first shows; // keyrates.js when a provider with two or more keys opens; // the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "rotfig.js", "ompadvisor.js", "claudemagpie.js", "keyrates.js", "updatetrust.js", "currencyprefs.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "plugininstalled.js", "rotfig.js", "ompadvisor.js", "claudemagpie.js", "keyrates.js", "updatetrust.js", "currencyprefs.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/plugin-installed-filter.test.cjs b/internal/gui/tests/plugin-installed-filter.test.cjs new file mode 100644 index 000000000..9bf6b358c --- /dev/null +++ b/internal/gui/tests/plugin-installed-filter.test.cjs @@ -0,0 +1,166 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Installed is narrowed as Discover is (WJaunita45604 on X: 要求在已安装的 +// 插件里面,也要按照发现界面里面的分类…并且可以筛选是否为官方插件,具体实现 +// 分类方法与发现界面里的分类方法一致): the same strip of kinds, each with how +// many are installed, and the same Origin menu (magpie community, other +// authors, unofficial on GitHub), with nothing about installing. A plugin +// Discover lists is put where its card is; one it doesn't (a folder, an +// npm package nobody listed) by what it is. A pick that leaves nothing +// says so with Show all, and Discover's own picks are left alone. Seven +// plugins: a community subscription and middleware, another author's +// agent, two repositories tagged on GitHub (a provider and a middleware, +// from the dev instance's real /api/plugins/github answer), a middleware +// in a folder and an unlisted npm subscription. The API is faked and no +// request leaves the page. Every language, both engines, 1100px and 420px. +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 GH = require("./fixtures/plugins-github-31.json"); +const LISTINGS = [ + { package: "@magpie-community/opencode-zed-auth", name: "Zed", community: true }, + { package: "@magpie-community/opencode-think-tags", name: "Think tags", community: true, kind: "middleware" }, + { package: "opencode-some-agent", name: "Some Agent", kind: "agent" }, +]; +const ghEntry = (repo) => { const r = GH.repos.find((x) => x.repo === repo); return { spec: r.spec, package: r.package, providers: [], version: "1.0.0", moved: [] }; }; +const INSTALLED = [ + { spec: "@magpie-community/opencode-zed-auth", providers: [], version: "0.2.0", moved: [] }, + { spec: "@magpie-community/opencode-think-tags", providers: [], version: "0.1.2", moved: [], isMiddleware: true, middlewareOnly: true }, + { spec: "opencode-some-agent", providers: [], version: "1.0.0", moved: [], isAgent: true }, + ghEntry("mu-zi-lee/magpie-our-free-model"), + ghEntry("ezdemo/magpie-haiku55-thinking"), + { spec: "/Users/me/plugins/my-hook", ownName: "My hook", providers: [], moved: [], isMiddleware: true, middlewareOnly: true }, + { spec: "opencode-unlisted-auth", providers: [], version: "3.0.0", moved: [] }, +]; +// what Discover calls each: [kind, origin] +const WANT = { + "Zed": ["pv", "ours"], "Think tags": ["mw", "ours"], "Some Agent": ["ag", "third"], + "magpie-our-free-model": ["pv", "gh"], "magpie-opendesign-compatible-fix": ["mw", "gh"], + "My hook": ["mw", "third"], "opencode-unlisted-auth": ["pv", "third"], +}; + +function server(lang, fetched) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + 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/gateway/trace") return json({ routes: [] }); + if (url.pathname === "/api/plugins") return json({ bun: true, bunVersion: "1.4.2", plugins: INSTALLED, picker: false, movable: [] }); + if (url.pathname === "/api/plugins/listings") return json({ listings: LISTINGS }); + if (url.pathname === "/api/plugins/npm") return json({ npm: {} }); + if (url.pathname === "/api/plugins/github") return json(GH); + if (url.pathname.startsWith("/api/")) return json({}); + if (url.host !== "magpie.test" || !/^\/[\w./-]*$/.test(url.pathname)) { fetched.push(url.href); 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: "" }); } + }; +} + +const names = (k, src) => Object.keys(WANT).filter((n) => (!k || WANT[n][0] === k) && (!src || WANT[n][1] === src)).sort(); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": Installed is narrowed by Discover's kinds and origins", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) for (const width of [1100, 420]) { + await t.test(`${lang} ${width}px`, async () => { + const ctx = await browser.newContext({ viewport: { width, height: 860 } }); + const page = await ctx.newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const errors = [], fetched = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, fetched)); + try { + await page.goto("http://magpie.test/?view=plugins"); + const view = page.locator("#view-plugins"); + await view.locator(".pm-bar").first().waitFor(); + await view.locator(".pm-ghlook").waitFor({ state: "detached" }); + const tr = (s) => page.evaluate((s) => t(s), s); + // the tabs are in the sidebar's list on some widths + const tab = async (s) => page.locator(":is(.lib-tabs .opt, .nav-s):visible", { hasText: await tr(s) }).first().click(); + await tab("Installed"); + const head = view.locator(".pm-listhead"); + await head.locator(".pm-kinds").waitFor(); + const rows = view.locator(".pm-list .pm-row"); + const shown = async () => (await rows.locator(".who .name > span:first-child").allInnerTexts()).map((s) => s.trim()).sort(); + const kinds = head.locator(".pm-kinds .opt"); + const said = () => kinds.evaluateAll((bs) => bs.map((b) => [b.firstChild.textContent, b.querySelector("em").textContent])); + const want = async (src) => Promise.all([["", "All"], ["pv", "Subscriptions"], ["mw", "Middleware"], ["ag", "Agents"]].map(async ([k, n]) => [await tr(n), String(names(k, src).length)])); + const pop = head.locator(".pm-pop"); + const choose = async (name) => { + await pop.click(); + await page.locator(".proto-menu .pm-item", { hasText: await tr(name) }).first().click(); + await page.locator(".proto-menu").waitFor({ state: "hidden" }).catch(() => {}); + }; + + // every one, and the strip counts each kind as Discover would + assert.deepEqual(await shown(), names()); + assert.deepEqual(await said(), await want()); + assert.equal(await view.locator("select").count(), 0, "no native select"); + const overflow = () => page.evaluate(() => { + const h = document.querySelector("#view-plugins .pm-listhead"), v = document.querySelector("#view-plugins"); + return [h.scrollWidth - h.clientWidth, v.scrollWidth - v.clientWidth, document.documentElement.scrollWidth - innerWidth].map((x) => Math.max(0, x)); + }); + assert.deepEqual(await overflow(), [0, 0, 0]); + + // a kind + await kinds.nth(2).click(); + assert.deepEqual(await shown(), names("mw")); + // and an origin: the strip counts what it leaves + await pop.click(); + assert(!(await page.locator(".proto-menu .pm-item", { hasText: await tr("Not installed only") }).count()), "no Not installed only"); + await page.keyboard.press("Escape"); + await page.locator(".proto-menu").waitFor({ state: "hidden" }).catch(() => {}); + await choose("magpie community"); + assert.deepEqual(await shown(), names("mw", "ours")); + assert.deepEqual(await said(), await want("ours")); + assert.equal((await pop.locator("b").textContent()).trim(), await tr("magpie community")); + await choose("Unofficial, on GitHub"); + assert.deepEqual(await shown(), names("mw", "gh")); + await kinds.nth(0).click(); + assert.deepEqual(await shown(), names("", "gh")); + await choose("Other authors"); + assert.deepEqual(await shown(), names("", "third")); + assert.deepEqual(await said(), await want("third")); + + // a pick that leaves nothing: said, and Show all puts back all + await choose("Unofficial, on GitHub"); + await kinds.nth(3).click(); + assert.equal(await rows.count(), 0); + const none = view.locator(".pm-ghnone"); + assert.equal((await none.locator("span").textContent()).trim(), await tr("No plugin matches")); + await none.locator("button").click(); + assert.deepEqual(await shown(), names()); + assert.equal(await head.locator(".pm-kinds .opt.on").evaluate((b) => b.firstChild.textContent), await tr("All")); + assert.equal((await pop.locator("b").textContent()).trim(), await tr("All")); + + // Discover's own picks are its own + await kinds.nth(1).click(); + await tab("Discover"); + const dbar = view.locator(".pm-body > .pm-bar"); + await dbar.waitFor(); + assert.equal(await dbar.locator(".pm-kinds .opt.on").evaluate((b) => b.firstChild.textContent), await tr("All")); + // and back, the pick kept + await tab("Installed"); + await head.locator(".pm-kinds").waitFor(); + assert.deepEqual(await shown(), names("pv")); + assert.deepEqual(await overflow(), [0, 0, 0]); + assert.deepEqual(errors, []); + assert.deepEqual(fetched, []); + } finally { + await ctx.close(); + } + }); + } + }); +}