library: Claude Code plugins kept as one item, with a Claude plugins tab (FakeshadowzZ on X)

A Claude Code plugin (.claude-plugin/plugin.json, skills/, agents/,
hooks/hooks.json, .mcp.json) can be installed into the Library from a
folder, a git address or a marketplace.json, and is one row: turned on, off
or removed as a whole, and given to the agents picked with the chips every
tab has. Its skills, MCP servers, hooks and subagents are ordinary library
items tagged Bundle: <plugin>, so each agent gets them through the code of
its kind and the Skills, MCP servers, Hooks and Subagents tabs go on
working. Off clears every part's agents and keeps them for on; Remove
removes the parts. A part whose name the library has gets the plugin's name
as a prefix, never over the user's own. Claude hook events and matchers map
to the portable ones; others become claude:<Event>, for Claude Code only.
Slash commands, LSP servers and non-command hooks are listed as not
carried, not dropped. internal/library/plugin.go, POST /api/library/plugins/*,
the Claude plugins tab in plugins/library/client.js (en, zh, zh-TW, ja, de),
docs/subsystems/library.md.

Run (mote): go test -tags nogui ./internal/library ./internal/gui
./internal/backup ./internal/davsync ok; gofmt clean; go vet darwin, linux
(-tags nogui) and windows clean. GUI, chromium and webkit, en zh zh-TW ja de
at 420 and 1100: library-plugins (new), library-hooks, library-subagents,
i18n-keys, i18n-en-no-cjk, click-scroll all pass. Whole GUI suite started
and cut short at ~460 of its tests: failing only account-dragging and
accounts-sheet (routing, untouched by this), not compared on origin/main.
Broken by hand: dropping the Off handling in givePlugin and the hookTakes
filter each turned the new Go tests red.

Not tried: a real Claude Code plugin from a marketplace, a git source
(tests use folders), WSL, Windows. Not carried yet: commands/*.md, LSP
servers, a plugin's folder across computers (a backup carries the parts, not
the plugin record).
This commit is contained in:
yetone
2026-11-11 02:55:15 +08:00
parent 036b691542
commit 6af54dc9a9
16 changed files with 2013 additions and 12 deletions
+3 -2
View File
@@ -34,6 +34,7 @@ Pi's extensions and packages.
| 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. What installing a skill's dependencies or running it writes in its folder is no change (`fromInstall`: `node_modules`, `.venv`, `venv`, `__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache` folders, `*.pyc`/`*.pyo`, and `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock`, `bun.lockb`, `uv.lock` written again; ggbr on Discord): `Own` is the hash of the files as fetched leaving those aside (`ownHash`), and `onlyInstalled` compares the folder with it, or for a skill fetched before `Own` was kept with `Hash` (so a lock file the install wrote again still reads as changed until its next update). An update carries those entries over to the version fetched where it has none of its own (`carryInstalled`), so they aren't installed again. `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 are found from its fetch (`findNewGit`, above); 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. A session-start hook can be narrowed to some starts (#5604, NEKO-CwC: re-inject a file after compaction alone), one or more of `HookStarts` (startup, resume, clear, compact, fork, Claude Code's words) joined by `|`; `startMatcher` writes each agent's own matcher for them. Claude Code and Codex take the starts as written (Codex reads a `|` list as exact names). Gemini CLI has startup, resume and clear only and compares its matcher whole, so it takes one of them. Grok has `new` (startup and /clear) and `load` (resume), so it takes exactly one of those groups. Cursor's sessionStart takes no matcher. Starts an agent doesn't have are dropped, and one that has all that are left is given the hook whole. An agent that can't run it at exactly the starts picked is refused with why, as for any other per-agent limit: never widened to every start, which would run it at the starts the user narrowed away (a fork per subagent), nor written with a matcher it never matches. The written matcher is in `Applied.Hooks`, so an agent's own edit of the entry is still theirs. `HookAgentView.Starts` lists the matchers each agent takes, and the editor's At which starts app menu greys the chips of those that can't. A bundle carrying a narrowed hook to a magpie before this writes it whole. `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`, `model` when set, `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. A subagent's optional `Model` (a model or routing group of Codex's list, `subagentModels` in `/api/library`) is written only into Codex's role (luckymanjc on Discord): the role file is a config layer, and Codex lays its `model` over the one its lead names in spawn_agent (`apply_spawn_agent_role` after `apply_requested_spawn_agent_model_overrides` in codex-rs `core/src/agent/child_config.rs`), so the subagent's requests carry it and the gateway routes them as any other. Codex's subagent model on the Agents page (`CodexSubagentModel`), when set, still rewrites every subagent's request, and the editor says so. Without one, a Codex subagent runs on the model its lead names, else the lead's own. The page lists, per agent, whether it binds skills, servers and a model (`SubagentAgentView`), names the agents that run a subagent on their own pick, and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) |
| Claude plugins | A `Plugin` (FakeshadowzZ on X) is a Claude Code plugin kept as one item: `.claude-plugin/plugin.json`, `skills/<name>/SKILL.md`, `agents/*.md`, `hooks/hooks.json` and `.mcp.json`, from a folder, a git address or a marketplace.json (`ProbePlugins`, `InstallPlugins`; a marketplace entry with a relative path, or a github/url/git source, is fetched when installed). Its files are copied to `<library>/plugins/<name>`; `${CLAUDE_PLUGIN_ROOT}` is that folder and `${CLAUDE_PLUGIN_DATA}` is `<library>/plugin-data/<name>`, which an update keeps. Its parts are ordinary library skills, MCP servers, hooks and subagents, each tagged `Bundle: <plugin>`, so every agent gets them through the code of its kind and the old tabs go on working; the plugin holds the names, its agents and `Off`. `PluginAgents` sets every part's agents, `PluginOn` clears them (kept in `Agents` for turning it on again) or gives them back, `RemovePlugin` removes the parts, and `UpdatePlugin` reads the source again. A hook whose Claude event and matcher have a portable event becomes it (Stop turn-end, PostToolUse after-tool, PreToolUse before-tool, UserPromptSubmit prompt, SessionStart session-start; Bash is shell, Edit/Write/MultiEdit is edit); any other event is `claude:<Event>`, for Claude Code only. Subagents go to the agents in `SubagentAgents`. A part whose name the library has gets the prefix `<plugin>-`: the user's own item is never written over or removed. Slash commands, LSP servers and hooks that aren't a command are listed in `Left` and shown, not carried. A backup file carries the parts but not the plugin record or its folder, so on another computer they are ordinary items whose `${CLAUDE_PLUGIN_ROOT}` paths don't exist (`TestPluginImportCarryOnOffRemove`, `TestPluginNameClashKeepsTheUsersOwn`, `TestPluginMarketplaceAndUpdate`, `TestPluginRefusesWhatIsNone`, `library-plugins.test.cjs`). | [`plugin.go`](../../internal/library/plugin.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) |
| 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) |
| RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. Factory's Droid (lml0664 on Discord) gets rtk's own `rtk init -g --agent droid`, given Droid's folder as `FACTORY_HOME_OVERRIDE`; rtk puts its `Execute` group (`rtk hook droid`) in the root `hooks.json`, or in `settings.json`'s `hooks.PreToolUse` where Droid's hooks already are, so `droidHookFiles` reads and switches off all three places rtk 1.1.0 may use (`hooks.json`, `hooks/hooks.json`, `settings.json`), leaving the user's own hooks. rtk before 0.44 has no Droid agent, so it is `blocked` (`droidBlocked`). A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off; Qoder and Qoder CN: rtk 1.1.0 has no Qoder agent; Cline and Kimi Code: `rtk init --agent cline|kimi` writes only one project's `.clinerules` or `AGENTS.md`, instructions with no hook, and Kimi's refuses `-g`). RTK 1.1.0's Trae, Windsurf, Kilo Code and Mistral Vibe have no magpie agent. The page's No RTK hook tag gives each agent's own reason and rtk-ai/rtk issue (`rtkNoHookWhy` in plugins/library/client.js: dsh #3847, Grok Build and Grok App #2136, Qoder and Qoder CN #1327, Cline #3841), and an agent with no entry gets no link; `TestRTKNoHookIssuesAreEachAgents` fails when the page and `rtkNoHook` cite different issues, or two agents cite the same ones without a reason in `sharedRTKIssues`. | [`rtk.go`](../../internal/library/rtk.go) |
| RTK in WSL | An agent in a WSL distro (`claude@wsl:Ubuntu`) is listed by its kind (`rtkKind`), and its hook runs in the distro, where Windows' rtk.exe is no command, so it gets the distro's own rtk (lex on Discord). `rtkDistroOf` asks the distro with `wsl.exe -d <distro> -e sh -lc` where rtk is (a login or interactive shell's PATH; else `~/.local/bin` or `~/.cargo/bin`, `offPath`), kept 15s; `ReadRTK` lists one `RTKDistro` for each distro its agents are in. Install RTK in WSL `<distro>` (`InstallRTKIn`, `POST /api/library/rtk/install` with `distro`, `magpie library rtk install <distro>`) runs RTK's own Linux installer in the distro (`curl -fsSL …/install.sh \| sh`, wget where there's no curl). Switching an agent on runs the distro's rtk there (`rtkInstallWSL`: `rtk init -g …` with its folder on PATH, Claude Code pointed at a folder of its own for the OpenCode and Cursor installers), and reads and edits its files under the distro's home as magpie opens it (`rtkClaudeDir`, `rtkCodexDir`, `rtkHome`). A distro that isn't running is never started (#3896): `rtkWSLLive` and `rtkDistroOf` check `agent.WSLRunning` first, its agents are listed `asleep` with the switch off, and switching or installing says to start it (`TestRTKWSLAsleep`). The page gives each distro a card (`rtkDistroCard` in plugins/library/client.js; library-rtk-wsl.test.cjs). | [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) |
@@ -105,7 +106,7 @@ Pi's extensions and packages.
## Verification
```sh
go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestWSLPiMCP|TestWSLMCPSiblings|TestServer|TestHub|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|TestCheckNamesAgentsSignedInThemselves|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut|TestUpdateFindsSkillsRemovedUpstream|TestGoneFromNeedsTheSourceRead'
go test -tags nogui ./internal/library -run 'TestPlugin|TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestWSLPiMCP|TestWSLMCPSiblings|TestServer|TestHub|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|TestCheckNamesAgentsSignedInThemselves|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut|TestUpdateFindsSkillsRemovedUpstream|TestGoneFromNeedsTheSourceRead'
go test -tags nogui ./internal/library -run 'TestSkillOffHere|TestLocalServerNotCarried|TestPutKeepsLocalServer|TestPutSameNameAsLocal'
go test -tags nogui ./internal/backup -run 'TestRestoreKeepsLocalServer|TestBackupFileCarriesSubagents|TestBackupFileCarriesHooks'
go test -tags nogui ./internal/library -run 'TestHandOver|TestSharedUnderAnotherName|TestSharedAgentsSkills'
@@ -121,7 +122,7 @@ node --test internal/gui/tests/library-pi-extensions.test.cjs internal/gui/tests
node --test internal/gui/tests/library-rtk-wsl.test.cjs
node --test internal/gui/tests/library-wsl-asleep.test.cjs
node --test internal/gui/tests/skill-off-here.test.cjs internal/gui/tests/mcp-local-server.test.cjs internal/gui/tests/skill-handover.test.cjs
node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-mcp-hub.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/library-mcp-health-wsl.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-mcp-hub.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-plugins.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/library-mcp-health-wsl.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 the
+159 -3
View File
@@ -702,7 +702,7 @@ magpie.plugin("library", (ctx) => {
ul.append(li);
}
if (ul.childElementCount) card.append(ul);
const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), subagents: t("Subagents") };
const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), subagents: t("Subagents"), plugins: t("Claude plugins") };
const others = Object.keys(away).filter((k) => k in tabNames);
if (others.length) {
const more = el("div", "lib-problems-away");
@@ -738,7 +738,7 @@ magpie.plugin("library", (ctx) => {
}
// the tab a problem is about; "" is one shown on every tab
function problemTab(what) {
return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", subagent: "subagents" }[what.split(":")[0]] || "";
return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", subagent: "subagents", plugin: "plugins" }[what.split(":")[0]] || "";
}
function problemWhat(what) {
const [kind, ...rest] = what.split(":");
@@ -851,6 +851,7 @@ magpie.plugin("library", (ctx) => {
["skills", t("Skills") + n("skills")],
["hooks", t("Hooks") + n("hooks")],
["subagents", t("Subagents") + n("subagents")],
["plugins", t("Claude plugins") + n("plugins")],
["rtk", "RTK"],
["bili", "billion-context"],
...(hasPi() ? [["pi", t("Pi packages")]] : []),
@@ -909,7 +910,7 @@ magpie.plugin("library", (ctx) => {
if (agentless()) tab = "mcp";
// Pi's tab only while a Pi is here; the pick is kept for when one is
else if (tab === "pi" && !hasPi()) tab = "instructions";
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, subagents: (lib.subagents || []).length });
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, subagents: (lib.subagents || []).length, plugins: (lib.plugins || []).length });
page.append(head);
head.classList.toggle("stuck", top > 0);
// what changed in a tab is drawn in place: only another tab (or the
@@ -926,6 +927,7 @@ magpie.plugin("library", (ctx) => {
else if (tab === "pi") renderPi(body);
else if (tab === "hooks") renderHooks(body);
else if (tab === "subagents") renderSubagents(body);
else if (tab === "plugins") renderPlugins(body);
else renderSkills(body);
page.append(body);
for (const n of body.querySelectorAll(".row-head .note")) n.title = n.textContent;
@@ -4382,6 +4384,160 @@ magpie.plugin("library", (ctx) => {
if (!s) requestAnimationFrame(() => name.focus());
}
// ---------- Claude plugins ----------
// A Claude Code plugin kept as one item (FakeshadowzZ on X): its skills,
// MCP servers, hooks and subagents are ordinary library items marked with
// the plugin, so each agent gets them through the code that writes that
// kind, and the other tabs go on listing them. The plugin's switch, its
// agents and Remove act on every part at once (library/plugin.go).
let plProbe = null; // plugins found at an address: { source, found, pick:Set, agents }
let plProbing = false;
const pluginParts = (p) => [
p.skills?.length ? t("Skills: {names}", { names: p.skills.join(", ") }) : "",
p.mcp?.length ? t("MCP servers: {names}", { names: p.mcp.join(", ") }) : "",
p.hooks?.length ? t("Hooks: {names}", { names: p.hooks.join(", ") }) : "",
p.subagents?.length ? t("Subagents: {names}", { names: p.subagents.join(", ") }) : "",
].filter(Boolean).join(" · ");
function renderPlugins(body) {
body.append(intro(t("A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.")));
body.append(pluginFind());
const all = shownAgents();
const plugins = lib.plugins || [];
if (!plugins.length) {
body.append(empty(t("No Claude plugins in the library yet"), t("Install one from a folder, a git address or a marketplace.json.")));
return;
}
const list = el("div", "list lib-list");
list.append(...[...plugins].sort((a, b) => a.name.localeCompare(b.name)).map((p) => pluginRow(p, all)));
body.append(list);
}
function pluginFind() {
const card = el("div", "list lib-card lib-install lib-plfind");
const line = el("div", "lib-find");
const inp = el("input");
inp.type = "text";
inp.dataset.lib = "plsource";
inp.placeholder = t("owner/repo, a git address, or a folder with a plugin or a marketplace.json");
inp.spellcheck = false;
inp.autocomplete = "off";
inp.value = plProbe?.source || "";
const go = button(plProbing ? t("Looking…") : t("Find plugins"), "action", () => find());
go.disabled = plProbing;
if (plProbing) go.classList.add("busy");
inp.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") find(); else if (e.key === "Escape" && plProbe) { plProbe = null; render(); } };
line.append(glyph(GLYPH.search, "lib-mini"), inp, go);
card.append(line);
async function find() {
const src = inp.value.trim();
if (!src || plProbing) return;
plProbing = true;
plProbe = { source: src };
render();
try {
const f = await api("library/plugins/probe", { source: src });
const fresh = f.candidates.filter((c) => !c.have);
plProbe = { source: src, found: f, pick: new Set((fresh.length === 1 ? fresh : []).map((c) => c.name)), agents: shownAgents().map((a) => a.id) };
if (!f.candidates.length) status(t("No Claude plugin found there"), "warn");
} catch (e) {
plProbe = { source: src, error: e.message };
}
plProbing = false;
render();
}
if (plProbe?.error) card.append(el("div", "lib-err", plProbe.error));
if (plProbe?.found?.candidates.length) card.append(pluginPicks(plProbe));
return card;
}
function pluginPicks(p) {
const box = el("div", "lib-probe");
const list = el("div", "lib-picks");
for (const x of p.found.candidates) {
const r = el("label", "lib-pick lib-plpick" + (x.have ? " dim" : ""));
const cb = el("input");
cb.type = "checkbox";
cb.checked = p.pick.has(x.name);
cb.onchange = () => { if (cb.checked) p.pick.add(x.name); else p.pick.delete(x.name); syncGo(); };
const w = el("span", "who");
w.append(el("span", "name", x.name), el("span", "sub", x.description || ""));
const count = (n) => (n ? [String(n)] : []);
const parts = x.remote ? t("Fetched from its own repository when installed")
: pluginParts({ skills: count(x.skills), mcp: count(x.mcp), hooks: count(x.hooks), subagents: count(x.subagents) });
if (parts) w.append(el("span", "sub lib-plparts", parts));
r.append(cb, w);
if (x.have) r.append(tag(t("in the library"), ""));
list.append(r);
}
box.append(list);
const foot = el("div", "lib-probefoot");
const agentsBox = el("div");
const drawAgents = () => agentsBox.replaceChildren(agentChips(shownAgents(), p.agents, (n) => { p.agents = n; drawAgents(); }, { names: false, all: true }));
drawAgents();
foot.append(el("span", "note", t("for")), agentsBox, el("span", "grow"));
foot.append(button(t("Cancel"), "", () => { plProbe = null; render(); }));
const go = button("", "primary", async () => {
go.disabled = true;
go.textContent = t("Installing…");
const n = p.pick.size;
if (await change("plugins/install", { source: p.source, names: [...p.pick], agents: p.agents }, n === 1 ? t("1 plugin installed") : t("{n} plugins installed", { n }))) { plProbe = null; render(); }
else { go.disabled = false; syncGo(); }
});
const syncGo = () => { const n = p.pick.size; go.textContent = n === 1 ? t("Install 1 plugin") : t("Install {n} plugins", { n }); go.disabled = !n; };
syncGo();
foot.append(go);
box.append(foot);
return box;
}
function pluginRow(p, all) {
const row = el("div", "row lib-row click lib-plugin" + (p.off ? " off" : ""));
const who = el("div", "who");
who.append(el("div", "name mono", p.name + (p.version ? " " + p.version : "")));
if (p.description) who.append(el("div", "lib-subagentdesc", p.description));
const line = pluginParts(p);
if (line) who.append(el("div", "sub lib-plparts", line));
row.append(glyph(GLYPH.folder), who,
agentChips(all, p.agents, chipsChange("plugins/agents", p.name, "plugins", (x) => pluginRow(x, all)), { all: true }),
toggle(!p.off, t("Turn {name} on or off", { name: p.name }), (v) => change("plugins/on", { name: p.name, on: v },
v ? t("{name} is on again", { name: p.name }) : t("{name} is off for every agent", { name: p.name }))));
row.onclick = () => pluginDetail(p);
row.title = t("Open the plugin {name}", { name: p.name });
return row;
}
function pluginDetail(p) {
const ed = el("div", "editor lib-editor lib-pldetail");
const head = el("div", "ehead");
head.append(glyph(GLYPH.folder), el("b", "", p.name));
ed.append(head);
if (p.description) ed.append(el("p", "lib-subagentdesc", p.description));
const rows = [[t("Skills"), p.skills], [t("MCP servers"), p.mcp], [t("Hooks"), p.hooks], [t("Subagents"), p.subagents]].filter(([, v]) => v?.length);
for (const [label, names] of rows) ed.append(...field(label, el("div", "mono lib-plnames", names.join(", "))));
if (p.missing?.length) ed.append(el("div", "hint lib-plmissing", t("Taken out by hand: {names}", { names: p.missing.join(", ") })));
if (p.left?.length) {
const left = el("div", "lib-plleft");
for (const x of p.left) left.append(el("div", "hint", x.what + " — " + x.why));
ed.append(...field(t("Not carried"), left));
}
if (p.source) ed.append(el("div", "hint lib-plsource mono", p.source + (p.pick ? " · " + p.pick : "")));
const bar = el("div", "bar");
bar.append(button(t("Remove from the library"), "danger", async () => {
if (!await confirmRemoval(p.name, "It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.")) return;
if (await change("plugins/remove", { name: p.name }, t("{name} is out of the library and the agents it was given to", { name: p.name }))) closeLibModal(true);
}));
bar.append(el("span", "grow"));
if (p.source) bar.append(button(t("Update"), "", async () => {
if (await change("plugins/update", { name: p.name }, t("{name} read again from its source", { name: p.name }))) closeLibModal(true);
}));
bar.append(button(t("Cancel"), "", closeLibModal));
ed.append(bar);
modal = { dirty: () => false };
openLib(ed);
}
// ---------- skills ----------
function renderSkills(body) {
@@ -937,6 +937,25 @@ magpie.strings({
"Nothing folded yet over {requests}: billion-context folds a session once it nears the model's window.": "已经过 {requests},还没有折叠:会话接近模型窗口时 billion-context 才会折叠。",
"billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "这是 billion-context 自己的统计,已扣除折叠后的重建和摘要的开销(扣除前 {gross}):包括这台电脑上它运行过的所有会话,不分 Agent。",
"As of {time}: billion-context isn't running now.": "截至 {time}:billion-context 现在没有运行。",
"Claude plugins": "Claude 插件",
"A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Claude Code 插件把技能、MCP 服务器、hooks 和子代理装成一个包。装一次,magpie 就把每一部分交给你选的智能体;插件可以整体开启、关闭或移除。它的各部分也会出现在各自的标签页里。",
"No Claude plugins in the library yet": "资源库里还没有 Claude 插件",
"Install one from a folder, a git address or a marketplace.json.": "从文件夹、git 地址或 marketplace.json 安装。",
"owner/repo, a git address, or a folder with a plugin or a marketplace.json": "owner/repo、git 地址,或含插件或 marketplace.json 的文件夹",
"Find plugins": "查找插件",
"No Claude plugin found there": "那里没有找到 Claude 插件",
"Fetched from its own repository when installed": "安装时从它自己的仓库获取",
"1 plugin installed": "已安装 1 个插件",
"{n} plugins installed": "已安装 {n} 个插件",
"Install 1 plugin": "安装 1 个插件",
"Install {n} plugins": "安装 {n} 个插件",
"Hooks: {names}": "Hooks:{names}",
"Subagents: {names}": "子代理:{names}",
"Taken out by hand: {names}": "已手动取出:{names}",
"Not carried": "未带上的部分",
"It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "它会连同技能、MCP 服务器、hooks 和子代理一起从资源库移除,也会从它们所在的智能体中取出。",
"Open the plugin {name}": "打开插件 {name}",
"{name} read again from its source": "已重新从来源读取 {name}",
},
"zh-TW": {
"Stop picking memories": "不再選擇記憶",
@@ -1874,6 +1893,25 @@ magpie.strings({
"Nothing folded yet over {requests}: billion-context folds a session once it nears the model's window.": "已經過 {requests},還沒有摺疊:工作階段接近模型視窗時 billion-context 才會摺疊。",
"billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "這是 billion-context 自己的統計,已扣除摺疊後的重建和摘要的開銷(扣除前 {gross}):包括這台電腦上它執行過的所有工作階段,不分 Agent。",
"As of {time}: billion-context isn't running now.": "截至 {time}:billion-context 現在沒有執行。",
"Claude plugins": "Claude 外掛",
"A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Claude Code 外掛把技能、MCP 伺服器、hooks 和子代理裝成一個包。裝一次,magpie 就把每一部分交給你選的代理;外掛可以整體開啟、關閉或移除。它的各部分也會出現在各自的分頁裡。",
"No Claude plugins in the library yet": "資源庫裡還沒有 Claude 外掛",
"Install one from a folder, a git address or a marketplace.json.": "從資料夾、git 位址或 marketplace.json 安裝。",
"owner/repo, a git address, or a folder with a plugin or a marketplace.json": "owner/repo、git 位址,或含外掛或 marketplace.json 的資料夾",
"Find plugins": "查詢外掛",
"No Claude plugin found there": "那裡沒有找到 Claude 外掛",
"Fetched from its own repository when installed": "安裝時從它自己的儲存庫取得",
"1 plugin installed": "已安裝 1 個外掛",
"{n} plugins installed": "已安裝 {n} 個外掛",
"Install 1 plugin": "安裝 1 個外掛",
"Install {n} plugins": "安裝 {n} 個外掛",
"Hooks: {names}": "Hooks:{names}",
"Subagents: {names}": "子代理:{names}",
"Taken out by hand: {names}": "已手動取出:{names}",
"Not carried": "未帶上的部分",
"It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "它會連同技能、MCP 伺服器、hooks 和子代理一起從資源庫移除,也會從它們所在的代理中取出。",
"Open the plugin {name}": "開啟外掛 {name}",
"{name} read again from its source": "已重新從來源讀取 {name}",
},
ja: {
"Stop picking memories": "メモリの選択を終える",
@@ -2811,6 +2849,25 @@ magpie.strings({
"Nothing folded yet over {requests}: billion-context folds a session once it nears the model's window.": "{requests}を処理しましたが、まだ折りたたんでいません。billion-context はセッションがモデルのウィンドウに近づくと折りたたみます。",
"billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "billion-context 自身の集計で、折りたたみ後の再構築と要約のコストを差し引いた値です(差し引く前は {gross})。このコンピューターで動いたすべてのセッションが対象で、エージェントは問いません。",
"As of {time}: billion-context isn't running now.": "{time} 時点:billion-context は現在動いていません。",
"Claude plugins": "Claude プラグイン",
"A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Claude Code プラグインは、スキル、MCP サーバー、フック、サブエージェントを 1 つにまとめたパッケージです。一度インストールすると、magpie が選んだエージェントに各パーツを渡し、プラグイン全体をオン、オフ、削除できます。各パーツはそれぞれのタブにも表示されます。",
"No Claude plugins in the library yet": "ライブラリにはまだ Claude プラグインがありません",
"Install one from a folder, a git address or a marketplace.json.": "フォルダ、git アドレス、marketplace.json からインストールします。",
"owner/repo, a git address, or a folder with a plugin or a marketplace.json": "owner/repo、git アドレス、またはプラグインか marketplace.json があるフォルダ",
"Find plugins": "プラグインを探す",
"No Claude plugin found there": "そこに Claude プラグインは見つかりませんでした",
"Fetched from its own repository when installed": "インストール時に専用リポジトリから取得します",
"1 plugin installed": "プラグインを 1 件インストールしました",
"{n} plugins installed": "プラグインを {n} 件インストールしました",
"Install 1 plugin": "プラグインを 1 件インストール",
"Install {n} plugins": "プラグインを {n} 件インストール",
"Hooks: {names}": "フック: {names}",
"Subagents: {names}": "サブエージェント: {names}",
"Taken out by hand: {names}": "手動で外したもの: {names}",
"Not carried": "引き継がれない部分",
"It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "スキル、MCP サーバー、フック、サブエージェントごとライブラリから削除され、渡されていたエージェントからも外されます。",
"Open the plugin {name}": "プラグイン {name} を開く",
"{name} read again from its source": "{name} をソースから読み直しました",
},
de: {
"Stop picking memories": "Keine Erinnerungen mehr auswählen",
@@ -3748,5 +3805,24 @@ magpie.strings({
"Nothing folded yet over {requests}: billion-context folds a session once it nears the model's window.": "Noch nichts gefaltet nach {requests}: billion-context faltet eine Sitzung, wenn sie sich dem Fenster des Modells nähert.",
"billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "Die eigene Zählung von billion-context, abzüglich der Neuaufbauten nach einer Faltung und der Kosten der Zusammenfassungen ({gross} davor): jede Sitzung, in der es auf diesem Computer lief, von jedem Agenten.",
"As of {time}: billion-context isn't running now.": "Stand {time}: billion-context läuft gerade nicht.",
"Claude plugins": "Claude-Plugins",
"A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Ein Claude-Code-Plugin bündelt Skills, MCP-Server, Hooks und Subagenten in einem Paket. Einmal installieren: magpie gibt jeden Teil den gewählten Agenten, und das Plugin lässt sich als Ganzes ein-, ausschalten oder entfernen. Die Teile erscheinen auch in ihren eigenen Tabs.",
"No Claude plugins in the library yet": "Noch keine Claude-Plugins in der Bibliothek",
"Install one from a folder, a git address or a marketplace.json.": "Aus einem Ordner, einer Git-Adresse oder einer marketplace.json installieren.",
"owner/repo, a git address, or a folder with a plugin or a marketplace.json": "owner/repo, eine Git-Adresse oder ein Ordner mit einem Plugin oder einer marketplace.json",
"Find plugins": "Plugins suchen",
"No Claude plugin found there": "Dort wurde kein Claude-Plugin gefunden",
"Fetched from its own repository when installed": "Wird bei der Installation aus dem eigenen Repository geladen",
"1 plugin installed": "1 Plugin installiert",
"{n} plugins installed": "{n} Plugins installiert",
"Install 1 plugin": "1 Plugin installieren",
"Install {n} plugins": "{n} Plugins installieren",
"Hooks: {names}": "Hooks: {names}",
"Subagents: {names}": "Subagenten: {names}",
"Taken out by hand: {names}": "Von Hand entfernt: {names}",
"Not carried": "Nicht übernommen",
"It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "Es wird samt Skills, MCP-Servern, Hooks und Subagenten aus der Bibliothek und aus den Agenten entfernt, denen sie gegeben wurden.",
"Open the plugin {name}": "Plugin {name} öffnen",
"{name} read again from its source": "{name} wurde erneut aus der Quelle gelesen",
},
});
@@ -789,6 +789,10 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col
.lib-subagent > .who { flex-basis: 240px; }
.lib-subagent .lib-subagentdesc { font-size: 12px; line-height: 1.45; color: var(--fg); white-space: normal; overflow-wrap: anywhere; margin-top: 1px; }
.lib-subagent .lib-subagentuses { white-space: normal; overflow-wrap: anywhere; }
.lib-plugin > .who { flex-basis: 240px; }
.lib-plugin.off .name, .lib-plugin.off .lib-subagentdesc { opacity: .55; }
.lib-plugin .lib-plparts, .lib-plpick .lib-plparts { white-space: normal; overflow-wrap: anywhere; }
.lib-pldetail .lib-plnames, .lib-pldetail .lib-plsource { white-space: normal; overflow-wrap: anywhere; }
.lib-subagentedit .lib-menu { max-width: 100%; height: 28px; color: var(--fg); }
.lib-subagentedit .lib-menu > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.lib-subagentedit .lib-subagentdescin, .lib-subagentedit .lib-subagentprompt { width: 100%; box-sizing: border-box; resize: none; font: inherit; font-size: 12.5px; line-height: 1.45; }
+25
View File
@@ -248,6 +248,21 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
}
writeJSON(rw, p)
})
// the Claude Code plugins at an address: a folder, a repository, a
// marketplace.json (plugin.go); nothing is written
mux.HandleFunc("POST /api/library/plugins/probe", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Source string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
p, err := library.ProbePlugins(in.Source)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, p)
})
// which skills GitHub has changed: the page as it is, each skill from
// there carrying what the check found of it
mux.HandleFunc("POST /api/library/skills/check", func(rw http.ResponseWriter, r *http.Request) {
@@ -681,6 +696,16 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
res, err = library.RemoveHooks([]string{in.Name})
case "hooks/remove-all":
res, err = library.RemoveHooks(in.Names)
case "plugins/install":
res, err = library.InstallPlugins(in.Source, in.Names, in.Agents)
case "plugins/agents":
res, err = library.PluginAgents(in.Name, in.Agents)
case "plugins/on":
res, err = library.PluginOn(in.Name, in.On)
case "plugins/update":
res, err = library.UpdatePlugin(in.Name)
case "plugins/remove":
res, err = library.RemovePlugin(in.Name)
case "subagents/save":
res, err = library.SaveSubagent(in.Old, in.Subagent)
case "subagents/agents":
+1 -1
View File
@@ -152,7 +152,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the tab, with its count, between Skills and Subagents
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
assert.deepEqual(tabs.slice(3, 7), [w("Skills"), w("Hooks") + " · 2", w("Subagents"), "RTK"]);
assert.deepEqual(tabs.slice(3, 8), [w("Skills"), w("Hooks") + " · 2", w("Subagents"), w("Claude plugins"), "RTK"]);
// each hook says when it runs, in words, and what it runs
assert.equal((await row("fmt").locator(".lib-hookev").textContent()).trim(), w("After a tool runs") + " · " + w("File edits"));
assert.equal((await row("bark").locator(".lib-hookev").textContent()).trim(), w("When a turn ends"));
+210
View File
@@ -0,0 +1,210 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// FakeshadowzZ on X: the Library's Claude plugins tab. A Claude Code plugin
// is one row: its parts (skills, MCP servers, hooks, subagents), the agents
// it is given to, a switch that turns it on or off as a whole, and a dialog
// with what it holds, what magpie doesn't carry, Update and Remove (which
// asks first). Find plugins posts plugins/probe and lists what it found
// with an Install that posts plugins/install; a chip posts plugins/agents,
// the switch plugins/on. No native <select>; nothing wider than the window
// at 420 and 1100 in en, zh, zh-TW, ja and de. No backend: the API is faked.
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/chuan";
const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more });
const WSL = "claude@wsl:Ubuntu";
const SUB_AGENTS = [
{ id: "claude", dir: `${HOME}/.claude/agents`, skills: true, mcp: true },
{ id: "codex", dir: `${HOME}/.codex/agents`, model: true },
{ id: "cursor", dir: `${HOME}/.cursor/agents` },
{ id: "droid", dir: `${HOME}/.factory/droids`, mcp: true },
{ id: "opencode", dir: `${HOME}/.config/opencode/agents` },
{ id: WSL, wsl: true, no: "magpie gives no subagents to an agent in WSL yet" },
];
const MODELS = [{ id: "openai/gpt-6-sol", name: "GPT-6 Sol", note: "OpenAI" }, { id: "group/review", name: "review", group: true }];
const LONG = "Reviews code a change touched and reports only real bugs: logic errors, edge cases, races and leaks, never style, and never refactors that have nothing to do with the change.";
const PLUGIN = { name: "code-kit", version: "1.2.0", description: LONG, agents: ["claude", "codex"], skills: ["code-kit-tdd"], mcp: ["code-kit-docs"], hooks: ["code-kit-lint"], subagents: ["code-kit-reviewer"], left: [{ what: "commands/ship.md", why: "slash commands aren't carried" }], source: "/Users/chuan/code-kit", installed: "2026-11-11" };
const FOUND = { source: "/Users/chuan/market", candidates: [{ name: "fresh-kit", description: "A new one", skills: 2, mcp: 1, hooks: 0, subagents: 1 }, { name: "code-kit", description: "Have it", skills: 1, mcp: 0, hooks: 0, subagents: 0, have: true }] };
const lib = (plugins) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [agent("claude", "Claude Code"), agent("codex", "Codex")],
instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [], problems: [],
hooks: [], hookAgents: [], subagents: [], subagentAgents: [], plugins,
});
let I18N;
// the words the page says in lang; a string missing from a language fails
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, state, 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(state.plugins));
if (url.pathname.startsWith("/api/library/") && req.method() === "POST" && !url.pathname.endsWith("/reveal")) {
const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", "");
posts.push({ what, body });
if (what === "plugins/probe") return json(FOUND);
if (what === "plugins/agents") state.plugins = state.plugins.map((x) => (x.name === body.name ? { ...x, agents: body.agents } : x));
if (what === "plugins/on") state.plugins = state.plugins.map((x) => (x.name === body.name ? { ...x, off: !body.on } : x));
if (what === "plugins/remove") state.plugins = state.plugins.filter((x) => x.name !== body.name);
if (what === "plugins/install") state.plugins = [...state.plugins, { name: body.names[0], agents: body.agents, skills: ["x"] }];
return json({ ...lib(state.plugins), 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: "" }); }
};
}
// a click where the button is, as the reader's, and what was clicked stays
// where it was on the screen while the click redraws around it
const press = async (page, loc) => {
await page.waitForFunction(() => !document.querySelector("#view-library").getAnimations({ subtree: true }).some((a) => a.effect?.getComputedTiming().endTime !== Infinity));
const b = await loc.boundingBox();
const sel = String(loc);
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
await page.waitForTimeout(250);
if (!(await loc.count())) return;
const a = await loc.boundingBox();
if (a && a.width) assert(Math.abs(a.y - b.y) <= 1, `${sel} moved on the screen from ${Math.round(b.y)} to ${Math.round(a.y)}`);
};
const settled = (page) => page.waitForFunction(() => !document.querySelector("#modal").getAnimations({ subtree: true }).length);
// nothing wider than the window: the page, the Library, its rows and dialog
const sideways = (page) => page.evaluate(() => {
const over = [];
const w = document.documentElement.clientWidth;
if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth);
const v = document.querySelector("#view-library");
if (v.scrollWidth > v.clientWidth + 1) over.push("library " + v.scrollWidth + ">" + v.clientWidth);
for (const e of document.querySelectorAll("#view-library .lib-plugin, #view-library .lib-plpick, #view-library .lib-tabs, #modal .lib-pldetail *")) {
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 + ": the Library's Claude plugins tab", 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 lang of ["en", "zh", "zh-TW", "ja", "de"]) {
await t.test(lang, async () => {
const w = (key, vars) => tr(lang, key, vars);
const state = { plugins: [{ ...PLUGIN }] };
const posts = [], errors = [];
const open = async (width) => {
const ctx = await browser.newContext({ viewport: { width, height: 1000 }, reducedMotion: "reduce" });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "plugins"); } 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, state, posts));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
await page.locator("#view-library .lib-plugin").first().waitFor();
return { ctx, page };
};
{
const { ctx, page } = await open(1100);
assert.deepEqual(await sideways(page), [], "sideways scroll at 1100");
await press(page, page.locator("#view-library .lib-plugin").first());
await page.locator("#modal .lib-pldetail").waitFor();
await settled(page);
assert.deepEqual(await sideways(page), [], "sideways scroll in the dialog at 1100");
await ctx.close();
}
const { ctx, page } = await open(420);
const v = page.locator("#view-library");
const row = (name) => v.locator(".lib-plugin").filter({ has: page.locator(".name", { hasText: name }) });
// the tab, counted, and the row's parts
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
assert(tabs.includes(w("Claude plugins") + " · 1"), tabs.join("|"));
assert.equal((await row("code-kit").locator(".lib-plparts").textContent()).trim(),
[w("Skills: {names}", { names: "code-kit-tdd" }), w("MCP servers: {names}", { names: "code-kit-docs" }), w("Hooks: {names}", { names: "code-kit-lint" }), w("Subagents: {names}", { names: "code-kit-reviewer" })].join(" · "));
assert.deepEqual(await sideways(page), [], "sideways scroll at 420");
assert.equal(await page.locator("select").count(), 0, "a native <select>");
// the switch turns every part off at once
await press(page, row("code-kit").locator(".lib-switch"));
await page.waitForFunction(() => document.querySelector("#view-library .lib-plugin.off"));
assert.deepEqual(posts.shift(), { what: "plugins/on", body: { name: "code-kit", on: false } });
await press(page, row("code-kit").locator(".lib-switch"));
await page.waitForFunction(() => !document.querySelector("#view-library .lib-plugin.off"));
assert.deepEqual(posts.shift(), { what: "plugins/on", body: { name: "code-kit", on: true } });
// a chip changes its agents
await press(page, row("code-kit").locator('.lib-ag[data-agent="codex"]'));
await page.waitForTimeout(250);
assert.deepEqual(posts.shift(), { what: "plugins/agents", body: { name: "code-kit", agents: ["claude"] } });
// find: probe, pick the new one, install
await v.locator('input[data-lib="plsource"]').fill("/Users/chuan/market");
await v.locator(".lib-plfind .lib-find button").click();
await v.locator(".lib-plpick").first().waitFor();
assert.deepEqual(posts.shift(), { what: "plugins/probe", body: { source: "/Users/chuan/market" } });
assert.equal(await v.locator(".lib-plpick input:checked").count(), 1);
assert.equal(await v.locator(".lib-plpick input:disabled").count(), 0);
assert.deepEqual(await sideways(page), [], "sideways scroll with the finds at 420");
await v.locator(".lib-plfind .lib-probefoot button.primary", { hasText: w("Install 1 plugin") }).click();
await row("fresh-kit").waitFor();
const inst = posts.shift();
assert.equal(inst.what, "plugins/install");
assert.deepEqual(inst.body.names, ["fresh-kit"]);
assert.equal(inst.body.source, "/Users/chuan/market");
// the dialog: parts, what isn't carried; Remove asks first
await press(page, row("code-kit"));
const d = page.locator("#modal .lib-pldetail");
await d.waitFor();
await settled(page);
assert.equal((await d.locator(".lib-plleft").textContent()).trim(), "commands/ship.md — slash commands aren't carried");
await d.locator(".bar button.danger").click();
const sheet = page.locator("dialog.action-confirm");
await sheet.waitFor();
await sheet.locator("button", { hasText: w("Cancel") }).click();
await sheet.waitFor({ state: "detached" });
await page.waitForTimeout(150);
assert.deepEqual(posts, [], "Cancel posts nothing");
await d.locator(".bar button.danger").click();
await sheet.waitFor();
await sheet.locator("button.danger-fill").click();
await d.waitFor({ state: "detached" });
assert.deepEqual(posts.shift(), { what: "plugins/remove", body: { name: "code-kit" } });
assert.equal(await row("code-kit").count(), 0);
assert.deepEqual(posts, []);
assert.deepEqual(errors, []);
await ctx.close();
});
}
});
}
@@ -172,7 +172,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the tab, with its count, between Hooks and RTK
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
assert.deepEqual(tabs.slice(4, 7), [w("Hooks"), w("Subagents") + " · 1", "RTK"]);
assert.deepEqual(tabs.slice(4, 8), [w("Hooks"), w("Subagents") + " · 1", w("Claude plugins"), "RTK"]);
// the row: what it is for, and what it binds
assert.equal((await row("reviewer").locator(".lib-subagentdesc").textContent()).trim(), LONG);
assert.equal((await row("reviewer").locator(".lib-subagentuses").textContent()).trim(), w("Skills: {names}", { names: "tdd" }) + " · " + w("MCP servers: {names}", { names: "github" }));
+2 -1
View File
@@ -40,7 +40,8 @@ import (
// Hook is a command the agents ticked for it run at Event.
type Hook struct {
Name string `json:"name"`
Name string `json:"name"`
Bundle string `json:"bundle,omitempty"` // the plugin it came with (plugin.go)
// Description says what the hook is for, in any language (#2011):
// the name is letters, digits, - and _, which says little to someone
// who reads Chinese. Only the library keeps it; no agent is given it.
+4
View File
@@ -32,6 +32,10 @@ type Library struct {
// Subagents are agents of their own the agents ticked for each can
// hand a task to (subagents.go, #2283)
Subagents []*Subagent `json:"subagents,omitempty"`
// Plugins are the Claude Code plugins kept as one item each: its
// skills, servers, hooks and subagents are the items above marked
// with its name (plugin.go)
Plugins []*Plugin `json:"plugins,omitempty"`
// Applied is what magpie wrote into each agent, so that what it takes
// away is only ever its own.
Applied map[string]*Applied `json:"applied,omitempty"`
+2 -1
View File
@@ -33,7 +33,8 @@ import (
// Server is one MCP server: a command magpie's agents start, or a URL they
// reach.
type Server struct {
Name string `json:"name"`
Name string `json:"name"`
Bundle string `json:"bundle,omitempty"` // the Claude Code plugin it came with (plugin.go)
// Transport is stdio for a command, http (streamable) or sse for a URL.
Transport string `json:"transport"`
Command string `json:"command,omitempty"`
File diff suppressed because it is too large Load Diff
+238
View File
@@ -0,0 +1,238 @@
package library
import (
"os"
"path/filepath"
"strings"
"testing"
)
// writePlugin writes a Claude Code plugin's folder: a skill, a subagent
// that names it, a hook on shell tools, a Stop hook, an MCP server, a
// slash command and a hook that isn't a command.
func writePlugin(t *testing.T, dir string) {
t.Helper()
write(t, filepath.Join(dir, ".claude-plugin/plugin.json"), `{"name":"acme-kit","version":"1.2.0","description":"Acme's review kit"}`)
write(t, filepath.Join(dir, "skills/tdd/SKILL.md"), "---\nname: tdd\ndescription: Test first\n---\nWrite the test first.\n")
write(t, filepath.Join(dir, "agents/reviewer.md"), "---\nname: reviewer\ndescription: Reviews a diff\nskills: tdd\n---\nYou review code.\n")
write(t, filepath.Join(dir, "commands/ship.md"), "Ship it\n")
write(t, filepath.Join(dir, "hooks/hooks.json"), `{"hooks":{
"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"${CLAUDE_PLUGIN_ROOT}/scripts/lint.sh","timeout":20}]}],
"Stop":[{"hooks":[{"type":"command","command":"echo done"}]}],
"PreCompact":[{"hooks":[{"type":"command","command":"echo compacting"},{"type":"prompt","prompt":"x"}]}]}}`)
write(t, filepath.Join(dir, ".mcp.json"), `{"mcpServers":{"acme-db":{"command":"${CLAUDE_PLUGIN_ROOT}/bin/db","args":["--data","${CLAUDE_PLUGIN_DATA}"],"env":{"K":"v"}}}}`)
}
func pluginAgents(t *testing.T, h string) {
t.Helper()
write(t, filepath.Join(h, ".claude/settings.json"), "{}\n")
write(t, filepath.Join(h, ".codex/config.toml"), "")
write(t, filepath.Join(h, ".config/opencode/opencode.json"), "{}\n")
}
func TestPluginImportCarryOnOffRemove(t *testing.T) {
h := sandbox(t)
pluginAgents(t, h)
src := filepath.Join(t.TempDir(), "acme")
writePlugin(t, src)
p, err := ProbePlugins(src)
if err != nil || len(p.Candidates) != 1 {
t.Fatalf("probe: %v %+v", err, p)
}
c := p.Candidates[0]
if c.Name != "acme-kit" || c.Skills != 1 || c.MCP != 1 || c.Hooks != 3 || c.Subagents != 1 || len(c.Left) != 2 {
t.Fatalf("candidate: %+v", c)
}
res := ok(t)(InstallPlugins(src, nil, []string{"claude", "codex"}))
if len(res.Installed) != 1 || res.Installed[0] != "acme-kit" {
t.Fatalf("installed: %+v", res.Installed)
}
root := filepath.Join(Dir(), "plugins", "acme-kit")
data := filepath.Join(Dir(), "plugin-data", "acme-kit")
// every part is an ordinary item of its page, marked with the plugin
v := View0(t)
if len(v.Plugins) != 1 || v.Plugins[0].Name != "acme-kit" || v.Plugins[0].Version != "1.2.0" {
t.Fatalf("plugins: %+v", v.Plugins)
}
if len(v.Skills) != 1 || v.Skills[0].Bundle != "acme-kit" {
t.Fatalf("skills: %+v", v.Skills)
}
// carried, each part to the agents that take it
if got := read(t, filepath.Join(h, ".claude/agents/reviewer.md")); !strings.Contains(got, "You review code.") || !strings.Contains(got, `skills: ["tdd"]`) {
t.Errorf("claude subagent:\n%s", got)
}
if _, err := os.Stat(filepath.Join(h, ".codex/agents/reviewer.toml")); err != nil {
t.Errorf("codex subagent: %v", err)
}
if _, err := os.Lstat(filepath.Join(h, ".claude/skills/tdd")); err != nil {
t.Errorf("claude skill: %v", err)
}
settings := read(t, filepath.Join(h, ".claude/settings.json"))
for _, want := range []string{filepath.Join(root, "scripts/lint.sh"), "Bash", "echo done"} {
if !strings.Contains(settings, want) {
t.Errorf("claude settings lack %q:\n%s", want, settings)
}
}
if strings.Contains(settings, "compacting") == false {
t.Errorf("claude's own PreCompact hook missing:\n%s", settings)
}
if codexHooks := read(t, filepath.Join(h, ".codex/hooks.json")); strings.Contains(codexHooks, "compacting") {
t.Errorf("codex was given claude's own event:\n%s", codexHooks)
}
cj := read(t, filepath.Join(h, ".claude.json"))
if !strings.Contains(cj, filepath.Join(root, "bin/db")) || !strings.Contains(cj, data) {
t.Errorf("claude's server lacks the plugin's folders:\n%s", cj)
}
if !strings.Contains(read(t, filepath.Join(h, ".codex/config.toml")), "acme-db") {
t.Errorf("codex lacks the server")
}
if _, err := os.Stat(data); err != nil {
t.Errorf("data folder: %v", err)
}
// off: every part leaves every agent, and stays in the library
ok(t)(PluginOn("acme-kit", false))
for _, f := range []string{".claude/agents/reviewer.md", ".claude/skills/tdd", ".codex/agents/reviewer.toml"} {
if _, err := os.Lstat(filepath.Join(h, f)); err == nil {
t.Errorf("%s stays while the plugin is off", f)
}
}
if s := read(t, filepath.Join(h, ".claude/settings.json")); strings.Contains(s, "echo done") || strings.Contains(s, "compacting") {
t.Errorf("hooks stay while off:\n%s", s)
}
if s := read(t, filepath.Join(h, ".claude.json")); strings.Contains(s, "acme-db") {
t.Errorf("server stays while off:\n%s", s)
}
if v := View0(t); len(v.Skills) != 1 || len(v.Servers) != 1 || len(v.Subagents) != 1 || !v.Plugins[0].Off {
t.Fatalf("off keeps the parts in the library: %+v", v)
}
// on again, and for one agent only
ok(t)(PluginAgents("acme-kit", []string{"codex"}))
ok(t)(PluginOn("acme-kit", true))
if _, err := os.Stat(filepath.Join(h, ".claude/agents/reviewer.md")); err == nil {
t.Errorf("claude got the subagent it wasn't ticked for")
}
if _, err := os.Stat(filepath.Join(h, ".codex/agents/reviewer.toml")); err != nil {
t.Errorf("codex: %v", err)
}
// removed: nothing of it is left, in an agent or the library
ok(t)(RemovePlugin("acme-kit"))
v = View0(t)
if len(v.Plugins)+len(v.Skills)+len(v.Servers)+len(v.Hooks)+len(v.Subagents) != 0 {
t.Errorf("left after remove: %+v", v)
}
if _, err := os.Stat(root); err == nil {
t.Errorf("its folder stays")
}
if _, err := os.Stat(filepath.Join(h, ".codex/agents/reviewer.toml")); err == nil {
t.Errorf("codex's subagent stays")
}
}
// The user's own items by the same names are never written over, and a
// plugin never takes them for its own.
func TestPluginNameClashKeepsTheUsersOwn(t *testing.T) {
h := sandbox(t)
pluginAgents(t, h)
ok(t)(SaveServer("", Server{Name: "acme-db", Transport: "stdio", Command: "mine", Agents: []string{"claude"}}))
src := filepath.Join(t.TempDir(), "acme")
writePlugin(t, src)
res := ok(t)(InstallPlugins(src, nil, []string{"claude"}))
if len(res.Skipped) == 0 {
t.Fatalf("nothing said about the clash")
}
v := View0(t)
var own, theirs int
for _, s := range v.Servers {
if s.Name == "acme-db" && s.Bundle == "" && s.Command == "mine" {
own++
}
if s.Name == "acme-kit-acme-db" && s.Bundle == "acme-kit" {
theirs++
}
}
if own != 1 || theirs != 1 {
t.Fatalf("servers: %+v", v.Servers)
}
ok(t)(RemovePlugin("acme-kit"))
if v := View0(t); len(v.Servers) != 1 || v.Servers[0].Command != "mine" {
t.Errorf("remove took the user's own: %+v", v.Servers)
}
_ = h
}
// A marketplace lists several plugins, each a folder in it; one picked is
// installed, and an update reads it again from the same place keeping
// where it was given.
func TestPluginMarketplaceAndUpdate(t *testing.T) {
h := sandbox(t)
pluginAgents(t, h)
mk := filepath.Join(t.TempDir(), "market")
write(t, filepath.Join(mk, ".claude-plugin/marketplace.json"), `{"name":"m","plugins":[
{"name":"one","source":"./plugins/one","description":"First"},
{"name":"two","source":"./plugins/two"},
{"name":"far","source":{"source":"github","repo":"o/r"}},
{"name":"out","source":"../../etc"}]}`)
write(t, filepath.Join(mk, "plugins/one/skills/a/SKILL.md"), "---\nname: a\ndescription: A\n---\nA\n")
write(t, filepath.Join(mk, "plugins/two/.mcp.json"), `{"two-srv":{"url":"https://example.com/mcp"}}`)
p, err := ProbePlugins(mk)
if err != nil || len(p.Candidates) != 4 || p.Marketplace != "m" {
t.Fatalf("probe: %v %+v", err, p)
}
if !p.Candidates[2].Remote || len(p.Candidates[3].Left) == 0 {
t.Fatalf("candidates: %+v", p.Candidates)
}
if _, err := InstallPlugins(mk, nil, nil); err == nil {
t.Fatalf("a marketplace with no pick installs nothing")
}
ok(t)(InstallPlugins(mk, []string{"one", "two"}, []string{"claude"}))
v := View0(t)
if len(v.Plugins) != 2 || v.Plugins[0].Description != "First" || len(v.Skills) != 1 || len(v.Servers) != 1 || v.Servers[0].Transport != "http" {
t.Fatalf("%+v", v)
}
ok(t)(PluginOn("one", false))
write(t, filepath.Join(mk, "plugins/one/skills/b/SKILL.md"), "---\nname: b\ndescription: B\n---\nB\n")
ok(t)(UpdatePlugin("one"))
v = View0(t)
if len(v.Skills) != 2 || !v.Plugins[0].Off || len(v.Plugins[0].Agents) != 1 {
t.Fatalf("update keeps off and agents: %+v", v.Plugins[0])
}
for _, s := range v.Skills {
if len(s.Agents) != 0 {
t.Errorf("%s was given to %v while off", s.Name, s.Agents)
}
}
}
func TestPluginRefusesWhatIsNone(t *testing.T) {
sandbox(t)
empty := t.TempDir()
if _, err := ProbePlugins(empty); err == nil {
t.Errorf("an empty folder is no plugin")
}
if _, err := ProbePlugins("-oProxyCommand=x"); err == nil {
t.Errorf("an option isn't an address")
}
cmds := t.TempDir()
write(t, filepath.Join(cmds, "commands/x.md"), "x")
if _, err := InstallPlugins(cmds, nil, nil); err == nil {
t.Errorf("a plugin of slash commands only has nothing to carry")
}
}
// View0 is the page's view of the library.
func View0(t *testing.T) *View {
t.Helper()
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
return v
}
+1
View File
@@ -33,6 +33,7 @@ import (
// the agents that get it.
type Skill struct {
Name string `json:"name"`
Bundle string `json:"bundle,omitempty"` // the plugin it came with (plugin.go)
Source *Source `json:"source,omitempty"`
Agents []string `json:"agents"`
// Hash is of the skill's files as last fetched from GitHub, and Commit
+1
View File
@@ -53,6 +53,7 @@ import (
// Subagent is one the agents ticked for it are given.
type Subagent struct {
Name string `json:"name"`
Bundle string `json:"bundle,omitempty"` // the plugin it came with (plugin.go)
Description string `json:"description"`
Prompt string `json:"prompt"`
// Model is the model or routing group the subagent runs on, as the
+7 -3
View File
@@ -458,6 +458,7 @@ type ServerView struct {
// SkillView is a library skill as the page shows it.
type SkillView struct {
Name string `json:"name"`
Bundle string `json:"bundle,omitempty"` // the plugin it came with
Description string `json:"description"`
Source string `json:"source,omitempty"`
Kind string `json:"kind"` // github, git, folder, or "" for one kept in the library
@@ -511,8 +512,10 @@ type View struct {
Subagents []SubagentView `json:"subagents"`
SubagentAgents []SubagentAgentView `json:"subagentAgents"`
FoundServers []Found `json:"foundServers"`
Skills []SkillView `json:"skills"`
FoundSkills []FoundSkill `json:"foundSkills"`
// Plugins are the plugins kept as one item each (plugin.go)
Plugins []PluginView `json:"plugins"`
Skills []SkillView `json:"skills"`
FoundSkills []FoundSkill `json:"foundSkills"`
// NewSkills are skills a check found its skills' repositories, or
// the folders they were added from, to have beside them since, to
// add or set aside
@@ -704,9 +707,10 @@ func readView(problems []Problem, glance bool) (*View, error) {
}
v.Hooks, v.HookAgents = l.hooksView(append(slices.Clone(targets), gone...), asleep, of)
v.Subagents, v.SubagentAgents = l.subagentsView(targets, asleep, of)
v.Plugins = l.pluginsView()
tr := &tracer{}
for _, s := range l.Skills {
sv := SkillView{Name: s.Name, Agents: append([]string{}, s.Agents...), Icon: skillIcon(s), Problems: of("skill:" + s.Name), Repo: tr.repoOf(s), OffHere: s.OffHere, Note: s.Note, Router: s.Router}
sv := SkillView{Name: s.Name, Bundle: s.Bundle, Agents: append([]string{}, s.Agents...), Icon: skillIcon(s), Problems: of("skill:" + s.Name), Repo: tr.repoOf(s), OffHere: s.OffHere, Note: s.Note, Router: s.Router}
if s.Source != nil {
sv.Source, sv.Kind = s.Source.String(), s.Source.Kind
}