diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index ecd3284fa..3c7a02c27 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -1,9 +1,9 @@ -# Library: instructions, MCP servers, skills, hooks, subagents, RTK and billion-context +# Library: instructions, MCP servers, skills, hooks, subagents, slash commands, RTK and billion-context The library keeps what every agent should know in one place: the instructions each agent reads before a conversation, the MCP servers it can call, the skills it can load, the hooks it runs at points of its turn, and -the subagents it can hand a task to. +the subagents it can hand a task to, and the slash commands typed into it. magpie writes these into each agent's own files in that agent's format, and takes back only what it wrote. Everything else in those files stays as it was. Package `internal/library` also gives @@ -37,6 +37,7 @@ Pi's extensions and packages. | Variables | An `EnvVar` (paopao_baobao on X) is a name, a value and the agents ticked for it (`internal/library/env.go`). Claude Code gets it in `settings.json`'s `env`, Codex in `config.toml`'s `[shell_environment_policy.set]` (`envFile`, `writeEnv`); an agent with no such setting is greyed on the tab, saying why. `syncEnv` records what it wrote in `Applied.Env` and never overrides the user: a name the file already sets to another value is left as it is and reported as a problem on the row (`env:`), and a recorded value the user changed in the file is theirs from then on (the record is dropped, a removal or a turn-off leaves it). Turning an agent off or removing the variable takes out only the recorded, unchanged value. Codex's spelling is respected: a `set` sub-table or an inline `set = {…}` is edited, a dotted spelling is refused with `left as it is`. An unreadable or wrongly typed file is an error, never empty, and nothing is written. Names are `[A-Za-z_][A-Za-z0-9_]*`, at most 128, values at most 8192 bytes. Variables are carried with the library (see below). Tests: `TestEnvWrittenAndTakenOut`, `TestEnvNeverOverridesTheUsers`, `TestEnvValueChanged`, `TestEnvCodexInlineSet`, `TestEnvUnreadableFileLeftAlone`, `TestEnvChecked`, `library-env.test.cjs`. | | 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` (`.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) | | Subagents from a repository | The Subagents tab's find line (CHENGJIAHEGOXIS on X: msitarzewski/agency-agents) takes what the skill installer does, owner/repo, a GitHub or GitLab link to the repository, a folder or a file in it, any git address, or a folder here, and fetches it the same way (`fetchSourceRoot`, shared with `resolvePluginRoot`; `tooBig` refuses a whole repository too big to download and asks for its folder's link). `ProbeSubagents` lists each Markdown file with front matter that has a description (`readSubagentAt`): its name is the slug of `name` (`subagentName`), else the file's own name when it sits in an `agents` or `droids` folder; its description is folded to one line of at most 1000 characters; the body is the prompt. Every other key (`color`, `emoji`, `vibe`, `tools`, `author`, `model`, …) is dropped, a Codex TOML role is not read, and a skill's folder (one with a SKILL.md) and `.git`, `.github`, `node_modules` are skipped. Of two files with one name the shallower is taken and the other is listed in `Left` with why, as is one `Subagent.check` refuses (a reserved name). `ImportSubagents` (`POST /api/library/subagents/probe`, then `subagents/import` with `source`, `paths`, `agents`) adds the picked ones for the agents ticked, recording where each came from (`From`, a `Source` with the file's path) and the hash of its description and prompt as imported (`FromHash`). Imported again, from the repository's link or a folder's or a file's, a subagent from the same file is `have` when it is the same, `update` when upstream changed and the library's still matches `FromHash` (its description and prompt are replaced, its agents, skills, servers and model kept), and `edited` when the user changed it here (`SaveSubagent` keeps `From`; it is left as it is). A name the library has for another subagent is never written over: the import takes the next free `name-N`. A carried library carries `From`. The page lists what was found to pick from, with Select all, a filter past eight, a tag for each state and the files left out (`TestSubagentsFromAgencyAgents`, `TestSubagentImportLeavesTheUsersOwn`, `TestSubagentImportAgainUpdates`, `TestSubagentsFromAFolder`, `library-subagents-import.test.cjs`; the fixture is agency-agents' own files in `testdata/agency-agents`). | [`subagent_import.go`](../../internal/library/subagent_import.go), [`plugin.go`](../../internal/library/plugin.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | +| Slash commands | A `Command` (miantiao_me on X) is a name (lowercase letters, digits, - and _), a one-line description and a prompt, given to the agents ticked for it, and typed as /name there. The prompt says `$ARGUMENTS` for every word typed after the name and `$1`, `$2`… for the first, second… of them. `syncCommands` writes it as a file of its own in each agent's user-level folder, in that agent's shape (`commandSpecOf`): `/commands/.md` (front matter `description`; `$n` becomes Claude Code's `$ARGUMENTS[n-1]`, counted from 0), OpenCode's `commands/.md` beside its config and Pi's `/prompts/.md` (`$ARGUMENTS` and `$n` as magpie's), `~/.gemini/commands/.toml` (`description`, `prompt`, `$ARGUMENTS` as `{{args}}`), Qwen Code's `commands/.md` (`{{args}}`) and `~/.factory/commands/.md` (`$ARGUMENTS`). Gemini CLI, Qwen Code and Droid take no words by place, so a command that uses `$1`… isn't written for them: the agent gets a problem, the editor names them under the prompt while it uses one, and the tab says so under the list. Codex is listed but greyed: Codex 0.165 has no loader of `~/.codex/prompts` any more, its skills took their place. An agent in a WSL distro gets none. The page lists, per agent, its folder and whether it takes `$1`… (`CommandAgentView`). There is no CLI for them yet. | [`commands.go`](../../internal/library/commands.go), `TestCommandsEachAgentsFile`, `TestCommandsWordsByPlace` | | Claude plugins | A `Plugin` (FakeshadowzZ on X) is a Claude Code plugin kept as one item: `.claude-plugin/plugin.json`, `skills//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 `/plugins/`; `${CLAUDE_PLUGIN_ROOT}` is that folder and `${CLAUDE_PLUGIN_DATA}` is `/plugin-data/`, which an update keeps. No agent sets either variable outside Claude Code's plugin runtime, so every reference is resolved before a part is written out ([`plugin_env.go`](../../internal/library/plugin_env.go)): `${NAME}`/`$NAME` in a hook command, a server's command, args and env, a subagent's prompt and a copied SKILL.md become the folder; a hook program's own read (`process.env.NAME`, `Bun.env`, `Deno.env.get`, Python's `os.environ`/`os.getenv`, Ruby's `ENV`) becomes a quoted string literal of the folder with forward slashes, and PowerShell's `$env:NAME` and cmd's `%NAME%` the folder (ponytail's hooks threw at every start without it, @AXmake110 on X); a command server is given both variables in its env, as Claude Code gives them. Parts a magpie before this wrote with the variables in them are resolved at load (`healPluginRefs`) and written out again at the next sync; a SKILL.md copied before is fixed by Update or a reinstall. Exec-form hooks (`args`) and `CLAUDE_PLUGIN_OPTION_` are not carried yet (#6682). Its parts are ordinary library skills, MCP servers, hooks and subagents, each tagged `Bundle: `, 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:`, for Claude Code only. Subagents go to the agents in `SubagentAgents`. A part whose name the library has gets the prefix `-`: 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`, `TestPluginHookReadsRootFromItsProgram`, `TestPluginHookWrittenBeforeIsResolved`, `TestPluginPartsGetItsFolders`, `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. An rtk.exe in one of winget's folders that winget has no record of (`winget list` says so, or its records name another folder; netube99 on X, 0x8A150014) is upgraded from rtk's own Windows release over the file a `WinGet\Links` link points to, not by `winget upgrade`. `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) | @@ -50,7 +51,7 @@ Pi's extensions and packages. 1. **Edit.** The Library page or `magpie library` calls an exported function such as `SaveServer`, `ServerAgents`, `InstallSkills`, `SkillAgents` or `SetSkillHow`. The skills and servers pages each have Select, Turn all on, Turn all off and Remove all; the heading shows Select (and a busy Checking…, Grouping… or Updating…) and keeps the rest under its ⋯, the app's row menu (`barMore` in plugins/library/client.js). Select's bar calls `SomeSkillsAgents` or `SomeServersAgents` (`/api/library/{skills,servers}/agents-some`), Turn all on or off calls `EverySkillAgents` or `EveryServerAgents` for the agents shown, and Remove all calls `RemoveSkills` or `RemoveServers`. The hooks page has Select and Remove all too (`SomeHooksAgents`, `RemoveHooks`). Each of these is one change that takes every item out as a single removal would (#1027). Select's bar also has Remove… (#1852), which asks first, naming the count, and sends only the picked names to `RemoveSkills`, `RemoveServers` or `RemoveHooks`; ticking a group's or part's header picks all of it. A name that wasn't removed stays picked, with its error in its row's place (`pickErrs`), and the status names it; when every name fails the endpoint answers 400 and the sheet stays open. A row's agent chips start with All (`allChip` in `plugins/library/client.js`), which gives the item to every agent shown that can take it, or takes it from them all; the pickers that choose the agents before an item is added (installing skills from a repository or the market, adding, bringing in or installing a server) have the same All: most start with every agent lit, and one agent alone took a click on each of the others (#1531). 2. **Change.** `change` edits `library.json` under the lock and calls `sync`. -3. **Write.** For each target, `syncInstructions`, `syncMCP`, `syncHooks` and `syncSubagents` write magpie's part in the agent's format and record it in `Applied`. Skills are linked or copied into the agent's skills folder. A copy edited since it was made is taken into the library first. +3. **Write.** For each target, `syncInstructions`, `syncMCP`, `syncHooks`, `syncSubagents` and `syncCommands` write magpie's part in the agent's format and record it in `Applied`. Skills are linked or copied into the agent's skills folder. A copy edited since it was made is taken into the library first. 4. **Result.** The `Result` lists the agents changed, a `Problem` for each thing that couldn't be given, and the backup folder. Each change's folder is its own (`freshBackup`): named by the millisecond, with `-2`, `-3`… after it when another change took that millisecond, so a change's copy is never another's (`TestBackupsInOneMillisecond`). ## Constraints and failure behavior @@ -109,6 +110,7 @@ Pi's extensions and packages. - CC Switch's own skills folder is only ever read. - Reading the page never waits on reading skills through (#541). `Read` compares an agent's own skill with the same name in another agent (`sameTree`) and hashes each library skill given as a copy (`hashFiles`, for `behind`). Both are kept against a stamp of the folders (each file's and link's path, type, size and mtime, `stamper` in [`treememo.go`](../../internal/library/treememo.go)), taken by the same walk that compares or hashes them, before a file is opened; a later read walks the folder without opening a file, and while the stamps match reuses the answer. Only an answer from a whole read of folders untouched for `settleFor` (3s) is kept: a folder that couldn't be walked or read, or was written a moment ago, is read again next time, never taken as unchanged. A rewrite that keeps a file's size and mtime isn't seen. `Glance` (`GET /api/library?glance=1`) is the page without those two, marked `partial`; the page draws it first, then the whole read, which runs `behind` and `foundSkills` after the library's lock is let go, so a change doesn't wait on them either. - A read of the page (`Read`, `Glance`) follows the links on the way to a few hundred paths, most of them many times over: each agent's skills folder for each skill, CC Switch's and the shared folder for each source. While the read holds the lock, `resolve` looks at each entry on the way once (`lookPart` in [`linkmemo.go`](../../internal/library/linkmemo.go)): one `Lstat`, and a `Readlink` for a link. Nothing is kept past the read, so a link made or moved on disk between two visits shows on the second. An entry that couldn't be looked at for another reason than its not being there is unknown and looked at again. One read had taken ~10,000 looks; on oxyuan's Windows machine that was ~1.3s a visit (#1771). +- A slash command file is recorded as a subagent's is (`Applied.Commands`, through the shared `syncOwnFiles`): magpie writes over or takes away only a file still exactly as it wrote it, an edited one is the user's from then on, a file of the user's own by the name is never written over (the agent gets a problem), one whose bytes are what magpie would write is taken as magpie's, and one of magpie's the user deleted is written again. A carried library carries the commands (`Bundle.Commands`: name, description, prompt, agents ticked), never `Applied.Commands`; nil keeps this computer's, and an empty list hashes as before the field (`TestCommandsLeaveTheUsersFiles`, `TestCommandsCarried`). - Skills installed together (`InstallSkills`, `InstallMarketSkill`, `AddNewSkills`, through `installFrom` and `installChange`) install each on its own. One the library lists from the same source, or a folder in the library's own skills folder holding exactly that skill's files (left by an install that stopped before the library was saved), is had already and goes in `Result.Had`. Its files are never written, so the user's edits stay. Another skill by that name, listed or only in the folder, is left as it is. One from GitHub or another git repository then goes in beside it under a name of its own (mora1n on Discord: anthropics/skills' and openai/skills' `skill-creator` are two skills): the name with its source's owner added (`skill-creator-openai`), then owner and repository, the repository, then a number, at most 64 bytes (`freeSkillName` in [`skill_beside.go`](../../internal/library/skill_beside.go)). The library's copy of its `SKILL.md` gives that name too (`nameSkill`, only the front matter's top-level `name:` line), so an agent never sees two skills by one name; `Skill.Called` keeps the name its `SKILL.md` gave. Its hash is of the renamed copy, and a check or update compares what it fetches named the same way (`fetchedHash`), so it reads as unchanged and an update keeps the name. Being had is decided by source, not name (`hadSkill`): the same source under any name here, or a skill with no source (taken in from an agent's folder) by that name holding the very same files. A probe's candidate says which (`Candidate.Have`, `Candidate.As`), the page and the TUI show "in the library as …" or "adds as …", the market's had check matches by name only a skill with no repository (`haveSkill`), and the new-skills check no longer drops a skill because its name is taken. A skill already in the library keeps its name, folder and links; nothing is renamed after the fact. A folder of the user's own is linked as it is, so its `SKILL.md` can't be named apart: one by a taken name, or a folder that can't be read, goes in `Result.Skipped` with why (`TestSameNameFromAnotherSourceGoesInBeside`, `TestSameFilesByNameAreHad`, `TestInstallSetPutsAnotherByTheSameNameBeside`, `TestAddFromLibraryFolderKeepsIt`). The rest are installed and named in `Result.Installed`. Only when nothing was installed or had does the change fail, with the first reason. - A skill the library has from a folder of the user's, or took in from an agent's folder, has nothing to update from, though it often came from GitHub (biubiu8802 on X: downloaded from there, then added from its folder). Installing that skill from GitHub links the two when it is that skill: traced to that repository, or traced nowhere with the same description in its SKILL.md (`followsHere`, `linkSkill` in [`skill_link.go`](../../internal/library/skill_link.go)): the library's skill keeps its name, agents and links, takes GitHub's files and GitHub as its `Source` (`skillUpdate.apply` with `adopt`, as an update of a CC Switch skill does), and a check and an update cover it from then on. The library's link to a folder elsewhere is all that goes; that folder stays as it is. A copy of the library's own whose files aren't GitHub's goes to the backups (`keepReplaced`), as `UpdateSkill` with replace keeps an edited one. One whose files are GitHub's to the file only takes the source, and so does one had by the very same files (`hadSkill`). The install names it in `Result.Linked`, and in `Result.LinkedKept` when its files were kept; a probe's candidate says so first (`Candidate.Links`), and the page tags the row "links to GitHub" and says both after the install (`skill-install-link.test.cjs`), the TUI likewise. A skill traced to another repository (`tracer.repoOf`: `From`, CC Switch's record, the skills CLI's lock, a git checkout) and an untraced one that describes something else are other skills by that name, and the GitHub one goes in beside them as above (`TestInstallSetPutsAnotherByTheSameNameBeside`); a skill from GitHub or git is never taken over (`TestFolderSkillFollowsGitHub`, `TestOwnSkillFollowsGitHubKeepsItsFiles`, `TestSkillFromElsewhereIsNotLinked`). The market's had check is unchanged: it still counts such a skill as had by its name. @@ -116,6 +118,7 @@ Pi's extensions and packages. ```sh 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 'TestCommand' go test -tags nogui ./internal/library -run 'TestSkillOffHere|TestLocalServerNotCarried|TestPutKeepsLocalServer|TestPutSameNameAsLocal|TestServerHere' go test -tags nogui ./internal/backup -run 'TestRestoreKeepsLocalServer|TestBackupFileCarriesSubagents|TestBackupFileCarriesHooks' go test -tags nogui ./internal/library -run 'TestHandOver|TestSharedUnderAnotherName|TestSharedAgentsSkills' @@ -134,7 +137,7 @@ node --test internal/gui/tests/library-rtk-wsl.test.cjs node --test internal/gui/tests/skill-auto-update.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/mcp-server-here.test.cjs internal/gui/tests/skill-handover.test.cjs -node --test internal/gui/tests/mcp-accounts.test.cjs 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-subagents-import.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 +node --test internal/gui/tests/mcp-accounts.test.cjs 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-subagents-import.test.cjs internal/gui/tests/library-commands.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 diff --git a/internal/cli/backup_cmd.go b/internal/cli/backup_cmd.go index d9676ed6f..83ddafb67 100644 --- a/internal/cli/backup_cmd.go +++ b/internal/cli/backup_cmd.go @@ -75,6 +75,9 @@ func backupCmd(args []string) error { if l.Subagents != nil && len(*l.Subagents) > 0 { fmt.Printf(", %d subagents", len(*l.Subagents)) } + if l.Commands != nil && len(*l.Commands) > 0 { + fmt.Printf(", %d slash commands", len(*l.Commands)) + } if l.Hooks != nil && len(*l.Hooks) > 0 { fmt.Printf(", %d hooks", len(*l.Hooks)) } diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index 503d81c45..2564e31b7 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -956,6 +956,11 @@ func hashes(b backup.Bundle) map[string]string { c.Subagents = nil lib = &c } + if lib != nil && lib.Commands != nil && len(*lib.Commands) == 0 { // as before them, without one + c := *lib + c.Commands = nil + lib = &c + } if lib != nil && lib.Hooks != nil && len(*lib.Hooks) == 0 { // as before them, without one c := *lib c.Hooks = nil @@ -1029,7 +1034,7 @@ func unset(b backup.Bundle, p string) bool { } } return len(l.MCP) == 0 && len(l.Skills) == 0 && - (l.Subagents == nil || len(*l.Subagents) == 0) && (l.Hooks == nil || len(*l.Hooks) == 0) && + (l.Subagents == nil || len(*l.Subagents) == 0) && (l.Commands == nil || len(*l.Commands) == 0) && (l.Hooks == nil || len(*l.Hooks) == 0) && (l.Bili == nil || strings.TrimSpace(*l.Bili) == "") } return false diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 3b17c2c95..b8610d36f 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -937,6 +937,7 @@ const I18N = { "also for small background tasks": "也用于后台小任务", "the default tier": "默认档位", "Subagents": "子代理", + "Codex reads custom prompts no more: its skills took their place": "Codex 已不再读取自定义提示词:由它的技能取代", "Claude models": "Claude 模型", "Your Claude subscription is in magpie; picking a claude-* model goes through it as before": "已在 magpie 添加 Claude 订阅,claude-* 模型照常走该订阅", "Add a Claude subscription": "添加 Claude 订阅", @@ -6244,6 +6245,7 @@ const I18N = { "also for small background tasks": "也用於後臺小任務", "the default tier": "預設檔位", "Subagents": "子代理", + "Codex reads custom prompts no more: its skills took their place": "Codex 已不再讀取自訂提示詞:由它的技能取代", "Claude models": "Claude 模型", "Your Claude subscription is in magpie; picking a claude-* model goes through it as before": "已在 magpie 新增 Claude 訂閱,claude-* 模型照常走該訂閱", "Add a Claude subscription": "新增 Claude 訂閱", @@ -11515,6 +11517,7 @@ const I18N = { "also for small background tasks": "小さなバックグラウンドタスクにも使用", "the default tier": "デフォルトの階層", "Subagents": "サブエージェント", + "Codex reads custom prompts no more: its skills took their place": "Codex はカスタムプロンプトを読み込まなくなりました:スキルに置き換えられています", "Claude models": "Claude モデル", "Your Claude subscription is in magpie; picking a claude-* model goes through it as before": "Claude サブスクリプションは magpie にあります。claude-* モデルを選ぶと、これまでどおりそのサブスクリプションを使います", "Add a Claude subscription": "Claude サブスクリプションを追加", @@ -16804,6 +16807,7 @@ const I18N = { "also for small background tasks": "auch für kleine Hintergrundaufgaben", "the default tier": "die Standardstufe", "Subagents": "Subagenten", + "Codex reads custom prompts no more: its skills took their place": "Codex liest keine eigenen Prompts mehr: seine Skills haben sie ersetzt", "Claude models": "Claude-Modelle", "Your Claude subscription is in magpie; picking a claude-* model goes through it as before": "Ihr Claude-Abo ist in magpie hinterlegt; ein claude-*-Modell läuft wie bisher darüber", "Add a Claude subscription": "Claude-Abo hinzufügen", diff --git a/internal/gui/assets/navicons.js b/internal/gui/assets/navicons.js index f3bfd9251..569f92f25 100644 --- a/internal/gui/assets/navicons.js +++ b/internal/gui/assets/navicons.js @@ -5,7 +5,7 @@ // The sections a page's list is cut into, by tab id: a section none of whose // tabs shows has no name (app.js navSubs), as does a list of one section. window.NAV_SUB_GROUPS = { - library: { instructions: "Every agent", memory: "Every agent", mcp: "Every agent", skills: "Every agent", hooks: "Every agent", env: "Every agent", subagents: "Every agent", plugins: "One agent", pi: "One agent", rtk: "magpie", bili: "magpie" }, + library: { instructions: "Every agent", memory: "Every agent", mcp: "Every agent", skills: "Every agent", hooks: "Every agent", env: "Every agent", subagents: "Every agent", commands: "Every agent", plugins: "One agent", pi: "One agent", rtk: "magpie", bili: "magpie" }, }; // the tabs [tab, its place in the strip, its section's name where one starts], // in sections in order, each in the strip's order @@ -27,6 +27,8 @@ window.NAV_SUB_IC = { hooks: "M10.5 2.5v6.5a3 3 0 0 1-6 0V7.5 M3 9l1.5-1.5L6 9", env: "M5.5 3.5h-1.5v9h1.5 M10.5 3.5h1.5v9h-1.5 M6.5 8h3", subagents: "M6 3a2.2 2.2 0 1 0 0 4.4A2.2 2.2 0 0 0 6 3z M2 13c.5-2.2 2-3.4 4-3.4s3.5 1.2 4 3.4 M11.5 7.5a1.5 1.5 0 1 0 0 .01 M10.2 12.5c.3-1.3 1.1-2 2.3-2s1.6.5 1.9 1.4", + // a slash in a key, as a command is typed + commands: "M4.5 3h7A1.5 1.5 0 0 1 13 4.5v7a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 3 11.5v-7A1.5 1.5 0 0 1 4.5 3z M9.6 5.4l-3.2 5.2", rtk: "M2.5 3.5h11v9h-11z M5 6.5l1.5 1.5L5 9.5 M8.5 9.5h2.5", bili: "M8 2v4 M6 4.2 8 6l2-1.8 M8 14v-4 M6 11.8 8 10l2 1.8 M3 8h10", pi: "M8 2.5l5 2.5v6L8 13.5 3 11V5z M3 5l5 2.5L13 5 M8 7.5v6", diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 3025a3a9c..6adff90c6 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -52,6 +52,8 @@ magpie.plugin("library", (ctx) => { hook: "M10.5 2.5v6.5a3 3 0 0 1-6 0V7.5 M3 9l1.5-1.5L6 9", // a person with a second, smaller one it hands work to subagent: "M6 3a2.2 2.2 0 1 0 0 4.4A2.2 2.2 0 0 0 6 3z M2 13c.5-2.2 2-3.4 4-3.4s3.5 1.2 4 3.4 M11.5 7.5a1.5 1.5 0 1 0 0 .01 M10.2 12.5c.3-1.3 1.1-2 2.3-2s1.6.5 1.9 1.4", + // a slash in a key, as a command is typed + command: "M4.5 3h7A1.5 1.5 0 0 1 13 4.5v7a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 3 11.5v-7A1.5 1.5 0 0 1 4.5 3z M9.6 5.4l-3.2 5.2", // a clock with an arrow going back round it, as macOS draws backups backup: "M3.2 8a4.8 4.8 0 1 0 1.4-3.4 M2.8 2.6v2.4h2.4 M8 5.3V8l1.9 1.2", power: "M8 2.5v5 M4.7 4.6a4.8 4.8 0 1 0 6.6 0", @@ -528,7 +530,7 @@ magpie.plugin("library", (ctx) => { // What All did, said of the item: on for how many of the agents it went // to, and which of them couldn't be given it, and why. function reportAll(v, me) { - const what = ({ servers: "mcp:", hooks: "hook:", env: "env:", subagents: "subagent:" }[me.list] || "skill:") + me.name; + const what = ({ servers: "mcp:", hooks: "hook:", env: "env:", subagents: "subagent:", commands: "command:" }[me.list] || "skill:") + me.name; const shown = [...me.box.children].filter((x) => isChip(x) && !cannot(x)).flatMap((x) => idsOf(x).filter((id) => !x.dataset.fixed?.split("\t").includes(id))); const n = shown.filter((id) => me.want.includes(id)).length; const bad = (v.result?.problems || []).filter((p) => p.what === what && shown.includes(p.agent)); @@ -805,7 +807,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"), env: t("Environment variables"), subagents: t("Subagents"), plugins: t("Claude plugins") }; + const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), env: t("Environment variables"), subagents: t("Subagents"), commands: t("Slash commands"), plugins: t("Claude plugins") }; const others = Object.keys(away).filter((k) => k in tabNames); if (others.length) { const more = el("div", "lib-problems-away"); @@ -841,7 +843,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", env: "env", subagent: "subagents", plugin: "plugins" }[what.split(":")[0]] || ""; + return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", env: "env", subagent: "subagents", command: "commands", plugin: "plugins" }[what.split(":")[0]] || ""; } function problemWhat(what) { const [kind, ...rest] = what.split(":"); @@ -851,6 +853,7 @@ magpie.plugin("library", (ctx) => { if (kind === "skill") return t("Skill {name}", { name }); if (kind === "hook") return t("Hook {name}", { name }); if (kind === "subagent") return t("Subagent {name}", { name }); + if (kind === "command") return t("Slash command {name}", { name: "/" + name }); if (kind === "project") return name ? t("Skill {name}", { name }) : t("The project"); return what; } @@ -955,6 +958,7 @@ magpie.plugin("library", (ctx) => { ["hooks", t("Hooks") + n("hooks")], ["env", t("Environment variables") + n("env")], ["subagents", t("Subagents") + n("subagents")], + ["commands", t("Slash commands") + n("commands")], ["plugins", t("Claude plugins") + n("plugins")], ["rtk", "RTK"], ["bili", "billion-context"], @@ -1018,7 +1022,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, env: (lib.env || []).length, subagents: (lib.subagents || []).length, plugins: (lib.plugins || []).length }); + const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, env: (lib.env || []).length, subagents: (lib.subagents || []).length, commands: (lib.commands || []).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 @@ -1038,6 +1042,7 @@ magpie.plugin("library", (ctx) => { else if (tab === "hooks") renderHooks(body); else if (tab === "env") renderEnv(body); else if (tab === "subagents") renderSubagents(body); + else if (tab === "commands") renderCommands(body); else if (tab === "plugins") renderPlugins(body); else renderSkills(body); page.append(body); @@ -1074,7 +1079,7 @@ magpie.plugin("library", (ctx) => { if (JSON.stringify(follow) !== JSON.stringify(was) && lib && page.isConnected) render(); } function followNote() { - const part = tab === "memory" ? "memory" : ["instructions", "mcp", "skills", "hooks", "env", "subagents", "plugins"].includes(tab) ? "library" : ""; + const part = tab === "memory" ? "memory" : ["instructions", "mcp", "skills", "hooks", "env", "subagents", "commands", "plugins"].includes(tab) ? "library" : ""; if (!part || !follow?.[part]) return null; const p = el("p", "lib-intro lib-follow", t("This computer follows the server: what you change here is replaced by the next sync.") + " "); const go = button(t("Sync settings"), "link", (e) => openSettingsAt(e, "sync", "#syncList .sync-follows")); @@ -5071,6 +5076,132 @@ magpie.plugin("library", (ctx) => { if (!s) requestAnimationFrame(() => name.focus()); } + // ---------- slash commands ---------- + + // A slash command (miantiao_me on X) is a prompt typed as /name in an + // agent: the words after the name go where it says $ARGUMENTS, and the + // first, second… of them where it says $1, $2…. It is kept once and + // written into each agent picked, as that agent's own command file in + // its own folder and shape (commands.go). Codex is listed, greyed: it + // reads custom prompts no more. + const commandAgentOf = (id) => (lib.commandAgents || []).find((x) => x.id === id); + const commandAgents = () => shownAgents().filter((a) => commandAgentOf(a.id)); + // why a can't be given a slash command, or "" + const commandBlocked = (a) => { + const ca = commandAgentOf(a.id); + if (ca && !ca.no) return ""; + if (ca?.wsl) return t("magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL", { agent: a.name }); + if (a.id === "codex") return t("Codex reads custom prompts no more: its skills took their place"); + return t("{agent} reads no slash commands magpie can write", { agent: a.name }); + }; + // a prompt that takes words by their place ($1, $2…; $0 is none) + const usesArgs = (p) => /\$(?!0(?![0-9]))[0-9]+/.test(p || ""); + // the agents of ids that take only $ARGUMENTS + const noArgs = (all, ids) => all.filter((a) => ids.includes(a.id) && !commandBlocked(a) && !commandAgentOf(a.id).args); + + function renderCommands(body) { + body.append(intro(t("A slash command is a prompt you type as /name in an agent. Add it once and magpie writes it into each agent you pick, as that agent's own command."))); + const all = commandAgents(); + const cmds = lib.commands || []; + if (!cmds.length) { + body.append(empty(t("No slash commands in the library yet"), t("Add one, and pick the agents that get it."), button(t("+ Add a slash command"), "action", () => editCommand(null)))); + } else { + const list = el("div", "list lib-list"); + list.append(...[...cmds].sort((a, b) => a.name.localeCompare(b.name)).map((c) => commandRow(c, all))); + body.append(list); + const after = el("div", "after-list"); + after.append(button(t("+ Add slash command"), "", () => editCommand(null))); + body.append(after); + } + const noPlace = [...new Set(cmds.filter((c) => usesArgs(c.prompt)).flatMap((c) => noArgs(all, c.agents || [])))]; + if (noPlace.length) body.append(el("p", "lib-aside lib-commands-noargs", t("{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.", { agents: noPlace.map((a) => a.name).join(", ") }))); + const skip = all.filter((a) => commandAgentOf(a.id).no); + if (skip.length) body.append(el("p", "lib-aside lib-commands-no", t("magpie can't give slash commands to {agents}: their chips are greyed, and say why.", { agents: skip.map((a) => a.name).join(", ") }))); + } + + function commandRow(c, all) { + const row = el("div", "row lib-row click lib-command"); + const who = el("div", "who"); + who.append(el("div", "name mono", "/" + c.name)); + if (c.description) who.append(el("div", "lib-commanddesc", c.description)); + row.append(glyph(GLYPH.command), who, + agentChips(all, c.agents, chipsChange("commands/agents", c.name, "commands", (x) => commandRow(x, all)), { problems: c.problems, blocked: commandBlocked, all: true })); + row.onclick = () => editCommand(c); + row.title = t("Edit {name}", { name: "/" + c.name }); + return row; + } + + function editCommand(c) { + const all = commandAgents(); + const d = c ? { name: c.name, description: c.description || "", prompt: c.prompt, agents: [...(c.agents || [])] } + : { name: "", description: "", prompt: "", agents: all.filter((a) => !commandBlocked(a)).map((a) => a.id) }; + const ed = el("div", "editor lib-editor lib-commandedit"); + const head = el("div", "ehead"); + head.append(glyph(GLYPH.command), el("b", "", c ? "/" + c.name : t("New slash command"))); + ed.append(head); + const err = el("div", "editor-error"); + const name = field2(d.name, t("e.g. review"), (v) => { d.name = v.trim(); }); + name.classList.add("mono"); + ed.append(...field(t("Name"), name, t("Typed as /name: lowercase letters, digits, - and _"))); + const box = (cls, value, placeholder, rows, max, onEnter) => { + const ta = el("textarea", "lib-text small " + cls); + ta.value = value; + ta.placeholder = placeholder; + ta.spellcheck = false; + ta.rows = rows; + ta.maxLength = max; + ta.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (onEnter && e.key === "Enter" && modal?.save) { e.preventDefault(); modal.save(); } }; + autosize(ta, rows * 20); + return ta; + }; + // one line, as the agents list it (library.SaveCommand joins its + // lines), so Enter saves; the prompt's Enter is a new line + const desc = box("lib-commanddescin", d.description, t("e.g. Review a diff for bugs"), 1, 1000, true); + desc.oninput = () => { d.description = desc.value; }; + ed.append(...field(t("Description"), desc)); + const prompt = box("lib-commandprompt", d.prompt, t("Review $ARGUMENTS for bugs. Report only what is wrong."), 6, 100000, false); + const argsHint = el("div", "hint lib-commandhint-args"); + prompt.oninput = () => { d.prompt = prompt.value; drawHint(); }; + const [pl, pw] = field(t("Prompt"), prompt, t("$ARGUMENTS is what you type after the name; $1, $2… its first, second… word")); + pw.append(argsHint); + ed.append(pl, pw); + const agentsBox = el("div"); + ed.append(...field(t("Agents"), agentsBox)); + ed.append(err); + function drawHint() { + const no = usesArgs(d.prompt) ? noArgs(all, d.agents) : []; + argsHint.textContent = no.length ? t("Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS", { agents: no.map((a) => a.name).join(", ") }) : ""; + } + function drawAgents() { + agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, blocked: commandBlocked, all: true })); + drawHint(); + } + drawAgents(); + + const bar = el("div", "bar"); + if (c) bar.append(button(t("Remove from the library"), "danger", async () => { + if (!await confirmRemoval("/" + c.name, "It will be removed from the library and the agents it was given to.")) return; + if (await change("commands/remove", { name: c.name }, t("{name} is out of the library and the agents it was given to", { name: "/" + c.name }))) closeLibModal(true); + })); + bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal)); + const save = async () => { + err.textContent = ""; + try { + const command = { name: d.name.replace(/^\//, ""), description: d.description.trim(), prompt: d.prompt, agents: d.agents.filter((id) => !commandBlocked(agentOf(id) || { id })) }; + take(await api("library/commands/save", { old: c ? c.name : "", command })); + report(lib.result, c ? t("{name} saved", { name: "/" + command.name }) : ""); + closeLibModal(true); + render(); + } catch (e) { err.textContent = e.message; } + }; + bar.append(button(c ? t("Save") : t("Add"), "primary", save)); + ed.append(bar); + const original = JSON.stringify(d); + modal = { save, dirty: () => JSON.stringify(d) !== original }; + openLib(ed); + if (!c) requestAnimationFrame(() => name.focus()); + } + // ---------- Claude plugins ---------- // A Claude Code plugin kept as one item (FakeshadowzZ on X): its skills, diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 26c4d18b1..7b9712618 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -170,6 +170,23 @@ magpie.strings({ "Not bound for {agents}: theirs uses every skill the agent has": "{agents} 不会绑定:其子代理可用该 Agent 的全部技能", "Skills: {names}": "技能:{names}", "Subagent {name}": "子代理 {name}", + "Slash commands": "斜杠命令", + "Slash command {name}": "斜杠命令 {name}", + "magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL": "magpie 只给这台电脑上的代理写入斜杠命令,暂不支持 WSL 中的 {agent}", + "{agent} reads no slash commands magpie can write": "{agent} 没有 magpie 能写入的斜杠命令", + "A slash command is a prompt you type as /name in an agent. Add it once and magpie writes it into each agent you pick, as that agent's own command.": "斜杠命令是在代理里以 /名称 输入的一段提示词。在这里添加一次,magpie 会把它写入你选择的每个代理,成为该代理自己的命令。", + "No slash commands in the library yet": "资源库里还没有斜杠命令", + "+ Add a slash command": "+ 添加斜杠命令", + "+ Add slash command": "+ 添加斜杠命令", + "{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} 只支持 $ARGUMENTS(一次取全部参数):用到 $1、$2… 的命令不会写入它们。", + "magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie 无法给 {agents} 写入斜杠命令:它们的标签为灰色,并说明了原因。", + "New slash command": "新建斜杠命令", + "e.g. review": "例如 review", + "Typed as /name: lowercase letters, digits, - and _": "以 /名称 输入:小写字母、数字、- 和 _", + "e.g. Review a diff for bugs": "例如 检查一个 diff 中的 bug", + "Review $ARGUMENTS for bugs. Report only what is wrong.": "检查 $ARGUMENTS 中的 bug,只报告有问题的地方。", + "$ARGUMENTS is what you type after the name; $1, $2… its first, second… word": "$ARGUMENTS 是名称后输入的内容;$1、$2… 是其中第一个、第二个…词", + "Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS": "用到 $1、$2… 时不会写入 {agents}:它们只支持 $ARGUMENTS", "The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents.": "Cursor 应用会读取这些子代理;它的 cursor-agent 命令只读取项目自己的 .cursor/agents。", "The library has no MCP servers yet": "资源库里还没有 MCP 服务器", "The library has no skills yet": "资源库里还没有技能", @@ -1212,6 +1229,23 @@ magpie.strings({ "Not bound for {agents}: theirs uses every skill the agent has": "{agents} 不會綁定:其子代理可用該 Agent 的全部技能", "Skills: {names}": "技能:{names}", "Subagent {name}": "子代理 {name}", + "Slash commands": "斜線命令", + "Slash command {name}": "斜線命令 {name}", + "magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL": "magpie 只給這台電腦上的代理寫入斜線命令,暫不支援 WSL 中的 {agent}", + "{agent} reads no slash commands magpie can write": "{agent} 沒有 magpie 能寫入的斜線命令", + "A slash command is a prompt you type as /name in an agent. Add it once and magpie writes it into each agent you pick, as that agent's own command.": "斜線命令是在代理裡以 /名稱 輸入的一段提示詞。在這裡新增一次,magpie 會把它寫入你選擇的每個代理,成為該代理自己的命令。", + "No slash commands in the library yet": "資源庫裡還沒有斜線命令", + "+ Add a slash command": "+ 新增斜線命令", + "+ Add slash command": "+ 新增斜線命令", + "{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} 只支援 $ARGUMENTS(一次取全部參數):用到 $1、$2… 的命令不會寫入它們。", + "magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie 無法給 {agents} 寫入斜線命令:它們的標籤為灰色,並說明了原因。", + "New slash command": "新增斜線命令", + "e.g. review": "例如 review", + "Typed as /name: lowercase letters, digits, - and _": "以 /名稱 輸入:小寫字母、數字、- 和 _", + "e.g. Review a diff for bugs": "例如 檢查一個 diff 中的 bug", + "Review $ARGUMENTS for bugs. Report only what is wrong.": "檢查 $ARGUMENTS 中的 bug,只回報有問題的地方。", + "$ARGUMENTS is what you type after the name; $1, $2… its first, second… word": "$ARGUMENTS 是名稱後輸入的內容;$1、$2… 是其中第一個、第二個…詞", + "Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS": "用到 $1、$2… 時不會寫入 {agents}:它們只支援 $ARGUMENTS", "The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents.": "Cursor 應用程式會讀取這些子代理;它的 cursor-agent 命令只讀取專案自己的 .cursor/agents。", "The library has no MCP servers yet": "資源庫裡還沒有 MCP 伺服器", "The library has no skills yet": "資源庫裡還沒有技能", @@ -2254,6 +2288,23 @@ magpie.strings({ "Not bound for {agents}: theirs uses every skill the agent has": "{agents} では割り当てられません。エージェントのすべてのスキルを使います", "Skills: {names}": "スキル: {names}", "Subagent {name}": "サブエージェント {name}", + "Slash commands": "スラッシュコマンド", + "Slash command {name}": "スラッシュコマンド {name}", + "magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL": "magpie がスラッシュコマンドを書き込めるのはこのコンピューター上のエージェントだけで、WSL の {agent} にはまだ対応していません", + "{agent} reads no slash commands magpie can write": "{agent} には magpie が書き込めるスラッシュコマンドがありません", + "A slash command is a prompt you type as /name in an agent. Add it once and magpie writes it into each agent you pick, as that agent's own command.": "スラッシュコマンドは、エージェントで /名前 と入力して使うプロンプトです。ここで一度追加すると、magpie が選んだ各エージェントにそのエージェント独自のコマンドとして書き込みます。", + "No slash commands in the library yet": "ライブラリにスラッシュコマンドはまだありません", + "+ Add a slash command": "+ スラッシュコマンドを追加", + "+ Add slash command": "+ スラッシュコマンドを追加", + "{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} は $ARGUMENTS(すべての引数をまとめて)のみ対応です:$1、$2… を使うコマンドは書き込まれません。", + "magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie は {agents} にスラッシュコマンドを書き込めません:チップはグレー表示で、理由が表示されます。", + "New slash command": "新しいスラッシュコマンド", + "e.g. review": "例:review", + "Typed as /name: lowercase letters, digits, - and _": "/名前 で入力:小文字、数字、- と _", + "e.g. Review a diff for bugs": "例:diff のバグを確認する", + "Review $ARGUMENTS for bugs. Report only what is wrong.": "$ARGUMENTS のバグを確認し、問題のある箇所だけを報告してください。", + "$ARGUMENTS is what you type after the name; $1, $2… its first, second… word": "$ARGUMENTS は名前の後に入力した内容、$1、$2… はその 1 番目、2 番目…の語です", + "Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS": "$1、$2… を使う間は {agents} に書き込まれません:$ARGUMENTS のみ対応です", "The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents.": "Cursor アプリはこれらのサブエージェントを読み込みます。cursor-agent コマンドが読むのはプロジェクト自身の .cursor/agents だけです。", "The library has no MCP servers yet": "ライブラリにはまだ MCP サーバーがありません", "The library has no skills yet": "ライブラリにはまだスキルがありません", @@ -3296,6 +3347,23 @@ magpie.strings({ "Not bound for {agents}: theirs uses every skill the agent has": "Für {agents} nicht zugewiesen: Dort nutzt er jeden Skill, den der Agent hat", "Skills: {names}": "Skills: {names}", "Subagent {name}": "Subagent {name}", + "Slash commands": "Slash-Befehle", + "Slash command {name}": "Slash-Befehl {name}", + "magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL": "magpie gibt Slash-Befehle nur Agenten auf diesem Computer, noch nicht {agent} in WSL", + "{agent} reads no slash commands magpie can write": "{agent} liest keine Slash-Befehle, die magpie schreiben kann", + "A slash command is a prompt you type as /name in an agent. Add it once and magpie writes it into each agent you pick, as that agent's own command.": "Ein Slash-Befehl ist ein Prompt, den du in einem Agenten als /Name eingibst. Füge ihn einmal hinzu, und magpie schreibt ihn in jeden gewählten Agenten als dessen eigenen Befehl.", + "No slash commands in the library yet": "Noch keine Slash-Befehle in der Bibliothek", + "+ Add a slash command": "+ Slash-Befehl hinzufügen", + "+ Add slash command": "+ Slash-Befehl hinzufügen", + "{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} kennen nur $ARGUMENTS, alle Wörter auf einmal: ein Befehl mit $1, $2… wird für sie nicht geschrieben.", + "magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie kann {agents} keine Slash-Befehle geben: ihre Chips sind ausgegraut und sagen, warum.", + "New slash command": "Neuer Slash-Befehl", + "e.g. review": "z. B. review", + "Typed as /name: lowercase letters, digits, - and _": "Eingegeben als /Name: Kleinbuchstaben, Ziffern, - und _", + "e.g. Review a diff for bugs": "z. B. Einen Diff auf Fehler prüfen", + "Review $ARGUMENTS for bugs. Report only what is wrong.": "Prüfe $ARGUMENTS auf Fehler. Melde nur, was falsch ist.", + "$ARGUMENTS is what you type after the name; $1, $2… its first, second… word": "$ARGUMENTS ist, was du nach dem Namen eingibst; $1, $2… sein erstes, zweites… Wort", + "Not written for {agents} while it uses $1, $2…: they take only $ARGUMENTS": "Nicht für {agents} geschrieben, solange er $1, $2… nutzt: sie kennen nur $ARGUMENTS", "The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents.": "Die Cursor-App liest diese Subagenten; ihr Befehl cursor-agent liest nur das eigene .cursor/agents eines Projekts.", "The library has no MCP servers yet": "Die Bibliothek hat noch keine MCP-Server", "The library has no skills yet": "Die Bibliothek hat noch keine Skills", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index 69abe9fb8..374a82691 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -810,6 +810,13 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .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; } .lib-subagentedit .lib-subagentprompt { max-height: 40vh; overflow-y: auto; } .lib-subagentedit .hint:empty { display: none; } +/* a slash command's row: its /name in mono, its description under it; + its editor's prompt a box that grows */ +.lib-command > .who { flex-basis: 240px; } +.lib-command .lib-commanddesc { font-size: 12px; line-height: 1.45; color: var(--fg); white-space: normal; overflow-wrap: anywhere; margin-top: 1px; } +.lib-commandedit .lib-commanddescin, .lib-commandedit .lib-commandprompt { width: 100%; box-sizing: border-box; resize: none; font: inherit; font-size: 12.5px; line-height: 1.45; } +.lib-commandedit .lib-commandprompt { max-height: 40vh; overflow-y: auto; } +.lib-commandedit .hint:empty { display: none; } /* a chip whose agent has the item whatever is ticked (it reads ~/.agents/skills itself, #595): lit, as it has it, with a lock on its diff --git a/internal/gui/library.go b/internal/gui/library.go index 59079053b..afdbe6d83 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -702,6 +702,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { Env library.EnvVar // a variable saved // a subagent saved (#2283) Subagent library.Subagent + Command library.Command Agent string // the agent whose own skill is in the library's way App string // the app the MCP hub is added to (servers/hub-open) Note string // what the MCP router says of itself (servers/hub-note), or a skill's note (skills/note) @@ -810,6 +811,12 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.SubagentAgentsSet(in.Name, in.Agents) case "subagents/remove": res, err = library.RemoveSubagents([]string{in.Name}) + case "commands/save": + res, err = library.SaveCommand(in.Old, in.Command) + case "commands/agents": + res, err = library.CommandAgentsSet(in.Name, in.Agents) + case "commands/remove": + res, err = library.RemoveCommands([]string{in.Name}) case "subagents/import": res, err = library.ImportSubagents(in.Source, in.Paths, in.Agents) case "skills/install": diff --git a/internal/gui/tests/library-commands.test.cjs b/internal/gui/tests/library-commands.test.cjs new file mode 100644 index 000000000..ce741cdd9 --- /dev/null +++ b/internal/gui/tests/library-commands.test.cjs @@ -0,0 +1,263 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// miantiao_me on X: Slash commands, a Library tab after Subagents. A slash +// command (a name, a description, a prompt with $ARGUMENTS and $1, $2…) +// is kept once and given to agents with the chips every other tab has. +// Its row shows /name and what it is for, wrapped. Asides say which +// agents it is given to take only $ARGUMENTS (so a command using $1 isn't +// written for them) and which agents magpie can't write one for: Codex, +// which reads custom prompts no more, and an agent in WSL. Their chips +// are greyed, say why, and post nothing. A row's chip posts +// commands/agents. Add opens the editor with every agent that can take +// one picked: the prompt's Enter is a new line, not a save; an input +// method's Enter saves nothing; a hint names the agents picked that take +// only $ARGUMENTS while the prompt uses $1; a leading / on the name is +// dropped; Save posts commands/save. A row opens it again, and Remove +// asks first, then posts commands/remove. +// At 420 and 1100 wide in en, zh, zh-TW, ja and de: no sideways scroll, +// and what each click pressed stays where it was on the screen. +// No backend: the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { strings } = require("./strings.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/mian"; +const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more }); +const LONG = "审阅指定文件或目录里改动过的代码,只报告真正的 bug:逻辑错误、边界条件、并发问题和资源泄漏;不评论代码风格,也不提出与本次改动无关的重构建议。"; +const cmd = (name, description, prompt, agents) => ({ name, description, prompt, agents }); +const WSL = "claude@wsl:Ubuntu"; +const COMMAND_AGENTS = [ + { id: "claude", dir: `${HOME}/.claude/commands`, args: true }, + { id: "codex", no: "Codex reads custom prompts no more: its skills took their place" }, + { id: "gemini", dir: `${HOME}/.gemini/commands` }, + { id: "opencode", dir: `${HOME}/.config/opencode/commands`, args: true }, + { id: WSL, wsl: true, no: "magpie gives no slash commands to an agent in WSL yet" }, +]; +const lib = (commands) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("claude", "Claude Code"), agent("codex", "Codex"), agent("gemini", "Gemini CLI"), agent("opencode", "OpenCode"), agent(WSL, "Claude Code (Ubuntu)")], + instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [], problems: [], + hooks: [], hookAgents: [], subagents: [], subagentAgents: [], commands, commandAgents: COMMAND_AGENTS, +}); + +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.commands)); + 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 === "commands/agents") state.commands = state.commands.map((x) => (x.name === body.name ? { ...x, agents: body.agents } : x)); + if (what === "commands/save") state.commands = [...state.commands.filter((x) => x.name !== body.old), body.command]; + if (what === "commands/remove") state.commands = state.commands.filter((x) => x.name !== body.name); + return json({ ...lib(state.commands), 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-command, #view-library .lib-aside, #view-library .lib-tabs, #modal .lib-commandedit *")) { + 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 Slash commands tab", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + I18N = strings().I18N; // i18n.js's and the plugins' + 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 = { commands: [cmd("review", LONG, "Review $1 for bugs.\n\nFocus: $ARGUMENTS", ["claude", "gemini"])] }; + 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", "commands"); } 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-command").first().waitFor(); + return { ctx, page }; + }; + const wrapped = async (page, width) => { + const r = page.locator("#view-library .lib-command").first(); + const fit = await r.locator(".lib-commanddesc").evaluate((e) => ({ clipped: e.scrollWidth > e.clientWidth + 1 || e.scrollHeight > e.clientHeight + 1, lines: Math.round(e.getBoundingClientRect().height / parseFloat(getComputedStyle(e).lineHeight)) })); + assert.equal(fit.clipped, false, `the description is cut off at ${width}`); + assert(fit.lines >= 2, `the description isn't wrapped at ${width}: ${fit.lines} line`); + const gap = await r.evaluate((x) => Math.abs(x.firstElementChild.getBoundingClientRect().top - x.querySelector(".name").getBoundingClientRect().top)); + assert(gap < 12, `the name is ${Math.round(gap)}px off its glyph at ${width}`); + assert.deepEqual(await sideways(page), [], `sideways scroll with the list at ${width}`); + }; + + // 1100 wide in a window of its own: the list, and the editor + { + const { ctx, page } = await open(1100); + await wrapped(page, 1100); + await press(page, page.locator("#view-library .lib-command").first()); + await page.locator("#modal .lib-commandedit").waitFor(); + await settled(page); + assert.deepEqual(await sideways(page), [], "sideways scroll in the editor at 1100"); + await ctx.close(); + } + + const { ctx, page } = await open(420); + const v = page.locator("#view-library"); + const row = (name) => v.locator(".lib-command").filter({ has: page.locator(".name", { hasText: new RegExp("^/" + name + "$") }) }); + const agentsOf = (name) => state.commands.find((s) => s.name === name)?.agents; + + // the tab, with its count, between Subagents and Claude plugins + const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim()); + const at = tabs.indexOf(w("Slash commands") + " · 1"); + assert(at > 0, tabs.join("|")); + assert.deepEqual(tabs.slice(at - 1, at + 2), [w("Subagents"), w("Slash commands") + " · 1", w("Claude plugins")]); + assert.equal((await row("review").locator(".lib-commanddesc").textContent()).trim(), LONG); + await wrapped(page, 420); + // Gemini takes only $ARGUMENTS, and review uses $1 + await v.locator(".lib-commands-noargs").filter({ hasText: w("{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.", { agents: "Gemini CLI" }) }).waitFor(); + await v.locator(".lib-commands-no").filter({ hasText: w("magpie can't give slash commands to {agents}: their chips are greyed, and say why.", { agents: "Codex, Claude Code (Ubuntu)" }) }).waitFor(); + + // Codex and the agent in WSL: greyed, say why, and a click posts nothing + const codex = row("review").locator('.lib-ag[data-agent="codex"]'); + assert.equal(await codex.getAttribute("aria-disabled"), "true"); + assert.equal(await codex.getAttribute("title"), w("Codex reads custom prompts no more: its skills took their place")); + const wsl = row("review").locator(`.lib-ag[data-agent="${WSL}"]`); + assert.equal(await wsl.getAttribute("aria-disabled"), "true"); + assert.equal(await wsl.getAttribute("title"), w("magpie gives slash commands only to agents on this computer, not yet to {agent} in WSL", { agent: "Claude Code (Ubuntu)" })); + await press(page, codex); + await press(page, wsl); + await page.waitForTimeout(150); + assert.deepEqual(posts, [], "a greyed chip posted"); + + // a row's chip gives it to OpenCode + await press(page, row("review").locator('.lib-ag[data-agent="opencode"]')); + await page.waitForFunction(() => document.querySelector('#view-library .lib-command .lib-ag[data-agent="opencode"][aria-pressed="true"]')); + await page.waitForTimeout(200); + assert.deepEqual(posts.shift(), { what: "commands/agents", body: { name: "review", agents: ["claude", "gemini", "opencode"] } }); + assert.deepEqual(agentsOf("review"), ["claude", "gemini", "opencode"]); + + // Add: the editor, every agent that can take it picked + await press(page, v.locator(".after-list button")); + const ed = page.locator("#modal .lib-commandedit"); + await ed.waitFor(); + await settled(page); + assert.equal(await page.locator("#modal select").count(), 0, "a native