diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 2b5eb9c13..a232944e2 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1447,6 +1447,14 @@ const I18N = { "Writes the library into every agent again": "把资源库重新写入每个 Agent", "MCP server {name}": "MCP 服务器 {name}", "Skill {name}": "技能 {name}", + "{agent} has a skill of its own called {name}, not the same as the library's": "{agent} 已有自己的同名技能 {name},与资源库中的不同", + "Use the library's": "用资源库的", + "Keep {agent}'s": "保留 {agent} 自己的", + "Sets {agent}'s own {name} aside with the backups and gives it the library's in its place": "把 {agent} 自己的 {name} 移到备份里,换成资源库的", + "{agent} keeps its own {name}, and the library no longer gives it this skill": "{agent} 保留自己的 {name},资源库不再把这个技能给它", + "{agent} has the library's {name} now; its own is kept with the backups": "{agent} 已换成资源库的 {name},它自己的已放进备份", + "{agent} keeps its own {name}": "{agent} 保留了自己的 {name}", + "{agents} has the very same files; bringing it in gives it the library's, its copy kept with the backups": "{agents} 有一份完全相同的副本;导入后它会换成资源库的,副本放进备份", "The project": "项目", "Written to {agent}": "已写入 {agent}", "Written to {n} agents": "已写入 {n} 个 Agent", diff --git a/internal/gui/assets/library.css b/internal/gui/assets/library.css index fbda0cd32..b51809ba2 100644 --- a/internal/gui/assets/library.css +++ b/internal/gui/assets/library.css @@ -140,6 +140,7 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-problems li { min-width: 0; } .lib-problems-sep { color: var(--muted); } .lib-problems-err { display: block; color: var(--fg-2); font: 11px var(--code); margin-top: 1px; } +.lib-problems-fix { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 5px; } /* agents a server or skill is given to: an icon each, lit when it has it */ .lib-agents { display: flex; flex-wrap: wrap; gap: 3px; flex: none; justify-content: flex-end; max-width: 50%; } diff --git a/internal/gui/assets/library.js b/internal/gui/assets/library.js index b0bb096d9..4e96dfbb4 100644 --- a/internal/gui/assets/library.js +++ b/internal/gui/assets/library.js @@ -399,7 +399,20 @@ const li = el("li"); const who = p.what.startsWith("project:") ? tilde(p.agent) : p.agent ? nameOf(p.agent) : ""; if (who) li.append(el("b", "", who), el("span", "lib-problems-sep", " · ")); - li.append(el("span", "", problemWhat(p.what)), el("span", "lib-problems-err", p.error)); + // an agent's own skill in the library's way is settled right here: + // the library's in its place (the agent's kept aside), or the agent's + const own = p.own && p.what.startsWith("skill:") && p.agent; + const name = own && p.what.slice("skill:".length); + li.append(el("span", "", problemWhat(p.what)), el("span", "lib-problems-err", own ? t("{agent} has a skill of its own called {name}, not the same as the library's", { agent: who, name }) : p.error)); + if (own) { + const fix = el("div", "lib-problems-fix"); + const use = button(t("Use the library's"), "action", () => change("skills/use-library", { name, agent: p.agent }, t("{agent} has the library's {name} now; its own is kept with the backups", { agent: who, name }))); + use.title = t("Sets {agent}'s own {name} aside with the backups and gives it the library's in its place", { agent: who, name }); + const keep = button(t("Keep {agent}'s", { agent: who }), "action", () => change("skills/keep-own", { name, agent: p.agent }, t("{agent} keeps its own {name}", { agent: who, name }))); + keep.title = t("{agent} keeps its own {name}, and the library no longer gives it this skill", { agent: who, name }); + fix.append(use, keep); + li.append(fix); + } ul.append(li); } card.append(ttl, ul); @@ -2172,13 +2185,15 @@ if (f.shared) { const src = el("div", "lib-src"); src.append(el("span", "", t("shared in")), pathLink(f.shared)); who.append(src); } if (f.link) { const src = el("div", "lib-src"); src.append(el("span", "", t("linked from")), pathLink(f.link)); who.append(src); } const have = el("div", "lib-have"); - for (const id of f.agents) { const a = agentOf(id); if (a) { const i = agentIcon(a.icon); i.title = a.name; have.append(i); } } + // an agent with a copy of the very same files has it as much as one + // with the folder itself: it isn't said to differ + for (const id of [...f.agents, ...(f.copies || [])]) { const a = agentOf(id); if (a) { const i = agentIcon(a.icon); i.title = f.agents.includes(id) ? a.name : a.name + " — " + t("{agents} has the very same files; bringing it in gives it the library's, its copy kept with the backups", { agents: a.name }); have.append(i); } } row.append(glyph(GLYPH.skill), who, have); if (f.others?.length) row.append(tag(t("differs in {agents}", { agents: f.others.map(nameOf).join(", ") }), "warn", t("{agents} has another skill by this name; bringing this one in leaves that one as it is", { agents: f.others.map(nameOf).join(", ") }))); const b = button(t("Bring in"), "action", () => change("skills/import", { name: f.name }, t("{name} is in the library now", { name: f.name }))); b.title = f.shared ? t("Keeps it where it is in the shared skills folder and links to it: you can give it to any agent") - : f.link ? t("Keeps a link to where it is: {agents} go on having it, and you can give it to the others", { agents: f.agents.map(nameOf).join(", ") }) - : t("Moves it into the library and links it back: {agents} go on having it, and you can give it to the others", { agents: f.agents.map(nameOf).join(", ") }); + : f.link ? t("Keeps a link to where it is: {agents} go on having it, and you can give it to the others", { agents: [...f.agents, ...(f.copies || [])].map(nameOf).join(", ") }) + : t("Moves it into the library and links it back: {agents} go on having it, and you can give it to the others", { agents: [...f.agents, ...(f.copies || [])].map(nameOf).join(", ") }); row.append(b); return row; } diff --git a/internal/gui/library.go b/internal/gui/library.go index 151c0ecb2..f76d27c4b 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -258,6 +258,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { Paths []string Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents Server library.Server + Agent string // the agent whose own skill is in the library's way ID string // a market server's, or a market skill's in its repository Values map[string]string // what a market server needs Dir string // a project's folder @@ -301,6 +302,10 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.ImportSkill(in.Name) case "skills/import-all": res, err = library.ImportSkills(in.Names) + case "skills/use-library": + res, err = library.UseLibrarySkill(in.Name, in.Agent) + case "skills/keep-own": + res, err = library.KeepAgentSkill(in.Name, in.Agent) case "market/server": res, err = library.InstallServer(in.ID, in.Values, in.Agents) case "market/skill": diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index fe16bb58d..beac25e0a 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -293,6 +293,16 @@ name at once, the rows go and the toast says "3 skills are in the library now", or names the one that couldn't be brought in, which stays listed; the click scrolls nothing; in English and Chinese, with `/api/plugins` faked. +`own-skill.test.cjs` opens the Library with Claude Code's own impeccable in +the library skill's way (StringKe, JasonLeeForOnly on Discord): the warning +row says so in the reader's language and has "Use the library's" and "Keep +Claude Code's", which post `skills/use-library` and `skills/keep-own` with +the skill and the agent; the warning goes, the toast says what was done, and +the click scrolls nothing; no coloured stripe down the card or the row. A +found skill with a byte copy in another agent shows both agents' icons and +no "differs in"; one that really differs still says so. Chromium and +WebKit, in English and Chinese, with `/api/plugins` faked. + `model-pick.test.cjs` picks Claude Code's model with the Agents page scrolled while a faked `/api/set` takes 2.5s to answer: the row shows the new model at once, in the window and in the tray panel's opened row and its @@ -358,7 +368,7 @@ that draws the latest numbers. The checks run in English and Chinese. With Node.js and Playwright available: ```sh -node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs +node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs ``` If Playwright is installed outside the repository, set `NODE_PATH` to the diff --git a/internal/gui/tests/own-skill.test.cjs b/internal/gui/tests/own-skill.test.cjs new file mode 100644 index 000000000..78fa4a84f --- /dev/null +++ b/internal/gui/tests/own-skill.test.cjs @@ -0,0 +1,144 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// StringKe and JasonLeeForOnly on Discord: after Bring in all, "Claude Code +// already has a skill of its own called impeccable" stood in the Library's +// warning with nothing to do about it. The warning row now says it in the +// reader's language and settles it in place: "Use the library's" posts +// skills/use-library (the agent's own kept aside), "Keep Claude Code's" +// posts skills/keep-own (the agent off the skill), the warning goes, and the +// click scrolls nothing. A skill found in an agent with a byte copy in +// another is shown as that agent's too, not as differing there. 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/stringke"; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills` }); +const problem = { agent: "claude", what: "skill:impeccable", error: "Claude Code already has a skill of its own called impeccable", own: true }; +const lib = (agents, problems, foundSkills = []) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("claude", "Claude Code"), agent("codex", "Codex"), agent("gemini", "Gemini CLI")], + instructions: { agents: [] }, servers: [], foundServers: [], projects: [], foundSkills, + skills: [ + { name: "impeccable", description: "Design", kind: "", agents }, + ...Array.from({ length: 12 }, (_, i) => ({ name: "s" + i, description: "d", kind: "", agents: ["codex"] })), + ], + problems, +}); +const found = [ + { name: "polish", description: "Polish", agents: ["claude"], copies: ["codex"] }, + { name: "audit", description: "Audit", agents: ["claude"], others: ["gemini"] }, +]; + +function server(lang, posts) { + 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(["claude", "codex"], [problem], found) }); + if (url.pathname === "/api/library/skills/use-library") { + posts.push([url.pathname, req.postDataJSON()]); + return route.fulfill({ json: { ...lib(["claude", "codex"], [], found), result: { changed: ["claude"], problems: [] } } }); + } + if (url.pathname === "/api/library/skills/keep-own") { + posts.push([url.pathname, req.postDataJSON()]); + return route.fulfill({ json: { ...lib(["codex"], [], found), 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: { + line: "Claude Code · Skill impeccable", + err: "Claude Code has a skill of its own called impeccable, not the same as the library's", + use: "Use the library's", keep: "Keep Claude Code's", + used: "Claude Code has the library's impeccable now; its own is kept with the backups", + kept: "Claude Code keeps its own impeccable", + differs: "differs in Gemini CLI", + }, + zh: { + line: "Claude Code · 技能 impeccable", + err: "Claude Code 已有自己的同名技能 impeccable,与资源库中的不同", + use: "用资源库的", keep: "保留 Claude Code 自己的", + used: "Claude Code 已换成资源库的 impeccable,它自己的已放进备份", + kept: "Claude Code 保留了自己的 impeccable", + differs: "Gemini CLI 中不同", + }, +}; + +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(" ")); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": an agent's own skill in the library's way", 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(); + }); + const open = async (lang, posts) => { + const ctx = await browser.newContext({ viewport: { width: 980, height: 700 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + 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(); + await page.locator("#view-library .lib-row").first().waitFor(); + return page; + }; + + for (const lang of ["en", "zh"]) { + const w = words[lang]; + for (const [which, route, done, agents] of [["use", "/api/library/skills/use-library", "used"], ["keep", "/api/library/skills/keep-own", "kept"]]) { + await t.test(`${lang}: ${w[which]} settles it from the warning`, async () => { + const posts = []; + const page = await open(lang, posts); + const card = page.locator("#view-library > .lib-problems"); + const li = card.locator("li"); + await li.waitFor(); + assert.equal(await li.evaluate((l) => [...l.children].filter((c) => !c.matches(".lib-problems-err, .lib-problems-fix")).map((c) => c.textContent).join("")), w.line); + assert.equal(await li.locator(".lib-problems-err").textContent(), w.err); + const buttons = li.locator(".lib-problems-fix button"); + assert.deepEqual(await buttons.allTextContents(), [w.use, w.keep]); + // a dot says it, not a coloured stripe down its side + assert.equal(await card.evaluate((c) => getComputedStyle(c).borderLeftWidth), "0px"); + assert.equal(await li.evaluate((c) => getComputedStyle(c).borderLeftWidth), "0px"); + const before = await scrolled(page); + await li.getByRole("button", { name: w[which], exact: true }).click(); + await card.waitFor({ state: "detached" }); + assert.deepEqual(posts, [[route, { name: "impeccable", agent: "claude" }]]); + await page.locator("#status").filter({ hasText: w[done] }).waitFor(); + assert.equal(await scrolled(page), before, "the click scrolled the page"); + await page.close(); + }); + } + + await t.test(lang + ": a byte copy in another agent isn't said to differ", async () => { + const page = await open(lang, []); + const polish = page.locator("#view-library .lib-row").filter({ has: page.locator(".name", { hasText: /^polish$/ }) }); + const audit = page.locator("#view-library .lib-row").filter({ has: page.locator(".name", { hasText: /^audit$/ }) }); + await polish.waitFor(); + assert.equal(await polish.locator(".lib-have > *").count(), 2, "Claude Code and Codex have it"); + assert.equal(await polish.getByText(w.differs.replace("Gemini CLI", "Codex")).count(), 0); + assert.equal(await audit.getByText(w.differs).count(), 1); + await page.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/library/backup.go b/internal/library/backup.go index 2b8ee27c6..2b82e8f5e 100644 --- a/internal/library/backup.go +++ b/internal/library/backup.go @@ -57,7 +57,9 @@ func (b *backups) keep(agent, path string) error { return os.WriteFile(dst, data, 0o600) } -// prune leaves the newest keepBackups. +// prune leaves the newest keepBackups, and every one that holds a skill +// folder set aside (a skill taken out of the library, or an agent's own +// the library's took the place of): that is the only copy of it left. func pruneBackups() { es, err := os.ReadDir(BackupDir()) if err != nil { @@ -65,7 +67,7 @@ func pruneBackups() { } var names []string for _, e := range es { - if e.IsDir() && !strings.HasPrefix(e.Name(), ".") { + if e.IsDir() && !strings.HasPrefix(e.Name(), ".") && !holdsSkills(filepath.Join(BackupDir(), e.Name())) { names = append(names, e.Name()) } } @@ -75,3 +77,14 @@ func pruneBackups() { names = names[1:] } } + +// holdsSkills is whether a backup has skill folders in it: /skills, +// or //skills. +func holdsSkills(dir string) bool { + for _, pat := range []string{"skills", "*/skills"} { + if m, _ := filepath.Glob(filepath.Join(dir, pat)); len(m) > 0 { + return true + } + } + return false +} diff --git a/internal/library/own_skill_test.go b/internal/library/own_skill_test.go new file mode 100644 index 000000000..935c7ac5e --- /dev/null +++ b/internal/library/own_skill_test.go @@ -0,0 +1,171 @@ +package library + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// After Bring in all (StringKe, JasonLeeForOnly on Discord): "Claude Code +// already has a skill of its own called impeccable", and nothing to do +// about it. An agent's folder by the library skill's name that holds the +// very same files — a copy CC Switch made into each agent, or one put back +// by what installed it — gives way to the library's, kept aside; one that +// differs is said, and settled either way from the warning. +func TestOwnSkillInTheWay(t *testing.T) { + h := sandbox(t) + claude := filepath.Join(h, ".claude/skills/impeccable") + codex := filepath.Join(h, ".codex/skills/impeccable") + gemini := filepath.Join(h, ".gemini/skills/impeccable") + skill(t, claude, "impeccable", "Design") + skill(t, codex, "impeccable", "Design") // a byte copy + skill(t, gemini, "impeccable", "Old design") // another + write(t, filepath.Join(codex, ".DS_Store"), "finder") + skill(t, filepath.Join(h, ".claude/skills/notes"), "notes", "Mine") + + v, _ := Read(nil) + i := slices.IndexFunc(v.FoundSkills, func(f FoundSkill) bool { return f.Name == "impeccable" }) + if i < 0 { + t.Fatalf("found: %+v", v.FoundSkills) + } + if f := v.FoundSkills[i]; !slices.Equal(f.Agents, []string{"claude"}) || !slices.Equal(f.Copies, []string{"codex"}) || !slices.Equal(f.Others, []string{"gemini"}) { + t.Errorf("impeccable: %+v", f) + } + + // brought in from the agents' own folders: nothing stands in the way + r := ok(t)(ImportSkills([]string{"impeccable", "notes"})) + if len(r.Unimported) != 0 { + t.Fatalf("unimported: %+v", r.Unimported) + } + for _, p := range []string{claude, codex} { + if !ours(p, "impeccable") { + t.Errorf("%s isn't the library's", p) + } + } + if agents := skillAgents(t, "impeccable"); !slices.Equal(agents, []string{"claude", "codex"}) { + t.Errorf("agents: %v", agents) + } + if m, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "codex", "skills", "impeccable", "SKILL.md")); len(m) != 1 { + t.Errorf("codex's copy isn't kept aside: %v", m) + } + if read(t, filepath.Join(gemini, "SKILL.md")) == "" || linked(gemini) { + t.Error("gemini's own was touched") + } + + // what installed it puts a copy back into Claude Code: the library's + // takes its place again, the copy kept + os.Remove(claude) + if err := copyDir(skillDir("impeccable"), claude); err != nil { + t.Fatal(err) + } + write(t, filepath.Join(claude, ".DS_Store"), "x") + ok(t)(Sync()) + if !ours(claude, "impeccable") { + t.Error("claude's copy wasn't taken over") + } + if m, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "claude", "skills", "impeccable", "SKILL.md")); len(m) != 1 { + t.Errorf("claude's copy isn't kept aside: %v", m) + } + + // given to Gemini, whose own differs: said, and left as it is + r, err := SkillAgents("impeccable", []string{"claude", "codex", "gemini"}) + if err != nil { + t.Fatal(err) + } + if len(r.Problems) != 1 || r.Problems[0].Agent != "gemini" || !r.Problems[0].Own || !strings.Contains(r.Problems[0].Error, "of its own") { + t.Fatalf("problems: %+v", r.Problems) + } + if linked(gemini) || !strings.Contains(read(t, filepath.Join(gemini, "SKILL.md")), "Old design") { + t.Error("gemini's own was touched") + } + + // keep the agent's: Gemini is off the skill, its own stays, no problem + ok(t)(KeepAgentSkill("impeccable", "gemini")) + if agents := skillAgents(t, "impeccable"); slices.Contains(agents, "gemini") { + t.Errorf("gemini still gets it: %v", agents) + } + if linked(gemini) || !strings.Contains(read(t, filepath.Join(gemini, "SKILL.md")), "Old design") { + t.Error("gemini's own was touched") + } + + // use the library's: Gemini's own is kept aside, the library's linked + ok(t)(UseLibrarySkill("impeccable", "gemini")) + if !ours(gemini, "impeccable") { + t.Error("gemini hasn't the library's") + } + if !slices.Contains(skillAgents(t, "impeccable"), "gemini") { + t.Error("gemini isn't on the skill") + } + m, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "gemini", "skills", "impeccable", "SKILL.md")) + if len(m) != 1 || !strings.Contains(read(t, m[0]), "Old design") { + t.Errorf("gemini's own isn't kept aside: %v", m) + } + + if _, err := UseLibrarySkill("nothing", "gemini"); err == nil { + t.Error("no such skill, and no error") + } + if _, err := KeepAgentSkill("impeccable", "nobody"); err == nil { + t.Error("no such agent, and no error") + } +} + +func skillAgents(t *testing.T, name string) []string { + t.Helper() + v, err := Read(nil) + if err != nil { + t.Fatal(err) + } + for _, s := range v.Skills { + if s.Name == name { + return s.Agents + } + } + t.Fatalf("no skill %s", name) + return nil +} + +func TestSameTree(t *testing.T) { + d := t.TempDir() + a, b := filepath.Join(d, "a"), filepath.Join(d, "b") + skill(t, a, "x", "X") + skill(t, b, "x", "X") + write(t, filepath.Join(a, ".DS_Store"), "1") + write(t, filepath.Join(b, ".git/HEAD"), "ref") + write(t, filepath.Join(b, marker), "copied") + if !sameTree(a, b) { + t.Fatal("the same files aren't the same") + } + write(t, filepath.Join(b, "scripts/run.sh"), "echo ho\n") // same size + if sameTree(a, b) { + t.Error("other bytes are the same") + } + write(t, filepath.Join(b, "scripts/run.sh"), "echo hi\n") + write(t, filepath.Join(b, "more.md"), "") + if sameTree(a, b) { + t.Error("another file is the same") + } + if sameTree(a, filepath.Join(d, "gone")) { + t.Error("a folder that isn't there is the same") + } +} + +// A backup holding a skill folder set aside is its only copy: it is never +// pruned with the others. +func TestPruneKeepsSkillsSetAside(t *testing.T) { + sandbox(t) + write(t, filepath.Join(BackupDir(), "2000-01-01_00-00-00.000", "gemini", "skills", "x", "SKILL.md"), "mine") + for i := range keepBackups + 3 { + write(t, filepath.Join(BackupDir(), fmt.Sprintf("2026-01-01_00-00-%02d.000", i), "claude", "CLAUDE.md"), "") + } + pruneBackups() + if _, err := os.Stat(filepath.Join(BackupDir(), "2000-01-01_00-00-00.000", "gemini", "skills", "x", "SKILL.md")); err != nil { + t.Error("the skill set aside was pruned") + } + es, _ := os.ReadDir(BackupDir()) + if len(es) != keepBackups+1 { + t.Errorf("%d backups", len(es)) + } +} diff --git a/internal/library/shared_skills_test.go b/internal/library/shared_skills_test.go index dbe51afae..338fc4ebe 100644 --- a/internal/library/shared_skills_test.go +++ b/internal/library/shared_skills_test.go @@ -67,7 +67,7 @@ func TestSharedAgentsSkills(t *testing.T) { if f.Shared == "" || f.Link != "" || !slices.Equal(agents, []string{"codex", "pi"}) || len(f.Others) != 0 { t.Errorf("orchestration is one skill in the shared folder, pi and codex: %+v", f) } - if f := byName["orca-cli"]; f.Shared == "" || len(f.Agents) != 0 || !slices.Equal(f.Others, []string{"codex"}) { + if f := byName["orca-cli"]; f.Shared == "" || len(f.Agents) != 0 || len(f.Others) != 0 || !slices.Equal(f.Copies, []string{"codex"}) { t.Errorf("orca-cli: %+v", f) } @@ -95,14 +95,15 @@ func TestSharedAgentsSkills(t *testing.T) { t.Errorf("the library's %s isn't a link to %s", n, want) } } - // the agents that had it have the library's, the one with its own copy keeps it - for _, d := range []string{".pi/agent/skills/orchestration", ".codex/skills/orchestration", ".gemini/skills/grilling"} { + // the agents that had it have the library's, and so has the one with a + // byte copy of its own, kept aside with the backups + for _, d := range []string{".pi/agent/skills/orchestration", ".codex/skills/orchestration", ".gemini/skills/grilling", ".codex/skills/orca-cli"} { if !ours(filepath.Join(h, d), filepath.Base(d)) { t.Errorf("%s isn't the library's", d) } } - if linked(filepath.Join(h, ".codex/skills/orca-cli")) { - t.Error("codex's own copy was replaced") + if m, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "codex", "skills", "orca-cli", "SKILL.md")); len(m) != 1 { + t.Errorf("codex's own copy isn't kept aside: %v", m) } v, _ := Read(nil) for _, s := range v.Skills { diff --git a/internal/library/skills.go b/internal/library/skills.go index 9398984a1..1caf430d3 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -2,6 +2,7 @@ package library import ( "archive/tar" + "bytes" "compress/gzip" "errors" "fmt" @@ -307,8 +308,20 @@ func (l *Library) syncSkills(t *Target, res *Result, all []*Target) { continue } if _, err := os.Lstat(p); err == nil { - res.fail(id, "skill:"+s.Name, fmt.Errorf("%s already has a skill of its own called %s", t.Agent.Name, s.Name)) - continue + // the agent has one of its own by that name: the very one, or + // a copy of it (what installed it put it back, or copied it + // into each agent, as CC Switch does), gives way to the + // library's, kept aside; one that differs is the user's to + // settle (UseLibrarySkill, KeepAgentSkill) + if !sameTree(p, skillDir(s.Name)) { + res.Problems = append(res.Problems, Problem{Agent: id, What: "skill:" + s.Name, Own: true, + Error: fmt.Sprintf("%s already has a skill of its own called %s", t.Agent.Name, s.Name)}) + continue + } + if _, err := setAside(id, p); err != nil { + res.fail(id, "skill:"+s.Name, err) + continue + } } if err := link(p, s.Name); err != nil { res.fail(id, "skill:"+s.Name, err) @@ -916,6 +929,71 @@ func RemoveSkill(name string) (*Result, error) { }) } +// UseLibrarySkill settles an agent's own skill that stands in the way of +// the library's by that name for the library's: the agent's folder is kept +// aside with the backups, and the library's linked in its place. +func UseLibrarySkill(name, agentID string) (*Result, error) { + return change(func(l *Library) error { + s, t, err := ownSkill(l, name, agentID) + if err != nil { + return err + } + p := filepath.Join(t.Skills, name) + if _, err := os.Lstat(p); err == nil && !ours(p, name) && realDir(p) != realDir(skillDir(name)) { + if _, err := setAside(t.Agent.ID, p); err != nil { + return err + } + } + if !slices.Contains(s.Agents, t.Agent.ID) && !slices.ContainsFunc(sharing(t), func(o string) bool { return slices.Contains(s.Agents, o) }) { + s.Agents = set(s.Agents, t.Agent.ID, true) + } + return nil + }) +} + +// KeepAgentSkill settles it the other way: the agent keeps its own, and +// the library no longer gives it that skill (nor any agent that reads the +// very same folder). +func KeepAgentSkill(name, agentID string) (*Result, error) { + return change(func(l *Library) error { + s, t, err := ownSkill(l, name, agentID) + if err != nil { + return err + } + for _, id := range append(sharing(t), t.Agent.ID) { + s.Agents = set(s.Agents, id, false) + } + return nil + }) +} + +func ownSkill(l *Library, name, agentID string) (*Skill, *Target, error) { + s := l.skill(name) + if s == nil { + return nil, nil, fmt.Errorf("no skill called %s", name) + } + id, err := Takes(agentID, "skills") + if err != nil { + return nil, nil, err + } + t := targetByID(id) + if t == nil || t.Skills == "" { + return nil, nil, fmt.Errorf("%s has no skills folder magpie knows of", agentID) + } + return s, t, nil +} + +// sharing are the other agents whose skills folder is the very same as t's. +func sharing(t *Target) []string { + var out []string + for _, o := range Targets() { + if o.Agent.ID != t.Agent.ID && o.Skills != "" && realDir(o.Skills) == realDir(t.Skills) { + out = append(out, o.Agent.ID) + } + } + return out +} + // ---- skills the agents have of their own ---------------------------------- // FoundSkill is a skill an agent has that the library doesn't. @@ -924,6 +1002,10 @@ type FoundSkill struct { Description string `json:"description"` Agents []string `json:"agents"` // the agents that have this very folder Others []string `json:"others,omitempty"` // agents with another by that name + // Copies are the agents with another folder by that name holding the + // very same files (CC Switch copies a skill into each agent): brought + // in, they get the library's in its place + Copies []string `json:"copies,omitempty"` Link string `json:"link,omitempty"` // where it really is, when it's a link // Shared is its entry in the user-wide ~/.agents/skills, when it is // there; the agents that have it are those whose entry is a link (or a @@ -976,6 +1058,8 @@ func foundSkills(l *Library) []FoundSkill { if pl.agent != "" && !slices.Contains(f.Agents, pl.agent) { f.Agents = append(f.Agents, pl.agent) } + case sameTree(p, f.at): + f.Copies = append(f.Copies, pl.agent) default: f.Others = append(f.Others, pl.agent) } @@ -1043,19 +1127,30 @@ func importSkill(l *Library, found []FoundSkill, name string) error { return err } } else { - if err := move(f.real, skillDir(name)); err != nil { + // a move that copied it all but couldn't take the whole folder away + // (a file in it held open) has brought it in all the same: what is + // left is set aside below, not left to stand in the library's way + var left *leftBehind + if err := move(f.real, skillDir(name)); err != nil && !errors.As(err, &left) { return err } src = nil } for _, id := range f.Agents { // links to what was moved, or to the folder elsewhere if t := targetByID(id); t != nil { - if p := filepath.Join(t.Skills, name); linked(p) { + p := filepath.Join(t.Skills, name) + if linked(p) { os.Remove(p) + } else if _, err := os.Lstat(p); err == nil && src == nil { + setAside(id, p) } } } - l.Skills = append(l.Skills, &Skill{Name: name, Source: src, Agents: slices.Clone(f.Agents)}) + // an agent with a copy of the very same gets the library's in its + // place (its copy kept aside), as the agents with the folder itself do + agents := slices.Concat(f.Agents, f.Copies) + slices.Sort(agents) + l.Skills = append(l.Skills, &Skill{Name: name, Source: src, Agents: slices.Compact(agents)}) return nil } @@ -1112,7 +1207,134 @@ func move(from, to string) error { os.RemoveAll(to) return err } - return os.RemoveAll(from) + if err := os.RemoveAll(from); err != nil { + return &leftBehind{err} + } + return nil +} + +// leftBehind is a move that copied everything but couldn't take all of +// what it moved away (a file in it open, on Windows): the copy is whole. +type leftBehind struct{ err error } + +func (e *leftBehind) Error() string { return e.err.Error() } +func (e *leftBehind) Unwrap() error { return e.err } + +// setAside moves an agent's own skill (a folder, or a link) out of its +// way, into a backup of its own: nothing of the user's is just deleted. +func setAside(agent, p string) (string, error) { + dst := filepath.Join(BackupDir(), time.Now().Format("2006-01-02_15-04-05.000"), agent, "skills", filepath.Base(p)) + for i := 2; ; i++ { + if _, err := os.Lstat(dst); errors.Is(err, fs.ErrNotExist) { + break + } + dst = filepath.Join(filepath.Dir(dst), fmt.Sprintf("%s-%d", filepath.Base(p), i)) + } + if err := os.MkdirAll(filepath.Dir(dst), 0o700); err != nil { + return "", err + } + if err := move(p, dst); err != nil { + return "", err + } + return dst, nil +} + +// sameTree is whether two skill folders (links followed) hold the same +// files with the same bytes, leaving aside what Finder or version control +// keeps in one (.DS_Store, .git) and the mark on magpie's own copy. +func sameTree(a, b string) bool { + a, b = realDir(a), realDir(b) + fa, okA := treeOf(a) + fb, okB := treeOf(b) + if !okA || !okB || len(fa) != len(fb) { + return false + } + for rel, x := range fa { + y, ok := fb[rel] + if !ok || x != y { + return false + } + if x.link == "" && !sameFile(filepath.Join(a, rel), filepath.Join(b, rel)) { + return false + } + } + return true +} + +type treeEntry struct { + size int64 + link string // where a link in it points +} + +// treeOf is a folder's files and links by where they are in it; not ok +// when it can't be read, or is too big to be worth comparing. +func treeOf(root string) (map[string]treeEntry, bool) { + out := map[string]treeEntry{} + var total int64 + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if p == root { + if !d.IsDir() { + return errors.New("not a folder") + } + return nil + } + if n := d.Name(); n == ".DS_Store" || n == marker || n == ".git" { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + if d.IsDir() { + return nil + } + rel, _ := filepath.Rel(root, p) + if d.Type()&fs.ModeSymlink != 0 { + to, err := os.Readlink(p) + if err != nil { + return err + } + out[rel] = treeEntry{link: to} + } else if d.Type().IsRegular() { + fi, err := d.Info() + if err != nil { + return err + } + out[rel] = treeEntry{size: fi.Size()} + total += fi.Size() + } + if len(out) > 20000 || total > 256<<20 { + return errors.New("too big to compare") + } + return nil + }) + return out, err == nil +} + +func sameFile(a, b string) bool { + fa, err := os.Open(a) + if err != nil { + return false + } + defer fa.Close() + fb, err := os.Open(b) + if err != nil { + return false + } + defer fb.Close() + ba, bb := make([]byte, 64<<10), make([]byte, 64<<10) + for { + na, ea := io.ReadFull(fa, ba) + nb, eb := io.ReadFull(fb, bb) + if na != nb || !bytes.Equal(ba[:na], bb[:nb]) { + return false + } + if ea != nil || eb != nil { + return ea == eb || (ea == io.EOF || ea == io.ErrUnexpectedEOF) && (eb == io.EOF || eb == io.ErrUnexpectedEOF) + } + } } // SkillText is a library skill's SKILL.md, for the page to show. diff --git a/internal/library/sync.go b/internal/library/sync.go index d169fb228..65ba03a3d 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -27,6 +27,9 @@ type Problem struct { Agent string `json:"agent"` What string `json:"what"` // instructions, mcp:, skill: Error string `json:"error"` + // Own is a skill the agent has a folder of its own for, not the + // library's: the page offers to use the library's or keep the agent's + Own bool `json:"own,omitempty"` } func (r *Result) changed(agent string) { diff --git a/library_cli.go b/library_cli.go index 0f2f91d21..827898361 100644 --- a/library_cli.go +++ b/library_cli.go @@ -20,6 +20,8 @@ const libraryUsage = `magpie library what the library gives magpie library skill agents magpie library skill rm (skills are installed from the app's Library page) magpie library skill update [name] fetch a skill from GitHub again; with no name, every one from there + magpie library skill use-library an agent's own skill by that name is in the way: set it aside, link the library's + magpie library skill keep-own …or keep the agent's, and take the agent off the library's magpie library rtk which agents run their shell commands through RTK (rtk-ai.app), to save tokens magpie library rtk on|off switch it (on with RTK's own installer; off works with RTK gone) magpie library rtk install install RTK (Homebrew, winget, or RTK's own script) @@ -112,6 +114,10 @@ func libraryCmd(args []string) error { } case len(rest) == 2 && rest[0] == "rm": res, err = library.RemoveSkill(rest[1]) + case len(rest) == 3 && rest[0] == "use-library": + res, err = library.UseLibrarySkill(rest[1], rest[2]) + case len(rest) == 3 && rest[0] == "keep-own": + res, err = library.KeepAgentSkill(rest[1], rest[2]) case len(rest) == 2 && rest[0] == "update": if res, err = library.UpdateSkill(rest[1]); err == nil { fmt.Println(green.Render("✓"), rest[1], "is up to date") @@ -169,6 +175,10 @@ func printLibraryResult(res *library.Result) { } for _, p := range res.Problems { fmt.Println(amber.Render("!"), p.Agent, muted.Render(p.What+":"), p.Error) + if n, ok := strings.CutPrefix(p.What, "skill:"); ok && p.Own { + fmt.Println(muted.Render(" use the library's (the agent's kept aside): magpie library skill use-library " + n + " " + p.Agent)) + fmt.Println(muted.Render(" or keep the agent's: magpie library skill keep-own " + n + " " + p.Agent)) + } } if len(res.Updated) > 0 { fmt.Println(green.Render("✓"), "up to date:", strings.Join(res.Updated, ", "))