library: a market of Pi's packages, installed and removed by pi itself (nineruiing on X)
Library -> Pi now has a Discover list of Pi packages: npm packages with the pi-package keyword (pi's own docs: the keyword makes a package eligible for the pi.dev/packages gallery), sorted by monthly downloads, with search. Like the other markets it ships a 500-entry snapshot (market_pi.json), keeps a 6h memory and disk cache, and refreshes from npm. Install and remove run that Pi's own `pi install npm:<name>` / `pi remove npm:<name>` with PI_CODING_AGENT_DIR set to its folder, so settings.json's packages list and <agentDir>/npm are written by pi, not by magpie. Each card says which Pis have it; Install goes straight to the only Pi without it or asks which one; the Pi's list gets a remove button behind a confirm. New routes: GET /api/library/market/pi, POST /api/library/pi/install and /api/library/pi/remove. Run: - mote: go test -count=1 -timeout 45m ./internal/library ./internal/cli ./internal/gui at this head: ok, ok, ok. - mote: gofmt -l clean; go vet of library, gui, cli for darwin, linux (-tags nogui) and windows: ok. - mote: library-pi-market, library-pi-extensions, i18n-keys, i18n-en-no-cjk in chromium and webkit: 52 of 52; the 17 market and library GUI files: 598 pass, 0 fail (pre-rebase tree). - win-run: go test -tags nogui ./internal/library -run 'TestPi|TestMarket' ok (TestPiRunGivesAgentDir skips on Windows). - wsl-run: library TestPi|TestMarket ok; library-pi-market 22 of 22. - Real pi 1.5.1 in a sandbox HOME on WSL: PI_CODING_AGENT_DIR=$A pi install npm:pi-btw wrote packages ["npm:pi-btw"] beside the existing theme and installed node_modules/pi-btw; pi remove put packages back to []. The live ~/.pi was untouched. Broken by hand (each red, then green restored): - the pi-package keyword filter dropped: TestPiMarketFromNPM; - the name check dropped in the market: TestPiMarketFromNPM; - the name check dropped in install: TestPiInstallAndRemove; - PI_CODING_AGENT_DIR not set: TestPiRunGivesAgentDir; - the identity dedupe dropped: TestPiInstallAndRemove; - the installed marking always "live": library-pi-market 11 of 11 red. Not tried: a real magpie binary driving pi install end to end; pi on native Windows; git: and local package sources (the market lists npm only, and the Pi's list still shows and removes them as before).
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -358,6 +358,7 @@ var notYet = map[string]string{
|
||||
"GET /api/library/icon": W, // library.go
|
||||
"GET /api/library/market/servers": L, // library.go
|
||||
"GET /api/library/market/skills": L, // library.go
|
||||
"GET /api/library/market/pi": L, // library.go
|
||||
"GET /api/library/mcp-signin/{id}": L, // library.go
|
||||
"GET /api/library/pi": L, // library.go
|
||||
"GET /api/library/rtk": L, // library.go
|
||||
@@ -372,6 +373,8 @@ var notYet = map[string]string{
|
||||
"POST /api/library/mcp/config": L, // library.go
|
||||
"POST /api/library/pi": L, // library.go
|
||||
"POST /api/library/pi/copy": L, // library.go
|
||||
"POST /api/library/pi/install": L, // library.go
|
||||
"POST /api/library/pi/remove": L, // library.go
|
||||
"POST /api/library/projects/choose": W, // library.go
|
||||
"POST /api/library/reveal": W, // library.go
|
||||
"POST /api/library/rtk": L, // library.go
|
||||
|
||||
@@ -1798,14 +1798,15 @@ magpie.plugin("library", (ctx) => {
|
||||
const tags = [tag(k.kind)];
|
||||
if (!k.installed) tags.push(tag(t("Not installed"), "", t("Pi installs it when it next starts")));
|
||||
else if (k.version) tags.push(tag("v" + k.version));
|
||||
list.append(piRow(p, others, { pkg: k.source }, k.name, k.source, k.on, tags, k.filtered));
|
||||
list.append(piRow(p, others, { pkg: k.source }, k.name, k.source, k.on, tags, k.filtered, () => confirmRemovePi(p, k)));
|
||||
}
|
||||
if (!(p.extensions || []).length && !(p.packages || []).length) list.append(el("div", "lib-none", t("No extensions or packages yet.")));
|
||||
}
|
||||
body.append(list);
|
||||
}
|
||||
if (live.length) body.append(discover("pi"));
|
||||
}
|
||||
function piRow(p, others, what, name, sub, on, tags, filtered) {
|
||||
function piRow(p, others, what, name, sub, on, tags, filtered, remove) {
|
||||
const key = p.id + " " + (what.ext || what.pkg);
|
||||
const row = el("div", "row lib-row lib-pi-row");
|
||||
row.dataset.id = what.ext || what.pkg;
|
||||
@@ -1825,6 +1826,13 @@ magpie.plugin("library", (ctx) => {
|
||||
if (filtered) sw.title = t("This entry loads only some of the package; change it with pi config");
|
||||
sw.disabled = !!filtered || piBusy.has(key);
|
||||
row.append(sw);
|
||||
if (remove) {
|
||||
const rm = button("", "lib-icon danger lib-rm lib-pi-rm", remove);
|
||||
rm.append(svg(GLYPH.trash, 13, 1.4));
|
||||
rm.title = t("Remove");
|
||||
rm.disabled = piBusy.has(key);
|
||||
row.append(rm);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
async function setPi(p, what, name, on) {
|
||||
@@ -7105,6 +7113,7 @@ magpie.plugin("library", (ctx) => {
|
||||
const market = {
|
||||
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 },
|
||||
pi: { 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;
|
||||
@@ -7116,7 +7125,7 @@ magpie.plugin("library", (ctx) => {
|
||||
m.loading = true;
|
||||
drawMarket(kind);
|
||||
try {
|
||||
const r = await api("library/market/" + (kind === "mcp" ? "servers" : "skills") + "?q=" + encodeURIComponent(m.q.trim()));
|
||||
const r = await api("library/market/" + ({ mcp: "servers", skills: "skills", pi: "pi" })[kind] + "?q=" + encodeURIComponent(m.q.trim()));
|
||||
if (seq !== m.seq) return;
|
||||
m.items = r.items || [];
|
||||
m.shown = MARKET_PAGE;
|
||||
@@ -7136,6 +7145,7 @@ magpie.plugin("library", (ctx) => {
|
||||
m.loading = false;
|
||||
drawMarket(kind);
|
||||
if (kind === "skills") describeSkills();
|
||||
if (kind === "pi") return;
|
||||
// The market reads the library as it is now; one it calls added that
|
||||
// this page doesn't list was added elsewhere — another window, the CLI.
|
||||
const mine = new Set((kind === "mcp" ? lib?.servers : lib?.skills)?.map((x) => x.name) || []);
|
||||
@@ -7171,7 +7181,7 @@ magpie.plugin("library", (ctx) => {
|
||||
const inp = el("input");
|
||||
inp.type = "search";
|
||||
inp.dataset.lib = "market-" + kind;
|
||||
inp.placeholder = kind === "mcp" ? t("Search MCP servers — GitHub, Postgres, Figma…") : t("Search skills on skills.sh — react, pdf, testing…");
|
||||
inp.placeholder = kind === "mcp" ? t("Search MCP servers — GitHub, Postgres, Figma…") : kind === "pi" ? t("Search Pi packages on npm — mcp, web, subagents…") : t("Search skills on skills.sh — react, pdf, testing…");
|
||||
inp.spellcheck = false;
|
||||
inp.autocomplete = "off";
|
||||
inp.value = m.q;
|
||||
@@ -7179,7 +7189,7 @@ magpie.plugin("library", (ctx) => {
|
||||
m.q = inp.value;
|
||||
clearTimeout(m.timer);
|
||||
const q = m.q.trim();
|
||||
if (kind === "skills" && q.length === 1) return;
|
||||
if (kind !== "mcp" && q.length === 1) return;
|
||||
m.timer = setTimeout(() => fetchMarket(kind), 320);
|
||||
};
|
||||
inp.onkeydown = (e) => {
|
||||
@@ -7202,7 +7212,7 @@ magpie.plugin("library", (ctx) => {
|
||||
box.classList.toggle("loading", m.loading);
|
||||
const note = box.querySelector(".mk-note");
|
||||
note.textContent = q && m.items ? (m.items.length === 1 ? t("1 result") : t("{n} results", { n: m.items.length }))
|
||||
: kind === "mcp" ? t("Featured, and the official MCP Registry") : t("Popular on skills.sh");
|
||||
: kind === "mcp" ? t("Featured, and the official MCP Registry") : kind === "pi" ? t("Most downloaded on npm") : t("Popular on skills.sh");
|
||||
const grid = box.querySelector(".mk-grid");
|
||||
grid.replaceChildren();
|
||||
if (!m.items) {
|
||||
@@ -7225,6 +7235,7 @@ magpie.plugin("library", (ctx) => {
|
||||
if (m.error && m.failed && m.items.length) {
|
||||
grid.append(el("div", "mk-msg mk-partial", kind === "mcp"
|
||||
? t("The MCP Registry didn't answer ({error}), so these are only magpie's featured servers that match.", { error: m.failed.cause })
|
||||
: kind === "pi" ? t("npm's search didn't answer ({error}), so these are only the matches among the most downloaded packages.", { error: m.failed.cause })
|
||||
: t("skills.sh's search didn't answer ({error}), so these are only the matches among magpie's picks and the most installed skills.", { error: m.failed.cause })));
|
||||
} else if (m.error) grid.append(el("div", "mk-msg err", m.error));
|
||||
if (kind === "mcp" && q && m.custom) grid.append(customAt(q, m.custom, m.items.length));
|
||||
@@ -7232,10 +7243,12 @@ 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.slice(0, m.shown)) grid.append(kind === "mcp" ? serverCard(x) : skillCard(x));
|
||||
for (const x of m.items.slice(0, m.shown)) grid.append(cardOf(kind, x));
|
||||
moreCards(kind, grid);
|
||||
}
|
||||
|
||||
const cardOf = (kind, x) => kind === "mcp" ? serverCard(x) : kind === "pi" ? piCard(x) : skillCard(x);
|
||||
|
||||
// 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) {
|
||||
@@ -7245,7 +7258,7 @@ magpie.plugin("library", (ctx) => {
|
||||
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.before(...m.items.slice(from, m.shown).map((x) => cardOf(kind, x)));
|
||||
more.remove();
|
||||
moreCards(kind, grid);
|
||||
if (kind === "skills") describeSkills();
|
||||
@@ -7588,6 +7601,102 @@ magpie.plugin("library", (ctx) => {
|
||||
return ok;
|
||||
}
|
||||
|
||||
// A package from Pi's market: who has it, or Install into a Pi (picked
|
||||
// when there are several). Pi itself installs it.
|
||||
const piLive = () => (piView?.pis || []).filter((p) => !p.asleep && !p.err && !isHidden({ id: p.id }));
|
||||
const piHas = (x) => piLive().filter((p) => (p.packages || []).some((k) => k.kind === "npm" && k.name === x.name));
|
||||
function piCard(x) {
|
||||
const has = piHas(x);
|
||||
const c = el("div", "mk-card" + (has.length ? " have" : ""));
|
||||
c.dataset.id = x.source;
|
||||
const top = el("div", "mk-top");
|
||||
const who = el("div", "mk-who");
|
||||
const nm = el("div", "mk-name");
|
||||
nm.append(el("span", "mk-title", x.name));
|
||||
who.append(nm);
|
||||
const meta = el("div", "mk-meta");
|
||||
if (x.publisher) meta.append(el("span", "mk-pub", x.publisher));
|
||||
if (x.version) meta.append(el("span", "mk-badge", "v" + x.version));
|
||||
who.append(meta);
|
||||
top.append(logo(x.icon, x.name), who);
|
||||
const d = el("p", "mk-desc", x.description || "");
|
||||
d.title = x.description || "";
|
||||
const foot = el("div", "mk-foot");
|
||||
if (x.downloads) {
|
||||
const n = el("span", "mk-installs");
|
||||
n.append(svg(GLYPH.down, 11, 1.5), el("span", "", compact(x.downloads)));
|
||||
n.title = t("{n} downloads last month", { n: x.downloads.toLocaleString(intlLang()) });
|
||||
foot.append(n);
|
||||
}
|
||||
foot.append(extLink(x.repo || x.npm, x.repo ? t("Source") : "npm"), el("span", "grow"));
|
||||
const live = piLive();
|
||||
const want = live.filter((p) => !has.includes(p));
|
||||
if (has.length && !want.length) {
|
||||
const b = el("span", "mk-have");
|
||||
b.append(svg(CHECK, 11, 2), el("span", "", t("Installed")));
|
||||
b.title = t("In {agents}", { agents: has.map((p) => p.name).join(", ") });
|
||||
foot.append(b);
|
||||
} else if (want.length) {
|
||||
const busy = want.some((p) => piBusy.has(p.id + " " + x.source));
|
||||
const b = button(busy ? t("Installing…") : t("Install"), "action mk-add", () => {
|
||||
if (want.length === 1) return installPi(want[0], x);
|
||||
openProtoMenu(b, want.map((p) => ({ v: p.id, name: p.name, literalName: true, note: "" })), "", (id) => installPi(want.find((p) => p.id === id), x), "Install into", "", "right");
|
||||
});
|
||||
if (busy) { b.disabled = true; b.classList.add("busy"); }
|
||||
if (has.length) b.title = t("In {agents}", { agents: has.map((p) => p.name).join(", ") });
|
||||
foot.append(b);
|
||||
}
|
||||
c.append(top, d, foot);
|
||||
return c;
|
||||
}
|
||||
async function installPi(p, x) {
|
||||
if (!p) return;
|
||||
const key = p.id + " " + x.source;
|
||||
piBusy.add(key);
|
||||
drawMarket("pi");
|
||||
status(t("Installing {name} into {agent}…", { name: x.name, agent: p.name }), "", 300000);
|
||||
try {
|
||||
const v = await api("library/pi/install", { pi: p.id, source: x.source });
|
||||
piView = v;
|
||||
status(v.pending
|
||||
? t("{name} is in {agent}'s packages now: Pi installs it when it next starts", { name: x.name, agent: p.name })
|
||||
: t("{name} is installed in {agent}: Pi loads it when it next starts, or at /reload", { name: x.name, agent: p.name }), "ok", 8000);
|
||||
} catch (e) {
|
||||
status(e.message, "err", 10000);
|
||||
}
|
||||
piBusy.delete(key);
|
||||
if (tab === "pi") render();
|
||||
}
|
||||
function confirmRemovePi(p, k) {
|
||||
const ed = el("div", "editor lib-editor lib-rmone");
|
||||
const head = el("div", "ehead");
|
||||
head.append(glyph(GLYPH.trash), el("b", "", t("Remove {name} from {agent}?", { name: k.name, agent: p.name })));
|
||||
ed.append(head);
|
||||
ed.append(el("p", "lib-confirm", p.wsl
|
||||
? t("It is taken out of {agent}'s settings.json; Pi stops loading it when it next starts.", { agent: p.name })
|
||||
: t("pi remove takes it out of {agent}'s settings.json and uninstalls it.", { agent: p.name })));
|
||||
const bar = el("div", "bar");
|
||||
const go = button(t("Remove"), "primary danger-fill", async () => {
|
||||
go.disabled = true;
|
||||
const key = p.id + " " + k.source;
|
||||
piBusy.add(key);
|
||||
try {
|
||||
piView = await api("library/pi/remove", { pi: p.id, source: k.source });
|
||||
status(t("{name} removed from {agent}", { name: k.name, agent: p.name }), "ok", 6000);
|
||||
closeLibModal(true);
|
||||
} catch (e) {
|
||||
status(e.message, "err", 10000);
|
||||
go.disabled = false;
|
||||
}
|
||||
piBusy.delete(key);
|
||||
if (tab === "pi") render();
|
||||
});
|
||||
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
|
||||
ed.append(bar);
|
||||
modal = { save: () => go.click() };
|
||||
openLib(ed);
|
||||
}
|
||||
|
||||
function skillSheet(x) {
|
||||
const all = skillAgents();
|
||||
let agents = all.map((a) => a.id);
|
||||
|
||||
@@ -893,6 +893,18 @@ magpie.strings({
|
||||
"No extensions or packages yet.": "还没有扩展或包。",
|
||||
"Copy to…": "复制到…",
|
||||
"Copy to another Pi": "复制到另一个 Pi",
|
||||
"Search Pi packages on npm — mcp, web, subagents…": "在 npm 上搜索 Pi 包 — mcp、web、subagents…",
|
||||
"Most downloaded on npm": "npm 下载最多",
|
||||
"npm's search didn't answer ({error}), so these are only the matches among the most downloaded packages.": "npm 搜索没有响应({error}),下面只是下载最多的包里匹配的。",
|
||||
"{n} downloads last month": "上个月下载 {n} 次",
|
||||
"In {agents}": "已在 {agents}",
|
||||
"Install into": "安装到",
|
||||
"Installing {name} into {agent}…": "正在把 {name} 安装到 {agent}…",
|
||||
"{name} is installed in {agent}: Pi loads it when it next starts, or at /reload": "{name} 已安装到 {agent}:Pi 下次启动或 /reload 时加载",
|
||||
"Remove {name} from {agent}?": "从 {agent} 移除 {name}?",
|
||||
"It is taken out of {agent}'s settings.json; Pi stops loading it when it next starts.": "它会从 {agent} 的 settings.json 中移除;Pi 下次启动时不再加载。",
|
||||
"pi remove takes it out of {agent}'s settings.json and uninstalls it.": "pi remove 会把它从 {agent} 的 settings.json 中移除并卸载。",
|
||||
"{name} removed from {agent}": "已从 {agent} 移除 {name}",
|
||||
"{agent} loads {name}": "{agent} 加载 {name}",
|
||||
"This entry loads only some of the package; change it with pi config": "这一项只加载包的一部分;请用 pi config 更改",
|
||||
"{name} is on for {agent}: Pi loads it when it next starts, or at /reload": "{name} 已为 {agent} 打开:Pi 下次启动或 /reload 时加载它",
|
||||
@@ -1814,6 +1826,18 @@ magpie.strings({
|
||||
"No extensions or packages yet.": "還沒有擴充或套件。",
|
||||
"Copy to…": "複製到…",
|
||||
"Copy to another Pi": "複製到另一個 Pi",
|
||||
"Search Pi packages on npm — mcp, web, subagents…": "在 npm 上搜尋 Pi 套件 — mcp、web、subagents…",
|
||||
"Most downloaded on npm": "npm 下載最多",
|
||||
"npm's search didn't answer ({error}), so these are only the matches among the most downloaded packages.": "npm 搜尋沒有回應({error}),下面只是下載最多的套件裡符合的。",
|
||||
"{n} downloads last month": "上個月下載 {n} 次",
|
||||
"In {agents}": "已在 {agents}",
|
||||
"Install into": "安裝到",
|
||||
"Installing {name} into {agent}…": "正在把 {name} 安裝到 {agent}…",
|
||||
"{name} is installed in {agent}: Pi loads it when it next starts, or at /reload": "{name} 已安裝到 {agent}:Pi 下次啟動或 /reload 時載入",
|
||||
"Remove {name} from {agent}?": "從 {agent} 移除 {name}?",
|
||||
"It is taken out of {agent}'s settings.json; Pi stops loading it when it next starts.": "它會從 {agent} 的 settings.json 中移除;Pi 下次啟動時不再載入。",
|
||||
"pi remove takes it out of {agent}'s settings.json and uninstalls it.": "pi remove 會把它從 {agent} 的 settings.json 中移除並解除安裝。",
|
||||
"{name} removed from {agent}": "已從 {agent} 移除 {name}",
|
||||
"{agent} loads {name}": "{agent} 載入 {name}",
|
||||
"This entry loads only some of the package; change it with pi config": "這一項只載入套件的一部分;請用 pi config 變更",
|
||||
"{name} is on for {agent}: Pi loads it when it next starts, or at /reload": "{name} 已為 {agent} 開啟:Pi 下次啟動或 /reload 時載入它",
|
||||
@@ -2735,6 +2759,18 @@ magpie.strings({
|
||||
"No extensions or packages yet.": "拡張機能もパッケージもまだありません。",
|
||||
"Copy to…": "コピー先…",
|
||||
"Copy to another Pi": "別の Pi にコピー",
|
||||
"Search Pi packages on npm — mcp, web, subagents…": "npm で Pi パッケージを検索 — mcp、web、subagents…",
|
||||
"Most downloaded on npm": "npm でダウンロード数上位",
|
||||
"npm's search didn't answer ({error}), so these are only the matches among the most downloaded packages.": "npm の検索が応答しませんでした({error})。ダウンロード数上位のパッケージから一致したものだけを表示しています。",
|
||||
"{n} downloads last month": "先月 {n} 回ダウンロード",
|
||||
"In {agents}": "{agents} にあります",
|
||||
"Install into": "インストール先",
|
||||
"Installing {name} into {agent}…": "{name} を {agent} にインストール中…",
|
||||
"{name} is installed in {agent}: Pi loads it when it next starts, or at /reload": "{name} を {agent} にインストールしました。Pi の次回起動時か /reload で読み込まれます",
|
||||
"Remove {name} from {agent}?": "{agent} から {name} を削除しますか?",
|
||||
"It is taken out of {agent}'s settings.json; Pi stops loading it when it next starts.": "{agent} の settings.json から外します。Pi は次回起動時から読み込みません。",
|
||||
"pi remove takes it out of {agent}'s settings.json and uninstalls it.": "pi remove で {agent} の settings.json から外し、アンインストールします。",
|
||||
"{name} removed from {agent}": "{agent} から {name} を削除しました",
|
||||
"{agent} loads {name}": "{agent} が {name} を読み込む",
|
||||
"This entry loads only some of the package; change it with pi config": "この項目はパッケージの一部だけを読み込みます。pi config で変更してください",
|
||||
"{name} is on for {agent}: Pi loads it when it next starts, or at /reload": "{agent} で {name} をオンにしました。Pi は次回起動時か /reload で読み込みます",
|
||||
@@ -3656,6 +3692,18 @@ magpie.strings({
|
||||
"No extensions or packages yet.": "Noch keine Erweiterungen oder Pakete.",
|
||||
"Copy to…": "Kopieren nach…",
|
||||
"Copy to another Pi": "Zu einem anderen Pi kopieren",
|
||||
"Search Pi packages on npm — mcp, web, subagents…": "Pi-Pakete auf npm suchen — mcp, web, subagents…",
|
||||
"Most downloaded on npm": "Auf npm am meisten geladen",
|
||||
"npm's search didn't answer ({error}), so these are only the matches among the most downloaded packages.": "Die npm-Suche hat nicht geantwortet ({error}), daher sind das nur die Treffer unter den meistgeladenen Paketen.",
|
||||
"{n} downloads last month": "{n} Downloads im letzten Monat",
|
||||
"In {agents}": "In {agents}",
|
||||
"Install into": "Installieren in",
|
||||
"Installing {name} into {agent}…": "{name} wird in {agent} installiert…",
|
||||
"{name} is installed in {agent}: Pi loads it when it next starts, or at /reload": "{name} ist in {agent} installiert: Pi lädt es beim nächsten Start oder bei /reload",
|
||||
"Remove {name} from {agent}?": "{name} aus {agent} entfernen?",
|
||||
"It is taken out of {agent}'s settings.json; Pi stops loading it when it next starts.": "Es wird aus der settings.json von {agent} entfernt; Pi lädt es ab dem nächsten Start nicht mehr.",
|
||||
"pi remove takes it out of {agent}'s settings.json and uninstalls it.": "pi remove entfernt es aus der settings.json von {agent} und deinstalliert es.",
|
||||
"{name} removed from {agent}": "{name} aus {agent} entfernt",
|
||||
"{agent} loads {name}": "{agent} lädt {name}",
|
||||
"This entry loads only some of the package; change it with pi config": "Dieser Eintrag lädt nur einen Teil des Pakets; ändere ihn mit pi config",
|
||||
"{name} is on for {agent}: Pi loads it when it next starts, or at /reload": "{name} ist für {agent} an: Pi lädt es beim nächsten Start oder bei /reload",
|
||||
|
||||
@@ -209,6 +209,10 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
|
||||
list, err := library.MarketSkills(r.URL.Query().Get("q"))
|
||||
writeJSON(rw, marketOf(list, err))
|
||||
})
|
||||
mux.HandleFunc("GET /api/library/market/pi", func(rw http.ResponseWriter, r *http.Request) {
|
||||
list, err := library.MarketPiPackages(r.URL.Query().Get("q"))
|
||||
writeJSON(rw, marketOf(list, err))
|
||||
})
|
||||
mux.HandleFunc("POST /api/library/market/about", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ IDs []string }
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
@@ -320,6 +324,34 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
|
||||
}
|
||||
writeJSON(rw, v)
|
||||
})
|
||||
// a package from Pi's market installed into a Pi, or one of a Pi's
|
||||
// packages removed, by Pi's own install and remove
|
||||
mux.HandleFunc("POST /api/library/pi/install", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Pi, Source string }
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
v, err := library.InstallPiPackage(in.Pi, in.Source)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, v)
|
||||
})
|
||||
mux.HandleFunc("POST /api/library/pi/remove", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Pi, Source string }
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
v, err := library.RemovePiPackage(in.Pi, in.Source)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, v)
|
||||
})
|
||||
// RTK:which agents have its hook, switching one on or off, and
|
||||
// installing rtk when the page is asked to
|
||||
mux.HandleFunc("GET /api/library/rtk", func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// nineruiing on X: a market of Pi's packages. Under the Pi packages tab,
|
||||
// Discover lists npm's most downloaded pi-package packages; a package every
|
||||
// running Pi has shows Installed; Install goes to the one Pi that lacks it,
|
||||
// or asks which when several do (never a stopped distro); a search npm
|
||||
// couldn't answer says so over what was found; a package's trash button
|
||||
// asks first and sends pi remove. In every language, both engines, at a
|
||||
// phone's width too. 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 = "C:\\Users\\nine";
|
||||
const lib = () => ({
|
||||
dir: `${HOME}\\.magpie\\library`, backups: `${HOME}\\.magpie\\backups`, home: HOME,
|
||||
agents: [
|
||||
{ id: "pi", name: "Pi", icon: "", skills: `${HOME}\\.pi\\agent\\skills` },
|
||||
{ id: "pi@wsl:Ubuntu", name: "Pi · WSL Ubuntu", icon: "", skills: "\\\\wsl.localhost\\Ubuntu\\home\\nine\\.pi\\agent\\skills", wsl: "Ubuntu" },
|
||||
],
|
||||
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [],
|
||||
});
|
||||
const pkg = (name, extra) => ({ source: "npm:" + name, name, kind: "npm", on: true, installed: true, version: "1.0.0", ...extra });
|
||||
// state: which Pi has which package
|
||||
function piView(has) {
|
||||
return {
|
||||
pis: [
|
||||
{ id: "pi", name: "Pi", icon: "", dir: `${HOME}\\.pi\\agent`, extensions: [], packages: has.pi.map((n) => pkg(n)) },
|
||||
{ id: "pi@wsl:Ubuntu", name: "Pi · WSL Ubuntu", icon: "", wsl: "Ubuntu", dir: "\\\\wsl.localhost\\Ubuntu\\home\\nine\\.pi\\agent", extensions: [], packages: has.ubuntu.map((n) => pkg(n, { installed: false })) },
|
||||
{ id: "pi@wsl:Arch", name: "Pi · WSL Arch", icon: "", wsl: "Arch", asleep: true, extensions: [], packages: [] },
|
||||
],
|
||||
};
|
||||
}
|
||||
const card = (name, downloads, extra) => ({
|
||||
source: "npm:" + name, name, version: "0.3.1", description: name + " for Pi", publisher: "nine", downloads,
|
||||
npm: "https://www.npmjs.com/package/" + name, ...extra,
|
||||
});
|
||||
const popular = [
|
||||
card("pi-mcp-adapter", 48210, { repo: "https://github.com/nicobailon/pi-mcp-adapter" }),
|
||||
card("pi-web-access", 20113),
|
||||
card("pi-subagents", 9050),
|
||||
];
|
||||
|
||||
function server(lang, calls) {
|
||||
const has = { pi: ["pi-mcp-adapter", "pi-subagents"], ubuntu: ["pi-mcp-adapter"] };
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
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 route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
|
||||
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
|
||||
if (url.pathname === "/api/library") return route.fulfill({ json: lib() });
|
||||
if (url.pathname === "/api/library/pi") return route.fulfill({ json: piView(has) });
|
||||
if (url.pathname === "/api/library/market/pi") {
|
||||
const q = url.searchParams.get("q") || "";
|
||||
calls.push(["market", q]);
|
||||
if (!q) return route.fulfill({ json: { items: popular } });
|
||||
// npm's search is down: only the popular matches
|
||||
return route.fulfill({ json: { items: popular.filter((x) => x.name.includes(q)), error: "npm: timeout", failed: "npm", cause: "timeout" } });
|
||||
}
|
||||
if (url.pathname === "/api/library/pi/install") {
|
||||
const b = req.postDataJSON();
|
||||
calls.push(["install", b]);
|
||||
has[b.pi === "pi" ? "pi" : "ubuntu"].push(b.source.slice(4));
|
||||
return route.fulfill({ json: { ...piView(has), pending: b.pi !== "pi" } });
|
||||
}
|
||||
if (url.pathname === "/api/library/pi/remove") {
|
||||
const b = req.postDataJSON();
|
||||
calls.push(["remove", b]);
|
||||
const k = b.pi === "pi" ? "pi" : "ubuntu";
|
||||
has[k] = has[k].filter((n) => "npm:" + n !== b.source);
|
||||
return route.fulfill({ json: piView(has) });
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
|
||||
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
|
||||
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
|
||||
if (url.pathname.startsWith("/api/")) return route.fulfill({ 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)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: {
|
||||
tab: "Pi packages", note: "Most downloaded on npm", install: "Install", installed: "Installed", into: "Install into", remove: "Remove",
|
||||
pending: "pi-subagents is in Pi · WSL Ubuntu's packages now: Pi installs it when it next starts",
|
||||
done: "pi-web-access is installed in Pi: Pi loads it when it next starts, or at /reload",
|
||||
partial: "npm's search didn't answer (timeout), so these are only the matches among the most downloaded packages.",
|
||||
ask: "Remove pi-subagents from Pi?", removed: "pi-subagents removed from Pi",
|
||||
},
|
||||
zh: {
|
||||
tab: "Pi 包", note: "npm 下载最多", install: "安装", installed: "已安装", into: "安装到", remove: "移除",
|
||||
pending: "pi-subagents 已加入 Pi · WSL Ubuntu 的包:Pi 下次启动时安装它",
|
||||
done: "pi-web-access 已安装到 Pi:Pi 下次启动或 /reload 时加载",
|
||||
partial: "npm 搜索没有响应(timeout),下面只是下载最多的包里匹配的。",
|
||||
ask: "从 Pi 移除 pi-subagents?", removed: "已从 Pi 移除 pi-subagents",
|
||||
},
|
||||
"zh-TW": {
|
||||
tab: "Pi 套件", note: "npm 下載最多", install: "安裝", installed: "已安裝", into: "安裝到", remove: "移除",
|
||||
pending: "pi-subagents 已加入 Pi · WSL Ubuntu 的套件:Pi 下次啟動時安裝它",
|
||||
done: "pi-web-access 已安裝到 Pi:Pi 下次啟動或 /reload 時載入",
|
||||
partial: "npm 搜尋沒有回應(timeout),下面只是下載最多的套件裡符合的。",
|
||||
ask: "從 Pi 移除 pi-subagents?", removed: "已從 Pi 移除 pi-subagents",
|
||||
},
|
||||
ja: {
|
||||
tab: "Pi パッケージ", note: "npm でダウンロード数上位", install: "インストール", installed: "インストール済み", into: "インストール先", remove: "削除",
|
||||
pending: "pi-subagents を Pi · WSL Ubuntu のパッケージに追加しました。Pi が次回起動時にインストールします",
|
||||
done: "pi-web-access を Pi にインストールしました。Pi の次回起動時か /reload で読み込まれます",
|
||||
partial: "npm の検索が応答しませんでした(timeout)。ダウンロード数上位のパッケージから一致したものだけを表示しています。",
|
||||
ask: "Pi から pi-subagents を削除しますか?", removed: "Pi から pi-subagents を削除しました",
|
||||
},
|
||||
de: {
|
||||
tab: "Pi-Pakete", note: "Auf npm am meisten geladen", install: "Installieren", installed: "Installiert", into: "Installieren in", remove: "Entfernen",
|
||||
pending: "pi-subagents ist jetzt in den Paketen von Pi · WSL Ubuntu: Pi installiert es beim nächsten Start",
|
||||
done: "pi-web-access ist in Pi installiert: Pi lädt es beim nächsten Start oder bei /reload",
|
||||
partial: "Die npm-Suche hat nicht geantwortet (timeout), daher sind das nur die Treffer unter den meistgeladenen Paketen.",
|
||||
ask: "pi-subagents aus Pi entfernen?", removed: "pi-subagents aus Pi entfernt",
|
||||
},
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": Pi's market lists npm's packages, installs into a Pi and removes from one", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const errors = [];
|
||||
t.after(async () => {
|
||||
if (errors.length) console.log(errors);
|
||||
await browser.close();
|
||||
});
|
||||
for (const lang of Object.keys(words)) for (const width of [980, 380]) {
|
||||
await t.test(`${lang} at ${width}px`, async () => {
|
||||
const w = words[lang], calls = [];
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 900 } });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, calls));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
const v = page.locator("#view-library");
|
||||
await v.locator(".lib-tabs").getByText(w.tab, { exact: true }).click();
|
||||
const mk = v.locator('.mk[data-market="pi"]');
|
||||
const cardOf = (name) => mk.locator(`.mk-card[data-id="npm:${name}"]`);
|
||||
await cardOf("pi-mcp-adapter").waitFor();
|
||||
assert.equal(await mk.locator(".mk-note").textContent(), w.note);
|
||||
assert.deepEqual(await mk.locator(".mk-title").allTextContents(), ["pi-mcp-adapter", "pi-web-access", "pi-subagents"]);
|
||||
// both running Pis have it: Installed, no button
|
||||
const both = cardOf("pi-mcp-adapter");
|
||||
assert.equal(await both.locator(".mk-have").textContent(), w.installed);
|
||||
assert.equal(await both.locator(".mk-add").count(), 0);
|
||||
// only Ubuntu lacks it: Install goes there, no menu
|
||||
const sub = cardOf("pi-subagents");
|
||||
assert.equal(await sub.locator(".mk-add").textContent(), w.install);
|
||||
await sub.locator(".mk-add").click();
|
||||
await page.waitForFunction((want) => document.querySelector("#status").textContent === want, w.pending).catch(() => {});
|
||||
assert.equal(await page.locator("#status").textContent(), w.pending);
|
||||
assert.equal(await page.locator(".proto-menu").count(), 0);
|
||||
assert.equal(await cardOf("pi-subagents").locator(".mk-have").textContent(), w.installed);
|
||||
const ubuntu = v.locator(".lib-list.lib-pi").nth(1);
|
||||
await ubuntu.locator('.lib-pi-row[data-id="npm:pi-subagents"]').waitFor();
|
||||
|
||||
// nobody has it: Install asks which Pi, never the stopped Arch
|
||||
await cardOf("pi-web-access").locator(".mk-add").click();
|
||||
const menu = page.locator(".proto-menu");
|
||||
await menu.locator(".pm-item").first().waitFor();
|
||||
assert((await menu.textContent()).includes(w.into), await menu.textContent());
|
||||
assert.deepEqual(await menu.locator(".pm-item .pm-name").allTextContents(), ["Pi", "Pi · WSL Ubuntu"]);
|
||||
await menu.locator(".pm-item").first().click();
|
||||
await page.waitForFunction((want) => document.querySelector("#status").textContent === want, w.done).catch(() => {});
|
||||
assert.equal(await page.locator("#status").textContent(), w.done);
|
||||
const here = v.locator(".lib-list.lib-pi").nth(0);
|
||||
await here.locator('.lib-pi-row[data-id="npm:pi-web-access"]').waitFor();
|
||||
|
||||
// a package's trash button asks first, then pi remove
|
||||
await here.locator('.lib-pi-row[data-id="npm:pi-subagents"] .lib-pi-rm').click();
|
||||
const ed = page.locator(".lib-rmone");
|
||||
await ed.waitFor();
|
||||
assert.equal(await ed.locator(".ehead b").textContent(), w.ask);
|
||||
await ed.getByRole("button", { name: w.remove, exact: true }).click();
|
||||
await page.waitForFunction((want) => document.querySelector("#status").textContent === want, w.removed).catch(() => {});
|
||||
assert.equal(await page.locator("#status").textContent(), w.removed);
|
||||
await here.locator('.lib-pi-row[data-id="npm:pi-subagents"]').waitFor({ state: "detached" });
|
||||
await ed.waitFor({ state: "detached" }); // the dialog closes
|
||||
// Pi lacks it again
|
||||
assert.equal(await cardOf("pi-subagents").locator(".mk-add").textContent(), w.install);
|
||||
|
||||
// npm's search down: what was found, and why that's all
|
||||
await mk.locator('input[data-lib="market-pi"]').fill("web");
|
||||
await mk.locator(".mk-partial").waitFor();
|
||||
assert.equal(await mk.locator(".mk-partial").textContent(), w.partial);
|
||||
assert.deepEqual(await mk.locator(".mk-title").allTextContents(), ["pi-web-access"]);
|
||||
|
||||
assert.deepEqual(calls.filter((c) => c[0] !== "market"), [
|
||||
["install", { pi: "pi@wsl:Ubuntu", source: "npm:pi-subagents" }],
|
||||
["install", { pi: "pi", source: "npm:pi-web-access" }],
|
||||
["remove", { pi: "pi", source: "npm:pi-subagents" }],
|
||||
]);
|
||||
assert.deepEqual(calls.filter((c) => c[0] === "market").map((c) => c[1]), ["", "web"]);
|
||||
// nothing runs off the side at a phone's width
|
||||
const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
|
||||
assert(over <= 0, `the page scrolls sideways by ${over}px`);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,396 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
)
|
||||
|
||||
// Pi's package market (nineruiing on X). Pi's gallery, pi.dev/packages, is
|
||||
// npm's packages with the keyword "pi-package", drawn on its server with no
|
||||
// API of its own; magpie reads the same list from npm's search, kept as
|
||||
// the skills market keeps skills.sh's: six hours in memory, on disk for
|
||||
// when npm can't be reached, else the snapshot magpie shipped with.
|
||||
//
|
||||
// A package is installed and removed by Pi's own `pi install npm:<name>`
|
||||
// and `pi remove`, run with PI_CODING_AGENT_DIR set to that Pi's agent
|
||||
// folder (@earendil-works/pi-coding-agent 1.5.1, package-manager-cli.js and
|
||||
// core/package-manager.js: installAndPersist installs it under
|
||||
// <agent dir>/npm and adds its source to settings.json; removeAndPersist
|
||||
// uninstalls it and takes out every entry of the same identity). A Pi
|
||||
// whose command magpie can't run here, one in WSL or one without its CLI
|
||||
// found, is given the entry alone, which Pi installs when it next starts
|
||||
// (resolve → installMissing), as a copy from another Pi is.
|
||||
|
||||
// PiMarketPackage is one package the market offers.
|
||||
type PiMarketPackage struct {
|
||||
// Source is what Pi installs it by: npm:<name>
|
||||
Source string `json:"source"`
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Publisher string `json:"publisher,omitempty"`
|
||||
// Downloads is npm's count for the last month
|
||||
Downloads int `json:"downloads,omitempty"`
|
||||
Icon string `json:"icon,omitempty"`
|
||||
NPM string `json:"npm"`
|
||||
Repo string `json:"repo,omitempty"`
|
||||
Homepage string `json:"homepage,omitempty"`
|
||||
Updated string `json:"updated,omitempty"`
|
||||
}
|
||||
|
||||
// piListed is a package as the snapshot and the disk cache keep it.
|
||||
type piListed struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Publisher string `json:"publisher,omitempty"`
|
||||
Downloads int `json:"downloads,omitempty"`
|
||||
Repository string `json:"repository,omitempty"`
|
||||
Homepage string `json:"homepage,omitempty"`
|
||||
Date string `json:"date,omitempty"`
|
||||
}
|
||||
|
||||
// piNPMURL is npm's search; a variable for tests.
|
||||
var piNPMURL = "https://registry.npmjs.org/-/v1/search"
|
||||
|
||||
//go:embed market_pi.json
|
||||
var piSnapshot []byte
|
||||
|
||||
var piPopular = struct {
|
||||
sync.Mutex
|
||||
list []piListed
|
||||
at time.Time
|
||||
}{}
|
||||
|
||||
// popularPi is the most downloaded of the first 500 packages npm lists by
|
||||
// the keyword: Pi's gallery's own source.
|
||||
func popularPi() []piListed {
|
||||
piPopular.Lock()
|
||||
defer piPopular.Unlock()
|
||||
if piPopular.list != nil && time.Since(piPopular.at) < 6*time.Hour {
|
||||
return piPopular.list
|
||||
}
|
||||
cache := marketCache("pi-packages.json")
|
||||
if list, err := fetchPiPopular(); err == nil && len(list) > 0 {
|
||||
piPopular.list, piPopular.at = list, time.Now()
|
||||
if b, err := json.Marshal(list); err == nil && cache != "" {
|
||||
_ = os.MkdirAll(filepath.Dir(cache), 0o755)
|
||||
_ = os.WriteFile(cache, b, 0o644)
|
||||
}
|
||||
return list
|
||||
}
|
||||
var list []piListed
|
||||
if b, err := os.ReadFile(cache); err != nil || json.Unmarshal(b, &list) != nil || len(list) == 0 {
|
||||
_ = json.Unmarshal(piSnapshot, &list)
|
||||
}
|
||||
piPopular.list, piPopular.at = list, time.Now().Add(-6*time.Hour+5*time.Minute) // try again in a while
|
||||
return list
|
||||
}
|
||||
|
||||
func fetchPiPopular() ([]piListed, error) {
|
||||
var list []piListed
|
||||
for from := 0; from < 500; from += 250 {
|
||||
page, total, err := searchPiNPM("", 250, from)
|
||||
if err != nil {
|
||||
if len(list) > 0 {
|
||||
break
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
list = append(list, page...)
|
||||
if from+250 >= total {
|
||||
break
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(list, func(a, b piListed) int { return cmp.Compare(b.Downloads, a.Downloads) })
|
||||
return piOnce(list), nil
|
||||
}
|
||||
|
||||
// searchPiNPM is one page of npm's search for packages with the keyword,
|
||||
// and how many there are.
|
||||
func searchPiNPM(q string, size, from int) ([]piListed, int, error) {
|
||||
text := "keywords:pi-package"
|
||||
if q = strings.TrimSpace(q); q != "" {
|
||||
text += " " + q
|
||||
}
|
||||
var body struct {
|
||||
Total int `json:"total"`
|
||||
Objects []struct {
|
||||
Downloads struct {
|
||||
Monthly int `json:"monthly"`
|
||||
} `json:"downloads"`
|
||||
Package struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Description string `json:"description"`
|
||||
Keywords []string `json:"keywords"`
|
||||
Date string `json:"date"`
|
||||
Publisher struct {
|
||||
Username string `json:"username"`
|
||||
} `json:"publisher"`
|
||||
Links struct {
|
||||
Homepage string `json:"homepage"`
|
||||
Repository string `json:"repository"`
|
||||
} `json:"links"`
|
||||
} `json:"package"`
|
||||
} `json:"objects"`
|
||||
}
|
||||
u := piNPMURL + "?" + url.Values{"text": {text}, "size": {strconv.Itoa(size)}, "from": {strconv.Itoa(from)}}.Encode()
|
||||
if err := getJSON(u, &body); err != nil {
|
||||
return nil, 0, &SearchError{Source: "npm", Err: err}
|
||||
}
|
||||
var out []piListed
|
||||
for _, o := range body.Objects {
|
||||
p := o.Package
|
||||
// a word of the search can match a package by its text alone; Pi's
|
||||
// gallery lists only those with the keyword
|
||||
if !slices.Contains(p.Keywords, "pi-package") || !piNameRe.MatchString(p.Name) {
|
||||
continue
|
||||
}
|
||||
d := strings.TrimSpace(p.Description)
|
||||
if r := []rune(d); len(r) > 280 {
|
||||
d = strings.TrimSpace(string(r[:277])) + "…"
|
||||
}
|
||||
out = append(out, piListed{Name: p.Name, Version: p.Version, Description: d, Publisher: p.Publisher.Username,
|
||||
Downloads: o.Downloads.Monthly, Repository: p.Links.Repository, Homepage: p.Links.Homepage, Date: p.Date})
|
||||
}
|
||||
return out, body.Total, nil
|
||||
}
|
||||
|
||||
func piOnce(list []piListed) []piListed {
|
||||
seen := map[string]bool{}
|
||||
return slices.DeleteFunc(list, func(p piListed) bool {
|
||||
if seen[p.Name] {
|
||||
return true
|
||||
}
|
||||
seen[p.Name] = true
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
// MarketPiPackages is what the market shows for a search: the popular
|
||||
// packages that match it, then what npm finds for it.
|
||||
func MarketPiPackages(q string) ([]PiMarketPackage, error) {
|
||||
q = strings.ToLower(strings.TrimSpace(q))
|
||||
var list []piListed
|
||||
for _, p := range popularPi() {
|
||||
if q == "" || strings.Contains(strings.ToLower(p.Name+" "+p.Publisher+" "+p.Description), q) {
|
||||
list = append(list, p)
|
||||
}
|
||||
}
|
||||
var err error
|
||||
if len([]rune(q)) >= 2 {
|
||||
var found []piListed
|
||||
found, _, err = searchPiNPM(q, 100, 0)
|
||||
list = piOnce(append(list, found...))
|
||||
}
|
||||
out := []PiMarketPackage{}
|
||||
for _, p := range list {
|
||||
out = append(out, piMarketOf(p))
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
func piMarketOf(p piListed) PiMarketPackage {
|
||||
m := PiMarketPackage{Source: "npm:" + p.Name, Name: p.Name, Version: p.Version, Description: p.Description,
|
||||
Publisher: p.Publisher, Downloads: p.Downloads, NPM: "https://www.npmjs.com/package/" + p.Name}
|
||||
if repo := piRepoURL(p.Repository); repo != "" {
|
||||
m.Repo = repo
|
||||
if owner := githubOwner(repo); owner != "" {
|
||||
m.Icon = gh(owner)
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(p.Homepage, "https://") {
|
||||
m.Homepage = p.Homepage
|
||||
}
|
||||
if len(p.Date) >= 10 {
|
||||
m.Updated = p.Date[:10]
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// piRepoURL is a package's repository as a page to open: npm's
|
||||
// git+https://…/x.git as https://…/x; nothing that isn't https.
|
||||
func piRepoURL(s string) string {
|
||||
s = strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(s), "git+"), ".git")
|
||||
if !strings.HasPrefix(s, "https://") {
|
||||
return ""
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ---- install and remove -----------------------------------------------------
|
||||
|
||||
// piNameRe is an npm package's name (validate-npm-package-name): never one
|
||||
// that starts with "-" or ".", which a command would read as a flag or a
|
||||
// path.
|
||||
var piNameRe = lazyre.New(`^(@[a-z0-9][a-z0-9._~-]*/)?[a-z0-9_][a-z0-9._~-]*$`)
|
||||
|
||||
// PiInstalled is what an install or a removal did, for the page to say.
|
||||
type PiInstalled struct {
|
||||
*PiExtensions
|
||||
// Pending: only settings.json was changed; Pi installs the package
|
||||
// (or no longer loads it) when it next starts
|
||||
Pending bool `json:"pending,omitempty"`
|
||||
}
|
||||
|
||||
// piBin is the pi command magpie runs for p, "" when it can't run one: a
|
||||
// Pi in WSL, or one whose CLI isn't found; a var for tests.
|
||||
var piBin = func(p piPlace) string {
|
||||
if p.a.WSL != "" {
|
||||
return ""
|
||||
}
|
||||
return p.a.BinPath()
|
||||
}
|
||||
|
||||
// piRun runs `pi <args>` for the Pi whose agent folder is dir, with
|
||||
// nothing to answer it; a var for tests.
|
||||
var piRun = func(bin, dir string, args ...string) (string, error) {
|
||||
const timeout = 5 * time.Minute
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
cmd := proc.CommandContext(ctx, bin, args...)
|
||||
cmd.Stdin = nil
|
||||
cmd.Dir = dir
|
||||
// pi is a node script: its folder first, so its node is found
|
||||
cmd.Env = append(os.Environ(), "PI_CODING_AGENT_DIR="+dir, "PATH="+filepath.Dir(bin)+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
out, err := cmd.CombinedOutput()
|
||||
text := strings.TrimSpace(string(out))
|
||||
if err != nil {
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
|
||||
return text, fmt.Errorf("pi %s didn't finish in %s", strings.Join(args, " "), timeout)
|
||||
}
|
||||
if text == "" {
|
||||
text = err.Error()
|
||||
}
|
||||
return text, fmt.Errorf("pi %s: %s", strings.Join(args, " "), lastLines(text, 4))
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
// InstallPiPackage installs an npm package from the market into a Pi.
|
||||
func InstallPiPackage(pi, source string) (*PiInstalled, error) {
|
||||
name, ok := strings.CutPrefix(strings.TrimSpace(source), "npm:")
|
||||
if !ok || !piNameRe.MatchString(name) {
|
||||
return nil, fmt.Errorf("%q isn't an npm package Pi can install", source)
|
||||
}
|
||||
source = "npm:" + name
|
||||
piMu.Lock()
|
||||
defer piMu.Unlock()
|
||||
p, err := piPlaceOf(pi)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s, err := p.settings()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id := p.piIdentity(source)
|
||||
for _, r := range s.pkgs {
|
||||
if x, ok := piPackageOf(r); ok && p.piIdentity(x.Source) == id {
|
||||
return nil, fmt.Errorf("%s has %s already", piLabel(p), name)
|
||||
}
|
||||
}
|
||||
if err := newBackups().keep(p.a.ID, p.settingsPath()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bin := piBin(p); bin != "" {
|
||||
if _, err := piRun(bin, p.dir, "install", source); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if has, err := p.has(id); err != nil {
|
||||
return nil, err
|
||||
} else if !has {
|
||||
return nil, fmt.Errorf("pi install %s finished, but %s's settings.json doesn't list it", source, piLabel(p))
|
||||
}
|
||||
return &PiInstalled{PiExtensions: ReadPiExtensions()}, nil
|
||||
}
|
||||
b, _ := json.Marshal(source)
|
||||
next := append(slices.Clone(s.pkgs), b)
|
||||
if err := os.MkdirAll(p.dir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := edit.SetJSON(p.settingsPath(), edit.KV{Path: "packages", Value: next}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &PiInstalled{PiExtensions: ReadPiExtensions(), Pending: true}, nil
|
||||
}
|
||||
|
||||
// RemovePiPackage takes a package out of a Pi, as `pi remove` does.
|
||||
func RemovePiPackage(pi, source string) (*PiInstalled, error) {
|
||||
source = strings.TrimSpace(source)
|
||||
if source == "" || strings.HasPrefix(source, "-") {
|
||||
return nil, fmt.Errorf("%q isn't a package", source)
|
||||
}
|
||||
piMu.Lock()
|
||||
defer piMu.Unlock()
|
||||
p, err := piPlaceOf(pi)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s, err := p.settings()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id := p.piIdentity(source)
|
||||
var next []json.RawMessage
|
||||
for _, r := range s.pkgs {
|
||||
if x, ok := piPackageOf(r); ok && p.piIdentity(x.Source) == id {
|
||||
continue
|
||||
}
|
||||
next = append(next, r)
|
||||
}
|
||||
if len(next) == len(s.pkgs) {
|
||||
return nil, fmt.Errorf("%s has no package %s", piLabel(p), source)
|
||||
}
|
||||
if err := newBackups().keep(p.a.ID, p.settingsPath()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bin := piBin(p); bin != "" {
|
||||
if _, err := piRun(bin, p.dir, "remove", source); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if has, err := p.has(id); err != nil {
|
||||
return nil, err
|
||||
} else if has {
|
||||
return nil, fmt.Errorf("pi remove %s finished, but %s's settings.json still lists it", source, piLabel(p))
|
||||
}
|
||||
return &PiInstalled{PiExtensions: ReadPiExtensions()}, nil
|
||||
}
|
||||
if next == nil {
|
||||
next = []json.RawMessage{}
|
||||
}
|
||||
if err := edit.SetJSON(p.settingsPath(), edit.KV{Path: "packages", Value: next}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &PiInstalled{PiExtensions: ReadPiExtensions(), Pending: true}, nil
|
||||
}
|
||||
|
||||
// has says whether p's settings.json lists a package of this identity;
|
||||
// one that can't be read says nothing either way.
|
||||
func (p piPlace) has(id string) (bool, error) {
|
||||
s, err := p.settings()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return slices.ContainsFunc(s.pkgs, func(r json.RawMessage) bool {
|
||||
x, ok := piPackageOf(r)
|
||||
return ok && p.piIdentity(x.Source) == id
|
||||
}), nil
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// piNPM is npm's search as the market asks it, answering with these
|
||||
// packages for the keyword alone and those for a search's words.
|
||||
func piNPM(t *testing.T, popular, found []string) (asked *atomic.Int32, texts *[]string, down *atomic.Bool) {
|
||||
t.Helper()
|
||||
asked, texts, down = &atomic.Int32{}, &[]string{}, &atomic.Bool{}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
asked.Add(1)
|
||||
if down.Load() {
|
||||
http.Error(w, "down", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
text := r.URL.Query().Get("text")
|
||||
*texts = append(*texts, text)
|
||||
list := popular
|
||||
if text != "keywords:pi-package" {
|
||||
list = found
|
||||
}
|
||||
if r.URL.Query().Get("from") != "0" {
|
||||
list = nil
|
||||
}
|
||||
fmt.Fprintf(w, `{"total":%d,"objects":[%s]}`, len(list), strings.Join(list, ","))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
was := piNPMURL
|
||||
piNPMURL = srv.URL
|
||||
t.Cleanup(func() { piNPMURL = was })
|
||||
piForget(t)
|
||||
return asked, texts, down
|
||||
}
|
||||
|
||||
func piForget(t *testing.T) {
|
||||
piPopular.Lock()
|
||||
piPopular.list, piPopular.at = nil, time.Time{}
|
||||
piPopular.Unlock()
|
||||
t.Cleanup(func() {
|
||||
piPopular.Lock()
|
||||
piPopular.list, piPopular.at = nil, time.Time{}
|
||||
piPopular.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
// piCacheHere gives the test a cache folder of its own on every system:
|
||||
// XDG_CACHE_HOME (Linux) is shared by the whole binary otherwise, and
|
||||
// LOCALAPPDATA (Windows) is blank in a sandbox.
|
||||
func piCacheHere(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", d)
|
||||
t.Setenv("LOCALAPPDATA", d)
|
||||
}
|
||||
|
||||
func npmObject(name, desc, repo string, monthly int, keywords ...string) string {
|
||||
if keywords == nil {
|
||||
keywords = []string{"pi-package"}
|
||||
}
|
||||
kw, _ := json.Marshal(keywords)
|
||||
return fmt.Sprintf(`{"downloads":{"monthly":%d,"weekly":1},"package":{"name":%q,"version":"1.2.3","description":%q,"keywords":%s,"date":"2026-11-01T10:00:00.000Z","publisher":{"username":"pub"},"links":{"repository":%q,"homepage":"https://example.dev/%s"}}}`,
|
||||
monthly, name, desc, kw, repo, name)
|
||||
}
|
||||
|
||||
func piNames(list []PiMarketPackage) []string {
|
||||
var out []string
|
||||
for _, p := range list {
|
||||
out = append(out, p.Name)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// nineruiing on X asked for a market of Pi's packages. Before a search it
|
||||
// offers npm's packages with Pi's keyword, the most downloaded first (as
|
||||
// Pi's gallery reads them); one without the keyword, or whose name would
|
||||
// read as a flag, is never offered. A search adds npm's own matches.
|
||||
func TestPiMarketFromNPM(t *testing.T) {
|
||||
sandbox(t)
|
||||
piCacheHere(t)
|
||||
_, texts, down := piNPM(t, []string{
|
||||
npmObject("pi-small", "A small one.", "git+https://github.com/small/pi-small.git", 10),
|
||||
npmObject("@big/pi-web", "Web search for Pi.", "git+https://github.com/big/pi-web.git", 5000),
|
||||
npmObject("not-pi", "Has the word only.", "", 9999, "other"),
|
||||
npmObject("-flag", "A flag.", "", 8000),
|
||||
npmObject("pi-mid", "Middle.", "git+ssh://git@example.com/x.git", 300),
|
||||
}, []string{
|
||||
npmObject("pi-web-extra", "Found by a search.", "", 1),
|
||||
npmObject("@big/pi-web", "Web search for Pi.", "git+https://github.com/big/pi-web.git", 5000),
|
||||
})
|
||||
|
||||
list, err := MarketPiPackages("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := piNames(list); !slices.Equal(got, []string{"@big/pi-web", "pi-mid", "pi-small"}) {
|
||||
t.Fatalf("popular = %v", got)
|
||||
}
|
||||
web := list[0]
|
||||
if web.Source != "npm:@big/pi-web" || web.Icon != gh("big") || web.Repo != "https://github.com/big/pi-web" ||
|
||||
web.NPM != "https://www.npmjs.com/package/@big/pi-web" || web.Downloads != 5000 || web.Updated != "2026-11-01" {
|
||||
t.Errorf("card = %+v", web)
|
||||
}
|
||||
if list[1].Repo != "" || list[1].Icon != "" {
|
||||
t.Errorf("an ssh repository made a link or an icon: %+v", list[1])
|
||||
}
|
||||
if !offered(web.Icon) {
|
||||
t.Error("the icon proxy refuses the market's own icon")
|
||||
}
|
||||
|
||||
list, err = MarketPiPackages("web")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := piNames(list); !slices.Equal(got, []string{"@big/pi-web", "pi-web-extra"}) {
|
||||
t.Errorf("search = %v", got)
|
||||
}
|
||||
if !slices.Contains(*texts, "keywords:pi-package web") {
|
||||
t.Errorf("npm was asked %q", *texts)
|
||||
}
|
||||
|
||||
// npm not answering a search: the popular ones that match, and which
|
||||
// source failed
|
||||
down.Store(true)
|
||||
list, err = MarketPiPackages("small")
|
||||
var se *SearchError
|
||||
if !errors.As(err, &se) || se.Source != "npm" {
|
||||
t.Errorf("err = %v, want npm's SearchError", err)
|
||||
}
|
||||
if got := piNames(list); !slices.Equal(got, []string{"pi-small"}) {
|
||||
t.Errorf("with npm down = %v", got)
|
||||
}
|
||||
|
||||
// kept on disk: a later start with npm down has the same list
|
||||
piForget(t)
|
||||
if got := piNames(func() []PiMarketPackage { l, _ := MarketPiPackages(""); return l }()); !slices.Equal(got, []string{"@big/pi-web", "pi-mid", "pi-small"}) {
|
||||
t.Errorf("from the disk cache = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// With npm down and nothing on disk, the market is the snapshot magpie
|
||||
// shipped with, not empty.
|
||||
func TestPiMarketSnapshot(t *testing.T) {
|
||||
sandbox(t)
|
||||
piCacheHere(t)
|
||||
_, _, down := piNPM(t, nil, nil)
|
||||
down.Store(true)
|
||||
list, _ := MarketPiPackages("")
|
||||
if len(list) < 100 || !slices.Contains(piNames(list), "pi-mcp-adapter") {
|
||||
t.Fatalf("snapshot = %d packages", len(list))
|
||||
}
|
||||
for i := 1; i < len(list); i++ {
|
||||
if list[i].Downloads > list[i-1].Downloads {
|
||||
t.Fatalf("snapshot isn't by downloads at %d: %v then %v", i, list[i-1], list[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func piSettingsPackages(t *testing.T, dir string) []any {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "settings.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var s struct{ Packages []any }
|
||||
if err := json.Unmarshal(raw, &s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s.Packages
|
||||
}
|
||||
|
||||
// piFake stands for the pi command of this machine's Pi: what it was run
|
||||
// with, and settings.json changed as `pi install` and `pi remove` change it.
|
||||
func piFake(t *testing.T) *[][]string {
|
||||
t.Helper()
|
||||
runs := &[][]string{}
|
||||
wasBin, wasRun := piBin, piRun
|
||||
piBin = func(p piPlace) string {
|
||||
if p.a.WSL != "" {
|
||||
return ""
|
||||
}
|
||||
return "/fake/pi"
|
||||
}
|
||||
piRun = func(bin, dir string, args ...string) (string, error) {
|
||||
*runs = append(*runs, append([]string{bin, dir}, args...))
|
||||
p := piPlace{dir: dir}
|
||||
s, err := p.settings()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
next := []json.RawMessage{}
|
||||
id := p.piIdentity(args[1])
|
||||
for _, r := range s.pkgs {
|
||||
if x, ok := piPackageOf(r); !ok || p.piIdentity(x.Source) != id {
|
||||
next = append(next, r)
|
||||
}
|
||||
}
|
||||
if args[0] == "install" {
|
||||
b, _ := json.Marshal(args[1])
|
||||
next = append(next, b)
|
||||
}
|
||||
return "", edit.SetJSON(p.settingsPath(), edit.KV{Path: "packages", Value: next})
|
||||
}
|
||||
t.Cleanup(func() { piBin, piRun = wasBin, wasRun })
|
||||
return runs
|
||||
}
|
||||
|
||||
// This machine's Pi gets a package by `pi install npm:<name>` run for its
|
||||
// own agent folder, and loses it by `pi remove`; a Pi in WSL gets the
|
||||
// settings.json entry, which Pi installs when it next starts, and loses
|
||||
// every entry of that package. One a Pi has already, or a source that
|
||||
// isn't an npm package's name, is refused before anything runs.
|
||||
func TestPiInstallAndRemove(t *testing.T) {
|
||||
here, wsl := piTwo(t)
|
||||
runs := piFake(t)
|
||||
write(t, filepath.Join(here, "settings.json"), `{"theme": "dark", "packages": ["git:github.com/a/b"]}`)
|
||||
write(t, filepath.Join(wsl, "settings.json"), `{"packages": [{"source": "npm:pi-foo@1.0.0", "skills": []}, "npm:keep"]}`)
|
||||
|
||||
v, err := InstallPiPackage("pi", "npm:@scope/pi-foo")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v.Pending || len(*runs) != 1 || !slices.Equal((*runs)[0], []string{"/fake/pi", here, "install", "npm:@scope/pi-foo"}) {
|
||||
t.Fatalf("pending %v, runs %q", v.Pending, *runs)
|
||||
}
|
||||
if p := piOf(t, v.PiExtensions, "pi"); len(p.Packages) != 2 || p.Packages[1].Source != "npm:@scope/pi-foo" {
|
||||
t.Errorf("packages = %+v", p.Packages)
|
||||
}
|
||||
if _, err := InstallPiPackage("pi", "npm:@scope/pi-foo"); err == nil || !strings.Contains(err.Error(), "already") {
|
||||
t.Errorf("installed twice: %v", err)
|
||||
}
|
||||
for _, bad := range []string{"npm:-g", "npm:--prefix=/x", "git:github.com/a/b", "pi-foo", "npm:../x", "npm:a b"} {
|
||||
if _, err := InstallPiPackage("pi", bad); err == nil {
|
||||
t.Errorf("%q installed", bad)
|
||||
}
|
||||
}
|
||||
if len(*runs) != 1 {
|
||||
t.Errorf("pi ran for a refused install: %q", *runs)
|
||||
}
|
||||
|
||||
v, err = InstallPiPackage("pi@wsl:Ubuntu", "npm:pi-bar")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !v.Pending || len(*runs) != 1 {
|
||||
t.Errorf("WSL install: pending %v, runs %q", v.Pending, *runs)
|
||||
}
|
||||
if got := piSettingsPackages(t, wsl); len(got) != 3 || got[2] != "npm:pi-bar" {
|
||||
t.Errorf("WSL packages = %#v", got)
|
||||
}
|
||||
if _, err := InstallPiPackage("pi@wsl:Ubuntu", "npm:pi-foo"); err == nil {
|
||||
t.Error("a package the Pi has under another pin installed again")
|
||||
}
|
||||
|
||||
if _, err := RemovePiPackage("pi", "npm:@scope/pi-foo"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(*runs) != 2 || !slices.Equal((*runs)[1], []string{"/fake/pi", here, "remove", "npm:@scope/pi-foo"}) {
|
||||
t.Errorf("runs %q", *runs)
|
||||
}
|
||||
if got := piSettingsPackages(t, here); len(got) != 1 || got[0] != "git:github.com/a/b" {
|
||||
t.Errorf("packages after remove = %#v", got)
|
||||
}
|
||||
v, err = RemovePiPackage("pi@wsl:Ubuntu", "npm:pi-foo")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !v.Pending {
|
||||
t.Error("a WSL removal isn't said to wait for Pi")
|
||||
}
|
||||
if got := piSettingsPackages(t, wsl); len(got) != 2 || got[0] != "npm:keep" || got[1] != "npm:pi-bar" {
|
||||
t.Errorf("WSL packages after remove = %#v", got)
|
||||
}
|
||||
if _, err := RemovePiPackage("pi", "npm:nothing"); err == nil {
|
||||
t.Error("removed a package the Pi doesn't have")
|
||||
}
|
||||
if _, err := RemovePiPackage("pi", "-l"); err == nil {
|
||||
t.Error("a flag taken for a package")
|
||||
}
|
||||
raw, _ := os.ReadFile(filepath.Join(here, "settings.json"))
|
||||
if !strings.Contains(string(raw), `"theme": "dark"`) {
|
||||
t.Errorf("the user's other settings lost: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// A settings.json that can't be read is unknown: nothing is installed into
|
||||
// it or removed from it, and pi isn't run.
|
||||
func TestPiInstallUnreadSettings(t *testing.T) {
|
||||
here, _ := piTwo(t)
|
||||
runs := piFake(t)
|
||||
bad := `{"packages": ["npm:a", ` // cut short
|
||||
write(t, filepath.Join(here, "settings.json"), bad)
|
||||
if _, err := InstallPiPackage("pi", "npm:pi-foo"); err == nil {
|
||||
t.Error("installed into an unreadable settings.json")
|
||||
}
|
||||
if _, err := RemovePiPackage("pi", "npm:a"); err == nil {
|
||||
t.Error("removed from an unreadable settings.json")
|
||||
}
|
||||
if raw, _ := os.ReadFile(filepath.Join(here, "settings.json")); string(raw) != bad || len(*runs) != 0 {
|
||||
t.Errorf("settings now %s, runs %q", raw, *runs)
|
||||
}
|
||||
}
|
||||
|
||||
// pi install that exits 0 but doesn't add the package is an error, not a
|
||||
// package said to be there.
|
||||
func TestPiInstallNotListedAfter(t *testing.T) {
|
||||
here, _ := piTwo(t)
|
||||
piFake(t)
|
||||
piRun = func(bin, dir string, args ...string) (string, error) { return "", nil }
|
||||
write(t, filepath.Join(here, "settings.json"), `{}`)
|
||||
if _, err := InstallPiPackage("pi", "npm:pi-foo"); err == nil || !strings.Contains(err.Error(), "doesn't list it") {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The real run: pi is given the Pi's agent folder as PI_CODING_AGENT_DIR,
|
||||
// runs in it, and has nothing to answer it.
|
||||
func TestPiRunGivesAgentDir(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a shell script stands for pi")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
bin := filepath.Join(t.TempDir(), "pi")
|
||||
testenv.Program(t, bin, "#!/bin/sh\necho \"$PI_CODING_AGENT_DIR|$(pwd -P)|$*\" > \"$PI_CODING_AGENT_DIR/ran\"\nread x && echo stdin >> \"$PI_CODING_AGENT_DIR/ran\"\nexit 0\n")
|
||||
if _, err := piRun(bin, dir, "install", "npm:pi-foo"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "ran"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
real, _ := filepath.EvalSymlinks(dir)
|
||||
if want := dir + "|" + real + "|install npm:pi-foo\n"; string(raw) != want {
|
||||
t.Errorf("pi ran as %q, want %q", raw, want)
|
||||
}
|
||||
testenv.Program(t, bin, "#!/bin/sh\necho 'npm ERR! 404 Not Found' >&2\nexit 1\n")
|
||||
if _, err := piRun(bin, dir, "install", "npm:nope"); err == nil || !strings.Contains(err.Error(), "404") {
|
||||
t.Errorf("err = %v, want npm's own words", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user