diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index d070a1108..e19ae02bf 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -230,6 +230,8 @@ body.panel .seg { display: none; } .top.tight .update { width: 22px; padding: 0; justify-content: center; margin-right: 4px; } body.window .top.cramped .seg { position: relative; left: auto; top: auto; transform: none; margin: 0 auto; } /* relative still: its thumb sits in it, not over the whole header */ .top.cramped .seg button { padding: 0 8px; } +.top.crowded .seg button { padding: 0 6px; font-size: 12px; } +.top.crowded .brand { display: none; } @keyframes update-in { from { opacity: 0; transform: translateY(-3px) scale(.94); } } @keyframes spin { to { transform: rotate(360deg); } } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 6c1e00204..4ce35e792 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -98,6 +98,7 @@ const CHECK = "m3.5 8.5 3 3 6-7"; const PLUS = "M8 3.5v9M3.5 8h9"; const OUT = "M6.5 3.5h-3v9h9v-3M9 3.5h3.5V7M12.5 3.5 7.5 8.5"; const COPY_ICON = "M5.5 5.5V3.5h7v7h-2M3.5 5.5h7v7h-7z"; +const PUZZLE = "M6.2 2.8h2.3a1.3 1.3 0 1 1 2.5 0h2.2V5a1.3 1.3 0 1 0 0 2.6v5.6H3V7.6a1.3 1.3 0 1 1 0-2.6V2.8z"; // A brand icon: colour logos are images, mono logos take the text colour. // Nothing is ever invented: a model with no known vendor keeps the slot @@ -1309,7 +1310,10 @@ async function load() { state = next; load.done = true; // the library may have drawn itself before the saved language was known - if (applyPrefs(state.settings, state.fx) && view === "library") window.loadLibrary?.(); + if (applyPrefs(state.settings, state.fx)) { + if (view === "library") window.loadLibrary?.(); + if (view === "plugins") window.loadPlugins?.(); + } tintPanel(); tintTitleBar(); renderAgents(); @@ -2844,6 +2848,7 @@ function renderAdd() { any = true; const grid = section("Subscriptions", "sign in, no key"); for (const x of subs) grid.append(subTile(x)); + if (!f) grid.append(morePluginsTile()); const w = subs.find((x) => signing?.agent === x.agent); if (w) tiles.append(renderSigning(w)); } @@ -2880,7 +2885,9 @@ function renderAdd() { none.append(t("Nothing called “{q}”. ", { q: presetQuery.trim() })); const b = el("button", "link", t("Add it as a custom provider")); b.onclick = () => { editing = { custom: true }; draft = null; renderProviders(); }; - none.append(b); + const pl = el("button", "link", t("look for a plugin")); + pl.onclick = () => openPlugins(presetQuery.trim()); + none.append(b, t(", or "), pl); tiles.append(none); } else if (!f) { // a vendor not listed: one line under them all @@ -2908,6 +2915,47 @@ function pickRow(ic, name, cls = "") { return b; } +// morePluginsTile: the add sheet's way to the Plugins tab, where more +// subscriptions are, each signed in to by a plugin +function morePluginsTile() { + const b = el("button", "tile more-plugins"); + b.dataset.pick = "plugins"; + const nm = el("span", "nm"); + nm.append(el("span", "n", t("More in Plugins"))); + const ic = el("span", "puzzle"); + ic.append(svg(PUZZLE, 15, 1.4)); + b.append(ic, nm, svg(CHEV_R, 11, 1.6)); + b.title = t("Subscriptions magpie doesn't sign in to itself: install a plugin for one in the Plugins tab"); + b.onclick = () => openPlugins(); + return b; +} + +// openPlugins: the Plugins tab, looking for q when there is one +function openPlugins(q) { + if (mode !== "window") { api("window/main?view=plugins", {}).catch(() => {}); return; } + show("plugins"); + window.pluginQuery?.(q || ""); +} + +// pluginSignIn: a plugin's provider signed in to as every subscription is, +// in the Providers add sheet +function pluginSignIn(id) { + closeModal(); + show("providers"); + adding = true; editing = null; draft = null; presetQuery = ""; + renderProviders(); + startSignIn(id); +} + +// openProvider: a provider opened in the Providers tab +function openProvider(id) { + closeModal(); + show("providers"); + adding = false; editing = id; draft = null; presetQuery = ""; + renderProviders(); + syncURL(); +} + // a row already added: a green dot after its name, and how many accounts // when a subscription has more than one function markAdded(b, n = 1) { @@ -5860,6 +5908,15 @@ function hostOf(u) { try { return new URL(u.includes("://") ? u : "https://" + u // view goes down with it. The button stays at the view's foot however long // the list is; with the sheet already open it takes the view down to it, // and it steps aside while the sheet's head is in sight. +// moreSubs: beside Add provider, the reminder that more subscriptions are +// a plugin away — three of them in a stack, and where to find them +{ + const b = $("#moreSubs"); + for (const ic of ["cursor", "githubcopilot", "gemini-color"]) b.firstElementChild.append(icon(ic)); + b.append(svg(CHEV_R, 10, 1.7)); + b.onclick = () => { openPlugins(); b.blur(); }; +} + $("#addProvider").onclick = (e) => { const view = $("#view-providers"), sheet = $("#addSheet"); if (!adding) { @@ -8338,7 +8395,6 @@ function renderSettings() { renderImages(s, keep); renderRedact(s, keep); renderLAN(s); - renderPlugins(); renderSync(); const about = $("#about"); @@ -8401,93 +8457,6 @@ function renderSessionTerminal(s, keep) { select.onchange = () => savePrefs({ ...keep, sessionTerminal: select.value === "system" ? "" : select.value }); } -// renderPlugins: OpenCode's provider plugins, each signing in to a -// subscription magpie doesn't (or no longer does) itself. They are other -// people's code: magpie runs them on Bun and passes their requests on. -let pluginsView = null; -let pluginsBusy = ""; -async function renderPlugins(v) { - const box = $("#pluginsList"); - if (!box) return; - if (v) pluginsView = v; - else if (!pluginsView) { - pluginsView = { plugins: [], loading: true }; - api("plugins").then((x) => renderPlugins(x), (e) => renderPlugins({ plugins: [], error: e.message })); - } - v = pluginsView; - box.replaceChildren(); - const run = async (op, body, busy) => { - pluginsBusy = busy; - renderPlugins(); - try { - const r = await api("plugins/" + op, body); - pluginsBusy = ""; - renderPlugins(r); - providers = await api("providers"); - renderProviders(); - } catch (e) { - pluginsBusy = ""; - renderPlugins(); - status(e.message, "err"); - } - }; - for (const p of v.plugins) { - const r = el("div", "row pref plugin-row" + (p.off ? " off" : "")); - const who = el("div", "who"); - who.append(el("div", "name", p.spec)); - const sub = el("div", "sub", p.off ? t("Off") - : p.error ? t("Didn't load: {error}", { error: p.error }) - : p.providers.length ? t("Signs in to {names}", { names: p.providers.join(t(", ")) }) - : v.loading ? t("Loading…") : t("Signs in to nothing magpie can use")); - if (p.error && !p.off) sub.classList.add("bad"); - who.append(sub); - const val = el("div", "val"); - const onoff = el("button", "text", t(p.off ? "Switch on" : "Switch off")); - onoff.onclick = () => run("off", { spec: p.spec, off: !p.off }, p.spec); - const rm = el("button", "text quiet", t("Remove")); - rm.title = t("Removes the plugin and what it installed; its sign-ins are kept until you sign out"); - rm.onclick = () => run("remove", { spec: p.spec }, p.spec); - onoff.disabled = rm.disabled = !!pluginsBusy; - val.append(onoff, rm); - r.append(who, val); - box.append(r); - } - // a new one: an npm package or a file on this computer - const r = el("div", "row pref plugin-add"); - const who = el("div", "who"); - who.append(el("div", "name", t("Add a plugin"))); - who.append(el("div", "sub", pluginsBusy === "+" ? (v.bun ? t("Installing…") : t("Downloading Bun {v}, which plugins run on, then installing…", { v: v.bunVersion || "" })) - : v.error ? t("Couldn't ask the plugins: {error}", { error: v.error }) - : t("An OpenCode provider plugin — its npm package or a path. Plugins are other people's code: they sign in and make the requests."))); - const val = el("div", "val"); - const form = el("form", "proxy-segs"); - const spec = input("", "opencode-gemini-auth"); - spec.className = "proxy"; - spec.setAttribute("aria-label", t("Plugin")); - spec.autocomplete = "off"; - spec.spellcheck = false; - spec.onkeydown = (e) => e.stopPropagation(); - const add = el("button", "text primary", t("Add")); - add.type = "submit"; - add.disabled = spec.disabled = !!pluginsBusy; - form.onsubmit = add.onclick = (e) => { - e.preventDefault(); - if (!spec.value.trim() || pluginsBusy) return; - run("add", { spec: spec.value.trim() }, "+"); - }; - form.append(spec, add); - val.append(form); - if (v.plugins.length) { - const up = el("button", "text", t(pluginsBusy === "update" ? "Updating…" : "Update all")); - up.title = t("Installs the newest version of each plugin"); - up.disabled = !!pluginsBusy; - up.onclick = () => run("update", {}, "update"); - val.append(up); - } - r.append(who, val); - box.append(r); -} - // renderSync: the Settings page's sync and backup — WebDAV keeping the // setup the same on every computer, and a sealed file to carry by hand. // One of the three opens a form below its row at a time. @@ -9408,7 +9377,7 @@ function show(v) { view = v; if (mode === "window") { for (const b of $("#nav").querySelectorAll("button")) b.classList.toggle("on", b.dataset.view === v); slide($("#nav"), "nav"); } $("#prefs").classList.toggle("on", v === "settings"); - for (const id of ["agents", "providers", "gateway", "routing", "usage", "library", "settings"]) $("#view-" + id).hidden = v !== id; + for (const id of ["agents", "providers", "gateway", "routing", "usage", "library", "plugins", "settings"]) $("#view-" + id).hidden = v !== id; // back to where the reader was in it, and again once it has what it loads const back = () => backToReader($("#view-" + v)); requestAnimationFrame(back); @@ -9419,6 +9388,7 @@ function show(v) { if (v === "usage") loadUsage().then(back, (e) => status(e.message, "err")); if (v === "settings") loadSettings().then(back, (e) => status(e.message, "err")); if (v === "library") window.loadLibrary?.()?.then(back); + if (v === "plugins") window.loadPlugins?.()?.then(back); syncURL(); } @@ -9482,7 +9452,7 @@ setTimeout(wag, 250); // A narrow window has no room for the whole header: the name goes, leaving // the magpie, and Update becomes its arrow; narrower still, the tabs stop -// centring and take the room between. +// centring and take the room between, and at the narrowest they draw in. function fitTop() { const top = $(".top"), nav = $("#nav"), brand = $(".brand"), actions = $(".actions"); const fits = () => { @@ -9493,10 +9463,12 @@ function fitTop() { const n = nav.getBoundingClientRect(); return left + 8 <= n.left && n.right + 8 <= a.left; }; - top.classList.remove("tight", "cramped"); + top.classList.remove("tight", "cramped", "crowded"); if (fits()) return; top.classList.add("tight"); - if (!fits()) top.classList.add("cramped"); + if (fits()) return; + top.classList.add("cramped"); + if (!fits()) top.classList.add("crowded"); } const topFit = new ResizeObserver(fitTop); for (const e of [".top", ".brand", ".actions"]) topFit.observe($(e)); @@ -9655,6 +9627,6 @@ if (mode === "window" && params.get("import")) { }).catch(() => {}); } if (mode === "window" && params.get("view") === "providers" && params.get("edit")) editing = params.get("edit"); -if (mode === "window" && ["providers", "gateway", "routing", "usage", "library", "settings"].includes(params.get("view"))) show(params.get("view")); +if (mode === "window" && ["providers", "gateway", "routing", "usage", "library", "plugins", "settings"].includes(params.get("view"))) show(params.get("view")); else if (mode === "window") slide($("#nav"), "nav"); load(); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index f1853a024..1accc20df 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1725,6 +1725,68 @@ const I18N = { "Folder": "文件夹", "The folder it may read and write": "它可以读写的文件夹", "Optional — raises the rate limit. From context7.com/dashboard": "可选 — 提高速率限制。在 context7.com/dashboard 获取", + // Plugins + "{name} is installed — sign in to use it": "{name} 已安装,登录后即可使用", + "{name} is installed": "{name} 已安装", + "Getting Bun…": "正在下载 Bun…", + "Plugins run on Bun {v}, downloaded once": "插件运行在 Bun {v} 上,只需下载一次", + "Coming soon": "即将上线", + "Not on npm yet": "还没有发布到 npm", + "Install": "安装", + "Sign in to {name}": "登录 {name}", + "Open {name} in Providers": "在供应商中打开 {name}", + "Installed": "已安装", + "magpie community": "magpie 社区", + "Written for magpie by its community, in github.com/magpie-community/plugins": "由 magpie 社区编写,源码在 github.com/magpie-community/plugins", + "{n}/week": "{n}/周", + "{n} downloads on npm last week": "上周在 npm 下载 {n} 次", + "Didn't load": "加载失败", + "Also built in": "也有内置", + "magpie also signs in to this itself, for now; the plugin keeps it working if the built-in one is retired": "magpie 目前也内置了这个订阅;如果内置的下线,插件能让它继续可用", + "magpie also signs in to this itself, for now; the plugin keeps it working if the built-in one is retired.": "magpie 目前也内置了这个订阅;如果内置的下线,插件能让它继续可用。", + "Search plugins and npm…": "搜索插件和 npm…", + "Search plugins": "搜索插件", + "Couldn't load the plugins: {error}": "无法加载插件:{error}", + "written for magpie, checked against its own sign-ins": "为 magpie 编写,与内置登录对照验证过", + "From OpenCode's community": "来自 OpenCode 社区", + "popular OpenCode plugins that work in magpie": "在 magpie 中可用的热门 OpenCode 插件", + "Suggested": "推荐", + "On npm": "npm 上的插件", + "OpenCode plugins anyone published — read what one does before you install it": "任何人都可发布的 OpenCode 插件,安装前请先了解它做什么", + "Type two letters or more to search npm": "输入两个及以上字符以搜索 npm", + "Nothing else on npm": "npm 上没有更多了", + "No plugin called “{q}”": "没有叫「{q}」的插件", + "Subscriptions, as plugins": "以插件接入的订阅", + "Plugins sign in to coding plans and make their requests; the models then work in every agent, like any provider's. They're OpenCode's provider plugins, run on Bun.": "插件负责登录编程套餐并发出请求,模型随后就能像其他供应商的一样用在每个 agent 里。它们是 OpenCode 的供应商插件,运行在 Bun 上。", + "A plugin is someone else's code with your sign-in: install the ones you trust.": "插件是他人的代码,会拿到你的登录:只安装你信任的。", + "Have one in mind?": "已有想装的?", + "npm package or a folder on this computer": "npm 包名,或本机上的文件夹", + "No plugins yet": "还没有插件", + "Find a subscription in Discover and install it; it signs in from here.": "在「发现」中找到订阅并安装,然后在这里登录。", + "Discover plugins": "发现插件", + "Plugins run on Bun {v}": "插件运行在 Bun {v} 上", + "Update all ({n})": "全部更新({n})", + "Plugins updated": "插件已更新", + "v{v} out": "v{v} 可用", + "{name}: signed in": "{name}:已登录", + "{name}: not signed in": "{name}:未登录", + "{name} updated to v{v}": "{name} 已更新到 v{v}", + "Removing…": "移除中…", + "Downloads": "下载量", + "License": "许可证", + "Updated": "更新于", + "Signs in to": "登录", + "Source": "源码", + "Plugins are other people's code: they sign in and make the requests.": "插件是他人的代码:由它登录并发出请求。", + "No README": "没有 README", + "npm didn't answer: {error}": "npm 没有响应:{error}", + "More in Plugins": "插件中还有更多", + "Subscriptions magpie doesn't sign in to itself: install a plugin for one in the Plugins tab": "magpie 未内置的订阅:在「插件」页安装对应插件即可", + "look for a plugin": "找找插件", + ", or ": ",或", + "More subscriptions": "更多订阅", + "in Plugins": "在插件中", + "Cursor, Copilot, Gemini and others, each signed in to by a plugin you install from the Plugins tab": "Cursor、Copilot、Gemini 等订阅,在「插件」页安装对应插件后即可登录", }, }; diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 94a77e8fe..6d304215a 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -10,6 +10,7 @@ + @@ -25,6 +26,7 @@ +
+
@@ -157,6 +160,8 @@
+
+
Preferences
@@ -252,8 +257,6 @@
Privacy
-
Plugins
-
Sync and backup
About
@@ -295,5 +298,6 @@ + diff --git a/internal/gui/assets/plugins.css b/internal/gui/assets/plugins.css new file mode 100644 index 000000000..a2e11b609 --- /dev/null +++ b/internal/gui/assets/plugins.css @@ -0,0 +1,209 @@ +/* Plugins: the market of provider plugins, and the ones installed. */ +#view-plugins { gap: 0; } +.pm-head { gap: 10px; } +.pm-find { + display: flex; align-items: center; gap: 6px; height: 28px; padding: 0 10px; width: min(280px, 46%); + border-radius: 8px; background: var(--pill); color: var(--muted); + box-shadow: inset 0 0 0 1px transparent; transition: box-shadow .14s var(--ease), background .14s var(--ease); +} +.pm-find:focus-within { background: var(--card); box-shadow: inset 0 0 0 1px var(--accent), 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent); } +.pm-find svg { flex: none; } +.pm-find input { flex: 1; min-width: 0; border: 0; outline: none; background: none; color: var(--fg); font: inherit; font-size: 12.5px; } +.pm-find input::placeholder { color: var(--faint); } +.pm-find input::-webkit-search-cancel-button { cursor: default; } +.pm-body { gap: 18px; padding: 10px 0 18px; } + +/* the opening: what plugins are, and a few of the subscriptions they bring */ +.pm-intro { + position: relative; overflow: hidden; display: flex; align-items: center; gap: 18px; + padding: 16px 18px; border-radius: 14px; border: 1px solid var(--line); + background: + radial-gradient(120% 140% at 100% 0%, color-mix(in srgb, var(--accent) 11%, transparent), transparent 60%), + var(--card); +} +.pm-introtext { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 5px; } +.pm-intro h2 { margin: 0; font-size: 15px; font-weight: 650; letter-spacing: -.01em; text-wrap: balance; } +.pm-intro p { margin: 0; font-size: 12px; line-height: 1.55; color: var(--fg-2); max-width: 560px; } +.pm-intro .pm-trust { display: flex; align-items: center; gap: 6px; margin-top: 3px; font-size: 11.5px; color: var(--muted); } +.pm-intro .pm-trust svg { flex: none; color: var(--green); } +.pm-art { flex: none; display: grid; grid-template-columns: repeat(3, 34px); gap: 8px; transform: rotate(-6deg); margin-right: 6px; } +.pm-art .pm-logo { width: 34px; height: 34px; border-radius: 10px; box-shadow: 0 1px 2px rgba(0, 0, 0, .06), 0 0 0 1px var(--line-2); background: var(--card); } +.pm-art .pm-logo:nth-child(4) { grid-column: 2; } +.pm-art .pm-logo:nth-child(odd) { transform: translateY(4px); } + +/* sections of cards */ +.pm-sec { display: flex; flex-direction: column; gap: 9px; } +.pm-sechead { display: flex; align-items: baseline; gap: 8px; padding: 0 2px; flex-wrap: wrap; } +.pm-sechead h3 { margin: 0; font-size: 12.5px; font-weight: 650; } +.pm-sechead span { font-size: 11.5px; color: var(--muted); } +.pm-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(262px, 1fr)); gap: 10px; } + +.pm-logo { flex: none; width: 36px; height: 36px; border-radius: 10px; display: grid; place-items: center; background: var(--pill); color: var(--fg-2); } +.pm-logo .ic { width: 20px; height: 20px; } +.pm-logo.big { width: 44px; height: 44px; border-radius: 12px; } +.pm-logo.big .ic { width: 25px; height: 25px; } + +.pm-card { + display: flex; flex-direction: column; gap: 8px; min-width: 0; padding: 12px 12px 11px 13px; + border-radius: 12px; border: 1px solid var(--line); background: var(--card); cursor: default; outline: none; + transition: border-color .16s var(--ease), box-shadow .16s var(--ease), transform .16s var(--ease); +} +.pm-card:hover { border-color: color-mix(in srgb, var(--fg) 16%, var(--line)); box-shadow: 0 4px 14px rgba(20, 22, 30, .07); } +.pm-card:focus-visible { box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 28%, transparent); border-color: var(--accent); } +.pm-top { display: flex; align-items: center; gap: 10px; min-width: 0; } +.pm-who { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; } +.pm-name { display: flex; align-items: center; gap: 6px; min-width: 0; } +.pm-name b { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.pm-by { display: flex; align-items: center; gap: 4px; min-width: 0; font-size: 11px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.pm-by > span { overflow: hidden; text-overflow: ellipsis; } +.pm-verified { display: inline-flex; align-items: center; gap: 3px; color: var(--green); font-weight: 500; } +.pm-sum { + margin: 0; font-size: 12px; line-height: 1.45; color: var(--fg-2); min-height: 2.9em; + display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; +} +.pm-meta { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 11px; color: var(--muted); font-variant-numeric: tabular-nums; min-height: 18px; } +.pm-dl { display: inline-flex; align-items: center; gap: 3px; } +.pm-ver { font: 10.5px var(--code); color: var(--muted); } +.pm-chip { display: inline-flex; align-items: center; height: 17px; padding: 0 6px; border-radius: 5px; font-size: 10.5px; font-weight: 500; background: var(--pill); color: var(--fg-2); } +.pm-chip.up { background: var(--accent-soft); color: var(--accent); } +.pm-chip.bad { background: var(--red-soft); color: var(--red); } +.pm-chip.soft { background: none; box-shadow: inset 0 0 0 1px var(--line); color: var(--muted); } + +/* a plugin's one button */ +.pm-act { + flex: none; display: inline-flex; align-items: center; justify-content: center; gap: 5px; + height: 26px; min-width: 64px; padding: 0 12px; border-radius: 13px; + font-size: 12px; font-weight: 600; white-space: nowrap; + background: var(--pill); color: var(--fg-2); transition: background .14s var(--ease), color .14s var(--ease), filter .14s; +} +.pm-act:hover:not(:disabled) { background: var(--pill-hover); color: var(--fg); } +.pm-act.get { background: var(--accent-soft); color: var(--accent); } +.pm-act.get:hover:not(:disabled) { background: var(--accent); color: var(--accent-fg); } +.pm-act.go { background: var(--accent); color: var(--accent-fg); } +.pm-act.go:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); color: var(--accent-fg); } +.pm-act.done { background: none; color: var(--green); padding: 0 8px; min-width: 0; } +.pm-act.done:hover:not(:disabled) { background: var(--green-soft); color: var(--green); } +.pm-act.busy { color: var(--muted); font-weight: 500; } +.pm-act:disabled:not(.busy):not(.done) { opacity: .55; } +.pm-act .spin { width: 10px; height: 10px; border-radius: 50%; border: 1.5px solid currentColor; border-right-color: transparent; animation: spin .7s linear infinite; } + +/* loading: cards drawn as grey bars */ +.pm-card.ghost { gap: 10px; pointer-events: none; } +.pm-card.ghost > div { border-radius: 6px; background: var(--pill); animation: pm-pulse 1.3s ease-in-out infinite; } +.pm-card.ghost .g1 { height: 36px; width: 60%; } +.pm-card.ghost .g2 { height: 11px; } +.pm-card.ghost .g3 { height: 11px; width: 40%; } +@keyframes pm-pulse { 50% { opacity: .5; } } + +.pm-note { margin: 0; padding: 4px 2px; font-size: 12px; color: var(--muted); } +.pm-note.bad { color: var(--red); } +.pm-empty { margin: 24px 4px; font-size: 12.5px; color: var(--red); } + +/* a package the market doesn't list */ +.pm-manual { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-radius: 12px; border: 1px dashed var(--line); flex-wrap: wrap; } +.pm-mlabel { font-size: 12px; color: var(--muted); } +.pm-minput { flex: 1; min-width: 180px; height: 26px; padding: 0 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font: 12px var(--code); outline: none; } +.pm-minput:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent); } + +/* Installed */ +.pm-list .row { min-height: 54px; padding: 8px 10px 8px 12px; gap: 11px; cursor: default; transition: background .14s var(--ease); } +.pm-list .row:hover { background: var(--card-2); } +.pm-list .row + .row { border-top: 1px solid var(--line-2); } +.pm-row .pm-logo { width: 32px; height: 32px; border-radius: 9px; } +.pm-row .pm-logo .ic { width: 18px; height: 18px; } +.pm-row .who { flex: 1; min-width: 0; } +.pm-row .name { display: flex; align-items: center; gap: 7px; font-size: 13px; font-weight: 500; } +.pm-row .sub { display: flex; align-items: center; flex-wrap: wrap; gap: 0 2px; margin-top: 2px; font-size: 11.5px; color: var(--muted); } +.pm-row .sub.bad { color: var(--red); display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.pm-row .sub .sep { color: var(--faint); } +.pm-sub { display: inline-flex; align-items: center; gap: 5px; } +.pm-sub .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--faint); } +.pm-sub.in .dot { background: var(--green); } +.pm-row .val { display: flex; align-items: center; gap: 2px; flex: none; } +.pm-row.off .who, .pm-row.off .pm-logo { opacity: .5; } +.pm-foot { display: flex; align-items: center; gap: 8px; padding: 0 4px; font-size: 11px; color: var(--faint); } +.pm-none { display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 44px 16px; text-align: center; } +.pm-none b { font-size: 13.5px; font-weight: 600; margin-top: 4px; } +.pm-none p { margin: 0 0 6px; font-size: 12px; color: var(--muted); max-width: 320px; line-height: 1.5; } + +/* a plugin's page */ +.modal .editor.pm-detail.framed > .ehead { min-height: 76px; gap: 12px; } +.modal .editor.pm-detail.framed > .ebody { display: block; padding: 0; } +.pm-dhead .pm-name b { font-size: 15px; } +.pm-dhead .pm-by { font-size: 11.5px; } +.pm-dact .pm-act { height: 28px; min-width: 80px; border-radius: 14px; } +.pm-dbody { display: flex; flex-direction: column; gap: 12px; padding: 14px 18px 18px; } +.pm-dsum { margin: 0; font-size: 13px; line-height: 1.5; color: var(--fg); } +.pm-facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 1px; border-radius: 10px; overflow: hidden; background: var(--line-2); border: 1px solid var(--line-2); } +.pm-fact { display: flex; flex-direction: column; gap: 2px; padding: 8px 11px; background: var(--card); min-width: 0; } +.pm-fact .k { font-size: 10.5px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); } +.pm-fact .v { font-size: 12.5px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; } +.pm-links { display: flex; gap: 6px; flex-wrap: wrap; } +.pm-link { display: inline-flex; align-items: center; gap: 4px; height: 24px; padding: 0 9px; border-radius: 7px; background: var(--pill); color: var(--fg-2); font-size: 11.5px; text-decoration: none; } +.pm-link:hover { background: var(--pill-hover); color: var(--fg); } +.pm-readme { border-top: 1px solid var(--line-2); padding-top: 12px; min-height: 60px; } +.pm-rskel { height: 11px; margin: 8px 0; border-radius: 5px; background: var(--pill); animation: pm-pulse 1.3s ease-in-out infinite; } +.pm-rskel.short { width: 55%; } + +/* a README */ +.pm-md { font-size: 12.5px; line-height: 1.6; color: var(--fg-2); overflow-wrap: anywhere; } +.pm-md > :first-child { margin-top: 0; } +.pm-md h3, .pm-md h4, .pm-md h5, .pm-md h6 { color: var(--fg); margin: 16px 0 6px; line-height: 1.3; text-wrap: balance; } +.pm-md h3 { font-size: 15px; font-weight: 650; } +.pm-md h4 { font-size: 13.5px; font-weight: 650; } +.pm-md h5, .pm-md h6 { font-size: 12.5px; font-weight: 600; } +.pm-md p { margin: 0 0 9px; } +.pm-md ul, .pm-md ol { margin: 0 0 9px; padding-left: 20px; } +.pm-md li + li { margin-top: 2px; } +.pm-md a { color: var(--accent); text-decoration: none; } +.pm-md a:hover { text-decoration: underline; } +.pm-md code { font: 11.5px var(--code); padding: 1px 4px; border-radius: 4px; background: var(--pill); color: var(--fg); } +.pm-md pre { margin: 0 0 10px; padding: 9px 11px; border-radius: 8px; background: var(--card-2); border: 1px solid var(--line-2); overflow-x: auto; } +.pm-md pre code { padding: 0; background: none; font-size: 11.5px; line-height: 1.5; white-space: pre; } +.pm-md blockquote { margin: 0 0 9px; padding: 7px 11px; border-radius: 8px; background: var(--card-2); color: var(--fg-2); } +.pm-md hr { border: 0; border-top: 1px solid var(--line-2); margin: 12px 0; } +.pm-table { overflow-x: auto; margin: 0 0 10px; } +.pm-md table { border-collapse: collapse; font-size: 12px; } +.pm-md th, .pm-md td { padding: 5px 9px; border: 1px solid var(--line-2); text-align: left; vertical-align: top; } +.pm-md th { background: var(--card-2); font-weight: 600; color: var(--fg); } + +/* the providers list's way here: three subscriptions in a stack, and a word */ +#view-providers .after-list { justify-content: space-between; } +.more-subs { + display: inline-flex; align-items: center; gap: 8px; height: 28px; padding: 0 9px 0 5px; border-radius: 14px; + background: var(--card); color: var(--fg-2); font-size: 12px; + box-shadow: 0 0 0 1px var(--line), 0 1px 2px rgba(0, 0, 0, .04); + transition: box-shadow .16s var(--ease), color .16s var(--ease); +} +.more-subs:hover { color: var(--fg); box-shadow: 0 0 0 1px color-mix(in srgb, var(--accent) 45%, var(--line)), 0 3px 10px rgba(20, 22, 30, .08); } +.more-subs .stack { display: inline-flex; align-items: center; } +.more-subs .stack .ic { + width: 20px; height: 20px; padding: 3px; box-sizing: border-box; border-radius: 50%; + background: var(--card); box-shadow: 0 0 0 1px var(--line-2); transition: transform .22s var(--ease); +} +.more-subs .stack .ic + .ic { margin-left: -6px; } +.more-subs .stack .ic:nth-child(1) { z-index: 3; position: relative; } +.more-subs .stack .ic:nth-child(2) { z-index: 2; position: relative; } +.more-subs:hover .stack .ic:nth-child(2) { transform: translateX(2px); } +.more-subs:hover .stack .ic:nth-child(3) { transform: translateX(4px); } +.more-subs .say { display: inline-flex; gap: 4px; white-space: nowrap; } +.more-subs .say .in { color: var(--accent); font-weight: 500; } +.more-subs > svg { color: var(--faint); transition: transform .18s var(--ease), color .18s; } +.more-subs:hover > svg { color: var(--accent); transform: translateX(2px); } + +/* the add sheet's row to Plugins */ +.tile.more-plugins { color: var(--accent); } +.tile.more-plugins .puzzle { flex: none; width: 18px; height: 18px; display: grid; place-items: center; } +.tile.more-plugins > svg { flex: none; opacity: .7; } +.tile.more-plugins:hover { background: var(--accent-soft); } + +@media (max-width: 560px) { + .pm-head { flex-wrap: wrap; } + .pm-find { width: 100%; order: 3; } + .pm-art { display: none; } + .more-subs .say .in { display: none; } +} +@media (prefers-reduced-motion: reduce) { + .pm-card, .more-subs .stack .ic, .more-subs > svg { transition: none; } + .pm-card.ghost > div, .pm-rskel { animation: none; } +} diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js new file mode 100644 index 000000000..be79e79d3 --- /dev/null +++ b/internal/gui/assets/plugins.js @@ -0,0 +1,620 @@ +// Plugins: the market of OpenCode provider plugins — subscriptions magpie +// signs in to through someone else's code. Discover lists the plugins +// magpie suggests (the community repo's list, with what npm says of each +// now) and finds the rest on npm; Installed is what was added, to sign in +// with, update, switch off or remove. Everything comes from +// /api/plugins/market; a sign-in happens in the Providers add sheet, as +// every other subscription's does. +(() => { + const page = $("#view-plugins"); + if (!page) return; + + let market = null; // /api/plugins/market + let failed = ""; // why the market couldn't be loaded + let tab = "discover"; + try { tab = localStorage.getItem("magpie.pluginTab") || tab; } catch {} + let query = ""; + let hits = null; // npm's answer for query: { q, list } | { q, loading } | { q, error } + let searchTimer = 0; + const busy = new Map(); // package → "add" | "remove" | "upgrade" | "off" + let shown = ""; + + const SEARCH = "M7 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z M10 10l3 3"; + const DOWN = "M8 3v7.5 M4.8 7.6 8 10.8l3.2-3.2 M3.5 13h9"; + const SHIELD = "M8 2.3 13 4v3.8c0 3-2.1 5.1-5 5.9-2.9-.8-5-2.9-5-5.9V4z M5.8 8l1.6 1.6 2.9-3"; + const OUTL = "M9.5 3.5h3v3 M12.5 3.5 7.5 8.5 M11 9.5v3H3.5V5h3"; + + const name = (spec) => { const i = spec.lastIndexOf("@"); return i > 0 && !spec.startsWith(".") && !spec.includes("/", i) ? spec.slice(0, i) : spec; }; + const lang = () => (document.documentElement.lang || "").startsWith("zh") ? "zh" : "en"; + const summary = (l) => l.summary?.[lang()] || l.summary?.en || l.npm?.description || ""; + const count = (n) => n >= 1e6 ? (n / 1e6).toFixed(n >= 1e7 ? 0 : 1) + "M" : n >= 1e3 ? (n / 1e3).toFixed(n >= 1e4 ? 0 : 1) + "k" : String(n || 0); + const entryOf = (pkg) => market?.state.plugins.find((e) => name(e.spec) === pkg); + // the providers a plugin signs in to, as the add sheet knows them + const subsOf = (pkg) => (providers?.plugins || []).filter((x) => name(x.spec) === pkg); + const newer = (a, b) => { + const p = (v) => (v || "").split(/[.+-]/).slice(0, 3).map((x) => parseInt(x, 10) || 0); + const [x, y] = [p(a), p(b)]; + for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i]; + return false; + }; + + function glyph(d, size = 14, stroke = 1.5) { return svg(d, size, stroke); } + function logo(ic, big) { + const box = el("span", "pm-logo" + (big ? " big" : "")); + if (ic) box.append(icon(ic)); + else box.append(glyph(PUZZLE, big ? 22 : 17, 1.4)); + return box; + } + + async function load() { + const first = !market; + if (first) draw(); + try { + const [m] = await Promise.all([api("plugins/market"), providers ? null : loadProviders().catch(() => {})]); + market = m; + failed = ""; + } catch (e) { + failed = e.message; + } + draw(); + } + window.loadPlugins = load; + // pluginQuery: Discover, looking for q (the add sheet found nothing by it) + window.pluginQuery = (q) => { + if (q === query && !q) return; + query = q; + tab = "discover"; + clearTimeout(searchTimer); + hits = q.trim().length >= 2 ? { q: q.trim(), loading: true } : null; + if (hits) searchNPM(hits.q); + draw(); + }; + + async function refresh() { + try { + const [m, p] = await Promise.all([api("plugins/market"), api("providers")]); + market = m; + providers = p; + // the Providers page owns the dialog as it draws: only drawn when shown + if (view === "providers") renderProviders(); + } catch (e) { status(e.message, "err"); } + draw(); + } + + async function act(pkg, op, body, done) { + if (busy.size && op !== "off") return; + busy.set(pkg, op); + draw(); + try { + await api("plugins/" + op, body); + busy.delete(pkg); + await refresh(); + if (done) done(); + } catch (e) { + busy.delete(pkg); + draw(); + status(e.message, "err"); + } + } + const install = (pkg, nm) => act(pkg, "add", { spec: pkg }, () => { + const subs = subsOf(pkg); + status(subs.length ? t("{name} is installed — sign in to use it", { name: nm }) : t("{name} is installed", { name: nm }), "ok"); + }); + + // the one button a plugin shows: what to do with it next + function actionFor(pkg, nm, listed) { + const b = el("button", "pm-act"); + const e = entryOf(pkg); + const op = busy.get(pkg); + if (op === "add" || op === "upgrade") { + b.classList.add("busy"); + b.append(el("span", "spin"), el("span", "", op === "upgrade" ? t("Updating…") : market?.state.bun ? t("Installing…") : t("Getting Bun…"))); + b.disabled = true; + if (!market?.state.bun) b.title = t("Plugins run on Bun {v}, downloaded once", { v: market?.state.bunVersion || "" }); + return b; + } + if (!e) { + if (listed && !listed.npm?.version) { + b.textContent = t("Coming soon"); + b.disabled = true; + b.title = t("Not on npm yet"); + return b; + } + b.classList.add("get"); + b.textContent = t("Install"); + b.disabled = busy.size > 0; + b.onclick = (ev) => { ev.stopPropagation(); install(pkg, nm); }; + return b; + } + if (e.off) { + b.textContent = t("Switch on"); + b.onclick = (ev) => { ev.stopPropagation(); act(pkg, "off", { spec: e.spec, off: false }); }; + return b; + } + const subs = subsOf(pkg); + const out = subs.find((x) => !x.signedIn); + if (out) { + b.classList.add("go"); + b.textContent = t("Sign in"); + b.title = subs.length > 1 ? t("Sign in to {name}", { name: out.name }) : ""; + b.onclick = (ev) => { ev.stopPropagation(); pluginSignIn(out.id); }; + return b; + } + if (subs.length) { + b.classList.add("done"); + b.append(glyph(CHECK, 11, 2), el("span", "", t("Signed in"))); + b.title = t("Open {name} in Providers", { name: subs[0].name }); + b.onclick = (ev) => { ev.stopPropagation(); openProvider(subs[0].id); }; + return b; + } + b.classList.add("done"); + b.append(glyph(CHECK, 11, 2), el("span", "", t("Installed"))); + b.disabled = true; + return b; + } + + function card(l) { + const c = el("div", "pm-card"); + c.tabIndex = 0; + c.setAttribute("role", "button"); + c.dataset.pkg = l.package; + const e = entryOf(l.package); + if (e) c.classList.add("have"); + const top = el("div", "pm-top"); + const who = el("div", "pm-who"); + const nm = el("div", "pm-name"); + nm.append(el("b", "", l.name)); + who.append(nm); + const by = el("div", "pm-by"); + if (l.community) { + const v = el("span", "pm-verified"); + v.append(glyph(SHIELD, 11, 1.5), el("span", "", t("magpie community"))); + v.title = t("Written for magpie by its community, in github.com/magpie-community/plugins"); + by.append(v); + } else by.append(el("span", "", l.npm?.publisher || l.package)); + who.append(by); + top.append(logo(l.icon), who, actionFor(l.package, l.name, l)); + const sum = el("p", "pm-sum", summary(l)); + const meta = el("div", "pm-meta"); + if (l.npm?.weekly) { + const d = el("span", "pm-dl"); + d.append(glyph(DOWN, 11, 1.5), el("span", "", t("{n}/week", { n: count(l.npm.weekly) }))); + d.title = t("{n} downloads on npm last week", { n: l.npm.weekly.toLocaleString() }); + meta.append(d); + } + if (l.npm?.version) meta.append(el("span", "pm-ver", "v" + (e?.version || l.npm.version))); + if (e && e.latest && e.version && newer(e.latest, e.version)) meta.append(el("span", "pm-chip up", t("Update"))); + if (e?.error && !e.off) meta.append(el("span", "pm-chip bad", t("Didn't load"))); + else if (e?.off) meta.append(el("span", "pm-chip", t("Off"))); + if (l.replaces) { + const b = el("span", "pm-chip soft", t("Also built in")); + b.title = t("magpie also signs in to this itself, for now; the plugin keeps it working if the built-in one is retired"); + meta.append(b); + } + c.append(top, sum, meta); + c.onclick = () => detail(l); + c.onkeydown = (ev) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); detail(l); } }; + return c; + } + + function skeleton(n) { + const g = el("div", "pm-grid"); + for (let i = 0; i < n; i++) { + const c = el("div", "pm-card ghost"); + c.append(el("div", "g1"), el("div", "g2"), el("div", "g3")); + g.append(c); + } + return g; + } + + function section(title, hint, list) { + const box = el("section", "pm-sec"); + const h = el("div", "pm-sechead"); + h.append(el("h3", "", title)); + if (hint) h.append(el("span", "", hint)); + const g = el("div", "pm-grid"); + for (const l of list) g.append(card(l)); + box.append(h, g); + return box; + } + + function head() { + const h = el("div", "lib-head pm-head"); + const n = market?.state.plugins.length || 0; + const tabs = segs([["discover", t("Discover")], ["installed", t("Installed") + (n ? " · " + n : "")]], tab, (id) => { + tab = id; + try { localStorage.setItem("magpie.pluginTab", id); } catch {} + drawBody(); + }); + tabs.classList.add("lib-tabs"); + const find = el("label", "pm-find"); + find.append(glyph(SEARCH, 13, 1.6)); + const q = el("input"); + q.type = "search"; + q.placeholder = t("Search plugins and npm…"); + q.value = query; + q.spellcheck = false; + q.autocomplete = "off"; + q.setAttribute("aria-label", t("Search plugins")); + q.oninput = () => { + query = q.value; + if (tab !== "discover") { tab = "discover"; draw(); page.querySelector(".pm-find input")?.focus(); } + clearTimeout(searchTimer); + const s = query.trim(); + if (s.length < 2) hits = null; + else { + hits = { q: s, loading: true }; + searchTimer = setTimeout(() => searchNPM(s), 350); + } + drawBody(); + }; + q.onkeydown = (ev) => { ev.stopPropagation(); if (ev.key === "Escape" && q.value) { q.value = ""; q.oninput(); } }; + find.append(q); + h.append(tabs, el("span", "grow"), find); + h.classList.toggle("stuck", page.scrollTop > 0); + return h; + } + + async function searchNPM(s) { + try { + const r = await api("plugins/search?q=" + encodeURIComponent(s)); + if (hits?.q === s) hits = { q: s, list: r.hits }; + } catch (e) { + if (hits?.q === s) hits = { q: s, error: e.message }; + } + if (hits?.q === s) drawBody(); + } + + page.addEventListener("scroll", () => page.querySelector(".pm-head")?.classList.toggle("stuck", page.scrollTop > 0), { passive: true }); + + let body = null; + function draw() { + const scroll = page.scrollTop; + page.replaceChildren(head()); + body = el("div", "lib-body pm-body"); + page.append(body); + drawBody(); + page.scrollTop = scroll; + } + + function drawBody() { + if (!body) return; + const key = tab + (query ? ":q" : ""); + body.classList.toggle("enter", shown !== key); + shown = key; + body.replaceChildren(); + // the search field keeps its focus: only the body is redrawn while typing + if (failed && !market) { + body.append(el("p", "pm-empty", t("Couldn't load the plugins: {error}", { error: failed }))); + return; + } + if (tab === "installed") return drawInstalled(); + if (!market) { + body.append(intro(), skeleton(6)); + return; + } + const f = query.trim().toLowerCase(); + const ls = market.listings.filter((l) => !f || [l.name, l.package, summary(l), (l.providers || []).join(" "), l.npm?.publisher || ""].join(" ").toLowerCase().includes(f)); + if (!f) { + body.append(intro()); + const ours = ls.filter((l) => l.community); + const theirs = ls.filter((l) => !l.community).sort((a, b) => (b.npm?.weekly || 0) - (a.npm?.weekly || 0)); + if (ours.length) body.append(section(t("magpie community"), t("written for magpie, checked against its own sign-ins"), ours)); + if (theirs.length) body.append(section(t("From OpenCode's community"), t("popular OpenCode plugins that work in magpie"), theirs)); + body.append(manual()); + return; + } + if (ls.length) body.append(section(t("Suggested"), "", ls)); + const known = new Set(market.listings.map((l) => l.package)); + const box = el("section", "pm-sec"); + const h = el("div", "pm-sechead"); + h.append(el("h3", "", t("On npm")), el("span", "", t("OpenCode plugins anyone published — read what one does before you install it"))); + box.append(h); + if (!hits) box.append(el("p", "pm-note", t("Type two letters or more to search npm"))); + else if (hits.loading) box.append(skeleton(2)); + else if (hits.error) box.append(el("p", "pm-note bad", hits.error)); + else { + const list = hits.list.filter((x) => !known.has(x.package)); + if (!list.length) box.append(el("p", "pm-note", ls.length ? t("Nothing else on npm") : t("No plugin called “{q}”", { q: query.trim() }))); + const g = el("div", "pm-grid"); + for (const x of list) g.append(card({ package: x.package, name: x.package, npm: x })); + box.append(g); + } + body.append(box); + } + + function intro() { + const box = el("div", "pm-intro"); + const text = el("div", "pm-introtext"); + text.append(el("h2", "", t("Subscriptions, as plugins"))); + text.append(el("p", "", t("Plugins sign in to coding plans and make their requests; the models then work in every agent, like any provider's. They're OpenCode's provider plugins, run on Bun."))); + const trust = el("p", "pm-trust"); + trust.append(glyph(SHIELD, 12, 1.5), el("span", "", t("A plugin is someone else's code with your sign-in: install the ones you trust."))); + text.append(trust); + const art = el("div", "pm-art"); + for (const ic of ["zcode", "githubcopilot", "gemini-color", "zed", "kiro-color"]) art.append(logo(ic)); + box.append(text, art); + return box; + } + + // a package or a folder the market doesn't list + function manual() { + const box = el("form", "pm-manual"); + box.append(el("span", "pm-mlabel", t("Have one in mind?"))); + const spec = el("input", "pm-minput"); + spec.placeholder = t("npm package or a folder on this computer"); + spec.spellcheck = false; + spec.autocomplete = "off"; + spec.setAttribute("aria-label", t("Plugin")); + spec.onkeydown = (ev) => ev.stopPropagation(); + const go = el("button", "text primary", t("Install")); + go.type = "submit"; + go.disabled = busy.size > 0; + if (busy.has("+")) { go.textContent = t("Installing…"); spec.disabled = true; } + box.onsubmit = (ev) => { + ev.preventDefault(); + const s = spec.value.trim(); + if (!s || busy.size) return; + act("+", "add", { spec: s }, () => status(t("{name} is installed", { name: s }), "ok")); + }; + box.append(spec, go); + return box; + } + + function drawInstalled() { + if (!market) { body.append(skeleton(2)); return; } + const es = market.state.plugins; + if (!es.length) { + const none = el("div", "pm-none"); + none.append(logo("", true), el("b", "", t("No plugins yet")), el("p", "", t("Find a subscription in Discover and install it; it signs in from here."))); + const b = el("button", "pm-act get", t("Discover plugins")); + b.onclick = () => { tab = "discover"; draw(); }; + none.append(b); + body.append(none); + return; + } + const list = el("div", "list pm-list"); + for (const e of es) list.append(installedRow(e)); + body.append(list); + const foot = el("div", "pm-foot"); + const outdated = es.filter((e) => e.latest && e.version && newer(e.latest, e.version)); + foot.append(el("span", "", market.state.bun ? t("Plugins run on Bun {v}", { v: market.state.bunVersion }) : ""), el("span", "grow")); + if (outdated.length) { + const up = el("button", "text", busy.has("*") ? t("Updating…") : t("Update all ({n})", { n: outdated.length })); + up.disabled = busy.size > 0; + up.onclick = () => act("*", "update", {}, () => status(t("Plugins updated"), "ok")); + foot.append(up); + } + body.append(foot); + } + + function installedRow(e) { + const pkg = name(e.spec); + const l = market.listings.find((x) => x.package === pkg); + const r = el("div", "row pm-row" + (e.off ? " off" : "")); + const who = el("div", "who"); + const nm = el("div", "name"); + nm.append(el("span", "", l?.name || pkg)); + if (e.version) nm.append(el("span", "pm-ver", "v" + e.version)); + if (e.latest && e.version && newer(e.latest, e.version)) nm.append(el("span", "pm-chip up", t("v{v} out", { v: e.latest }))); + who.append(nm); + const subs = subsOf(pkg); + const sub = el("div", "sub"); + if (e.off) sub.textContent = t("Off"); + else if (e.error) { sub.textContent = t("Didn't load: {error}", { error: e.error }); sub.classList.add("bad"); sub.title = e.error; } + else if (subs.length) { + for (const [i, x] of subs.entries()) { + if (i) sub.append(el("span", "sep", " · ")); + const s = el("span", "pm-sub" + (x.signedIn ? " in" : "")); + s.append(el("span", "dot"), el("span", "", x.signedIn ? t("{name}: signed in", { name: x.name }) : t("{name}: not signed in", { name: x.name }))); + sub.append(s); + } + } else sub.textContent = e.providers.length ? t("Signs in to {names}", { names: e.providers.join(t(", ")) }) : t("Signs in to nothing magpie can use"); + who.append(sub); + r.append(logo(l?.icon || subs[0]?.icon), who); + const val = el("div", "val"); + const b = busy.get(pkg) || busy.get(e.spec); + if (e.latest && e.version && newer(e.latest, e.version) && !e.off) { + const up = el("button", "text", b === "upgrade" ? t("Updating…") : t("Update")); + up.disabled = busy.size > 0; + up.onclick = () => act(pkg, "upgrade", { spec: e.spec }, () => status(t("{name} updated to v{v}", { name: l?.name || pkg, v: e.latest }), "ok")); + val.append(up); + } + if (!e.off && !e.error && subs.some((x) => !x.signedIn)) { + const s = el("button", "text primary", t("Sign in")); + s.onclick = () => pluginSignIn(subs.find((x) => !x.signedIn).id); + val.append(s); + } + const onoff = el("button", "text", t(e.off ? "Switch on" : "Switch off")); + onoff.disabled = !!b; + onoff.onclick = () => act(pkg, "off", { spec: e.spec, off: !e.off }); + const rm = el("button", "text quiet", b === "remove" ? t("Removing…") : t("Remove")); + rm.title = t("Removes the plugin and what it installed; its sign-ins are kept until you sign out"); + rm.disabled = busy.size > 0; + rm.onclick = () => act(pkg, "remove", { spec: e.spec }, () => status(t("{name} removed", { name: l?.name || pkg }), "ok")); + val.append(onoff, rm); + r.append(val); + r.onclick = (ev) => { if (!ev.target.closest("button")) detail(l || { package: pkg, name: pkg, npm: { version: e.latest } }); }; + return r; + } + + // the plugin's page: what it is, what npm says of it, and its README + async function detail(l) { + const ed = el("div", "editor pm-detail"); + const hd = el("div", "ehead pm-dhead"); + hd.append(logo(l.icon, true)); + const who = el("div", "pm-who"); + const nm = el("div", "pm-name"); + nm.append(el("b", "", l.name)); + who.append(nm, el("div", "pm-by", l.community ? t("magpie community") + " · " + l.package : [l.npm?.publisher, l.package].filter(Boolean).join(" · "))); + const actBox = el("div", "pm-dact"); + // redrawn only when what it would say changes: a button made afresh + // loses the pointer's hover + let said = ""; + const redrawAct = () => { + const b = actionFor(l.package, l.name, l.npm ? l : null); + const now = b.className + b.textContent + b.disabled; + if (now !== said) { said = now; actBox.replaceChildren(b); } + }; + redrawAct(); + hd.append(who, el("span", "grow"), actBox); + ed.append(hd); + const main = el("div", "pm-dbody"); + const sum = summary(l); + if (sum) main.append(el("p", "pm-dsum", sum)); + const facts = el("div", "pm-facts"); + const fact = (k, v) => { if (!v) return; const f = el("div", "pm-fact"); f.append(el("span", "k", k), typeof v === "string" ? el("span", "v", v) : v); facts.append(f); }; + fact(t("Version"), l.npm?.version && "v" + l.npm.version); + fact(t("Downloads"), l.npm?.weekly ? t("{n}/week", { n: count(l.npm.weekly) }) : ""); + fact(t("License"), l.npm?.license); + const upd = el("span", "v", "…"); + fact(t("Updated"), upd); + if (l.providers?.length) fact(t("Signs in to"), l.providers.join(t(", "))); + main.append(facts); + const links = el("div", "pm-links"); + const link = (label, href) => { + if (!href) return; + const a = el("a", "pm-link"); + a.href = href; + a.append(el("span", "", label), glyph(OUTL, 11, 1.5)); + a.onclick = (ev) => { ev.preventDefault(); api("open", { url: href }).catch(() => {}); }; + links.append(a); + }; + link("npm", "https://www.npmjs.com/package/" + l.package); + link(t("Source"), l.npm?.repository); + if (l.npm?.homepage && l.npm.homepage !== l.npm.repository && !l.npm.homepage.startsWith(l.npm.repository + "#")) link(t("Homepage"), l.npm.homepage); + main.append(links); + if (l.replaces) main.append(el("p", "pm-note", t("magpie also signs in to this itself, for now; the plugin keeps it working if the built-in one is retired."))); + const readme = el("div", "pm-readme"); + readme.append(el("div", "pm-rskel"), el("div", "pm-rskel short"), el("div", "pm-rskel")); + main.append(readme); + ed.append(main); + const bar = el("div", "bar"); + bar.append(el("span", "note", t("Plugins are other people's code: they sign in and make the requests.")), el("span", "grow")); + const close = el("button", "text", t("Close")); + close.onclick = () => { stop(); closeModal(); }; + bar.append(close); + ed.append(bar); + openModal(ed); + // the button follows an install or a sign-in made while it's open + const tick = setInterval(() => { if (!ed.isConnected) return stop(); redrawAct(); }, 600); + function stop() { clearInterval(tick); } + try { + const p = await api("plugins/page?name=" + encodeURIComponent(l.package)); + upd.textContent = p.updated && !p.updated.startsWith("0001") ? new Date(p.updated).toLocaleDateString(document.documentElement.lang || undefined, { year: "numeric", month: "short", day: "numeric" }) : "—"; + readme.replaceChildren(markdown(p.readme || t("No README"))); + } catch (e) { + upd.textContent = "—"; + readme.replaceChildren(el("p", "pm-note", t("npm didn't answer: {error}", { error: e.message }))); + } + } + + // markdown: a README as text, links and code — no HTML of its own, no + // pictures (a README's badges and screenshots come from anywhere) + function markdown(src) { + const root = el("div", "pm-md"); + const lines = src.replace(/\r\n?/g, "\n").replace(/|<(script|style)\b[\s\S]*?<\/\1\s*>/gi, "").split("\n"); + const inline = (text, into) => { + const re = /(`[^`]+`)|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\s][^*]*)\*|!\[[^\]]*\]\([^)]*\)|\[([^\]]+)\]\(([^)\s]+)[^)]*\)|<(https?:\/\/[^>\s]+)>|<\/?[a-zA-Z][^>]*>/g; + let at = 0, m; + while ((m = re.exec(text))) { + if (m.index > at) into.append(text.slice(at, m.index)); + if (m[1]) into.append(el("code", "", m[1].slice(1, -1))); + else if (m[2] || m[3]) into.append(el("strong", "", m[2] || m[3])); + else if (m[4]) into.append(el("em", "", m[4])); + else if (m[5]) { + const href = m[6]; + if (/^https?:\/\//.test(href)) { + const a = el("a", "", ""); + a.href = href; + inline(m[5].replace(/!\[[^\]]*\]\([^)]*\)/g, "").trim() || href, a); + a.onclick = (ev) => { ev.preventDefault(); api("open", { url: href }).catch(() => {}); }; + into.append(a); + } else inline(m[5], into); + } else if (m[7]) { + const a = el("a", "", m[7]); + a.href = m[7]; + a.onclick = (ev) => { ev.preventDefault(); api("open", { url: m[7] }).catch(() => {}); }; + into.append(a); + } + at = re.lastIndex; + } + if (at < text.length) into.append(text.slice(at)); + }; + let i = 0, list = null, para = null; + const flush = () => { list = null; para = null; }; + while (i < lines.length) { + const line = lines[i]; + const fence = line.match(/^\s*(```|~~~)\s*([\w+-]*)/); + if (fence) { + flush(); + const code = []; + i++; + while (i < lines.length && !lines[i].trimStart().startsWith(fence[1])) code.push(lines[i++]); + i++; + const pre = el("pre", "", ""); + pre.append(el("code", "", code.join("\n"))); + root.append(pre); + continue; + } + const h = line.match(/^(#{1,6})\s+(.*?)\s*#*\s*$/); + if (h) { + flush(); + const e = el("h" + Math.min(6, h[1].length + 2)); + inline(h[2], e); + if (e.textContent.trim()) root.append(e); + i++; + continue; + } + if (/^\s*\|.*\|\s*$/.test(line) && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1] || "")) { + flush(); + const cells = (s) => s.trim().replace(/^\||\|$/g, "").split("|").map((c) => c.trim()); + const wrap = el("div", "pm-table"); + const table = el("table"); + const tr = el("tr"); + for (const c of cells(line)) { const th = el("th"); inline(c, th); tr.append(th); } + table.append(tr); + i += 2; + while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) { + const r = el("tr"); + for (const c of cells(lines[i])) { const td = el("td"); inline(c, td); r.append(td); } + table.append(r); + i++; + } + wrap.append(table); + root.append(wrap); + continue; + } + const li = line.match(/^\s*([-*+]|\d+[.)])\s+(.*)$/); + if (li) { + para = null; + const ordered = /\d/.test(li[1]); + if (!list || list.tagName !== (ordered ? "OL" : "UL")) { list = el(ordered ? "ol" : "ul"); root.append(list); } + const item = el("li"); + inline(li[2].replace(/^\[( |x)\]\s*/i, (s, x) => x.trim() ? "✓ " : "☐ "), item); + list.append(item); + i++; + continue; + } + const q = line.match(/^\s*>\s?(.*)$/); + if (q) { + flush(); + const bq = el("blockquote"); + const parts = []; + while (i < lines.length && /^\s*>/.test(lines[i])) parts.push(lines[i++].replace(/^\s*>\s?/, "")); + inline(parts.join(" ").replace(/^\[!(\w+)\]\s*/, (s, k) => k.toUpperCase() + ": "), bq); + root.append(bq); + continue; + } + if (/^\s*([-*_])\s*\1\s*\1[\s\1]*$/.test(line)) { flush(); root.append(el("hr")); i++; continue; } + if (!line.trim()) { flush(); i++; continue; } + if (list && /^\s{2,}\S/.test(line)) { const last = list.lastElementChild; last.append(" "); inline(line.trim(), last); i++; continue; } + if (!para) { para = el("p"); root.append(para); list = null; } else para.append(" "); + inline(line.trim(), para); + if (!para.textContent.trim() && !para.children.length) { para.remove(); para = null; } + i++; + } + for (const p of root.querySelectorAll("p")) if (!p.textContent.trim()) p.remove(); + return root; + } +})(); diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index 72f1660dd..e6a9780e6 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -63,6 +63,8 @@ type pluginEntryJSON struct { plugin.Entry Error string `json:"error,omitempty"` // why it didn't load Providers []string `json:"providers"` // the names of those it signs in to + Version string `json:"version,omitempty"` // installed + Latest string `json:"latest,omitempty"` // on npm, when the market asked } type pluginsJSON struct { @@ -92,7 +94,7 @@ func pluginsState(ctx context.Context) pluginsJSON { } } for _, e := range l.Plugins { - j := pluginEntryJSON{Entry: e, Error: errs[e.Spec], Providers: names[e.Spec]} + j := pluginEntryJSON{Entry: e, Error: errs[e.Spec], Providers: names[e.Spec], Version: plugin.Installed(e.Spec)} if j.Providers == nil { j.Providers = []string{} } @@ -101,7 +103,67 @@ func pluginsState(ctx context.Context) pluginsJSON { return s } +// pluginMarketJSON is the plugin market: the plugins magpie suggests, what npm +// says of each, and those added. +type pluginMarketJSON struct { + Listings []pluginListingJSON `json:"listings"` + State pluginsJSON `json:"state"` +} + +type pluginListingJSON struct { + plugin.Listing + NPM plugin.NPM `json:"npm"` +} + +func pluginMarketState(ctx context.Context) pluginMarketJSON { + var ls []plugin.Listing + var st pluginsJSON + done := make(chan struct{}) + go func() { st = pluginsState(ctx); close(done) }() + ls = plugin.Market(ctx) + names := []string{} + for _, l := range ls { + names = append(names, l.Package) + } + <-done + for _, e := range st.Plugins { + if !plugin.IsPath(e.Spec) { + names = append(names, plugin.Name(e.Spec)) + } + } + info := plugin.Info(ctx, names) + m := pluginMarketJSON{Listings: []pluginListingJSON{}, State: st} + for _, l := range ls { + m.Listings = append(m.Listings, pluginListingJSON{Listing: l, NPM: info[l.Package]}) + } + for i, e := range m.State.Plugins { + m.State.Plugins[i].Latest = info[plugin.Name(e.Spec)].Version + } + return m +} + func pluginRoutes(mux *http.ServeMux, w Windows) { + mux.HandleFunc("GET /api/plugins/market", func(rw http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + writeJSON(rw, pluginMarketState(ctx)) + }) + mux.HandleFunc("GET /api/plugins/search", func(rw http.ResponseWriter, r *http.Request) { + hits, err := plugin.Search(r.Context(), r.URL.Query().Get("q")) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, map[string]any{"hits": hits}) + }) + mux.HandleFunc("GET /api/plugins/page", func(rw http.ResponseWriter, r *http.Request) { + p, err := plugin.Readme(r.Context(), r.URL.Query().Get("name")) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, p) + }) mux.HandleFunc("GET /api/plugins", func(rw http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), time.Minute) defer cancel() @@ -128,6 +190,8 @@ func pluginRoutes(mux *http.ServeMux, w Windows) { err = plugin.Remove(ctx, in.Spec) case "update": err = plugin.Update(ctx) + case "upgrade": + err = plugin.Upgrade(ctx, plugin.Name(in.Spec)) case "off": err = plugin.SetOff(in.Spec, in.Off) default: diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 36a3a97b2..49b34d2ac 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -27,10 +27,19 @@ and a pending or accepted submission cannot be submitted twice. `plugin-signin.test.cjs` checks a provider an OpenCode plugin signs in to: the add sheet lists it under "From plugins"; its sign-in asks the way, the method's questions (a pick, then a text the plugin checks), then takes the -code the browser page shows; an API-key way opens the account. Settings → -Plugins lists the plugins, why one didn't load, and adds one. English and +code the browser page shows; an API-key way opens the account. English and Chinese, Chromium and WebKit, with the API faked. +`plugin-market.test.cjs` checks the Plugins tab: Discover lists the +suggested plugins in their two sections, a card installs its plugin and +then offers its sign-in, which opens in the Providers add sheet; a search +filters the list at once and adds what npm has; a card opens the plugin's +page with its README (no pictures, links opened outside); Installed shows +why one didn't load, updates one and removes one. The providers list's +"More subscriptions in Plugins" button and the add sheet's row and "look +for a plugin" link lead there. English and Chinese, Chromium and WebKit, +with the API faked. + `panel-fold.test.cjs` expands and collapses on the Agents page with the list scrolled to its end, in the tray panel (one agent open) and in the window: "Show {n} more" unrolls the rest under the button, the view going down with @@ -304,7 +313,7 @@ works as follows, in English and Chinese: With Node.js and Playwright available: ```sh -node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs +node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs ``` If Playwright is installed outside the repository, set `NODE_PATH` to the diff --git a/internal/gui/tests/plugin-market.test.cjs b/internal/gui/tests/plugin-market.test.cjs new file mode 100644 index 000000000..c089416a0 --- /dev/null +++ b/internal/gui/tests/plugin-market.test.cjs @@ -0,0 +1,210 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Plugins tab: Discover lists the plugins magpie suggests in two +// sections; a card installs its plugin, then offers its sign-in, which +// opens in the Providers add sheet. A search filters at once and adds what +// npm has. A card opens the plugin's page with its README — no pictures, +// links opened outside. Installed shows why one didn't load, updates one +// and removes one. The providers list's button and the add sheet lead +// here. English and Chinese; 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 listings = [ + { package: "@magpie-community/opencode-zed-auth", name: "Zed", icon: "zed", providers: ["zed"], community: true, replaces: "zed", + summary: { en: "Claude, GPT, Gemini and Grok hosted by Zed, on your Zed plan.", zh: "用 Zed 订阅使用 Zed 托管的 Claude、GPT、Gemini 和 Grok。" }, + npm: { version: "0.1.0", weekly: 120, license: "MIT", repository: "https://github.com/magpie-community/plugins" } }, + { package: "@magpie-community/opencode-qoder-auth", name: "Qoder", icon: "qoder", providers: ["qoder"], community: true, + summary: { en: "Your Qoder subscription.", zh: "Qoder 订阅。" }, npm: { weekly: 0 } }, + { package: "opencode-copilot-auth", name: "GitHub Copilot", icon: "githubcopilot", providers: ["github-copilot"], + summary: { en: "Your GitHub Copilot plan.", zh: "你的 GitHub Copilot 套餐。" }, + npm: { version: "0.0.9", weekly: 48213, publisher: "thdxr", license: "MIT", repository: "https://github.com/sst/opencode-copilot-auth" } }, + { package: "opencode-gemini-auth", name: "Gemini", icon: "gemini-color", providers: ["google"], + summary: { en: "Gemini with a Google account.", zh: "用 Google 账号使用 Gemini。" }, + npm: { version: "1.4.0", weekly: 9100, publisher: "jenslys" } }, +]; + +const README = [ + "# opencode-copilot-auth", + "![badge](https://img.shields.io/npm/v/x.svg) Copilot for **OpenCode**.", + "", + "## Install", + "```sh", + "opencode auth login", + "```", + "- one `item`", + "- see [the docs](https://example.test/docs)", + " ", +].join("\n"); + +function server(lang, asked) { + const installed = [{ spec: "opencode-broken", error: "Cannot find module 'x'", providers: [], version: "1.0.0" }]; + const subs = []; + const market = () => ({ listings, state: { bun: true, bunVersion: "1.3.0", plugins: installed } }); + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + const body = () => route.request().postDataJSON(); + 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: [{ id: "openai", name: "OpenAI", icon: "openai", preset: "openai", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }], + presets: [], excluded: [], gateway: { running: true, window: true }, plugins: subs }); + } + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/gateway/trace") return json({ routes: [] }); + if (url.pathname === "/api/plugins/market") return json(market()); + if (url.pathname === "/api/plugins/search") { + asked.push(["search", url.searchParams.get("q")]); + return json({ hits: [ + { package: "opencode-copilot-auth", version: "0.0.9" }, + { package: "opencode-copilot-proxy-auth", version: "2.1.0", description: "Copilot through a proxy", publisher: "someone" }, + ] }); + } + if (url.pathname === "/api/plugins/page") { asked.push(["page", url.searchParams.get("name")]); return json({ readme: README, updated: "2026-09-01T00:00:00Z" }); } + if (url.pathname === "/api/plugins/add") { + const b = body(); + asked.push(["add", b]); + await new Promise((r) => setTimeout(r, 150)); + installed.push({ spec: b.spec, providers: ["GitHub Copilot"], version: "0.0.7", latest: "0.0.9" }); + subs.push({ id: "github-copilot-plugin", pid: "github-copilot", name: "GitHub Copilot", icon: "githubcopilot", spec: b.spec, signedIn: false, models: 34, + methods: [{ type: "oauth", label: "Login with GitHub" }] }); + return json({}); + } + if (url.pathname === "/api/plugins/upgrade") { asked.push(["upgrade", body()]); installed.find((e) => e.spec === body().spec).version = "0.0.9"; return json({}); } + if (url.pathname === "/api/plugins/remove") { asked.push(["remove", body()]); installed.splice(installed.findIndex((e) => e.spec === body().spec), 1); return json({}); } + if (url.pathname === "/api/open") { asked.push(["open", body()]); return route.fulfill({ status: 204 }); } + if (url.pathname === "/api/plugin-signin") { asked.push(["signin", body()]); return json({ id: "p1", agent: "github-copilot-plugin", state: "waiting", url: "https://github.test/login/device" }); } + if (url.pathname === "/api/signin/p1") return json({ id: "p1", agent: "github-copilot-plugin", state: "waiting", url: "https://github.test/login/device" }); + if (url.pathname.startsWith("/api/")) return json({}); + if (!/^\/[\w./-]*$/.test(url.pathname) || url.host !== "magpie.test") { asked.push(["fetched", 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 L = { + en: { tab: "Plugins", ours: "magpie community", theirs: "From OpenCode's community", install: "Install", soon: "Coming soon", signIn: "Sign in", onNpm: "On npm", + installed: "Installed", failed: /Didn't load: Cannot find module/, update: "Update", remove: "Remove", more: "More subscriptions", moreTile: "More in Plugins", + lookFor: "look for a plugin", week: "48k/week", readme: "Install", signing: "GitHub Copilot" }, + zh: { tab: "插件", ours: "magpie 社区", theirs: "来自 OpenCode 社区", install: "安装", soon: "即将上线", signIn: "登录", onNpm: "npm 上的插件", + installed: "已安装", failed: /没有加载成功:Cannot find module/, update: "更新", remove: "移除", more: "更多订阅", moreTile: "插件中还有更多", + lookFor: "找找插件", week: "48k/周", readme: "Install", signing: "GitHub Copilot" }, +}; + +const shot = async (loc, name) => { + if (!process.env.ARTIFACT_DIR) return; + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await loc.screenshot({ path: path.join(process.env.ARTIFACT_DIR, name + ".png") }); +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Plugins tab", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh"]) { + await t.test(lang, async () => { + const w = L[lang]; + const page = await (await browser.newContext({ viewport: { width: 980, height: 820 } })).newPage(); + page.setDefaultTimeout(5000); + const errors = [], asked = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, asked)); + + // the providers list's button leads to the Plugins tab + await page.goto("http://magpie.test/?view=providers"); + const more = page.locator("#moreSubs"); + await more.waitFor(); + assert.match(await more.innerText(), new RegExp(w.more)); + assert.equal(await more.locator(".stack .ic").count(), 3); + await shot(page.locator("#view-providers .after-list"), `plugins-button-${engine}-${lang}`); + await more.click(); + const view = page.locator("#view-plugins"); + await view.waitFor({ state: "visible" }); + assert.equal(await page.locator('#nav button[data-view="plugins"]').getAttribute("class"), "on"); + assert.match(page.url(), /view=plugins/); + + // Discover: two sections, sorted by downloads in the second + await view.locator(".pm-sechead h3", { hasText: w.ours }).waitFor(); + await view.locator(".pm-sechead h3", { hasText: w.theirs }).waitFor(); + const theirs = view.locator(".pm-sec").nth(1).locator(".pm-card .pm-name b"); + assert.deepEqual(await theirs.allInnerTexts(), ["GitHub Copilot", "Gemini"]); + const copilot = view.locator('.pm-card[data-pkg="opencode-copilot-auth"]'); + await copilot.locator(".pm-dl", { hasText: w.week }).waitFor(); + assert.equal((await copilot.locator(".pm-by").innerText()).trim(), "thdxr"); + assert.equal(await view.locator('.pm-card[data-pkg="@magpie-community/opencode-qoder-auth"] .pm-act').innerText(), w.soon); + assert.ok(await view.locator('.pm-card[data-pkg="@magpie-community/opencode-qoder-auth"] .pm-act').isDisabled()); + await shot(view, `plugins-discover-${engine}-${lang}`); + + // a card's page: facts, links opened outside, the README without pictures + await copilot.locator(".pm-sum").click(); + const dlg = page.locator("#modal .pm-detail"); + await dlg.locator(".pm-md h4", { hasText: w.readme }).waitFor(); + assert.equal(await dlg.locator(".pm-md img, .pm-md script").count(), 0); + assert.equal(await page.evaluate(() => window.pwned), undefined); + assert.doesNotMatch(await dlg.locator(".pm-md").innerText(), /pwned/); + assert.equal(await dlg.locator(".pm-md pre code").innerText(), "opencode auth login"); + await shot(page.locator("#modal .dialog"), `plugins-page-${engine}-${lang}`); + await dlg.locator(".pm-md a", { hasText: "the docs" }).click(); + assert.deepEqual(asked.find(([k]) => k === "open")[1], { url: "https://example.test/docs" }); + + // install from the page: the button becomes Sign in, which opens the add sheet's sign-in + await dlg.locator(".pm-act", { hasText: w.install }).click(); + await dlg.locator(".pm-act.go", { hasText: w.signIn }).waitFor(); + assert.deepEqual(asked.find(([k]) => k === "add")[1], { spec: "opencode-copilot-auth" }); + await dlg.locator(".pm-act.go").click(); + await page.locator("#view-providers").waitFor({ state: "visible" }); + await page.waitForFunction(() => document.querySelector("#modal").hidden); + await page.locator("#addSheet .signing").waitFor(); + assert.match(await page.locator("#addSheet .signing").innerText(), new RegExp(w.signing)); + + // the add sheet's row to Plugins, and its way when a search finds nothing + const tile = page.locator("#addSheet .tile.more-plugins"); + await page.locator("#addSheet .signing button.text:not(.primary)").last().click().catch(() => {}); + await tile.waitFor(); + assert.equal((await tile.innerText()).trim(), w.moreTile); + await page.locator("#addSheet input.find").fill("fakeco"); + await page.locator("#addSheet .none button", { hasText: w.lookFor }).click(); + await view.waitFor({ state: "visible" }); + assert.equal(await view.locator(".pm-find input").inputValue(), "fakeco"); + + // a search: the list filtered at once, and what npm has + const q = view.locator(".pm-find input"); + await q.fill("copilot"); + await view.locator(".pm-sechead h3", { hasText: w.onNpm }).waitFor(); + await view.locator('.pm-card[data-pkg="opencode-copilot-proxy-auth"]').waitFor(); + assert.equal(await view.locator('.pm-card[data-pkg="opencode-copilot-auth"]').count(), 1, "a listed plugin isn't shown twice"); + assert.ok(asked.some(([k, v]) => k === "search" && v === "copilot")); + assert.equal(await q.evaluate((e) => e === document.activeElement), true, "typing keeps the field"); + await shot(view, `plugins-search-${engine}-${lang}`); + await q.fill(""); + + // Installed: why one didn't load, an update, a removal + await view.locator(".lib-tabs .opt", { hasText: w.installed }).click(); + const rows = view.locator(".pm-row"); + await rows.first().waitFor(); + assert.equal(await rows.count(), 2); + await view.locator(".pm-row .sub.bad", { hasText: w.failed }).waitFor(); + const cp = rows.filter({ hasText: "GitHub Copilot" }); + await cp.locator(".pm-chip.up").waitFor(); + await shot(view, `plugins-installed-${engine}-${lang}`); + const top = await view.evaluate((e) => e.scrollTop); + await cp.locator("button", { hasText: new RegExp("^" + w.update + "$") }).click(); + await cp.locator(".pm-chip.up").waitFor({ state: "detached" }); + assert.deepEqual(asked.find(([k]) => k === "upgrade")[1], { spec: "opencode-copilot-auth" }); + await rows.filter({ hasText: "opencode-broken" }).locator("button", { hasText: w.remove }).click(); + await page.waitForFunction(() => document.querySelectorAll("#view-plugins .pm-row").length === 1); + assert.equal(await view.evaluate((e) => e.scrollTop), top, "a click doesn't move the page"); + + assert.deepEqual(asked.filter(([k]) => k === "fetched"), [], "nothing fetched from elsewhere"); + assert.deepEqual(errors, []); + }); + } + }); +} diff --git a/internal/gui/tests/plugin-signin.test.cjs b/internal/gui/tests/plugin-signin.test.cjs index 4dabe6ecb..4089b7dfc 100644 --- a/internal/gui/tests/plugin-signin.test.cjs +++ b/internal/gui/tests/plugin-signin.test.cjs @@ -3,8 +3,8 @@ // "From plugins"; its sign-in asks the way to sign in, the method's // questions (a pick, then a text the plugin checks), then opens the // browser and takes the code its page shows; an "api" way takes a key and -// opens the account. Settings → Plugins lists the plugins, why one didn't -// load, and adds one. English and Chinese; the API is faked here. +// opens the account. (The Plugins tab is plugin-market.test.cjs.) English +// and Chinese; the API is faked here. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -50,11 +50,6 @@ function server(lang, asked) { } if (url.pathname === "/api/signin/p1/callback") { asked.push(["code", body()]); return route.fulfill({ status: 204 }); } if (url.pathname === "/api/signin/p1") return json({ id: "p1", agent: "fakeco", state: "waiting", url: "https://fake.test/auth", pasteCode: true, instructions: "Paste the code FakeCo shows." }); - if (url.pathname === "/api/plugins") return json({ bun: true, bunVersion: "1.3.0", plugins: [ - { spec: "opencode-fakeco-auth", providers: ["FakeCo"] }, - { spec: "opencode-broken", error: "Cannot find module 'x'", providers: [] }, - ] }); - if (url.pathname === "/api/plugins/add") { asked.push(["add", body()]); return json({ bun: true, plugins: [{ spec: "opencode-fakeco-auth", providers: ["FakeCo"] }, { spec: body().spec, providers: ["Other"] }] }); } if (url.pathname.startsWith("/api/")) return 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)]; @@ -63,10 +58,8 @@ function server(lang, asked) { } const L = { - en: { section: "From plugins", how: "How do you sign in to FakeCo?", next: "Next", code: "Code", finish: "Finish sign-in", key: "FakeCo API key", signIn: "Sign in", - plugins: "Plugins", failed: /Didn't load: Cannot find module/, signs: "Signs in to FakeCo", add: "Add" }, - zh: { section: "来自插件", how: "用哪种方式登录 FakeCo?", next: "下一步", code: "验证码", finish: "完成登录", key: "FakeCo API Key", signIn: "登录", - plugins: "插件", failed: /没有加载成功:Cannot find module/, signs: "可登录 FakeCo", add: "添加" }, + en: { section: "From plugins", how: "How do you sign in to FakeCo?", next: "Next", code: "Code", finish: "Finish sign-in", key: "FakeCo API key", signIn: "Sign in" }, + zh: { section: "来自插件", how: "用哪种方式登录 FakeCo?", next: "下一步", code: "验证码", finish: "完成登录", key: "FakeCo API Key", signIn: "登录" }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -126,19 +119,6 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.waitForFunction(() => editing === "fakeco"); assert.deepEqual(asked.filter(([k]) => k === "signin").pop()[1], { provider: "fakeco", method: 0, inputs: {}, key: "k1" }); - // Settings → Plugins - await page.goto("http://magpie.test/?view=settings"); - const list = page.locator("#pluginsList"); - await list.locator(".sub", { hasText: w.signs }).waitFor(); - await list.locator(".sub.bad", { hasText: w.failed }).waitFor(); - await list.getByRole("textbox").fill("opencode-other-auth"); - await list.locator("button", { hasText: new RegExp("^" + w.add + "$") }).click(); - await list.locator(".name", { hasText: "opencode-other-auth" }).waitFor(); - assert.deepEqual(asked.find(([k]) => k === "add")[1], { spec: "opencode-other-auth" }); - if (process.env.ARTIFACT_DIR) { - await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); - await list.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `plugins-${engine}-${lang}.png`) }); - } assert.deepEqual(errors, []); }); } diff --git a/internal/plugin/market.go b/internal/plugin/market.go new file mode 100644 index 000000000..f7a6775de --- /dev/null +++ b/internal/plugin/market.go @@ -0,0 +1,407 @@ +package plugin + +import ( + "context" + _ "embed" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +// The plugin market: the plugins magpie suggests, from the community +// repo's registry.json (a copy is built in, for when GitHub can't be +// reached), each with what npm says of it now; and npm's search for the +// rest. + +//go:embed market.json +var builtinMarket []byte + +// MarketURL is where the list is kept; MAGPIE_PLUGIN_MARKET moves it, and +// "off" keeps to the built-in copy. +const MarketURL = "https://raw.githubusercontent.com/magpie-community/plugins/main/registry.json" + +// Listing is a plugin the market suggests. +type Listing struct { + Package string `json:"package"` + Name string `json:"name"` + Icon string `json:"icon,omitempty"` + Providers []string `json:"providers,omitempty"` // OpenCode's ids of those it signs in to + Community bool `json:"community,omitempty"` // written by magpie's community + Replaces string `json:"replaces,omitempty"` // the built-in subscription it does the work of + Summary map[string]string `json:"summary,omitempty"` // by language: en, zh +} + +type registry struct { + Plugins []Listing `json:"plugins"` +} + +// NPM is what npm says of a package now. +type NPM struct { + Version string `json:"version,omitempty"` // latest; none when npm has no such package + Description string `json:"description,omitempty"` + Publisher string `json:"publisher,omitempty"` + License string `json:"license,omitempty"` + Homepage string `json:"homepage,omitempty"` + Repository string `json:"repository,omitempty"` + Weekly int `json:"weekly"` // downloads last week +} + +var ( + marketMu sync.Mutex + marketList []Listing + marketAt time.Time + npmMu sync.Mutex + npmCache = map[string]npmEntry{} +) + +type npmEntry struct { + info NPM + ok bool + at time.Time +} + +func marketCache() string { + if x := os.Getenv("XDG_CACHE_HOME"); x != "" { + return filepath.Join(x, "magpie", "plugin-market.json") + } + home, _ := os.UserHomeDir() + return filepath.Join(home, ".cache", "magpie", "plugin-market.json") +} + +func parseMarket(b []byte) ([]Listing, error) { + var r registry + if err := json.Unmarshal(b, &r); err != nil { + return nil, err + } + out := r.Plugins[:0] + for _, l := range r.Plugins { + if l.Package != "" && pkgName.MatchString(l.Package) { + if l.Name == "" { + l.Name = l.Package + } + out = append(out, l) + } + } + if len(out) == 0 { + return nil, errors.New("the list has no plugins") + } + return out, nil +} + +// Market is the list of plugins magpie suggests: fetched at most every six +// hours, else the copy fetched last, else the one built in. +func Market(ctx context.Context) []Listing { + marketMu.Lock() + defer marketMu.Unlock() + if marketList != nil && time.Since(marketAt) < 6*time.Hour { + return marketList + } + src := os.Getenv("MAGPIE_PLUGIN_MARKET") + if src == "" { + src = MarketURL + } + if src != "off" { + c, cancel := context.WithTimeout(ctx, 6*time.Second) + b, err := fetchJSON(c, src, 1<<20) + cancel() + if err == nil { + if l, err := parseMarket(b); err == nil { + marketList, marketAt = l, time.Now() + _ = os.MkdirAll(filepath.Dir(marketCache()), 0o755) + _ = os.WriteFile(marketCache(), b, 0o644) + return l + } + } + if b, err := os.ReadFile(marketCache()); err == nil { + if l, err := parseMarket(b); err == nil { + // tried again in a minute, not six hours + marketList, marketAt = l, time.Now().Add(-6*time.Hour+time.Minute) + return l + } + } + } + l, _ := parseMarket(builtinMarket) + marketList, marketAt = l, time.Now().Add(-6*time.Hour+time.Minute) + return l +} + +func fetchJSON(ctx context.Context, u string, limit int64) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, "GET", u, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", "magpie") + req.Header.Set("Accept", "application/json") + res, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode == http.StatusNotFound { + return nil, errNotFound + } + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("%s: %s", u, res.Status) + } + return io.ReadAll(io.LimitReader(res.Body, limit)) +} + +var errNotFound = errors.New("not found") + +// npmPath is a package's name as the registry's paths take it. +func npmPath(name string) string { return strings.Replace(url.PathEscape(name), "%40", "@", 1) } + +// Info is what npm says of each package, asked at most hourly and all at +// once; a package npm doesn't have has no Version. +func Info(ctx context.Context, names []string) map[string]NPM { + out := map[string]NPM{} + var wg sync.WaitGroup + var mu sync.Mutex + for _, n := range names { + npmMu.Lock() + e, hit := npmCache[n] + npmMu.Unlock() + if hit && time.Since(e.at) < time.Hour { + out[n] = e.info + continue + } + wg.Add(1) + go func(n string) { + defer wg.Done() + info, ok := npmInfo(ctx, n) + mu.Lock() + out[n] = info + mu.Unlock() + if ok { + npmMu.Lock() + npmCache[n] = npmEntry{info, true, time.Now()} + npmMu.Unlock() + } else if hit { + mu.Lock() + out[n] = e.info // npm didn't answer: what it said last + mu.Unlock() + } + }(n) + } + wg.Wait() + return out +} + +type npmLatest struct { + Version string `json:"version"` + Description string `json:"description"` + License any `json:"license"` + Homepage string `json:"homepage"` + Repository any `json:"repository"` + Author any `json:"author"` + NPMUser struct { + Name string `json:"name"` + } `json:"_npmUser"` +} + +func person(v any) string { + switch x := v.(type) { + case string: + if i := strings.IndexAny(x, "<("); i > 0 { + return strings.TrimSpace(x[:i]) + } + return x + case map[string]any: + s, _ := x["name"].(string) + return s + } + return "" +} + +// repoURL is a package.json repository as a web address. +func repoURL(v any) string { + s, _ := v.(string) + if m, ok := v.(map[string]any); ok { + s, _ = m["url"].(string) + } + s = strings.TrimPrefix(s, "git+") + s = strings.TrimSuffix(s, ".git") + s = strings.Replace(s, "git://", "https://", 1) + s = strings.Replace(s, "ssh://git@", "https://", 1) + if strings.HasPrefix(s, "github:") { + s = "https://github.com/" + strings.TrimPrefix(s, "github:") + } else if !strings.Contains(s, "://") && strings.Count(s, "/") == 1 { + s = "https://github.com/" + s + } + if !strings.HasPrefix(s, "https://") { + return "" + } + return s +} + +func npmInfo(ctx context.Context, name string) (NPM, bool) { + ctx, cancel := context.WithTimeout(ctx, 8*time.Second) + defer cancel() + var info NPM + var wg sync.WaitGroup + var latestErr error + wg.Add(2) + go func() { + defer wg.Done() + b, err := fetchJSON(ctx, "https://registry.npmjs.org/"+npmPath(name)+"/latest", 1<<20) + if err != nil { + latestErr = err + return + } + var l npmLatest + if err := json.Unmarshal(b, &l); err != nil { + latestErr = err + return + } + info.Version, info.Description, info.Homepage = l.Version, l.Description, l.Homepage + info.License, _ = l.License.(string) + info.Repository = repoURL(l.Repository) + info.Publisher = person(l.Author) + if info.Publisher == "" { + info.Publisher = l.NPMUser.Name + } + }() + var weekly int + go func() { + defer wg.Done() + b, err := fetchJSON(ctx, "https://api.npmjs.org/downloads/point/last-week/"+npmPath(name), 64<<10) + if err != nil { + return + } + var d struct{ Downloads int } + if json.Unmarshal(b, &d) == nil { + weekly = d.Downloads + } + }() + wg.Wait() + info.Weekly = weekly + if latestErr != nil { + return NPM{}, errors.Is(latestErr, errNotFound) // not on npm: known, and kept + } + return info, true +} + +// Hit is a package npm's search found. +type Hit struct { + Package string `json:"package"` + NPM +} + +// Search asks npm for OpenCode plugins matching q. +func Search(ctx context.Context, q string) ([]Hit, error) { + q = strings.TrimSpace(q) + if q == "" { + return []Hit{}, nil + } + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + v := url.Values{"text": {q + " opencode"}, "size": {"30"}} + b, err := fetchJSON(ctx, "https://registry.npmjs.org/-/v1/search?"+v.Encode(), 4<<20) + if err != nil { + return nil, err + } + var r struct { + Objects []struct { + Package struct { + Name string `json:"name"` + Version string `json:"version"` + Description string `json:"description"` + Keywords []string `json:"keywords"` + License string `json:"license"` + Publisher struct { + Username string `json:"username"` + } `json:"publisher"` + Links struct { + Homepage string `json:"homepage"` + Repository string `json:"repository"` + } `json:"links"` + } `json:"package"` + Downloads struct { + Weekly int `json:"weekly"` + } `json:"downloads"` + } `json:"objects"` + } + if err := json.Unmarshal(b, &r); err != nil { + return nil, err + } + out := []Hit{} + for _, o := range r.Objects { + p := o.Package + // a plugin, not a tool that mentions OpenCode: its name says so, + // or its keywords name an OpenCode plugin + text := strings.ToLower(p.Name + " " + strings.Join(p.Keywords, " ")) + if !strings.Contains(text, "opencode") || !(strings.Contains(text, "auth") || strings.Contains(text, "plugin") || strings.Contains(text, "provider")) { + continue + } + out = append(out, Hit{Package: p.Name, NPM: NPM{ + Version: p.Version, Description: p.Description, Publisher: p.Publisher.Username, License: p.License, + Homepage: p.Links.Homepage, Repository: repoURL(p.Links.Repository), Weekly: o.Downloads.Weekly, + }}) + } + return out, nil +} + +// Page is a package's page: its README and when it last changed. +type Page struct { + Readme string `json:"readme"` + Updated time.Time `json:"updated"` +} + +// Readme is the package's README, as npm has it. +func Readme(ctx context.Context, name string) (Page, error) { + if !pkgName.MatchString(name) { + return Page{}, fmt.Errorf("%q isn't an npm package name", name) + } + ctx, cancel := context.WithTimeout(ctx, 12*time.Second) + defer cancel() + b, err := fetchJSON(ctx, "https://registry.npmjs.org/"+npmPath(name), 32<<20) + if err != nil { + return Page{}, err + } + var d struct { + Readme string `json:"readme"` + Time map[string]time.Time `json:"time"` + } + if err := json.Unmarshal(b, &d); err != nil { + return Page{}, err + } + const most = 200 << 10 + if len(d.Readme) > most { + d.Readme = d.Readme[:most] + } + return Page{Readme: d.Readme, Updated: d.Time["modified"]}, nil +} + +// Installed is the version of the plugin spec installed, "" for a path or +// one not installed. +func Installed(spec string) string { + if IsPath(spec) { + return "" + } + b, err := os.ReadFile(filepath.Join(Target(spec), "package.json")) + if err != nil { + return "" + } + var p struct{ Version string } + _ = json.Unmarshal(b, &p) + return p.Version +} + +// Upgrade installs the newest version of one plugin. +func Upgrade(ctx context.Context, name string) error { + for _, e := range Load().Plugins { + if Name(e.Spec) == name && !IsPath(e.Spec) { + _, err := Add(ctx, name) + return err + } + } + return fmt.Errorf("no plugin %q", name) +} diff --git a/internal/plugin/market.json b/internal/plugin/market.json new file mode 100644 index 000000000..427828b2b --- /dev/null +++ b/internal/plugin/market.json @@ -0,0 +1,46 @@ +{ + "version": 1, + "plugins": [ + { "package": "@magpie-community/opencode-zcode-auth", "name": "ZCode", "icon": "zcode", "providers": ["zcode"], "community": true, "replaces": "zcode", + "summary": { "en": "Z.ai and BigModel GLM Coding Plan, team seats and ZCode's free Start Plan.", "zh": "Z.ai 与智谱 GLM Coding Plan,支持团队席位和 ZCode 免费 Start Plan。" } }, + { "package": "@magpie-community/opencode-qoder-auth", "name": "Qoder", "icon": "qoder", "providers": ["qoder"], "community": true, "replaces": "qoder", + "summary": { "en": "Your Qoder subscription, with Qoder's own device sign-in.", "zh": "用 Qoder 自己的设备登录使用 Qoder 订阅。" } }, + { "package": "@magpie-community/opencode-devin-auth", "name": "Devin", "icon": "devin", "providers": ["devin"], "community": true, "replaces": "devin", + "summary": { "en": "Devin's models with your Devin account — a browser sign-in or the devin CLI's.", "zh": "用 Devin 账号使用 Devin 的模型:浏览器登录,或沿用 devin CLI 的登录。" } }, + { "package": "@magpie-community/opencode-zed-auth", "name": "Zed", "icon": "zed", "providers": ["zed"], "community": true, "replaces": "zed", + "summary": { "en": "Claude, GPT, Gemini and Grok hosted by Zed, on your Zed plan.", "zh": "用 Zed 订阅使用 Zed 托管的 Claude、GPT、Gemini 和 Grok。" } }, + { "package": "@magpie-community/opencode-factory-auth", "name": "Factory", "icon": "factory", "providers": ["factory"], "community": true, "replaces": "factory", + "summary": { "en": "Factory's Droid subscription: 30 models from Anthropic, OpenAI, xAI and open labs.", "zh": "Factory Droid 订阅:Anthropic、OpenAI、xAI 及开源模型共 30 个。" } }, + { "package": "@magpie-community/opencode-grok-auth", "name": "Grok", "icon": "xai", "providers": ["grok"], "community": true, "replaces": "grok", + "summary": { "en": "SuperGrok and X Premium+, through the Grok Build CLI's sign-in.", "zh": "通过 Grok Build CLI 的登录使用 SuperGrok 和 X Premium+。" } }, + { "package": "@magpie-community/opencode-commandcode-auth", "name": "Command Code", "icon": "commandcode", "providers": ["commandcode-plan"], "community": true, "replaces": "commandcode-plan", + "summary": { "en": "Command Code plans — Pro, GOAT, Max, Ultra, Go and Teams.", "zh": "Command Code 各档套餐:Pro、GOAT、Max、Ultra、Go 和 Teams。" } }, + { "package": "@magpie-community/opencode-mimo-auth", "name": "Xiaomi MiMo", "icon": "mimocode", "providers": ["mimo-app"], "community": true, "replaces": "mimo-app", + "summary": { "en": "Xiaomi MiMo models with your Xiaomi account.", "zh": "用小米账号使用小米 MiMo 模型。" } }, + { "package": "@magpie-community/opencode-cursor-auth", "name": "Cursor", "icon": "cursor", "providers": ["cursor"], "community": true, "replaces": "cursor", + "summary": { "en": "Cursor Pro, Pro+, Ultra and Teams — every model your plan has, with tool calls.", "zh": "Cursor Pro、Pro+、Ultra 与 Teams:套餐里的所有模型,支持工具调用。" } }, + { "package": "@magpie-community/opencode-kiro-auth", "name": "Kiro", "icon": "kiro-color", "providers": ["kiro"], "community": true, "replaces": "kiro", + "summary": { "en": "Kiro Free, Pro, Pro+ and Power — Kiro's sign-in, kiro-cli's, or an API key.", "zh": "Kiro Free、Pro、Pro+ 与 Power:Kiro 登录、沿用 kiro-cli 的登录,或 API key。" } }, + { "package": "@magpie-community/opencode-workbuddy-auth", "name": "WorkBuddy", "icon": "workbuddy-color", "providers": ["workbuddy", "workbuddy-ai"], "community": true, "replaces": "workbuddy", + "summary": { "en": "WorkBuddy's China build (CodeBuddy plan) and its international build.", "zh": "WorkBuddy 国内版(CodeBuddy 套餐)与国际版。" } }, + + { "package": "opencode-gemini-auth", "name": "Gemini", "icon": "gemini-color", "providers": ["google"], + "summary": { "en": "Gemini with a Google account — Code Assist and Google AI plans.", "zh": "用 Google 账号使用 Gemini:Code Assist 与 Google AI 套餐。" } }, + { "package": "opencode-antigravity-auth", "name": "Antigravity", "icon": "antigravity-color", "providers": ["google"], + "summary": { "en": "Gemini and Claude through Google Antigravity's sign-in.", "zh": "通过 Google Antigravity 的登录使用 Gemini 和 Claude。" } }, + { "package": "opencode-copilot-auth", "name": "GitHub Copilot", "icon": "githubcopilot", "providers": ["github-copilot"], + "summary": { "en": "Your GitHub Copilot plan, signed in with GitHub's device code.", "zh": "用 GitHub 设备码登录,使用你的 GitHub Copilot 套餐。" } }, + { "package": "opencode-openai-codex-auth", "name": "ChatGPT (Codex)", "icon": "openai", "providers": ["openai"], + "summary": { "en": "ChatGPT Plus and Pro through the Codex backend.", "zh": "通过 Codex 后端使用 ChatGPT Plus / Pro。" } }, + { "package": "oc-codex-multi-auth", "name": "ChatGPT multi-account", "icon": "openai", "providers": ["openai"], + "summary": { "en": "ChatGPT Plus and Pro with several accounts taking turns.", "zh": "多个 ChatGPT Plus / Pro 账号轮换使用。" } }, + { "package": "@ex-machina/opencode-anthropic-auth", "name": "Claude Pro / Max", "icon": "claude-color", "providers": ["anthropic"], + "summary": { "en": "Claude Pro and Max with your Claude account.", "zh": "用 Claude 账号使用 Claude Pro / Max。" } }, + { "package": "@servoy/opencode-kiro-auth", "name": "Kiro", "icon": "kiro-color", "providers": ["kiro"], + "summary": { "en": "Claude models on your AWS Kiro plan.", "zh": "用 AWS Kiro 套餐使用 Claude 模型。" } }, + { "package": "@cognitionai/opencode-devin", "name": "Devin by Cognition", "icon": "devin", "providers": ["devin"], + "summary": { "en": "Cognition's own plugin: sign in with Devin and use Devin's AI gateway.", "zh": "Cognition 官方插件:登录 Devin,使用 Devin 的 AI 网关。" } }, + { "package": "opencode-qoder-bridge", "name": "Qoder (Agent SDK)", "icon": "qoder", "providers": ["qoder"], + "summary": { "en": "Qoder through the official Qoder Agent SDK.", "zh": "通过官方 Qoder Agent SDK 使用 Qoder。" } } + ] +} diff --git a/internal/plugin/market_test.go b/internal/plugin/market_test.go new file mode 100644 index 000000000..e31b8907f --- /dev/null +++ b/internal/plugin/market_test.go @@ -0,0 +1,74 @@ +package plugin + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +// The list built in is what a magpie that can't reach the market shows: +// every entry a real package name, said in English and Chinese, once. +func TestBuiltinMarket(t *testing.T) { + l, err := parseMarket(builtinMarket) + if err != nil { + t.Fatal(err) + } + seen := map[string]bool{} + for _, x := range l { + if seen[x.Package] { + t.Errorf("%s listed twice", x.Package) + } + seen[x.Package] = true + if x.Summary["en"] == "" || x.Summary["zh"] == "" { + t.Errorf("%s: summary needs en and zh", x.Package) + } + if len(x.Providers) == 0 || x.Icon == "" { + t.Errorf("%s: needs providers and an icon", x.Package) + } + } + if len(l) < 10 { + t.Errorf("%d listed", len(l)) + } +} + +// The market is fetched; one that fails is the copy fetched last, and +// with none, the one built in. "off" never asks. +func TestMarketSources(t *testing.T) { + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + reset := func() { marketMu.Lock(); marketList = nil; marketMu.Unlock() } + up := true + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !up { + http.Error(w, "down", 500) + return + } + w.Write([]byte(`{"version":1,"plugins":[{"package":"opencode-x-auth","name":"X"},{"package":"not a name"}]}`)) + })) + defer srv.Close() + t.Setenv("MAGPIE_PLUGIN_MARKET", srv.URL) + ctx := context.Background() + + reset() + if l := Market(ctx); len(l) != 1 || l[0].Name != "X" { + t.Fatalf("fetched: %+v", l) + } + up = false + reset() + if l := Market(ctx); len(l) != 1 || l[0].Package != "opencode-x-auth" { + t.Fatalf("down, the copy kept: %+v", l) + } + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + reset() + builtin, _ := parseMarket(builtinMarket) + if l := Market(ctx); len(l) != len(builtin) { + t.Fatalf("down, nothing kept: %d, want the %d built in", len(l), len(builtin)) + } + up = true + t.Setenv("MAGPIE_PLUGIN_MARKET", "off") + reset() + if l := Market(ctx); len(l) != len(builtin) { + t.Fatalf("off: %d", len(l)) + } + reset() +}