diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index a71532307..8798c2a6f 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -5374,6 +5374,11 @@ magpie.plugin("library", (ctx) => { // MCP tab lists the same projects with the servers. let addingProject = null; // the folder being added: { dir, error, busy } const openProjects = new Set(); // projects whose skills (or servers) are shown + // An open project's card lists the skills it has, not every library + // skill as though each were in it (POM_JUMPING on X): its menu picks + // which go in. A row whose chips are switched off stays till the card is + // closed, so it doesn't vanish under the pointer. + const projectShown = new Map(); // project dir → the skills its open card lists const projectAgents = () => shownAgents().filter((a) => a.projectSkills); // a project's file may take less than the agent's own: Pi's .pi/mcp.json // no SSE, whatever extension its user-wide file is for @@ -5472,7 +5477,7 @@ magpie.plugin("library", (ctx) => { const chev = el("span", "chev"); chev.append(svg(CHEV_R, 11, 1.7)); head.append(glyph(GLYPH.folder), who, pills, acts, chev); - head.onclick = () => { isOpen ? openProjects.delete(p.dir) : openProjects.add(p.dir); render(); }; + head.onclick = () => { isOpen ? openProjects.delete(p.dir) : openProjects.add(p.dir); projectShown.delete(p.dir); render(); }; head.title = mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets"); card.append(head); if (p.problems?.[""]) card.append(el("div", "lib-err", p.problems[""])); @@ -5489,10 +5494,17 @@ magpie.plugin("library", (ctx) => { opts.append(lab, el("span", "note", p.copy ? t("Copies are made again whenever the library's skill changes; edits made to them are replaced.") : t("Links follow the library's skill: an update reaches the project at once."))); + const all = projectAgents(); + const shown = projectShown.get(p.dir) || new Set(); + projectShown.set(p.dir, shown); + const has = (s) => !!(p.skills[s.name]?.length || p.problems?.[s.name]); + for (const s of lib.skills) if (has(s)) shown.add(s.name); + opts.append(projectSkillsPick(p, all, has)); card.append(opts); - const all = projectAgents(); - for (const s of lib.skills) { + const listed = lib.skills.filter((s) => shown.has(s.name)); + if (!listed.length) card.append(el("p", "lib-aside lib-projfoot lib-projnone", t("No skills yet"))); + for (const s of listed) { const row = el("div", "row lib-row lib-projskill"); const w = el("div", "who"); const n = el("div", "name", s.name); @@ -5517,6 +5529,40 @@ magpie.plugin("library", (ctx) => { return card; } + // The open card's menu of the library's skills, those in the project + // ticked. One ticked goes to the agents the project's skills are for + // already, or, in a project with none yet, to every agent here that + // reads a project's skills; its chips change that after. One unticked is + // taken out of the project. The rest keep their agents. + function projectSkillsPick(p, all, has) { + const b = menuButton(t("Skills"), "lib-projpick", () => { + const now = lib.skills.filter(has).map((s) => s.name); + const opts = lib.skills.map((s) => ({ v: s.name, name: s.name, literalName: true, note: "" })); + openProtoMenu(b, opts, now, async (next) => { + const adds = next.filter((n) => !now.includes(n)), outs = now.filter((n) => !next.includes(n)); + const ids = new Set(all.map((a) => a.id)); + const used = [...new Set(Object.values(p.skills || {}).flat())].filter((id) => ids.has(id)); + const agents = used.length ? used : all.filter((a) => !a.gone && !a.unseen && !a.asleep).map((a) => a.id); + const names = (xs) => xs.join(", "); + if (adds.length && agents.length) { + await change("projects/skills", { dir: p.dir, names: adds, agents }, adds.length === 1 + ? t("{skill} is in {name} for {agents}", { skill: adds[0], name: p.name, agents: agents.map(nameOf).join(", ") }) + : t("{skills} are in {name} for {agents}", { skills: names(adds), name: p.name, agents: agents.map(nameOf).join(", ") })); + } + if (outs.length) { + const shown = projectShown.get(p.dir); + for (const n of outs) shown?.delete(n); + await change("projects/skills", { dir: p.dir, names: outs, agents: [] }, outs.length === 1 + ? t("{skill} is out of {name}", { skill: outs[0], name: p.name }) + : t("{skills} are out of {name}", { skills: names(outs), name: p.name })); + } + }, "Pick the skills it gets", "", "right", false, opts.length > 8 ? "Find a skill" : ""); + }); + b.setAttribute("aria-expanded", "false"); + if (!lib.skills.length || !all.length) b.disabled = true; + return b; + } + // A project row's chip: lit at once, so a second click before magpie has // answered the first counts from it; the clicks are sent one at a time, // the last of them winning, and the page drawn again once they're in. diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index c530a710f..c81093381 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -686,6 +686,8 @@ magpie.strings({ "Not placed": "未放入", "{skill} is in {name} for {agents}": "{skill} 已放入 {name},供 {agents} 使用", "{skill} is out of {name}": "{skill} 已从 {name} 移除", + "{skills} are in {name} for {agents}": "{skills} 已放入 {name},供 {agents} 使用", + "{skills} are out of {name}": "{skills} 已从 {name} 移除", "Placed in {dirs} of the project and listed in its .gitignore. A folder there that isn't magpie's is left as it is.": "放在项目的 {dirs} 中并写入其 .gitignore。其中非 magpie 放入的文件夹保持不动。", "{agents} reads no project skills folder magpie knows of.": "{agents} 没有 magpie 已知的项目技能文件夹。", "The skills and MCP servers magpie put in it are taken away, with their lines in its .gitignore. Nothing else in the folder is touched.": "移除 magpie 放入的技能和 MCP 服务器及其在 .gitignore 中的行,文件夹中其他内容不受影响。", @@ -1592,6 +1594,8 @@ magpie.strings({ "Not placed": "未放入", "{skill} is in {name} for {agents}": "{skill} 已放入 {name},供 {agents} 使用", "{skill} is out of {name}": "{skill} 已從 {name} 移除", + "{skills} are in {name} for {agents}": "{skills} 已放入 {name},供 {agents} 使用", + "{skills} are out of {name}": "{skills} 已從 {name} 移除", "Placed in {dirs} of the project and listed in its .gitignore. A folder there that isn't magpie's is left as it is.": "放在專案的 {dirs} 中並寫入其 .gitignore。其中非 magpie 放入的資料夾保持不動。", "{agents} reads no project skills folder magpie knows of.": "{agents} 沒有 magpie 已知的專案技能資料夾。", "The skills and MCP servers magpie put in it are taken away, with their lines in its .gitignore. Nothing else in the folder is touched.": "移除 magpie 放入的技能和 MCP 伺服器及其在 .gitignore 中的行,資料夾中其他內容不受影響。", @@ -2489,6 +2493,8 @@ magpie.strings({ "Not placed": "未配置", "{skill} is in {name} for {agents}": "{skill} を {name} に配置しました({agents} 用)", "{skill} is out of {name}": "{skill} を {name} から外しました", + "{skills} are in {name} for {agents}": "{skills} を {name} に配置しました({agents} 用)", + "{skills} are out of {name}": "{skills} を {name} から外しました", "Placed in {dirs} of the project and listed in its .gitignore. A folder there that isn't magpie's is left as it is.": "プロジェクトの {dirs} に配置し、.gitignore に記載します。そこにある magpie のものでないフォルダはそのままです。", "{agents} reads no project skills folder magpie knows of.": "{agents} は magpie が把握しているプロジェクトのスキルフォルダを読みません。", "The skills and MCP servers magpie put in it are taken away, with their lines in its .gitignore. Nothing else in the folder is touched.": "magpie がそこに置いたスキルと MCP サーバーは、.gitignore の該当行とともに取り除かれます。フォルダ内の他のものには触れません。", @@ -3391,6 +3397,8 @@ magpie.strings({ "Not placed": "Nicht abgelegt", "{skill} is in {name} for {agents}": "{skill} liegt in {name} für {agents}", "{skill} is out of {name}": "{skill} ist aus {name} entfernt", + "{skills} are in {name} for {agents}": "{skills} liegen in {name} für {agents}", + "{skills} are out of {name}": "{skills} sind aus {name} entfernt", "Placed in {dirs} of the project and listed in its .gitignore. A folder there that isn't magpie's is left as it is.": "In {dirs} des Projekts abgelegt und in seiner .gitignore eingetragen. Ein Ordner dort, der nicht von magpie stammt, bleibt unverändert.", "{agents} reads no project skills folder magpie knows of.": "{agents} liest keinen Projekt-Skills-Ordner, den magpie kennt.", "The skills and MCP servers magpie put in it are taken away, with their lines in its .gitignore. Nothing else in the folder is touched.": "Die Skills und MCP-Server, die magpie dort abgelegt hat, werden entfernt, samt ihrer Zeilen in der .gitignore. Sonst wird im Ordner nichts angerührt.", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index 2e4cc4f7b..d2f3eb110 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -672,6 +672,7 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-tag.lib-dot::before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: var(--muted); } .lib-projopts { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding: 8px 12px 8px 49px; border-top: 1px solid var(--line-2); background: var(--card-2); } .lib-projopts .note { font-size: 11px; color: var(--faint); line-height: 1.45; min-width: 0; flex: 1 1 220px; } +.lib-projopts .lib-projpick { height: 26px; color: var(--fg); } .lib-projcopy { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; color: var(--fg-2); cursor: default; } .lib-project .lib-projskill { border-top: 1px solid var(--line-2); } .lib-projfoot { margin: 0; padding: 8px 12px 10px 49px; border-top: 1px solid var(--line-2); } diff --git a/internal/gui/library.go b/internal/gui/library.go index d732672dd..75a5991bd 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -732,6 +732,8 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.RemoveProject(in.Dir, in.Keep) case "projects/skill": res, err = library.ProjectSkill(in.Dir, in.Name, in.Agents) + case "projects/skills": + res, err = library.ProjectSkills(in.Dir, in.Names, in.Agents) case "projects/server": res, err = library.ProjectServer(in.Dir, in.Name, in.Agents) case "projects/copy": diff --git a/internal/gui/tests/project-skills-pick.test.cjs b/internal/gui/tests/project-skills-pick.test.cjs new file mode 100644 index 000000000..03f3d98a3 --- /dev/null +++ b/internal/gui/tests/project-skills-pick.test.cjs @@ -0,0 +1,144 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// POM_JUMPING on X: "skill加入本地项目是能否可选?之前添加到本地项目会把所有skill添加进去". +// An open project's card listed every library skill, one row each, as +// though all were in the project. It now lists the skills the project has, +// and its Skills menu (the app menu, the project's skills ticked) picks which +// go in: one ticked posts projects/skills for the agents the project's skills +// are for already (every agent that reads a project's skills, in a project +// with none yet), one unticked posts it with no agents. The skills it had +// keep their agents. In English and Chinese. No backend: the API is faked. +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 APP = HOME + "/code/app", WEB = HOME + "/code/web"; +const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, ...more }); +const sk = (name) => ({ name, description: name + " things", agents: ["claude", "codex"] }); + +function server(lang, posts) { + const projects = { + [APP]: { pdf: ["codex"] }, + [WEB]: {}, + }; + const lib = () => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [ + agent("claude", "Claude Code", { projectSkills: ".claude/skills" }), + agent("codex", "Codex", { projectSkills: ".agents/skills" }), + agent("goose", "Goose"), + ], + instructions: { agents: [] }, servers: [], skills: [sk("pdf"), sk("docx"), sk("xlsx")], foundServers: [], foundSkills: [], + projects: Object.entries(projects).map(([dir, skills]) => ({ dir, name: path.basename(dir), copy: false, skills: { ...skills }, placed: [], servers: {}, wrote: {} })), + }); + 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() }); + if (url.pathname === "/api/library/projects/skills") { + const b = req.postDataJSON(); + posts.push(b); + for (const n of b.names) { + if (b.agents.length) projects[b.dir][n] = b.agents; + else delete projects[b.dir][n]; + } + return route.fulfill({ json: { ...lib(), result: { changed: [], problems: [] } } }); + } + 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 words = { + en: { menu: "Skills", head: "Pick the skills it gets", none: "No skills yet", in: "docx is in app for Codex", out: "docx is out of app", both: "docx, xlsx are in web for Claude Code, Codex" }, + zh: { menu: "技能", head: "选择它要用的技能", none: "还没有技能", in: "docx 已放入 app,供 Codex 使用", out: "docx 已从 app 移除", both: "docx, xlsx 已放入 web,供 Claude Code, Codex 使用" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a project's skills, picked from its menu", 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 ["en", "zh"]) { + await t.test(lang, async () => { + const w = words[lang], posts = []; + const ctx = await browser.newContext({ viewport: { width: 860, height: 1300 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } 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 app = page.locator("#view-library .lib-project").filter({ hasText: "~/code/app" }); + await app.waitFor(); + await app.locator(".lib-projhead").click(); + const rows = app.locator(".lib-projskill"); + await rows.first().waitFor(); + const names = async (loc) => loc.locator(".who > .name").evaluateAll((ns) => ns.map((n) => n.firstChild.textContent.trim())); + assert.deepEqual(await names(rows), ["pdf"], "the open card lists the skills the project has, not every library skill"); + + const status = (s) => page.waitForFunction((s) => document.querySelector("#status").textContent.trim() === s, s); + const menu = page.locator(".proto-menu"); + const pick = app.locator(".lib-projpick"); + assert.equal((await pick.textContent()).trim(), w.menu); + await pick.click(); + await menu.waitFor(); + assert.equal((await menu.locator(".pm-head").textContent()).trim(), w.head); + assert.deepEqual(await menu.locator(".pm-item").evaluateAll((bs) => bs.map((b) => [b.textContent.trim(), b.getAttribute("aria-checked")])), [["pdf", "true"], ["docx", "false"], ["xlsx", "false"]]); + await menu.locator(".pm-item", { hasText: "docx" }).click(); + assert.equal(posts.length, 0, "nothing is written while the menu is open"); + await page.keyboard.press("Escape"); + await status(w.in); + assert.deepEqual(posts, [{ dir: APP, names: ["docx"], agents: ["codex"] }], "a skill ticked goes to the agents the project's skills are for"); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-project.list .lib-projskill").length === 2); + assert.deepEqual(await names(rows), ["pdf", "docx"]); + + // unticked: out of the project, the rest kept as they were + await pick.click(); + await menu.waitFor(); + await menu.locator(".pm-item", { hasText: "docx" }).click(); + await page.keyboard.press("Escape"); + await status(w.out); + assert.deepEqual(posts.at(-1), { dir: APP, names: ["docx"], agents: [] }); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-projskill").length === 1); + assert.deepEqual(await names(rows), ["pdf"]); + assert.equal(posts.length, 2, "pdf was never written"); + + // a project with no skills yet: its card says so, and two ticked go + // in together, to every agent that reads a project's skills + const web = page.locator("#view-library .lib-project").filter({ hasText: "~/code/web" }); + await web.locator(".lib-projhead").click(); + await web.locator(".lib-projnone").waitFor(); + assert.equal((await web.locator(".lib-projnone").textContent()).trim(), w.none); + assert.equal(await web.locator(".lib-projskill").count(), 0); + await web.locator(".lib-projpick").click(); + await menu.waitFor(); + await menu.locator(".pm-item", { hasText: "docx" }).click(); + await menu.locator(".pm-item", { hasText: "xlsx" }).click(); + await page.mouse.click(5, 5); + await status(w.both); + assert.deepEqual(posts.at(-1), { dir: WEB, names: ["docx", "xlsx"], agents: ["claude", "codex"] }); + await page.waitForFunction(() => [...document.querySelectorAll("#view-library .lib-project")].some((c) => c.querySelectorAll(".lib-projskill").length === 2 && c.textContent.includes("~/code/web"))); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/library/projects.go b/internal/library/projects.go index 865f0e49f..98cef51f5 100644 --- a/internal/library/projects.go +++ b/internal/library/projects.go @@ -423,13 +423,26 @@ func RemoveProject(dir string, keep bool) (*Result, error) { // ProjectSkill sets which agents get a library skill in a project; none // takes it out of the project. func ProjectSkill(dir, name string, agents []string) (*Result, error) { + return ProjectSkills(dir, []string{name}, agents) +} + +// ProjectSkills sets which agents get each of some library skills in a +// project, in one write: the skills a project's card picks from its menu +// (POM_JUMPING on X). The project's other skills stay as they are; none +// takes these out of it. +func ProjectSkills(dir string, names, agents []string) (*Result, error) { return change(func(l *Library) error { p := l.project(dir) if p == nil { return fmt.Errorf("no project %s", dir) } - if l.skill(name) == nil { - return fmt.Errorf("no skill called %s", name) + if len(names) == 0 { + return fmt.Errorf("no skills given") + } + for _, name := range names { + if l.skill(name) == nil { + return fmt.Errorf("no skill called %s", name) + } } var ids []string for _, id := range agents { @@ -438,14 +451,16 @@ func ProjectSkill(dir, name string, agents []string) (*Result, error) { } ids = set(ids, id, true) } - if len(ids) == 0 { - delete(p.Skills, name) - return nil + for _, name := range names { + if len(ids) == 0 { + delete(p.Skills, name) + continue + } + if p.Skills == nil { + p.Skills = map[string][]string{} + } + p.Skills[name] = slices.Clone(ids) } - if p.Skills == nil { - p.Skills = map[string][]string{} - } - p.Skills[name] = ids return nil }) } diff --git a/internal/library/projects_test.go b/internal/library/projects_test.go index 4da049777..1f4bbf261 100644 --- a/internal/library/projects_test.go +++ b/internal/library/projects_test.go @@ -82,6 +82,43 @@ func TestProjectSkillsLinked(t *testing.T) { } } +// A project's card picks some of the library's skills in one write +// (POM_JUMPING on X): only those go in, and the skills the project had +// keep their agents; a name the library doesn't have changes nothing. +func TestProjectSkillsPickSome(t *testing.T) { + h, proj := projectLib(t) + skill(t, filepath.Join(h, "src", "xlsx"), "xlsx", "Sheets") + ok(t)(InstallSkills(filepath.Join(h, "src"), []string{"xlsx"}, nil)) + ok(t)(ProjectSkill(proj, "pdf", []string{"codex"})) + + ok(t)(ProjectSkills(proj, []string{"docx"}, []string{"claude", "codex"})) + v, _ := Read(nil) + if got := v.Projects[0].Skills; len(got) != 2 || !slices.Equal(got["pdf"], []string{"codex"}) || !slices.Equal(got["docx"], []string{"claude", "codex"}) { + t.Errorf("skills: %+v", got) + } + for _, e := range []string{".claude/skills/docx", ".agents/skills/docx", ".agents/skills/pdf"} { + if !isLink(t, filepath.Join(proj, e)) { + t.Errorf("%s isn't placed", e) + } + } + for _, e := range []string{".claude/skills/pdf", ".claude/skills/xlsx", ".agents/skills/xlsx"} { + gone(t, filepath.Join(proj, e)) + } + + if _, err := ProjectSkills(proj, []string{"xlsx", "nope"}, []string{"claude"}); err == nil { + t.Error("a skill the library hasn't was taken") + } + gone(t, filepath.Join(proj, ".claude/skills/xlsx")) + + ok(t)(ProjectSkills(proj, []string{"docx"}, nil)) + v, _ = Read(nil) + if got := v.Projects[0].Skills; len(got) != 1 || !slices.Equal(got["pdf"], []string{"codex"}) { + t.Errorf("skills after: %+v", got) + } + gone(t, filepath.Join(proj, ".claude/skills/docx")) + gone(t, filepath.Join(proj, ".agents/skills/docx")) +} + func TestProjectGitignoreMadeAndTakenAway(t *testing.T) { _, proj := projectLib(t) os.Remove(filepath.Join(proj, ".gitignore"))