diff --git a/internal/agent/plugged.go b/internal/agent/plugged.go index 0a9284038..b1a89399f 100644 --- a/internal/agent/plugged.go +++ b/internal/agent/plugged.go @@ -476,7 +476,7 @@ func pluggedIcon(p *agentplug.Agent) string { if ic := provider.PluginOwnIcon(p.Desc.Icon); ic != "" { return ic } - if ic := plugin.Icon(p.Spec, p.Desc.ID); ic != "" { + if ic := provider.MarketIcon(plugin.Icon(p.Spec, p.Desc.ID)); ic != "" { return ic } // magpie's glyph for one it has no picture of, not an empty square diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 193774dae..6127e997e 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -285,11 +285,10 @@ function keepIcons(...roots) { keptIcons.get(e.dataset.icon).push(e); } } -// A mono logo is a CSS mask, and a mask is not an : a row drawn again -// makes its span afresh, and nothing but the spans on the page keeps the -// picture, so between the old row going and the new one painting the -// engine may let it go and paint the new one empty until it has loaded it -// again: the logo blinks, where an beside it doesn't (#1847). Every +// A mono logo is a CSS mask, not an : a row drawn again makes its +// span afresh, and only the spans on the page keep the picture, so the +// engine may let it go between rows and paint the new one empty until it +// is loaded again: the logo blinks, an beside it doesn't (#1847). Every // mask picture that has loaded is kept by a span of its own on a hidden // shelf for as long as the page is open, so a logo drawn again paints at // once on any page. Each picture is tried once, not once per logo: a @@ -328,9 +327,9 @@ function maskSpan(src, failed) { } const pngIcons = new Set(["crush", "zcode", "alma", "hanako", "cindy", "lody", "typesafe", "atomcode", "snow", "mlx-serve", "mothx", "zoo-code"]); -// lazy: a picture in a long list (Plugins' rows) is asked for when it -// nears the screen. Each SVG an draws is a document of its own in -// the webview, ~0.6 MB, kept while the page is open (#909) +// lazy: a picture in a long list (Plugins' rows) is asked for near the +// screen. Each SVG an draws is a webview document, ~0.6 MB, kept +// while the page is open (#909) function icon(name, lazy) { const kept = keptIcons?.get(name || "")?.shift(); if (kept) { kept.removeAttribute("title"); return kept; } @@ -352,6 +351,8 @@ function icon(name, lazy) { e.append(img); return e; } + // a URL: the server keeps pictures (file:…), never the page + if (/[:/]/.test(name)) return icon("generic"); if (name) { if (name.endsWith("-color") || pngIcons.has(name)) { const img = el("img"); diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index 1087b1c62..4f6273c62 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -436,12 +436,8 @@ func pluginListings(ctx context.Context) []pluginListingJSON { } out = append(out, j) } - ns := make([]*plugin.NPM, len(out)) - for i := range out { - ns[i] = out[i].NPM - } // at once: a picture still being fetched shows on the next ask - npmIcons(ns, 0) + listingIcons(out, 0) return out } @@ -461,6 +457,34 @@ func pluginAgents(ctx context.Context) []string { return out } +// listingIcons puts each listing's pictures as the page can show them: +// the one registry.json gives (Kilo Code's https://github.com/Kilo-Org.png) +// and the one its package.json gives, both kept as a GitHub-tagged +// plugin's is, in one wait. A bundled icon's name is left as it is; a +// picture not kept by wait is left out, so the card shows npm's picture +// or its kind's glyph until the next ask. +func listingIcons(ls []pluginListingJSON, wait time.Duration) { + n := len(ls) + said := make([]string, 2*n) + for i, l := range ls { + if provider.MarketPicture(l.Icon) { + said[i] = l.Icon + } + if l.NPM != nil { + said[n+i] = l.NPM.Icon + } + } + got := provider.RepoIcons(said, wait) + for i := range ls { + if said[i] != "" { + ls[i].Icon = got[i] + } + if ls[i].NPM != nil { + ls[i].NPM.Icon = got[n+i] + } + } +} + // npmIcons puts the picture each package gives (magpie.icon) as the page // can show it, kept here as a GitHub-tagged plugin's is: a data URI or an // https URL isn't sent on to the page. One not kept by wait is left out. @@ -512,11 +536,7 @@ func pluginMarketState(ctx context.Context, w Windows) pluginMarketJSON { n := info[l.Package] m.Listings = append(m.Listings, pluginListingJSON{Listing: l, NPM: &n}) } - ns := make([]*plugin.NPM, len(m.Listings)) - for i := range m.Listings { - ns[i] = m.Listings[i].NPM - } - npmIcons(ns, 3*time.Second) + listingIcons(m.Listings, 3*time.Second) for i, e := range m.State.Plugins { if !plugin.IsGit(e.Spec) { m.State.Plugins[i].Latest = info[plugin.Name(e.Spec)].Version diff --git a/internal/gui/plugins_registry_icon_test.go b/internal/gui/plugins_registry_icon_test.go new file mode 100644 index 000000000..fdf201804 --- /dev/null +++ b/internal/gui/plugins_registry_icon_test.go @@ -0,0 +1,83 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/plugin" +) + +// registry.json can give a listing a picture as its icon (Kilo Code's +// https://github.com/Kilo-Org.png) where most give a bundled icon's name. +// The page drew icon() as the generic cube. Both of Discover's +// answers now give such a picture kept as a file, as a package's own +// magpie.icon is, and leave a bundled name as it is. A data:image URI +// stands in for the URL here, so nothing is fetched; the https fetch is +// provider.TestMarketIconURLKept's. +func TestRegistryIconPictureKept(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("MAGPIE_BUN", "") + t.Setenv("PATH", "") + const png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"version":1,"plugins":[ + {"package":"@magpie-community/agent-kilo","name":"Kilo Code","kind":"agent","community":true,"icon":"` + png + `"}, + {"package":"@magpie-community/opencode-copilot-auth","name":"GitHub Copilot","icon":"githubcopilot","community":true}, + {"package":"@magpie-community/tools-plain","name":"Plain","kind":"tools","icon":"javascript:alert(1)","community":true} + ]}`)) + })) + defer srv.Close() + t.Setenv("MAGPIE_PLUGIN_MARKET", srv.URL) + plugin.RefreshMarket() + t.Cleanup(plugin.RefreshMarket) + plugin.ReloadInfo() + t.Cleanup(plugin.ReloadInfo) + + icons := func(ls []pluginListingJSON) map[string]string { + out := map[string]string{} + for _, l := range ls { + out[l.Package] = l.Icon + } + return out + } + mux := http.NewServeMux() + pluginRoutes(mux, nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("GET", "/api/plugins/listings", nil)) + var ls struct{ Listings []pluginListingJSON } + if err := json.Unmarshal(rec.Body.Bytes(), &ls); err != nil { + t.Fatalf("%d %s: %v", rec.Code, rec.Body, err) + } + got := icons(ls.Listings) + if ic := got["@magpie-community/agent-kilo"]; !strings.HasPrefix(ic, "file:") { + t.Errorf("Kilo Code's picture = %.60q, want it kept as a file", ic) + } + if ic := got["@magpie-community/opencode-copilot-auth"]; ic != "githubcopilot" { + t.Errorf("a bundled name = %q", ic) + } + if ic := got["@magpie-community/tools-plain"]; ic != "" { + t.Errorf("a picture magpie doesn't take = %q", ic) + } + // the whole market at once (pluginMarketState), npm not asked here + var asked []pluginListingJSON + for _, l := range plugin.Market(t.Context()) { + asked = append(asked, pluginListingJSON{Listing: l}) + } + listingIcons(asked, 0) + if ic := icons(asked)["@magpie-community/agent-kilo"]; !strings.HasPrefix(ic, "file:") { + t.Errorf("market: Kilo Code's picture = %.60q", ic) + } + // what the market keeps is the registry's own word, not the page's + for _, l := range plugin.Market(t.Context()) { + if l.Package == "@magpie-community/agent-kilo" && l.Icon != png { + t.Errorf("the market's listing was changed to %.60q", l.Icon) + } + } +} diff --git a/internal/gui/tests/plugin-registry-icon.test.cjs b/internal/gui/tests/plugin-registry-icon.test.cjs new file mode 100644 index 000000000..1c845f7e8 --- /dev/null +++ b/internal/gui/tests/plugin-registry-icon.test.cjs @@ -0,0 +1,114 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// registry.json gives Kilo Code, Search1API and PowerContext an https +// picture as their icon where the rest give a bundled icon's name. The +// server fetches and keeps such a picture (provider.MarketIcon) and the +// listing says file:…; Discover's card and the plugin's page draw it. A +// URL that still reaches the page is never taken for a bundled file's +// name (icons/https://….svg) nor loaded from its host: the card wears +// the generic cube at once. A kept picture that fails to load wears the +// cube too, never a blank square. Every language, both engines, wide and +// narrow; the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const KILO = "@magpie-community/agent-kilo", S1 = "@magpie-community/tools-search1api"; +const PC = "@magpie-community/tools-powercontext", COPILOT = "@magpie-community/opencode-copilot-auth"; +const npm = { version: "0.1.0", weekly: 5, license: "MIT" }; +const listings = [ + { package: KILO, name: "Kilo Code", kind: "agent", community: true, icon: "file:kilo.png", summary: { en: "Kilo Code." }, npm }, + { package: S1, name: "Search1API", kind: "tools", community: true, icon: "https://s1.dev/icon.png", summary: { en: "Search." }, npm }, + { package: PC, name: "PowerContext", kind: "tools", community: true, icon: "file:gone.png", summary: { en: "Context." }, npm }, + { package: COPILOT, name: "GitHub Copilot", community: true, icon: "githubcopilot", providers: ["github-copilot"], summary: { en: "Copilot." }, npm }, +]; +const state = { bun: true, bunVersion: "1.4.2", plugins: [] }; +// a 1x1 picture +const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", "base64"); + +function server(lang, asked) { + return async (route) => { + const url = new URL(route.request().url()); + asked.push(url.href); + const json = (data) => route.fulfill({ json: data }); + if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/plugins") return json(state); + if (url.pathname === "/api/plugins/listings") return json({ listings }); + if (url.pathname === "/api/plugins/market") return json({ listings, state }); + if (url.pathname === "/api/icons/kilo.png") return route.fulfill({ contentType: "image/png", body: PNG }); + if (url.pathname.startsWith("/api/icons/")) return route.fulfill({ status: 404, body: "" }); + if (url.pathname.startsWith("/api/")) return json({}); + if (!/^\/[\w./-]*$/.test(url.pathname)) return route.fulfill({ status: 404, body: "" }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a registry icon that is a picture draws it, else the cube", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) for (const width of [980, 420]) { + await t.test(lang + " " + width, async () => { + const ctx = await browser.newContext({ viewport: { width, height: 820 } }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + const errors = [], asked = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, asked)); + await page.goto("http://magpie.test/?view=plugins"); + const card = (pkg) => page.locator(`#view-plugins .pm-card[data-pkg="${pkg}"] .pm-logo`); + // the list is drawn again as the market comes in: a card found a + // moment ago can be gone by the scroll, so the scroll looks again + const into = async (loc) => { + for (let i = 0; ; i++) { + try { return await loc.scrollIntoViewIfNeeded({ timeout: 1000 }); } + catch (e) { if (i > 8 || !/not attached|Timeout/.test(e.message)) throw e; } + } + }; + await card(KILO).waitFor(); + await into(card(KILO)); + // the kept picture, drawn + assert.equal(await card(KILO).locator("img").getAttribute("src"), "/api/icons/kilo.png"); + await page.waitForFunction((pkg) => document.querySelector(`#view-plugins .pm-card[data-pkg="${pkg}"] .pm-logo img`)?.naturalWidth > 0, KILO); + // a URL: the cube at once, nothing asked for it + await into(card(S1)); + assert.equal(await card(S1).locator(".ic.generic").count(), 1, "a URL wears the cube"); + // a kept picture that fails: the cube, not a blank square + await into(card(PC)); + await card(PC).locator(".ic.generic").waitFor(); + assert.equal(await card(PC).locator("img").count(), 0); + // a bundled name is still a bundled icon + assert.equal(await card(COPILOT).locator('.ic[data-icon="githubcopilot"]').count(), 1); + for (const pkg of [KILO, S1, PC]) { + const box = await card(pkg).boundingBox(); + assert.ok(box && box.width > 0 && box.x >= 0 && box.x + box.width <= width, `${pkg}'s logo fits: ${JSON.stringify(box)}`); + } + + // the plugin's page wears the same + await page.locator(`#view-plugins .pm-card[data-pkg="${S1}"] .pm-name`).first().click(); + const dlg = page.locator("#modal .pm-detail"); + await dlg.waitFor(); + assert.equal(await dlg.locator(".pm-dhead .pm-logo .ic.generic").count(), 1, "the page of a URL wears the cube"); + await page.goto("http://magpie.test/?view=plugins"); + await page.locator(`#view-plugins .pm-card[data-pkg="${KILO}"] .pm-name`).first().click(); + await dlg.waitFor(); + assert.equal(await dlg.locator(".pm-dhead .pm-logo img").getAttribute("src"), "/api/icons/kilo.png"); + + await page.waitForTimeout(0); + const wrong = asked.filter((u) => !u.startsWith("http://magpie.test/") || /\/icons\/.*(https?:|s1\.dev)/.test(decodeURIComponent(u))); + assert.deepEqual(wrong, [], "nothing asked of another host, nor a bundled file named by a URL"); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/provider/market_icon_test.go b/internal/provider/market_icon_test.go new file mode 100644 index 000000000..7d8588f84 --- /dev/null +++ b/internal/provider/market_icon_test.go @@ -0,0 +1,78 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" +) + +// registry.json gives Kilo Code, Search1API and PowerContext an https +// picture as their icon, not a bundled icon's name. A provider or agent +// the market gives such an icon shows it as a plugin's own picture is +// shown: fetched through FetchIcon's checks and kept, "" until it is in, +// and never the URL itself, which the page took for a bundled file's +// name and drew as the generic cube. A bundled name is given as it is, +// and a picture magpie doesn't take is refused. +func TestMarketIconURLKept(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"version":1,"plugins":[ + {"package":"@magpie-community/agent-kilo","name":"Kilo Code","kind":"agent","community":true,"icon":"https://kilo.example/kilo.png","providers":["kilo-p"]}, + {"package":"@magpie-community/opencode-copilot-auth","name":"GitHub Copilot","icon":"githubcopilot","providers":["github-copilot"],"community":true}, + {"package":"@magpie-community/opencode-plain-auth","name":"Plain","icon":"http://plain.example/x.png","providers":["plain"],"community":true} + ]}`)) + })) + defer srv.Close() + t.Setenv("MAGPIE_PLUGIN_MARKET", srv.URL) + plugin.RefreshMarket() + t.Cleanup(plugin.RefreshMarket) + plugin.Market(context.Background()) + + png := []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR") + var fetched atomic.Int32 + was := fetchPluginIcon + t.Cleanup(func() { fetchPluginIcon = was }) + fetchPluginIcon = func(_ context.Context, u string) (string, error) { + fetched.Add(1) + if u != "https://kilo.example/kilo.png" { + t.Errorf("fetched %q", u) + } + return StoreIcon(png) + } + + kilo := plugin.Provider{ID: "kilo-p", Spec: "@magpie-community/agent-kilo"} + got := PluginIcon(kilo) + if strings.Contains(got, "://") { + t.Fatalf("the market's https icon went to the page as %q", got) + } + for i := 0; i < 200 && !strings.HasPrefix(got, "file:"); i++ { + time.Sleep(20 * time.Millisecond) + got = PluginIcon(kilo) + } + if !strings.HasPrefix(got, "file:") || IconFile(strings.TrimPrefix(got, "file:")) == "" { + t.Fatalf("after the fetch = %q, want a kept picture", got) + } + if ic := MarketIcon(plugin.Icon(kilo.Spec, kilo.ID)); ic != got { + t.Errorf("MarketIcon = %q, PluginIcon = %q", ic, got) + } + if ic := PluginIcon(plugin.Provider{ID: "github-copilot", Spec: "@magpie-community/opencode-copilot-auth"}); ic != "githubcopilot" { + t.Errorf("a bundled name = %q", ic) + } + if ic := PluginIcon(plugin.Provider{ID: "plain", Spec: "@magpie-community/opencode-plain-auth"}); ic != "" { + t.Errorf("plain http = %q, want refused", ic) + } + if n := fetched.Load(); n != 1 { + t.Errorf("fetched %d times", n) + } +} diff --git a/internal/provider/plugin_icon.go b/internal/provider/plugin_icon.go index 1ebd837c3..2f8c4acce 100644 --- a/internal/provider/plugin_icon.go +++ b/internal/provider/plugin_icon.go @@ -21,9 +21,27 @@ func PluginIcon(pp plugin.Provider) string { if ic := pluginOwnIcon(pp.Icon); ic != "" { return ic } - return plugin.Icon(pp.Spec, pp.ID) + return MarketIcon(plugin.Icon(pp.Spec, pp.ID)) } +// MarketIcon is an icon the plugin market (registry.json) gives, as the +// page can show it. A bundled icon's name is given as it is. A picture +// (an https URL or a data:image URI) is checked, fetched and kept as a +// plugin's own picture is, and is "" until it is in: the page never +// loads a remote URL itself, and an icon("https://…") would look for a +// bundled file of that name. +func MarketIcon(said string) string { + if MarketPicture(said) { + return pluginOwnIcon(said) + } + return said +} + +// MarketPicture is whether a market icon is a picture to fetch or decode +// (anything with a scheme or a path in it) rather than a bundled icon's +// name. +func MarketPicture(said string) bool { return strings.ContainsAny(said, ":/") } + // PluginOwnIcon is the Icon value of a picture a plugin gave (a data:image // URI or an https URL), "" while there is none to show: an agent a // plugin adds shows it as a provider's does.