diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 591045050..748b970fe 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -19,7 +19,7 @@ Pi's extensions and packages. | library.json | `Library` holds the instruction sets, the MCP servers, the skills, the projects, skill groups and copy settings. `Applied` records what magpie last wrote into each agent, so it only ever takes away its own. The instruction texts and skill folders live under `Dir` (`library/` in magpie's config folder). | [`library.go`](../../internal/library/library.go) | | A Remote magpie's skills and prompts | A Remote magpie provider's editor has a switch, Use its skills and prompts (`borrowOn` in library.json, `SetBorrow`; KoiLx0 on X: manage them once on the remote machine). The remote serves its Library at `GET /v1/magpie/library` (`gateway.SharedLibrary` = `library.Shared`, to `local` or `sharedWith` callers; a held key is refused; no MCP servers, which the MCP switch covers; borrowed items are never passed on). `keepBorrowed` (10 minutes, and once on switching on) fetches it with the provider's key (`provider.RemoteLibrary`) and `Borrow` adds each skill and each instruction set as `remote--`, recording a hash of what it wrote (`Borrowed`). It only ever changes what still matches that hash: a skill or set of the user's by the same name, one the user edited, and one the user removed after it was taken stay as they are (`Kept`, shown under the switch); an update or a drop moves the old copy to the backups; switching off takes out what is unchanged. The first set becomes the active one only when nothing is active. `Collect`/`Put` (sync backups) still carry borrowed items as ordinary ones. | [`borrow.go`](../../internal/library/borrow.go), [`remote_library.go`](../../internal/provider/remote_library.go), `TestBorrowRemoteLibrary` | | One change | `change` locks the library, loads it, applies one edit, saves, syncs every agent and saves again. Every exported mutation (`SaveServer`, `InstallSkills`, `SetSkillHow` and the rest) goes through it. One change runs at a time, whether from the page or the CLI. | [`library.go`](../../internal/library/library.go) | -| Targets | `Targets` lists the detected agents (`agent.Detected`), a folder an agent shares with its vendor's other app when only that app is here (`agent.SharedHere`: the Cursor editor's `~/.cursor`, whose `mcp.json` and skills it reads, listed as Cursor; `TestCursorEditorAloneKeepsItsLibraryRow`), plus apps like Claude Desktop, with where each keeps its instructions file (and an `Override` it reads instead), its MCP file and its skills folder. An agent whose CLI is gone (`CLIMissing`: an uninstall that left the folder behind, #2177, #2254) is no target: it is given nothing it can't read. One that isn't a target but still has skills, servers or hooks magpie gave it (in `Applied`, or listed in an item's `Agents`) is held (`held`, a `Target` with `Gone`): a sync takes edits from its copies and then only takes out of it (`syncSkills`, `syncMCP` and `syncHooks` give a gone target nothing new), and `Read` lists it with `gone: true` while it has any. The page shows a gone agent's chip only on the rows of what it has, lit, so a click takes it out (`withGone` in plugins/library/client.js), leaves it out of All, the per-agent How sheet and every picker, and lists it in By agent as Not installed here with Turn all on off (@jiahao_jayden on X: an uninstalled WorkBuddy was on every skill's row; `TestGoneAgentListedToTakeOut`, `library-gone-agents.test.cjs`). On a Mac WorkBuddy and WorkBuddy AI are detected by their apps' bundle ids (`com.tencent.workbuddy.mac`, `com.workbuddy.workbuddy-ai`, `macBundle`), not by `~/.workbuddy`, which an uninstall leaves and magpie itself writes into (`TestWorkBuddyOnMacIsItsApp`); off a Mac the folder still counts. `everyTarget` keeps it for the guards that refuse an agent's own places: a project folder whose skills folder or MCP file is the agent's, and an instruction set kept in its instructions file. An agent in a running WSL distro has its places under the distro's home (`wslTargetOf`): Claude Code, Codex, Pi, OmO, Gemini CLI, Antigravity CLI, Crush, Cline, CodeBuddy Code, Kimi Code and Goose each by its own rule, never reading this machine's variables (Kimi Code's and Goose's shared `~/.agents/skills` there isn't given), Pi's MCP file chosen by `piMCP` as on this machine from the version the distro's `pi --version` gave its probe (`InstalledVersion`) and the distro's npm folders (`wslPiRoots`; leokon on Discord: only the Windows Pi was offered MCP servers, `TestWSLPiMCP`, `TestWSLMCPSiblings`), and every agent that keeps all of them in its own folder (Hermes Agent, omp, OpenCode, Droid and the rest of `ownFolder`, #1323) by the same rule as on this machine, its MCP file marked as WSL's so a Windows program isn't given to it. A place below a folder the distro has as a link is opened where the link leads (`wslOpen`, agent-wiring's WSL folders that are links, #4502); a link the distro couldn't resolve gives that agent one `wsl` problem and nothing is written to it (`TestWSLFolderIsALinkToC`, `TestWSLFolderLinkUnresolved`). An agent a plugin adds (`a.Plugin`) has the places its plugin's `agent.library` names (`pluginTarget`): an instructions file, an MCP file in one of `agentplug.MCPFormats` (each the `mcpFormat` of the agent it is named for, `pluginMCP`) and a skills folder, `~` and `$VAR` expanded as its config is; one that names none is no target. Before, a plugin's agent got models and keys only. Every built-in agent is a target or is in `noLibrary` with why: OpenBot was added with neither and was in no picker (SSNQT on X), so `TestEveryAgentInLibrary` fails a new agent until it gets one (34 were in no picker when it landed, listed there under #5897). | [`targets.go`](../../internal/library/targets.go) | +| Targets | `Targets` lists the detected agents (`agent.Detected`), a folder an agent shares with its vendor's other app when only that app is here (`agent.SharedHere`: the Cursor editor's `~/.cursor`, whose `mcp.json` and skills it reads, listed as Cursor; `TestCursorEditorAloneKeepsItsLibraryRow`), plus apps like Claude Desktop, with where each keeps its instructions file (and an `Override` it reads instead), its MCP file and its skills folder. An agent whose CLI is gone (`CLIMissing`: an uninstall that left the folder behind, #2177, #2254) is no target: it is given nothing it can't read. One that isn't a target but still has skills, servers or hooks magpie gave it (in `Applied`, or listed in an item's `Agents`) is held (`held`, a `Target` with `Gone`): a sync takes edits from its copies and then only takes out of it (`syncSkills`, `syncMCP` and `syncHooks` give a gone target nothing new), and `Read` lists it with `gone: true` while it has any. On a row, an agent's profiles (`hermes#name`, `omp#name`, `claude#name`, `qwenpaw#id`, WSL ones included) are one chip with a count, when an agent has more than one (`profileChip` in plugins/library/client.js, Yanzhongixuy on X: about twenty identical Hermes glyphs on every skill row); a click opens the app menu to pick profiles singly, and All still means every profile (`library-profile-chip.test.cjs`). The page shows a gone agent's chip only on the rows of what it has, lit, so a click takes it out (`withGone` in plugins/library/client.js), leaves it out of All, the per-agent How sheet and every picker, and lists it in By agent as Not installed here with Turn all on off (@jiahao_jayden on X: an uninstalled WorkBuddy was on every skill's row; `TestGoneAgentListedToTakeOut`, `library-gone-agents.test.cjs`). On a Mac WorkBuddy and WorkBuddy AI are detected by their apps' bundle ids (`com.tencent.workbuddy.mac`, `com.workbuddy.workbuddy-ai`, `macBundle`), not by `~/.workbuddy`, which an uninstall leaves and magpie itself writes into (`TestWorkBuddyOnMacIsItsApp`); off a Mac the folder still counts. `everyTarget` keeps it for the guards that refuse an agent's own places: a project folder whose skills folder or MCP file is the agent's, and an instruction set kept in its instructions file. An agent in a running WSL distro has its places under the distro's home (`wslTargetOf`): Claude Code, Codex, Pi, OmO, Gemini CLI, Antigravity CLI, Crush, Cline, CodeBuddy Code, Kimi Code and Goose each by its own rule, never reading this machine's variables (Kimi Code's and Goose's shared `~/.agents/skills` there isn't given), Pi's MCP file chosen by `piMCP` as on this machine from the version the distro's `pi --version` gave its probe (`InstalledVersion`) and the distro's npm folders (`wslPiRoots`; leokon on Discord: only the Windows Pi was offered MCP servers, `TestWSLPiMCP`, `TestWSLMCPSiblings`), and every agent that keeps all of them in its own folder (Hermes Agent, omp, OpenCode, Droid and the rest of `ownFolder`, #1323) by the same rule as on this machine, its MCP file marked as WSL's so a Windows program isn't given to it. A place below a folder the distro has as a link is opened where the link leads (`wslOpen`, agent-wiring's WSL folders that are links, #4502); a link the distro couldn't resolve gives that agent one `wsl` problem and nothing is written to it (`TestWSLFolderIsALinkToC`, `TestWSLFolderLinkUnresolved`). An agent a plugin adds (`a.Plugin`) has the places its plugin's `agent.library` names (`pluginTarget`): an instructions file, an MCP file in one of `agentplug.MCPFormats` (each the `mcpFormat` of the agent it is named for, `pluginMCP`) and a skills folder, `~` and `$VAR` expanded as its config is; one that names none is no target. Before, a plugin's agent got models and keys only. Every built-in agent is a target or is in `noLibrary` with why: OpenBot was added with neither and was in no picker (SSNQT on X), so `TestEveryAgentInLibrary` fails a new agent until it gets one (34 were in no picker when it landed, listed there under #5897). | [`targets.go`](../../internal/library/targets.go) | | Stopped WSL distro | A stopped distro's agents are no targets: opening their files would start the distro, or the read fails (#3896). While a distro runs, `keepShape` keeps each agent's places and what its MCP file takes in `wsl.json` (`agent.WSLKeep`, key `library:`). While it is stopped, `Read` lists its agents from that (`asleepView`, `asleep: `), ticks as library.json has them; one magpie never saw there is listed only on the rows that name it, as `unseen`, its ticks not shown (cybercaius on Discord: the MCP page knew a distro's agents only once WSL had started). A tick on a stopped agent is kept in library.json as any is (`Takes` accepts one with a known shape; `serversAgents` judges it by `shape.reaches`), nothing is written and nothing in the distro runs; `Woken`, from `KeepLinked`'s loop (and the app's start-up sync), syncs when a distro the library names is seen go from stopped to running (`wsl.exe -l --running`, which starts nothing). The page greys a stopped agent's chip, says so in its tooltip and in one line per distro (`.lib-asleep`); an unseen chip is `aria-disabled` and kept by every click on its row (`keptOf`). The CLI says the same on stderr (`AsleepIn`). Queued, not a start button: a start costs the memory #3896 is about, and All or a bulk tick would start every distro. The Instructions page lists them too (`asleepInstructions`, #4182), at the instructions file the shape keeps, switched on as library.json has them, with what each gets besides (magpie's own folder) and nothing read from the file: its own lines and edits aren't counted then, and its path is plain text, not a reveal, which would open the distro. One switched on whose file magpie never saw is listed as `unseen`, its switch greyed out and kept by every other switch; before, a switch on the page sent the agents without the stopped distro's and took them off. A switch on one is written by `Woken`, which watches a distro named in `Instructions.Agents`, or whose agent still has magpie's part (`Applied.Instructions`), so one switched off has it taken out. The Hooks page lists the stopped agents with a shape as it does while the distro runs (`hooksView`, #4237): greyed, since magpie gives no agent in WSL hooks yet (`wslNoHooks`), and a hook given one says so; there is nothing for `Woken` to write. So does the Subagents page for the kinds it lists (`subagentsView`, `wslNoSubagents`, #4238). | [`wsl_asleep.go`](../../internal/library/wsl_asleep.go), [`targets.go`](../../internal/library/targets.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | | Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first (`sweepShared`, then `syncShared` for the Put skills in setting), so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) | | Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid, Cline and DeepSeek Harness (which reads it, and `.dsh/skills`, at the nearest folder up with a `.git`, else where it runs: a project folder inside a repository but not at its root doesn't reach it, #5172). A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape, DeepSeek Harness's MCP, whose servers are rows in its profiles' patch layers with no project layer) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away. Nothing of magpie's goes into the project's git: what it placed is listed in the repository's own `info/exclude` (`writeExclude`, one block per project between `excludeBegin(dir)` and `ignoreEnd`, read by every worktree, never committed), and the project's `.gitignore` is left as it is (a block an older magpie wrote there is taken out, `TestProjectKeptOutOfGitByExclude`). A folder outside git gets no ignore file; once it is `git init`ed, `treesChanged` sees no block and the next `KeepLinked` writes it (`TestProjectOutsideGit`). A project is the global set ± its own (WhyULose0 on X): `ServersOff` and `SkillsOff` turn a global server or skill off in the project for some agents (`ProjectServerOff`, `ProjectSkillsOff`; `POST /api/library/projects/server-off` and `skill-off` with `dir`, `name`/`names`, `agents`; none gives it back). Each is done the way the agent reads it for a folder (`project_scope.go`): Claude Code's record of the project in `~/.claude.json` (`projects[
]`, `claudeRoot`) gets the name in `disabledMcpServers`, where magpie takes out only names it added (`Claude.Off`); Codex gets `[mcp_servers.] enabled = false` in the project's `.codex/config.toml`, only for a server in its own config (`CodexOff`); a skill is `skillOverrides. = "off"` in the project's `.claude/settings.local.json` (`Overrides`), a value the user set there is theirs (`TestProjectServerOff`, `TestProjectSkillOff`). Only those (`ProjectOffAgents`, `ProjectSkillOffAgents`) can take an off, and a skill an agent reaches through the [skill router](skill-router.md) can't; the card shows a global agent that can't as always on, with why. With the [MCP router](mcp-router.md) on, a project that adds or turns off a server the router serves gives Claude Code and Codex their own hub entry, `~` (`projectHubs`): Claude Code's in its record's `mcpServers` (local scope), Codex's in the project's `.codex/config.toml`; the server added isn't written into `.mcp.json` then (`TestProjectSetThroughRouter`). Claude Code keys its record by the repository's main top folder, so a project in a subfolder turns its offs on for the whole repository. A git worktree of the project's repository follows the project (`treeDirs`, `Trees`): the project's folder in each worktree gets the same skills, servers and offs, and is let go when the worktree is removed; `KeepLinked` checks for new ones (`keepProjectTrees`, `TestProjectWorktreeFollows`). `magpie library project …` (#5193, [`library_project_cli.go`](../../internal/cli/library_project_cli.go)) adds and removes a project and its skills through the same calls as the page (`AddProject`, `RemoveProject`, `ProjectSkills`, `ProjectSkill`, `ProjectCopy`); a skill added with no `agents=` goes to the agents the page's Skills menu picks (those the project's skills are for already, else every agent here with a project skills folder), and one not placed exits 1 with why (`TestLibraryProjectCmd`). A project card's Skills menu lists the skills by source as the Library does (`skillGroups(true)`, whatever sort the list has; one group is the flat list), a heading over each that ticks or unticks the whole group (`group` in `openProtoMenu`, half-ticked while some are in; Elorynth on X, `project-skills-groups.test.cjs`). | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`project_scope.go`](../../internal/library/project_scope.go), [`project_git.go`](../../internal/library/project_git.go) | diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 565c851e4..061c5e723 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -284,17 +284,29 @@ magpie.plugin("library", (ctx) => { function agentChips(all, on, onChange, opts = {}) { on ||= []; const box = el("div", "lib-agents"); - box.style.setProperty("--lib-agent-count", all.length); + // a row's profiles of one agent (hermes#coder, omp#work…) are one chip + // that opens a menu of them, not one icon each (Yanzhongixuy on X: 20 + // Hermes glyphs in a row) + const fams = onChange.rows ? profileFamilies(all) : new Map(); + const shown = [], made = new Set(); + for (const a of all) { + const f = familyOf(a.id); + if (!fams.has(f)) shown.push({ a }); + else if (!made.has(f)) { made.add(f); shown.push({ family: f, members: fams.get(f) }); } + } + box.style.setProperty("--lib-agent-count", shown.length); // the row it is put in says so (.with-agents), for its name's room: // Safari before 15.4 has no :has(). Every caller appends it at once. queueMicrotask(() => box.parentElement?.classList.contains("lib-row") && box.parentElement.classList.add("with-agents")); - for (const [i, a] of all.entries()) { + for (const [i, g] of shown.entries()) { + if (g.family) { box.append(profileChip(g, i, shown.length, all, on, onChange, opts)); continue; } + const a = g.a; const always = opts.always?.(a) || ""; const has = on.includes(a.id) || !!always; const c = el("button", "lib-ag" + (has ? " on" : "") + (always ? " always" : "")); c.dataset.agent = a.id; // how many chips are to its right, how far it slides into the hand - c.style.setProperty("--k", all.length - 1 - i); + c.style.setProperty("--k", shown.length - 1 - i); c.append(agentIcon(a.icon)); if (opts.names) c.append(el("span", "n", a.name)); const problem = !always && opts.problems?.[a.id]; @@ -330,10 +342,76 @@ magpie.plugin("library", (ctx) => { }; box.append(c); } - if (opts.all) allChip(box, all, on, onChange); + if (opts.all) allChip(box, all, on, onChange, opts); return box; } + // The agent a profile belongs to: hermes#coder and hermes are Hermes, + // omp#work@wsl:Ubuntu and omp@wsl:Ubuntu are omp in that distro. + const familyOf = (id) => id.replace(/#[^@]*/, ""); + // Three or more of an agent's own and its profiles are one chip; fewer + // fit the row as they are. + function profileFamilies(all) { + const by = new Map(); + for (const a of all) { + const f = familyOf(a.id); + if (!by.has(f)) by.set(f, []); + by.get(f).push(a); + } + for (const [f, ms] of [...by]) if (ms.length < 3 || !ms.some((a) => a.id !== f)) by.delete(f); + return by; + } + // The agents a chip stands for: its own, or the profiles of a group. + const idsOf = (x) => x.dataset.members ? x.dataset.members.split("\t") : x.dataset.agent ? [x.dataset.agent] : []; + const isChip = (x) => !!(x.dataset.agent || x.dataset.members); + const memberOn = (x) => x.dataset.members ? (x.dataset.lit ? x.dataset.lit.split("\t") : []) : x.getAttribute("aria-pressed") === "true" ? [x.dataset.agent] : []; + // A group's chip: lit when any profile has the item, dashed while only + // some do, with how many in the corner. + function paintProfiles(c, lit) { + const n = lit.length, total = idsOf(c).length - (c.dataset.fixed ? c.dataset.fixed.split("\t").length : 0); + c.dataset.lit = lit.join("\t"); + const has = n > 0 || !!c.dataset.fixed; + c.classList.toggle("on", has); + c.classList.toggle("some", n > 0 && n < total); + c.setAttribute("aria-pressed", has ? "true" : "false"); + const k = c.querySelector(":scope > .cnt"); + if (k) k.textContent = n + (c.dataset.fixed ? c.dataset.fixed.split("\t").length : 0) || ""; + } + function profileChip(g, i, count, all, on, onChange, opts) { + const ms = g.members, main = ms.find((a) => a.id === g.family) || ms[0]; + const always = new Map(ms.map((a) => [a.id, opts.always?.(a) || ""]).filter(([, w]) => w)); + const fixed = ms.filter((a) => always.has(a.id) || a.unseen).map((a) => a.id); + const lit = ms.filter((a) => on.includes(a.id) && !fixed.includes(a.id)).map((a) => a.id); + const name = main.id === g.family ? main.name : main.name.split(" · ")[0]; + const c = el("button", "lib-ag profiles"); + c.dataset.members = ms.map((a) => a.id).join("\t"); + c.dataset.fixed = fixed.join("\t"); + c.style.setProperty("--k", count - 1 - i); + c.append(agentIcon(main.icon)); + if (opts.names) c.append(el("span", "n", name)); + c.append(el("span", "cnt")); + paintProfiles(c, lit); + const problems = ms.filter((a) => opts.problems?.[a.id]); + if (problems.length) c.classList.add("warn"); + c.setAttribute("aria-haspopup", "menu"); + c.title = problems.length ? name + ": " + problems.map((a) => a.name + ": " + opts.problems[a.id]).join("\n") : name; + c.onclick = (e) => { + e.stopPropagation(); + const me = e.currentTarget; + const pick = ms.filter((a) => !fixed.includes(a.id) && !opts.blocked?.(a)); + const stuck = ms.filter((a) => !fixed.includes(a.id) && opts.blocked?.(a) && memberOn(me).includes(a.id)).map((a) => a.id); + const menu = [{ v: "\x00" + g.family, group: pick.map((a) => a.id), name, literalName: true, note: "" }, + ...pick.map((a) => ({ v: a.id, name: a.name, literalName: true, note: "", title: opts.problems?.[a.id] || "" }))]; + openProtoMenu(me, menu, memberOn(me).filter((id) => !stuck.includes(id)), (next) => { + const now = [...stuck, ...next.filter((id) => pick.some((a) => a.id === id))]; + paintProfiles(me, now); + const litAll = litOf(me.parentElement); + onChange([...keptOf(me.parentElement, all, on), ...litAll], me); + }, name, "", "left", true); + }; + return c; + } + // cannot says a chip's agent can't be given the item, or has it whatever // is ticked: a click says why rather than switching it const cannot = (c) => c.getAttribute("aria-disabled") === "true"; @@ -341,13 +419,14 @@ magpie.plugin("library", (ctx) => { // The agents a row's chips have lit by a click: not one lit because it // has the item whatever is ticked. function litOf(box) { - return [...box.children].filter((x) => x.dataset.agent && !x.classList.contains("always") && !x.classList.contains("unseen") && x.getAttribute("aria-pressed") === "true").map((x) => x.dataset.agent); + return [...box.children].filter((x) => isChip(x) && !x.classList.contains("always") && !x.classList.contains("unseen")).flatMap(memberOn); } // What a click leaves as it was: an agent not shown, one that has the // item whatever is ticked, whose chip can't be clicked, and one in a // stopped distro magpie can't show the ticks of (unseen). function keptOf(box, all, on) { - const fixed = [...box.children].filter((x) => x.classList.contains("always") || x.classList.contains("unseen")).map((x) => x.dataset.agent); + const fixed = [...box.children].filter((x) => x.classList.contains("always") || x.classList.contains("unseen")).map((x) => x.dataset.agent) + .concat([...box.children].flatMap((x) => x.dataset.fixed ? x.dataset.fixed.split("\t") : [])); return on.filter((id) => !all.some((x) => x.id === id) || fixed.includes(id)); } @@ -358,8 +437,8 @@ magpie.plugin("library", (ctx) => { // choose the agents before an item is added (installing skills, adding or // bringing in servers) have it too (#1531): most start with every agent // lit, and one agent alone was a click on each of the others. - function allChip(box, all, on, onChange) { - const can = [...box.children].filter((c) => !cannot(c) && !c.classList.contains("gone")).map((c) => c.dataset.agent); + function allChip(box, all, on, onChange, opts = {}) { + const can = [...box.children].filter((c) => !cannot(c) && !c.classList.contains("gone")).flatMap((c) => c.dataset.members ? idsOf(c).filter((id) => !c.dataset.fixed?.split("\t").includes(id) && !opts.blocked?.(all.find((a) => a.id === id))) : [c.dataset.agent]); if (can.length < 2) return; const c = el("button", "lib-ag all", t("All")); c.dataset.all = "1"; @@ -378,7 +457,9 @@ magpie.plugin("library", (ctx) => { const c = box.querySelector(":scope > .lib-ag.all"); if (!c) return; const can = [...box.children].filter((x) => x.dataset.agent && !cannot(x) && !x.classList.contains("gone")); - const n = can.length, full = can.every((x) => x.getAttribute("aria-pressed") === "true"); + const groups = [...box.children].filter((x) => x.dataset.members); + const n = can.length + groups.reduce((k, g) => k + idsOf(g).length - (g.dataset.fixed ? g.dataset.fixed.split("\t").length : 0), 0); + const full = can.every((x) => x.getAttribute("aria-pressed") === "true") && groups.every((g) => g.dataset.lit.split("\t").filter(Boolean).length === idsOf(g).length - (g.dataset.fixed ? g.dataset.fixed.split("\t").length : 0)); c.classList.toggle("on", full); c.setAttribute("aria-pressed", full ? "true" : "false"); c.title = full ? t("Every agent that can take it has it — click to take it from all {n}", { n }) : t("Give it to all {n} agents that can take it", { n }); @@ -396,10 +477,14 @@ magpie.plugin("library", (ctx) => { const writing = new Map(); // path + name → { list, name, want, box } while a row's agents are written let refused = 0; // when a row's write last failed, whose error another row's "Written" doesn't cover function chipsChange(path, name, list, rowOf) { - return async (next, c) => { + const go = async (next, c) => { // All lights or darkens every chip of the row, a chip only itself const every = !!c.dataset.all; - for (const x of every ? [...c.parentElement.children].filter((y) => y.dataset.agent && !y.classList.contains("always")) : [c]) { + for (const x of every ? [...c.parentElement.children].filter((y) => isChip(y) && !y.classList.contains("always")) : [c]) { + if (x.dataset.members) { + paintProfiles(x, idsOf(x).filter((id) => next.includes(id) && !x.dataset.fixed?.split("\t").includes(id))); + continue; + } const on = next.includes(x.dataset.agent); x.classList.toggle("on", on); if (on || x === c) x.classList.remove("via"); @@ -437,12 +522,14 @@ magpie.plugin("library", (ctx) => { if (!me.box.isConnected) { if (failed) render(); } // drawn again meanwhile, from the clicks else if (fresh && !morphChips(me.box, fresh)) me.box.replaceWith(fresh); }; + go.rows = true; // its chips are a row's: an agent's profiles go into one + return go; } // 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 shown = [...me.box.children].filter((x) => x.dataset.agent && !cannot(x)).map((x) => x.dataset.agent); + 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)); if (!bad.length) { @@ -486,9 +573,11 @@ magpie.plugin("library", (ctx) => { } function morphChips(box, fresh) { const was = [...box.children], now = [...fresh.children]; - if (was.length !== now.length || was.some((c, i) => c.dataset.agent !== now[i].dataset.agent)) return false; + const key = (c) => c.dataset.agent || c.dataset.members; + if (was.length !== now.length || was.some((c, i) => key(c) !== key(now[i]))) return false; was.forEach((c, i) => { const n = now[i]; + if (n.dataset.members) { c.dataset.lit = n.dataset.lit; c.dataset.fixed = n.dataset.fixed; c.querySelector(":scope > .cnt")?.replaceWith(n.querySelector(":scope > .cnt").cloneNode(true)); } c.className = n.className; c.title = n.title; if (cannot(n)) c.setAttribute("aria-disabled", "true"); else c.removeAttribute("aria-disabled"); diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index 7fd23426b..5644276c7 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -919,3 +919,8 @@ input.lib-memq:focus, input.lib-memtags:focus, input.lib-memwhy:focus { border-c .lib-acct-act { display: flex; gap: 8px; } @media (hover: hover) and (pointer: fine) { .lib-acct:not(.on):hover { background: var(--hover, var(--accent-soft)); } } @media (prefers-reduced-motion: reduce) { .lib-acct, .lib-acct-dot { transition: none; } } + +/* an agent's profiles as one chip: how many have the item, in the corner */ +.lib-ag.profiles .cnt { position: absolute; right: -3px; bottom: -3px; min-width: 12px; height: 12px; padding: 0 3px; border-radius: 6px; box-sizing: border-box; background: var(--card); border: 1px solid var(--line); color: var(--fg-2); font-size: 9px; line-height: 10px; text-align: center; font-variant-numeric: tabular-nums; pointer-events: none; } +.lib-ag.profiles .cnt:empty { display: none; } +.lib-ag.profiles.open { background: var(--pill); } diff --git a/internal/gui/tests/library-profile-chip.test.cjs b/internal/gui/tests/library-profile-chip.test.cjs new file mode 100644 index 000000000..dcdb0fd01 --- /dev/null +++ b/internal/gui/tests/library-profile-chip.test.cjs @@ -0,0 +1,103 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// An agent's profiles (hermes#coder, hermes#work, ...) are one chip in a +// row, not an icon each (Yanzhongixuy on X: twenty Hermes glyphs in every +// skill row). The chip opens an app menu of the profiles, ticked as the row +// has them, and a tick writes the whole list. Agents with fewer than three +// entries keep their own chips. English, Chinese, Traditional Chinese, +// Japanese and German; 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 assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/me"; +const agent = (id, name, icon) => ({ id, name, icon, skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` }); +const AGENTS = [agent("claude", "Claude Code", "claudecode-color"), agent("hermes", "Hermes Agent", "hermes"), + ...["coder", "work", "play", "ops", "docs"].map((n) => agent("hermes#" + n, "Hermes · " + n, "hermes")), + agent("omp", "omp", "omp"), agent("omp#a", "omp · a", "omp")]; +const ALL = AGENTS.map((a) => a.id); + +const sent = []; +function server(lang, lib) { + return async (route) => { + const url = new URL(route.request().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); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/library/servers/agents") { sent.push(route.request().postDataJSON()); lib.servers[0].agents = route.request().postDataJSON().agents; return json(lib); } + if (url.pathname.startsWith("/api/")) return json({}); + if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + + +const lib = () => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: structuredClone(AGENTS), + instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], problems: [], skills: [], + servers: [{ name: "context7", transport: "stdio", command: "npx", args: ["-y", "@upstash/context7-mcp"], agents: ["claude", "hermes", "hermes#work"] }], +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": an agent's profiles are one chip with a menu", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + 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 () => { + sent.length = 0; + const ctx = await browser.newContext({ viewport: { width: 1000, height: 700 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, lib())); + try { + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const strip = page.locator("#view-library .lib-row > .lib-agents").first(); + await strip.locator(".lib-ag.profiles").waitFor(); + // claude, one Hermes chip, omp and omp#a as they were: 4 chips (+ All) + assert.equal(await strip.locator(".lib-ag[data-agent]").count(), 3); + assert.equal(await strip.locator(".lib-ag.profiles").count(), 1); + assert.equal(await strip.locator('.lib-ag[data-agent^="hermes"]').count(), 0); + const chip = strip.locator(".lib-ag.profiles"); + assert.equal(await chip.locator(".cnt").textContent(), "2"); + assert(await chip.evaluate((c) => c.classList.contains("on") && c.classList.contains("some"))); + await chip.click(); + const menu = page.locator(".proto-menu"); + await menu.waitFor(); + // the heading ticks all; then each of the six + assert.equal(await menu.locator(".pm-item").count(), 7); + assert.equal(await menu.locator('.pm-item.on').count(), 2); + await menu.locator(".pm-item", { hasText: "coder" }).click(); + await page.waitForFunction(() => document.querySelector(".lib-ag.profiles .cnt")?.textContent === "3"); + await page.waitForFunction(() => true); + await page.waitForTimeout(100); + assert.deepEqual([...sent.at(-1).agents].sort(), ["claude", "hermes", "hermes#coder", "hermes#work"].sort()); + // the heading takes them all + await menu.locator(".pm-group").click(); + await page.waitForFunction(() => document.querySelector(".lib-ag.profiles .cnt")?.textContent === "6"); + await page.waitForTimeout(100); + assert.deepEqual([...sent.at(-1).agents].sort(), ["claude", "hermes", "hermes#coder", "hermes#docs", "hermes#ops", "hermes#play", "hermes#work"].sort()); + assert(!(await chip.evaluate((c) => c.classList.contains("some")))); + assert.deepEqual(errors, []); + } finally { + await ctx.close(); + } + }); + } + }); +}