library: a project's Pi packages, on, off or removed, and adopting its own (#7249)

A project now takes Pi packages: entries of its .pi/settings.json
`packages`, matched by piSourceID. A package is on (its source), off but
kept (every filter empty, as `pi config` writes it) or removed. Project.Pi
is what the project wants, PiRecs what magpie wrote; only an entry still as
magpie wrote it is changed or taken out, and a file magpie made goes with
its last entry. An entry the project had is its own: refused with a problem
until adopted, then switched without a rewrite, and put back as it was (never
deleted) when let go; one that picks some resources is refused.

Surfaces: POST /api/library/projects/pi (how on|off|removed|adopt),
`magpie library project pi [list|add|on|off|rm|adopt] <dir> <source...>`,
the project's own packages in Own["pi"], and a Pi packages block on the
Claude plugins tab's project card (switch, remove, Take over, add field) in
en, zh, zh-TW, ja, de. Pi installs a package itself when it next starts.

Run (mote): gofmt, go vet; go test ./internal/library ./internal/cli
./internal/gui (library, cli ok; gui red only in TestBuiltinsTranslated
#7257 and TestSettingsSaveKeepsWhatItDoesNotSend #7240, both filed);
GUI project-pi (new), project-own, project-plugins, project-hooks,
project-claude-plugins, project-servers, i18n-keys in chromium and webkit.
Not tried: a real Pi starting in a project with these packages; the whole
GUI suite; Windows.
This commit is contained in:
yetone
2026-11-20 05:46:18 +08:00
parent cfe006ea0f
commit 54b9516473
14 changed files with 858 additions and 7 deletions
File diff suppressed because one or more lines are too long
+8
View File
@@ -36,6 +36,12 @@ const libraryProjectUsage = `magpie library project [--json] the projects (
.claude/settings.local.json and .codex/hooks.json beside what's there
magpie library project hook rm <dir> <hook…> take them out, only the entries magpie wrote
magpie library project hook agents <dir> <hook> <a,b…|none> the agents it has the hook for
magpie library project pi [list] <dir> [--json] its packages for Pi (.pi/settings.json) and the project's own
magpie library project pi add|on <dir> <source…> give it packages for Pi: npm:<name>[@version] or a git source; Pi
installs them when it next starts there
magpie library project pi off <dir> <source…> keep them listed but loading nothing; on turns them on again
magpie library project pi rm <dir> <source…> take them out, only what magpie wrote
magpie library project pi adopt <dir> <source…> switch a package the project declares itself, left as written
magpie library project instructions <dir> [--json] its own instructions, the agents they're for and the files
magpie library project instructions <dir> text <text…>|--file <f>|- set them ("" takes them out); written, between
magpie's two marker lines, into the project file each agent reads: by default for
@@ -148,6 +154,8 @@ func libraryProjectCmd(args []string) error {
return projectKindCmd(projectSubagents, rest, usage)
case "hook":
return projectKindCmd(projectHooks, rest, usage)
case "pi":
return projectPiCmd(rest, usage)
case "instructions", "instr":
return projectInstrCmd(rest, usage)
}
+130
View File
@@ -0,0 +1,130 @@
package cli
import (
"encoding/json"
"fmt"
"os"
"slices"
"strings"
"github.com/yetone/magpie/internal/library"
)
// projectPiCmd is magpie library project pi …: the packages of a project's
// .pi/settings.json (#7249), through the calls the Library page makes.
func projectPiCmd(rest []string, usage func() error) error {
if len(rest) == 0 {
return usage()
}
verb, args := rest[0], rest[1:]
if !slices.Contains([]string{"add", "on", "off", "rm", "remove", "adopt", "list"}, verb) {
verb, args = "list", rest
}
if verb == "list" {
asJSON := slices.Contains(args, "--json")
args = slices.DeleteFunc(slices.Clone(args), func(a string) bool { return a == "--json" })
if len(args) != 1 || strings.HasPrefix(args[0], "-") {
return usage()
}
dir, err := projectDir(args[0])
if err != nil {
return err
}
return listProjectPi(dir, asJSON)
}
if len(args) < 2 || strings.HasPrefix(args[0], "-") {
return usage()
}
dir, err := projectDir(args[0])
if err != nil {
return err
}
var bad []string
for _, src := range args[1:] {
var res *library.Result
switch verb {
case "add", "on":
res, err = library.ProjectPi(dir, src, "on")
case "off":
res, err = library.ProjectPi(dir, src, "off")
case "rm", "remove":
res, err = library.ProjectPi(dir, src, "removed")
case "adopt":
res, err = library.ProjectPiAdopt(dir, src)
}
if err != nil {
fmt.Println(amber.Render("!"), src, muted.Render(err.Error()))
bad = append(bad, src)
continue
}
v, err := library.Read(res.Problems)
if err != nil {
return err
}
p := projectView(v, dir)
if p == nil {
return fmt.Errorf("%s isn't a project", dir)
}
if why := p.Problems["pi:"+src]; why != "" {
fmt.Println(amber.Render("!"), src, muted.Render(why))
bad = append(bad, src)
continue
}
state := "removed"
for _, x := range p.Pi {
if x.Source == src {
state = x.State
}
}
fmt.Println(green.Render("✓"), src, muted.Render(state))
}
if len(bad) > 0 {
return fmt.Errorf("%s not changed in %s", strings.Join(bad, ", "), dir)
}
return nil
}
func listProjectPi(dir string, asJSON bool) error {
v, err := library.Read(nil)
if err != nil {
return err
}
p := projectView(v, dir)
if p == nil {
return fmt.Errorf("%s isn't a project", dir)
}
type item struct {
Source string `json:"source"`
State string `json:"state"`
Adopted bool `json:"adopted,omitempty"`
By string `json:"by"` // "magpie" or "project"
}
items := []item{}
for _, x := range p.Pi {
items = append(items, item{x.Source, x.State, x.Adopted, "magpie"})
}
for _, o := range p.Own["pi"] {
st := "on"
if o.Event == "off" {
st = "off"
}
items = append(items, item{o.Name, st, false, "project"})
}
if asJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(map[string]any{"dir": dir, "items": items})
}
if len(items) == 0 {
fmt.Println(muted.Render("nothing for Pi in " + dir))
return nil
}
for _, it := range items {
who := it.By
if it.Adopted {
who = "adopted"
}
fmt.Println(it.Source, muted.Render(it.State+" · "+who))
}
return nil
}
+49
View File
@@ -427,3 +427,52 @@ func TestLibraryProjectHookCmd(t *testing.T) {
t.Error("the file magpie made stayed")
}
}
// magpie library project pi (#7249): add, off, on, rm, adopt and list, and
// the project's own package left as it is.
func TestLibraryProjectPiCmd(t *testing.T) {
proj := projectSandbox(t)
if err := os.MkdirAll(filepath.Join(proj, ".pi"), 0o755); err != nil {
t.Fatal(err)
}
own := `{"packages":["npm:pi-own"]}`
if err := os.WriteFile(filepath.Join(proj, ".pi", "settings.json"), []byte(own), 0o644); err != nil {
t.Fatal(err)
}
must := func(args ...string) string {
t.Helper()
out, err := projectOut(t, args...)
if err != nil {
t.Fatalf("library project %v: %v\n%s", args, err, out)
}
return out
}
read := func() string {
b, _ := os.ReadFile(filepath.Join(proj, ".pi", "settings.json"))
return strings.Join(strings.Fields(string(b)), "")
}
must("add", ".")
for _, bad := range [][]string{{"pi", "add", ".", "--evil"}, {"pi", "add", ".", "-x"}, {"pi", "add", ".", "./local dir"}, {"pi", "add", ".", "npm:pi-own"}} {
if out, err := projectOut(t, bad...); err == nil {
t.Errorf("library project %v was taken:\n%s", bad, out)
}
}
must("pi", "add", ".", "npm:pi-demo")
if got := read(); !strings.Contains(got, `"npm:pi-own"`) || !strings.Contains(got, `"npm:pi-demo"`) {
t.Errorf("add: %s", got)
}
must("pi", "off", ".", "npm:pi-demo")
if got := read(); !strings.Contains(got, `"extensions":[]`) {
t.Errorf("off: %s", got)
}
out := must("pi", ".", "--json")
if !strings.Contains(out, `"by": "project"`) || !strings.Contains(out, `"state": "off"`) {
t.Errorf("list:\n%s", out)
}
must("pi", "on", ".", "npm:pi-demo")
must("pi", "adopt", ".", "npm:pi-own")
must("pi", "rm", ".", "npm:pi-demo", "npm:pi-own")
if got := read(); got != own {
t.Errorf("rm: %s", got)
}
}
@@ -7493,11 +7493,65 @@ magpie.plugin("library", (ctx) => {
}
card.append(el("p", "lib-aside lib-projfoot lib-projclaude-note", t("The plugins above are Claude Code's own, turned on for this project in .claude/settings.local.json. They stay installed through Claude Code.")));
}
projectPiPackages(p, card);
card.append(el("p", "lib-aside lib-projfoot", t("Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.")));
if (plugins.some((b) => b.hooks?.length && (p.plugins?.[b.name] || []).includes("codex"))) card.append(el("p", "lib-aside lib-projfoot lib-projhooks-codex", t("Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.")));
return card;
}
// A project's Pi packages (#7249): the entries of its .pi/settings.json,
// each on, off (kept, loading nothing) or removed, and those the project
// declares itself, left as written until adopted.
function projectPiPackages(p, card) {
if (!shownAgents().some((a) => a.id === "pi")) return;
const box = el("div", "lib-projpi");
box.append(el("div", "lib-projownhead", t("Pi packages")));
const set = (source, how, said) => change("projects/pi", { dir: p.dir, name: source, how }, said);
for (const x of p.pi || []) {
const row = el("div", "row lib-row lib-projskill lib-projpirow" + (x.state === "off" ? " off" : ""));
row.dataset.source = x.source;
const w = el("div", "who");
const n = el("div", "name mono", x.name);
const problem = p.problems?.["pi:" + x.source];
if (problem) n.append(tag(t("Not written"), "warn", problem));
w.append(n);
const sub = el("div", "sub mono", x.source);
sub.title = problem || x.source;
w.append(sub);
const sw = toggle(x.state === "on", x.source, (on) =>
set(x.source, on ? "on" : "off", on ? t("{item} is on in {name}", { item: x.name, name: p.name }) : t("{item} is off in {name}", { item: x.name, name: p.name })));
const rm = button("", "lib-icon danger", () => set(x.source, "removed", t("{item} is out of {name}", { item: x.name, name: p.name })));
rm.append(svg(GLYPH.trash, 13, 1.4));
rm.title = t("Remove");
row.append(glyph(GLYPH.folder), w, sw, rm);
box.append(row);
}
for (const o of p.own?.pi || []) {
const row = el("div", "row lib-row lib-projskill lib-projownrow lib-projpiown");
row.dataset.source = o.name;
const w = el("div", "who");
w.append(el("div", "name mono", o.name));
const line = [o.event, o.path].filter(Boolean).join(" · ");
w.append(el("div", "sub mono", line));
row.append(glyph(GLYPH.folder), w);
// one that picks some of the package's resources is `pi config`'s
if (!o.description) row.append(button(t("Take over"), "lib-btn", () => set(o.name, "adopt", t("{item} is magpie's in {name}", { item: o.name, name: p.name }))));
box.append(row);
}
const add = el("div", "row lib-row lib-projpiadd");
const inp = input("", t("Pi package, e.g. npm:pi-demo"));
inp.className = "grow";
inp.dataset.lib = "projpi:" + p.dir;
const go = async () => {
const source = inp.value.trim();
if (source) await set(source, "on", t("{item} is on in {name}", { item: source, name: p.name }));
};
inp.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") go(); };
add.append(inp, button(t("Add"), "lib-btn", go));
box.append(add);
card.append(box);
}
// The agents a project's first instructions are for: those here that
// read a project's instructions file and have the shared ones on, else
// every one of them here.
@@ -798,6 +798,11 @@ magpie.strings({
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "它的技能、服务器和子代理放在项目自己的那些位置,hooks 写进 .claude/settings.local.json 和 .codex/hooks.json。那里不是 magpie 写的文件、你改过的条目,都保持原样。",
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex 只在你信任的项目里运行项目的 hooks,并且要先在 /hooks 中审阅。",
"Project hooks": "项目 Hooks",
"Pi package, e.g. npm:pi-demo": "Pi 包,例如 npm:pi-demo",
"Take over": "接管",
"{item} is on in {name}": "{item} 已在 {name} 中开启",
"{item} is off in {name}": "{item} 已在 {name} 中关闭",
"{item} is magpie's in {name}": "{item} 已由 magpie 接管({name})",
"Project's own": "项目自带",
"No hooks yet": "还没有 Hook",
"Hide its hooks": "收起它的 Hook",
@@ -1954,6 +1959,11 @@ magpie.strings({
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "它的技能、伺服器和子代理放在專案自己的那些位置,hooks 寫進 .claude/settings.local.json 和 .codex/hooks.json。那裡不是 magpie 寫的檔案、你改過的條目,都保持原樣。",
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex 只在你信任的專案裡執行專案的 hooks,並且要先在 /hooks 中審閱。",
"Project hooks": "專案 Hooks",
"Pi package, e.g. npm:pi-demo": "Pi 套件,例如 npm:pi-demo",
"Take over": "接管",
"{item} is on in {name}": "{item} 已在 {name} 中開啟",
"{item} is off in {name}": "{item} 已在 {name} 中關閉",
"{item} is magpie's in {name}": "{item} 已由 magpie 接管({name})",
"Project's own": "專案自帶",
"No hooks yet": "還沒有 Hook",
"Hide its hooks": "收起它的 Hook",
@@ -3101,6 +3111,11 @@ magpie.strings({
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "スキル、サーバー、サブエージェントはプロジェクト自身のものと同じ場所に、フックは .claude/settings.local.json と .codex/hooks.json に書き込まれます。magpie のものではないファイルや、あなたが変更した項目はそのまま残ります。",
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex は信頼したプロジェクトでのみ、/hooks で確認した後にプロジェクトのフックを実行します。",
"Project hooks": "プロジェクトのフック",
"Pi package, e.g. npm:pi-demo": "Pi パッケージ(例: npm:pi-demo)",
"Take over": "引き継ぐ",
"{item} is on in {name}": "{item} を {name} でオンにしました",
"{item} is off in {name}": "{item} を {name} でオフにしました",
"{item} is magpie's in {name}": "{item} を {name} で magpie の管理にしました",
"Project's own": "プロジェクト自身のもの",
"No hooks yet": "フックはまだありません",
"Hide its hooks": "フックを閉じる",
@@ -4253,6 +4268,11 @@ magpie.strings({
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "Skills, Server und Subagenten kommen dorthin, wo die eigenen des Projekts liegen, Hooks in .claude/settings.local.json und .codex/hooks.json. Eine Datei dort, die nicht von magpie ist, oder ein Eintrag, den du geändert hast, bleibt, wie er ist.",
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex führt die Hooks eines Projekts nur in einem Projekt aus, dem du vertraust, und erst, nachdem du sie in /hooks geprüft hast.",
"Project hooks": "Projekt-Hooks",
"Pi package, e.g. npm:pi-demo": "Pi-Paket, z. B. npm:pi-demo",
"Take over": "Übernehmen",
"{item} is on in {name}": "{item} ist in {name} an",
"{item} is off in {name}": "{item} ist in {name} aus",
"{item} is magpie's in {name}": "{item} wird in {name} von magpie verwaltet",
"Project's own": "Eigene des Projekts",
"No hooks yet": "Noch keine Hooks",
"Hide its hooks": "Hooks ausblenden",
@@ -700,6 +700,9 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col
.lib-projown { border-top: 1px solid var(--line-2); }
.lib-projownhead { padding: 8px 12px 2px 49px; font-size: 11px; color: var(--muted); }
.lib-projownrow { opacity: .8; }
.lib-projpi { border-top: 1px solid var(--line-2); }
.lib-projpiadd { display: flex; gap: 8px; padding: 8px 12px 10px 49px; border-top: 1px solid var(--line-2); }
.lib-projpiadd input { min-width: 0; }
/* the library's skills: a card for each GitHub repository they came from,
and one for those on this computer, folded to its heading line */
+8
View File
@@ -963,6 +963,14 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
return
}
res, err = library.ProjectClaudePlugin(in.Dir, in.Name, len(in.Agents) == 1)
case "projects/pi":
// a Pi package of the project's .pi/settings.json: "on", "off"
// (kept, loads nothing), "removed", or "adopt" for one it declares
if in.How == "adopt" {
res, err = library.ProjectPiAdopt(in.Dir, in.Name)
} else {
res, err = library.ProjectPi(in.Dir, in.Name, in.How)
}
case "projects/server-off":
// a Library server turned off in this project only
res, err = library.ProjectServerOff(in.Dir, in.Name, in.Agents)
+144
View File
@@ -0,0 +1,144 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// (#7249, jinpwng on X) A project's Pi packages: a row each with an on/off
// switch and a remove button, the package the project declares itself with
// Adopt, and a field to add one. In English and Chinese.
// No backend: the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/emo";
const DIR = HOME + "/code/app";
const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more });
const plugin = (name, more) => ({ name, version: "1.0.0", description: "", agents: [], skills: [], mcp: [], hooks: [], subagents: [], ...more });
const lib = (pi, own) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [
agent("claude", "Claude Code", { projectSkills: ".claude/skills", projectMCP: ".mcp.json", projectSubagents: ".claude/agents", projectHooks: ".claude/settings.local.json" }),
agent("codex", "Codex", { projectMCP: ".codex/config.toml", projectSubagents: ".codex/agents", projectHooks: ".codex/hooks.json" }),
agent("pi", "Pi", { projectSkills: ".agents/skills", projectMCP: ".pi/mcp.json" }),
agent("goose", "Goose"),
],
instructions: { agents: [] }, servers: [], subagents: [], skills: [], foundServers: [], foundSkills: [],
hooks: [{ name: "bark", event: "turn-end", command: "say bark", agents: [] }], hookAgents: [{ id: "claude", file: `${HOME}/.claude/settings.json`, events: ["Stop"] }, { id: "codex", file: `${HOME}/.codex/hooks.json`, events: ["Stop"] }], plugins: [], claudeInstalled: [{ id: "fmt@acme", on: false }, { id: "lint@acme", on: true }],
projects: [{ dir: DIR, name: "app", copy: false, skills: {}, placed: [], servers: {}, subagents: {}, plugins: {}, hooks: {}, wrote: {}, pi, own: { pi: own } }],
});
function server(lang, posts) {
let pi = [], own = [{ name: "npm:pi-own", path: ".pi/settings.json", agent: "pi" }];
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/library") return route.fulfill({ json: lib(pi, own) });
if (url.pathname === "/api/library/projects/pi") {
const b = req.postDataJSON();
posts.push(b);
const name = (s) => s.replace(/^npm:/, "");
if (b.how === "adopt") { own = own.filter((o) => o.name !== b.name); pi = [...pi, { source: b.name, name: name(b.name), state: "on", adopted: true }]; }
else if (b.how === "removed") pi = pi.filter((x) => x.source !== b.name);
else if (pi.some((x) => x.source === b.name)) pi = pi.map((x) => (x.source === b.name ? { ...x, state: b.how } : x));
else pi = [...pi, { source: b.name, name: name(b.name), state: b.how }];
return route.fulfill({ json: { ...lib(pi, own), result: { changed: [], problems: [] } } });
}
if (url.pathname === "/api/library/native") return route.fulfill({ json: [] });
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
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 scrolled = (page) => page.evaluate(() => [window.scrollX, window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop || e.scrollLeft).map((e) => `${e.className}:${e.scrollTop},${e.scrollLeft}`)].join(" "));
// a click where the element is, as the reader's: Playwright's own click
// first scrolls it into view
const press = async (page, loc) => {
const b = await loc.boundingBox();
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
};
// a chip: the chips fan out under the pointer first, as a reader's hand
// does, and the chip is pressed where it is then
// (a render after the last write may replace it under the pointer, so it
// is found again until it stays)
const box = async (loc) => {
for (;;) {
await loc.waitFor({ state: "visible" });
const b = await loc.boundingBox();
if (b) return b;
}
};
const chip = async (page, loc) => {
const a = await box(loc);
await page.mouse.move(a.x + a.width / 2, a.y + a.height / 2);
await page.waitForTimeout(350);
const b = await box(loc);
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
};
const words = { en: "Pi packages", zh: "Pi 包" };
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a project's Pi packages are added, switched, adopted and removed", async (t) => {
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 ["en", "zh"]) {
await t.test(lang, async () => {
const posts = [];
const ctx = await browser.newContext({ viewport: { width: 860, height: 800 } });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "plugins"); } catch {} });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posts));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const card = page.locator("#view-library .lib-project");
await card.waitFor();
await press(page, card.locator(".lib-projhead"));
await card.locator(".lib-projpiadd").waitFor();
assert.equal((await card.locator(".lib-projpi .lib-projownhead").textContent()).trim(), words[lang]);
// the project's own, with Adopt
const own = card.locator(".lib-projpiown");
assert.match(await own.textContent(), /npm:pi-own/);
// add one: Enter in the field
const inp = card.locator(".lib-projpiadd input");
await inp.fill("npm:pi-demo");
await inp.press("Enter");
const row = card.locator('.lib-projpirow[data-source="npm:pi-demo"]');
await row.waitFor();
assert.deepEqual(posts.at(-1), { dir: DIR, name: "npm:pi-demo", how: "on" });
// off, then on
await row.locator(".lib-switch").click();
await card.locator('.lib-projpirow.off[data-source="npm:pi-demo"]').waitFor();
assert.equal(posts.at(-1).how, "off");
await card.locator(".lib-projpirow .lib-switch").click();
await card.locator('.lib-projpirow:not(.off)[data-source="npm:pi-demo"]').waitFor();
assert.equal(posts.at(-1).how, "on");
// adopt the project's own
await own.locator("button").click();
await card.locator('.lib-projpirow[data-source="npm:pi-own"]').waitFor();
assert.equal(posts.at(-1).how, "adopt");
assert.equal(await card.locator(".lib-projpiown").count(), 0);
// remove
await card.locator('.lib-projpirow[data-source="npm:pi-demo"] .lib-icon').click();
await card.locator('.lib-projpirow[data-source="npm:pi-demo"]').waitFor({ state: "detached" });
assert.equal(posts.at(-1).how, "removed");
await ctx.close();
});
}
});
}
+30
View File
@@ -65,6 +65,7 @@ func (p *Project) ownResources() map[string][]OwnResource {
for _, id := range ids {
out["subagents"] = append(out["subagents"], p.ownSubagents(id)...)
}
out["pi"] = p.ownPi()
for k, rows := range out {
if len(rows) == 0 {
delete(out, k)
@@ -228,3 +229,32 @@ func (p *Project) ownSubagents(id string) []OwnResource {
}
return out
}
// ownPi are the packages the project's .pi/settings.json declares that magpie
// didn't write: its own, which can be adopted (#7249).
func (p *Project) ownPi() []OwnResource {
abs := filepath.Join(p.Dir, filepath.FromSlash(piSettingsRel))
if p.inside(abs) != nil {
return nil
}
list, err := projectPiList(abs)
if err != nil {
return nil
}
var out []OwnResource
for _, r := range list {
pk, ok := piPackageOf(r)
if !ok || slices.ContainsFunc(p.PiRecs, func(x PiRec) bool { return piIDOf(x.Source) == piIDOf(pk.Source) }) {
continue
}
row := OwnResource{Name: pk.Source, Path: piSettingsRel, Agent: "pi"}
if !pk.On {
row.Event = "off"
}
if pk.Filtered {
row.Description = "filtered"
}
out = append(out, row)
}
return out
}
+296
View File
@@ -0,0 +1,296 @@
package library
import (
"encoding/json"
"errors"
"fmt"
"path/filepath"
"slices"
"sort"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/edit"
)
// A project's Pi packages (#7249, jinpwng on X): entries of `packages` in the
// project's .pi/settings.json, which Pi reads for the folder and installs
// itself (into .pi/npm and .pi/git) when it next starts there. Three states:
// on (the source alone), off but kept (every filter empty, which loads none
// of it, as `pi config` writes it) and removed (no entry). Project.Pi is what
// the project wants by source, PiRecs what magpie wrote, the only entries it
// changes or takes out, and only while they are still as it wrote them.
//
// An entry the project had before is the user's: it is never rewritten or
// taken out. Adopting it records it (Orig is what it was) so it can be turned
// off and on; letting go of an adopted entry puts Orig back, it is never
// deleted.
//
// <project>/.pi/settings.json {"packages": ["npm:pi-demo", {"source": "...", "extensions": [], ...}]}
const piSettingsRel = ".pi/settings.json"
// PiRec is a package entry magpie wrote in a project: Entry as it is now,
// Orig the user's entry it adopted, nil for one magpie added.
type PiRec struct {
Source string `json:"source"`
Entry json.RawMessage `json:"entry"`
Orig json.RawMessage `json:"orig,omitempty"`
}
// ProjectPiView is a package the project has by magpie, for its card.
type ProjectPiView struct {
Source string `json:"source"`
Name string `json:"name"`
// State is "on" or "off" (kept, loads nothing)
State string `json:"state"`
// Adopted: the entry was the project's own, which magpie only switches
Adopted bool `json:"adopted,omitempty"`
}
func piIDOf(s string) string {
if id := piSourceID(s); id != "" {
return id
}
return "local:" + filepath.ToSlash(filepath.Clean(s))
}
// piEntryFor is the entry that says state: a package's source alone for on,
// the same with every filter empty for off.
func piEntryFor(source, state string, orig json.RawMessage) json.RawMessage {
if state == "on" {
if orig != nil {
if pk, ok := piPackageOf(orig); ok && pk.On {
return orig
}
}
b, _ := json.Marshal(source)
return b
}
o := map[string]json.RawMessage{}
if orig != nil {
_ = json.Unmarshal(orig, &o)
}
b, _ := json.Marshal(source)
o["source"] = b
for _, k := range piFilterKeys {
o[k] = json.RawMessage("[]")
}
e, _ := json.Marshal(o)
return e
}
// projectPiList is the project's packages entries; the file not there is an
// empty list, one that can't be read an error (unknown, never empty).
func projectPiList(abs string) ([]json.RawMessage, error) {
doc, err := readHooksFile(abs)
if err != nil {
return nil, err
}
r := gjson.GetBytes(doc, "packages")
if !r.Exists() || r.Type == gjson.Null {
return nil, nil
}
var list []json.RawMessage
if err := json.Unmarshal([]byte(r.Raw), &list); err != nil {
return nil, fmt.Errorf("%s: packages isn't a list: it is left as it is", abs)
}
return list, nil
}
func piIndex(list []json.RawMessage, source string) int {
id := piIDOf(source)
return slices.IndexFunc(list, func(r json.RawMessage) bool {
pk, ok := piPackageOf(r)
return ok && piIDOf(pk.Source) == id
})
}
// syncProjectPi writes the packages the project wants into its
// .pi/settings.json and takes out what magpie wrote that it no longer does.
func (l *Library) syncProjectPi(p *Project, fail func(what string, err error)) {
if len(p.Pi) == 0 && len(p.PiRecs) == 0 {
return
}
abs := filepath.Join(p.Dir, filepath.FromSlash(piSettingsRel))
if err := p.inside(abs); err != nil {
fail("pi", err)
return
}
list, err := projectPiList(abs)
if err != nil {
fail("pi", err)
return
}
changed := false
var recs []PiRec
for _, rec := range p.PiRecs {
i := piIndex(list, rec.Source)
if i < 0 {
continue // the user took it out
}
if canonical(list[i]) != canonical(rec.Entry) {
fail("pi:"+rec.Source, fmt.Errorf("%s has been changed since magpie wrote %s: it's left as it is", piSettingsRel, rec.Source))
continue
}
state, want := p.Pi[rec.Source]
switch {
case !want:
changed = true
if rec.Orig != nil {
list[i] = rec.Orig
} else {
list = slices.Delete(list, i, i+1)
}
continue
default:
if cur, _ := piPackageOf(list[i]); cur.On != (state == "on") {
rec.Entry = piEntryFor(rec.Source, state, rec.Orig)
list[i] = rec.Entry
changed = true
}
}
recs = append(recs, rec)
}
srcs := make([]string, 0, len(p.Pi))
for s := range p.Pi {
srcs = append(srcs, s)
}
sort.Strings(srcs)
for _, s := range srcs {
if slices.ContainsFunc(recs, func(r PiRec) bool { return r.Source == s }) {
continue
}
if piIndex(list, s) >= 0 {
fail("pi:"+s, fmt.Errorf("%s has %s already: it's the project's own, left as it is until it is adopted", piSettingsRel, s))
continue
}
e := piEntryFor(s, p.Pi[s], nil)
list = append(list, e)
recs = append(recs, PiRec{Source: s, Entry: e})
changed = true
}
if changed {
if !exists(abs) && len(list) > 0 {
if err := p.mkdirs(filepath.Dir(abs)); err != nil {
fail("pi", err)
return
}
if !slices.Contains(p.MadeFiles, piSettingsRel) {
p.MadeFiles = append(p.MadeFiles, piSettingsRel)
}
}
var err error
if len(list) == 0 {
err = edit.DelJSON(abs, "packages")
} else {
err = edit.SetJSON(abs, edit.KV{Path: "packages", Value: list})
}
if err != nil {
fail("pi", err)
return
}
}
p.PiRecs = recs
if len(recs) == 0 {
p.PiRecs = nil
p.dropMadeFile(piSettingsRel)
}
}
func checkPiSource(source string) error {
if !piSourceOK(source) {
return fmt.Errorf("%q isn't a Pi package source magpie can give a project: npm:<name>[@version] or a git source", source)
}
return nil
}
// ProjectPi sets a package of a project's Pi to state: "on", "off" (kept,
// loads nothing) or "removed". A package the project declares already is
// refused until it is adopted.
func ProjectPi(dir, source, state string) (*Result, error) {
if !slices.Contains([]string{"on", "off", "removed"}, state) {
return nil, fmt.Errorf("a package is on, off or removed, not %q", state)
}
if state != "removed" {
if err := checkPiSource(source); err != nil {
return nil, err
}
}
return change(func(l *Library) error {
p := l.project(dir)
if p == nil {
return fmt.Errorf("no project %s", dir)
}
if state == "removed" {
delete(p.Pi, source)
if len(p.Pi) == 0 {
p.Pi = nil
}
return nil
}
if p.Pi == nil {
p.Pi = map[string]string{}
}
p.Pi[source] = state
return nil
})
}
// ProjectPiAdopt takes the package the project declares in its
// .pi/settings.json into magpie's keeping without rewriting it: it can then be
// turned off and on, and letting it go puts the entry back as it was. An entry
// that picks some of the package's resources is refused (`pi config` changes
// those).
func ProjectPiAdopt(dir, source string) (*Result, error) {
return change(func(l *Library) error {
p := l.project(dir)
if p == nil {
return fmt.Errorf("no project %s", dir)
}
abs := filepath.Join(p.Dir, filepath.FromSlash(piSettingsRel))
if err := p.inside(abs); err != nil {
return err
}
list, err := projectPiList(abs)
if err != nil {
return err
}
i := piIndex(list, source)
if i < 0 {
return fmt.Errorf("%s has no package %s", piSettingsRel, source)
}
pk, _ := piPackageOf(list[i])
if pk.Filtered {
return fmt.Errorf("%s picks some of %s's resources; change it with `pi config`", piSettingsRel, pk.Name)
}
if slices.ContainsFunc(p.PiRecs, func(r PiRec) bool { return r.Source == pk.Source }) {
return errors.New(pk.Source + " is magpie's already")
}
state := "on"
if !pk.On {
state = "off"
}
if p.Pi == nil {
p.Pi = map[string]string{}
}
p.Pi[pk.Source] = state
p.PiRecs = append(p.PiRecs, PiRec{Source: pk.Source, Entry: list[i], Orig: list[i]})
return nil
})
}
// piViews is the project's packages by magpie, for its card.
func (p *Project) piViews() []ProjectPiView {
var out []ProjectPiView
for s, st := range p.Pi {
name, _ := piPackageName(s)
if name == "" {
name = s
}
out = append(out, ProjectPiView{Source: s, Name: name, State: st,
Adopted: slices.ContainsFunc(p.PiRecs, func(r PiRec) bool { return r.Source == s && r.Orig != nil })})
}
sort.Slice(out, func(i, j int) bool { return out[i].Source < out[j].Source })
return out
}
+100
View File
@@ -0,0 +1,100 @@
package library
import (
"os"
"path/filepath"
"strings"
"testing"
)
// A project's Pi packages (#7249): added, turned off and on, removed, and a
// declaration the project had is its own until adopted.
func TestProjectPiPackages(t *testing.T) {
h := sandbox(t)
_ = h
proj := t.TempDir()
if err := os.MkdirAll(filepath.Join(proj, ".git"), 0o755); err != nil {
t.Fatal(err)
}
ok(t)(AddProject(proj))
file := filepath.Join(proj, ".pi/settings.json")
view := func() ProjectView {
for _, p := range View0(t).Projects {
if p.Dir == proj {
return p
}
}
t.Fatal("no project")
return ProjectView{}
}
// add: one entry, and the file is magpie's
ok(t)(ProjectPi(proj, "npm:pi-demo", "on"))
if got := strings.Join(strings.Fields(read(t, file)), ""); got != `{"packages":["npm:pi-demo"]}` {
t.Fatalf("settings: %s", got)
}
ok(t)(ProjectPi(proj, "npm:pi-demo", "on"))
if strings.Count(read(t, file), "pi-demo") != 1 {
t.Errorf("reapplied twice:\n%s", read(t, file))
}
// off but kept, then on again
ok(t)(ProjectPi(proj, "npm:pi-demo", "off"))
if s := read(t, file); !strings.Contains(s, `"extensions": []`) && !strings.Contains(strings.Join(strings.Fields(s), ""), `"extensions":[]`) {
t.Errorf("off writes no empty filters:\n%s", s)
}
if v := view(); len(v.Pi) != 1 || v.Pi[0].State != "off" {
t.Errorf("view: %+v", v.Pi)
}
ok(t)(ProjectPi(proj, "npm:pi-demo", "on"))
if got := strings.Join(strings.Fields(read(t, file)), ""); got != `{"packages":["npm:pi-demo"]}` {
t.Fatalf("on again: %s", got)
}
// removed: the file magpie made goes with it
ok(t)(ProjectPi(proj, "npm:pi-demo", "removed"))
if _, err := os.Stat(file); err == nil {
t.Errorf("settings stay:\n%s", read(t, file))
}
// the project's own declaration is never written over or taken out
own := "{\n \"theme\": \"dark\",\n \"packages\": [{\"source\": \"npm:pi-own\", \"skills\": [\"a\"]}, \"npm:pi-plain\"]\n}\n"
write(t, file, own)
res, err := ProjectPi(proj, "npm:pi-plain", "on")
if err != nil {
t.Fatal(err)
}
if len(res.Problems) != 1 || !strings.Contains(res.Problems[0].Error, "adopted") {
t.Fatalf("problems: %+v", res.Problems)
}
ok(t)(ProjectPi(proj, "npm:pi-plain", "removed"))
ok(t)(ProjectPi(proj, "npm:pi-new", "on"))
if s := read(t, file); !strings.Contains(s, "npm:pi-new") || !strings.Contains(s, `"theme"`) || !strings.Contains(s, "npm:pi-own") {
t.Fatalf("settings:\n%s", s)
}
if o := view().Own["pi"]; len(o) != 2 {
t.Errorf("own: %+v", o)
}
ok(t)(ProjectPi(proj, "npm:pi-new", "removed"))
if squash(read(t, file)) != squash(own) {
t.Fatalf("the project's own file changed:\n%s", read(t, file))
}
// adopt: switched, never rewritten until asked, put back on letting go;
// a filtered one is refused
if _, err := ProjectPiAdopt(proj, "npm:pi-own"); err == nil {
t.Errorf("a filtered entry was adopted")
}
ok(t)(ProjectPiAdopt(proj, "npm:pi-plain"))
if squash(read(t, file)) != squash(own) {
t.Fatalf("adopting rewrote the file:\n%s", read(t, file))
}
ok(t)(ProjectPi(proj, "npm:pi-plain", "off"))
if s := read(t, file); !strings.Contains(s, `"npm:pi-own"`) || strings.Contains(squash(s), `["npm:pi-plain"`) || !strings.Contains(strings.Join(strings.Fields(s), ""), `"source":"npm:pi-plain"`) {
t.Fatalf("off:\n%s", s)
}
ok(t)(ProjectPi(proj, "npm:pi-plain", "removed"))
if got := strings.Join(strings.Fields(read(t, file)), ""); got != strings.Join(strings.Fields(own), "") {
t.Fatalf("letting go did not put the entry back:\n%s", read(t, file))
}
}
func squash(s string) string { return strings.Join(strings.Fields(s), "") }
+4 -4
View File
@@ -461,7 +461,7 @@ func (l *Library) syncTrees(p *Project, res *Result, hubs map[string]*Server) {
t = &Project{Dir: d}
}
t.Copy, t.Skills, t.Servers, t.ServersOff, t.SkillsOff, t.Subagents = p.Copy, p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents
t.Instr, t.InstrAgents, t.Plugins, t.ClaudePlugins, t.Hooks = p.Instr, p.InstrAgents, p.Plugins, p.ClaudePlugins, p.Hooks
t.Instr, t.InstrAgents, t.Plugins, t.ClaudePlugins, t.Hooks, t.Pi = p.Instr, p.InstrAgents, p.Plugins, p.ClaudePlugins, p.Hooks, p.Pi
l.syncFolder(t, res, hubs)
trees = append(trees, t)
}
@@ -475,7 +475,7 @@ func (l *Library) syncTrees(p *Project, res *Result, hubs map[string]*Server) {
// no longer one of the repository's worktrees, or no longer the
// project's: what magpie put there comes out
t.Skills, t.Servers, t.ServersOff, t.SkillsOff, t.Subagents = nil, nil, nil, nil, nil
t.Instr, t.InstrAgents, t.Plugins, t.ClaudePlugins, t.Hooks = "", nil, nil, nil, nil
t.Instr, t.InstrAgents, t.Plugins, t.ClaudePlugins, t.Hooks, t.Pi = "", nil, nil, nil, nil, nil
l.syncFolder(t, res, nil)
if t.holds() {
trees = append(trees, t)
@@ -498,7 +498,7 @@ func (p *Project) tree(dir string) *Project {
// holds says whether magpie has anything of its own in the folder still.
func (p *Project) holds() bool {
return len(p.Placed) > 0 || len(p.Wrote) > 0 || len(p.CodexOff) > 0 || len(p.Overrides) > 0 || len(p.MadeFiles) > 0 || len(p.AgentFiles) > 0 || len(p.InstrFiles) > 0 || len(p.HookRecs) > 0 || len(p.ClaudeWrote) > 0
return len(p.Placed) > 0 || len(p.Wrote) > 0 || len(p.CodexOff) > 0 || len(p.Overrides) > 0 || len(p.MadeFiles) > 0 || len(p.AgentFiles) > 0 || len(p.InstrFiles) > 0 || len(p.HookRecs) > 0 || len(p.ClaudeWrote) > 0 || len(p.PiRecs) > 0
}
// ignored are the files and folders of the project magpie put there, which
@@ -533,7 +533,7 @@ func (l *Library) treesChanged() bool {
}
}
}
if len(p.Skills)+len(p.Servers)+len(p.ServersOff)+len(p.SkillsOff)+len(p.Subagents)+len(p.InstrAgents)+len(p.Plugins)+len(p.Hooks)+len(p.ClaudePlugins) == 0 && len(p.Trees) == 0 {
if len(p.Skills)+len(p.Servers)+len(p.ServersOff)+len(p.SkillsOff)+len(p.Subagents)+len(p.InstrAgents)+len(p.Plugins)+len(p.Hooks)+len(p.ClaudePlugins)+len(p.Pi) == 0 && len(p.Trees) == 0 {
continue
}
dirs := p.treeDirs()
+11 -2
View File
@@ -87,6 +87,11 @@ type Project struct {
// ones it takes out (project_claude_plugins.go)
ClaudePlugins []string `json:"claudePlugins,omitempty"`
ClaudeWrote []string `json:"claudeWrote,omitempty"`
// Pi are the Pi packages the project wants in its .pi/settings.json by
// source ("on" or "off"), PiRecs the entries magpie wrote or adopted
// (project_pi.go)
Pi map[string]string `json:"pi,omitempty"`
PiRecs []PiRec `json:"piRecs,omitempty"`
}
// projectSkillsDirs is where, in a project, each agent reads skills of its
@@ -161,7 +166,7 @@ func (l *Library) syncProjects(res *Result) {
func (l *Library) syncProject(p *Project, res *Result) {
if fi, err := os.Stat(p.Dir); err != nil || !fi.IsDir() {
if len(p.Skills) > 0 || len(p.Servers) > 0 || len(p.Subagents) > 0 || len(p.Plugins) > 0 || len(p.Hooks) > 0 || len(p.ClaudePlugins) > 0 || len(p.ServersOff) > 0 || len(p.SkillsOff) > 0 || p.Instr != "" && len(p.InstrAgents) > 0 || p.holds() {
if len(p.Skills) > 0 || len(p.Servers) > 0 || len(p.Subagents) > 0 || len(p.Plugins) > 0 || len(p.Hooks) > 0 || len(p.ClaudePlugins) > 0 || len(p.Pi) > 0 || len(p.ServersOff) > 0 || len(p.SkillsOff) > 0 || p.Instr != "" && len(p.InstrAgents) > 0 || p.holds() {
res.Problems = append(res.Problems, Problem{Agent: p.Dir, What: "project:", Error: "the folder is gone"})
}
return
@@ -257,6 +262,7 @@ func (l *Library) syncFolder(p *Project, res *Result, hubs map[string]*Server) {
l.syncProjectInstr(p, fail)
l.syncProjectHooks(p, fail)
l.syncProjectClaudePlugins(p, fail)
l.syncProjectPi(p, fail)
p.tidy()
}
@@ -556,7 +562,7 @@ func RemoveProject(dir string, keep bool) (*Result, error) {
l.Projects = slices.DeleteFunc(l.Projects, func(x *Project) bool { return x == p })
return nil
}
p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents, p.InstrAgents, p.Plugins, p.ClaudePlugins, p.Hooks = nil, nil, nil, nil, nil, nil, nil, nil, nil
p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents, p.InstrAgents, p.Plugins, p.ClaudePlugins, p.Hooks, p.Pi = nil, nil, nil, nil, nil, nil, nil, nil, nil, nil
l.syncProject(p, &Result{})
if !p.holds() && p.Claude == nil && !slices.ContainsFunc(p.Trees, (*Project).holds) {
l.Projects = slices.DeleteFunc(l.Projects, func(x *Project) bool { return x == p })
@@ -656,6 +662,8 @@ type ProjectView struct {
// ClaudePlugins are the plugins Claude Code has installed that the
// project turns on for itself
ClaudePlugins []string `json:"claudePlugins"`
// Pi are the Pi packages the project has by magpie (#7249)
Pi []ProjectPiView `json:"pi"`
// Hooks are the library's hooks the project has on their own, for
// the agents given
Hooks map[string][]string `json:"hooks"`
@@ -706,6 +714,7 @@ func projectViews(l *Library, problems []Problem) []ProjectView {
v.Plugins[k] = append([]string{}, a...)
}
v.ClaudePlugins = append([]string{}, p.ClaudePlugins...)
v.Pi = append([]ProjectPiView{}, p.piViews()...)
v.Hooks = map[string][]string{}
for k, a := range p.Hooks {
v.Hooks[k] = append([]string{}, a...)