Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
library: a skill removed from its source is said so, and every such skill goes in one click, asked first
yetonec417b1f4e300
diff --git a/docs/subsystems/library.md b/docs/subsystems/library.mdindex 9b2a80eaf..08dbee14d 100644--- a/docs/subsystems/library.md+++ b/docs/subsystems/library.md@@ -24,7 +24,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.| Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`) go first, marked official: `magpie-quota`, in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills/magpie-quota), lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) || Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) || Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in plugins/library/client.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). | [`skill_from.go`](../../internal/library/skill_from.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) |-| Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`, or `$XDG_STATE_HOME/skills/.skill-lock.json` when that is set, both read with the XDG one winning) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. A skill from another git repository (`kind: git`) keeps the repository's head commit it was fetched at in `Commit`, and `Hash`. A check runs `git ls-remote` for the ref (`gitRemoteHead`): the same head is current; another one is fetched shallowly, once per repository and ref in a check, and the skill's folder hashed, so a commit that left the skill as it was is current and its head is kept as `Commit` (`checkGitSkill`). Its `*EditedError` and the page's Changed here, Update and the question before replacing a change name that repository, not GitHub (`editedError`, `skill-git-source.test.cjs`). New skills in such a repository (`findNew`), Group again, icons and the market are GitHub's only. | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skills.go`](../../internal/library/skills.go) |+| Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`, or `$XDG_STATE_HOME/skills/.skill-lock.json` when that is set, both read with the XDG one winning) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. A skill from another git repository (`kind: git`) keeps the repository's head commit it was fetched at in `Commit`, and `Hash`. A check runs `git ls-remote` for the ref (`gitRemoteHead`): the same head is current; another one is fetched shallowly, once per repository and ref in a check, and the skill's folder hashed, so a commit that left the skill as it was is current and its head is kept as `Commit` (`checkGitSkill`). Its `*EditedError` and the page's Changed here, Update and the question before replacing a change name that repository, not GitHub (`editedError`, `skill-git-source.test.cjs`). New skills in such a repository (`findNew`), Group again, icons and the market are GitHub's only. A skill whose source was read whole and no longer has its folder or `SKILL.md` was removed there (`goneFrom`; スライム on Discord): `UpdateSkill` returns `*GoneError`, `UpdateSkills`/`UpdateSomeSkills` list it in `Result.Gone`, not `Unupdated`, and a check gives it status `gone`. Each records `Skill.Gone` (the view's `gone`), cleared when a check or an update finds it there again. A fetch that failed, a skill left out of a fetch as too big (`leftOutAt`) and a folder that can't be read are unknown, never gone. Nothing is taken out by itself: `RemoveGoneSkills` (`POST /api/library/skills/remove-gone`, `magpie library skill rm --gone [--yes]`, the TUI's `d` on the row) takes the ones named, or every one marked, as `RemoveSkills` does, folders to the backups, and keeps one found in its source again. The page tags such a row Removed upstream with no Update, says them apart from failures after Update all, and offers Clean up N in the group's heading (in the bar with one group), which asks first, naming each one and which was changed here (`confirmRemoveGone`, `skill-gone.test.cjs`). | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skills.go`](../../internal/library/skills.go) || Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `<claude dir>/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.<Event>]]` array tables with a `[[hooks.<Event>.hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:<Event>` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) || Subagents | A `Subagent` (#2283) is a name (lowercase letters, digits and -), a one-line description, a prompt, and the library's skills and MCP servers it uses, given to the agents ticked for it. `syncSubagents` writes it as a file of its own in each agent's user-level folder, in that agent's format (`subagentSpecOf`): Markdown with YAML front matter in `~/.claude/agents` (with `skills` and `mcpServers`), `~/.factory/droids` (with `mcpServers`), `~/.config/opencode/agents` (`mode: subagent`), `~/.gemini/agents`, `~/.qwen/agents`, `~/.grok/agents`, `~/.cursor/agents` and `~/.copilot/agents` (`<name>.agent.md`); a TOML role (`name`, `description`, `developer_instructions`) in `$CODEX_HOME/agents`. Skills and servers are named only where the agent's file can name them, and only those the library has. The page lists, per agent, whether it binds skills and servers (`SubagentAgentView`) and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) || Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) |@@ -76,10 +76,11 @@ agents RTK, a CLI that cuts shell output down before the model reads it.## Verification```sh-go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckWSLOnlyServerInItsDistro|TestCheckWindowsServerHere|TestCheckMixedServerEachSide|TestCheckSaysSignInRanOut|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut'+go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckWSLOnlyServerInItsDistro|TestCheckWindowsServerHere|TestCheckMixedServerEachSide|TestCheckSaysSignInRanOut|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut|TestUpdateFindsSkillsRemovedUpstream|TestGoneFromNeedsTheSourceRead'+go test -tags nogui ./internal/cli -run 'TestLibrarySkillRm'go test -race ./internal/mcpauthgo test -tags nogui ./internal/library-node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs+node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-gone.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs```The package's `TestMain` runs in a home of its own (`testenv`), never thediff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.goindex beee87327..ac219534a 100644--- a/internal/cli/library_cli.go+++ b/internal/cli/library_cli.go@@ -25,6 +25,7 @@ const libraryUsage = `magpie library what the library givesmagpie library skill agents <name> <a,b…|none>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 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@@ -122,6 +123,10 @@ func libraryCmd(args []string) error {if as, err = libraryAgents(rest[2], "skills"); err == nil {res, err = library.SkillAgents(rest[1], as)}+ case len(rest) >= 2 && rest[0] == "rm" && slices.Contains(rest[1:], "--gone"):+ if res, err = removeGoneSkills(rest[1:]); res == nil && err == nil {+ return nil+ }case len(rest) >= 2 && rest[0] == "rm" && slices.Contains(rest[1:], "--all"):if res, err = removeEverySkill(rest[1:]); res == nil && err == nil {return nil@@ -136,10 +141,16 @@ func libraryCmd(args []string) error {// a skill changed here is updated only when asked to be, its// changed version kept with the backups (#1449)var edited *library.EditedError+ var gone *library.GoneErrorif res, err = library.UpdateSkill(rest[1], len(rest) == 3); err == nil {fmt.Println(green.Render("✓"), rest[1], "is up to date")} else if errors.As(err, &edited) {err = fmt.Errorf("%w\n magpie library skill update %s --replace-edits takes the fetched one in its place, keeping yours with the backups", err, rest[1])+ } else if errors.As(err, &gone) {+ // removed there: said, with how to take it out; it's kept till then+ fmt.Println(amber.Render("!"), err)+ fmt.Println(muted.Render(" magpie library skill rm " + rest[1] + " takes it out (its folder goes to the backups)"))+ return nil}case len(rest) == 1 && rest[0] == "update":res, err = library.UpdateSkills()@@ -225,6 +236,65 @@ func removeEverySkill(args []string) (*library.Result, error) {return res, nil}+// removeGoneSkills is magpie library skill rm --gone: every skill an+// 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+ for _, a := range args {+ switch a {+ case "--gone":+ case "--yes", "-y":+ yes = true+ default:+ return nil, fmt.Errorf("usage:\n %s", libraryUsage)+ }+ }+ v, err := library.Read(nil)+ if err != nil {+ return nil, err+ }+ var names, shown []string+ for _, s := range v.Skills {+ if s.Gone == "" {+ continue+ }+ names = append(names, s.Name)+ if s.Edited {+ shown = append(shown, s.Name+" (changed here)")+ } else {+ shown = append(shown, s.Name)+ }+ }+ if len(names) == 0 {+ fmt.Println(green.Render("✓"), "no skill is removed from its source", muted.Render("(magpie library skill update finds them)"))+ return nil, nil+ }+ if !yes {+ 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, ", "))+ 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)+ if err != nil {+ return nil, err+ }+ n := 0+ for _, name := range names {+ if !slices.ContainsFunc(res.Unremoved, func(p library.Problem) bool { return p.What == "skill:"+name }) {+ n+++ }+ }+ fmt.Println(green.Render("✓"), plural(n, "skill"), "removed")+ return res, nil+}+// agentList is a comma list of agents; none (or nothing) is no agent.func agentList(s string) []string {out := []string{}@@ -269,6 +339,10 @@ func printLibraryResult(res *library.Result) {for _, p := range res.Unupdated {fmt.Println(amber.Render("!"), strings.TrimPrefix(p.What, "skill:"), muted.Render("not updated:"), p.Error)}+ if len(res.Gone) > 0 {+ fmt.Println(amber.Render("!"), "removed from their source:", strings.Join(res.Gone, ", "))+ fmt.Println(muted.Render(" kept here till you take them out: magpie library skill rm --gone"))+ }for _, p := range res.Unremoved {fmt.Println(amber.Render("!"), strings.TrimPrefix(p.What, "skill:"), muted.Render("not removed:"), p.Error)}@@ -345,6 +419,9 @@ func libraryStatus() error {if s.Missing {fmt.Println(" ", amber.Render("!"), muted.Render("its folder is gone"))}+ if s.Gone != "" {+ fmt.Println(" ", amber.Render("!"), muted.Render("removed from "+s.Source+" · magpie library skill rm --gone"))+ }}fmt.Println(muted.Render(" kept in " + v.Dir + " · magpie library help"))return nildiff --git a/internal/cli/library_rm_gone_test.go b/internal/cli/library_rm_gone_test.gonew file mode 100644index 000000000..4e0ca19ba--- /dev/null+++ b/internal/cli/library_rm_gone_test.go@@ -0,0 +1,114 @@+package cli++import (+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/library"+)++// magpie library skill rm --gone (スライム on Discord): an update says the+// skills its source no longer has apart from failures, and rm --gone takes+// every one of them out, asked first; with nobody at a terminal, only with+// --yes. A skill still in its source stays.+func TestLibrarySkillRmGone(t *testing.T) {+ git, err := exec.LookPath("git")+ if err != nil {+ t.Skip("git isn't installed")+ }+ 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": "",+ "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": filepath.Join(h, "gitconfig")} {+ t.Setenv(k, v)+ }+ write := func(p, s string) {+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(p, []byte(s), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ write(filepath.Join(h, ".claude/settings.json"), "")+ bare, work := filepath.Join(h, "skills.git"), filepath.Join(h, "work")+ run := func(dir string, args ...string) {+ t.Helper()+ cmd := exec.Command(git, append([]string{"-c", "user.name=t", "-c", "[email protected]", "-c", "init.defaultBranch=main", "-c", "commit.gpgsign=false"}, args...)...)+ cmd.Dir = dir+ if out, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("git %v: %v\n%s", args, err, out)+ }+ }+ run(h, "init", "-q", "--bare", bare)+ run(h, "init", "-q", work)+ for _, n := range []string{"pdf", "docx"} {+ write(filepath.Join(work, "skills", n, "SKILL.md"), "---\nname: "+n+"\ndescription: "+n+"\n---\n")+ }+ push := func() {+ run(work, "add", "-A")+ run(work, "commit", "-q", "-m", "skills")+ run(work, "push", "-q", bare, "HEAD:refs/heads/main")+ }+ push()+ addr := filepath.ToSlash(bare)+ if !strings.HasPrefix(addr, "/") {+ addr = "/" + addr+ }+ if _, err := library.InstallSkills("file://"+addr, []string{"skills/pdf", "skills/docx"}, []string{"claude"}); err != nil {+ t.Fatal(err)+ }+ if err := os.RemoveAll(filepath.Join(work, "skills", "docx")); err != nil {+ t.Fatal(err)+ }+ push()++ if err := libraryCmd([]string{"library", "skill", "update"}); err != nil {+ t.Fatal(err)+ }+ gone := func() (out []string) {+ v, _ := library.Read(nil)+ for _, s := range v.Skills {+ if s.Gone != "" {+ out = append(out, s.Name)+ }+ }+ return out+ }+ if g := gone(); len(g) != 1 || g[0] != "docx" {+ t.Fatalf("marked gone after update: %v", g)+ }+ // one asked for by name is said, not failed+ if err := libraryCmd([]string{"library", "skill", "update", "docx"}); err != nil {+ t.Errorf("update of a skill removed upstream: %v", err)+ }++ err = libraryCmd([]string{"library", "skill", "rm", "--gone"})+ if err == nil || !strings.Contains(err.Error(), "--yes") {+ t.Fatalf("with no terminal and no --yes: %v", err)+ }+ if v, _ := library.Read(nil); len(v.Skills) != 2 {+ t.Fatalf("taken without asking: %d left", len(v.Skills))+ }+ if err := libraryCmd([]string{"library", "skill", "rm", "--gone", "--nope"}); err == nil {+ t.Error("an unknown flag was taken")+ }+ if err := libraryCmd([]string{"library", "skill", "rm", "--gone", "--yes"}); err != nil {+ t.Fatal(err)+ }+ v, _ := library.Read(nil)+ if len(v.Skills) != 1 || v.Skills[0].Name != "pdf" {+ t.Errorf("left: %+v", v.Skills)+ }+ if _, err := os.Lstat(filepath.Join(h, ".claude/skills/docx")); !os.IsNotExist(err) {+ t.Error("claude still has docx")+ }+ if _, err := os.Lstat(filepath.Join(h, ".claude/skills/pdf")); err != nil {+ t.Errorf("pdf, still in its source, went: %v", err)+ }+ if err := libraryCmd([]string{"library", "skill", "rm", "--gone", "--yes"}); err != nil {+ t.Errorf("nothing gone: %v", err)+ }+}diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.jsindex d26c77041..9fc562ba2 100644--- a/internal/gui/assets/plugins/library/client.js+++ b/internal/gui/assets/plugins/library/client.js@@ -521,6 +521,12 @@ magpie.plugin("library", (ctx) => {// agent written that isn't one of them had it taken out (#332).function report(res, done, given) {if (!res) return;+ // an update that found its source without the skill: said so, not+ // as done or failed (スライム on Discord)+ if (res.gone?.length) {+ status(goneSaid(res.gone), "warn", 10000);+ return;+ }// skills installed together (lc on Discord): those the library had// already, and those left out because another by that name is in the// way, are named, beside how many were installed@@ -2699,8 +2705,14 @@ magpie.plugin("library", (ctx) => {autoChecked = true;setTimeout(() => checkSkills(true), 0);}+ // skills their source no longer has, from one place only: no group+ // heading is drawn to hold its Clean up, so the bar does+ if (skillGroups().length === 1) {+ const gone = lib.skills.filter(isGone);+ if (gone.length) rh.append(cleanUpButton(gone));+ }// one changed here is updated from its own row, which asks first- const stale = lib.skills.filter((s) => s.check?.status === "update" && !s.edited);+ const stale = lib.skills.filter((s) => s.check?.status === "update" && !s.edited && !isGone(s));if (stale.length) {const n = stale.length;const u = button(t("Update {n}", { n }), "action lib-updall", async (e, b) => {@@ -3132,7 +3144,7 @@ magpie.plugin("library", (ctx) => {head.append(chev, el("span", "name" + (p.mono && p.key ? " mono" : ""), p.label),el("span", "sub", filtering && hits.length !== n ? t("{n} of {total}", { n: hits.length, total: n }) : String(n)));// a dot when GitHub changed some of its skills- const stale = p.skills.filter((s) => s.check?.status === "update").length;+ const stale = p.skills.filter((s) => s.check?.status === "update" && !isGone(s)).length;if (stale) {const dot = el("span", "lib-dot");dot.title = stale === 1 ? t("1 skill has an update") : t("{n} skills have updates", { n: stale });@@ -3183,7 +3195,9 @@ magpie.plugin("library", (ctx) => {who.append(sub);const tags = el("div", "lib-tags");// one changed here is updated from its own row, which asks first (#1449)- const stale = g.skills.filter((s) => s.check?.status === "update" && !s.edited);+ const stale = g.skills.filter((s) => s.check?.status === "update" && !s.edited && !isGone(s));+ const gone = g.skills.filter((s) => isGone(skillNamed(s.name) || s));+ if (gone.length) tags.append(cleanUpButton(gone.map((s) => skillNamed(s.name) || s)));if (stale.length) {const u = button(t("Update {n}", { n: stale.length }), "action lib-updall", async (e, b) => {b.classList.add("busy");@@ -3995,13 +4009,14 @@ magpie.plugin("library", (ctx) => {const v = await api(names ? "library/skills/update-some" : "library/skills/update-all", names ? { names } : {});take(v);const res = v.result || {};- const up = res.updated?.length || 0, no = res.unupdated || [];+ const up = res.updated?.length || 0, no = res.unupdated || [], gone = res.gone || [];// one changed here is left as it is (#1449): said apart from those// that couldn't be fetchedconst isEdited = (p) => lib.skills.some((s) => s.edited && "skill:" + s.name === p.what);const kept = no.filter(isEdited).map((p) => p.what.replace(/^skill:/, "")), failed = no.filter((p) => !isEdited(p));- if (no.length) {+ if (no.length || gone.length) {const parts = [];+ if (gone.length) parts.push(goneSaid(gone));if (failed.length) {const p = failed[0];parts.push(t("{name} wasn't updated: {error}", { name: p.what.replace(/^skill:/, ""), error: p.error }) + (failed.length > 1 ? " " + t("(and {n} more)", { n: failed.length - 1 }) : ""));@@ -4357,20 +4372,23 @@ magpie.plugin("library", (ctx) => {try {take(await api("library/skills/check", {}));const got = lib.skills.filter((s) => s.check);- const n = got.filter((s) => s.check.status === "update").length;+ const n = got.filter((s) => s.check.status === "update" && !isGone(s)).length;const unknown = got.filter((s) => s.check.status === "unknown");- let msg = n ? (n === 1 ? t("1 skill has an update") : t("{n} skills have updates", { n })) : t("Every skill is up to date");+ const gone = lib.skills.filter(isGone).map((s) => s.name);+ let msg = n ? (n === 1 ? t("1 skill has an update") : t("{n} skills have updates", { n })) : gone.length ? "" : t("Every skill is up to date");+ if (gone.length) msg += (msg ? " · " : "") + goneSaid(gone);const more = lib.newSkills?.length || 0;if (more) msg += " · " + (more === 1 ? t("1 more skill in their repositories") : t("{n} more skills in their repositories", { n: more }));if (quiet) {const said = [];if (n) said.push(n === 1 ? t("1 skill has an update") : t("{n} skills have updates", { n }));+ if (gone.length) said.push(goneSaid(gone));if (more) said.push(more === 1 ? t("1 more skill in their repositories") : t("{n} more skills in their repositories", { n: more }));if (said.length) status(said.join(" · "), "ok");} else if (unknown.length) {msg += " · " + t("{n} couldn't be checked: {error}", { n: unknown.length, error: checkError(unknown[0].check) });status(msg, "warn", 8000);- } else status(msg, "ok");+ } else status(msg, gone.length ? "warn" : "ok", gone.length ? 10000 : undefined);} catch (e) {if (!quiet) status(e.message, "err", 6000);}@@ -4546,7 +4564,14 @@ magpie.plugin("library", (ctx) => {const who = el("div", "who");const nm = el("div", "name", s.name);const c = s.check;- if (c?.status === "update") {+ const gone = isGone(s);+ if (gone) {+ // its source no longer has it: kept till the user takes it out+ const repo = gitRepoOf(s) || skillRepo(s);+ nm.append(tag(t("Removed upstream"), "warn lib-gone", repo+ ? t("{repo} no longer has this skill: it was removed there. It stays here until you remove it.", { repo })+ : t("Its source no longer has this skill: it was removed there. It stays here until you remove it.")));+ } else if (c?.status === "update") {const b = tag(t("Update available"), "lib-new", t("Changed on GitHub since it was installed") + "\n" + checkLine(c));if (c.url) {b.classList.add("link");@@ -4601,7 +4626,9 @@ magpie.plugin("library", (ctx) => {who.append(src);}const acts = el("div", "lib-rowacts");- if (s.kind === "github" || s.kind === "git" || s.origin) {+ // one its source no longer has has nothing to update from: Update all,+ // or a check, finds it there again if it comes back+ if (!gone && (s.kind === "github" || s.kind === "git" || s.origin)) {const u = button("", "lib-icon", async (e, b) => {if (s.edited) return confirmUpdateEdited(s);b.classList.add("busy");@@ -4628,6 +4655,70 @@ magpie.plugin("library", (ctx) => {return row;}+ // A skill its source no longer has (スライム on Discord): an update or a+ // check read the repository and found it removed there. Nothing takes+ // it out by itself; Clean up takes out every such skill of a group at+ // once, asking first, and a row's Remove takes out one.+ const isGone = (s) => !!s.gone || s.check?.status === "gone";+ function goneSaid(names) {+ return names.length === 1 ? t("{name} was removed from its source", { name: names[0] })+ : t("{n} skills were removed from their sources: {names}", { n: names.length, names: names.join(", ") });+ }+ function cleanUpButton(skills) {+ const b = button(t("Clean up {n}", { n: skills.length }), "action lib-updall lib-cleanup", () => confirmRemoveGone(skills));+ b.title = skills.length === 1 ? t("Remove {name}: its source no longer has it", { name: skills[0].name })+ : t("Remove the {n} skills their source no longer has", { n: skills.length });+ return b;+ }+ function confirmRemoveGone(skills) {+ const names = skills.map((s) => s.name), n = names.length;+ const repos = [...new Set(skills.map((s) => gitRepoOf(s) || skillRepo(s)).filter(Boolean))];+ const ed = el("div", "editor lib-editor lib-remove-gone");+ const head = el("div", "ehead");+ head.append(glyph(GLYPH.trash), el("b", "", n === 1 ? t("Remove {name}?", { name: names[0] }) : t("Remove {n} skills removed upstream?", { n })));+ ed.append(head);+ ed.append(el("p", "lib-confirm", repos.length === 1+ ? (n === 1 ? t("{repo} no longer has this skill: it was removed there.", { repo: repos[0] }) : t("{repo} no longer has these skills: they were removed there.", { repo: repos[0] }))+ : t("Their sources no longer have these skills: they were removed there.")));+ // each by name, and one changed here says so: removing it takes the change out too+ const list = el("ul", "lib-gonelist");+ for (const s of skills) {+ const li = el("li", "", s.name);+ if (s.edited) li.append(tag(t("Changed here"), "warn lib-edited", t("You changed it here since it was fetched.")));+ 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 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);+ else go.disabled = false;+ });+ bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);+ ed.append(bar);+ modal = { save: () => go.click() };+ 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) {+ try {+ const v = await api("library/skills/remove-gone", { names });+ take(v);+ const res = v.result || {}, no = res.unremoved || [];+ const out = names.filter((x) => !no.some((p) => p.what === "skill:" + x));+ const done = out.length === 1 ? t("{name} removed", { name: out[0] }) : t("{n} skills removed", { n: out.length });+ if (no.length) status((out.length ? done + " · " : "") + t("{name} wasn't removed: {error}", { name: no[0].what.replace(/^skill:/, ""), error: no[0].error }) + (no.length > 1 ? " " + t("(and {n} more)", { n: no.length - 1 }) : ""), "warn", 10000);+ else report(res, done);+ render();+ return true;+ } catch (e) {+ status(e.message, "err", 6000);+ return false;+ }+ }+// An update of a skill changed here replaces the change (#1449): asked in// the page, and the version replaced is kept with the backups.function confirmUpdateEdited(s) {diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.jsindex 747fd81d1..b9e925a2b 100644--- a/internal/gui/assets/plugins/library/i18n.js+++ b/internal/gui/assets/plugins/library/i18n.js@@ -550,6 +550,20 @@ magpie.strings({"Changed on GitHub since it was installed": "安装后 GitHub 上已有改动","Up to date with GitHub": "与 GitHub 一致","Changed here": "本地已改动",+ "{name} was removed from its source": "{name} 已从来源中删除",+ "{n} skills were removed from their sources: {names}": "{n} 个技能已从来源中删除:{names}",+ "Clean up {n}": "清理 {n} 个",+ "Remove {name}: its source no longer has it": "移除 {name}:来源里已经没有它了",+ "Remove the {n} skills their source no longer has": "移除来源里已没有的 {n} 个技能",+ "Remove {n} skills removed upstream?": "移除 {n} 个上游已删除的技能?",+ "{repo} no longer has this skill: it was removed there.": "{repo} 里已经没有这个技能了:它在那里被删除了。",+ "{repo} no longer has these skills: they were removed there.": "{repo} 里已经没有这些技能了:它们在那里被删除了。",+ "Their sources no longer have these skills: they were removed there.": "它们的来源里已经没有这些技能了:它们在那里被删除了。",+ "You changed it here since it was fetched.": "获取之后你在本地改过它。",+ "Their folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.": "它们的文件夹会移到 magpie 的备份里(资料库顶部的“备份”),不会被删除。",+ "Removed upstream": "上游已删除",+ "{repo} no longer has this skill: it was removed there. It stays here until you remove it.": "{repo} 里已经没有这个技能了:它在那里被删除了。在你移除之前,它会一直留在这里。",+ "Its source no longer has this skill: it was removed there. It stays here until you remove it.": "来源里已经没有这个技能了:它在那里被删除了。在你移除之前,它会一直留在这里。","You changed it since it was fetched from GitHub. Updating asks before it replaces your changes.": "从 GitHub 获取后你在本地改动过它。更新前会先询问,不会直接覆盖你的改动。","Changed here: asks before it replaces your changes": "本地已改动:更新前会先询问,不会直接覆盖","Replace your changes to {name}?": "用 GitHub 的版本替换你对 {name} 的改动?",@@ -1162,6 +1176,20 @@ magpie.strings({"Changed on GitHub since it was installed": "安裝後 GitHub 上已有改動","Up to date with GitHub": "與 GitHub 一致","Changed here": "本機已改動",+ "{name} was removed from its source": "{name} 已從來源中刪除",+ "{n} skills were removed from their sources: {names}": "{n} 個技能已從來源中刪除:{names}",+ "Clean up {n}": "清理 {n} 個",+ "Remove {name}: its source no longer has it": "移除 {name}:來源裡已經沒有它了",+ "Remove the {n} skills their source no longer has": "移除來源裡已沒有的 {n} 個技能",+ "Remove {n} skills removed upstream?": "移除 {n} 個上游已刪除的技能?",+ "{repo} no longer has this skill: it was removed there.": "{repo} 裡已經沒有這個技能了:它在那裡被刪除了。",+ "{repo} no longer has these skills: they were removed there.": "{repo} 裡已經沒有這些技能了:它們在那裡被刪除了。",+ "Their sources no longer have these skills: they were removed there.": "它們的來源裡已經沒有這些技能了:它們在那裡被刪除了。",+ "You changed it here since it was fetched.": "取得之後你在本機改過它。",+ "Their folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.": "它們的資料夾會移到 magpie 的備份裡(資料庫頂部的「備份」),不會被刪除。",+ "Removed upstream": "上游已刪除",+ "{repo} no longer has this skill: it was removed there. It stays here until you remove it.": "{repo} 裡已經沒有這個技能了:它在那裡被刪除了。在你移除之前,它會一直留在這裡。",+ "Its source no longer has this skill: it was removed there. It stays here until you remove it.": "來源裡已經沒有這個技能了:它在那裡被刪除了。在你移除之前,它會一直留在這裡。","You changed it since it was fetched from GitHub. Updating asks before it replaces your changes.": "從 GitHub 取得後你在本機改動過它。更新前會先詢問,不會直接覆蓋你的改動。","Changed here: asks before it replaces your changes": "本機已改動:更新前會先詢問,不會直接覆蓋","Replace your changes to {name}?": "用 GitHub 的版本取代你對 {name} 的改動?",@@ -1773,6 +1801,20 @@ magpie.strings({"Changed on GitHub since it was installed": "インストール後に GitHub で変更されています","Up to date with GitHub": "GitHub と同じ","Changed here": "ローカルで変更済み",+ "{name} was removed from its source": "{name} はソースから削除されました",+ "{n} skills were removed from their sources: {names}": "{n} 個のスキルがソースから削除されました:{names}",+ "Clean up {n}": "{n} 件を整理",+ "Remove {name}: its source no longer has it": "{name} を削除:ソースにもうありません",+ "Remove the {n} skills their source no longer has": "ソースにもうない {n} 個のスキルを削除",+ "Remove {n} skills removed upstream?": "上流で削除された {n} 個のスキルを削除しますか?",+ "{repo} no longer has this skill: it was removed there.": "{repo} にこのスキルはもうありません:そこで削除されました。",+ "{repo} no longer has these skills: they were removed there.": "{repo} にこれらのスキルはもうありません:そこで削除されました。",+ "Their sources no longer have these skills: they were removed there.": "ソースにこれらのスキルはもうありません:そこで削除されました。",+ "You changed it here since it was fetched.": "取得後にローカルで変更しています。",+ "Their folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.": "フォルダは削除されず、magpie のバックアップ(ライブラリ上部の「バックアップ」)に移されます。",+ "Removed upstream": "上流で削除",+ "{repo} no longer has this skill: it was removed there. It stays here until you remove it.": "{repo} にこのスキルはもうありません:そこで削除されました。削除するまでここに残ります。",+ "Its source no longer has this skill: it was removed there. It stays here until you remove it.": "ソースにこのスキルはもうありません:そこで削除されました。削除するまでここに残ります。","You changed it since it was fetched from GitHub. Updating asks before it replaces your changes.": "GitHub から取得した後、ここで変更されています。更新は変更を置き換える前に確認します。","Changed here: asks before it replaces your changes": "ローカルで変更済み:変更を置き換える前に確認します","Replace your changes to {name}?": "{name} への変更を GitHub の版で置き換えますか?",@@ -2385,6 +2427,20 @@ magpie.strings({"Changed on GitHub since it was installed": "Seit der Installation auf GitHub geändert","Up to date with GitHub": "Auf dem Stand von GitHub","Changed here": "Hier geändert",+ "{name} was removed from its source": "{name} wurde aus seiner Quelle entfernt",+ "{n} skills were removed from their sources: {names}": "{n} Skills wurden aus ihren Quellen entfernt: {names}",+ "Clean up {n}": "{n} aufräumen",+ "Remove {name}: its source no longer has it": "{name} entfernen: seine Quelle hat ihn nicht mehr",+ "Remove the {n} skills their source no longer has": "Die {n} Skills entfernen, die ihre Quelle nicht mehr hat",+ "Remove {n} skills removed upstream?": "{n} upstream entfernte Skills entfernen?",+ "{repo} no longer has this skill: it was removed there.": "{repo} hat diesen Skill nicht mehr: Er wurde dort entfernt.",+ "{repo} no longer has these skills: they were removed there.": "{repo} hat diese Skills nicht mehr: Sie wurden dort entfernt.",+ "Their sources no longer have these skills: they were removed there.": "Ihre Quellen haben diese Skills nicht mehr: Sie wurden dort entfernt.",+ "You changed it here since it was fetched.": "Du hast ihn hier geändert, seit er geholt wurde.",+ "Their folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.": "Ihre Ordner werden in magpies Backups verschoben (Backups, oben in der Bibliothek), nicht gelöscht.",+ "Removed upstream": "Upstream entfernt",+ "{repo} no longer has this skill: it was removed there. It stays here until you remove it.": "{repo} hat diesen Skill nicht mehr: Er wurde dort entfernt. Er bleibt hier, bis du ihn entfernst.",+ "Its source no longer has this skill: it was removed there. It stays here until you remove it.": "Seine Quelle hat diesen Skill nicht mehr: Er wurde dort entfernt. Er bleibt hier, bis du ihn entfernst.","You changed it since it was fetched from GitHub. Updating asks before it replaces your changes.": "Du hast ihn geändert, seit er von GitHub geholt wurde. Ein Update fragt, bevor es deine Änderungen ersetzt.","Changed here: asks before it replaces your changes": "Hier geändert: fragt, bevor es deine Änderungen ersetzt","Replace your changes to {name}?": "Deine Änderungen an {name} ersetzen?",diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.cssindex e98bf5d66..41f3793ea 100644--- a/internal/gui/assets/plugins/library/library.css+++ b/internal/gui/assets/plugins/library/library.css@@ -350,6 +350,9 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col.lib-editor .lib-picks { grid-column: 1 / -1; max-height: 320px; }.lib-editor .lib-keep { grid-column: 1 / -1; margin: 0 -6px; }.lib-confirm { grid-column: 1 / -1; margin: 0; font-size: 12.5px; line-height: 1.55; color: var(--fg-2); }+/* the skills a Clean up takes out, by name; one changed here says so */+.lib-gonelist { grid-column: 1 / -1; margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 4px; max-height: 40vh; overflow-y: auto; }+.lib-gonelist li { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; min-width: 0; font-family: var(--code-font, var(--code)); font-size: 12.5px; color: var(--fg); overflow-wrap: anywhere; }.text.danger-fill { background: var(--red); color: #fff; }/* one agent's skills or servers on or off at once (#475) */.lib-byagent-sheet .lib-byagent-list { grid-column: 1 / -1; max-height: min(52vh, 420px); overflow: auto; }diff --git a/internal/gui/library.go b/internal/gui/library.goindex 860c4ba8d..8110d9dfb 100644--- a/internal/gui/library.go+++ b/internal/gui/library.go@@ -500,6 +500,13 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {res, err = library.InstallSkills(in.Source, in.Paths, in.Agents)case "skills/update":res, err = library.UpdateSkill(in.Name, in.Replace)+ var gone *library.GoneError+ if errors.As(err, &gone) {+ // removed from its source: the page shows it so, not a failure+ res, err = &library.Result{Changed: []string{}, Problems: []library.Problem{}, Gone: []string{gone.Name}}, nil+ }+ case "skills/remove-gone":+ res, err = library.RemoveGoneSkills(in.Names)case "skills/update-all":res, err = library.UpdateSkills()case "skills/update-some":diff --git a/internal/gui/tests/skill-gone.test.cjs b/internal/gui/tests/skill-gone.test.cjsnew file mode 100644index 000000000..5ff6e5565--- /dev/null+++ b/internal/gui/tests/skill-gone.test.cjs@@ -0,0 +1,175 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// スライム on Discord: a repository took some of its skills out, Update all+// said each of them failed, and they could only be taken out one by one.+// A skill an update or a check found its source without carries "Removed+// upstream" (no Update available, no update icon), Update all says them+// apart from failures, and Clean up N, in the group's heading or, with one+// group only, in the bar, asks first, naming each one and saying which was+// changed here, then sends skills/remove-gone with their names. Nothing is+// sent before the answer, and Cancel sends nothing. In English and+// Chinese, 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/lionel";+const REPO = "leonxlnx/taste-skill";+const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills` });+const sk = (name, extra) => ({ name, description: name + " skill", kind: "github", source: `https://github.com/${REPO}/tree/HEAD/skills/${name}`, agents: ["claude"], ...extra });+const mine = (name) => ({ name, description: name + " of mine", kind: "folder", source: `${HOME}/skills/${name}`, agents: ["claude"] });+const goneCheck = (name) => ({ name, status: "gone", error: `${REPO} has no ${name} any more: it was removed from there` });+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: [], foundSkills: [], newSkills: [],+ checkDue: false,+ skills: [+ ...(st.removed ? [] : [+ sk("taste", { edited: true, gone: "2026-10-22T21:00:00Z", check: goneCheck("taste") }),+ sk("brutal", { gone: "2026-10-22T21:00:00Z", check: goneCheck("brutal") }),+ ]),+ sk("minimal", { check: { name: "minimal", status: st.updated ? "current" : "update", commit: "c2", message: "minimal: spacing" } }),+ sk("soft", { check: { name: "soft", status: "current", commit: "c1" } }),+ ...(st.single ? [] : Array.from({ length: 4 }, (_, i) => mine("note-" + i))),+ ],+});++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();+ posts.push({ what, body: req.postDataJSON() });+ let result = { changed: ["claude"] };+ if (what === "update-some") {+ st.updated = true;+ result = { updated: ["minimal"], gone: ["brutal", "taste"], changed: [] };+ }+ if (what === "remove-gone") {+ st.removed = true;+ result = { removed: ["brutal", "taste"], changed: ["claude"] };+ }+ return route.fulfill({ json: { ...lib(st), result } });+ }+ 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 press = async (page, loc) => {+ await page.waitForFunction(() => !document.getAnimations().some((a) => a.playState === "running" && a.effect?.target?.closest?.("#modal")));+ const b = await loc.boundingBox();+ await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);+};++const scrolls = (page) => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => (e.id || e.className) + ":" + e.scrollTop).concat("doc:" + document.scrollingElement.scrollTop).join(" "));++const words = {+ en: { tag: "Removed upstream", tip: `${REPO} no longer has this skill: it was removed there. It stays here until you remove it.`, clean: "Clean up 2", updN: "Update 1",+ updated: "2 skills were removed from their sources: brutal, taste · 1 up to date", head: "Remove 2 skills removed upstream?", edited: "Changed here",+ cancel: "Cancel", go: "Remove 2", done: "2 skills removed" },+ zh: { tag: "上游已删除", tip: `${REPO} 里已经没有这个技能了:它在那里被删除了。在你移除之前,它会一直留在这里。`, clean: "清理 2 个", updN: "更新 1 个",+ updated: "2 个技能已从来源中删除:brutal, taste · 1 个已是最新", head: "移除 2 个上游已删除的技能?", edited: "本地已改动",+ cancel: "取消", go: "删除 2 个", done: "已删除 2 个技能" },+};++const shots = process.env.ARTIFACT_DIR;++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(engine + ": skills removed upstream are said apart and cleaned up at once, asked first", 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 [860, 400]) for (const lang of ["en", "zh"]) for (const single of [false, true]) {+ await t.test(`${lang} at ${width}px, ${single ? "one group" : "two groups"}`, async () => {+ const w = words[lang], posts = [], st = { single };+ const ctx = await browser.newContext({ viewport: { width, height: 1100 } });+ await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} });+ const page = await ctx.newPage();+ page.setDefaultTimeout(5000);+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", server(lang, posts, st));+ await page.goto("http://magpie.test/");+ await page.locator('button[data-view="library"]').click();+ const v = page.locator("#view-library");+ await v.locator(".lib-skill .lib-tag.lib-gone").first().waitFor();++ const row = (n) => v.locator(".lib-skill", { has: page.locator(".name", { hasText: new RegExp("^" + n) }) });+ for (const n of ["taste", "brutal"]) {+ const tag = row(n).locator(".lib-tag.lib-gone");+ assert.equal((await tag.textContent()).trim(), w.tag);+ assert.equal(await tag.getAttribute("title"), w.tip);+ assert.equal(await row(n).locator(".lib-tag.lib-new").count(), 0, n + " says Update available");+ assert.equal(await row(n).locator(".lib-rowacts button.lib-icon").count(), await row("soft").locator(".lib-rowacts button.lib-icon").count() - 1, n + " has an update icon");+ }+ assert.equal(await v.locator(".lib-skill .lib-tag.lib-gone").count(), 2);+ // Clean up: in the bar with one group, in the group's heading with more+ const clean = v.locator("button.lib-cleanup");+ assert.equal(await clean.count(), 1, "one Clean up");+ assert.equal((await clean.textContent()).trim(), w.clean);+ assert.equal(await v.locator(".row-head button.lib-cleanup").count(), single ? 1 : 0, "where Clean up is");+ // Update N leaves the gone ones out+ const updN = v.locator("button.lib-updall:not(.lib-cleanup)", { hasText: w.updN });+ assert(await updN.count() >= 1, "Update 1");+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll");+ if (shots) await page.screenshot({ path: path.join(shots, `skill-gone-${engine}-${lang}-${width}-${single ? 1 : 2}.png`) });++ // Update N says the gone ones apart from failures+ await press(page, updN.first());+ await page.waitForFunction((s) => document.querySelector("#status")?.textContent.trim() === s, w.updated).catch(() => {});+ assert.deepEqual(posts[0], { what: "update-some", body: { names: ["minimal"] } });+ assert.equal((await page.locator("#status").textContent()).trim(), w.updated);++ const before = await scrolls(page);+ await press(page, clean);+ const modal = page.locator(".lib-remove-gone");+ await modal.waitFor();+ assert.equal((await modal.locator(".ehead b").textContent()).trim(), w.head);+ const items = modal.locator("ul.lib-gonelist li");+ assert.equal(await items.count(), 2);+ const listed = await items.evaluateAll((ls) => ls.map((l) => [l.firstChild.textContent, l.querySelector(".lib-edited")?.textContent || ""]));+ assert.deepEqual(listed.sort(), [["brutal", ""], ["taste", w.edited]]);+ for (const b of await modal.locator(".bar button").all()) {+ const box = await b.boundingBox();+ assert(box && box.x >= 0 && box.x + box.width <= width, `a button out of view: ${JSON.stringify(box)}`);+ }+ await page.waitForTimeout(300);+ if (shots) await page.screenshot({ path: path.join(shots, `skill-gone-ask-${engine}-${lang}-${width}-${single ? 1 : 2}.png`) });+ assert.equal(posts.length, 1, "nothing sent before the answer");+ await press(page, modal.locator(".bar button", { hasText: w.cancel }));+ await modal.waitFor({ state: "detached" });+ assert.equal(posts.length, 1, "Cancel sends nothing");+ assert.equal(await scrolls(page), before, "asking moved the page");++ await press(page, clean);+ await modal.waitFor();+ await press(page, modal.locator(".bar button.primary", { hasText: w.go }));+ await modal.waitFor({ state: "detached" });+ assert.equal(posts[1].what, "remove-gone");+ assert.deepEqual([...posts[1].body.names].sort(), ["brutal", "taste"]);+ await v.locator(".lib-skill .lib-tag.lib-gone").first().waitFor({ state: "detached" });+ assert.equal(await v.locator("button.lib-cleanup").count(), 0, "Clean up after cleaning up");+ await ctx.close();+ });+ }+ assert.deepEqual(errors, []);+ });+}diff --git a/internal/library/skill_gone.go b/internal/library/skill_gone.gonew file mode 100644index 000000000..c256a5526--- /dev/null+++ b/internal/library/skill_gone.go@@ -0,0 +1,153 @@+package library++// A skill its source no longer has (スライム on Discord): the repository+// it came from was read, and its folder isn't there any more. An update+// then has nothing to fetch, which is no failure of the update: the skill+// is marked removed from its source (Skill.Gone), for the page to say so+// and offer to take out every such skill of a source at once. Nothing is+// taken out by itself, as the user may keep using it. Only a source read+// whole tells: a fetch that failed, or a skill left out of a fetch as too+// big, says nothing of whether it is still there.++import (+ "errors"+ "fmt"+ "io/fs"+ "os"+ "path/filepath"+ "slices"+ "syscall"+ "time"+)++// GoneError is a skill its source was read without: it was removed there.+type GoneError struct {+ Name string+ Source string // the repository+}++func (e *GoneError) Error() string {+ return fmt.Sprintf("%s has no %s any more: it was removed from there", e.Source, e.Name)+}++// goneFrom is whether a fetched source folder, tmp, lacks the skill at+// path: neither the folder nor its SKILL.md is there. A skill the fetch+// left out as too big is there, only not fetched; a folder that can't be+// read is unknown, not gone.+func goneFrom(tmp, path string) bool {+ if leftOutAt(tmp, path) {+ return false+ }+ dir := filepath.Join(tmp, filepath.FromSlash(path))+ fi, err := os.Stat(dir)+ if err != nil {+ return absent(err)+ }+ if !fi.IsDir() {+ return true // a file stands where the skill's folder was+ }+ _, err = os.Stat(filepath.Join(dir, "SKILL.md"))+ return err != nil && absent(err)+}++// absent is whether err says a path isn't there, rather than that it+// couldn't be read.+func absent(err error) bool {+ return errors.Is(err, fs.ErrNotExist) || errors.Is(err, syscall.ENOTDIR)+}++// leftOutAt is whether the fetch into dir left out the skill at path, or+// one inside it, as too big; unlike tookLeftOut it forgets nothing.+func leftOutAt(dir, path string) bool {+ leftOut.Lock()+ defer leftOut.Unlock()+ for _, l := range leftOut.m[dir] {+ if path == "" || l.Path == path || len(l.Path) > len(path) && l.Path[:len(path)+1] == path+"/" {+ return true+ }+ }+ return false+}++// markGone records which skills their sources were found without, and+// which were found there again.+func markGone(gone, there []string) {+ if len(gone) == 0 && len(there) == 0 {+ return+ }+ mu.Lock()+ defer mu.Unlock()+ l, err := load()+ if err != nil {+ return+ }+ if l.setGone(gone, there) {+ _ = l.save()+ }+}++// setGone is markGone on a library already loaded; it says whether+// anything changed.+func (l *Library) setGone(gone, there []string) bool {+ now := time.Now().UTC().Format(time.RFC3339)+ changed := false+ for _, s := range l.Skills {+ switch {+ case slices.Contains(gone, s.Name) && s.Gone == "":+ s.Gone, changed = now, true+ case slices.Contains(there, s.Name) && s.Gone != "":+ s.Gone, changed = "", true+ }+ }+ return changed+}++// goneCheck is the check a skill found removed from its source keeps+// till it is updated, installed again or removed.+func goneCheck(e *GoneError) SkillCheck {+ return SkillCheck{Name: e.Name, Status: "gone", Error: e.Error()}+}++// RemoveGoneSkills takes out of the library, as RemoveSkills does, the+// skills named that their sources no longer have; with none named, every+// such skill. One found in its source again since is left, and said in+// Unremoved.+func RemoveGoneSkills(names []string) (*Result, error) {+ mu.Lock()+ l, err := load()+ mu.Unlock()+ if err != nil {+ return nil, err+ }+ var take []string+ var left []Problem+ if names == nil {+ for _, s := range l.Skills {+ if s.Gone != "" {+ take = append(take, s.Name)+ }+ }+ } else {+ for _, name := range slices.Compact(slices.Sorted(slices.Values(names))) {+ switch s := l.skill(name); {+ case s == nil:+ left = append(left, Problem{What: "skill:" + name, Error: "no skill called " + name})+ case s.Gone == "":+ left = append(left, Problem{What: "skill:" + name, Error: name + " is in its source again; it's kept"})+ default:+ take = append(take, name)+ }+ }+ }+ if len(take) == 0 {+ if len(left) > 0 {+ return nil, errors.New(left[0].Error)+ }+ return nil, fmt.Errorf("no skill is removed from its source")+ }+ res, err := RemoveSkills(take)+ if res != nil {+ res.Unremoved = append(res.Unremoved, left...)+ }+ return res, err+}diff --git a/internal/library/skill_gone_test.go b/internal/library/skill_gone_test.gonew file mode 100644index 000000000..40d9be5aa--- /dev/null+++ b/internal/library/skill_gone_test.go@@ -0,0 +1,254 @@+package library++import (+ "errors"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "slices"+ "strings"+ "sync"+ "testing"+)++// スライム on Discord: a repository took some of its skills out, and+// Update all said each of them failed, with no way to take them all out+// but one by one. An update that reads the repository and finds a skill+// gone says so apart from failures, marks it, and every skill so marked+// goes at once, asked for. A repository that couldn't be fetched says+// nothing of whether its skills are gone.+func TestUpdateFindsSkillsRemovedUpstream(t *testing.T) {+ h := sandbox(t)+ removed, down := false, false+ var amu sync.Mutex+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ amu.Lock()+ defer amu.Unlock()+ if down && strings.Contains(r.URL.Path, "other") {+ http.NotFound(w, r)+ return+ }+ files := map[string]string{+ "skills/pdf/SKILL.md": "---\nname: pdf\ndescription: PDFs\n---\n",+ "skills/pdf/forms.md": "forms",+ "skills/docx/SKILL.md": "---\nname: docx\ndescription: Word\n---\n",+ "skills/slides/SKILL.md": "---\nname: slides\ndescription: Slides\n---\n",+ "x/SKILL.md": "---\nname: x\ndescription: X\n---\n",+ }+ if removed {+ delete(files, "skills/docx/SKILL.md")+ delete(files, "skills/slides/SKILL.md")+ files["skills/pdf/forms.md"] = "forms two"+ }+ w.Write(tarball(t, files))+ }))+ defer srv.Close()+ old := tarballURL+ tarballURL = func(repo, ref string) string { return srv.URL + "/" + repo + "/" + ref }+ defer func() { tarballURL = old }()++ // repositories no other test probes: a probe is kept for an install+ // from it, so another test's owner/repo would be installed from here+ ok(t)(InstallSkills("owner/taken", []string{"skills/pdf", "skills/docx", "skills/slides"}, []string{"claude"}))+ ok(t)(InstallSkills("owner/taken-other", []string{"x"}, []string{"claude"}))+ if v, _ := Read(nil); len(v.Skills) != 4 {+ t.Fatalf("installed %d skills, want 4", len(v.Skills))+ }+ // slides is changed here: it is still said to be gone, and the page+ // says it was changed+ write(t, filepath.Join(skillDir("slides"), "SKILL.md"), "---\nname: slides\ndescription: mine\n---\n")+ amu.Lock()+ removed, down = true, true+ amu.Unlock()++ res, err := UpdateSkills()+ if err != nil {+ t.Fatal(err)+ }+ if !slices.Equal(res.Updated, []string{"pdf"}) {+ t.Errorf("updated %v", res.Updated)+ }+ if !slices.Equal(res.Gone, []string{"docx", "slides"}) {+ t.Errorf("gone %v", res.Gone)+ }+ // x's repository couldn't be fetched: a failure, not gone+ if len(res.Unupdated) != 1 || res.Unupdated[0].What != "skill:x" {+ t.Errorf("unupdated %+v", res.Unupdated)+ }+ v, _ := Read(nil)+ for _, s := range v.Skills {+ gone := s.Name == "docx" || s.Name == "slides"+ if (s.Gone != "") != gone {+ t.Errorf("%s: gone %q", s.Name, s.Gone)+ }+ if gone && (s.Check == nil || s.Check.Status != "gone" || !strings.Contains(s.Check.Error, "owner/taken")) {+ t.Errorf("%s: check %+v", s.Name, s.Check)+ }+ if s.Name == "slides" && !s.Edited {+ t.Error("slides, changed here, isn't said to be")+ }+ }+ // nothing is taken out by itself+ for _, n := range []string{"docx", "slides"} {+ if _, err := os.Stat(filepath.Join(skillDir(n), "SKILL.md")); err != nil {+ t.Errorf("%s went by itself: %v", n, err)+ }+ }++ // one named that isn't gone is kept, and said+ if _, err := RemoveGoneSkills([]string{"pdf"}); err == nil || !strings.Contains(err.Error(), "in its source again") {+ t.Errorf("pdf, still in its source: %v", err)+ }+ r := ok(t)(RemoveGoneSkills(nil))+ if len(r.Unremoved) != 0 {+ t.Errorf("unremoved %+v", r.Unremoved)+ }+ v, _ = Read(nil)+ var left []string+ for _, s := range v.Skills {+ left = append(left, s.Name)+ }+ if !slices.Equal(left, []string{"pdf", "x"}) {+ t.Errorf("left %v", left)+ }+ for _, n := range []string{"docx", "slides"} {+ if _, err := os.Lstat(filepath.Join(h, ".claude/skills", n)); !os.IsNotExist(err) {+ t.Errorf("claude still has %s", n)+ }+ }+ // the changed one's folder is with the backups, as Remove keeps it+ kept, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "skills", "slides", "SKILL.md"))+ if len(kept) != 1 || !strings.Contains(read(t, kept[0]), "mine") {+ t.Errorf("slides in the backups: %v", kept)+ }+ if _, err := RemoveGoneSkills(nil); err == nil {+ t.Error("with nothing gone, nothing to say")+ }+}++// A skill marked gone that its repository has again is updated, and the+// mark goes.+func TestSkillBackUpstreamIsNotGone(t *testing.T) {+ sandbox(t)+ removed := false+ var amu sync.Mutex+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ amu.Lock()+ defer amu.Unlock()+ files := map[string]string{"skills/a/SKILL.md": "---\nname: a\ndescription: A\n---\n", "skills/b/SKILL.md": "---\nname: b\ndescription: B\n---\n"}+ if removed {+ delete(files, "skills/b/SKILL.md")+ }+ w.Write(tarball(t, files))+ }))+ defer srv.Close()+ old := tarballURL+ tarballURL = func(repo, ref string) string { return srv.URL + "/" + repo + "/" + ref }+ defer func() { tarballURL = old }()++ ok(t)(InstallSkills("owner/back", []string{"skills/a", "skills/b"}, nil))+ amu.Lock()+ removed = true+ amu.Unlock()+ _, err := UpdateSkill("b", false)+ var gone *GoneError+ if !errors.As(err, &gone) || gone.Name != "b" || gone.Source != "owner/back" {+ t.Fatalf("update of a skill removed there: %v", err)+ }+ if l, _ := load(); l.skill("b").Gone == "" {+ t.Fatal("not marked")+ }+ amu.Lock()+ removed = false+ amu.Unlock()+ ok(t)(UpdateSkill("b", false))+ if l, _ := load(); l.skill("b").Gone != "" {+ t.Error("still marked once its source has it again")+ }+ if c := lastCheck("b"); c != nil && c.Status == "gone" {+ t.Errorf("check %+v", c)+ }+ if _, err := RemoveGoneSkills([]string{"b"}); err == nil {+ t.Error("b, back in its source, was taken out")+ }+}++// A skill of another git repository, removed there: an update and a check+// both say so, and it goes at once when asked.+func TestGitSkillRemovedUpstream(t *testing.T) {+ sandbox(t)+ addr, commit := gitRepo(t, map[string]string{+ "skills/a/SKILL.md": "---\nname: a\ndescription: A\n---\nv1\n",+ "skills/b/SKILL.md": "---\nname: b\ndescription: B\n---\n",+ })+ ok(t)(InstallSkills(addr, []string{"skills/a", "skills/b"}, []string{"claude"}))+ commit(map[string]string{"skills/b": gitRemoved, "skills/a/SKILL.md": "---\nname: a\ndescription: A\n---\nv2\n"})++ checks, err := CheckSkills()+ if err != nil {+ t.Fatal(err)+ }+ for _, c := range checks {+ want := map[string]string{"a": "update", "b": "gone"}[c.Name]+ if c.Status != want {+ t.Errorf("check of %s: %+v, want %s", c.Name, c, want)+ }+ }+ if l, _ := load(); l.skill("b").Gone == "" {+ t.Error("the check didn't mark b")+ }+ res := ok(t)(UpdateSkills())+ if !slices.Equal(res.Updated, []string{"a"}) || !slices.Equal(res.Gone, []string{"b"}) || len(res.Unupdated) != 0 {+ t.Errorf("updated %v, gone %v, unupdated %+v", res.Updated, res.Gone, res.Unupdated)+ }+ ok(t)(RemoveGoneSkills([]string{"b"}))+ if l, _ := load(); l.skill("b") != nil || l.skill("a") == nil {+ t.Errorf("after removing: %+v", l.Skills)+ }+}++// Only a source read whole says a skill is gone: one left out of a fetch+// as too big is there, and a folder that can't be read is unknown.+func TestGoneFromNeedsTheSourceRead(t *testing.T) {+ tmp := t.TempDir()+ write(t, filepath.Join(tmp, "skills/here/SKILL.md"), "---\nname: here\n---\n")+ write(t, filepath.Join(tmp, "skills/file"), "not a folder")+ if err := os.MkdirAll(filepath.Join(tmp, "skills/empty"), 0o755); err != nil {+ t.Fatal(err)+ }+ for path, want := range map[string]bool{+ "skills/here": false,+ "skills/missing": true,+ "skills/file": true, // a file where the skill's folder was+ "skills/empty": true, // a folder that is no skill any more+ "nothing/at/all": true,+ } {+ if got := goneFrom(tmp, path); got != want {+ t.Errorf("%s: gone %v, want %v", path, got, want)+ }+ }+ leftOut.Lock()+ leftOut.m[tmp] = []LeftOut{{Path: "skills/big", Size: 300 << 20}}+ leftOut.Unlock()+ t.Cleanup(func() { leftOut.Lock(); delete(leftOut.m, tmp); leftOut.Unlock() })+ if goneFrom(tmp, "skills/big") {+ t.Error("a skill left out as too big was called gone")+ }+ if len(leftOut.m[tmp]) != 1 {+ t.Error("asking forgot what was left out")+ }+ if runtime.GOOS == "windows" || os.Getuid() == 0 {+ return+ }+ locked := filepath.Join(tmp, "skills/locked")+ write(t, filepath.Join(locked, "SKILL.md"), "x")+ if err := os.Chmod(locked, 0o000); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { os.Chmod(locked, 0o755) })+ if goneFrom(tmp, "skills/locked") {+ t.Error("a folder that couldn't be read was called gone")+ }+}diff --git a/internal/library/skillcheck.go b/internal/library/skillcheck.goindex d0e25d6b7..c905f17cb 100644--- a/internal/library/skillcheck.go+++ b/internal/library/skillcheck.go@@ -32,8 +32,9 @@ var githubAPI = "https://api.github.com"type SkillCheck struct {Name string `json:"name"`// Status is current when GitHub has the skill as the library does,- // update when it has changed it since, and unknown when it couldn't be- // told (Error says why)+ // update when it has changed it since, gone when it was read without+ // the skill (removed there, skill_gone.go), and unknown when it+ // couldn't be told (Error says why)Status string `json:"status"`Commit string `json:"commit,omitempty"` // the last commit to touch the skill's folderDate string `json:"date,omitempty"` // when it was made@@ -359,6 +360,16 @@ func CheckSkills() ([]SkillCheck, error) {}mu.Unlock()}+ var gone, there []string+ for _, c := range out {+ switch c.Status {+ case "gone":+ gone = append(gone, c.Name)+ case "current", "update":+ there = append(there, c.Name)+ }+ }+ markGone(gone, there)checks.Lock()for _, c := range out {checks.m[c.Name] = c@@ -411,6 +422,13 @@ func checkSkill(s *Skill, f *fetcher, asked map[string]*commit, limited *atomic.c.Status = "current"return c, "", ""}+ if s.Gone != "" {+ // the last commit to touch its folder may be the one that+ // removed it: it stays removed till an update finds it there+ g := goneCheck(&GoneError{Name: s.Name, Source: src.Repo})+ g.Commit, g.Date, g.Message = c.Commit, c.Date, c.Message+ return g, "", ""+ }c.Status, c.URL = "update", "https://github.com/"+src.Repo+"/compare/"+s.Commit+"..."+last.SHAreturn c, "", ""}@@ -422,6 +440,9 @@ func checkSkill(s *Skill, f *fetcher, asked map[string]*commit, limited *atomic.}from := filepath.Join(tmp, filepath.FromSlash(src.Path))if _, ok := readMeta(from); !ok {+ if goneFrom(tmp, src.Path) {+ return goneCheck(&GoneError{Name: s.Name, Source: src.Repo}), "", ""+ }c.Error = fmt.Sprintf("%s has no SKILL.md at %s any more", src.Repo, src.Path)return c, "", ""}diff --git a/internal/library/skillgit.go b/internal/library/skillgit.goindex 9175b6dca..3cfdc74c2 100644--- a/internal/library/skillgit.go+++ b/internal/library/skillgit.go@@ -435,6 +435,9 @@ func checkGitSkill(s *Skill, f *fetcher, asked map[string]string) (SkillCheck, s}from := filepath.Join(tmp, filepath.FromSlash(src.Path))if _, ok := readMeta(from); !ok {+ if goneFrom(tmp, src.Path) {+ return goneCheck(&GoneError{Name: s.Name, Source: src.Repo}), "", ""+ }c.Error = fmt.Sprintf("%s has no SKILL.md at %s any more", src.Repo, src.Path)return c, "", ""}diff --git a/internal/library/skills.go b/internal/library/skills.goindex 34afbda5c..e98b277d1 100644--- a/internal/library/skills.go+++ b/internal/library/skills.go@@ -41,6 +41,9 @@ type Skill struct {// From is the repository one not installed from GitHub was found to// come from (skill_from.go), only to group it with the rest of itFrom string `json:"from,omitempty"`+ // Gone is when an update or a check found its source without it: it+ // was removed there (skill_gone.go). Kept on this computer only.+ Gone string `json:"gone,omitempty"`}// Source is where a skill came from: a GitHub repository it can be updated@@ -1256,6 +1259,13 @@ func UpdateSkill(name string, replace bool) (*Result, error) {return nil, editedError(s)}up, err := f.prepare(s)+ var gone *GoneError+ if errors.As(err, &gone) {+ markGone([]string{name}, nil)+ checks.Lock()+ checks.m[name] = goneCheck(gone)+ checks.Unlock()+ }if err != nil {return nil, err}@@ -1298,6 +1308,7 @@ func updateSkills(names []string) (*Result, error) {var (ups []*skillUpdatefailed []Problem+ gone []*GoneErrorpmu sync.Mutexwg sync.WaitGroupsem = make(chan struct{}, 4)@@ -1314,6 +1325,11 @@ func updateSkills(names []string) (*Result, error) {up, err := f.prepare(s)pmu.Lock()defer pmu.Unlock()+ var g *GoneError+ if errors.As(err, &g) {+ gone = append(gone, g)+ return+ }if err != nil {failed = append(failed, Problem{What: "skill:" + s.Name, Error: err.Error()})return@@ -1324,6 +1340,14 @@ func updateSkills(names []string) (*Result, error) {wg.Wait()sort.Slice(failed, func(i, j int) bool { return failed[i].What < failed[j].What })res, err := change(func(l *Library) error {+ var names []string+ checks.Lock()+ for _, g := range gone {+ names = append(names, g.Name)+ checks.m[g.Name] = goneCheck(g)+ }+ checks.Unlock()+ l.setGone(names, nil)targets := Targets()for _, up := range ups {if s := l.skill(up.name); s != nil {@@ -1349,6 +1373,10 @@ func updateSkills(names []string) (*Result, error) {}sort.Strings(res.Updated)res.Unupdated = failed+ for _, g := range gone {+ res.Gone = append(res.Gone, g.Name)+ }+ sort.Strings(res.Gone)return res, nil}@@ -1446,6 +1474,10 @@ func (f *fetcher) prepare(s *Skill) (*skillUpdate, error) {}from := filepath.Join(tmp, filepath.FromSlash(src.Path))if _, ok := readMeta(from); !ok {+ if !adopt && goneFrom(tmp, src.Path) {+ // the repository was read, and the skill isn't in it+ return nil, &GoneError{Name: name, Source: src.Repo}+ }return nil, fmt.Errorf("%s has no SKILL.md at %s any more", src.Repo, src.Path)}up := &skillUpdate{name: name, src: src, adopt: adopt, from: from}@@ -1497,6 +1529,7 @@ func (up *skillUpdate) apply(l *Library, targets []*Target) error {// the commit it's at is known again once a check finds the files// GitHub has to be these; a git repository's is the one fetcheds.Hash, s.Commit = hash, up.commit+ s.Gone = "" // its source has it again}forgetCheck(name)if old == "" {diff --git a/internal/library/sync.go b/internal/library/sync.goindex 41fd4289c..9618c66ed 100644--- a/internal/library/sync.go+++ b/internal/library/sync.go@@ -21,6 +21,9 @@ type Result struct {// fetched again and the ones that couldn't be (What is skill:<name>)Updated []string `json:"updated,omitempty"`Unupdated []Problem `json:"unupdated,omitempty"`+ // Gone are, for an update of skills, the ones their sources no longer+ // have: removed there, not failed (skill_gone.go)+ Gone []string `json:"gone,omitempty"`// Unimported are, for skills brought in together, the ones that// couldn't be (What is skill:<name>)Unimported []Problem `json:"unimported,omitempty"`@@ -344,6 +347,9 @@ type SkillView struct {// in the library or in an agent's copy: an update replaces that, so// the page asks first (#1449)Edited bool `json:"edited,omitempty"`+ // Gone is when its source was found without it: removed there, the+ // page offers to take it out (skill_gone.go)+ Gone string `json:"gone,omitempty"`}// View is the Library page.@@ -513,6 +519,7 @@ func readView(problems []Problem, glance bool) (*View, error) {}sv.Check = lastCheck(s.Name)sv.Edited, _ = l.editState(s, targets)+ sv.Gone = s.Gonev.Skills = append(v.Skills, sv)}v.FoundServers = foundServersOf(l, targets)diff --git a/internal/tui/library.go b/internal/tui/library.goindex a6c52feed..bc2527e1b 100644--- a/internal/tui/library.go+++ b/internal/tui/library.go@@ -6,6 +6,7 @@ package tui// the terminal.import (+ "errors""fmt""os""path"@@ -69,6 +70,8 @@ func (m *model) reloadLibrary() {r := libRow{kind: "skill", name: s.Name, about: s.Description, on: s.Agents, bad: len(s.Problems)}if s.Missing {r.about, r.bad = "its folder is gone", r.bad+1+ } else if s.Gone != "" {+ r.about, r.bad = "removed from "+s.Source+" · d takes it out", r.bad+1}m.lib = append(m.lib, r)}@@ -159,7 +162,15 @@ func (m model) updateLibrary(msg tea.KeyMsg) (tea.Model, tea.Cmd) {return m, nil}m.flash, m.flashOK = "fetching "+r.name+" from GitHub again…", true- return m, libCmd(func() (*library.Result, error) { return library.UpdateSkill(r.name, false) }, "updated "+r.name)+ return m, libCmd(func() (*library.Result, error) {+ res, err := library.UpdateSkill(r.name, false)+ var gone *library.GoneError+ if errors.As(err, &gone) {+ // removed from its source: kept till the user takes it out+ err = fmt.Errorf("%w · d takes it out", err)+ }+ return res, err+ }, "updated "+r.name)case "i":if r.own {m.flash, m.flashOK = r.name+" is put there by the agent's app itself, each time it starts: it stays as it is", false