library: a skill brought in from an agent goes back to it when removed (BeiWeiji on X)

BeiWeiji on X (v0.1.4322, zh): a skill imported from "Agent 中已有"
had no way back, only off or Remove, and removed it was gone from the
agents and from "Agent 中已有" too: Remove sent the folder that had been
moved into the library to magpie's backups and took the agents' links
and marked copies away.

ImportSkill now records where the skill was (Skill.Home, this
computer's own; Put keeps it for the same source, a sync never carries
it): the folder moved in (Home.Dir; handOver points it at the shared
~/.agents/skills place) and each agent's entry, a link with its own
text or a byte copy. RemoveSkill/RemoveSkills put it back (putBack):
the library's folder moves back to Home.Dir with what was changed in
the library, or the library's link goes; each agent's link is made
again as it was and each copy copied back. It is in "In your agents"
again and nothing goes to the backups. An entry the user replaced since
is left alone; when Home.Dir is taken the skill is removed as before,
its folder to the backups. This covers every agent with a skills folder
(the record is per agent entry, links and copies alike).

The page: SkillView.back lists those agents, and such a row has Put
back in the trash's place ("放回 {agents}"), whose sheet says where it
goes and sends skills/remove. Other skills keep the trash.

Old imports: a skill brought in before this has no Home record.
Removed, its folder goes to magpie's backups as before, where it can
be moved back by hand (the reporter's already-removed skill is there).

Run (at this change on acc358f07, then rebased on a75a1fffc and on
d67ccbd3c; the commits between touch no library code):
- go test -tags nogui ./internal/library ./internal/gui on mote at
  this head (d67ccbd3c base): ok; go build ./...: ok.
- Full go test -timeout 45m ./... on mica at the acc358f07 base: exit 0,
  every package ok. Not run again after the rebases.
- GOOS=windows go vet and GOOS=linux go vet -tags nogui: ok (whole tree
  at acc358f07; internal/library and internal/gui at this head).
- gofmt -l internal/: clean.
- GUI: skill-put-back.test.cjs (new) in chromium and webkit, en, zh,
  zh-TW, ja, de at 980px and 400px: ok; remove-found-skill ok;
  i18n-keys: only #6877 (", with an image"), red the same at a fresh
  origin/main copy.
- Whole GUI suite (make test-ui) on mica at the acc358f07 base, beside
  another session's suite (load to 200): 28548 tests, 1060 red in 128
  files. Each red file was run at a fresh origin/main a75a1fffc copy:
  118 files (1039 tests) red there too, filed as #6975 (108 already in
  #6934, the rest with their own issues). The other 10 (editor-advanced-
  align, group-new-head, ledger-swipe, library-problems-hide,
  nav-sub-fold, routing-pulse-composited, search-mcp-library,
  signin-closes-sheet, readable-focus, library-env) pass at this change
  run alone on mote, 150 of 150.
Broken by hand: canPutBack forced false; TestRemoveSkills,
TestRemovedImportGoesBackToTheAgents and TestRemovedLinkedImportGoesBack
went red (TestPutBackLeavesTheUsersNewFolder guards the fallback and
passes either way).
Not tried: a real magpie with real agents (tests run in a sandbox
HOME); Windows junctions and WSL-distro links (a WSL distro agent's own
entry is recorded like any other but not tried there); the link tests are skipped on Windows.
This commit is contained in:
yetone
2026-11-17 20:48:59 +08:00
parent d67ccbd3c7
commit 3be322fe4c
10 changed files with 466 additions and 10 deletions
+1
View File
@@ -94,6 +94,7 @@ Pi's extensions and packages.
- A synced command server can be started its own way on this computer (#3836, #6426; jinpwng on X: one server on a Mac and in WSL, each with its own program path), where `Local` would keep the whole server here. `Server.Shared` holds the synced start (`Start`: command, args, env) while `Command`, `Args` and `Env` are this computer's, so every reader (the agents' files, projects, the router, the check) runs this computer's with no change of its own. `Collect` carries `Shared` in their place and never the field (`carriedStart`), so what this computer carries is what came in; `putServers` gives a server that comes in this computer's start again and makes what came its `Shared` (`keepStart`): the name, agents, note and tools still come and go with a sync. One that comes in as a URL ends it; so does turning the server local (`ServerLocal` on, and `check` drops `Shared` off a URL or local server). The editor's Use another command on this computer under Command (a synced, saved command server that isn't a plugin's) keeps the saved start as `shared` and leaves the line this computer's, its hint naming what the other computers run; Use the synced command puts it back. `SaveServer` takes `Shared` as sent, so the editor sends it every time and the TUI's edit copies it. CLI: `magpie library mcp here <name> <command args…>` and `here <name> off` (`ServerHere`); `magpie library` lists what the others run. Not covered: a URL server's own address here, and a cwd (the library has none). (`TestServerHereThroughSync`, `TestServerHereEnds`, `mcp-server-here.test.cjs`) [`mcp_here.go`](../../internal/library/mcp_here.go)
- The CLI sets a server's headers, env and startup timeout (#6111, Abandon332 on X): `magpie library mcp add <name> <url|command args…> header=K=V env=K=V timeout=SECS agents=…`, `mcp set <name> header=K=V|header-=K|env=K=V|env-=K|timeout=SECS` (the rest of the server kept) and `mcp show <name>` (JSON). `SplitServerWords` takes those words out of the line before `--`; words after `--` are the program's own, and a word that looks like a setting magpie doesn't know (`headers=`, `envs=`) is refused rather than passed on as an argument. `header=` on a command or `env=` on a URL is an error. (`TestSplitServerWords`, `TestLibraryMCPHeadersEnvTimeout`) [`mcp_options.go`](../../internal/library/mcp_options.go)
- A skill brought in from a link into a folder an app keeps per version (ego lite's framework `Versions/<v>`, #2635) is linked through the app's own steady link, or through `Versions/Current` when Current is that version (`linkVia`, `currentVersion`; `TestImportedSkillFollowsAppUpdate`, `TestImportedSkillThroughVersionsCurrent`). One brought in before that links straight to `Versions/<old>`, which the app's update deletes (tjhhhh on Discord). Every read of the page (looking at each link once, `readParts`, and starting that over when a link was mended) and the first step of every sync mend such links (`followMovedSkills`): a library skill that is a link, whose target isn't there, and whose first missing part is named like a version (`versionName`) is linked to the same place under that folder's `Current`, `current` or `latest` link, else under the highest version beside it that has a `SKILL.md` there (`movedVersion`, `versionLess`); one whose target is in `Versions/<v>` while the bundle's `Versions/Current` is a link to another version with the same skill is linked through Current (`laterCurrent`). `Source.Dir` follows. Only the library's link is replaced (`os.Remove` of the link, then `dirLink`; put back as it was when the new link can't be made). A folder of the library's own, a link to a folder the user deleted that isn't a version (shown missing as before) and the app's old version folder are left as they are (`TestOldImportFollowsDeletedVersion`, `TestOldImportFollowsVersionsCurrent`, `TestOldImportFollowsHighestVersion`, `TestMovedSkillsLeaveTheRest`). The app's own steady link can be left naming the version its update deleted (ego's `active_version_dir` still at 0.6.2.5 with only 0.6.2.7 on disk, tjhhhh again): the app's links are its own and never written to. When the library's link dangles and its target isn't in a version folder, the links on the way are followed as far as they are there (`linkedEnd`) and `movedVersion` is asked of where they end; the library links to the folder found, and keeps the steady link as `Source.Via`. Once the steady link leads to a `SKILL.md` again, the library links through it once more and `Via` is cleared (`TestSteadyLinkLeftOnDeletedVersion`, `TestSteadyLinkLeftOnDeletedVersionNoOther`). [`skill_moved.go`](../../internal/library/skill_moved.go)
- A skill brought in from the agents ("In your agents", `ImportSkill`) goes back to them when it leaves the library (BeiWeiji on X). The import records where it was (`Skill.Home`, this computer's own, kept by `Put` for the same source and never carried by a sync): the folder moved in (`Home.Dir`, which `handOver` points at its shared `~/.agents/skills` place) and each agent's entry, a link with its own text or a copy (`HomeEntry`). `RemoveSkill` (and `RemoveSkills`) puts it back (`putBack`): the library's folder is moved back to `Home.Dir` with what was changed there, or the library's link is taken away, and each agent's link is made again as it was and each copy copied back; it is then in "In your agents" again and nothing goes to the backups. An agent entry the user replaced since is left as it is, and when `Home.Dir` is taken the skill is removed as any other, its folder to the backups. The view's `back` lists the agents (`canPutBack`), and the page shows Put back in their place of the trash, with a sheet saying where it goes (`confirmPutBack`). A skill brought in before `Home` was kept has none: removed, its folder goes to the backups as before, where it can be taken back by hand (`TestRemovedImportGoesBackToTheAgents`, `TestRemovedLinkedImportGoesBack`, `TestPutBackLeavesTheUsersNewFolder`, `skill-put-back.test.cjs`). [`skills.go`](../../internal/library/skills.go)
- A skill kept in `~/.agents/skills` is handed over to the library on the user's click (`HandOverSkills`, `POST /api/library/skills/hand-over` with `names`; the row's Manage in magpie in its source line, Manage {n} in magpie in the skills' heading, each asking first; `magpie library skill hand-over <name…>|--all`; tnt1223 on Discord). "Kept there" is `sharedEntry`: the entry in that folder that is the library skill's own folder, by its name or, for a library link into it under another folder's name, by that folder's (`SkillView.Shared`; `SharedElsewhere` when the entry only links to a folder kept elsewhere). Every reader of `sharedHas`/`sharedEntry` follows: `Always`, `syncSkills`' `inShared`, and the shared folder's own target (Goose, Kimi Code, Cindy), which is given no second link beside such an entry (`TestSharedUnderAnotherName`). Handed over, a folder in `~/.agents/skills` moves into the library's skills folder (`moveIn`: renamed, or copied, read back the same with `sameTree` and only then set aside with the backups; a failure leaves it where it was and the library's link as it was, `TestHandOverFailureKeepsOriginal`), and an entry that only links elsewhere is taken away while the library links past it to that folder. The user's own links to it in agents' folders, which would point at nothing, go too. Every agent here that read it (`readsSharedHere`, and the agent of each such link) is ticked, so each keeps it, now from the library, till it is unticked or turned off here. A skill found there and not in the library yet is brought in first. One that can't be handed over is left as it was, in `Result.Unmoved`, and the others are handed over all the same. `HandBackSkill` (`magpie library skill hand-back <name>`, CLI only; the sheet names it) moves the folder back and links the library to it, its ticks as they are. Not covered: another computer whose skill is still in its own `~/.agents/skills` gets the library's copy from a sync beside its own, until it is handed over there too; and the skills CLI's lock (`npx skills update`) may put the entry back (`TestHandOverSharedFolder`, `TestHandOverSharedLink`, `TestHandOverFound`, `TestHandOverWithGoose`, `TestLibrarySkillHandOver`, `skill-handover.test.cjs`). [`skill_handover.go`](../../internal/library/skill_handover.go) It also turns off `SharedSkills` (Put skills in, `skills_shared.go`): with every skill kept in `~/.agents/skills` every reader has every skill and the sync would link the handed-over one back there, which can't go with choosing agents; the sync then takes out magpie's own links there and never the user's entries (`TestHandOverWithSharedSetting`; the sheet says so when the setting is on; ConatusMoon2222 on X). The skill router lists nothing for an agent while that setting is on, which the Put skills in note says when both are on.
- The agents that read `~/.agents/skills` themselves are `readsShared` (Codex, Gemini CLI, OpenCode, DevEco Code, Crush, dsh, Command Code, Devin, Droid, Cline, Grok Build, Grok App, fx, Alma, Kimi Code, ZCode and OmO) and, from the version that started to, `Target.SharedToo`: Pi from 0.54.0 (its CHANGELOG; `userAgentsSkillsDir` in package-manager.js) and omp from 11.0.0 (`discovery/agents.ts`; 10.6.2 doesn't). OmO runs on senpi, whose oldest version on npm (0.74.0) already reads it. A Pi or omp whose version isn't known is taken as older, as before. Every reader goes through `Target.readsSharedDir`: `Always` (the row's lock), `syncSkills`' `inShared` (no second link in its own folder) and `readsSharedHere` for a handover (usrname1833 on Discord; `TestPiReadsSharedSkillsFromItsVersion`). A user's own skill in `~/.agents/skills` by the library skill's name (another installer's, such as the skills CLI's, or copied by hand: not magpie's link or marked copy, not the library's own folder) counts too, under that folder name or another whose `SKILL.md` gives the name (`readSharedOwn`, `sharedOwn.rival`), since Pi 1.4.0 knows a skill by that name and drops one read twice only when both paths are one file (`realPathSet` in dist/core/skills.js): it warned of a collision for the two trees. Such a reader gets nothing in its own folder, and magpie's link or marked copy there, an older magpie's too, goes on the next sync. When it holds the library's very files (`sameTree`) the reader has the library's already. When it holds other files the reader has a skill of its own by that name, an `Own` problem settled as one in its own folder: Keep {agent}'s unticks it, Use the library's sets the shared entry aside with the backups (every other reader of the folder loses it too) and gives the library's (math_milian on Discord; `TestSharedCopyNotGivenTwice`, `TestSharedCopyOtherFolderName`, `TestSharedOwnSettled`). The user's entry is otherwise never touched. Not covered: a library skill that is a link to the agent's own folder (brought in from there) beside such a copy keeps both, since that folder is the library's; OpenCode reads Claude Code's folder and the shared one into one map by name, so it finds Claude Code's link and the user's copy as one skill; and a Pi or omp of unknown version is given its own as before.
- Put skills in (`Library.SharedSkills`; `SetSkillsWhere`, `POST /api/library/skills/where` with `how` `agents` or `shared`; `magpie library skill where agents|shared`; the Skills tab's bar under How, `skillWhereBar` in plugins/library/client.js; usrname1833 on Discord). Off, the default and what a library.json from before reads as, each agent gets the skills ticked for it in its own folder. On, every library skill on here (`keepsShared`: not `OffHere`, its folder there) also gets magpie's link in `~/.agents/skills` (`syncShared`, run after `sweepShared`), so every agent and tool that reads that folder has it, ticked or not, and is in its `Always`. The files stay in the library, so updates, checks, edit tracking and Off here work as before, and nothing is moved when it is turned on: existing skills just get links. An entry of the user's own by a skill's name is left alone, silently, and the agents ticked for the library's skill still get it in their own folders, unless they read the folder themselves (`sharedOwn.rival`, above). A sync leaves an existing link as it is. A skill given to the folder's own agent (Kimi Code, Goose, Cindy) is that agent's sync's. Turned off, `sweepShared` takes out magpie's links there and nothing else, and each agent's own links come back. It is this computer's: `Collect` never carries it (`TestSkillsWhereShared`, `TestSkillsWhereSharedWithKimi`, `skill-where.test.cjs`). Not covered: on Windows without the right to make links the entry is a marked copy; a stale one is set aside and copied again, but `takeEdits` doesn't take edits made in that copy into the library, so they go to the backups when the setting is turned off or the skill changes (#4958). [`skills_shared.go`](../../internal/library/skills_shared.go)
+25 -3
View File
@@ -49,6 +49,8 @@ magpie.plugin("library", (ctx) => {
key: "M10 2.8a3.2 3.2 0 1 0 0 6.4 3.2 3.2 0 0 0 0-6.4z M7.8 8.2 3 13 M4.5 11.5 6 13",
person: "M8 3a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z M3.5 13.5c.6-2.4 2.3-3.6 4.5-3.6s3.9 1.2 4.5 3.6",
back: "m9.5 4.5-3 3.5 3 3.5",
// an arrow turning back: a skill going back where it came from
putBack: "M6 3.5 3 6.5l3 3 M3 6.5h6.5a3.5 3.5 0 0 1 0 7H7",
hook: "M10.5 2.5v6.5a3 3 0 0 1-6 0V7.5 M3 9l1.5-1.5L6 9",
// a person with a second, smaller one it hands work to
subagent: "M6 3a2.2 2.2 0 1 0 0 4.4A2.2 2.2 0 0 0 6 3z M2 13c.5-2.2 2-3.4 4-3.4s3.5 1.2 4 3.4 M11.5 7.5a1.5 1.5 0 1 0 0 .01 M10.2 12.5c.3-1.3 1.1-2 2.3-2s1.6.5 1.9 1.4",
@@ -7910,9 +7912,12 @@ magpie.plugin("library", (ctx) => {
here.title = s.offHere ? t("Turn on on this computer") : t("Turn off on this computer only: your other computers keep it");
here.setAttribute("aria-pressed", s.offHere ? "true" : "false");
acts.append(here);
const rm = button("", "lib-icon danger", () => confirmRemoveSkill(s));
rm.append(svg(GLYPH.trash, 13, 1.4));
rm.title = t("Remove");
// brought in from the agents (BeiWeiji on X): Remove gives it back to
// them as they had it, and says so
const back = s.back?.length ? s.back.map(nameOf).join(", ") : "";
const rm = button("", "lib-icon" + (back ? " lib-putback" : " danger"), () => confirmRemoveSkill(s));
rm.append(svg(back ? GLYPH.putBack : GLYPH.trash, 13, 1.4));
rm.title = back ? t("Put back in {agents}", { agents: back }) : t("Remove");
acts.append(rm);
row.append(mark(s.icon, GLYPH.skill), who, acts, agentChips(withGone(all, s.agents), s.agents, chipsChange("skills/agents", s.name, "skills", (x) => skillRow(x, all)), { problems: s.problems, via: viaFor(s), all: true, always: alwaysFor(s) }));
if (picking) return pickRow(row, s.name);
@@ -8087,6 +8092,7 @@ magpie.plugin("library", (ctx) => {
}
function confirmRemoveSkill(s) {
if (s.back?.length) return confirmPutBack(s);
const ed = el("div", "editor lib-editor");
const head = el("div", "ehead");
head.append(glyph(GLYPH.trash), el("b", "", t("Remove {name}?", { name: s.name })));
@@ -8102,6 +8108,22 @@ magpie.plugin("library", (ctx) => {
openLib(ed);
}
// one brought in from the agents leaves the library for them again
function confirmPutBack(s) {
const agents = s.back.map(nameOf).join(", ");
const ed = el("div", "editor lib-editor lib-putback-sheet");
const head = el("div", "ehead");
head.append(glyph(GLYPH.putBack), el("b", "", t("Put {name} back?", { name: s.name })));
ed.append(head);
ed.append(el("p", "lib-confirm", t("It leaves the library and goes back to {agents} as it was before you brought it in.", { agents })));
const bar = el("div", "bar");
const go = button(t("Put it back"), "primary", async () => { if (await change("skills/remove", { name: s.name }, t("{name} went back to {agents}", { name: s.name, agents }))) closeLibModal(true); });
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
ed.append(bar);
modal = { save: () => go.click() };
openLib(ed);
}
// A skill's files, read and edited here (refeccd on Discord: skills
// handed over from ~/.agents/skills had no other place to be edited).
// Markdown is shown as it reads, its front matter as rows; Save writes
@@ -2,6 +2,11 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"Put back in {agents}": "放回 {agents}",
"Put {name} back?": "把 {name} 放回?",
"It leaves the library and goes back to {agents} as it was before you brought it in.": "它会离开资源库,按导入前的样子放回 {agents}。",
"Put it back": "放回",
"{name} went back to {agents}": "{name} 已放回 {agents}",
"Pick the agents that may search and read what was said in your other sessions.": "选择可以搜索、阅读你其他会话内容的 Agent。",
"Update by themselves": "自动更新",
"Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "GitHub 和 git 上的技能有改动时自动重新获取。你在这里改过的技能保持不变。",
@@ -1078,6 +1083,11 @@ magpie.strings({
"{name} read again from its source": "已重新从来源读取 {name}",
},
"zh-TW": {
"Put back in {agents}": "放回 {agents}",
"Put {name} back?": "把 {name} 放回?",
"It leaves the library and goes back to {agents} as it was before you brought it in.": "它會離開資源庫,依匯入前的樣子放回 {agents}。",
"Put it back": "放回",
"{name} went back to {agents}": "{name} 已放回 {agents}",
"Pick the agents that may search and read what was said in your other sessions.": "選擇可以搜尋、閱讀你其他會話內容的 Agent。",
"Update by themselves": "自動更新",
"Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "GitHub 和 git 上的技能有變動時自動重新取得。你在這裡改過的技能保持不變。",
@@ -2154,6 +2164,11 @@ magpie.strings({
"{name} read again from its source": "已重新從來源讀取 {name}",
},
ja: {
"Put back in {agents}": "{agents} に戻す",
"Put {name} back?": "{name} を戻しますか?",
"It leaves the library and goes back to {agents} as it was before you brought it in.": "ライブラリから外れ、取り込む前の状態で {agents} に戻ります。",
"Put it back": "戻す",
"{name} went back to {agents}": "{name} を {agents} に戻しました",
"Pick the agents that may search and read what was said in your other sessions.": "ほかのセッションで話した内容を検索して読める Agent を選びます。",
"Update by themselves": "自動で更新",
"Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "GitHub や git でスキルが変わったら自動で取得し直します。ここで変更したスキルはそのままです。",
@@ -3230,6 +3245,11 @@ magpie.strings({
"{name} read again from its source": "{name} をソースから読み直しました",
},
de: {
"Put back in {agents}": "Zurück zu {agents}",
"Put {name} back?": "{name} zurückgeben?",
"It leaves the library and goes back to {agents} as it was before you brought it in.": "Er verlässt die Bibliothek und kommt so zu {agents} zurück, wie er vor dem Übernehmen war.",
"Put it back": "Zurückgeben",
"{name} went back to {agents}": "{name} ist wieder in {agents}",
"Pick the agents that may search and read what was said in your other sessions.": "Wähle die Agents, die durchsuchen und lesen dürfen, was in deinen anderen Sitzungen gesagt wurde.",
"Update by themselves": "Selbst aktualisieren",
"Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "Skills von GitHub und git neu laden, wenn sie sich dort ändern. Ein hier geänderter Skill bleibt, wie er ist.",
+132
View File
@@ -0,0 +1,132 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// BeiWeiji on X: a skill brought into the library from "In your agents"
// had no way back, only off or Remove, and removed it was gone from the
// agents too. A skill brought in from the agents (back: the agents it came
// from) has Put back in their place of the trash: its sheet says where it
// goes, the button sends skills/remove (which gives it back to them as
// they had it), and it is under "In your agents" again. A skill from
// anywhere else keeps its trash. In every language, in Chromium and
// WebKit, wide and narrow. 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/bei";
const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills` });
const lib = (st) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [agent("claude", "Claude Code"), agent("codex", "Codex")],
instructions: { agents: [] }, servers: [], foundServers: [], projects: [], newSkills: [],
checkDue: false,
skills: [
...st.back ? [] : [{ name: "notes", description: "My notes", agents: ["claude", "codex"], back: ["claude", "codex"] }],
{ name: "pdf", description: "Read PDFs", kind: "github", source: "https://github.com/a/b/tree/main/pdf", agents: ["claude"] },
],
foundSkills: st.back ? [{ name: "notes", description: "My notes", agents: ["claude", "codex"] }] : [],
});
function server(lang, posts, st) {
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(st) });
if (url.pathname.startsWith("/api/library/skills/")) {
const what = url.pathname.split("/").pop(), body = req.postDataJSON();
posts.push({ what, body });
if (what === "remove") st.back = true;
return route.fulfill({ json: { ...lib(st), result: { changed: ["claude", "codex"] } } });
}
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: { title: "Put back in Claude Code, Codex", head: "Put notes back?", go: "Put it back", in: "In your agents",
text: "It leaves the library and goes back to Claude Code, Codex as it was before you brought it in.", done: "notes went back to Claude Code, Codex" },
zh: { title: "放回 Claude Code, Codex", head: "把 notes 放回?", go: "放回", in: "Agent 中已有",
text: "它会离开资源库,按导入前的样子放回 Claude Code, Codex。", done: "notes 已放回 Claude Code, Codex" },
"zh-TW": { title: "放回 Claude Code, Codex", head: "把 notes 放回?", go: "放回",
text: "它會離開資源庫,依匯入前的樣子放回 Claude Code, Codex。", done: "notes 已放回 Claude Code, Codex" },
ja: { title: "Claude Code, Codex に戻す", head: "notes を戻しますか?", go: "戻す",
text: "ライブラリから外れ、取り込む前の状態で Claude Code, Codex に戻ります。", done: "notes を Claude Code, Codex に戻しました" },
de: { title: "Zurück zu Claude Code, Codex", head: "notes zurückgeben?", go: "Zurückgeben",
text: "Er verlässt die Bibliothek und kommt so zu Claude Code, Codex zurück, wie er vor dem Übernehmen war.", done: "notes ist wieder in Claude Code, Codex" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a skill brought in from the agents is put back", 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 width of [980, 400]) for (const lang of Object.keys(words)) {
await t.test(`${lang} at ${width}px`, async () => {
const w = words[lang], posts = [], st = { back: false };
const ctx = await browser.newContext({ viewport: { width, height: 900 } });
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, st));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const v = page.locator("#view-library");
const row = (n) => v.locator(".lib-skill", { has: page.locator(".name", { hasText: new RegExp("^" + n) }) });
await row("notes").waitFor();
// the one from the agents: Put back, not a trash; the other keeps its trash
const pb = row("notes").locator("button.lib-putback");
assert.equal(await pb.getAttribute("title"), w.title);
assert.equal(await row("notes").locator("button.lib-icon.danger").count(), 0);
assert.equal(await row("pdf").locator("button.lib-putback").count(), 0);
assert.equal(await row("pdf").locator("button.lib-icon.danger").count(), 1);
const rb = await row("notes").boundingBox(), bb = await pb.boundingBox();
assert(bb && bb.width >= 16 && bb.x + bb.width <= rb.x + rb.width + 0.5, `Put back sticks out of its row at ${width}px`);
// its sheet says where it goes; Cancel sends nothing
await pb.click();
const ed = page.locator(".lib-putback-sheet");
await ed.waitFor();
assert.equal((await ed.locator(".ehead b").textContent()).trim(), w.head);
assert.equal((await ed.locator(".lib-confirm").textContent()).trim(), w.text);
await ed.locator(".bar button:not(.primary)").click();
await ed.waitFor({ state: "detached" });
assert.deepEqual(posts, []);
await pb.click();
await ed.waitFor();
const go = ed.locator(".bar button.primary");
assert.equal((await go.textContent()).trim(), w.go);
await go.click();
await ed.waitFor({ state: "detached" });
assert.deepEqual(posts, [{ what: "remove", body: { name: "notes" } }]);
await row("notes").waitFor({ state: "detached" });
assert.equal((await page.locator("#status").textContent()).trim(), w.done);
// and it is in the agents' list again
const found = v.locator(".lib-foundhead");
await found.waitFor();
if (w.in) assert.equal((await found.locator(".label").textContent()).trim(), w.in);
assert.equal(await v.locator(".lib-row .name", { hasText: /^notes$/ }).count(), 1);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll");
await ctx.close();
});
}
assert.deepEqual(errors, []);
});
}
+1
View File
@@ -586,6 +586,7 @@ func Put(b *Bundle) (*Result, error) {
n.From = cur.From
}
n.Gone = cur.Gone // kept on this computer only
n.Home = cur.Home // where it was in this computer's agents
}
skills = append(skills, n)
if keep[s.Name] {
+7 -6
View File
@@ -9,7 +9,8 @@ import (
// Every skill out of the library at once (#449): each as RemoveSkill takes
// it — out of every agent, its folder kept aside in one backup, a folder of
// the user's only unlinked — and one that can't be taken out said, the rest
// gone all the same.
// gone all the same. One brought in from an agent goes back to it as it
// had it (BeiWeiji on X), not to the backups.
func TestRemoveSkills(t *testing.T) {
h := sandbox(t)
src := filepath.Join(h, "src/skills")
@@ -41,7 +42,7 @@ func TestRemoveSkills(t *testing.T) {
if v, _ := Read(nil); len(v.Skills) != 0 {
t.Errorf("left in the library: %+v", v.Skills)
}
for _, d := range []string{".claude/skills/pdf", ".codex/skills/pdf", ".claude/skills/xlsx", ".claude/skills/notes", ".codex/skills/notes"} {
for _, d := range []string{".claude/skills/pdf", ".codex/skills/pdf", ".claude/skills/xlsx", ".codex/skills/notes"} {
if _, err := os.Lstat(filepath.Join(h, d)); !os.IsNotExist(err) {
t.Errorf("%s is still there", d)
}
@@ -52,10 +53,10 @@ func TestRemoveSkills(t *testing.T) {
t.Errorf("the user's %s went with it", d)
}
}
kept, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "skills", "*"))
if len(kept) != 1 || filepath.Base(kept[0]) != "notes" {
if fi, err := os.Lstat(filepath.Join(h, ".claude/skills/notes/SKILL.md")); err != nil || linkEntry(fi) {
t.Errorf("notes isn't back in Claude Code's folder: %v", err)
}
if kept, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "skills", "*")); len(kept) != 0 {
t.Errorf("kept aside: %v", kept)
} else if _, err := os.Stat(filepath.Join(kept[0], "SKILL.md")); err != nil {
t.Error("notes' folder wasn't kept whole")
}
}
+3
View File
@@ -148,6 +148,9 @@ func handOver(l *Library, found *[]FoundSkill, ts []*Target, name string) (left
}
}
s.Source = nil
if s.Home != nil {
s.Home.Dir = r // removed, it goes back there
}
} else {
// the entry only links to a folder elsewhere (or to the library's
// own): the library links past it, and only the link goes
+135
View File
@@ -0,0 +1,135 @@
package library
import (
"os"
"path/filepath"
"runtime"
"slices"
"testing"
)
// BeiWeiji on X: a skill brought into the library from "In your agents"
// had no way back, and removed from the library it was gone from the
// agents too, and from "In your agents". Removed now, it goes back to the
// agents as they had it: the folder moved in goes back where it was, with
// what was changed in the library, each agent's own link to it is made
// again and a copy of the very same files copied back. It is in "In your
// agents" again, and the library's folder isn't left with the backups.
func TestRemovedImportGoesBackToTheAgents(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("links need Developer Mode on Windows")
}
h := sandbox(t)
claude := filepath.Join(h, ".claude/skills/notes")
skill(t, claude, "notes", "Mine")
codex := filepath.Join(h, ".codex/skills/notes")
if err := os.MkdirAll(filepath.Dir(codex), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink("../../.claude/skills/notes", codex); err != nil {
t.Fatal(err)
}
gemini := filepath.Join(h, ".gemini/skills/notes")
skill(t, gemini, "notes", "Mine") // a byte copy
ok(t)(ImportSkill("notes"))
v, _ := Read(nil)
if len(v.Skills) != 1 || !slices.Equal(v.Skills[0].Back, []string{"claude", "codex", "gemini"}) {
t.Fatalf("skills: %+v", v.Skills)
}
if !ours(claude, "notes") || !ours(gemini, "notes") {
t.Fatal("the agents weren't given the library's")
}
// changed in the library while it was there: the change goes back too
write(t, filepath.Join(skillDir("notes"), "more.md"), "added in the library\n")
ok(t)(RemoveSkill("notes"))
if fi, err := os.Lstat(claude); err != nil || linkEntry(fi) {
t.Fatalf("claude's folder isn't back: %v", err)
}
if read(t, filepath.Join(claude, "more.md")) == "" || read(t, filepath.Join(claude, "scripts/run.sh")) == "" {
t.Error("claude's folder came back without its files")
}
if to, err := os.Readlink(codex); err != nil || to != "../../.claude/skills/notes" {
t.Errorf("codex's link is %q, %v", to, err)
}
if fi, err := os.Lstat(gemini); err != nil || linkEntry(fi) || ours(gemini, "notes") || read(t, filepath.Join(gemini, "SKILL.md")) == "" {
t.Errorf("gemini's copy isn't back: %v", err)
}
if _, err := os.Lstat(skillDir("notes")); !os.IsNotExist(err) {
t.Error("the library still has its folder")
}
if m, _ := filepath.Glob(filepath.Join(BackupDir(), "*/skills/notes")); len(m) != 0 {
t.Errorf("its folder went to the backups: %v", m)
}
v, _ = Read(nil)
if len(v.Skills) != 0 || len(v.FoundSkills) != 1 || v.FoundSkills[0].Name != "notes" ||
!slices.Equal(v.FoundSkills[0].Agents, []string{"claude", "codex"}) || !slices.Equal(v.FoundSkills[0].Copies, []string{"gemini"}) {
t.Fatalf("after: skills %+v, found %+v", v.Skills, v.FoundSkills)
}
// and it can be brought in again
ok(t)(ImportSkill("notes"))
}
// One an agent only linked to, in a folder elsewhere: the library linked
// to it there, and removed, the agent's link is made again. The folder
// itself never moved.
func TestRemovedLinkedImportGoesBack(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("links need Developer Mode on Windows")
}
h := sandbox(t)
dev := filepath.Join(h, "src/dev")
skill(t, dev, "dev", "Work in progress")
entry := filepath.Join(h, ".claude/skills/dev")
if err := os.MkdirAll(filepath.Dir(entry), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink(dev, entry); err != nil {
t.Fatal(err)
}
ok(t)(ImportSkill("dev"))
if !ours(entry, "dev") {
t.Fatal("claude wasn't given the library's")
}
ok(t)(RemoveSkill("dev"))
if to, err := os.Readlink(entry); err != nil || to != dev {
t.Errorf("claude's link is %q, %v", to, err)
}
if read(t, filepath.Join(dev, "SKILL.md")) == "" {
t.Error("the folder elsewhere is gone")
}
v, _ := Read(nil)
if len(v.FoundSkills) != 1 || !slices.Equal(v.FoundSkills[0].Agents, []string{"claude"}) {
t.Fatalf("found: %+v", v.FoundSkills)
}
}
// Something of the user's put where the folder was, while the library had
// it: it stays as it is, and the skill is removed as one that came from
// anywhere else is, its folder kept with the backups.
func TestPutBackLeavesTheUsersNewFolder(t *testing.T) {
h := sandbox(t)
claude := filepath.Join(h, ".claude/skills/notes")
skill(t, claude, "notes", "Mine")
ok(t)(ImportSkill("notes"))
if err := unlink(claude); err != nil {
t.Fatal(err)
}
skill(t, claude, "notes", "Another")
if _, err := RemoveSkill("notes"); err != nil {
t.Fatal(err)
}
if m := readMetaOf(t, claude); m != "Another" {
t.Errorf("the user's folder was touched: %q", m)
}
if m, _ := filepath.Glob(filepath.Join(BackupDir(), "*/skills/notes/SKILL.md")); len(m) != 1 {
t.Errorf("the library's folder isn't with the backups: %v", m)
}
}
func readMetaOf(t *testing.T, p string) string {
t.Helper()
m, _ := readMeta(p)
return m.Description
}
+132 -1
View File
@@ -70,6 +70,28 @@ type Skill struct {
// Router is "direct" for a skill the skill router leaves out: each
// agent keeps its own link of it (skill_router.go). A sync carries it.
Router string `json:"router,omitempty"`
// Home is where the skill was in the agents before it was brought in
// from them (ImportSkill): removed from the library, it goes back there
// as it was (BeiWeiji on X). This computer's own: a sync never carries
// it, and keeps it for the same skill (Put).
Home *SkillHome `json:"home,omitempty"`
}
// SkillHome is where a skill brought in from the agents was (Skill.Home).
type SkillHome struct {
// Dir is the folder that was moved into the library, put back there.
// Empty when the library only linked to it where it is.
Dir string `json:"dir,omitempty"`
// Entries are what each agent that had it had in its skills folder
Entries []HomeEntry `json:"entries,omitempty"`
}
// HomeEntry is one agent's entry for a skill before it was brought in.
type HomeEntry struct {
Agent string `json:"agent"`
Path string `json:"path"`
Link string `json:"link,omitempty"` // a link, and what it pointed at
Copy bool `json:"copy,omitempty"` // a copy of the very same files
}
// gives reports whether the agent id gets the skill on this computer: it
@@ -2248,9 +2270,18 @@ func removeSkill(l *Library, name, stamp string) error {
if i < 0 {
return fmt.Errorf("no skill called %s", name)
}
// brought in from the agents: it goes back to them as it was
back := false
if canPutBack(l.Skills[i]) {
var err error
if back, err = putBack(l.Skills[i]); err != nil {
return err
}
}
p := skillDir(name)
fi, err := os.Lstat(p)
switch {
case back:
case errors.Is(err, fs.ErrNotExist):
// its folder is gone already: only the entry goes
case err == nil && (fi.Mode()&fs.ModeSymlink != 0 || linked(p)): // a junction too, as the page says
@@ -2628,6 +2659,28 @@ func importSkill(l *Library, found []FoundSkill, name string) error {
}
src = nil
}
// where it was, for Remove to put it back as it was (BeiWeiji on X):
// one already in the library's own folder was no agent's
var home *SkillHome
if f.Library == "" {
home = &SkillHome{}
if src == nil {
home.Dir = f.real
}
for _, id := range slices.Concat(f.Agents, f.Copies) {
t := targetByID(id)
if t == nil || t.Skills == "" {
continue
}
e := HomeEntry{Agent: id, Path: filepath.Join(t.Skills, name), Copy: slices.Contains(f.Copies, id)}
if to, err := os.Readlink(e.Path); err == nil {
e.Link = to
} else if to, ok := linkTarget(e.Path); ok {
e.Link = to
}
home.Entries = append(home.Entries, e)
}
}
for _, id := range f.Agents { // links to what was moved, or to the folder elsewhere
if t := targetByID(id); t != nil {
p := filepath.Join(t.Skills, name)
@@ -2642,10 +2695,88 @@ func importSkill(l *Library, found []FoundSkill, name string) error {
// 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), From: from})
l.Skills = append(l.Skills, &Skill{Name: name, Source: src, Agents: slices.Compact(agents), From: from, Home: home})
return nil
}
// canPutBack is whether s came in from the agents and can go back to them
// as it was: its folder put back where it was, or the library's link to
// it taken away.
func canPutBack(s *Skill) bool {
if s == nil || s.Home == nil || len(s.Home.Entries) == 0 && s.Home.Dir == "" {
return false
}
return linked(skillDir(s.Name)) || s.Home.Dir != ""
}
// putBack gives a skill brought in from the agents back to them as they
// had it (BeiWeiji on X: one taken out of the library was gone from the
// agents too). Its folder moves back to where it was, or the library's
// link to it goes; each agent's link to it is made again, and a copy it
// had of the very same files copied back. magpie's own links in their
// place go first. Something of the user's in the folder's old place now
// leaves it all as it is (false): the skill is removed as any other is.
// One in an agent's entry is left as it is.
func putBack(s *Skill) (bool, error) {
h, name := s.Home, s.Name
lib := skillDir(name)
clear := func(p string) (bool, error) {
if _, err := os.Lstat(p); errors.Is(err, fs.ErrNotExist) {
return true, nil
} else if err != nil {
return false, err
}
if !ours(p, name) {
return false, nil
}
return true, unlink(p)
}
dir := h.Dir
if linked(lib) {
dir = realDir(lib)
if err := os.Remove(lib); err != nil {
return false, err
}
} else if _, err := os.Lstat(lib); err == nil {
free, err := clear(h.Dir)
if err != nil || !free {
return false, err
}
if err := os.MkdirAll(filepath.Dir(h.Dir), 0o755); err != nil {
return false, err
}
var left *leftBehind
if err := move(lib, h.Dir); err != nil && !errors.As(err, &left) {
return false, err
}
} else {
// its folder is gone: nothing to give back
return false, err
}
for _, e := range h.Entries {
if e.Path == h.Dir || !e.Copy && e.Link == "" {
continue
}
if free, err := clear(e.Path); err != nil || !free {
continue // the user's own there now: left as it is
}
os.MkdirAll(filepath.Dir(e.Path), 0o755)
switch {
case e.Link != "":
to := e.Link
if runtime.GOOS == "windows" && !filepath.IsAbs(to) {
to = filepath.Join(filepath.Dir(e.Path), to)
}
dirLink(to, e.Path)
case dir != "":
if err := copyDir(dir, e.Path); err != nil {
os.RemoveAll(e.Path)
}
}
}
return true, nil
}
// RemoveFoundSkill takes a skill the agents have of their own out of every
// agent that has it (#1303), without bringing it into the library first:
// each agent's folder, and its copies of the very same files, go to the
+10
View File
@@ -512,6 +512,9 @@ type SkillView struct {
Manual bool `json:"manual,omitempty"`
// Router is "direct" for one the skill router leaves out (Skill.Router)
Router string `json:"router,omitempty"`
// Back are the agents it was brought in from: Remove gives it back
// to them as they had it (Skill.Home)
Back []string `json:"back,omitempty"`
}
// View is the Library page.
@@ -766,6 +769,13 @@ func readView(problems []Problem, glance bool) (*View, error) {
if s.Source != nil {
sv.Source, sv.Kind = s.Source.String(), s.Source.Kind
}
if canPutBack(s) {
for _, e := range s.Home.Entries {
if !slices.Contains(sv.Back, e.Agent) {
sv.Back = append(sv.Back, e.Agent)
}
}
}
// linked from a folder elsewhere is what the library's entry is, not
// what was written down when it came in: a linked folder moved in by
// hand is the library's own now, and Remove moves it to the backups