library: the skill market offers every skill skills.sh lists, 60 at a time

The owner: the Library's markets had too little in them ("这两个市场的
东西都太少了"). The skill market showed at most 60, four a repository.

Now it offers every skill on skills.sh's front page (its 600 most
installed), then each one on its trending page that isn't there, with no
count of installs: trending counts recent installs only, so the card
shows none rather than a wrong one. A repository's first skill comes
before anyone's second, so the first page still isn't one author's, and
nothing is cut. A search asks skills.sh for 200, not 40. The snapshot
magpie ships with has the same 772.

The page shows 60 cards and a "Show more (N left)" button that adds 60
under them; what was shown stays where it is, and skills' about is asked
for the cards shown only. MCP's list pages the same way. Strings in zh,
zh-TW, ja and de.

Run on mote at 0de6f2e57 (origin/main 1d8ded3ec plus this; pushed on 7c712847b, an agent row only): go test
./internal/library ok, gofmt clean, and the GUI files i18n-keys, market-*
and every-skill in both engines, 88/88. Main had changed internal/library
twice since the base below (399385307, 655d23f79).

At 073b3dfbb (origin/main c991733dc plus this):
- gofmt -l internal/library internal/gui: clean; go vet ./internal/library
- go test ./internal/library: ok
- go test -skip TestMainWindowCorners ./internal/gui: ok. That test is
  red on origin/main too (#3949).
- GUI: i18n-keys, market-*, every-skill in Chromium and WebKit: 88/88.
  i18n-keys was red at first, from a Go module cache an earlier run of
  mine had left in mote's copy of the tree; with it removed, 4/4.
- At 098f28929 (origin/main 5dfbca627 plus this), the wider set:
  i18n-keys, market-*, library-*, skeleton-bird, search-mcp-library,
  skill-install-agents-all, every-skill in both engines, 1128/1128.
  Between that base and this one, main changed only internal/library's
  MCP hub, browser and gateway code; none of it is in these pages.
- An earlier run of the same files at 647323409 plus this, with mote at
  load ~130, had 6 reds. All three files pass alone, both on main and on
  this change (110/110), and each has an issue: #4756
  (search-mcp-library), #4483 (library-mcp-hub) and #4125 (browser
  launch).

Broken by hand, red each time: the 4-per-repository cap back
(TestMarketSkillsAll), search limit 40, no trending page, and installs
shown for a trending skill (market-more.test.cjs). Removing the button
before the new cards are put in still passes, because the click scroll
keeper holds the reader's card. So nothing claims that order matters.

Not tried: the real skills.sh from the app. fetchPopular's parsing is the
one it had; the snapshot was made from the live pages today.
This commit is contained in:
yetone
2026-11-01 17:00:04 +08:00
parent 7c712847b7
commit df0320156b
7 changed files with 307 additions and 17 deletions
+27 -5
View File
@@ -5689,9 +5689,11 @@ magpie.plugin("library", (ctx) => {
// What the market offers: popular and featured ones until the reader
// searches. Kept across renders; asked for the first time a tab shows it.
const market = {
mcp: { q: "", items: null, error: "", loading: false, seq: 0, timer: 0, custom: null },
skills: { q: "", items: null, error: "", loading: false, seq: 0, timer: 0 },
mcp: { q: "", items: null, error: "", loading: false, seq: 0, timer: 0, custom: null, shown: 0 },
skills: { q: "", items: null, error: "", loading: false, seq: 0, timer: 0, shown: 0 },
};
// how many cards a list shows at first, and each Show more adds
const MARKET_PAGE = 60;
const asked = new Set(); // skills whose description has been asked for
async function fetchMarket(kind) {
@@ -5703,6 +5705,7 @@ magpie.plugin("library", (ctx) => {
const r = await api("library/market/" + (kind === "mcp" ? "servers" : "skills") + "?q=" + encodeURIComponent(m.q.trim()));
if (seq !== m.seq) return;
m.items = r.items || [];
m.shown = MARKET_PAGE;
m.error = r.error || "";
// the source that didn't answer when the rest did (#1589)
m.failed = r.failed ? { source: r.failed, cause: r.cause || "" } : null;
@@ -5815,7 +5818,25 @@ magpie.plugin("library", (ctx) => {
grid.append(el("div", "mk-msg", q ? t("Nothing matches “{q}”.", { q }) : t("Nothing to show.")));
return;
}
for (const x of m.items) grid.append(kind === "mcp" ? serverCard(x) : skillCard(x));
for (const x of m.items.slice(0, m.shown)) grid.append(kind === "mcp" ? serverCard(x) : skillCard(x));
moreCards(kind, grid);
}
// The rest of a long list, a page at a time: the cards added under the
// ones shown, which stay where they are.
function moreCards(kind, grid) {
const m = market[kind];
const left = m.items.length - m.shown;
if (left <= 0) return;
const more = button(t("Show more ({n} left)", { n: left.toLocaleString(intlLang()) }), "mk-more", () => {
const from = m.shown;
m.shown += MARKET_PAGE;
more.before(...m.items.slice(from, m.shown).map((x) => kind === "mcp" ? serverCard(x) : skillCard(x)));
more.remove();
moreCards(kind, grid);
if (kind === "skills") describeSkills();
});
grid.append(more);
}
// An address searched for that nothing listed is at: say so, over the
@@ -6053,7 +6074,8 @@ magpie.plugin("library", (ctx) => {
d.title = x.description || "";
const foot = el("div", "mk-foot");
// magpie's own skill has no count until skills.sh lists it
if (!x.featured || x.installs) {
// a trending skill's recent count isn't all its installs: none is told
if (x.installs) {
const n = el("span", "mk-installs");
n.append(svg(GLYPH.down, 11, 1.5), el("span", "", compact(x.installs)));
n.title = t("{n} installs", { n: x.installs.toLocaleString(intlLang()) });
@@ -6083,7 +6105,7 @@ magpie.plugin("library", (ctx) => {
who.append(el("div", "mk-name big", x.name));
const meta = el("div", "mk-meta");
meta.append(el("span", "mk-pub", x.source));
if (!x.featured || x.installs) meta.append(el("span", "mk-badge", t("{n} installs", { n: compact(x.installs) })));
if (x.installs) meta.append(el("span", "mk-badge", t("{n} installs", { n: compact(x.installs) })));
if (x.official) meta.append(el("span", "mk-badge", t("Official")));
who.append(meta);
head.append(logo(x.icon, x.source), who);
@@ -2,6 +2,7 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"Show more ({n} left)": "显示更多(还有 {n} 个)",
"This computer only": "只在这台电脑",
"Not through the router": "不经过路由",
"Each agent is given its own entry for it, as with the MCP router off": "每个 Agent 各自有它的条目,和关掉 MCP 路由时一样",
@@ -755,6 +756,7 @@ magpie.strings({
"{agents} can be changed once it runs.": "{agents} 要等它运行后才能修改。",
},
"zh-TW": {
"Show more ({n} left)": "顯示更多(還有 {n} 個)",
"This computer only": "只在這台電腦",
"Not through the router": "不經過路由",
"Each agent is given its own entry for it, as with the MCP router off": "每個 Agent 各自有它的條目,和關掉 MCP 路由時一樣",
@@ -1508,6 +1510,7 @@ magpie.strings({
"{agents} can be changed once it runs.": "{agents} 要等它執行後才能修改。",
},
ja: {
"Show more ({n} left)": "さらに表示(残り {n} 件)",
"This computer only": "このコンピュータだけ",
"Not through the router": "ルーターを通さない",
"Each agent is given its own entry for it, as with the MCP router off": "各エージェントに個別のエントリを渡します(MCP ルーターがオフのときと同じ)",
@@ -2261,6 +2264,7 @@ magpie.strings({
"{agents} can be changed once it runs.": "{agents} は起動後に変更できます。",
},
de: {
"Show more ({n} left)": "Mehr zeigen (noch {n})",
"This computer only": "Nur dieser Computer",
"Not through the router": "Nicht über den Router",
"Each agent is given its own entry for it, as with the MCP router off": "Jeder Agent bekommt einen eigenen Eintrag dafür, wie bei ausgeschaltetem MCP-Router",
@@ -555,6 +555,8 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col
.mk-add.busy { color: var(--muted); }
.mk-have { flex: none; display: inline-flex; align-items: center; gap: 4px; height: 26px; padding: 0 4px; font-size: 12px; color: var(--muted); }
.mk-card.have .mk-icon { opacity: .9; }
/* the rest of a long list, a page at a time, across the grid under it */
.mk-more { grid-column: 1 / -1; justify-self: center; margin-top: 4px; }
.mk-msg { grid-column: 1 / -1; padding: 22px 12px; text-align: center; font-size: 12px; color: var(--muted); }
.mk-msg.mk-custom { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 8px 12px; padding: 14px 12px; overflow-wrap: anywhere; }
.mk-msg.mk-partial { padding: 4px 2px 2px; text-align: left; line-height: 1.45; overflow-wrap: anywhere; }
+122
View File
@@ -0,0 +1,122 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The market's lists are long now (the owner: both markets had too little
// in them): every skill skills.sh lists and every server a search finds
// comes back, and the page shows 60 cards, then 60 more each Show more,
// added under the ones shown, which stay where they are. Skills' about is
// asked for the cards shown only, and a trending skill, sent with no count
// of installs, shows none. Every language, a narrow window, both engines.
// No backend: 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 HOME = "/Users/tester";
const skills = Array.from({ length: 150 }, (_, i) => ({
id: `o${i}/skills/s${i}`, name: `s${i}`, source: `o${i}/skills`, skillId: `s${i}`, installs: i < 140 ? 5000 - i : 0, icon: "",
}));
const servers = Array.from({ length: 130 }, (_, i) => ({
id: `io.github.o${i}/m${i}`, name: `m${i}`, title: `Server ${i}`, description: `Server number ${i}.`, transport: "stdio", runs: "npx", inputs: [],
}));
const more = { en: "Show more ({n} left)", zh: "显示更多(还有 {n} 个)", "zh-TW": "顯示更多(還有 {n} 個)", ja: "さらに表示(残り {n} 件)", de: "Mehr zeigen (noch {n})" };
function serve(lang, about) {
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
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/plugins") return json({ plugins: [] });
if (url.pathname === "/api/library") {
return json({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color", skills: `${HOME}/.claude/skills`, mcp: `${HOME}/.claude.json` }],
instructions: { agents: [], sets: [] }, servers: [], foundServers: [], projects: [], foundSkills: [], skills: [], problems: [],
});
}
if (url.pathname === "/api/library/market/servers") return json({ items: structuredClone(servers) });
if (url.pathname === "/api/library/market/skills") return json({ items: structuredClone(skills) });
if (url.pathname === "/api/library/market/about") {
const { ids } = route.request().postDataJSON();
about.push(ids);
return json(Object.fromEntries(ids.map((id) => [id, `About ${id}`])));
}
if (url.pathname === "/api/library/icon") return route.fulfill({ status: 404, body: "" });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });
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)];
const body = await fs.readFile(file).catch(() => null);
await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" }));
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const kind of ["skills", "mcp"]) {
test(`${engine} ${lang} ${kind}: a long market list shows 60 cards, and 60 more each Show more`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const context = await browser.newContext({ viewport: { width: 520, height: 760 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const about = [];
await page.route("**/*", serve(lang, about));
await page.addInitScript((tab) => { try { localStorage.setItem("magpie.libTab", tab); } catch {} }, kind);
t.after(() => browser.close());
await page.goto("http://magpie.test/?view=library");
const box = page.locator(`#view-library .mk[data-market="${kind}"]`);
const cards = box.locator(".mk-card");
const button = box.locator(".mk-more");
const total = kind === "skills" ? skills.length : servers.length;
const label = (n) => more[lang].replace("{n}", n.toLocaleString(lang));
await button.waitFor();
assert.equal(await cards.count(), 60);
assert.equal((await button.textContent()).trim(), label(total - 60));
// the button fits the narrow window
assert(await button.evaluate((b) => b.getBoundingClientRect().right <= document.documentElement.clientWidth));
if (kind === "skills") {
await page.waitForFunction(() => !document.querySelector(".mk-desc.wait"));
assert.deepEqual(about.flat().sort(), skills.slice(0, 60).map((x) => x.id).sort());
}
// a click adds cards under the ones shown and moves nothing (the
// button brought into view by the wheel, as a reader would)
await box.hover();
while (await button.evaluate((b) => b.getBoundingClientRect().bottom > innerHeight)) await page.mouse.wheel(0, 600);
// the wheel's last scroll told the page, a frame on
await page.evaluate(() => new Promise((ok) => requestAnimationFrame(() => requestAnimationFrame(ok))));
const first = cards.nth(59);
const at = await first.evaluate((e) => e.getBoundingClientRect().top);
await button.click();
await page.waitForFunction((k) => document.querySelectorAll(`.mk[data-market="${k}"] .mk-card`).length === 120, kind);
assert.equal(await first.evaluate((e) => e.getBoundingClientRect().top), at);
assert.equal(await cards.nth(60).getAttribute("data-id"), (kind === "skills" ? skills : servers)[60].id);
assert.equal((await button.textContent()).trim(), label(total - 120));
if (kind === "skills") {
await page.waitForFunction(() => !document.querySelector(".mk-desc.wait"));
assert.deepEqual(about.flat().sort(), skills.slice(0, 120).map((x) => x.id).sort());
assert.equal(await box.locator(`.mk-card[data-id="${skills[100].id}"] .mk-desc`).textContent(), `About ${skills[100].id}`);
}
// the last page: every card, and no button
await button.click();
await page.waitForFunction(([k, n]) => document.querySelectorAll(`.mk[data-market="${k}"] .mk-card`).length === n, [kind, total]);
assert.equal(await button.count(), 0);
if (kind === "skills") {
// a trending skill, sent with no count, shows none
assert.equal(await box.locator(`.mk-card[data-id="${skills[145].id}"] .mk-installs`).count(), 0);
assert.equal(await box.locator(`.mk-card[data-id="${skills[5].id}"] .mk-installs`).count(), 1);
}
assert.deepEqual(errors, []);
});
}
}
}
+47 -11
View File
@@ -891,8 +891,8 @@ func marketCache(name string) string {
}
// popularSkills are skills.sh's most installed, read off its front page,
// which lists them for itself; kept for six hours, and on disk for when
// it can't be reached, else what magpie shipped with.
// then the ones trending there that aren't among them; kept for six hours,
// and on disk for when it can't be reached, else what magpie shipped with.
func popularSkills() []skillsShEntry {
popular.Lock()
defer popular.Unlock()
@@ -916,8 +916,33 @@ func popularSkills() []skillsShEntry {
return list
}
// fetchPopular is skills.sh's front page's list, its 600 most installed,
// then its trending page's that aren't on it. A trending skill's count is
// of its recent installs, not all of them, so it isn't told.
func fetchPopular() ([]skillsShEntry, error) {
b, err := get(skillsShURL+"/", "text/html", 8<<20)
list, err := skillsShList("/")
if err != nil {
return nil, err
}
seen := map[string]bool{}
for _, e := range list {
seen[e.Source+"/"+e.SkillID] = true
}
if more, err := skillsShList("/trending"); err == nil {
for _, e := range more {
if !seen[e.Source+"/"+e.SkillID] {
seen[e.Source+"/"+e.SkillID] = true
e.Installs = 0
list = append(list, e)
}
}
}
return list, nil
}
// skillsShList is the list of skills a skills.sh page has in its data.
func skillsShList(path string) ([]skillsShEntry, error) {
b, err := get(skillsShURL+path, "text/html", 8<<20)
if err != nil {
return nil, err
}
@@ -939,7 +964,7 @@ func searchSkillsSh(q string) ([]skillsShEntry, error) {
var body struct {
Skills []skillsShEntry `json:"skills"`
}
if err := getJSON(skillsShURL+"/api/search?"+url.Values{"q": {q}, "limit": {"40"}}.Encode(), &body); err != nil {
if err := getJSON(skillsShURL+"/api/search?"+url.Values{"q": {q}, "limit": {"200"}}.Encode(), &body); err != nil {
return nil, &SearchError{Source: "skills.sh", Err: err}
}
return slices.DeleteFunc(body.Skills, func(e skillsShEntry) bool { return !repoRe.MatchString(e.Source) || e.SkillID == "" }), nil
@@ -958,10 +983,7 @@ func MarketSkills(q string) ([]MarketSkill, error) {
}
}
if q == "" {
// a few each from the repositories with the most, for the first page
// not to be one author's
per := map[string]int{}
list = slices.DeleteFunc(list, func(e skillsShEntry) bool { per[e.Source]++; return per[e.Source] > 4 })
list = byRepo(list)
}
if len(q) >= 2 {
var found []skillsShEntry
@@ -972,9 +994,6 @@ func MarketSkills(q string) ([]MarketSkill, error) {
}
}
}
if len(list) > 60 {
list = list[:60]
}
about := cachedAbout()
l, _ := loadLocked()
out := []MarketSkill{}
@@ -1011,6 +1030,23 @@ func MarketSkills(q string) ([]MarketSkill, error) {
return out, err
}
// byRepo is the most installed of each repository first, then each one's
// second, and so on, for the first page not to be one author's; all of
// them are there for the reader to go on to.
func byRepo(list []skillsShEntry) []skillsShEntry {
nth := map[string]int{}
rounds := [][]skillsShEntry{}
for _, e := range list {
n := nth[e.Source]
nth[e.Source]++
if n == len(rounds) {
rounds = append(rounds, nil)
}
rounds[n] = append(rounds[n], e)
}
return slices.Concat(rounds...)
}
func (l *Library) haveSkill(source, id, name string) string {
for _, s := range l.Skills {
if s.Source != nil && s.Source.Kind == "github" && strings.EqualFold(s.Source.Repo, source) &&
+104
View File
@@ -0,0 +1,104 @@
package library
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
)
// The owner: the skill market had too little in it. Every skill skills.sh's
// front page lists is offered, then its trending page's that aren't there
// (with no count, theirs being only recent installs), each repository's
// most installed first and its others after, and a search asks for 200.
func TestMarketSkillsAll(t *testing.T) {
sandbox(t)
t.Setenv("LOCALAPPDATA", t.TempDir())
popular.Lock()
popular.list = nil
popular.Unlock()
t.Cleanup(func() { popular.Lock(); popular.list = nil; popular.Unlock() })
var front, trending []string
// big/r has 100 skills, the most installed; 50 other repositories one each
for i := range 100 {
front = append(front, fmt.Sprintf(`{"source":"big/r","skillId":"b%d","name":"b%d","installs":%d}`, i, i, 100000-i))
}
for i := range 50 {
front = append(front, fmt.Sprintf(`{"source":"o%d/r","skillId":"s","name":"s","installs":%d}`, i, 1000-i))
}
// trending: one on the front page already, two new
trending = append(trending, `{"source":"big/r","skillId":"b3","name":"b3","installs":7}`,
`{"source":"new/r","skillId":"t1","name":"t1","installs":40}`, `{"source":"new/r","skillId":"t2","name":"t2","installs":30}`)
page := func(list []string) []byte {
js, _ := json.Marshal(`{"initialSkills":[` + strings.Join(list, ",") + `]}`)
return []byte(`<html><script>self.__next_f.push([1,` + string(js) + `])</script></html>`)
}
var limit string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
w.Write(page(front))
case "/trending":
w.Write(page(trending))
case "/api/search":
limit = r.URL.Query().Get("limit")
w.Write([]byte(`{"skills":[]}`))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
was := skillsShURL
skillsShURL = srv.URL
t.Cleanup(func() { skillsShURL = was })
list, err := MarketSkills("")
if err != nil {
t.Fatal(err)
}
var ids []string
for _, m := range list {
if !m.Featured {
ids = append(ids, m.ID)
}
}
if len(ids) != 152 {
t.Fatalf("%d offered, want all 152: %v", len(ids), ids)
}
// the first round has each repository's most installed: big/r's b0,
// the 50 others, new/r's t1; then big/r's b1 and new/r's t2
if ids[0] != "big/r/b0" || ids[1] != "o0/r/s" || ids[50] != "o49/r/s" || ids[51] != "new/r/t1" || ids[52] != "big/r/b1" || ids[53] != "new/r/t2" || ids[151] != "big/r/b99" {
t.Fatalf("order: %v", ids[:60])
}
i := slices.IndexFunc(list, func(m MarketSkill) bool { return m.ID == "new/r/t1" })
j := slices.IndexFunc(list, func(m MarketSkill) bool { return m.ID == "big/r/b3" })
if list[i].Installs != 0 || list[j].Installs != 100000-3 {
t.Fatalf("installs: trending %d, front page's %d", list[i].Installs, list[j].Installs)
}
// a search: the matches among them, all of them, and skills.sh asked for 200
list, _ = MarketSkills("big")
if len(list) != 100 || limit != "200" {
t.Fatalf("search: %d, limit %q", len(list), limit)
}
// the trending page failing leaves the front page's
popular.Lock()
popular.list = nil
popular.Unlock()
trending = nil
srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
w.Write(page(front))
return
}
http.Error(w, "", http.StatusBadGateway)
})
if list, err := fetchPopular(); err != nil || len(list) != 150 {
t.Fatalf("no trending: %d %v", len(list), err)
}
}
File diff suppressed because one or more lines are too long