library: Pi's extensions and packages, switched and copied between Pis

leokon3 runs Pi on Windows and in WSL and asked for magpie's Library to
manage Pi's extensions and packages. A new "Pi packages" tab in the
Library lists each Pi here (this computer's and each WSL distro's), with
the extensions and packages it loads, read by Pi's own rules
(@earendil-works/pi-coding-agent 1.4.0). Each has a switch, written as
`pi config` writes it, and a "Copy to…" menu for the other running Pis.

- A package is copied as its settings.json entry; Pi installs it itself
  when it next starts. node_modules is never copied. A local package, and
  one the other Pi already has by Pi's identity (npm name, git host/path),
  is refused.
- An extension file or folder is copied as files, without node_modules,
  .git or symlinks, never over one of the same name. The page says to run
  npm install there when it has dependencies.
- A package that already picks some parts (filtered in `pi config`) shows
  its switch disabled. A settings.json that can't be parsed lists nothing
  and is never written; a stopped distro is never started; every write is
  backed up first.
- GET/POST /api/library/pi, POST /api/library/pi/copy (notYet in the CLI
  parity list, stage 3: the library).

Run at 29d63e2dd (this tree on origin/main c7ebb6f8d; rebased after onto
608c1543e, which changes only internal/gateway), on mote:
- gofmt -l clean; go vet -tags nogui for darwin, linux and windows on
  internal/library and internal/gui: ok.
- go test -tags nogui ./internal/library ./internal/gui ./internal/cli:
  ok, ok, ok.
- A real pi 1.4.0 (npm) in a sandbox HOME and PI_CODING_AGENT_DIR, through
  an uncommitted pireal test: pi -p loads hello.ts (a marker file), the
  switch turns it off (no marker) and on again; a todo folder copied from
  a second Pi's dir is loaded by the real pi; npm:pi-web-access@0.47.0
  copied as a settings entry was installed by pi itself into
  <agentDir>/npm/node_modules and read back as installed v0.47.0; switched
  off, `pi list` still lists it and magpie reads it off.
- GUI, 70 files (library-*, i18n-*, gui-* and the Library's neighbours),
  both engines: 1503 of 1515 pass. The 12 reds are the same on origin/main
  c7ebb6f8d: page-width-steady's 11 (run there alone, 11 of 20 red; #5013)
  and i18n-keys "a plugin's words are its own" for "Use the library's",
  "No session ID" and "View routing" (#5482, #5426, #5332).
  library-pi-extensions runs en, zh, zh-TW, ja and de at 980 and 380px.
On Windows (win-run): go vet with and without the pireal tag ok; go test
-run TestPi ./internal/library ok.

Broken by hand: the first run named the tab "Pi extensions", which a
comment in internal/provider/discovery.go says too, and i18n-keys went
red for it; library-loading went red for the new tab next to RTK while a
Pi is here; and TestEveryRouteHasACommandOrIsNamed went red for the three
routes. All three were fixed and pass in the run above.

Not tried: a real copy between a WSL Pi and the Windows Pi (the WSL side
is covered by the unit tests' fake distro only), the full go test ./...,
and the whole GUI suite.

Reported-by: leokon3 (Discord)
This commit is contained in:
yetone
2026-11-09 16:33:28 +08:00
parent 608c1543e8
commit b475004d52
10 changed files with 1776 additions and 2 deletions
+5 -1
View File
@@ -7,7 +7,8 @@ the subagents it can hand a task to.
magpie writes these into each agent's own
files in that agent's format, and takes back only what it wrote. Everything
else in those files stays as it was. Package `internal/library` also gives
agents RTK, a CLI that cuts shell output down before the model reads it.
agents RTK, a CLI that cuts shell output down before the model reads it,
and lists, switches and copies each Pi's extensions and packages.
## Responsibilities and sources of truth
@@ -33,6 +34,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
| Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) |
| RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. Factory's Droid (lml0664 on Discord) gets rtk's own `rtk init -g --agent droid`, given Droid's folder as `FACTORY_HOME_OVERRIDE`; rtk puts its `Execute` group (`rtk hook droid`) in the root `hooks.json`, or in `settings.json`'s `hooks.PreToolUse` where Droid's hooks already are, so `droidHookFiles` reads and switches off all three places rtk 1.1.0 may use (`hooks.json`, `hooks/hooks.json`, `settings.json`), leaving the user's own hooks. rtk before 0.44 has no Droid agent, so it is `blocked` (`droidBlocked`). A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off; Qoder and Qoder CN: rtk 1.1.0 has no Qoder agent; Cline and Kimi Code: `rtk init --agent cline|kimi` writes only one project's `.clinerules` or `AGENTS.md`, instructions with no hook, and Kimi's refuses `-g`). RTK 1.1.0's Trae, Windsurf, Kilo Code and Mistral Vibe have no magpie agent. The page's No RTK hook tag gives each agent's own reason and rtk-ai/rtk issue (`rtkNoHookWhy` in plugins/library/client.js: dsh #3847, Grok Build and Grok App #2136, Qoder and Qoder CN #1327, Cline #3841), and an agent with no entry gets no link; `TestRTKNoHookIssuesAreEachAgents` fails when the page and `rtkNoHook` cite different issues, or two agents cite the same ones without a reason in `sharedRTKIssues`. | [`rtk.go`](../../internal/library/rtk.go) |
| RTK in WSL | An agent in a WSL distro (`claude@wsl:Ubuntu`) is listed by its kind (`rtkKind`), and its hook runs in the distro, where Windows' rtk.exe is no command, so it gets the distro's own rtk (lex on Discord). `rtkDistroOf` asks the distro with `wsl.exe -d <distro> -e sh -lc` where rtk is (a login or interactive shell's PATH; else `~/.local/bin` or `~/.cargo/bin`, `offPath`), kept 15s; `ReadRTK` lists one `RTKDistro` for each distro its agents are in. Install RTK in WSL `<distro>` (`InstallRTKIn`, `POST /api/library/rtk/install` with `distro`, `magpie library rtk install <distro>`) runs RTK's own Linux installer in the distro (`curl -fsSL …/install.sh \| sh`, wget where there's no curl). Switching an agent on runs the distro's rtk there (`rtkInstallWSL`: `rtk init -g …` with its folder on PATH, Claude Code pointed at a folder of its own for the OpenCode and Cursor installers), and reads and edits its files under the distro's home as magpie opens it (`rtkClaudeDir`, `rtkCodexDir`, `rtkHome`). A distro that isn't running is never started (#3896): `rtkWSLLive` and `rtkDistroOf` check `agent.WSLRunning` first, its agents are listed `asleep` with the switch off, and switching or installing says to start it (`TestRTKWSLAsleep`). The page gives each distro a card (`rtkDistroCard` in plugins/library/client.js; library-rtk-wsl.test.cjs). | [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) |
| Pi extensions | Each Pi here, this computer's and each WSL distro's (`piPlaces`), with the extensions and packages it loads, read by Pi's own rules (`@earendil-works/pi-coding-agent` 1.4: `resolveExtensionEntries`, `isEnabledByOverrides`, `applyPatterns`). An extension is a `.ts`/`.js` file or a folder (package.json `pi.extensions`, else `index.ts`, else `index.js`) in `<agentDir>/extensions`, or a path its settings.json `extensions` lists; a package is an entry of settings.json `packages`. Built-in extensions (`builtin:mcp` and the rest) aren't listed: `builtin:mcp` carries the MCP servers magpie gives Pi. `SetPiExtension` writes what `pi config` writes (`-path` off; the `-` taken out and `+path` only where still excluded, on); `SetPiPackage` sets a package's four filters to `[]` (off) or takes them out (on), and refuses an entry that already picks some parts (`filtered`, changed in `pi config`). `CopyPi` gives a package to another Pi as its settings.json entry, which Pi installs itself when it next starts (npm into `<agentDir>/npm`, git into `<agentDir>/git`), never as copied files; it refuses a local package, and one the other Pi has already by Pi's identity (npm name, git host/path). An extension is copied as its file or folder into the other's `extensions`, leaving out `node_modules`, `.git` and symlinks, never over one of the same name, and the page says to run `npm install` there when it has dependencies (leokon3 on Discord). A settings.json that can't be parsed lists nothing and is never written; a stopped distro is never started (`asleep`); every write is backed up first. `GET`/`POST /api/library/pi`, `POST /api/library/pi/copy`; the Library's Pi packages tab, shown while a Pi is here (`renderPi` in plugins/library/client.js; library-pi-extensions.test.cjs). | [`piext.go`](../../internal/library/piext.go) |
## Runtime path
@@ -108,6 +110,8 @@ go test -race ./internal/mcpauth
go test -tags nogui ./internal/library
go test -tags nogui ./internal/library -run 'TestWSLStopped'
go test -tags nogui ./internal/library -run 'TestRTKWSL'
go test -tags nogui ./internal/library -run 'TestPi'
node --test internal/gui/tests/library-pi-extensions.test.cjs
node --test internal/gui/tests/library-rtk-wsl.test.cjs
node --test internal/gui/tests/library-wsl-asleep.test.cjs
node --test internal/gui/tests/skill-off-here.test.cjs internal/gui/tests/mcp-local-server.test.cjs internal/gui/tests/skill-handover.test.cjs
+3
View File
@@ -341,6 +341,7 @@ var notYet = map[string]string{
"GET /api/library/market/servers": L, // library.go
"GET /api/library/market/skills": 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
"GET /api/library/skill": L, // library.go
"POST /api/library/market/about": L, // library.go
@@ -349,6 +350,8 @@ var notYet = map[string]string{
"POST /api/library/mcp-signout": L, // library.go
"POST /api/library/mcp/check": L, // library.go
"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/projects/choose": W, // library.go
"POST /api/library/reveal": W, // library.go
"POST /api/library/rtk": L, // library.go
@@ -535,6 +535,7 @@ magpie.plugin("library", (ctx) => {
// drawn over again replaced the row under the reader's pointer (#3099)
if (quiet === "open" && seen(lib) === was && tab !== "rtk" && page.querySelector(":scope > .lib-body")) return;
rtk = null; // asked again when its tab is drawn: an agent may have been installed since
piView = null;
render();
} catch (e) {
status(e.message, "err");
@@ -809,6 +810,8 @@ magpie.plugin("library", (ctx) => {
box.append(card, head("60px"), rows(6, true));
} else if (which === "rtk") {
box.append(rows(1, false), head("60px"), rows(5, true));
} else if (which === "pi") {
box.append(head("60px"), rows(4, true));
} else {
box.append(rows(5, true));
}
@@ -821,6 +824,8 @@ magpie.plugin("library", (ctx) => {
// RTK's count read afresh each time its tab is opened: an agent run
// since adds to it (#741); the page keeps the last one until then
if (id === "rtk" && rtk) loadRTK();
// Pi's extensions too: one installed or changed outside magpie since
if (id === "pi" && piView) loadPi();
if (!lib) return page.querySelector(":scope > .lib-skel")?.replaceWith(skeleton(id));
render(); syncLists();
}
@@ -837,6 +842,7 @@ magpie.plugin("library", (ctx) => {
["hooks", t("Hooks") + n("hooks")],
["subagents", t("Subagents") + n("subagents")],
["rtk", "RTK"],
...(hasPi() ? [["pi", t("Pi packages")]] : []),
], tab, openTab);
tabs.classList.add("lib-tabs");
head.append(tabs);
@@ -890,6 +896,8 @@ magpie.plugin("library", (ctx) => {
// the MCP servers alone with no agent to write to; the tab the reader
// last picked is kept for when there is one
if (agentless()) tab = "mcp";
// Pi's tab only while a Pi is here; the pick is kept for when one is
else if (tab === "pi" && !hasPi()) tab = "instructions";
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, subagents: (lib.subagents || []).length });
page.append(head);
head.classList.toggle("stuck", top > 0);
@@ -902,6 +910,7 @@ magpie.plugin("library", (ctx) => {
if (tab === "instructions") renderInstructions(body);
else if (tab === "mcp") renderServers(body);
else if (tab === "rtk") renderRTK(body);
else if (tab === "pi") renderPi(body);
else if (tab === "hooks") renderHooks(body);
else if (tab === "subagents") renderSubagents(body);
else renderSkills(body);
@@ -1123,6 +1132,119 @@ magpie.plugin("library", (ctx) => {
rtkBusy.delete(a.id);
render();
}
// ---------- Pi extensions ----------
// Each Pi here (this computer's, and each WSL distro's) with the
// extensions and packages it loads (piext.go). One is switched off or on
// in its settings.json the way `pi config` does it, and copied to
// another Pi: a package as its entry in that Pi's settings.json, which
// Pi installs itself when it starts; an extension as its file or folder.
// leokon3 on Discord: moving an extension from the WSL Pi to Windows'.
const hasPi = () => !!lib && !gatewayPage() && lib.agents.some((a) => a.id.split("@")[0] === "pi" && !a.gone && !a.unseen && !isHidden(a));
let piView = null; // /api/library/pi
const piBusy = new Set(); // "<pi> <ext or package>" being switched or copied
let piLoading = false;
async function loadPi() {
if (piLoading) return;
piLoading = true;
try {
piView = await api("library/pi");
} catch (e) {
status(e.message, "err");
}
piLoading = false;
if (tab === "pi" && piView) render();
}
function renderPi(body) {
body.append(intro(t("The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts.")));
if (!piView) {
body.append(el("div", "row skeleton"));
loadPi();
return;
}
const pis = (piView.pis || []).filter((p) => !isHidden({ id: p.id }));
const live = pis.filter((p) => !p.asleep && !p.err);
for (const p of pis) {
const rh = el("div", "row-head lib-pi-head");
rh.dataset.pi = p.id;
rh.append(el("span", "label", p.name), el("span", "grow"));
if (p.dir && !p.asleep) rh.append(pathLink(p.dir));
body.append(rh);
const list = el("div", "list lib-list lib-pi");
list.dataset.pi = p.id;
const others = live.filter((x) => x.id !== p.id);
if (p.asleep) {
list.append(el("div", "lib-none", t("WSL {distro} isn't running: magpie doesn't start it to read or change {agent}. Start the distro, then Check again.", { distro: p.wsl, agent: p.name })));
} else if (p.err) {
list.append(el("div", "lib-none lib-pi-err", t("magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}", { file: "settings.json", why: p.err })));
} else {
for (const x of p.extensions || []) list.append(piRow(p, others, { ext: x.id }, x.name, tilde(x.path), x.on, null));
for (const k of p.packages || []) {
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));
}
if (!(p.extensions || []).length && !(p.packages || []).length) list.append(el("div", "lib-none", t("No extensions or packages yet.")));
}
body.append(list);
}
}
function piRow(p, others, what, name, sub, on, tags, filtered) {
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;
const who = el("div", "who");
const n = el("div", "name mono", name);
for (const g of tags || []) n.append(g);
who.append(n, el("div", "sub mono", sub));
row.append(who);
if (others.length) {
const b = button(t("Copy to…"), "lib-pi-copy", () => {
openProtoMenu(b, others.map((x) => ({ v: x.id, name: x.name, literalName: true, note: "" })), "", (to) => copyPi(p, others.find((x) => x.id === to), what, name), "Copy to another Pi", "", "right");
});
b.disabled = piBusy.has(key);
row.append(b);
}
const sw = toggle(on, t("{agent} loads {name}", { agent: p.name, name }), (v) => setPi(p, what, name, v));
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);
return row;
}
async function setPi(p, what, name, on) {
const key = p.id + " " + (what.ext || what.pkg);
piBusy.add(key);
render();
try {
piView = await api("library/pi", { pi: p.id, ...what, on });
status(on ? t("{name} is on for {agent}: Pi loads it when it next starts, or at /reload", { name, agent: p.name }) : t("{name} is off for {agent}: Pi drops it when it next starts, or at /reload", { name, agent: p.name }), "ok", 6000);
} catch (e) {
status(e.message, "err", 8000);
}
piBusy.delete(key);
render();
}
async function copyPi(p, to, what, name) {
if (!to) return;
const key = p.id + " " + (what.ext || what.pkg);
piBusy.add(key);
render();
try {
const v = await api("library/pi/copy", { from: p.id, to: to.id, ...what });
piView = v;
status(what.pkg
? t("{name} is in {agent}'s packages now: Pi installs it when it next starts", { name, agent: to.name })
: v.install
? t("{name} is copied to {agent}. It needs its packages: run npm install in {dir} there", { name, agent: to.name, dir: v.install })
: t("{name} is copied to {agent}: Pi loads it when it next starts, or at /reload", { name, agent: to.name }), "ok", v.install ? 12000 : 6000);
} catch (e) {
status(e.message, "err", 8000);
}
piBusy.delete(key);
render();
}
// what rtk saved day by day (week by week past 92 days), over the last
// 30 or 90 days or since it first ran: each bar the commands' whole
// output, the part RTK kept from the model on top of what still went
@@ -827,6 +827,20 @@ magpie.strings({
"WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} 未运行:点一下,{agent} 会在该发行版下次运行时启用",
"WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.": "WSL {distro} 未运行:其中的 Agent 显示的是 magpie 上次看到的内容,你的修改会在它下次运行时写入。",
"{agents} can be changed once it runs.": "{agents} 要等它运行后才能修改。",
"Pi packages": "Pi 包",
"The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts.": "每个 Pi 加载的扩展和包。可以关闭其中一个,或复制到另一个 Pi:包会加入那个 Pi 的设置,Pi 下次启动时自行安装。",
"magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}": "magpie 无法读取 {file},因此这里不列出也不更改任何内容:{why}",
"Pi installs it when it next starts": "Pi 下次启动时安装它",
"No extensions or packages yet.": "还没有扩展或包。",
"Copy to…": "复制到…",
"Copy to another Pi": "复制到另一个 Pi",
"{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 时加载它",
"{name} is off for {agent}: Pi drops it when it next starts, or at /reload": "{name} 已为 {agent} 关闭:Pi 下次启动或 /reload 时不再加载它",
"{name} is in {agent}'s packages now: Pi installs it when it next starts": "{name} 已加入 {agent} 的包:Pi 下次启动时安装它",
"{name} is copied to {agent}. It needs its packages: run npm install in {dir} there": "{name} 已复制到 {agent}。它需要自己的依赖包:请在那里的 {dir} 中运行 npm install",
"{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} 已复制到 {agent}:Pi 下次启动或 /reload 时加载它",
},
"zh-TW": {
"Skill router": "Skill 路由",
@@ -1654,6 +1668,20 @@ magpie.strings({
"WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} 未執行:點一下,{agent} 會在該發行版下次執行時啟用",
"WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.": "WSL {distro} 未執行:其中的 Agent 顯示的是 magpie 上次看到的內容,你的修改會在它下次執行時寫入。",
"{agents} can be changed once it runs.": "{agents} 要等它執行後才能修改。",
"Pi packages": "Pi 套件",
"The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts.": "每個 Pi 載入的擴充和套件。可以關閉其中一個,或複製到另一個 Pi:套件會加入那個 Pi 的設定,Pi 下次啟動時自行安裝。",
"magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}": "magpie 無法讀取 {file},因此這裡不列出也不變更任何內容:{why}",
"Pi installs it when it next starts": "Pi 下次啟動時安裝它",
"No extensions or packages yet.": "還沒有擴充或套件。",
"Copy to…": "複製到…",
"Copy to another Pi": "複製到另一個 Pi",
"{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 時載入它",
"{name} is off for {agent}: Pi drops it when it next starts, or at /reload": "{name} 已為 {agent} 關閉:Pi 下次啟動或 /reload 時不再載入它",
"{name} is in {agent}'s packages now: Pi installs it when it next starts": "{name} 已加入 {agent} 的套件:Pi 下次啟動時安裝它",
"{name} is copied to {agent}. It needs its packages: run npm install in {dir} there": "{name} 已複製到 {agent}。它需要自己的相依套件:請在那裡的 {dir} 中執行 npm install",
"{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} 已複製到 {agent}:Pi 下次啟動或 /reload 時載入它",
},
ja: {
"Skill router": "スキルルーター",
@@ -2481,6 +2509,20 @@ magpie.strings({
"WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} は起動していません。クリックすると、ディストリビューションが次に起動したときに {agent} に追加されます",
"WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.": "WSL {distro} は起動していません。そのエージェントは magpie が最後に見た内容で表示され、変更は次に起動したときに書き込まれます。",
"{agents} can be changed once it runs.": "{agents} は起動後に変更できます。",
"Pi packages": "Pi パッケージ",
"The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts.": "各 Pi が読み込む拡張機能とパッケージです。オフにしたり、別の Pi にコピーしたりできます。パッケージはその Pi の設定に追加され、Pi が次回起動時に自分でインストールします。",
"magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}": "magpie は {file} を読めなかったため、ここでは何も表示も変更もしません: {why}",
"Pi installs it when it next starts": "Pi が次回起動時にインストールします",
"No extensions or packages yet.": "拡張機能もパッケージもまだありません。",
"Copy to…": "コピー先…",
"Copy to another Pi": "別の Pi にコピー",
"{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 で読み込みます",
"{name} is off for {agent}: Pi drops it when it next starts, or at /reload": "{agent} で {name} をオフにしました。Pi は次回起動時か /reload で外します",
"{name} is in {agent}'s packages now: Pi installs it when it next starts": "{name} を {agent} のパッケージに追加しました。Pi が次回起動時にインストールします",
"{name} is copied to {agent}. It needs its packages: run npm install in {dir} there": "{name} を {agent} にコピーしました。依存パッケージが必要です: そちらの {dir} で npm install を実行してください",
"{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} を {agent} にコピーしました。Pi は次回起動時か /reload で読み込みます",
},
de: {
"Skill router": "Skill-Router",
@@ -3308,5 +3350,19 @@ magpie.strings({
"WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} läuft nicht: Ein Klick gibt es {agent}, sobald die Distribution das nächste Mal läuft",
"WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.": "WSL {distro} läuft nicht: Seine Agenten zeigen, was magpie dort zuletzt gesehen hat, und Änderungen werden beim nächsten Start dorthin geschrieben.",
"{agents} can be changed once it runs.": "{agents} lässt sich ändern, sobald sie läuft.",
"Pi packages": "Pi-Pakete",
"The extensions and packages each Pi loads. Switch one off, or copy it to another Pi: a package is added to that Pi's settings, and Pi installs it when it next starts.": "Die Erweiterungen und Pakete, die jedes Pi lädt. Schalte eine aus oder kopiere sie zu einem anderen Pi: Ein Paket wird in dessen Einstellungen eingetragen, und Pi installiert es beim nächsten Start.",
"magpie couldn't read {file}, so it lists nothing and changes nothing there: {why}": "magpie konnte {file} nicht lesen, listet dort daher nichts und ändert nichts: {why}",
"Pi installs it when it next starts": "Pi installiert es beim nächsten Start",
"No extensions or packages yet.": "Noch keine Erweiterungen oder Pakete.",
"Copy to…": "Kopieren nach…",
"Copy to another Pi": "Zu einem anderen Pi kopieren",
"{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",
"{name} is off for {agent}: Pi drops it when it next starts, or at /reload": "{name} ist für {agent} aus: Pi lässt es beim nächsten Start oder bei /reload weg",
"{name} is in {agent}'s packages now: Pi installs it when it next starts": "{name} ist jetzt in den Paketen von {agent}: Pi installiert es beim nächsten Start",
"{name} is copied to {agent}. It needs its packages: run npm install in {dir} there": "{name} ist nach {agent} kopiert. Es braucht seine Pakete: Führe dort in {dir} npm install aus",
"{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} ist nach {agent} kopiert: Pi lädt es beim nächsten Start oder bei /reload",
},
});
@@ -855,3 +855,7 @@ body.window .lib-list .lib-row { --lib-indent: 38px; }
.lib-foundmore span { display: inline-flex; }
.lib-foundmore.open .chev { transform: rotate(180deg); }
@media (hover: hover) and (pointer: fine) { .lib-foundmore:hover { color: var(--fg); background: var(--card-2); } }
/* Pi's extensions: a heading per Pi, its path beside it */
.lib-pi-head > .lib-path { flex: 0 1 auto; min-width: 0; }
.lib-pi-row > .lib-pi-copy { flex: none; }
.lib-pi + .lib-pi-head { margin-top: 18px; }
+44
View File
@@ -274,6 +274,50 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
Regrouped int `json:"regrouped"`
}{v, n})
})
// Pi's extensions and packages, for each Pi here (this computer's and
// each WSL distro's): switched on or off as Pi itself does it, and
// copied from one Pi to another
mux.HandleFunc("GET /api/library/pi", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, library.ReadPiExtensions())
})
mux.HandleFunc("POST /api/library/pi", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
Pi, Ext, Pkg string
On bool
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
var v *library.PiExtensions
var err error
switch {
case in.Ext != "" && in.Pkg == "":
v, err = library.SetPiExtension(in.Pi, in.Ext, in.On)
case in.Pkg != "" && in.Ext == "":
v, err = library.SetPiPackage(in.Pi, in.Pkg, in.On)
default:
err = errors.New("name one extension or one package")
}
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, v)
})
mux.HandleFunc("POST /api/library/pi/copy", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ From, To, Ext, Pkg string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
v, err := library.CopyPi(in.From, in.To, in.Ext, in.Pkg)
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) {
+1 -1
View File
@@ -90,7 +90,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
open();
await v.locator(".lib-head .lib-more:not([disabled])").waitFor();
assert.equal(await v.locator(".lib-skel").count(), 0, "the outline goes");
assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "MCP servers · 1", "Skills · 1", "Hooks", "Subagents", "RTK"]);
assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "MCP servers · 1", "Skills · 1", "Hooks", "Subagents", "RTK", "Pi packages"]);
assert.equal(await v.locator(".lib-tabs .opt.on").textContent(), "Instructions");
assert.equal(await v.locator(".lib-head .lib-more").getAttribute("title"), "~/.magpie/library");
const after = await v.locator(".lib-tabs").boundingBox();
@@ -0,0 +1,147 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// leokon3 on Discord: Pi on Windows and in WSL, and no way to see or move
// an extension between them. The Library's Pi packages tab lists each
// Pi's extensions and packages with a switch each; a package that picks
// only some of its parts has its switch off limits (pi config changes it);
// Copy to… offers only the other Pis that are running, and sends the pick;
// a stopped distro says so and lists nothing. 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\\leo";
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\\leo\\.pi\\agent\\skills", wsl: "Ubuntu" },
],
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [],
});
const piView = (on) => ({
pis: [
{
id: "pi", name: "Pi", icon: "", dir: `${HOME}\\.pi\\agent`,
extensions: [{ id: "extensions/hello.ts", name: "hello.ts", path: `${HOME}\\.pi\\agent\\extensions\\hello.ts`, on: true }],
packages: [
{ source: "npm:pi-skills@1.2.0", name: "pi-skills", kind: "npm", pin: "1.2.0", on: true, installed: true, version: "1.2.0" },
{ source: "git:github.com/leo/pi-tools", name: "pi-tools", kind: "git", on: true, filtered: true, installed: false },
],
},
{
id: "pi@wsl:Ubuntu", name: "Pi · WSL Ubuntu", icon: "", wsl: "Ubuntu", dir: "\\\\wsl.localhost\\Ubuntu\\home\\leo\\.pi\\agent",
extensions: [{ id: "extensions/todo", name: "todo", path: "/home/leo/.pi/agent/extensions/todo", on, folder: true }],
packages: [],
},
{ id: "pi@wsl:Arch", name: "Pi · WSL Arch", icon: "", wsl: "Arch", asleep: true, extensions: [], packages: [] },
],
});
function server(lang, calls) {
let on = false;
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") {
if (req.method() === "POST") {
const b = req.postDataJSON();
calls.push(["set", b]);
on = b.on;
}
return route.fulfill({ json: piView(on) });
}
if (url.pathname === "/api/library/pi/copy") {
calls.push(["copy", req.postDataJSON()]);
return route.fulfill({ json: { ...piView(on), install: "~/.pi/agent/extensions/todo" } });
}
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", copy: "Copy to…", stopped: "WSL Arch isn't running", notInstalled: "Not installed", on: "todo is on for Pi · WSL Ubuntu: Pi loads it when it next starts, or at /reload", copied: "todo is copied to Pi. It needs its packages: run npm install in ~/.pi/agent/extensions/todo there" },
zh: { tab: "Pi 包", copy: "复制到…", stopped: "WSL Arch 未运行", notInstalled: "未安装", on: "todo 已为 Pi · WSL Ubuntu 打开:Pi 下次启动或 /reload 时加载它", copied: "todo 已复制到 Pi。它需要自己的依赖包:请在那里的 ~/.pi/agent/extensions/todo 中运行 npm install" },
"zh-TW": { tab: "Pi 套件", copy: "複製到…", stopped: "WSL Arch 未執行", notInstalled: "未安裝", on: "todo 已為 Pi · WSL Ubuntu 開啟:Pi 下次啟動或 /reload 時載入它", copied: "todo 已複製到 Pi。它需要自己的相依套件:請在那裡的 ~/.pi/agent/extensions/todo 中執行 npm install" },
ja: { tab: "Pi パッケージ", copy: "コピー先…", stopped: "WSL Arch は起動していません", notInstalled: "未インストール", on: "Pi · WSL Ubuntu で todo をオンにしました。Pi は次回起動時か /reload で読み込みます", copied: "todo を Pi にコピーしました。依存パッケージが必要です: そちらの ~/.pi/agent/extensions/todo で npm install を実行してください" },
de: { tab: "Pi-Pakete", copy: "Kopieren nach…", stopped: "WSL Arch läuft nicht", notInstalled: "Nicht installiert", on: "todo ist für Pi · WSL Ubuntu an: Pi lädt es beim nächsten Start oder bei /reload", copied: "todo ist nach Pi kopiert. Es braucht seine Pakete: Führe dort in ~/.pi/agent/extensions/todo npm install aus" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": each Pi's extensions are listed, switched and copied to another Pi", 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 lists = v.locator(".lib-list.lib-pi");
await lists.first().waitFor();
assert.equal(await lists.count(), 3);
assert.deepEqual(await v.locator(".lib-pi-head .label").allTextContents(), ["Pi", "Pi · WSL Ubuntu", "Pi · WSL Arch"]);
const here = lists.nth(0), ubuntu = lists.nth(1), arch = lists.nth(2);
// a stopped distro is never started to read it
assert((await arch.textContent()).startsWith(w.stopped), await arch.textContent());
assert.equal(await arch.locator(".lib-row").count(), 0);
const row = (list, id) => list.locator(`.lib-pi-row[data-id="${id}"]`);
assert.equal(await row(here, "extensions/hello.ts").getByRole("switch").getAttribute("aria-checked"), "true");
assert.deepEqual(await row(here, "npm:pi-skills@1.2.0").locator(".lib-tag").allTextContents(), ["npm", "v1.2.0"]);
assert.deepEqual(await row(here, "git:github.com/leo/pi-tools").locator(".lib-tag").allTextContents(), ["git", w.notInstalled]);
// a package picking some of its parts is changed in pi config
assert.equal(await row(here, "git:github.com/leo/pi-tools").getByRole("switch").isDisabled(), true);
assert.equal(await row(here, "npm:pi-skills@1.2.0").getByRole("switch").isDisabled(), false);
const todo = row(ubuntu, "extensions/todo");
await todo.getByRole("switch").click();
await page.waitForFunction((want) => document.querySelector("#status").textContent === want, w.on).catch(() => {});
assert.equal(await page.locator("#status").textContent(), w.on);
assert.equal(await row(ubuntu, "extensions/todo").getByRole("switch").getAttribute("aria-checked"), "true");
// Copy to… offers the running Pis but this one: not the stopped Arch
await row(ubuntu, "extensions/todo").getByRole("button", { name: w.copy, exact: true }).click();
const items = page.locator(".proto-menu .pm-item .pm-name");
await items.first().waitFor();
assert.deepEqual(await items.allTextContents(), ["Pi"]);
await page.locator(".proto-menu .pm-item").first().click();
await page.waitForFunction((want) => document.querySelector("#status").textContent === want, w.copied).catch(() => {});
assert.equal(await page.locator("#status").textContent(), w.copied);
assert.deepEqual(calls, [
["set", { pi: "pi@wsl:Ubuntu", ext: "extensions/todo", on: true }],
["copy", { from: "pi@wsl:Ubuntu", to: "pi", ext: "extensions/todo" }],
]);
// 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 it is too large Load Diff
+362
View File
@@ -0,0 +1,362 @@
package library
import (
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/tidwall/jsonc"
"github.com/yetone/magpie/internal/agent"
)
// piTwo is the sandbox's own Pi, found as magpie finds it, and a second
// one standing for a Pi in a WSL distro (leokon3's), its home a folder of
// the test's.
func piTwo(t *testing.T) (here, wsl string) {
t.Helper()
h := sandbox(t)
here = filepath.Join(h, ".pi", "agent")
wh := filepath.Join(t.TempDir(), "home", "u")
wsl = filepath.Join(wh, ".pi", "agent")
if err := os.MkdirAll(wsl, 0o755); err != nil {
t.Fatal(err)
}
real := piPlaces
piPlaces = func() []piPlace {
out := real()
w := &agent.Agent{ID: "pi@wsl:Ubuntu", Name: "Pi", WSL: "Ubuntu"}
return append(out, piPlace{a: w, dir: wsl, home: wh})
}
t.Cleanup(func() { piPlaces = real })
return here, wsl
}
func piOf(t *testing.T, v *PiExtensions, id string) PiHere {
t.Helper()
for _, p := range v.Pis {
if p.ID == id {
return p
}
}
t.Fatalf("no Pi %s in %+v", id, v.Pis)
return PiHere{}
}
func piExtOf(t *testing.T, p PiHere, id string) PiExt {
t.Helper()
for _, e := range p.Extensions {
if e.ID == id {
return e
}
}
t.Fatalf("%s has no extension %s: %+v", p.ID, id, p.Extensions)
return PiExt{}
}
func piExtensionsSetting(t *testing.T, dir string) []string {
t.Helper()
raw, err := os.ReadFile(filepath.Join(dir, "settings.json"))
if err != nil {
t.Fatal(err)
}
var s struct{ Extensions []string }
if err := json.Unmarshal(jsonc.ToJSON(raw), &s); err != nil {
t.Fatal(err)
}
return s.Extensions
}
// The extensions Pi itself loads are listed, each switched on or off by
// Pi's own rules: a .ts or .js file in extensions/, a folder there with an
// index.ts or a package.json naming its entries, and a path settings.json
// lists; a dot file, node_modules and a folder with no entry are none.
func TestPiExtensionsListedAsPiLoadsThem(t *testing.T) {
here, _ := piTwo(t)
ext := filepath.Join(here, "extensions")
write(t, filepath.Join(ext, "a.ts"), "")
write(t, filepath.Join(ext, "b.ts"), "")
write(t, filepath.Join(ext, "c.js"), "")
write(t, filepath.Join(ext, ".hidden.ts"), "")
write(t, filepath.Join(ext, "notes.md"), "")
write(t, filepath.Join(ext, "node_modules", "x", "index.ts"), "")
write(t, filepath.Join(ext, "tool", "index.ts"), "")
write(t, filepath.Join(ext, "multi", "package.json"), `{"pi":{"extensions":["./src/one.ts","./src/missing.ts"]}}`)
write(t, filepath.Join(ext, "multi", "src", "one.ts"), "")
write(t, filepath.Join(ext, "empty", "readme.md"), "")
home, _ := os.UserHomeDir()
write(t, filepath.Join(home, "dev", "mine.ts"), "")
write(t, filepath.Join(here, "settings.json"), `{
// the user's own comment
"extensions": ["~/dev/mine.ts", "-extensions/b.ts", "!*.js", "+extensions/c.js", "-builtin:llama.cpp"]
}`)
p := piOf(t, ReadPiExtensions(), "pi")
var ids []string
for _, e := range p.Extensions {
ids = append(ids, e.ID)
}
want := []string{"~/dev/mine.ts", "extensions/a.ts", "extensions/b.ts", "extensions/c.js", "extensions/multi", "extensions/tool"}
if !slices.Equal(ids, want) {
t.Fatalf("extensions = %v, want %v", ids, want)
}
for id, on := range map[string]bool{"~/dev/mine.ts": true, "extensions/a.ts": true, "extensions/b.ts": false, "extensions/c.js": true, "extensions/tool": true, "extensions/multi": true} {
if e := piExtOf(t, p, id); e.On != on {
t.Errorf("%s on = %v, want %v", id, e.On, on)
}
}
if e := piExtOf(t, p, "extensions/multi"); !slices.Equal(e.keys, []string{"extensions/multi/src/one.ts"}) {
t.Errorf("multi's keys = %v, want the entry its package.json names that is there", e.keys)
}
if e := piExtOf(t, p, "~/dev/mine.ts"); !e.Listed {
t.Errorf("a path settings.json lists isn't marked listed: %+v", e)
}
}
// Switched off and on as `pi config` does: "-<path>" written, then taken
// out again, the user's comment and other entries kept; on writes "+" only
// when a "!" pattern would still leave it out.
func TestPiExtensionSwitch(t *testing.T) {
here, _ := piTwo(t)
ext := filepath.Join(here, "extensions")
write(t, filepath.Join(ext, "a.ts"), "")
write(t, filepath.Join(ext, "tool", "index.ts"), "")
write(t, filepath.Join(ext, "old.js"), "")
write(t, filepath.Join(here, "settings.json"), "{\n // mine\n \"extensions\": [\"!*.js\", \"-builtin:llama.cpp\"]\n}\n")
v, err := SetPiExtension("pi", "extensions/a.ts", false)
if err != nil {
t.Fatal(err)
}
if e := piExtOf(t, piOf(t, v, "pi"), "extensions/a.ts"); e.On {
t.Error("a.ts still on after switching it off")
}
if got := piExtensionsSetting(t, here); !slices.Equal(got, []string{"!*.js", "-builtin:llama.cpp", "-extensions/a.ts"}) {
t.Errorf("extensions = %v", got)
}
if raw, _ := os.ReadFile(filepath.Join(here, "settings.json")); !strings.Contains(string(raw), "// mine") {
t.Errorf("the user's comment is gone:\n%s", raw)
}
if _, err := SetPiExtension("pi", "extensions/a.ts", true); err != nil {
t.Fatal(err)
}
if got := piExtensionsSetting(t, here); !slices.Equal(got, []string{"!*.js", "-builtin:llama.cpp"}) {
t.Errorf("on again: extensions = %v, want the -entry taken out and nothing added", got)
}
// a folder is switched by its entry file, as Pi names it
if _, err := SetPiExtension("pi", "extensions/tool", false); err != nil {
t.Fatal(err)
}
if got := piExtensionsSetting(t, here); !slices.Contains(got, "-extensions/tool/index.ts") {
t.Errorf("extensions = %v, want -extensions/tool/index.ts", got)
}
// left out by the user's "!*.js": on is "+"
v, err = SetPiExtension("pi", "extensions/old.js", true)
if err != nil {
t.Fatal(err)
}
if got := piExtensionsSetting(t, here); !slices.Contains(got, "+extensions/old.js") || !slices.Contains(got, "!*.js") {
t.Errorf("extensions = %v, want +extensions/old.js beside the user's !*.js", got)
}
if e := piExtOf(t, piOf(t, v, "pi"), "extensions/old.js"); !e.On {
t.Error("old.js still off")
}
}
// A package is switched whole: off is every filter empty, which Pi reads
// as none of its resources; on is its source alone again. One with the
// user's own filters is left to `pi config`.
func TestPiPackageSwitch(t *testing.T) {
here, _ := piTwo(t)
write(t, filepath.Join(here, "npm", "node_modules", "@x", "pi-foo", "package.json"), `{"version":"1.2.3"}`)
write(t, filepath.Join(here, "settings.json"), `{"packages": ["npm:@x/pi-foo@1.2.3", {"source": "git:github.com/a/b@v1", "skills": []}, "git:github.com/a/c"]}`)
p := piOf(t, ReadPiExtensions(), "pi")
if len(p.Packages) != 3 {
t.Fatalf("packages = %+v", p.Packages)
}
foo := p.Packages[0]
if foo.Name != "@x/pi-foo" || foo.Kind != "npm" || !foo.Installed || foo.Version != "1.2.3" || !foo.On {
t.Errorf("npm package = %+v", foo)
}
if b := p.Packages[1]; !b.Filtered || b.Kind != "git" || b.Installed {
t.Errorf("filtered git package = %+v", b)
}
if _, err := SetPiPackage("pi", "npm:@x/pi-foo@1.2.3", false); err != nil {
t.Fatal(err)
}
raw, _ := os.ReadFile(filepath.Join(here, "settings.json"))
var s struct{ Packages []any }
json.Unmarshal(raw, &s)
o, ok := s.Packages[0].(map[string]any)
if !ok || o["source"] != "npm:@x/pi-foo@1.2.3" || len(o) != 5 {
t.Fatalf("off: packages[0] = %#v", s.Packages[0])
}
for _, k := range piFilterKeys {
if l, ok := o[k].([]any); !ok || len(l) != 0 {
t.Errorf("off: %s = %#v, want []", k, o[k])
}
}
if p := piOf(t, ReadPiExtensions(), "pi"); p.Packages[0].On {
t.Error("still on after switching it off")
}
if _, err := SetPiPackage("pi", "npm:@x/pi-foo@1.2.3", true); err != nil {
t.Fatal(err)
}
raw, _ = os.ReadFile(filepath.Join(here, "settings.json"))
json.Unmarshal(raw, &s)
if s.Packages[0] != "npm:@x/pi-foo@1.2.3" {
t.Errorf("on: packages[0] = %#v, want its source alone", s.Packages[0])
}
before, _ := os.ReadFile(filepath.Join(here, "settings.json"))
if _, err := SetPiPackage("pi", "git:github.com/a/b@v1", false); err == nil || !strings.Contains(err.Error(), "pi config") {
t.Errorf("a filtered package switched: %v", err)
}
if after, _ := os.ReadFile(filepath.Join(here, "settings.json")); string(after) != string(before) {
t.Error("a refused switch wrote settings.json")
}
}
// A package goes to the other Pi as its settings.json entry, which Pi
// there installs when it starts; one it has already, however pinned, isn't
// written twice, and a local folder isn't sent at all.
func TestPiCopyPackage(t *testing.T) {
here, wsl := piTwo(t)
write(t, filepath.Join(here, "settings.json"), `{"packages": [{"source": "npm:pi-foo@2.0.0", "extensions": ["-a.ts"]}, "git:github.com/a/b@v1", "../mine"]}`)
write(t, filepath.Join(wsl, "settings.json"), "{\n \"packages\": [\"git:https://github.com/a/b\"]\n}\n")
if _, err := CopyPi("pi", "pi@wsl:Ubuntu", "", "npm:pi-foo@2.0.0"); err != nil {
t.Fatal(err)
}
raw, _ := os.ReadFile(filepath.Join(wsl, "settings.json"))
var s struct{ Packages []any }
if err := json.Unmarshal(raw, &s); err != nil {
t.Fatal(err)
}
if len(s.Packages) != 2 {
t.Fatalf("packages = %#v", s.Packages)
}
if o, _ := s.Packages[1].(map[string]any); o["source"] != "npm:pi-foo@2.0.0" || o["extensions"] == nil {
t.Errorf("copied entry = %#v, want it whole, filters kept", s.Packages[1])
}
if _, err := CopyPi("pi", "pi@wsl:Ubuntu", "", "git:github.com/a/b@v1"); err == nil || !strings.Contains(err.Error(), "already") {
t.Errorf("a package the other Pi has (another pin, another spelling) copied: %v", err)
}
if _, err := CopyPi("pi", "pi@wsl:Ubuntu", "", "../mine"); err == nil {
t.Error("a local folder's path was written into the other Pi")
}
if _, err := CopyPi("pi", "pi@wsl:Ubuntu", "", "npm:pi-foo@2.0.0"); err == nil {
t.Error("copied twice")
}
// the other way round, to a Pi with no settings.json yet
os.Remove(filepath.Join(here, "settings.json"))
if _, err := CopyPi("pi@wsl:Ubuntu", "pi", "", "git:https://github.com/a/b"); err != nil {
t.Fatal(err)
}
if p := piOf(t, ReadPiExtensions(), "pi"); len(p.Packages) != 1 || p.Packages[0].Source != "git:https://github.com/a/b" {
t.Errorf("packages = %+v", p.Packages)
}
}
// An extension goes to the other Pi as its file or folder, without
// node_modules; one with dependencies says they need installing there,
// and one by a name the other Pi has isn't written over.
func TestPiCopyExtension(t *testing.T) {
here, wsl := piTwo(t)
write(t, filepath.Join(wsl, "extensions", "one.ts"), "export default 1\n")
write(t, filepath.Join(wsl, "extensions", "kit", "index.ts"), "x")
write(t, filepath.Join(wsl, "extensions", "kit", "package.json"), `{"dependencies":{"zod":"^3"}}`)
write(t, filepath.Join(wsl, "extensions", "kit", "lib", "u.ts"), "u")
write(t, filepath.Join(wsl, "extensions", "kit", "node_modules", "zod", "index.js"), "")
write(t, filepath.Join(here, "extensions", "taken.ts"), "mine")
write(t, filepath.Join(wsl, "extensions", "taken.ts"), "theirs")
if _, err := CopyPi("pi@wsl:Ubuntu", "pi", "extensions/one.ts", ""); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(filepath.Join(here, "extensions", "one.ts")); string(b) != "export default 1\n" {
t.Errorf("one.ts = %q", b)
}
c, err := CopyPi("pi@wsl:Ubuntu", "pi", "extensions/kit", "")
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(here, "extensions", "kit", "lib", "u.ts")); err != nil {
t.Error("kit's lib wasn't copied")
}
if _, err := os.Stat(filepath.Join(here, "extensions", "kit", "node_modules")); err == nil {
t.Error("node_modules was copied")
}
if c.Install == "" {
t.Error("a folder with dependencies doesn't say to install them")
}
if e := piExtOf(t, piOf(t, c.PiExtensions, "pi"), "extensions/kit"); !e.On {
t.Error("the copy isn't listed on")
}
if _, err := CopyPi("pi@wsl:Ubuntu", "pi", "extensions/taken.ts", ""); err == nil {
t.Error("an extension of the same name was written over")
}
if b, _ := os.ReadFile(filepath.Join(here, "extensions", "taken.ts")); string(b) != "mine" {
t.Errorf("taken.ts = %q, want the Pi's own", b)
}
}
// A settings.json that can't be read is unknown, not empty: nothing is
// listed for it and nothing written to it.
func TestPiUnreadSettingsNotWritten(t *testing.T) {
here, _ := piTwo(t)
write(t, filepath.Join(here, "extensions", "a.ts"), "")
bad := `{"extensions": ["-extensions/a.ts"],,, oops`
write(t, filepath.Join(here, "settings.json"), bad)
p := piOf(t, ReadPiExtensions(), "pi")
if p.Err == "" || len(p.Extensions) != 0 {
t.Errorf("unreadable settings read as %+v", p)
}
if _, err := SetPiExtension("pi", "extensions/a.ts", false); err == nil {
t.Error("switched with settings.json unread")
}
if b, _ := os.ReadFile(filepath.Join(here, "settings.json")); string(b) != bad {
t.Errorf("settings.json written: %q", b)
}
}
// A Pi in a stopped distro is listed, with nothing read of it, and
// nothing is changed in it.
func TestPiAsleepNotRead(t *testing.T) {
piTwo(t)
real := piPlaces
piPlaces = func() []piPlace {
return append(real(), piPlace{a: &agent.Agent{ID: "pi@wsl:Debian", Name: "Pi", WSL: "Debian"}, asleep: true})
}
t.Cleanup(func() { piPlaces = real })
p := piOf(t, ReadPiExtensions(), "pi@wsl:Debian")
if !p.Asleep || len(p.Extensions) != 0 {
t.Errorf("asleep Pi = %+v", p)
}
if _, err := CopyPi("pi", "pi@wsl:Debian", "", "npm:x"); err == nil || !strings.Contains(err.Error(), "isn't running") {
t.Errorf("copy to a stopped distro: %v", err)
}
}
func TestPiGlob(t *testing.T) {
for _, c := range []struct {
g, s string
ok bool
}{
{"*.js", "c.js", true},
{"*.js", "extensions/c.js", false},
{"extensions/**", "extensions/a/b.ts", true},
{"**/b.ts", "extensions/a/b.ts", true},
{"**/b.ts", "b.ts", true},
{"extensions/?.ts", "extensions/a.ts", true},
{"extensions/[ab].ts", "extensions/c.ts", false},
{"a.ts", "xa.ts", false},
} {
if got := piGlob(c.g).MatchString(c.s); got != c.ok {
t.Errorf("%q ~ %q = %v, want %v", c.g, c.s, got, c.ok)
}
}
}