diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 47a406685..d029242ce 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -419,7 +419,7 @@ } else by.append(el("span", "", l.npm?.publisher || l.package)); who.append(by); if (l.github) c.classList.add("gh"); - top.append(logo(l.icon, false, kindOf(l)), who, actionFor(l.package, l.name, l)); + top.append(logo(l.icon || l.npm?.icon, false, kindOf(l)), who, actionFor(l.package, l.name, l)); const sum = el("p", "pm-sum", summary(l)); const meta = el("div", "pm-meta"); meta.append(kindChip(kindOf(l))); @@ -864,7 +864,7 @@ if (mw && !e.off && !ask) who.append(mwLine(mw)); if (ag && !e.off && !ask) who.append(agentLine(ag)); if (mw && !e.off && !ask && editing?.pkg === pkg) who.append(optionsEditor(e)); - r.append(logo(l?.icon || subs[0]?.icon || ag?.icon, false, e.middlewareOnly ? "mw" : e.inMagpieOnly && e.isAgent && !e.isMiddleware ? "ag" : ""), who); + r.append(logo(l?.icon || l?.npm?.icon || subs[0]?.icon || ag?.icon, false, e.middlewareOnly ? "mw" : e.inMagpieOnly && e.isAgent && !e.isMiddleware ? "ag" : ""), 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) { @@ -1064,7 +1064,7 @@ const local = isPath(l.package) || isGit(l.package); const ed = el("div", "editor pm-detail"); const hd = el("div", "ehead pm-dhead"); - hd.append(logo(l.icon, true, kindOf(l))); + hd.append(logo(l.icon || l.npm?.icon, true, kindOf(l))); const who = el("div", "pm-who"); const nm = el("div", "pm-name"); nm.append(el("b", "", l.name)); diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index 93c59bfa0..d9a119b21 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -242,9 +242,32 @@ 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) return out } +// 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. +func npmIcons(ns []*plugin.NPM, wait time.Duration) { + said := make([]string, len(ns)) + for i, n := range ns { + if n != nil { + said[i] = n.Icon + } + } + for i, ic := range provider.RepoIcons(said, wait) { + if ns[i] != nil { + ns[i].Icon = ic + } + } +} + // pluginMarketJSON is the plugin market: the plugins magpie suggests, what npm // says of each, and those added. type pluginMarketJSON struct { @@ -279,6 +302,11 @@ 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) for i, e := range m.State.Plugins { if !plugin.IsGit(e.Spec) { m.State.Plugins[i].Latest = info[plugin.Name(e.Spec)].Version @@ -319,7 +347,17 @@ func pluginRoutes(mux *http.ServeMux, w Windows) { names = append(names, n) } } - writeJSON(rw, map[string]any{"npm": plugin.Info(r.Context(), names)}) + info := plugin.Info(r.Context(), names) + keys := make([]string, 0, len(info)) + ns := make([]*plugin.NPM, 0, len(info)) + for k, n := range info { + keys, ns = append(keys, k), append(ns, &n) + } + npmIcons(ns, 3*time.Second) + for i, k := range keys { + info[k] = *ns[i] + } + writeJSON(rw, map[string]any{"npm": info}) }) // the whole market at once, npm's answers and all mux.HandleFunc("GET /api/plugins/market", func(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/gui/plugins_parts_test.go b/internal/gui/plugins_parts_test.go index 2420e486f..a335c3ed0 100644 --- a/internal/gui/plugins_parts_test.go +++ b/internal/gui/plugins_parts_test.go @@ -1,11 +1,13 @@ package gui import ( + "encoding/base64" "encoding/json" "net/http" "net/http/httptest" "os" "path/filepath" + "strings" "testing" "time" @@ -21,7 +23,16 @@ func TestPluginMarketInParts(t *testing.T) { t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("MAGPIE_PLUGIN_MARKET", "off") const pkg = "@magpie-community/opencode-zcode-auth" - kept := map[string]any{pkg: map[string]any{"info": map[string]any{"version": "0.4.0", "weekly": 321}, "at": time.Now().Add(-48 * time.Hour)}} + // a listing the market gives no icon (yetone: 这里的 agent plugin 为什么 + // 没有 logo): the picture its package gives (magpie.icon) is kept here, + // and the page gets it as a file, never the data URI + const agent = "@magpie-community/middleware-word-guard" + png := []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR") + data := "data:image/png;base64," + base64.StdEncoding.EncodeToString(png) + kept := map[string]any{ + pkg: map[string]any{"info": map[string]any{"version": "0.4.0", "weekly": 321}, "at": time.Now().Add(-48 * time.Hour)}, + agent: map[string]any{"info": map[string]any{"version": "0.1.1", "icon": data}, "at": time.Now()}, + } b, _ := json.Marshal(kept) if err := os.MkdirAll(filepath.Join(cache, "magpie"), 0o755); err != nil { t.Fatal(err) @@ -63,7 +74,9 @@ func TestPluginMarketInParts(t *testing.T) { switch { case l.Package == pkg && (l.NPM == nil || l.NPM.Version != "0.4.0" || l.NPM.Weekly != 321): t.Errorf("%s: %+v, want what npm said last", l.Package, l.NPM) - case l.Package != pkg && l.NPM != nil: + case l.Package == agent && (l.NPM == nil || !strings.HasPrefix(l.NPM.Icon, "file:")): + t.Errorf("%s: %+v, want its own picture kept as a file", l.Package, l.NPM) + case l.Package != pkg && l.Package != agent && l.NPM != nil: t.Errorf("%s: %+v before npm was asked", l.Package, l.NPM) } } diff --git a/internal/gui/tests/plugin-agent.test.cjs b/internal/gui/tests/plugin-agent.test.cjs index 2b9d08f8b..03e5cff64 100644 --- a/internal/gui/tests/plugin-agent.test.cjs +++ b/internal/gui/tests/plugin-agent.test.cjs @@ -3,7 +3,9 @@ // Agent chip, not Provider, and says which agent it adds to the Agents // page (or why it didn't load, in red); one switched off is an Agent still; // one that is middleware too wears both chips. Discover lists the market's -// agent plugins in their own section with the Agent chip. Every language, +// agent plugins in their own section with the Agent chip, wearing the +// picture its package gives (npm's magpie.icon, kept by magpie as a file) +// when the market gives it none. Every language, // both engines, at a narrow width too; the API is faked here. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); @@ -20,8 +22,10 @@ const state = { bun: true, bunVersion: "1.3.0", plugins: [ { spec: OFF, off: true, providers: [], moved: [], isAgent: true, inMagpieOnly: true }, { spec: BOTH, providers: [], moved: [], isAgent: true, inMagpieOnly: true, isMiddleware: true, agent: { id: "jot", name: "Jot" }, middleware: { hooks: ["onRequest"], calls: 0, avgMicros: 0, failures: 0 } }, ] }; +// a 1x1 picture +const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", "base64"); const listings = [ - { package: "@magpie-community/agent-aider", name: "Aider", kind: "agent", community: true, summary: { en: "Aider through magpie" }, npm: { version: "0.1.0" } }, + { package: "@magpie-community/agent-aider", name: "Aider", kind: "agent", community: true, summary: { en: "Aider through magpie" }, npm: { version: "0.1.0", icon: "file:aiderpic.png" } }, { package: "@magpie-community/middleware-block-patterns", name: "Block patterns", kind: "middleware", community: true, summary: { en: "Blocks patterns" }, npm: { version: "0.1.0" } }, ]; @@ -38,6 +42,7 @@ function server(lang) { 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/aiderpic.png") return route.fulfill({ contentType: "image/png", body: PNG }); 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)]; @@ -77,6 +82,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.ok((await card.innerText()).includes("Aider")); assert.deepEqual(await kinds(card), [w.agent]); assert.ok(await card.locator(".pm-chip.kind.ag").count()); + // yetone: 这里的 agent plugin 为什么没有 logo + assert.equal(await card.locator(".pm-logo img").getAttribute("src"), "/api/icons/aiderpic.png"); + assert.equal(await card.locator(".pm-logo svg").count(), 0); await view.locator(".lib-tabs .opt", { hasText: w.installed }).click(); const row = (name) => view.locator(".pm-row").filter({ has: page.locator(".name", { hasText: name }) }); diff --git a/internal/plugin/github.go b/internal/plugin/github.go index 8b71939f8..4d280f89b 100644 --- a/internal/plugin/github.go +++ b/internal/plugin/github.go @@ -222,9 +222,7 @@ func askTagged(ctx context.Context) ([]Tagged, error) { t.Package, t.Version = pj.Name, pj.Version // a picture, as host.js's iconOf takes one: magpie checks and // keeps it before the page shows it (the GUI's /api/plugins/github) - if ic := strings.TrimSpace(pj.Magpie.Icon); len(ic) <= 3<<19 && (strings.HasPrefix(strings.ToLower(ic), "https://") || strings.HasPrefix(strings.ToLower(ic), "data:image/")) { - t.Icon = ic - } + t.Icon = ownIcon(pj.Magpie.Icon) if pj.Main == "" && len(pj.Exports) == 0 { switch { case strings.TrimSpace(pj.Magpie.Middleware) != "": diff --git a/internal/plugin/market.go b/internal/plugin/market.go index df34cb24e..cad1b20cd 100644 --- a/internal/plugin/market.go +++ b/internal/plugin/market.go @@ -57,6 +57,24 @@ type NPM struct { Homepage string `json:"homepage,omitempty"` Repository string `json:"repository,omitempty"` Weekly int `json:"weekly"` // downloads last week + // Icon is the picture the package gives in package.json's + // magpie.icon, as npm has it: magpie checks and keeps it before the + // page shows it, as a GitHub-tagged plugin's (the GUI's listings) + Icon string `json:"icon,omitempty"` +} + +// ownIcon is a picture a package.json's magpie.icon gives, as host.js's +// iconOf takes one: an https URL or a data:image URI, not too big; "" +// for anything else. +func ownIcon(said string) string { + ic := strings.TrimSpace(said) + if len(ic) > 3<<19 { + return "" + } + if l := strings.ToLower(ic); strings.HasPrefix(l, "https://") || strings.HasPrefix(l, "data:image/") { + return ic + } + return "" } var ( @@ -328,6 +346,9 @@ type npmLatest struct { NPMUser struct { Name string `json:"name"` } `json:"_npmUser"` + Magpie struct { + Icon string `json:"icon"` + } `json:"magpie"` } func person(v any) string { @@ -396,6 +417,7 @@ func npmAsk(ctx context.Context, name string) (NPM, error) { info.License, _ = l.License.(string) info.Repository = repoURL(l.Repository) info.Publisher = person(l.Author) + info.Icon = ownIcon(l.Magpie.Icon) if info.Publisher == "" { info.Publisher = l.NPMUser.Name } diff --git a/internal/plugin/market_npm_test.go b/internal/plugin/market_npm_test.go index 41dc95040..556b7094b 100644 --- a/internal/plugin/market_npm_test.go +++ b/internal/plugin/market_npm_test.go @@ -137,3 +137,36 @@ func TestNPMInfoAtOnce(t *testing.T) { t.Fatalf("%d asked at once, want at most 3", most) } } + +// yetone: 这里的 agent plugin 为什么没有 logo. The picture a package gives +// in package.json's magpie.icon comes with what npm says of it, so a +// listing the market gives no icon shows it; anything but an https URL or +// a data:image URI is left out. +func TestNPMInfoGivesIcon(t *testing.T) { + icons := map[string]string{ + "agent-aider": "data:image/png;base64,iVBORw0KGgo=", + "agent-web": "https://aider.chat/icon.png", + "agent-plain": "http://aider.chat/icon.png", + "agent-js": "javascript:alert(1)", + "agent-none": "", + } + fakeNPM(t, func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/downloads/") { + w.Write([]byte(`{"downloads":1}`)) + return + } + name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/"), "/latest") + w.Write([]byte(`{"version":"0.1.1","magpie":{"agent":"./a.agent.js","icon":"` + icons[name] + `"}}`)) + }) + names := []string{} + for n := range icons { + names = append(names, n) + } + got := Info(context.Background(), names) + want := map[string]string{"agent-aider": icons["agent-aider"], "agent-web": icons["agent-web"]} + for _, n := range names { + if got[n].Version != "0.1.1" || got[n].Icon != want[n] { + t.Errorf("%s: %+v, want icon %q", n, got[n], want[n]) + } + } +} diff --git a/site/public/docs/ja/plugins.html b/site/public/docs/ja/plugins.html index 1e3ef7914..620a8eeb1 100644 --- a/site/public/docs/ja/plugins.html +++ b/site/public/docs/ja/plugins.html @@ -253,7 +253,7 @@ magpie quota # acme · Pro · 5h 37%

OpenCode は magpie オブジェクトを無視するので、OpenCode プラグインに追加しても安全です。

- +
フィールド意味
magpie.iconプロバイダの画像:https:// URL または data:image/… URI、最大 1 MB。SVG、PNG など。
magpie.iconプロバイダの画像。「発見」のプラグインのカードにも表示されます(npm から、GitHub のものはリポジトリから読み込み):https:// URL または data:image/… URI、最大 1 MB。SVG、PNG など。
magpie.maxConcurrency各アカウントが同時に受けるリクエスト数。1 から 1000 の整数。ユーザーがプロバイダに設定した上限が優先されます。

同じフィールドは auth フックにも設定でき(auth.icon、auth.maxConcurrency)、そちらが package.json より優先されます。

diff --git a/site/public/docs/plugins.html b/site/public/docs/plugins.html index 506f191cf..add091e6e 100644 --- a/site/public/docs/plugins.html +++ b/site/public/docs/plugins.html @@ -253,7 +253,7 @@ magpie quota # acme · Pro · 5h 37%

OpenCode ignores the magpie object, so these are safe to add to an OpenCode plugin.

- +
FieldMeaning
magpie.iconThe provider’s picture: an https:// URL or a data:image/… URI, at most 1 MB. SVG, PNG and the like.
magpie.iconThe provider’s picture, also on the plugin’s card in Discover (read from npm, or from the repository for one on GitHub): an https:// URL or a data:image/… URI, at most 1 MB. SVG, PNG and the like.
magpie.maxConcurrencyHow many requests each account takes at once, a whole number from 1 to 1000. A limit the user sets on the provider wins over it.

The same fields can be set on the auth hook (auth.icon, auth.maxConcurrency), where they win over package.json.

diff --git a/site/public/docs/zh/plugins.html b/site/public/docs/zh/plugins.html index be54a8858..fe3acbe29 100644 --- a/site/public/docs/zh/plugins.html +++ b/site/public/docs/zh/plugins.html @@ -253,7 +253,7 @@ magpie quota # acme · Pro · 5h 37%

OpenCode 会忽略 magpie 对象,所以给 OpenCode 插件加上它是安全的。

- +
字段含义
magpie.icon供应商的图标:https:// 地址或 data:image/… URI,最大 1 MB,SVG、PNG 等都行。
magpie.icon供应商的图标,也是这个插件在「发现」里卡片上的图标(从 npm 读取,GitHub 上的插件从仓库读取):https:// 地址或 data:image/… URI,最大 1 MB,SVG、PNG 等都行。
magpie.maxConcurrency每个账号同时接多少个请求,1 到 1000 的整数。用户在供应商上设置的上限优先。

同样的字段也可以写在 auth 钩子上(auth.icon、auth.maxConcurrency),优先于 package.json。