diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 147342251..7999b07c5 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -29,7 +29,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. ## Runtime path -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. 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). A row's agent chips start with All (`allChip` in `library.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). +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. 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 `library.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` and `syncHooks` 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. @@ -69,7 +69,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. ```sh go test -tags nogui ./internal/library -run 'TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionSets|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' go test -tags nogui ./internal/library -node --test internal/gui/tests/library-items.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-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/remove-found-skill.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 +node --test internal/gui/tests/library-items.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/remove-found-skill.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 ``` The package's `TestMain` runs in a home of its own (`testenv`), never the diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5064d0235..d0d09450c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3999,6 +3999,15 @@ const I18N = { "Find an event": "查找事件", "every agent, in its own name for it": "所有 Agent,各用自己的事件名", "Remove all {n} servers?": "删除全部 {n} 个服务器?", + "Remove…": "删除…", + "Remove {n}": "删除 {n} 个", + "Remove {n} skills?": "删除 {n} 个技能?", + "Remove {n} servers?": "删除 {n} 个服务器?", + "Remove {n} hooks?": "删除 {n} 个 Hook?", + "Take the skills picked out of the library": "从资源库中删除选中的技能", + "Take the servers picked out of the library": "从资源库中删除选中的服务器", + "Take the hooks picked out of the library": "从资源库中删除选中的 Hook", + "Not removed: {error}": "未能删除:{error}", "The servers magpie placed in {n} projects are taken away too.": "magpie 放进 {n} 个项目的这些服务器也会一并移除。", "magpie's sign-in to {n} of them is forgotten too.": "magpie 对其中 {n} 个服务器的登录也会一并清除。", "Servers your agents have that aren't in the library stay as they are.": "Agent 自己的、不在资源库中的服务器保持不变。", @@ -8437,6 +8446,15 @@ const I18N = { "Find an event": "搜尋事件", "every agent, in its own name for it": "所有 Agent,各用自己的事件名", "Remove all {n} servers?": "刪除全部 {n} 個伺服器?", + "Remove…": "刪除…", + "Remove {n}": "刪除 {n} 個", + "Remove {n} skills?": "刪除 {n} 個技能?", + "Remove {n} servers?": "刪除 {n} 個伺服器?", + "Remove {n} hooks?": "刪除 {n} 個 Hook?", + "Take the skills picked out of the library": "從資源庫中刪除選取的技能", + "Take the servers picked out of the library": "從資源庫中刪除選取的伺服器", + "Take the hooks picked out of the library": "從資源庫中刪除選取的 Hook", + "Not removed: {error}": "未能刪除:{error}", "The servers magpie placed in {n} projects are taken away too.": "magpie 放進 {n} 個專案的這些伺服器也會一併移除。", "magpie's sign-in to {n} of them is forgotten too.": "magpie 對其中 {n} 個伺服器的登入也會一併清除。", "Servers your agents have that aren't in the library stay as they are.": "Agent 自己的、不在資源庫中的伺服器保持不變。", @@ -12896,6 +12914,15 @@ const I18N = { "Find an event": "イベントを検索", "every agent, in its own name for it": "すべてのエージェント、それぞれの呼び名で", "Remove all {n} servers?": "{n} 個のサーバーをすべて削除しますか?", + "Remove…": "削除…", + "Remove {n}": "{n} 個を削除", + "Remove {n} skills?": "{n} 個のスキルを削除しますか?", + "Remove {n} servers?": "{n} 個のサーバーを削除しますか?", + "Remove {n} hooks?": "{n} 個のフックを削除しますか?", + "Take the skills picked out of the library": "選んだスキルをライブラリから削除", + "Take the servers picked out of the library": "選んだサーバーをライブラリから削除", + "Take the hooks picked out of the library": "選んだフックをライブラリから削除", + "Not removed: {error}": "削除できませんでした:{error}", "The servers magpie placed in {n} projects are taken away too.": "magpie が {n} 個のプロジェクトに置いたこれらのサーバーも外されます。", "magpie's sign-in to {n} of them is forgotten too.": "そのうち {n} 個のサーバーへの magpie のサインインも消去されます。", "Servers your agents have that aren't in the library stay as they are.": "エージェント自身の、ライブラリにないサーバーはそのまま残ります。", @@ -17357,6 +17384,15 @@ const I18N = { "Find an event": "Ereignis suchen", "every agent, in its own name for it": "jeder Agent, unter seinem eigenen Namen dafür", "Remove all {n} servers?": "Alle {n} Server entfernen?", + "Remove…": "Entfernen…", + "Remove {n}": "{n} entfernen", + "Remove {n} skills?": "{n} Skills entfernen?", + "Remove {n} servers?": "{n} Server entfernen?", + "Remove {n} hooks?": "{n} Hooks entfernen?", + "Take the skills picked out of the library": "Die ausgewählten Skills aus der Bibliothek entfernen", + "Take the servers picked out of the library": "Die ausgewählten Server aus der Bibliothek entfernen", + "Take the hooks picked out of the library": "Die ausgewählten Hooks aus der Bibliothek entfernen", + "Not removed: {error}": "Nicht entfernt: {error}", "The servers magpie placed in {n} projects are taken away too.": "Die Server, die magpie in {n} Projekte gelegt hat, werden ebenfalls entfernt.", "magpie's sign-in to {n} of them is forgotten too.": "magpies Anmeldung bei {n} von ihnen wird ebenfalls vergessen.", "Servers your agents have that aren't in the library stay as they are.": "Server Ihrer Agenten, die nicht in der Bibliothek sind, bleiben unverändert.", diff --git a/internal/gui/assets/library.css b/internal/gui/assets/library.css index 1659b635b..2503ccfd2 100644 --- a/internal/gui/assets/library.css +++ b/internal/gui/assets/library.css @@ -364,6 +364,8 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col /* every skill out of the library at once (#449): red from the start */ #view-library .row-head .lib-everyrm { color: var(--red); } #view-library .row-head .lib-everyrm:hover { background: var(--red-soft); } +.lib-pickbar .lib-pickrm { color: var(--red); } +.lib-pickbar .lib-pickrm:hover { background: var(--red-soft); } /* the market: servers and skills to add, each with its own picture */ .mk { display: flex; flex-direction: column; } @@ -564,6 +566,8 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-pickn { font-size: 12px; font-weight: 500; color: var(--fg); white-space: nowrap; } .lib-pickn.none { font-weight: 400; color: var(--faint); white-space: normal; } .lib-pickbar .lib-updall { height: 24px; padding: 0 9px; font-size: 12px; flex: none; } +/* one the bar's Remove left (#1852): why, in its line's place */ +.lib-row .sub.lib-pickerr { color: var(--red); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .lib-subhead > .lib-agents { margin-left: auto; } .lib-pickbar .lib-groupname { flex: 1 1 140px; min-width: 100px; max-width: 240px; margin: 0; } .lib-grouphead .lib-grouprename-in { height: 24px; margin: 0; max-width: 260px; font-weight: 500; } diff --git a/internal/gui/assets/library.js b/internal/gui/assets/library.js index 2ebcb85c7..0821f6927 100644 --- a/internal/gui/assets/library.js +++ b/internal/gui/assets/library.js @@ -2174,12 +2174,12 @@ if (!h) requestAnimationFrame(() => name.focus()); } - function confirmRemoveEveryHook() { - const hooks = (lib.hooks || []).slice(), names = hooks.map((x) => x.name); - confirmRemoveEvery("hooks", names, t("Remove all {n} hooks?", { n: names.length }), [ + function confirmRemoveEveryHook(some) { + const hooks = (some || lib.hooks || []).slice(), names = hooks.map((x) => x.name), n = names.length; + confirmRemoveEvery("hooks", names, !some ? t("Remove all {n} hooks?", { n }) : n === 1 ? t("Remove {name}?", { name: names[0] }) : t("Remove {n} hooks?", { n }), [ takenFrom(hooks), t("Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file."), - ]); + ], !!some); } // ---------- skills ---------- @@ -2364,6 +2364,7 @@ let picking = ""; // "skills" or "servers": that page's rows have a box each, to pick some (#791, #1027) let naming = false; // the pick bar asks the name of a group to put them in const picked = new Set(); // the names picked + const pickErrs = new Map(); // name → why Remove left it, as the bar's Remove said (#1852) let skillQuery = ""; // what the filter over the skills holds let skillTimer = 0; // the filter's redraw, waiting for typing to pause const unfiltered = new Set(); // groups folded while filtering, till the filter changes @@ -2751,6 +2752,7 @@ const b = button(picking ? t("Done") : t("Select"), "action lib-updall lib-select", () => { picking = picking ? "" : kind; picked.clear(); + pickErrs.clear(); render(); }); const skills = kind === "skills", hooks = kind === "hooks"; @@ -2762,8 +2764,9 @@ // what's picked is a page's own: another page, or a list too short to // pick from, ends it, and a name no longer in the list isn't picked function pickingFor(kind, items) { - if (picking && (picking !== kind || items.length < 2)) { picking = ""; picked.clear(); } + if (picking && (picking !== kind || items.length < 2)) { picking = ""; picked.clear(); pickErrs.clear(); } for (const n of picked) if (!items.some((x) => x.name === n)) picked.delete(n); + for (const n of pickErrs.keys()) if (!items.some((x) => x.name === n)) pickErrs.delete(n); } // a row with a box, which its click ticks rather than opening it @@ -2773,6 +2776,14 @@ row.classList.toggle("picked", picked.has(name)); row.onclick = () => box.click(); row.title = t("Select {name}", { name }); + // one the bar's Remove couldn't take out says why, under its name, in + // place of its line (a row's height is held, so it takes no more room) + const why = pickErrs.get(name), sub = why && row.querySelector(":scope > .who > .sub"); + if (sub) { + row.classList.add("lib-pickfailed"); + sub.className = "sub lib-pickerr"; + sub.textContent = sub.title = t("Not removed: {error}", { error: why }); + } return row; } @@ -2844,11 +2855,18 @@ } } if (servers && projectMCPAgents().length) bar.append(copyConfigButton(skills.map((x) => x.name))); + // the ones picked out of the library (#1852): asked first, as Remove + // all asks, and each taken out as its own row's Remove would. Its + // label holds still as the count changes (the count is beside it, and + // in the sheet), so a pick never rewraps the bar under the pointer + const rm = button(t("Remove…"), "action danger lib-updall lib-pickrm", () => servers ? confirmRemoveEveryServer(skills) : hooks ? confirmRemoveEveryHook(skills) : confirmRemoveEverySkill(skills)); + rm.title = servers ? t("Take the servers picked out of the library") : hooks ? t("Take the hooks picked out of the library") : t("Take the skills picked out of the library"); + bar.append(rm); const c = button(t("Clear"), "lib-updall lib-pickclear", () => { picked.clear(); syncPicks(); }); c.title = t("Unpick them all"); bar.append(c); } - bar.append(button(t("Done"), "action lib-updall lib-pickdone", () => { picking = ""; picked.clear(); render(); })); + bar.append(button(t("Done"), "action lib-updall lib-pickdone", () => { picking = ""; picked.clear(); pickErrs.clear(); render(); })); return bar; } @@ -3641,15 +3659,17 @@ return b; } - // the sheet asking first: its head and what it says, then Remove all n - function confirmRemoveEvery(kind, names, title, lines) { + // the sheet asking first: its head and what it says, then Remove all n, + // or Remove n when they are the ones picked (some) + function confirmRemoveEvery(kind, names, title, lines, some) { const ed = el("div", "editor lib-editor"); const head = el("div", "ehead"); head.append(glyph(GLYPH.trash), el("b", "", title)); ed.append(head); for (const l of lines) if (l) ed.append(el("p", "lib-confirm", l)); const bar = el("div", "bar"); - const go = button(t("Remove all {n}", { n: names.length }), "primary danger-fill", async () => { go.disabled = true; if (await removeEvery(kind, names)) closeLibModal(true); else go.disabled = false; }); + const label = !some ? t("Remove all {n}", { n: names.length }) : names.length === 1 ? t("Remove") : t("Remove {n}", { n: names.length }); + const go = button(label, "primary danger-fill", async () => { go.disabled = true; if (await removeEvery(kind, names, some)) closeLibModal(true); else go.disabled = false; }); bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go); ed.append(bar); modal = { save: () => go.click() }; @@ -3662,45 +3682,70 @@ : t("They are taken out of the library; no agent has any of them."); }; - function confirmRemoveEverySkill() { - const skills = lib.skills.slice(), names = skills.map((s) => s.name), n = names.length; + // every skill, or those picked (#1852) + function confirmRemoveEverySkill(some) { + const skills = (some || lib.skills).slice(), names = skills.map((s) => s.name), n = names.length; const linked = skills.filter((s) => s.kind === "folder").length, kept = n - linked; const projects = (lib.projects || []).filter((p) => names.some((x) => p.skills?.[x]?.length)).length; const where = []; if (kept) where.push(t("{n} folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.", { n: kept })); if (linked) where.push(t("{n} linked from folders of your own are only unlinked: those folders stay where they are.", { n: linked })); - confirmRemoveEvery("skills", names, t("Remove all {n} skills?", { n }), [ + confirmRemoveEvery("skills", names, !some ? t("Remove all {n} skills?", { n }) : n === 1 ? t("Remove {name}?", { name: names[0] }) : t("Remove {n} skills?", { n }), [ takenFrom(skills), projects && t("The skills magpie placed in {n} projects are taken away too.", { n: projects }), where.join(" "), - ]); + ], !!some); } - function confirmRemoveEveryServer() { - const servers = lib.servers.slice(), names = servers.map((s) => s.name), n = names.length; + function confirmRemoveEveryServer(some) { + const servers = (some || lib.servers).slice(), names = servers.map((s) => s.name), n = names.length; const projects = (lib.projects || []).filter((p) => names.some((x) => p.servers?.[x]?.length)).length; const signed = servers.filter((s) => s.signIn?.signedIn).length; - confirmRemoveEvery("servers", names, t("Remove all {n} servers?", { n }), [ + confirmRemoveEvery("servers", names, !some ? t("Remove all {n} servers?", { n }) : n === 1 ? t("Remove {name}?", { name: names[0] }) : t("Remove {n} servers?", { n }), [ takenFrom(servers), projects && t("The servers magpie placed in {n} projects are taken away too.", { n: projects }), signed && t("magpie's sign-in to {n} of them is forgotten too.", { n: signed }), t("Servers your agents have that aren't in the library stay as they are."), - ]); + ], !!some); } - async function removeEvery(kind, names) { + // Those picked (some, #1852): the ones taken out leave the list and the + // picks; one that couldn't be stays picked and says why on its row, and + // only those gone are counted as removed. Nothing removed at all (the + // change refused) leaves every one picked, the sheet open with why. + async function removeEvery(kind, names, some) { + const what = (p) => p.what.replace(/^(skill|mcp|hook):/, ""); try { const v = await api("library/" + kind + "/remove-all", { names }); take(v); const res = v.result || {}, no = res.unremoved || []; + if (some) { + pickErrs.clear(); + for (const p of no) pickErrs.set(what(p), p.error); + const gone = names.filter((x) => !pickErrs.has(x)); + for (const x of gone) picked.delete(x); + const done = gone.length === 1 ? t("{name} removed", { name: gone[0] }) + : kind === "skills" ? t("{n} skills removed", { n: gone.length }) : kind === "hooks" ? t("{n} hooks removed", { n: gone.length }) : t("{n} servers removed", { n: gone.length }); + if (no.length) status((gone.length ? done + " · " : "") + t("{name} wasn't removed: {error}", { name: what(no[0]), error: no[0].error }) + (no.length > 1 ? " " + t("(and {n} more)", { n: no.length - 1 }) : ""), "warn", 10000); + else report(res, done); + render(); + return true; + } if (no.length) { const p = no[0]; - status(t("{name} wasn't removed: {error}", { name: p.what.replace(/^(skill|mcp|hook):/, ""), error: p.error }) + (no.length > 1 ? " " + t("(and {n} more)", { n: no.length - 1 }) : ""), "warn", 8000); + status(t("{name} wasn't removed: {error}", { name: what(p), error: p.error }) + (no.length > 1 ? " " + t("(and {n} more)", { n: no.length - 1 }) : ""), "warn", 8000); } else report(res, kind === "skills" ? t("{n} skills removed", { n: names.length }) : kind === "hooks" ? t("{n} hooks removed", { n: names.length }) : t("{n} servers removed", { n: names.length })); render(); return true; } catch (e) { status(e.message, "err", 6000); + // none went: every one stays picked, and one alone says why on its + // row too (the change names only the first reason of several) + if (some) { + pickErrs.clear(); + if (names.length === 1) pickErrs.set(names[0], e.message); + render(); + } return false; } } diff --git a/internal/gui/tests/library-pick-remove.test.cjs b/internal/gui/tests/library-pick-remove.test.cjs new file mode 100644 index 000000000..e9b5f6a0a --- /dev/null +++ b/internal/gui/tests/library-pick-remove.test.cjs @@ -0,0 +1,241 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #1852: the library's skills went all at once (Remove all) or one row at a +// time; an outdated group (分组) of them had to go one by one. Select's bar +// now has Remove n…: it asks first in the page (no window.confirm), naming +// how many, and posts the names picked to skills/remove-all, the same +// change Remove all makes, each skill taken out as its row's Remove takes +// it. Here: a group's box picks its skills, Cancel posts nothing and leaves +// every one, Remove takes those picked and leaves the others; when one of +// those picked can't be taken out it stays, still picked, its row saying +// why, and only those gone are said to be removed; one picked alone that +// the change refuses stays too. Chromium and WebKit, 1100px and 390px, in +// en, zh, zh-TW, ja and de; no click moves the page, nothing runs off it +// sideways. No backend: the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/me"; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` }); +const gh = (name) => ({ name, description: name + " does a thing", kind: "github", repo: "old/pack", source: `https://github.com/old/pack/tree/main/skills/${name}`, agents: ["claude"] }); +const local = (name) => ({ name, description: name + " does a thing", kind: "local", agents: ["claude", "codex"] }); +const lib = (skills) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("claude", "Claude Code"), agent("codex", "Codex")], + instructions: { agents: [] }, servers: [], skills, foundServers: [], projects: [], foundSkills: [], problems: [], +}); +const STUCK = "the folder couldn't be moved: permission denied"; + +let I18N; +async function loadI18N() { + const src = await fs.readFile(path.join(assets, "i18n.js"), "utf8"); + I18N = new Function(src.slice(0, src.indexOf("\n};") + 3) + "; return 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)); +} + +// remove-all as RemoveSkills answers: "stuck" can't be taken out; the +// others go; when none went, the change fails with the first reason +function server(lang, state, posts) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data, status = 200) => route.fulfill({ status, 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.skills)); + 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 === "skills/remove-all") { + const failed = body.names.filter((n) => n === "stuck").map((n) => ({ what: "skill:" + n, error: STUCK })); + if (failed.length === body.names.length) return json({ error: STUCK }, 400); + state.skills = state.skills.filter((s) => !body.names.includes(s.name) || s.name === "stuck"); + return json({ ...lib(state.skills), result: { changed: ["claude", "codex"], unremoved: failed.length ? failed : undefined } }); + } + return json(lib(state.skills)); + } + 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 thing 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 reach(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); + const scrolls = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => (e.id || e.className) + ":" + e.scrollTop).join(" ")); + const top = await scrolls(); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); + await page.waitForTimeout(200); + assert.equal(await scrolls(), top, `${sel}'s click scrolled the page`); + 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)}`); +}; +// the reader scrolls the Library (not a click) till what they'll press is +// out from under the bar that stays in view at its foot: at 390px a row's +// chips wrap, and the last rows start under it +const reach = async (page, loc) => { + for (let i = 0; i < 20; i++) { + const b = await loc.boundingBox(); + if (b && await loc.evaluate((e, [x, y]) => e.contains(document.elementFromPoint(x, y)), [b.x + b.width / 2, b.y + b.height / 2])) return; + await page.mouse.move(b.x + b.width / 2, Math.max(b.y - 40, 10)); + await page.mouse.wheel(0, 120); + await page.waitForTimeout(80); + } + assert.fail(`${loc} is never out from under the bar`); +}; +const settled = (page) => page.waitForFunction(() => !document.querySelector("#modal").getAnimations({ subtree: true }).length); +// nothing wider than the window: the page, the Library, its rows, bar and sheet +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-skill, #view-library .lib-grouphead, #view-library .lib-pickbar, #view-library .lib-pickbar > *, #modal .lib-editor, #modal .lib-editor .bar > *")) { + 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 + ": some skills, a group's among them, out of the library at once", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + await loadI18N(); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + for (const width of [1100, 390]) for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + await t.test(`${lang} at ${width}px`, async () => { + const w = (key, vars) => tr(lang, key, vars); + const state = { skills: [gh("pack-a"), gh("pack-b"), gh("pack-c"), local("keep-me"), local("notes"), local("stuck")] }; + const posts = [], errors = []; + const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.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(); + const v = page.locator("#view-library"); + const row = (name) => v.locator(".lib-skill").filter({ has: page.locator(".name", { hasText: new RegExp("^" + name) }) }); + const names = () => state.skills.map((s) => s.name); + const shown = async () => (await v.locator(".lib-skill .who > .name").evaluateAll((ns) => ns.map((n) => n.firstChild.textContent))).sort(); + const group = v.locator(".lib-group").filter({ has: page.locator(".lib-grouphead .name", { hasText: /^old\/pack$/ }) }); + await group.waitFor(); + await row("stuck").waitFor(); + const bar = v.locator(".lib-pickbar"), rm = bar.locator(".lib-pickrm"); + const sheet = page.locator("#modal .lib-editor"); + + // Select; the group's box picks its three skills + await press(page, v.locator(".lib-skillshead .lib-select")); + await bar.locator(".lib-pickn.none").waitFor(); + assert.equal(await rm.count(), 0, "Remove with nothing picked"); + await press(page, group.locator(".lib-grouphead .lib-pickbox")); + await bar.locator(".lib-pickn").filter({ hasText: w("{n} selected", { n: 3 }) }).waitFor(); + for (const n of ["pack-a", "pack-b", "pack-c"]) assert.equal(await row(n).locator(".lib-pickbox").isChecked(), true, n); + assert.equal(await row("keep-me").locator(".lib-pickbox").isChecked(), false); + assert.equal((await rm.textContent()).trim(), w("Remove…")); + assert.equal(await rm.getAttribute("title"), w("Take the skills picked out of the library")); + assert.deepEqual(await sideways(page), [], "sideways with the bar"); + + // asked first, naming how many; Cancel posts nothing, leaves all six + await press(page, rm); + await sheet.waitFor(); + await settled(page); + assert.equal((await sheet.locator(".ehead b").textContent()).trim(), w("Remove {n} skills?", { n: 3 })); + await sheet.locator(".lib-confirm").filter({ hasText: w("They are taken out of the library and out of {agents}.", { agents: "Claude Code" }) }).waitFor(); + await sheet.locator(".lib-confirm").filter({ hasText: w("{n} folders are moved to magpie's backups (Backups, at the top of the Library), not deleted.", { n: 3 }) }).waitFor(); + assert.equal((await sheet.locator(".bar button.primary").textContent()).trim(), w("Remove {n}", { n: 3 })); + assert.deepEqual(await sideways(page), [], "sideways with the sheet"); + await sheet.locator(".bar button", { hasText: w("Cancel") }).click(); + await sheet.waitFor({ state: "detached" }); + assert.deepEqual(posts, [], "Cancel posted"); + assert.equal(names().length, 6); + assert.equal((await shown()).length, 6); + await bar.locator(".lib-pickn").filter({ hasText: w("{n} selected", { n: 3 }) }).waitFor(); + + // Remove: the three go, the others stay, nothing is picked + await press(page, rm); + await sheet.waitFor(); + await settled(page); + await sheet.locator(".bar button.primary").click(); + await sheet.waitFor({ state: "detached" }); + assert.deepEqual(posts.shift(), { what: "skills/remove-all", body: { names: ["pack-a", "pack-b", "pack-c"] } }); + await page.locator("#status").filter({ hasText: w("{n} skills removed", { n: 3 }) }).waitFor(); + assert.deepEqual(await shown(), ["keep-me", "notes", "stuck"]); + assert.equal(await group.count(), 0, "the group is still drawn"); + await bar.locator(".lib-pickn.none").waitFor(); + + // two picked, one can't be taken out: it stays, picked, saying why; + // only the one gone is said to be removed + await press(page, row("notes").locator(".lib-pickbox")); + await press(page, row("stuck").locator(".lib-pickbox")); + await press(page, rm); + await sheet.waitFor(); + await settled(page); + assert.equal((await sheet.locator(".ehead b").textContent()).trim(), w("Remove {n} skills?", { n: 2 })); + await sheet.locator(".bar button.primary").click(); + await sheet.waitFor({ state: "detached" }); + assert.deepEqual(posts.shift(), { what: "skills/remove-all", body: { names: ["notes", "stuck"] } }); + await page.locator("#status").filter({ hasText: w("{name} removed", { name: "notes" }) + " · " + w("{name} wasn't removed: {error}", { name: "stuck", error: STUCK }) }).waitFor(); + assert.deepEqual(await shown(), ["keep-me", "stuck"]); + assert.equal(await row("stuck").locator(".lib-pickbox").isChecked(), true, "the one left was unpicked"); + assert.equal(await row("keep-me").locator(".lib-pickbox").isChecked(), false); + assert.equal((await row("stuck").locator(".lib-pickerr").textContent()).trim(), w("Not removed: {error}", { error: STUCK })); + await bar.locator(".lib-pickn").filter({ hasText: w("{n} selected", { n: 1 }) }).waitFor(); + assert.equal((await rm.textContent()).trim(), w("Remove…")); + assert.deepEqual(await sideways(page), [], "sideways with a row's reason"); + + // that one alone: the change refuses, the sheet stays with why, and + // Cancel leaves it there, picked + await press(page, rm); + await sheet.waitFor(); + await settled(page); + assert.equal((await sheet.locator(".ehead b").textContent()).trim(), w("Remove {name}?", { name: "stuck" })); + assert.equal((await sheet.locator(".bar button.primary").textContent()).trim(), w("Remove")); + await sheet.locator(".bar button.primary").click(); + await page.locator("#status").filter({ hasText: STUCK }).waitFor(); + assert.deepEqual(posts.shift(), { what: "skills/remove-all", body: { names: ["stuck"] } }); + await sheet.locator(".bar button.primary:not([disabled])").waitFor(); + await sheet.locator(".bar button", { hasText: w("Cancel") }).click(); + await sheet.waitFor({ state: "detached" }); + assert.deepEqual(await shown(), ["keep-me", "stuck"]); + assert.equal(await row("stuck").locator(".lib-pickbox").isChecked(), true); + await row("stuck").locator(".lib-pickerr").waitFor(); + + // Done: no boxes, no reasons + await press(page, bar.locator(".lib-pickdone")); + assert.equal(await v.locator(".lib-pickbox").count(), 0); + assert.equal(await v.locator(".lib-pickerr").count(), 0); + assert.deepEqual(posts, []); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +}