library: a skill can be removed with no copy kept in the backups (Eternalfate__ on X)

Removing a skill always moved its folder to ~/.magpie/backups/<time>/,
and backups that hold skills are never pruned, so they piled up. The
sheet that asks first now has one tick under what it says, "Keep a copy
in magpie's backups", ticked unless the reader unticked it last time
(localStorage magpie.libSkillBackup). Unticked, the sheet says the
folder is deleted and Remove posts noBackup: true. The default is
unchanged.

What is deleted is only magpie's own folder for the skill, or an
agent's own skill folder. Never deleted, either way:
- a folder a library skill links to (~/.agents/skills or anywhere
  else): only the link goes, and there's no tick on its sheet;
- an entry in ~/.agents/skills, which other tools read too: it still
  goes to the backups (inSharedDir), and the sheet has no tick for it;
- a skill brought in from the agents: it still goes back to them;
- a link inside a skill's folder: RemoveAll takes the link, not its
  target.

Every path that removes skills:
- GUI: one skill, Remove all / Remove n, Remove gone, an agent's own
  skill and several of them (skills/remove, remove-all, remove-gone,
  remove-found, remove-found-some take noBackup);
- CLI: magpie library skill rm <name> --no-backup, and --no-backup on
  rm --all and rm --gone, whose prompt says so;
- TUI: d asks, then D deletes with no backup (d d still keeps a copy);
  the first d's flash says so, on rows with a folder to delete.
library: RemoveSkillsHow, RemoveFoundSkillsHow, RemoveGoneSkillsHow
(keep bool); RemoveSkill(s) and RemoveFoundSkill(s) keep a copy as
before.

The sheets with the tick say they hold nothing to lose (modal.dirty
false): toggling it made Cancel ask to discard changes. A page reload
with such a sheet open still reads the form as changed (beforeunload
reads the core's modalFormDirty); not changed here.

Existing backups stay where they are, in ~/.magpie/backups/<time>/skills
and <time>/<agent>/skills. Nothing clears them; the Library's Backups
button opens the folder. docs/subsystems/library.md says so.

Run (mote, this tree at base 9494a38b4; rebased onto 848e3b1b2, whose two
commits since touch only internal/gateway):
- new tests: TestRemoveSkillWithoutBackup, TestRemoveFoundSkillWithout-
  Backup (library), TestLibrarySkillRmNoBackup (cli),
  TestLibraryDeleteWithoutBackup (tui): ok.
- broken by hand: with keep forced true in RemoveSkillsHow and
  RemoveFoundSkillsHow, all four are red (folders found in the backups);
  with the inSharedDir guard taken out, TestRemoveFoundSkillWithoutBackup
  is red (the shared entry deleted, not backed up).
- go test ./internal/library ./internal/cli ./internal/tui ./internal/gui
  -timeout 45m: library, cli, tui ok. gui: TestBuiltinsTranslated (#7257)
  and TestSettingsSaveKeepsWhatItDoesNotSend (#7240) red, the same at
  origin/main 9494a38b4 without this change.
- gofmt -l: nothing. GOOS=linux go vet -tags nogui and GOOS=windows go
  vet of those four packages: ok.
- GUI, chromium and webkit: skill-remove-nobackup (new: en, zh, zh-TW, ja,
  de at 980 and 440px; tick, its text, the choice remembered, the post,
  no tick for linked or shared skills, nothing sideways), i18n-keys,
  i18n-en-no-cjk and the 27 files that remove skills or read these
  sheets' lines. Red: the new file's Cancel (the dirty-form ask above,
  fixed and green after), and api-key-theme (#6444),
  found-skill-pick-remove at 420px (#5013), saved-signedout-remove
  (#6666): those 18 the same at origin/main 9494a38b4.

Not run: the full go test ./... and the whole GUI suite. mote and mica
were both taken by other sessions' full suites for over an hour. No
guard test outside the packages run reads the files changed (grep for
docs/subsystems/library.md and plugins/library). Not tried in the real
app or on Windows or Linux; a Windows junction to a skill folder goes
through the same linked() branch as on macOS.
This commit is contained in:
yetone
2026-11-20 14:59:04 +08:00
parent 848e3b1b26
commit 6a0afc38a9
14 changed files with 648 additions and 99 deletions
+1
View File
@@ -101,6 +101,7 @@ Pi's extensions and packages.
- 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 can be removed with no copy kept (@Eternalfate__ on X: removing one always left its folder in `~/.magpie/backups`, and `pruneBackups` never prunes a backup holding skills, `holdsSkills`, so they piled up). `RemoveSkillsHow`, `RemoveGoneSkillsHow` and `RemoveFoundSkillsHow` take `keep`; `RemoveSkill(s)`, `RemoveGoneSkills` and `RemoveFoundSkill(s)` are those with `keep` true, as before. Without it, `removeSkill` deletes the library's own folder (`os.RemoveAll`, which takes a link inside it away without following it) and `removeFound` an agent's own folder or copy. What was never deleted still isn't: a link (a skill linked from a folder of the user's, `~/.agents/skills` among them) only loses the link, a skill brought in from the agents still goes back to them (`putBack`), and an agent's own skill with its folder in `~/.agents/skills` (`inSharedDir`, which other tools read too) still goes to the backups. The page's sheets (one skill's trash, an agent's own skill's, Remove all, the picked ones, the ones gone from their source) carry one tick, Keep a copy in magpie's backups, shown only when some folder would be deleted, ticked unless this browser unticked it last (`keepLines`, `magpie.libSkillBackup`); unticked, what the sheet says changes and the change posts `noBackup: true` (`skills/remove`, `remove-all`, `remove-gone`, `remove-found`, `remove-found-some`). CLI: `magpie library skill rm <name> --no-backup`, and `--no-backup` on `rm --all` and `rm --gone`. TUI: d, then D in place of the second d, on a row whose folder would be kept. Backups made before stay in `~/.magpie/backups/<time>/skills/` until the user deletes them (the Library's Backups opens the folder) (`TestRemoveSkillWithoutBackup`, `TestRemoveFoundSkillWithoutBackup`, `TestLibrarySkillRmNoBackup`, `TestLibraryDeleteWithoutBackup`, `skill-remove-nobackup.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)
+26 -13
View File
@@ -42,9 +42,10 @@ const libraryUsage = `magpie library what the library gives
magpie library skill hand-over <name…>|--all move skills kept in ~/.agents/skills into the library's folder: the agents that read them
there keep them, ticked, and you can turn each off
magpie library skill hand-back <name> …and back into ~/.agents/skills, where those agents read it whatever is ticked
magpie library skill rm <name> (skills are installed from the app's Library page)
magpie library skill rm --all [--yes] every skill out of the library and the agents (asks first; --yes doesn't)
magpie library skill rm --gone [--yes] every skill an update found removed from its source (asks first; --yes doesn't)
magpie library skill rm <name> [--no-backup] (skills are installed from the app's Library page)
its folder goes to magpie's backups; --no-backup deletes it (a folder of yours it links to stays)
magpie library skill rm --all [--yes] [--no-backup] every skill out of the library and the agents (asks first; --yes doesn't)
magpie library skill rm --gone [--yes] [--no-backup] every skill an update found removed from its source (asks first; --yes doesn't)
magpie library skill update [name] fetch a skill from GitHub again; with no name, every one from there
(one changed here is left as it is; update it by name with --replace-edits)
magpie library skill how link|copy [agent] give skills as links to the library's or as copies: every agent's way, or one agent's
@@ -238,8 +239,8 @@ func libraryCmd(args []string) error {
if res, err = library.HandBackSkill(rest[1]); err == nil {
fmt.Println(green.Render("✓"), rest[1], "is back in", filepath.Join("~", ".agents", "skills", rest[1]))
}
case len(rest) == 2 && rest[0] == "rm":
res, err = library.RemoveSkill(rest[1])
case (len(rest) == 2 || len(rest) == 3 && rest[2] == "--no-backup") && rest[0] == "rm" && !strings.HasPrefix(rest[1], "-"):
res, err = library.RemoveSkillsHow([]string{rest[1]}, len(rest) == 2)
case len(rest) == 3 && rest[0] == "use-library":
res, err = library.UseLibrarySkill(rest[1], rest[2])
case len(rest) == 3 && rest[0] == "keep-own":
@@ -311,10 +312,12 @@ func libraryCmd(args []string) error {
// terminal; with no terminal to ask on, only --yes takes them. A library
// with no skills is said, and answers a nil result.
func removeEverySkill(args []string) (*library.Result, error) {
yes := false
yes, keep := false, true
for _, a := range args {
switch a {
case "--all":
case "--no-backup":
keep = false
case "--yes", "-y":
yes = true
default:
@@ -337,14 +340,18 @@ func removeEverySkill(args []string) (*library.Result, error) {
if !term.IsTerminal(int(os.Stdin.Fd())) {
return nil, fmt.Errorf("this removes all %s; run it with --yes to do so without being asked", plural(len(names), "skill"))
}
fmt.Printf("Remove all %s (%s) from the library and every agent? Folders magpie keeps go to its backups; folders of your own are only unlinked. [y/N] ",
plural(len(names), "skill"), strings.Join(names, ", "))
where := "Folders magpie keeps go to its backups"
if !keep {
where = "Folders magpie keeps are deleted, with no backup"
}
fmt.Printf("Remove all %s (%s) from the library and every agent? %s; folders of your own are only unlinked. [y/N] ",
plural(len(names), "skill"), strings.Join(names, ", "), where)
line, _ := stdin().ReadString('\n')
if a := strings.ToLower(strings.TrimSpace(line)); a != "y" && a != "yes" {
return nil, fmt.Errorf("nothing removed")
}
}
res, err := library.RemoveSkills(names)
res, err := library.RemoveSkillsHow(names, keep)
if err != nil {
return nil, err
}
@@ -362,10 +369,12 @@ func removeEverySkill(args []string) (*library.Result, error) {
// update or a check found its source without, asked about first, naming
// the ones changed here.
func removeGoneSkills(args []string) (*library.Result, error) {
yes := false
yes, keep := false, true
for _, a := range args {
switch a {
case "--gone":
case "--no-backup":
keep = false
case "--yes", "-y":
yes = true
default:
@@ -396,14 +405,18 @@ func removeGoneSkills(args []string) (*library.Result, error) {
if !term.IsTerminal(int(os.Stdin.Fd())) {
return nil, fmt.Errorf("this removes %s removed from their source; run it with --yes to do so without being asked", plural(len(names), "skill"))
}
fmt.Printf("Remove %s removed from their source (%s) from the library and every agent? The library's folders go to magpie's backups. [y/N] ",
plural(len(names), "skill"), strings.Join(shown, ", "))
where := "The library's folders go to magpie's backups."
if !keep {
where = "The library's folders are deleted, with no backup."
}
fmt.Printf("Remove %s removed from their source (%s) from the library and every agent? %s [y/N] ",
plural(len(names), "skill"), strings.Join(shown, ", "), where)
line, _ := stdin().ReadString('\n')
if a := strings.ToLower(strings.TrimSpace(line)); a != "y" && a != "yes" {
return nil, fmt.Errorf("nothing removed")
}
}
res, err := library.RemoveGoneSkills(names)
res, err := library.RemoveGoneSkillsHow(names, keep)
if err != nil {
return nil, err
}
+55
View File
@@ -0,0 +1,55 @@
package cli
import (
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/library"
)
// @Eternalfate__ on X: magpie library skill rm <name> --no-backup deletes
// the library's own folder with no copy in the backups; without the flag a
// copy is kept as ever; --all --no-backup --yes the same for every skill.
func TestLibrarySkillRmNoBackup(t *testing.T) {
h := t.TempDir()
for k, v := range map[string]string{"HOME": h, "USERPROFILE": h, "XDG_CONFIG_HOME": filepath.Join(h, ".config"), "CLAUDE_CONFIG_DIR": "", "CODEX_HOME": "", "APPDATA": "", "LOCALAPPDATA": ""} {
t.Setenv(k, v)
}
if err := os.MkdirAll(filepath.Join(h, ".claude"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(h, ".claude/settings.json"), []byte("{}"), 0o644); err != nil {
t.Fatal(err)
}
for _, n := range []string{"a", "b", "c", "d"} {
if _, err := library.CreateSkill(n, "A skill", []string{"claude"}); err != nil {
t.Fatal(err)
}
}
kept := func(name string) int {
m, _ := filepath.Glob(filepath.Join(library.BackupDir(), "*", "skills", name))
return len(m)
}
if err := libraryCmd([]string{"library", "skill", "rm", "a", "--no-backup"}); err != nil {
t.Fatal(err)
}
if err := libraryCmd([]string{"library", "skill", "rm", "b"}); err != nil {
t.Fatal(err)
}
if kept("a") != 0 || kept("b") != 1 {
t.Errorf("a kept %d (want 0), b kept %d (want 1)", kept("a"), kept("b"))
}
if err := libraryCmd([]string{"library", "skill", "rm", "c", "--nope"}); err == nil {
t.Error("an unknown flag was taken")
}
if err := libraryCmd([]string{"library", "skill", "rm", "--all", "--no-backup", "--yes"}); err != nil {
t.Fatal(err)
}
if v, _ := library.Read(nil); len(v.Skills) != 0 {
t.Errorf("left: %d", len(v.Skills))
}
if kept("c") != 0 || kept("d") != 0 {
t.Errorf("--all --no-backup kept c %d, d %d", kept("c"), kept("d"))
}
}
+90 -45
View File
@@ -8054,20 +8054,50 @@ magpie.plugin("library", (ctx) => {
return b;
}
// What a sheet removing skills says, and below it a box keeping their
// folders in magpie's backups: ticked, as every removal did before;
// unticked, the folders are deleted (Eternalfate__ on X: a skill removed
// is to be gone, not kept somewhere on disk). say(keep) gives the lines,
// as many either way, said again as the box changes. The reader's last
// choice is the next sheet's. With nothing of magpie's to keep (a skill
// linked from a folder of the reader's, only unlinked) there's no box.
// Answers whether to keep, for the sheet's Remove to ask.
function keepLines(ed, say, box) {
let keep = true;
try { keep = localStorage.getItem("magpie.libSkillBackup") !== "off"; } catch {}
if (!box) keep = true;
const ps = say(keep).filter(Boolean).map((l) => ed.appendChild(el("p", "lib-confirm", l)));
if (!box) return () => true;
const lab = el("label", "tick lib-keepbox");
const c = el("input");
c.type = "checkbox";
c.checked = keep;
c.onchange = () => {
keep = c.checked;
try { localStorage.setItem("magpie.libSkillBackup", keep ? "on" : "off"); } catch {}
say(keep).filter(Boolean).forEach((l, i) => { if (ps[i]) ps[i].textContent = l; });
};
lab.append(c, el("span", "", t("Keep a copy in magpie's backups")));
ed.append(lab);
return () => keep;
}
// the sheet asking first: its head and what it says, then Remove all n,
// or Remove n when they are the ones picked (some)
function confirmRemoveEvery(kind, names, title, lines, some) {
// or Remove n when they are the ones picked (some); skills' sheets give
// say and box, for keepLines
function confirmRemoveEvery(kind, names, title, lines, some, say, box) {
const ed = el("div", "editor lib-editor");
const head = el("div", "ehead");
head.append(glyph(GLYPH.trash), el("b", "", title));
ed.append(head);
for (const l of lines) if (l) ed.append(el("p", "lib-confirm", l));
const keep = say ? keepLines(ed, say, box) : () => true;
const bar = el("div", "bar");
const label = !some ? t("Remove all {n}", { n: names.length }) : names.length === 1 ? t("Remove") : t("Remove {n}", { n: names.length });
const go = button(label, "primary danger-fill", async () => { go.disabled = true; if (await removeEvery(kind, names, some)) closeLibModal(true); else go.disabled = false; });
const go = button(label, "primary danger-fill", async () => { go.disabled = true; if (await removeEvery(kind, names, some, !keep())) closeLibModal(true); else go.disabled = false; });
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
ed.append(bar);
modal = { save: () => go.click() };
modal = { save: () => go.click(), dirty: () => false }; // the keep box is a choice, not an edit to lose
openLib(ed);
}
const takenFrom = (items) => {
@@ -8082,14 +8112,17 @@ magpie.plugin("library", (ctx) => {
const skills = (some || lib.skills).slice(), names = skills.map((s) => s.name), n = names.length;
const linked = skills.filter((s) => s.kind === "folder").length, kept = n - linked;
const projects = (lib.projects || []).filter((p) => names.some((x) => p.skills?.[x]?.length)).length;
const where = [];
if (kept) where.push(t("{n} folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.", { n: kept }));
if (linked) where.push(t("{n} linked from folders of your own are only unlinked: those folders stay where they are.", { n: linked }));
const where = (keep) => {
const w = [];
if (kept) w.push(keep ? t("{n} folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.", { n: kept })
: t("{n} folders are deleted, with no copy kept.", { n: kept }));
if (linked) w.push(t("{n} linked from folders of your own are only unlinked: those folders stay where they are.", { n: linked }));
return [w.join(" ")];
};
confirmRemoveEvery("skills", names, !some ? t("Remove all {n} skills?", { n }) : n === 1 ? t("Remove {name}?", { name: names[0] }) : t("Remove {n} skills?", { n }), [
takenFrom(skills),
projects && t("The skills magpie placed in {n} projects are taken away too.", { n: projects }),
where.join(" "),
], !!some);
], !!some, where, kept > 0);
}
function confirmRemoveEveryServer(some) {
@@ -8108,10 +8141,10 @@ magpie.plugin("library", (ctx) => {
// picks; one that couldn't be stays picked and says why on its row, and
// only those gone are counted as removed. Nothing removed at all (the
// change refused) leaves every one picked, the sheet open with why.
async function removeEvery(kind, names, some) {
async function removeEvery(kind, names, some, noBackup) {
const what = (p) => p.what.replace(/^(skill|mcp|hook):/, "");
try {
const v = await api("library/" + kind + "/remove-all", { names });
const v = await api("library/" + kind + "/remove-all", noBackup ? { names, noBackup } : { names });
take(v);
const res = v.result || {}, no = res.unremoved || [];
if (some) {
@@ -8586,23 +8619,24 @@ magpie.plugin("library", (ctx) => {
list.append(li);
}
ed.append(list);
ed.append(el("p", "lib-confirm", takenFrom(skills) + " " + t("Their folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.")));
const keep = keepLines(ed, (keep) => [takenFrom(skills) + " " + (keep ? t("Their folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.")
: t("Their folders are deleted, with no copy kept."))], true);
const bar = el("div", "bar");
const go = button(n === 1 ? t("Remove") : t("Remove {n}", { n }), "primary danger-fill", async () => {
go.disabled = true;
if (await removeGone(names)) closeLibModal(true);
if (await removeGone(names, !keep())) closeLibModal(true);
else go.disabled = false;
});
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
ed.append(bar);
modal = { save: () => go.click() };
modal = { save: () => go.click(), dirty: () => false }; // the keep box is a choice, not an edit to lose
openLib(ed);
}
// only those still marked removed from their source are taken out; one
// found there again meanwhile stays, and is said
async function removeGone(names) {
async function removeGone(names, noBackup) {
try {
const v = await api("library/skills/remove-gone", { names });
const v = await api("library/skills/remove-gone", noBackup ? { names, noBackup } : { names });
take(v);
const res = v.result || {}, no = res.unremoved || [];
const out = names.filter((x) => !no.some((p) => p.what === "skill:" + x));
@@ -8724,14 +8758,16 @@ magpie.plugin("library", (ctx) => {
const head = el("div", "ehead");
head.append(glyph(GLYPH.trash), el("b", "", t("Remove {name}?", { name: s.name })));
ed.append(head);
ed.append(el("p", "lib-confirm", s.kind === "folder"
const own = s.kind !== "folder" && !s.missing;
const keep = keepLines(ed, (keep) => [!own
? t("It is taken out of every agent it was given to. The folder it was linked from stays where it is.")
: t("It is taken out of every agent it was given to, and its folder is moved to magpie's backups.")));
: keep ? t("It is taken out of every agent it was given to, and its folder is moved to magpie's backups.")
: t("It is taken out of every agent it was given to, and its folder is deleted, with no copy kept.")], own);
const bar = el("div", "bar");
const go = button(t("Remove"), "primary danger-fill", async () => { if (await change("skills/remove", { name: s.name }, t("{name} removed", { name: s.name }))) closeLibModal(true); });
const go = button(t("Remove"), "primary danger-fill", async () => { if (await change("skills/remove", keep() ? { name: s.name } : { name: s.name, noBackup: true }, t("{name} removed", { name: s.name }))) closeLibModal(true); });
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
ed.append(bar);
modal = { save: () => go.click() };
modal = { save: () => go.click(), dirty: () => false }; // the keep box is a choice, not an edit to lose
openLib(ed);
}
@@ -9004,41 +9040,40 @@ magpie.plugin("library", (ctx) => {
const head = el("div", "ehead");
head.append(glyph(GLYPH.trash), el("b", "", n === 1 ? t("Remove {name}?", { name: names[0] }) : t("Remove {n} skills?", { n })));
ed.append(head);
const lines = [];
if (n === 1) {
const f = some[0], agents = [...f.agents, ...(f.copies || [])].map(nameOf).filter(Boolean);
lines.push(!agents.length ? t("Its folder is moved to magpie's backups.")
: f.link ? t("It is taken out of {agents}. The folder it was linked from stays where it is.", { agents: agents.join(", ") })
: t("It is taken out of {agents}, and its folder is moved to magpie's backups.", { agents: agents.join(", ") }));
if (f.shared) lines.push(t("Its entry in {path} goes to the backups too, so no agent reads it from there.", { path: f.shared }));
if (f.others?.length) lines.push(t("{agents} has another skill by this name; that one stays.", { agents: f.others.map(nameOf).join(", ") }));
} else {
// own: folders deleted when no copy is kept; one with an entry in the
// shared folder (other tools' too) goes to the backups either way
const linked = some.filter((f) => f.link).length, kept = n - linked, own = some.filter((f) => !f.link && !f.shared).length;
const keep = keepLines(ed, (keep) => n === 1 ? foundSaid(some[0], keep) : (() => {
const lines = [];
const agents = [...new Set(some.flatMap((f) => [...f.agents, ...(f.copies || [])]))].map(nameOf).filter(Boolean);
if (agents.length) lines.push(t("They are taken out of {agents}.", { agents: agents.join(", ") }));
const linked = some.filter((f) => f.link).length, kept = n - linked, shared = some.filter((f) => f.shared).length;
const shared = some.filter((f) => f.shared).length;
const where = [];
if (kept) where.push(t("{n} folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.", { n: kept }));
if (keep ? kept : own) where.push(keep ? t("{n} folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.", { n: kept })
: t("{n} folders are deleted, with no copy kept.", { n: own }));
if (linked) where.push(t("{n} linked from folders of your own are only unlinked: those folders stay where they are.", { n: linked }));
lines.push(where.join(" "));
// magpie never deletes in the shared folder, other tools' too: an
// entry there goes to the backups either way (removeFound)
if (shared) lines.push(t("{n} have an entry in the shared skills folder, which goes to the backups too, so no agent reads them from there.", { n: shared }));
if (some.some((f) => f.others?.length)) lines.push(t("Another agent's own skill by one of these names stays."));
}
for (const l of lines) if (l) ed.append(el("p", "lib-confirm", l));
return lines;
})(), own > 0);
const bar = el("div", "bar");
const go = button(n === 1 ? t("Remove") : t("Remove {n}", { n }), "primary danger-fill", async () => { go.disabled = true; if (await removeFoundSome(names)) closeLibModal(true); else go.disabled = false; });
const go = button(n === 1 ? t("Remove") : t("Remove {n}", { n }), "primary danger-fill", async () => { go.disabled = true; if (await removeFoundSome(names, !keep())) closeLibModal(true); else go.disabled = false; });
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
ed.append(bar);
modal = { save: () => go.click() };
modal = { save: () => go.click(), dirty: () => false }; // the keep box is a choice, not an edit to lose
openLib(ed);
}
// as the library's Remove… (#1852): the ones taken out leave the list and
// the picks; one that couldn't be stays picked and says why on its row;
// none taken out (the change refused) leaves the sheet open with why
async function removeFoundSome(names) {
async function removeFoundSome(names, noBackup) {
const what = (p) => p.what.replace(/^skill:/, "");
try {
const v = await api("library/skills/remove-found-some", { names });
const v = await api("library/skills/remove-found-some", noBackup ? { names, noBackup } : { names });
take(v);
const res = v.result || {}, no = res.unremoved || [];
foundErrs.clear();
@@ -9059,22 +9094,32 @@ magpie.plugin("library", (ctx) => {
}
}
// what removing one skill of the agents' own does, its folder kept in
// the backups or (keep false) deleted
function foundSaid(f, keep) {
const agents = [...f.agents, ...(f.copies || [])].map(nameOf).filter(Boolean);
return [
!agents.length ? (keep ? t("Its folder is moved to magpie's backups.") : t("Its folder is deleted, with no copy kept."))
: f.link ? t("It is taken out of {agents}. The folder it was linked from stays where it is.", { agents: agents.join(", ") })
: keep ? t("It is taken out of {agents}, and its folder is moved to magpie's backups.", { agents: agents.join(", ") })
: t("It is taken out of {agents}, and its folder is deleted, with no copy kept.", { agents: agents.join(", ") }),
// never deleted, as the shared folder is other tools' too (removeFound)
f.shared && t("Its entry in {path} goes to the backups too, so no agent reads it from there.", { path: f.shared }),
f.others?.length && t("{agents} has another skill by this name; that one stays.", { agents: f.others.map(nameOf).join(", ") }),
];
}
function confirmRemoveFoundSkill(f) {
const ed = el("div", "editor lib-editor");
const head = el("div", "ehead");
head.append(glyph(GLYPH.trash), el("b", "", t("Remove {name}?", { name: f.name })));
ed.append(head);
const agents = [...f.agents, ...(f.copies || [])].map(nameOf).filter(Boolean);
ed.append(el("p", "lib-confirm", !agents.length ? t("Its folder is moved to magpie's backups.")
: f.link ? t("It is taken out of {agents}. The folder it was linked from stays where it is.", { agents: agents.join(", ") })
: t("It is taken out of {agents}, and its folder is moved to magpie's backups.", { agents: agents.join(", ") })));
if (f.shared) ed.append(el("p", "lib-confirm", t("Its entry in {path} goes to the backups too, so no agent reads it from there.", { path: f.shared })));
if (f.others?.length) ed.append(el("p", "lib-confirm", t("{agents} has another skill by this name; that one stays.", { agents: f.others.map(nameOf).join(", ") })));
const keep = keepLines(ed, (keep) => foundSaid(f, keep), !f.link && !f.shared);
const bar = el("div", "bar");
const go = button(t("Remove"), "primary danger-fill", async () => { if (await change("skills/remove-found", { name: f.name }, t("{name} removed", { name: f.name }))) closeLibModal(true); });
const go = button(t("Remove"), "primary danger-fill", async () => { if (await change("skills/remove-found", keep() ? { name: f.name } : { name: f.name, noBackup: true }, t("{name} removed", { name: f.name }))) closeLibModal(true); });
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
ed.append(bar);
modal = { save: () => go.click() };
modal = { save: () => go.click(), dirty: () => false }; // the keep box is a choice, not an edit to lose
openLib(ed);
}
@@ -979,6 +979,12 @@ magpie.strings({
"It is taken out of {agents}. The folder it was linked from stays where it is.": "将从 {agents} 中移除。它链接到的原文件夹保持不动。",
"It is taken out of {agents}, and its folder is moved to magpie's backups.": "将从 {agents} 中移除,文件夹移到 magpie 的备份。",
"Its entry in {path} goes to the backups too, so no agent reads it from there.": "它在 {path} 中的条目也会移到备份,不会再有 Agent 从那里读取。",
"Keep a copy in magpie's backups": "在 magpie 的备份里保留一份",
"{n} folders are deleted, with no copy kept.": "{n} 个技能文件夹将被删除,不保留备份。",
"Their folders are deleted, with no copy kept.": "它们的文件夹会被删除,不保留备份。",
"It is taken out of every agent it was given to, and its folder is deleted, with no copy kept.": "将从所有已启用的 Agent 中移除,文件夹直接删除,不保留备份。",
"Its folder is deleted, with no copy kept.": "文件夹将直接删除,不保留备份。",
"It is taken out of {agents}, and its folder is deleted, with no copy kept.": "将从 {agents} 中移除,文件夹直接删除,不保留备份。",
"It is taken out of the MCP settings of {agents}. Each file is copied to magpie's backups before it changes.": "将从 {agents} 的 MCP 配置中移除。每个文件改动前都会先复制到 magpie 的备份。",
"{agents} has another server by this name; that one stays.": "{agents} 中有另一个同名服务器,那个保持不动。",
"{agents} has another skill by this name; that one stays.": "{agents} 中有另一个同名 Skill,那个保持不动。",
@@ -2139,6 +2145,12 @@ magpie.strings({
"It is taken out of {agents}. The folder it was linked from stays where it is.": "將從 {agents} 中移除。它連結到的原資料夾保持不動。",
"It is taken out of {agents}, and its folder is moved to magpie's backups.": "將從 {agents} 中移除,資料夾移到 magpie 的備份。",
"Its entry in {path} goes to the backups too, so no agent reads it from there.": "它在 {path} 中的項目也會移到備份,不會再有 Agent 從那裡讀取。",
"Keep a copy in magpie's backups": "在 magpie 的備份裡保留一份",
"{n} folders are deleted, with no copy kept.": "{n} 個技能資料夾將被刪除,不保留備份。",
"Their folders are deleted, with no copy kept.": "它們的資料夾會被刪除,不保留備份。",
"It is taken out of every agent it was given to, and its folder is deleted, with no copy kept.": "將從所有已啟用的 Agent 中移除,資料夾直接刪除,不保留備份。",
"Its folder is deleted, with no copy kept.": "資料夾將直接刪除,不保留備份。",
"It is taken out of {agents}, and its folder is deleted, with no copy kept.": "將從 {agents} 中移除,資料夾直接刪除,不保留備份。",
"It is taken out of the MCP settings of {agents}. Each file is copied to magpie's backups before it changes.": "將從 {agents} 的 MCP 設定中移除。每個檔案改動前都會先複製到 magpie 的備份。",
"{agents} has another server by this name; that one stays.": "{agents} 中有另一個同名伺服器,那個保持不動。",
"{agents} has another skill by this name; that one stays.": "{agents} 中有另一個同名 Skill,那個保持不動。",
@@ -3298,6 +3310,12 @@ magpie.strings({
"It is taken out of {agents}. The folder it was linked from stays where it is.": "{agents} から外されます。リンク元のフォルダはそのまま残ります。",
"It is taken out of {agents}, and its folder is moved to magpie's backups.": "{agents} から外され、フォルダは magpie のバックアップに移されます。",
"Its entry in {path} goes to the backups too, so no agent reads it from there.": "{path} にあるエントリもバックアップに移され、どのエージェントもそこから読まなくなります。",
"Keep a copy in magpie's backups": "magpie のバックアップにコピーを残す",
"{n} folders are deleted, with no copy kept.": "{n} 個のフォルダは削除され、コピーは残りません。",
"Their folders are deleted, with no copy kept.": "フォルダは削除され、コピーは残りません。",
"It is taken out of every agent it was given to, and its folder is deleted, with no copy kept.": "渡していたすべてのエージェントから外され、フォルダは削除されます。コピーは残りません。",
"Its folder is deleted, with no copy kept.": "フォルダは削除され、コピーは残りません。",
"It is taken out of {agents}, and its folder is deleted, with no copy kept.": "{agents} から外され、フォルダは削除されます。コピーは残りません。",
"It is taken out of the MCP settings of {agents}. Each file is copied to magpie's backups before it changes.": "{agents} の MCP 設定から外されます。各ファイルは変更前に magpie のバックアップにコピーされます。",
"{agents} has another server by this name; that one stays.": "{agents} には同じ名前の別のサーバーがあり、そちらはそのまま残ります。",
"{agents} has another skill by this name; that one stays.": "{agents} には同じ名前の別のスキルがあり、そちらはそのまま残ります。",
@@ -4458,6 +4476,12 @@ magpie.strings({
"It is taken out of {agents}. The folder it was linked from stays where it is.": "Er wird aus {agents} entfernt. Der Ordner, auf den er verlinkt war, bleibt, wo er ist.",
"It is taken out of {agents}, and its folder is moved to magpie's backups.": "Er wird aus {agents} entfernt, und sein Ordner wird in die Backups von magpie verschoben.",
"Its entry in {path} goes to the backups too, so no agent reads it from there.": "Sein Eintrag in {path} kommt ebenfalls in die Backups, sodass kein Agent ihn mehr von dort liest.",
"Keep a copy in magpie's backups": "Eine Kopie in den Backups von magpie behalten",
"{n} folders are deleted, with no copy kept.": "{n} Ordner werden gelöscht, ohne eine Kopie zu behalten.",
"Their folders are deleted, with no copy kept.": "Ihre Ordner werden gelöscht, ohne eine Kopie zu behalten.",
"It is taken out of every agent it was given to, and its folder is deleted, with no copy kept.": "Er wird aus jedem Agenten entfernt, dem er gegeben wurde, und sein Ordner wird gelöscht, ohne eine Kopie zu behalten.",
"Its folder is deleted, with no copy kept.": "Sein Ordner wird gelöscht, ohne eine Kopie zu behalten.",
"It is taken out of {agents}, and its folder is deleted, with no copy kept.": "Er wird aus {agents} entfernt, und sein Ordner wird gelöscht, ohne eine Kopie zu behalten.",
"It is taken out of the MCP settings of {agents}. Each file is copied to magpie's backups before it changes.": "Er wird aus den MCP-Einstellungen von {agents} entfernt. Jede Datei wird vorher in die Backups von magpie kopiert.",
"{agents} has another server by this name; that one stays.": "{agents} hat einen anderen Server mit diesem Namen; dieser bleibt.",
"{agents} has another skill by this name; that one stays.": "{agents} hat einen anderen Skill mit diesem Namen; dieser bleibt.",
@@ -996,3 +996,5 @@ input.lib-memq:focus, input.lib-memtags:focus, input.lib-memwhy:focus { border-c
.lib-rulefile { display: flex; align-items: baseline; gap: 8px; min-width: 0; flex-wrap: wrap; }
.lib-rulefile > .note { flex: none; font-size: 12px; color: var(--fg-2); }
.lib-rulefile > .lib-path { min-width: 0; white-space: normal; overflow-wrap: anywhere; }
/* the box keeping a removed skill's folder in the backups, under what the sheet says */
.lib-editor label.tick.lib-keepbox { grid-column: 1 / -1; font-size: 12.5px; }
+8 -5
View File
@@ -751,6 +751,9 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
// Replace updates a skill changed here all the same, its
// changed version kept with the backups (#1449)
Replace bool
// NoBackup deletes a skill's folder on skills/remove… rather
// than moving it to the backups, as the reader picked
NoBackup bool `json:"noBackup"`
// a skill's file saved: its place in the skill, its new text,
// and what it held when the page opened it
File, Text, Was string
@@ -874,7 +877,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
res, err = &library.Result{Changed: []string{}, Problems: []library.Problem{}, Gone: []string{gone.Name}}, nil
}
case "skills/remove-gone":
res, err = library.RemoveGoneSkills(in.Names)
res, err = library.RemoveGoneSkillsHow(in.Names, !in.NoBackup)
case "skills/update-all":
res, err = library.UpdateSkills()
case "skills/update-some":
@@ -894,9 +897,9 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
case "skills/agents-some":
res, err = library.SomeSkillsAgents(in.Names, in.Agents, in.On)
case "skills/remove":
res, err = library.RemoveSkill(in.Name)
res, err = library.RemoveSkillsHow([]string{in.Name}, !in.NoBackup)
case "skills/remove-all":
res, err = library.RemoveSkills(in.Names)
res, err = library.RemoveSkillsHow(in.Names, !in.NoBackup)
case "skills/group":
res, err = library.GroupSkills(in.Old, in.Name, in.Names)
case "skills/ungroup":
@@ -910,9 +913,9 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
case "skills/import-all":
res, err = library.ImportSkills(in.Names)
case "skills/remove-found":
res, err = library.RemoveFoundSkill(in.Name)
res, err = library.RemoveFoundSkillsHow([]string{in.Name}, !in.NoBackup)
case "skills/remove-found-some":
res, err = library.RemoveFoundSkills(in.Names)
res, err = library.RemoveFoundSkillsHow(in.Names, !in.NoBackup)
case "skills/hand-over":
// out of ~/.agents/skills, into the library's own folder (tnt1223)
res, err = library.HandOverSkills(oneOrMore(in.Name, in.Names))
@@ -0,0 +1,169 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// @Eternalfate__ on X: removing a skill from the Library always kept a copy
// in magpie's backups. The sheet that asks first now has one tick, "Keep a
// copy in magpie's backups", ticked unless the reader unticked it last time
// (remembered in this browser). Unticked, what the sheet says changes to
// the folder being deleted, and Remove posts noBackup: true; ticked, it
// posts what it did before. A skill linked from a folder of the user's,
// and an agent's own skill with an entry in ~/.agents/skills, have no tick:
// nothing of theirs is deleted either way. Chromium and WebKit, 980px and
// 440px, in en, zh, zh-TW, ja and de; nothing runs off the page sideways.
// 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 { strings } = require("./strings.cjs");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/ef";
const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });
const lib = (st) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [agent("claude", "Claude Code"), agent("codex", "Codex"), agent("goose", "Goose")],
instructions: { agents: [] }, servers: [], foundServers: [], projects: [], problems: [],
skills: st.skills, foundSkills: st.found,
});
let I18N;
function tr(lang, key, vars = {}) {
let s = key;
if (lang !== "en") {
assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`);
s = I18N[lang][key];
}
return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
}
function server(lang, st, posts) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
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 json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/library") return json(lib(st));
if (url.pathname === "/api/library/skills/remove" || url.pathname === "/api/library/skills/remove-found") {
const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", "");
posts.push({ what, body });
st.skills = st.skills.filter((s) => s.name !== body.name);
st.found = st.found.filter((s) => s.name !== body.name);
return json({ ...lib(st), result: { changed: ["claude"] } });
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });
if (url.pathname.startsWith("/api/")) return json({});
if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const sideways = (page) => page.evaluate(() => {
const over = [];
const w = document.documentElement.clientWidth;
if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth);
for (const e of document.querySelectorAll("#modal .lib-editor, #modal .lib-editor .bar > *, #modal .lib-editor .lib-confirm, #modal .lib-keepbox")) {
const r = e.getBoundingClientRect();
if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "–" + Math.round(r.right));
}
return over;
});
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a skill removed with no copy kept, when the reader unticks it", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
I18N = strings().I18N;
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
t.after(() => browser.close());
for (const width of [980, 440]) for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
await t.test(`${lang} at ${width}px`, async () => {
const w = (key, vars) => tr(lang, key, vars);
const st = {
skills: [
{ name: "notes", kind: "", description: "Notes", agents: ["claude"] },
{ name: "lint", kind: "folder", description: "Lint", source: `${HOME}/.agents/skills/lint`, agents: ["claude"] },
],
found: [
{ name: "old", description: "Not wanted", agents: ["claude"] },
{ name: "grilling", description: "Grill a plan", agents: ["goose"], shared: `${HOME}/.agents/skills/grilling` },
],
};
const posts = [], errors = [];
const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
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));
page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); });
await page.route("**/*", server(lang, st, posts));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const row = (name) => page.locator("#view-library .lib-row").filter({ has: page.locator(".name", { hasText: new RegExp("^" + name + "$") }) });
await row("notes").waitFor();
const sheet = page.locator("#modal .lib-editor");
const ask = async (name) => {
await row(name).hover();
await row(name).locator("button.lib-icon.danger").click();
await sheet.waitFor();
};
const lines = async () => (await sheet.locator(".lib-confirm").allTextContents()).map((s) => s.trim());
const box = sheet.locator("label.lib-keepbox input[type=checkbox]");
const cancel = async () => {
await sheet.locator(".bar button:not(.primary)").click();
await sheet.waitFor({ state: "detached" });
};
// the library's own folder: ticked at first, as it always was
await ask("notes");
assert.equal(await box.count(), 1, "no tick");
assert.equal(await box.isChecked(), true, "not ticked at first");
assert.equal((await sheet.locator("label.lib-keepbox").textContent()).trim(), w("Keep a copy in magpie's backups"));
assert.deepEqual(await lines(), [w("It is taken out of every agent it was given to, and its folder is moved to magpie's backups.")]);
await sheet.locator("label.lib-keepbox").click();
assert.equal(await box.isChecked(), false);
assert.deepEqual(await lines(), [w("It is taken out of every agent it was given to, and its folder is deleted, with no copy kept.")]);
assert.deepEqual(await sideways(page), [], "sideways with the tick");
await cancel();
assert.deepEqual(posts, [], "Cancel posted");
// remembered: unticked again, and Remove says so
await ask("notes");
assert.equal(await box.isChecked(), false, "the choice wasn't remembered");
await sheet.locator(".bar button.primary").click();
await sheet.waitFor({ state: "detached" });
assert.deepEqual(posts.shift(), { what: "skills/remove", body: { name: "notes", noBackup: true } });
await row("notes").waitFor({ state: "detached" });
// linked from a folder of the user's: no tick, its folder stays
await ask("lint");
assert.equal(await box.count(), 0, "a linked skill has the tick");
assert.deepEqual(await lines(), [w("It is taken out of every agent it was given to. The folder it was linked from stays where it is.")]);
await cancel();
// an agent's own: the same tick; ticked again, Remove keeps a copy
await ask("old");
assert.equal(await box.isChecked(), false);
assert.deepEqual(await lines(), [w("It is taken out of {agents}, and its folder is deleted, with no copy kept.", { agents: "Claude Code" })]);
await sheet.locator("label.lib-keepbox").click();
assert.deepEqual(await lines(), [w("It is taken out of {agents}, and its folder is moved to magpie's backups.", { agents: "Claude Code" })]);
await sheet.locator(".bar button.primary").click();
await sheet.waitFor({ state: "detached" });
assert.deepEqual(posts.shift(), { what: "skills/remove-found", body: { name: "old" } });
// one in ~/.agents/skills: never deleted, so no tick
await ask("grilling");
assert.equal(await box.count(), 0, "a shared skill has the tick");
await cancel();
assert.deepEqual(posts, []);
assert.deepEqual(errors, []);
await ctx.close();
});
}
});
}
+7 -1
View File
@@ -113,6 +113,12 @@ func goneCheck(e *GoneError) SkillCheck {
// such skill. One found in its source again since is left, and said in
// Unremoved.
func RemoveGoneSkills(names []string) (*Result, error) {
return RemoveGoneSkillsHow(names, true)
}
// RemoveGoneSkillsHow is RemoveGoneSkills, with keep false deleting their
// folders rather than moving them to the backups (RemoveSkillsHow).
func RemoveGoneSkillsHow(names []string, keep bool) (*Result, error) {
mu.Lock()
l, err := load()
mu.Unlock()
@@ -145,7 +151,7 @@ func RemoveGoneSkills(names []string) (*Result, error) {
}
return nil, fmt.Errorf("no skill is removed from its source")
}
res, err := RemoveSkills(take)
res, err := RemoveSkillsHow(take, keep)
if res != nil {
res.Unremoved = append(res.Unremoved, left...)
}
+82
View File
@@ -0,0 +1,82 @@
package library
import (
"os"
"path/filepath"
"testing"
)
// @Eternalfate__ on X: a skill removed from the library always left a copy
// in ~/.magpie/backups. Removed with keep false, the library's own folder
// is deleted and nothing goes to the backups; a skill linked from a folder
// of the user's (~/.agents/skills among them) only loses the link, and the
// folder it points to stays, files and all. Kept, as by default, the
// folder still goes to the backups.
func TestRemoveSkillWithoutBackup(t *testing.T) {
h := sandbox(t)
ok(t)(CreateSkill("pdf", "Read PDFs", []string{"claude"}))
ok(t)(CreateSkill("xlsx", "Sheets", []string{"claude"}))
shared := filepath.Join(h, ".agents/skills/mine")
skill(t, shared, "mine", "The user's own")
ok(t)(InstallSkills(shared, []string{""}, []string{"claude"}))
// a link inside the library's own folder is taken away, not followed
if err := os.Symlink(shared, filepath.Join(skillDir("pdf"), "ref")); err != nil {
t.Fatal(err)
}
ok(t)(RemoveSkillsHow([]string{"pdf", "mine"}, false))
for _, p := range []string{skillDir("pdf"), skillDir("mine"), filepath.Join(h, ".claude/skills/pdf"), filepath.Join(h, ".claude/skills/mine")} {
if _, err := os.Lstat(p); !os.IsNotExist(err) {
t.Errorf("%s is still there", p)
}
}
if m, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "skills", "*")); len(m) != 0 {
t.Errorf("kept with the backups, though not asked: %v", m)
}
if read(t, filepath.Join(shared, "SKILL.md")) == "" {
t.Error("the user's folder in ~/.agents/skills went with it")
}
// the default still keeps a copy
ok(t)(RemoveSkill("xlsx"))
if m, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "skills", "xlsx", "SKILL.md")); len(m) != 1 {
t.Errorf("xlsx isn't kept with the backups: %v", m)
}
}
// The same for a skill an agent has of its own: removed without a backup
// its folders are deleted; a link only unlinked, its folder kept; and an
// entry in ~/.agents/skills, which other tools read, still goes to the
// backups, never deleted.
func TestRemoveFoundSkillWithoutBackup(t *testing.T) {
h := sandbox(t)
claude := filepath.Join(h, ".claude/skills")
skill(t, filepath.Join(claude, "notes"), "notes", "Mine")
skill(t, filepath.Join(h, ".codex/skills/notes"), "notes", "Mine")
shared := filepath.Join(h, ".agents/skills/pdf")
skill(t, shared, "pdf", "PDFs")
if err := os.Symlink(shared, filepath.Join(claude, "pdf")); err != nil {
t.Fatal(err)
}
dev := filepath.Join(h, "src/dev")
skill(t, dev, "dev", "Work in progress")
if err := os.Symlink(dev, filepath.Join(claude, "dev")); err != nil {
t.Fatal(err)
}
ok(t)(RemoveFoundSkillsHow([]string{"notes", "pdf", "dev"}, false))
for _, p := range []string{filepath.Join(claude, "notes"), filepath.Join(h, ".codex/skills/notes"), filepath.Join(claude, "pdf"), filepath.Join(claude, "dev")} {
if _, err := os.Lstat(p); !os.IsNotExist(err) {
t.Errorf("%s is still there", p)
}
}
if m, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "*", "skills", "notes")); len(m) != 0 {
t.Errorf("notes kept with the backups, though not asked: %v", m)
}
if m, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "*", "skills", "pdf", "SKILL.md")); len(m) != 1 {
t.Errorf("the shared entry wasn't kept with the backups: %v", m)
}
if read(t, filepath.Join(dev, "SKILL.md")) == "" {
t.Error("the folder Claude Code linked to is gone")
}
}
+52 -12
View File
@@ -607,6 +607,13 @@ func linked(p string) bool {
// Goose, Cindy): one link there, whichever of them it's for.
func sharedSkillsDir() string { return filepath.Join(home(), ".agents", "skills") }
// inSharedDir is whether p is an entry of ~/.agents/skills, however its
// folder is reached: the user's own, which other tools read too, that
// magpie never deletes.
func inSharedDir(p string) bool {
return realDir(filepath.Dir(p)) == realDir(sharedSkillsDir())
}
// sharedHas is whether the library's skill by that name is kept in
// ~/.agents/skills, so every agent that reads the shared folder has it,
// whatever the library gives (sharedEntry).
@@ -2258,9 +2265,7 @@ func skillsAgents(names, agents []string, on bool) (*Result, error) {
// RemoveSkill takes a skill out of the library and every agent; its folder
// is kept aside with the backups, never just deleted.
func RemoveSkill(name string) (*Result, error) {
return change(func(l *Library) error {
return removeSkill(l, name, time.Now().Format("2006-01-02_15-04-05.000"))
})
return RemoveSkillsHow([]string{name}, true)
}
// RemoveSkills takes the skills named out of the library and every agent
@@ -2268,6 +2273,16 @@ func RemoveSkill(name string) (*Result, error) {
// together, in one backup, and a folder of the user's only unlinked. One
// that can't be taken out stays, and is said in Unremoved.
func RemoveSkills(names []string) (*Result, error) {
return RemoveSkillsHow(names, true)
}
// RemoveSkillsHow is RemoveSkills, with keep false deleting the library's
// folders rather than moving them to the backups (Eternalfate__ on X: a
// skill removed is to be gone, not kept somewhere on disk). Only the
// library's own folder is deleted: a folder of the user's it links to
// (~/.agents/skills, or anywhere else) is only unlinked, as with keep,
// and one brought in from the agents still goes back to them.
func RemoveSkillsHow(names []string, keep bool) (*Result, error) {
if len(names) == 0 {
return nil, fmt.Errorf("no skills to remove")
}
@@ -2275,6 +2290,9 @@ func RemoveSkills(names []string) (*Result, error) {
var failed []Problem
res, err := change(func(l *Library) error {
stamp := time.Now().Format("2006-01-02_15-04-05.000")
if !keep {
stamp = ""
}
for _, name := range names {
if err := removeSkill(l, name, stamp); err != nil {
failed = append(failed, Problem{What: "skill:" + name, Error: err.Error()})
@@ -2292,8 +2310,8 @@ func RemoveSkills(names []string) (*Result, error) {
}
// removeSkill takes a skill out of l, its folder moved aside to the backup
// stamped so, or its link to a folder of the user's taken away. The entry
// goes only once its folder has.
// stamped so (with no stamp, deleted), or its link to a folder of the
// user's taken away. The entry goes only once its folder has.
func removeSkill(l *Library, name, stamp string) error {
i := slices.IndexFunc(l.Skills, func(s *Skill) bool { return s.Name == name })
if i < 0 {
@@ -2317,6 +2335,13 @@ func removeSkill(l *Library, name, stamp string) error {
if err := os.Remove(p); err != nil { // a folder of the user's: only the link goes
return err
}
case stamp == "":
// deleted, as asked: p is the library's own folder, not a link
// (that case is above), and RemoveAll takes a link inside it away
// without following it
if err := os.RemoveAll(p); err != nil {
return err
}
default:
aside := filepath.Join(BackupDir(), stamp, "skills", name)
if err := os.MkdirAll(filepath.Dir(aside), 0o700); err != nil {
@@ -2816,9 +2841,7 @@ func putBack(s *Skill) (bool, error) {
// agents only linked to is left where it is, and so is another skill by
// that name (Others): that is another skill.
func RemoveFoundSkill(name string) (*Result, error) {
return change(func(l *Library) error {
return removeFound(foundSkills(l), name)
})
return RemoveFoundSkillsHow([]string{name}, true)
}
// RemoveFoundSkills takes the skills named, of those the agents have of
@@ -2827,6 +2850,13 @@ func RemoveFoundSkill(name string) (*Result, error) {
// be taken out stays, and is said in Unremoved; the others go all the
// same. Only when none went does the change fail, with the first reason.
func RemoveFoundSkills(names []string) (*Result, error) {
return RemoveFoundSkillsHow(names, true)
}
// RemoveFoundSkillsHow is RemoveFoundSkills, with keep false deleting the
// skills' folders rather than moving them to the backups. Links are only
// taken away either way: a folder they lead to stays.
func RemoveFoundSkillsHow(names []string, keep bool) (*Result, error) {
if len(names) == 0 {
return nil, fmt.Errorf("no skills to remove")
}
@@ -2835,7 +2865,7 @@ func RemoveFoundSkills(names []string) (*Result, error) {
res, err := change(func(l *Library) error {
found := foundSkills(l)
for _, name := range names {
if err := removeFound(found, name); err != nil {
if err := removeFound(found, name, keep); err != nil {
failed = append(failed, Problem{What: "skill:" + name, Error: err.Error()})
}
}
@@ -2844,15 +2874,16 @@ func RemoveFoundSkills(names []string) (*Result, error) {
}
return nil
})
if res != nil {
if res != nil && len(names) > 1 {
res.Unremoved = failed
}
return res, err
}
// removeFound takes the skill of that name, of those found in the agents,
// out of each place it is: links taken away, folders set aside.
func removeFound(found []FoundSkill, name string) error {
// out of each place it is: links taken away, folders set aside (with keep
// false, deleted).
func removeFound(found []FoundSkill, name string, keep bool) 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)
@@ -2899,6 +2930,15 @@ func removeFound(found []FoundSkill, name string) error {
}
continue
}
if !keep && !inSharedDir(e.p) {
// not a link (above): the skill's own folder, deleted as asked.
// One in ~/.agents/skills, which other tools read too, is never
// deleted: it goes to the backups as ever
if err := os.RemoveAll(e.p); err != nil {
return err
}
continue
}
if _, err := setAside(e.who, e.p); err != nil {
return err
}
+23 -21
View File
@@ -73,27 +73,29 @@ var zh = map[string]string{
"press d again to take %s out of the library and every agent": "再按一次 d,把 %s 从资源库和所有 Agent 中移除",
"press d again to take %s out of every agent that has it, kept with the backups": "再按一次 d,把 %s 从所有使用它的 Agent 中移除,保留在备份里",
"press d again to take %s out of every agent that has it, their files kept with the backups": "再按一次 d,把 %s 从所有使用它的 Agent 中移除,文件保留在备份里",
"removed %s": "已移除 %s",
"%s in the library already": "%s 已在资源库中",
"%s updates from GitHub now": "%s 现在从 GitHub 更新",
"files of their own kept with the backups: %s": "各自的文件已保留在备份里:%s",
"%s skipped: %s": "已跳过 %s:%s",
"written into %s": "已写入 %s",
"off": "关闭",
"on": "开启",
"library": "资源库",
"agents": "Agent",
"filter agents": "筛选 Agent",
"no agent here has a place for it": "这里没有 Agent 能放它",
"RTK %s for %s": "RTK %s 用于 %s",
"restart %s for it to take effect": "重启 %s 后生效",
"%s given to %s": "已把 %s 给 %s",
"%s taken from %s": "已从 %[2]s 拿走 %[1]s",
"add": "添加",
"filter": "筛选",
"mcp server": "MCP 服务器",
"a URL, or a command it runs": "一个 URL,或它运行的命令",
"skills": "技能",
"D deletes its folder, with no backup": "按 D 直接删除文件夹,不留备份",
"deleted %s": "已删除 %s",
"removed %s": "已移除 %s",
"%s in the library already": "%s 已在资源库中",
"%s updates from GitHub now": "%s 现在从 GitHub 更新",
"files of their own kept with the backups: %s": "各自的文件已保留在备份里:%s",
"%s skipped: %s": "已跳过 %s:%s",
"written into %s": "已写入 %s",
"off": "关闭",
"on": "开启",
"library": "资源库",
"agents": "Agent",
"filter agents": "筛选 Agent",
"no agent here has a place for it": "这里没有 Agent 能放它",
"RTK %s for %s": "RTK %s 用于 %s",
"restart %s for it to take effect": "重启 %s 后生效",
"%s given to %s": "已把 %s 给 %s",
"%s taken from %s": "已从 %[2]s 拿走 %[1]s",
"add": "添加",
"filter": "筛选",
"mcp server": "MCP 服务器",
"a URL, or a command it runs": "一个 URL,或它运行的命令",
"skills": "技能",
"from GitHub, GitLab or any git repository, or a folder on this machine": "来自 GitHub、GitLab 或任意 git 仓库,或本机的文件夹",
"owner/repo, a GitHub or GitLab link, a git address (git@host:group/repo.git), or a folder's full path": "owner/repo、GitHub 或 GitLab 链接、git 地址(git@host:group/repo.git),或文件夹的完整路径",
"magpie looks there for skills, then you pick one": "magpie 在那里查找技能,然后由你挑选",
+22 -2
View File
@@ -30,6 +30,10 @@ type libRow struct {
on []string // the agents that get it (or have it, when found)
own bool // a server the agent's app puts in itself: nothing to bring in
bad int // agents it couldn't be given to
// kept: a skill whose own folder removing it moves to the backups (D
// deletes it instead); not one linked from a folder of the user's,
// nor one going back to the agents it was brought in from
kept bool
}
// libKinds are what the library can give, by row kind.
@@ -70,7 +74,7 @@ func (m *model) reloadLibrary() {
m.lib = append(m.lib, libRow{kind: "mcp", name: s.Name, about: what, on: s.Agents, bad: len(s.Problems)})
}
for _, s := range v.Skills {
r := libRow{kind: "skill", name: s.Name, about: s.Description, on: s.Agents, bad: len(s.Problems)}
r := libRow{kind: "skill", name: s.Name, about: s.Description, on: s.Agents, bad: len(s.Problems), kept: s.Kind != "folder" && len(s.Back) == 0 && !s.Missing}
if s.Missing {
r.about, r.bad = tr("its folder is gone"), r.bad+1
} else if s.Gone != "" {
@@ -86,7 +90,7 @@ func (m *model) reloadLibrary() {
m.lib = append(m.lib, libRow{kind: "found-mcp", name: f.Server.Name, on: f.Server.Agents, own: f.Own})
}
for _, f := range v.FoundSkills {
m.lib = append(m.lib, libRow{kind: "found-skill", name: f.Name, about: f.Description, on: f.Agents})
m.lib = append(m.lib, libRow{kind: "found-skill", name: f.Name, about: f.Description, on: f.Agents, kept: f.Link == ""})
}
if rv := library.ReadRTK(); rv.Path != "" || len(rv.Agents) > 0 {
r := libRow{kind: "rtk", name: "RTK"}
@@ -121,6 +125,19 @@ func (m model) libName(id string) string {
func (m model) updateLibrary(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
n := len(m.lib)
key := msg.String()
// D, while a skill's d waits for its second press, takes it out with
// its folder deleted rather than kept with the backups
if key == "D" && n > 0 && strings.HasPrefix(m.confirm, "library/") {
r := m.lib[m.lrow]
if r.kept && m.confirm == "library/"+r.kind+"/"+r.name {
m.confirm = ""
how := library.RemoveSkillsHow
if r.kind == "found-skill" {
how = library.RemoveFoundSkillsHow
}
return m, libCmd(func() (*library.Result, error) { return how([]string{r.name}, false) }, trf("deleted %s", r.name))
}
}
if key != "d" {
m.confirm = ""
}
@@ -220,6 +237,9 @@ func (m model) updateLibrary(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
case "found-mcp":
m.flash = trf("press d again to take %s out of every agent that has it, their files kept with the backups", r.name)
}
if r.kept {
m.flash += " · " + tr("D deletes its folder, with no backup")
}
return m, nil
}
m.confirm = ""
+87
View File
@@ -0,0 +1,87 @@
package tui
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/library"
)
// @Eternalfate__ on X: removing a skill always left a copy in magpie's
// backups. On the library page d, then D in place of the second d, takes
// it out with its folder deleted, no copy kept; d twice keeps one, as
// ever. A skill linked from a folder of the user's isn't offered D: only
// its link goes, the folder stays.
func TestLibraryDeleteWithoutBackup(t *testing.T) {
h := home(t)
for _, n := range []string{"keep", "gone"} {
if _, err := library.CreateSkill(n, "A skill", []string{"claude"}); err != nil {
t.Fatal(err)
}
}
old := filepath.Join(h, ".claude/skills/old")
write(t, filepath.Join(old, "SKILL.md"), "---\nname: old\ndescription: Not wanted\n---\n")
ext := filepath.Join(h, ".agents/skills/mine")
write(t, filepath.Join(ext, "SKILL.md"), "---\nname: mine\ndescription: Mine\n---\n")
if _, err := library.InstallSkills(ext, []string{""}, []string{"claude"}); err != nil {
t.Fatal(err)
}
m := press(t, model{w: 120, h: 40}, "6")
row := func(kind, name string) int {
t.Helper()
i := slices.IndexFunc(m.lib, func(r libRow) bool { return r.kind == kind && r.name == name })
if i < 0 {
t.Fatalf("no %s %s: %+v", kind, name, m.lib)
}
return i
}
backups := func(name string) []string {
m, _ := filepath.Glob(filepath.Join(library.BackupDir(), "*", "skills", name))
n, _ := filepath.Glob(filepath.Join(library.BackupDir(), "*", "*", "skills", name))
return append(m, n...)
}
m.lrow = row("skill", "gone")
m = press(t, m, "d")
if !strings.Contains(m.flash, "D deletes its folder") {
t.Fatalf("d doesn't say D: %q", m.flash)
}
m = press(t, m, "D")
if _, err := os.Lstat(filepath.Join(library.Dir(), "skills", "gone")); !os.IsNotExist(err) {
t.Fatalf("gone is still in the library, flash %q", m.flash)
}
if b := backups("gone"); len(b) != 0 {
t.Errorf("gone kept with the backups: %v", b)
}
m.lrow = row("found-skill", "old")
m = press(t, m, "d", "D")
if _, err := os.Lstat(old); !os.IsNotExist(err) {
t.Fatalf("old is still there, flash %q", m.flash)
}
if b := backups("old"); len(b) != 0 {
t.Errorf("old kept with the backups: %v", b)
}
// linked: no D, and D alone does nothing
m.lrow = row("skill", "mine")
m = press(t, m, "d")
if strings.Contains(m.flash, "D deletes") {
t.Errorf("a linked skill is offered D: %q", m.flash)
}
m = press(t, m, "D")
row("skill", "mine")
if _, err := os.Stat(filepath.Join(ext, "SKILL.md")); err != nil {
t.Fatal("the user's folder went")
}
// d twice still keeps a copy
m.lrow = row("skill", "keep")
m = press(t, m, "d", "d")
if b := backups("keep"); len(b) != 1 {
t.Errorf("keep isn't with the backups: %v, flash %q", b, m.flash)
}
}