diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 51998020b..01c9fa573 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "regexp" "slices" "strconv" "strings" @@ -118,6 +119,74 @@ func codexIn(at place) *Agent { os.Remove(catalogPath) return nil } + // CC Switch's provider tables in Codex's config, each one's base URL + // by its id. A thread keeps the provider it was + // started on, and CC Switch moves every third-party thread onto its + // "custom" one, so one reopened there still went to the relay, a + // magpie model picked in it too, which the relay didn't know. While a + // magpie model is on, those tables go through magpie as well; a table + // a profile names is the user's to pick, and stays as it is. + ccSwitchTables := func() map[string]string { + names, _ := edit.TOMLTables(path) + named := map[string]bool{} + for _, n := range names { + if strings.HasPrefix(n, "profiles.") { + if t, _ := edit.GetTOMLTable(path, n); t["model_provider"] != "" { + named[t["model_provider"]] = true + } + } + } + out := map[string]string{} + for _, n := range names { + id, ok := strings.CutPrefix(n, "model_providers.") + if !ok || !ccSwitchProvider.MatchString(id) || named[id] { + continue + } + if t, _ := edit.GetTOMLTable(path, n); t["base_url"] != "" { + out[id] = t["base_url"] + } + } + return out + } + // takeTables points CC Switch's tables at magpie, each one's own base + // URL kept in the stash for giveTables (a table already on magpie's + // keeps the one kept for it) + takeTables := func() error { + was := map[string]string{} + json.Unmarshal([]byte(stashLoad()[at.key("codex.tables")]), &was) + for id, u := range ccSwitchTables() { + if u == at.v1() { + continue + } + if err := edit.SetTOMLKey(path, "model_providers."+id, "base_url", at.v1()); err != nil { + return err + } + was[id] = u + } + if len(was) == 0 { + return nil + } + b, _ := json.Marshal(was) + stash(map[string]string{at.key("codex.tables"): string(b)}) + return nil + } + // giveTables puts the base URLs back, on the tables still pointed at + // magpie; one changed since is left as it is now + giveTables := func() error { + var was map[string]string + json.Unmarshal([]byte(stashLoad()[at.key("codex.tables")]), &was) + now := ccSwitchTables() + for id, u := range was { + if now[id] != at.v1() { + continue + } + if err := edit.SetTOMLKey(path, "model_providers."+id, "base_url", u); err != nil { + return err + } + } + forget(at.key("codex.tables")) + return nil + } // api: the user wants magpie as Codex's provider even while Codex is // signed in to ChatGPT api := func() bool { return stashLoad()[at.key("codex.login")] == "api" } @@ -179,6 +248,9 @@ func codexIn(at place) *Agent { if err := dropSubagent(); err != nil { return err } + if err := giveTables(); err != nil { + return err + } // Codex as installed: OpenAI, its own catalog, its default model if err := dropBase(); err != nil { return err @@ -217,6 +289,9 @@ func codexIn(at place) *Agent { ); err != nil { return err } + if err := takeTables(); err != nil { + return err + } return settle() } if err := putProvider(); err != nil { @@ -241,8 +316,14 @@ func codexIn(at place) *Agent { if err := edit.SetTOMLTop(path, kv...); err != nil { return err } + if err := takeTables(); err != nil { + return err + } return settle() } + if err := giveTables(); err != nil { + return err + } if routed() { if err := dropSubagent(); err != nil { return err @@ -293,6 +374,12 @@ func codexIn(at place) *Agent { return err } } + // CC Switch's tables, left from before magpie took them over + if isMagpie(get("model")) && routed() { + if err := takeTables(); err != nil { + return err + } + } switch { case asProvider() && get("model_catalog_json") == at.native(catalogPath): // set up by a magpie from before #259: the threads started @@ -360,6 +447,11 @@ func codexIn(at place) *Agent { default: return "Codex's config no longer sends its model through magpie (no openai_base_url or model_provider of magpie's), so Codex asks OpenAI for a model OpenAI doesn't have" } + for id, u := range ccSwitchTables() { + if u != at.v1() { + return "Codex's [model_providers." + id + "] (CC Switch's) sends to " + u + ", not magpie's gateway: a Codex thread started on it goes there when reopened, a magpie model picked in it too" + } + } return "" }, // every prompt typed into Codex goes into history.jsonl @@ -456,6 +548,11 @@ func codexIn(at place) *Agent { }, path, catalogPath) } +// ccSwitchProvider matches the ids of the provider tables CC Switch writes +// into Codex's config: "custom", and "cc-switch", "cc-switch-2"… from its +// older versions. Its "cc-switch-official" is its own proxy to OpenAI. +var ccSwitchProvider = regexp.MustCompile(`^(custom|cc-switch(-[0-9]+)?)$`) + func contains(xs []string, x string) bool { for _, v := range xs { if v == x { diff --git a/internal/agent/codex_ccswitch_test.go b/internal/agent/codex_ccswitch_test.go new file mode 100644 index 000000000..c5d1c7ee7 --- /dev/null +++ b/internal/agent/codex_ccswitch_test.go @@ -0,0 +1,106 @@ +package agent + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/edit" +) + +// CC Switch's Codex config, as it writes it: its "custom" table, one of +// its older versions' named by a profile, and a table of the user's own. +const ccSwitchCodex = "model_provider = \"custom\"\nmodel = \"gpt-5.4\"\nmodel_reasoning_effort = \"high\"\n\n" + + "[model_providers.custom]\nname = \"custom\"\nbase_url = \"https://relay.example/v1\"\nwire_api = \"responses\"\nrequires_openai_auth = true\nexperimental_bearer_token = \"sk-relay\"\n\n" + + "[model_providers.cc-switch-2]\nname = \"old\"\nbase_url = \"https://old.example/v1\"\n\n" + + "[model_providers.mine]\nname = \"mine\"\nbase_url = \"https://mine.example/v1\"\n\n" + + "[profiles.work]\nmodel_provider = \"cc-switch-2\"\n" + +// A Codex thread keeps the provider it was started on, and CC Switch puts +// every third-party one on its "custom" table: reopened after magpie took +// Codex over, it still went to the relay, a magpie model picked in it +// too, and the relay said the model wasn't found. While a magpie model is +// on, CC Switch's tables go through magpie too, and get their own base URL +// back when Codex steps off magpie; a profile's table and the user's own +// stay as they are. +func TestCodexTakesCCSwitchTables(t *testing.T) { + for _, auth := range []string{`{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, ""} { + home, read := codexHome(t, auth, ccSwitchCodex) + path := filepath.Join(home, ".codex", "config.toml") + cx := codex(home) + table := func(id string) map[string]string { + tb, err := edit.GetTOMLTable(path, "model_providers."+id) + if err != nil { + t.Fatal(err) + } + return tb + } + v1 := here(home).v1() + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + if c := table("custom"); c["base_url"] != v1 || c["experimental_bearer_token"] != "sk-relay" || c["requires_openai_auth"] != "true" { + t.Fatalf("auth %q: custom not through magpie:\n%s", auth, read()) + } + if table("cc-switch-2")["base_url"] != "https://old.example/v1" || table("mine")["base_url"] != "https://mine.example/v1" { + t.Fatalf("auth %q: other tables changed:\n%s", auth, read()) + } + if d := cx.Check(); d != "" { + t.Fatalf("auth %q: check: %s", auth, d) + } + // CC Switch writes its table again: the row says so, and magpie's + // next sync takes it over again + if err := edit.SetTOMLKey(path, "model_providers.custom", "base_url", "https://relay2.example/v1"); err != nil { + t.Fatal(err) + } + if d := cx.Check(); !strings.Contains(d, "[model_providers.custom]") || !strings.Contains(d, "relay2.example") { + t.Fatalf("auth %q: check: %q", auth, d) + } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if table("custom")["base_url"] != v1 || cx.Check() != "" { + t.Fatalf("auth %q: sync:\n%s", auth, read()) + } + // one of Codex's own models: the table's own base URL is back + if err := cx.Fields[0].Set("gpt-5.4"); err != nil { + t.Fatal(err) + } + if table("custom")["base_url"] != "https://relay2.example/v1" { + t.Fatalf("auth %q: own model:\n%s", auth, read()) + } + // and a reset gives it back too + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + if err := cx.Fields[0].Set(""); err != nil { + t.Fatal(err) + } + if table("custom")["base_url"] != "https://relay2.example/v1" { + t.Fatalf("auth %q: reset:\n%s", auth, read()) + } + if _, ok := stashLoad()[here(home).key("codex.tables")]; ok { + t.Errorf("auth %q: stash left", auth) + } + } +} + +// A CC Switch table the user pointed at magpie by hand stays so when Codex +// steps off magpie: magpie gives back only what it took. +func TestCodexKeepsHandPointedCCSwitchTable(t *testing.T) { + home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "") + v1 := here(home).v1() + os.WriteFile(filepath.Join(home, ".codex", "config.toml"), + []byte("[model_providers.custom]\nname = \"custom\"\nbase_url = \""+v1+"\"\nwire_api = \"responses\"\n"), 0o644) + cx := codex(home) + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + if err := cx.Fields[0].Set(""); err != nil { + t.Fatal(err) + } + if !strings.Contains(read(), `base_url = "`+v1+`"`) { + t.Fatalf("\n%s", read()) + } +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7d83e855c..2b5eb9c13 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1561,6 +1561,11 @@ const I18N = { "{agents} has another server by this name; bringing this one in leaves that one as it is": "{agents} 有另一个同名服务器;导入这个不会改动那个", "Bring in": "导入", "{name} is in the library now": "{name} 已加入资源库", + "Bring in all": "全部导入", + "Bringing in…": "导入中…", + "Brings the {n} skills into the library: the agents that have them go on having them, and you can give them to the others": "把这 {n} 个技能导入资源库:已有它们的 Agent 照旧拥有,你也可以把它们给其他 Agent", + "{n} skills are in the library now": "{n} 个技能已加入资源库", + "{name} wasn't brought in: {error}": "{name} 未能导入:{error}", "Keeps it in the library: {agents} go on having it, and you can give it to the others": "放进资源库:{agents} 继续拥有它,你也可以把它给其他 Agent", "+ Add": "+ 添加", "New MCP server": "新的 MCP 服务器", diff --git a/internal/gui/assets/library.js b/internal/gui/assets/library.js index 76d643aff..b0bb096d9 100644 --- a/internal/gui/assets/library.js +++ b/internal/gui/assets/library.js @@ -1319,6 +1319,19 @@ if (lib.foundSkills.length) { const rh = el("div", "row-head"); rh.append(el("span", "label", t("In your agents")), el("span", "grow"), el("span", "note", t("not in the library — bring one in to give it to the others"))); + // every one at once, rather than a click for each + if (lib.foundSkills.length > 1) { + const names = lib.foundSkills.map((f) => f.name); + const all = button(t("Bring in all"), "action lib-updall lib-importall", async (e, b) => { + b.classList.add("busy"); + b.textContent = t("Bringing in…"); + await importAllSkills(names); + b.classList.remove("busy"); + b.textContent = t("Bring in all"); + }); + all.title = t("Brings the {n} skills into the library: the agents that have them go on having them, and you can give them to the others", { n: names.length }); + rh.append(all); + } body.append(rh); const list = el("div", "list lib-list"); for (const f of lib.foundSkills) list.append(foundSkillRow(f)); @@ -1900,6 +1913,23 @@ } } + // Every skill found in the agents brought in at once: one that couldn't be + // is said, and the others are brought in all the same. + async function importAllSkills(names) { + try { + const v = await api("library/skills/import-all", { names }); + take(v); + const res = v.result || {}, no = res.unimported || []; + if (no.length) { + const p = no[0]; + status(t("{name} wasn't brought in: {error}", { name: p.what.replace(/^skill:/, ""), error: p.error }) + (no.length > 1 ? " " + t("(and {n} more)", { n: no.length - 1 }) : ""), "warn", 8000); + } else report(res, t("{n} skills are in the library now", { n: names.length })); + render(); + } catch (e) { + status(e.message, "err", 6000); + } + } + // Which skills GitHub changed since they were installed: each row says, // and the heading offers to update just those. async function checkSkills() { diff --git a/internal/gui/library.go b/internal/gui/library.go index 84a2f0a66..151c0ecb2 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -256,7 +256,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { Agents []string `json:"agents"` Source string Paths []string - Names []string // the skills to update, of those a check found changed + Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents Server library.Server ID string // a market server's, or a market skill's in its repository Values map[string]string // what a market server needs @@ -299,6 +299,8 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.RemoveSkill(in.Name) case "skills/import": res, err = library.ImportSkill(in.Name) + case "skills/import-all": + res, err = library.ImportSkills(in.Names) 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 815c46bc8..ef62cff37 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -273,6 +273,12 @@ agents' icons and no "differs in"; a link in the shared folder also saying where it points; a copy of an agent's own still "differs in ZCode"; Bring in saying it stays where it is and posting the name; in English and Chinese. +`import-all-skills.test.cjs` opens the Library's Skills tab with three skills +found in the agents: Bring in all beside "In your agents" posts every +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. + `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 @@ -338,7 +344,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 +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 ``` If Playwright is installed outside the repository, set `NODE_PATH` to the diff --git a/internal/gui/tests/import-all-skills.test.cjs b/internal/gui/tests/import-all-skills.test.cjs new file mode 100644 index 000000000..956df2853 --- /dev/null +++ b/internal/gui/tests/import-all-skills.test.cjs @@ -0,0 +1,113 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// JasonLeeForOnly on Discord: the skills found in the agents (~/.agents/skills +// and the agents' own) were brought into the Library one click at a time. +// "Bring in all" beside "In your agents" posts every found skill's name at +// once, the rows go, and the toast says how many are in the library now, or +// the one that couldn't be brought in; the click scrolls nothing; 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/jason"; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills` }); +const found = [ + { name: "grilling", description: "Grill a plan", agents: ["codex"], shared: `${HOME}/.agents/skills/grilling` }, + { name: "orca-cli", description: "Orca", agents: ["pi"], shared: `${HOME}/.agents/skills/orca-cli` }, + { name: "notes", description: "Mine", agents: ["codex"] }, +]; +const lib = (foundSkills) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("codex", "Codex"), agent("pi", "Pi")], + instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills, +}); + +// fail, when given, is a skill the fake magpie can't bring in +function server(lang, posts, fail) { + 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(found) }); + if (url.pathname === "/api/library/skills/import-all") { + const { names } = req.postDataJSON(); + posts.push(names); + const left = found.filter((f) => !names.includes(f.name) || f.name === fail); + const unimported = fail ? [{ what: "skill:" + fail, error: "no skill called " + fail + " in the agents" }] : undefined; + return route.fulfill({ json: { ...lib(left), result: { changed: ["codex", "pi"], unimported } } }); + } + 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(" ")); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": bring in all the skills found", 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, fail) => { + const ctx = await browser.newContext({ viewport: { width: 980, height: 800 } }); + 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, fail)); + 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; + }; + + await t.test("in English", async () => { + const posts = []; + const page = await open("en", posts); + assert.equal(await page.locator("#view-library .lib-row").count(), 3); + const all = page.locator("#view-library .row-head button.lib-importall"); + assert.equal((await all.textContent()).trim(), "Bring in all"); + assert.match(await all.getAttribute("title"), /Brings the 3 skills into the library/); + const before = await scrolled(page); + await all.click(); + await page.waitForTimeout(300); + assert.deepEqual(posts, [["grilling", "orca-cli", "notes"]]); + assert.equal(await page.locator("#view-library .lib-row").count(), 0, "the rows found are gone"); + assert.equal(await page.locator("#view-library button.lib-importall").count(), 0); + assert.equal((await page.locator("#status").textContent()).trim(), "3 skills are in the library now"); + assert.equal(await scrolled(page), before, "the click scrolls nothing"); + }); + + await t.test("in Chinese, one not brought in", async () => { + const posts = []; + const page = await open("zh", posts, "notes"); + const all = page.locator("#view-library .row-head button.lib-importall"); + assert.equal((await all.textContent()).trim(), "全部导入"); + assert.match(await all.getAttribute("title"), /把这 3 个技能导入资源库/); + const before = await scrolled(page); + await all.click(); + await page.waitForTimeout(300); + assert.deepEqual(posts, [["grilling", "orca-cli", "notes"]]); + assert.equal(await page.locator("#view-library .lib-row").count(), 1, "the one not brought in is still listed"); + assert.equal(await page.locator("#view-library button.lib-importall").count(), 0, "no Bring in all for a single row"); + assert.equal((await page.locator("#status").textContent()).trim(), "notes 未能导入:no skill called notes in the agents"); + assert.equal(await scrolled(page), before, "the click scrolls nothing"); + }); + + assert.deepEqual(errors, []); + }); +} diff --git a/internal/library/import_all_test.go b/internal/library/import_all_test.go new file mode 100644 index 000000000..4adf21657 --- /dev/null +++ b/internal/library/import_all_test.go @@ -0,0 +1,47 @@ +package library + +import ( + "os" + "path/filepath" + "testing" +) + +// Bringing in every skill the agents have (JasonLeeForOnly on Discord: one +// click per skill found in ~/.agents): the ones found are brought in +// together, the shared folder's linked to and an agent's own moved in, and +// one that isn't there any more is said while the others go in all the same. +func TestImportSkills(t *testing.T) { + h := sandbox(t) + shared := filepath.Join(h, ".agents/skills") + skill(t, filepath.Join(shared, "grilling"), "grilling", "Grill a plan") + skill(t, filepath.Join(shared, "orca-cli"), "orca-cli", "Orca") + skill(t, filepath.Join(h, ".claude/skills/notes"), "notes", "Mine") + + r, err := ImportSkills([]string{"grilling", "orca-cli", "notes", "gone"}) + if err != nil { + t.Fatal(err) + } + if len(r.Unimported) != 1 || r.Unimported[0].What != "skill:gone" { + t.Errorf("unimported: %+v", r.Unimported) + } + v, _ := Read(nil) + have := map[string]bool{} + for _, s := range v.Skills { + have[s.Name] = true + } + if !have["grilling"] || !have["orca-cli"] || !have["notes"] || len(v.FoundSkills) != 0 { + t.Fatalf("skills: %+v, found: %+v", v.Skills, v.FoundSkills) + } + if _, err := os.Stat(filepath.Join(shared, "grilling/SKILL.md")); err != nil { + t.Error("the shared folder's skill was moved") + } + if fi, err := os.Lstat(filepath.Join(h, ".claude/skills/notes")); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Errorf("notes isn't linked from the library now: %v", err) + } + if _, err := ImportSkills([]string{"gone"}); err == nil { + t.Error("none brought in, and no error") + } + if _, err := ImportSkills(nil); err == nil { + t.Error("nothing asked for, and no error") + } +} diff --git a/internal/library/skills.go b/internal/library/skills.go index 912e0375a..9398984a1 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -993,39 +993,70 @@ func foundSkills(l *Library) []FoundSkill { // a folder is moved in, a link to a folder elsewhere is linked to from the // library, and the agents that had it get the library's from then on. func ImportSkill(name string) (*Result, error) { - return change(func(l *Library) error { - i := slices.IndexFunc(foundSkills(l), func(f FoundSkill) bool { return f.Name == name }) - if i < 0 { - return fmt.Errorf("no agent has a skill called %s that the library hasn't", name) - } - f := foundSkills(l)[i] - if err := os.MkdirAll(skillsDir(), 0o755); err != nil { - return err - } - src := &Source{Kind: "folder", Dir: f.real} - // one in the shared ~/.agents/skills (or a link into it) stays - // there, linked to: the shared folder is the user's, never emptied - shared := f.Shared != "" || within(f.real, realDir(sharedSkillsDir())) - if f.Link != "" || shared { - if err := os.Symlink(f.real, skillDir(name)); err != nil { - return err - } - } else { - if err := move(f.real, skillDir(name)); err != nil { - 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) { - os.Remove(p) - } + return change(func(l *Library) error { return importSkill(l, foundSkills(l), name) }) +} + +// ImportSkills is ImportSkill for several skills at once, written to the +// agents once. One that can't be brought in is said in Unimported, and +// the others are brought in all the same. +func ImportSkills(names []string) (*Result, error) { + if len(names) == 0 { + return nil, fmt.Errorf("no skills to bring in") + } + var failed []Problem + res, err := change(func(l *Library) error { + found := foundSkills(l) + for _, name := range names { + if err := importSkill(l, found, name); err != nil { + failed = append(failed, Problem{What: "skill:" + name, Error: err.Error()}) } } - l.Skills = append(l.Skills, &Skill{Name: name, Source: src, Agents: slices.Clone(f.Agents)}) + if len(failed) == len(names) { + return errors.New(failed[0].Error) + } return nil }) + if res != nil { + res.Unimported = failed + } + return res, err +} + +func importSkill(l *Library, found []FoundSkill, name string) error { + i := slices.IndexFunc(found, func(f FoundSkill) bool { return f.Name == name }) + if i < 0 { + return fmt.Errorf("no agent has a skill called %s that the library hasn't", name) + } + if slices.ContainsFunc(l.Skills, func(s *Skill) bool { return s.Name == name }) { + return fmt.Errorf("the library has a skill called %s already", name) + } + f := found[i] + if err := os.MkdirAll(skillsDir(), 0o755); err != nil { + return err + } + src := &Source{Kind: "folder", Dir: f.real} + // one in the shared ~/.agents/skills (or a link into it) stays + // there, linked to: the shared folder is the user's, never emptied + shared := f.Shared != "" || within(f.real, realDir(sharedSkillsDir())) + if f.Link != "" || shared { + if err := os.Symlink(f.real, skillDir(name)); err != nil { + return err + } + } else { + if err := move(f.real, skillDir(name)); err != nil { + 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) { + os.Remove(p) + } + } + } + l.Skills = append(l.Skills, &Skill{Name: name, Source: src, Agents: slices.Clone(f.Agents)}) + return nil } // ---- files ---------------------------------------------------------------- diff --git a/internal/library/sync.go b/internal/library/sync.go index e77d17b33..d169fb228 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -17,6 +17,9 @@ type Result struct { // fetched again and the ones that couldn't be (What is skill:) Updated []string `json:"updated,omitempty"` Unupdated []Problem `json:"unupdated,omitempty"` + // Unimported are, for skills brought in together, the ones that + // couldn't be (What is skill:) + Unimported []Problem `json:"unimported,omitempty"` } // Problem is one thing that couldn't be given to an agent.