diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 17b1a1a61..5ef21dd9d 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -1838,7 +1838,8 @@ } if (l.replaces) main.append(el("p", "pm-note", t("magpie's own sign-in to this subscription is deprecated: this plugin takes its place, and accounts signed in there move to it."))); const readme = el("div", "pm-readme"); - const had = pages.get(l.package); + const pageKey = l.package + "\n" + (document.documentElement.lang || "en"); + const had = pages.get(pageKey); const day = (p) => { const at = l.github && !entryOf(l.package) ? l.github.pushed : p.updated; upd.textContent = at && !at.startsWith("0001") ? new Date(at).toLocaleDateString(intlLang(), { year: "numeric", month: "short", day: "numeric" }) : "—"; @@ -1882,8 +1883,8 @@ n.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 240, easing: "ease-out" }); }; try { - const p = await api("plugins/page?name=" + encodeURIComponent(l.package)); - keep(l.package, p); + const p = await api("plugins/page?name=" + encodeURIComponent(l.package) + "&lang=" + encodeURIComponent(document.documentElement.lang || "en")); + keep(pageKey, p); day(p); if (!had) fill(markdown(p.readme || t("No README"))); else if (p.readme !== had.readme) readme.replaceChildren(markdown(p.readme || t("No README"))); diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index 320246159..69f9e6cff 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -684,7 +684,7 @@ func pluginRoutes(mux *http.ServeMux, w Windows) { 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")) + p, err := plugin.ReadmeIn(r.Context(), r.URL.Query().Get("name"), r.URL.Query().Get("lang")) if err != nil { fail(rw, err) return diff --git a/internal/gui/tests/plugin-readme-lang.test.cjs b/internal/gui/tests/plugin-readme-lang.test.cjs new file mode 100644 index 000000000..5901c8278 --- /dev/null +++ b/internal/gui/tests/plugin-readme-lang.test.cjs @@ -0,0 +1,84 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// ahwulv on X: a plugin that ships a Chinese README still showed the English +// one on its details page with the UI in Chinese. The page asks for the UI's +// language (?lang=), and a README read in one language is not shown again +// in another. In Chromium and WebKit; 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, + 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-copilot-auth", name: "GitHub Copilot", icon: "githubcopilot", providers: ["github-copilot"], community: true, + summary: { en: "Your GitHub Copilot plan.", zh: "你的 GitHub Copilot 套餐。" }, + npm: { version: "0.0.9", weekly: 48213, license: "MIT", repository: "https://github.com/magpie-community/plugins" } }, +]; + +function server(lang, asked) { + const installed = []; + 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/plugins/market" || url.pathname === "/api/plugins" || url.pathname === "/api/plugins/listings") { const m = market(); return json(url.pathname === "/api/plugins" ? m.state : url.pathname === "/api/plugins/listings" ? { listings: m.listings } : m); } + if (url.pathname === "/api/plugins/page") { asked.push(url.searchParams.get("lang")); return json({ readme: url.searchParams.get("lang") === "zh-CN" ? "# 中文说明" : "# English readme", updated: "2026-09-01T00:00:00Z" }); } + if (url.pathname === "/api/plugins/add") { + const b = body(); + asked.push(["add", b]); + installed.push({ spec: b.spec, providers: ["GitHub Copilot"], version: "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/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") return route.fulfill({ status: 404, body: "" }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a plugin's page asks for the README in the UI's language", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const [lang, tag, want] of [["en", "en", "English readme"], ["zh", "zh-CN", "中文说明"]]) { + await t.test(lang, async () => { + const ctx = await browser.newContext({ viewport: { width: 980, height: 820 }, reducedMotion: "reduce" }); + t.after(() => ctx.close()); + const page = await ctx.newPage(); + page.setDefaultTimeout(15000); + page.setDefaultNavigationTimeout(60000); + 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 zed = page.locator('#view-plugins .pm-card[data-pkg="@magpie-community/opencode-zed-auth"]'); + await zed.locator(".pm-sum").click(); + await page.locator("#modal .pm-detail .pm-md").waitFor(); + assert.match(await page.locator("#modal .pm-detail .pm-readme").innerText(), new RegExp(want)); + assert.deepEqual(asked, [tag]); + assert.deepEqual(errors, []); + }); + } + }); +} diff --git a/internal/plugin/market.go b/internal/plugin/market.go index 1921c1824..ddb4ee2c8 100644 --- a/internal/plugin/market.go +++ b/internal/plugin/market.go @@ -663,17 +663,30 @@ type Page struct { // Readme is the package's README, as npm has it, or — for a plugin added // from a folder on this computer or a git repository — the one its folder // carries. -func Readme(ctx context.Context, name string) (Page, error) { +func Readme(ctx context.Context, name string) (Page, error) { return ReadmeIn(ctx, name, "") } + +// ReadmeIn is Readme in the reader's language (the UI's, "zh-CN", "ja"): +// the README a package carries named for it (README.zh-CN.md, README_zh.md +// and the like) in place of its README.md, from its folder where it is +// installed and from npm's or GitHub's copy where it isn't. Without one, +// or with lang "" or English, the README.md. +func ReadmeIn(ctx context.Context, name, lang string) (Page, error) { if IsGit(name) { // one not installed yet (a repository tagged magpie-plugin): its // README as GitHub has it if _, err := os.Stat(Target(name)); err != nil { if repo := githubRepo(name); repo != "" { + if r, ok := githubLangReadme(ctx, repo, lang); ok { + return Page{Readme: r}, nil + } return githubReadme(ctx, repo) } } } if IsPath(name) || IsGit(name) { + if p, ok := folderLangReadme(Target(name), lang); ok { + return p, nil + } return folderReadme(Target(name)) } if !pkgName.MatchString(name) { @@ -681,6 +694,9 @@ func Readme(ctx context.Context, name string) (Page, error) { } ctx, cancel := context.WithTimeout(ctx, 12*time.Second) defer cancel() + if p, ok := folderLangReadme(Target(name), lang); ok { + return p, nil // installed: its own file, as it was installed + } b, err := fetchNPM(ctx, name, "/"+npmPath(name), 32<<20) if err != nil { // one npm doesn't have (yet): the README the community repo's @@ -695,8 +711,9 @@ func Readme(ctx context.Context, name string) (Page, error) { return Page{}, err } var d struct { - Readme string `json:"readme"` - Time map[string]time.Time `json:"time"` + Readme string `json:"readme"` + Time map[string]time.Time `json:"time"` + DistTags map[string]string `json:"dist-tags"` } if err := json.Unmarshal(b, &d); err != nil { return Page{}, err @@ -705,6 +722,14 @@ func Readme(ctx context.Context, name string) (Page, error) { if len(d.Readme) > most { d.Readme = d.Readme[:most] } + // the registry's entry holds the README.md alone; one named for the + // reader's language is in the package's files, which only the public + // registry's copy is asked of jsDelivr for + if _, _, official := npmBase(name); official { + if r, ok := npmLangReadme(ctx, name, d.DistTags["latest"], lang); ok { + d.Readme = r + } + } return Page{Readme: d.Readme, Updated: d.Time["modified"]}, nil } diff --git a/internal/plugin/readme_lang.go b/internal/plugin/readme_lang.go new file mode 100644 index 000000000..dec88407e --- /dev/null +++ b/internal/plugin/readme_lang.go @@ -0,0 +1,190 @@ +package plugin + +import ( + "context" + "encoding/json" + "net/url" + "os" + "path/filepath" + "strings" +) + +// Where the files of a published npm package are listed and read, moved +// by tests. A package's registry entry carries only its README.md; a +// README in the reader's language travels in the package's files. +var ( + jsdelivrData = "https://data.jsdelivr.com/v1/packages/npm" + jsdelivrCDN = "https://cdn.jsdelivr.net/npm" +) + +// readmeTags are the language tags a README named for the reader's +// language may carry, best first: "zh-CN" reads README.zh-CN.md, +// README_zh_cn.md, README.zh.md, README-CN.md and the like. The plain +// README.md is the caller's fallback, not listed. Traditional Chinese +// takes a simplified README over English. +func readmeTags(lang string) []string { + l := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(lang), "_", "-")) + base, _, _ := strings.Cut(l, "-") + var tags []string + switch base { + case "", "en": + return nil + case "zh": + if strings.Contains(l, "hant") || strings.Contains(l, "tw") || strings.Contains(l, "hk") || strings.Contains(l, "mo") { + tags = []string{"zh-tw", "zh-hant", "zh-hk", "tw", "zh", "zh-cn", "zh-hans", "cn"} + } else { + tags = []string{"zh-cn", "zh-hans", "zh", "cn", "zh-sg"} + } + case "ja": + tags = []string{l, "ja", "jp"} + default: + tags = []string{l, base} + } + seen := map[string]bool{} + out := tags[:0] + for _, t := range tags { + if !seen[t] { + seen[t] = true + out = append(out, t) + } + } + return out +} + +// readmeTag is the language tag a file name carries, lower-case with "-" +// for "_" ("README_zh_CN.md" is "zh-cn"), and whether it is a README at +// all; the plain README.md has the tag "". +func readmeTag(name string) (string, bool) { + n := strings.ToLower(name) + if !strings.HasPrefix(n, "readme") { + return "", false + } + n = n[len("readme"):] + for _, ext := range []string{".markdown", ".md", ".txt"} { + if strings.HasSuffix(n, ext) { + n = strings.TrimSuffix(n, ext) + break + } + } + n = strings.TrimLeft(n, "._-") + n = strings.ReplaceAll(n, "_", "-") + if strings.ContainsAny(n, "./ ") { + return "", false + } + return n, true +} + +// pickReadme is the file of names that is the README in lang, "" when +// there is none (the caller reads the plain one). +func pickReadme(names []string, lang string) string { + for _, tag := range readmeTags(lang) { + for _, n := range names { + if t, ok := readmeTag(n); ok && t == tag { + return n + } + } + } + return "" +} + +// folderLangReadme is the README in lang a plugin's folder carries, if it +// has one. +func folderLangReadme(dir, lang string) (Page, bool) { + ents, err := os.ReadDir(dir) + if err != nil { + return Page{}, false + } + var names []string + for _, e := range ents { + if !e.IsDir() { + names = append(names, e.Name()) + } + } + n := pickReadme(names, lang) + if n == "" { + return Page{}, false + } + b, err := os.ReadFile(filepath.Join(dir, n)) + if err != nil { + return Page{}, false + } + const most = 200 << 10 + if len(b) > most { + b = b[:most] + } + p := Page{Readme: string(b)} + if fi, err := os.Stat(filepath.Join(dir, n)); err == nil { + p.Updated = fi.ModTime() + } + return p, true +} + +// npmLangReadme is the README in lang of a package version npm has, read +// from its files through jsDelivr; false when it has none or jsDelivr +// doesn't answer, and the caller keeps npm's own README. +func npmLangReadme(ctx context.Context, name, version, lang string) (string, bool) { + if len(readmeTags(lang)) == 0 || version == "" { + return "", false + } + b, err := fetchJSON(ctx, jsdelivrData+"/"+npmPath(name)+"@"+url.PathEscape(version)+"?structure=flat", 4<<20) + if err != nil { + return "", false + } + var l struct { + Files []struct { + Name string `json:"name"` + } `json:"files"` + } + if json.Unmarshal(b, &l) != nil { + return "", false + } + var names []string + for _, f := range l.Files { + if strings.Count(f.Name, "/") == 1 { // the package's root only + names = append(names, strings.TrimPrefix(f.Name, "/")) + } + } + n := pickReadme(names, lang) + if n == "" { + return "", false + } + b, err = fetchJSON(ctx, jsdelivrCDN+"/"+npmPath(name)+"@"+url.PathEscape(version)+"/"+url.PathEscape(n), 200<<10) + if err != nil || len(b) == 0 { + return "", false + } + return string(b), true +} + +// githubLangReadme is the README in lang at the root of a GitHub +// repository's default branch, as its contents are listed. +func githubLangReadme(ctx context.Context, repo, lang string) (string, bool) { + if len(readmeTags(lang)) == 0 { + return "", false + } + b, err := fetchJSON(ctx, githubAPI+"/repos/"+repo+"/contents", 2<<20) + if err != nil { + return "", false + } + var l []struct { + Name string `json:"name"` + Type string `json:"type"` + } + if json.Unmarshal(b, &l) != nil { + return "", false + } + var names []string + for _, f := range l { + if f.Type == "file" { + names = append(names, f.Name) + } + } + n := pickReadme(names, lang) + if n == "" { + return "", false + } + b, err = fetchJSON(ctx, githubRaw+"/"+repo+"/HEAD/"+url.PathEscape(n), 200<<10) + if err != nil || len(b) == 0 { + return "", false + } + return string(b), true +} diff --git a/internal/plugin/readme_lang_test.go b/internal/plugin/readme_lang_test.go new file mode 100644 index 000000000..5c7ea5418 --- /dev/null +++ b/internal/plugin/readme_lang_test.go @@ -0,0 +1,96 @@ +package plugin + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestPickReadmeByLanguage(t *testing.T) { + files := []string{"README.md", "README.zh-CN.md", "README_ja.md", "readme-de.md", "README.zh-TW.md", "index.js", "README.fr.md.bak"} + for lang, want := range map[string]string{ + "zh-CN": "README.zh-CN.md", "zh": "README.zh-CN.md", "zh_CN": "README.zh-CN.md", + "zh-TW": "README.zh-TW.md", "ja": "README_ja.md", "de": "readme-de.md", + "en": "", "": "", "fr": "", "ko": "", + } { + if got := pickReadme(files, lang); got != want { + t.Errorf("pickReadme(%q) = %q, want %q", lang, got, want) + } + } + // the conventions a plugin may spell it in + for _, n := range []string{"README.zh.md", "README_zh.md", "README-zh.md", "README_zh_CN.md", "README.zh-cn.md", "README.CN.md", "README.zh-Hans.md", "readme.zh.markdown"} { + if got := pickReadme([]string{"README.md", n}, "zh-CN"); got != n { + t.Errorf("%s not picked for zh-CN, got %q", n, got) + } + } + // traditional readers take a simplified README over English + if got := pickReadme([]string{"README.md", "README.zh.md"}, "zh-TW"); got != "README.zh.md" { + t.Errorf("zh-TW got %q", got) + } +} + +// A plugin that ships a README in the UI's language shows it, installed or +// not; one without shows README.md. +func TestReadmeInUILanguage(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/npm/pk-zh"): + _, _ = w.Write([]byte(`{"readme":"# English","dist-tags":{"latest":"1.2.3"}}`)) + case strings.HasPrefix(r.URL.Path, "/npm/pk-en"): + _, _ = w.Write([]byte(`{"readme":"# English only","dist-tags":{"latest":"1.0.0"}}`)) + case r.URL.Path == "/data/pk-zh@1.2.3": + _, _ = w.Write([]byte(`{"files":[{"name":"/README.md"},{"name":"/README.zh-CN.md"},{"name":"/docs/README.ja.md"}]}`)) + case r.URL.Path == "/data/pk-en@1.0.0": + _, _ = w.Write([]byte(`{"files":[{"name":"/README.md"}]}`)) + case r.URL.Path == "/cdn/pk-zh@1.2.3/README.zh-CN.md": + _, _ = w.Write([]byte("# 中文")) + case r.URL.Path == "/api/repos/o/r/contents": + _, _ = w.Write([]byte(`[{"name":"README.md","type":"file"},{"name":"README_zh.md","type":"file"}]`)) + case r.URL.Path == "/raw/o/r/HEAD/README_zh.md": + _, _ = w.Write([]byte("# 仓库中文")) + case r.URL.Path == "/raw/o/r/HEAD/README.md": + _, _ = w.Write([]byte("# repo English")) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + a, b, c, d, e := npmRegistry, jsdelivrData, jsdelivrCDN, githubAPI, githubRaw + npmRegistry, jsdelivrData, jsdelivrCDN, githubAPI, githubRaw = srv.URL+"/npm", srv.URL+"/data", srv.URL+"/cdn", srv.URL+"/api", srv.URL+"/raw" + defer func() { npmRegistry, jsdelivrData, jsdelivrCDN, githubAPI, githubRaw = a, b, c, d, e }() + ctx := context.Background() + + for _, c := range []struct{ name, lang, want string }{ + {"pk-zh", "zh-CN", "# 中文"}, + {"pk-zh", "en", "# English"}, + {"pk-zh", "", "# English"}, + {"pk-zh", "ja", "# English"}, // not in the package root + {"pk-en", "zh-CN", "# English only"}, + {"github:o/r", "zh-CN", "# 仓库中文"}, + {"github:o/r", "en", "# repo English"}, + } { + p, err := ReadmeIn(ctx, c.name, c.lang) + if err != nil || p.Readme != c.want { + t.Errorf("ReadmeIn(%q, %q) = %q, %v; want %q", c.name, c.lang, p.Readme, err, c.want) + } + } + + // installed: the folder's own file, no ask + dir := Target("pk-zh") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "README_zh.md"), []byte("# 本地"), 0o644); err != nil { + t.Fatal(err) + } + srv.Close() + if p, err := ReadmeIn(ctx, "pk-zh", "zh"); err != nil || p.Readme != "# 本地" { + t.Errorf("installed: %q, %v", p.Readme, err) + } +}