diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 74be73f15..f17f80fca 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -74,6 +74,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. - A skill kept in `~/.agents/skills` is handed over to the library on the user's click (`HandOverSkills`, `POST /api/library/skills/hand-over` with `names`; the row's Manage in magpie in its source line, Manage {n} in magpie in the skills' heading, each asking first; `magpie library skill hand-over |--all`; tnt1223 on Discord). "Kept there" is `sharedEntry`: the entry in that folder that is the library skill's own folder, by its name or, for a library link into it under another folder's name, by that folder's (`SkillView.Shared`; `SharedElsewhere` when the entry only links to a folder kept elsewhere). Every reader of `sharedHas`/`sharedEntry` follows: `Always`, `syncSkills`' `inShared`, and the shared folder's own target (Goose, Kimi Code, Cindy), which is given no second link beside such an entry (`TestSharedUnderAnotherName`). Handed over, a folder in `~/.agents/skills` moves into the library's skills folder (`moveIn`: renamed, or copied, read back the same with `sameTree` and only then set aside with the backups; a failure leaves it where it was and the library's link as it was, `TestHandOverFailureKeepsOriginal`), and an entry that only links elsewhere is taken away while the library links past it to that folder. The user's own links to it in agents' folders, which would point at nothing, go too. Every agent here that read it (`readsSharedHere`, and the agent of each such link) is ticked, so each keeps it, now from the library, till it is unticked or turned off here. A skill found there and not in the library yet is brought in first. One that can't be handed over is left as it was, in `Result.Unmoved`, and the others are handed over all the same. `HandBackSkill` (`magpie library skill hand-back `, CLI only; the sheet names it) moves the folder back and links the library to it, its ticks as they are. Not covered: another computer whose skill is still in its own `~/.agents/skills` gets the library's copy from a sync beside its own, until it is handed over there too; and the skills CLI's lock (`npx skills update`) may put the entry back (`TestHandOverSharedFolder`, `TestHandOverSharedLink`, `TestHandOverFound`, `TestHandOverWithGoose`, `TestLibrarySkillHandOver`, `skill-handover.test.cjs`). [`skill_handover.go`](../../internal/library/skill_handover.go) - The agents that read `~/.agents/skills` themselves are `readsShared` (Codex, Gemini CLI, OpenCode, DevEco Code, Crush, dsh, Command Code, Devin, Droid, Cline, Grok Build, Grok App, fx, Alma, Kimi Code and OmO) and, from the version that started to, `Target.SharedToo`: Pi from 0.54.0 (its CHANGELOG; `userAgentsSkillsDir` in package-manager.js) and omp from 11.0.0 (`discovery/agents.ts`; 10.6.2 doesn't). OmO runs on senpi, whose oldest version on npm (0.74.0) already reads it. A Pi or omp whose version isn't known is taken as older, as before. Every reader goes through `Target.readsSharedDir`: `Always` (the row's lock), `syncSkills`' `inShared` (no second link in its own folder) and `readsSharedHere` for a handover (usrname1833 on Discord; `TestPiReadsSharedSkillsFromItsVersion`). - Put skills in (`Library.SharedSkills`; `SetSkillsWhere`, `POST /api/library/skills/where` with `how` `agents` or `shared`; `magpie library skill where agents|shared`; the Skills tab's bar under How, `skillWhereBar` in plugins/library/client.js; usrname1833 on Discord). Off, the default and what a library.json from before reads as, each agent gets the skills ticked for it in its own folder. On, every library skill on here (`keepsShared`: not `OffHere`, its folder there) also gets magpie's link in `~/.agents/skills` (`syncShared`, run after `sweepShared`), so every agent and tool that reads that folder has it, ticked or not, and is in its `Always`. The files stay in the library, so updates, checks, edit tracking and Off here work as before, and nothing is moved when it is turned on: existing skills just get links. An entry of the user's own by a skill's name is left alone, silently, and the agents ticked for the library's skill still get it in their own folders. A sync leaves an existing link as it is. A skill given to the folder's own agent (Kimi Code, Goose, Cindy) is that agent's sync's. Turned off, `sweepShared` takes out magpie's links there and nothing else, and each agent's own links come back. It is this computer's: `Collect` never carries it (`TestSkillsWhereShared`, `TestSkillsWhereSharedWithKimi`, `skill-where.test.cjs`). Not covered: on Windows without the right to make links the entry is a marked copy; a stale one is set aside and copied again, but `takeEdits` doesn't take edits made in that copy into the library, so they go to the backups when the setting is turned off or the skill changes (#4958). [`skills_shared.go`](../../internal/library/skills_shared.go) +- A skill's files are read and edited in the page (refeccd on Discord: skills handed over from `~/.agents/skills` had nowhere else to be edited). `GET /api/library/skill?name=&file=` answers `ReadSkillFile`: the file (`SKILL.md` when none is named), its text, the skill's folder and `files`, its text files (`skillTextFiles`: UTF-8 with no NUL, up to 1 MB each and 200 in all, `SKILL.md` first, leaving out links, hidden folders, `skipInSkill`'s entries and what installing writes, `fromInstall`). `SaveSkillFile` (`POST /api/library/skills/save` with `name`, `file`, `text` and `was`) goes through `change`: it writes only a regular file already in the skill's folder, never through a link or out of the folder (`skillFilePath`), refuses when the file no longer holds `was`, the text the page opened, keeps a file's CRLF line ends, and writes with `edit.WriteAtomic`. It writes the library's folder, so a linked agent reads it at once and the sync that follows copies it again into each copy; a copy edited in an agent before it is older than the save, so `takeEdits` keeps that edit aside with the backups. A skill from GitHub or git saved here reads as changed here (`editState`), so an update asks before it replaces the edit. The page (`viewSkill`, `rendered` in plugins/library/client.js) draws a Markdown file with the Plugins page's renderer (`window.mdRender`, `markdown` in plugins.js) and its front matter as rows, any other file as its text; Edit swaps in a text box, ⌘S or Save sends it, and the skill's other files are the app's menu under its name (`TestSavedSkillFileReachesEveryAgent`, `TestSkillFileSaveRefusesAChangedFile`, `TestSkillFileStaysInTheSkill`, `TestSkillFileKeepsLineEnds`, `skill-edit.test.cjs`). Not covered: the TUI and CLI have no editor; a new file can't be made, and a file can't be renamed or removed, here. [`skill_file.go`](../../internal/library/skill_file.go) - WorkBuddy's servers go in `$WORKBUDDY_CONFIG_DIR/mcp.json` (default `~/.workbuddy`; WorkBuddy AI, the international build, keeps its own in `~/.workbuddy-ai`, #1494), and CodeBuddy Code's go in the first of `.mcp.json`, `mcp.json` and `~/.codebuddy.json` that exists, as `resolveMcpFilePath` reads them (#1266). WorkBuddy connects a server only after the user has switched it on once in its own MCP settings. It keeps that approval in `mcp-approvals.json`, keyed by the command, args and env names or the URL's origin, so changing those asks again. magpie never writes the approval, and the servers page says so, by the build's name, when a server is given to WorkBuddy or WorkBuddy AI. - Alma's servers go in `~/.config/alma/mcp.json` on every system (its home, not its data folder), as its own MCP settings write them: `command`/`args`/`env`, or `url`/`headers` with `transport: "sse"` only for SSE (#1292). Alma reads the file as it starts and when its MCP settings refresh, so a server given to it while it runs reaches it after one of those. - Grok App's independent home (Use on a custom provider, `GROK_HOME` at `agent-home` under its data folder) gets instructions in `AGENTS.md`, MCP servers in `[mcp_servers]` of the same `config.toml` magpie's channel is in, skills in `skills/`, and hooks as `[[hooks.]]` tables in that config, and it also reads `~/.agents/skills`. Shared mode stays on Grok Build's `~/.grok` row. RTK lists Grok App, and Grok Build, with the switch off: `rtk init` has no Grok agent. diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 385843abf..114e89aab 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -10,6 +10,7 @@ (() => { const page = $("#view-plugins"); if (!page) return; + window.mdRender = markdown; let mine = null; // /api/plugins: what's installed let listings = null; // /api/plugins/listings: the plugins suggested diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 3db109fa9..7a88cc718 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -5558,24 +5558,101 @@ magpie.plugin("library", (ctx) => { openLib(ed); } - async function viewSkill(s) { - const ed = el("div", "editor lib-editor lib-reader"); + // A skill's files, read and edited here (refeccd on Discord: skills + // handed over from ~/.agents/skills had no other place to be edited). + // Markdown is shown as it reads, its front matter as rows; Save writes + // the library's folder, so every agent given the skill gets it. + async function viewSkill(s, file = "") { + const ed = el("div", "editor lib-editor lib-reader lib-skillfile"); const head = el("div", "ehead"); - head.append(mark(s.icon, GLYPH.skill), el("b", "", s.name), el("span", "grow")); - const pre = el("pre", "lib-md", "…"); - ed.append(head, pre); + const pick = el("button", "lib-filepick"); + pick.type = "button"; + pick.hidden = true; + head.append(mark(s.icon, GLYPH.skill), el("b", "", s.name), pick, el("span", "grow")); + const body = el("div", "lib-skillbody"); const bar = el("div", "bar"); - const where = el("span", "note"); - bar.append(where, el("span", "grow"), button(t("Close"), "", closeLibModal)); - ed.append(bar); - modal = {}; + ed.append(head, body, bar); + let cur = null, ta = null; + const lf = (x) => x.replace(/\r\n?/g, "\n"); + modal = { dirty: () => !!(ta && cur && ta.value !== lf(cur.text)) }; + const read = async (f) => { + body.replaceChildren(el("pre", "lib-md", "…")); + try { + cur = await api("library/skill?name=" + encodeURIComponent(s.name) + (f ? "&file=" + encodeURIComponent(f) : "")); + show(); + } catch (e) { + body.replaceChildren(el("pre", "lib-md", e.message)); + bar.replaceChildren(el("span", "grow"), button(t("Close"), "", closeLibModal)); + } + }; + const swap = async (f) => { + if (f === cur?.file || modal.dirty() && !(await confirmDiscard())) return; + ta = null; + read(f); + }; + pick.onclick = (e) => { + e.stopPropagation(); + openProtoMenu(pick, cur.files.map((f) => ({ v: f, name: f, literalName: true, note: "" })), cur.file, swap, "Files"); + }; + const show = () => { + ta = null; + pick.hidden = !(cur.files?.length > 1); + pick.replaceChildren(el("span", "", cur.file), svg(CHEV, 10, 1.7)); + body.replaceChildren(rendered(cur)); + const where = el("span", "note"); + where.append(pathLink(cur.path)); + bar.replaceChildren(where, el("span", "grow"), button(t("Edit"), "", edit), button(t("Close"), "", closeLibModal)); + }; + const edit = () => { + ta = el("textarea", "lib-text lib-skilltext"); + ta.spellcheck = false; + ta.value = lf(cur.text); + ta.onkeydown = (e) => { + if (e.isComposing || e.keyCode === 229) return; + if (e.key === "Escape") return; + e.stopPropagation(); + if ((e.metaKey || e.ctrlKey) && e.key === "s") { e.preventDefault(); save(); } + }; + body.replaceChildren(ta); + const note = el("span", "note lib-reaches", t("Saved in the library: every agent given {name} gets it", { name: s.name }) + " · " + (/^Mac/.test(navigator.platform) ? "⌘S" : "Ctrl+S")); + bar.replaceChildren(note, el("span", "grow"), button(t("Cancel"), "", async () => { if (!modal.dirty() || await confirmDiscard()) show(); }), button(t("Save"), "primary", save)); + ta.focus({ preventScroll: true }); + ta.setSelectionRange(0, 0); + }; + const save = async () => { + if (!ta) return; + if (!modal.dirty()) return show(); + const f = cur.file; + if (await change("skills/save", { name: s.name, file: f, text: ta.value, was: cur.text }, t("{name} saved", { name: f }))) { + ta = null; + read(f); + } + }; openLib(ed); - try { - const r = await api("library/skill?name=" + encodeURIComponent(s.name)); - pre.textContent = r.text; - where.replaceChildren(pathLink(r.path)); - } catch (e) { pre.textContent = e.message; } + read(file); } + // a skill's file as it reads: Markdown drawn, front matter as rows + // (name, description), anything else as its text + function rendered(f) { + if (!/\.(md|markdown)$/i.test(f.file) || !window.mdRender) return el("pre", "lib-md", f.text); + const text = f.text.replace(/\r\n?/g, "\n"); + const box = el("div", "lib-mdview"); + const m = text.match(/^---\n([\s\S]*?)\n---[ \t]*(?:\n|$)/); + if (m) { + const meta = []; + for (const line of m[1].split("\n")) { + const kv = line.match(/^([\w.-]+):\s*(.*)$/); + if (kv) meta.push([kv[1], kv[2]]); + else if (meta.length && line.trim()) meta[meta.length - 1][1] += " " + line.trim(); + } + const dl = el("dl", "lib-fm"); + for (const [k, v] of meta) dl.append(el("dt", "", k), el("dd", "", v.replace(/^[>|][-+]?\s*/, "").trim().replace(/^(["'])(.*)\1$/, "$2"))); + if (meta.length) box.append(dl); + } + box.append(window.mdRender(m ? text.slice(m[0].length) : text)); + return box; + } + function foundSkillRow(f) { const row = el("div", "row lib-row lib-found"); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 2d4fa3908..67fc93828 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -703,6 +703,7 @@ magpie.strings({ "Kept as you changed them: {names}. Update each from its row to replace your changes.": "已保留你改动过的:{names}。如要用 GitHub 的版本替换,请在各自的行里单独更新。", "Update from GitHub ({repo}, as CC Switch installed it)": "从 GitHub 更新({repo},CC Switch 安装时的来源)", "Read {name}'s SKILL.md": "查看 {name} 的 SKILL.md", + "Saved in the library: every agent given {name} gets it": "保存在资料库里:每个装了 {name} 的 Agent 都会拿到", "It is taken out of every agent it was given to. The folder it was linked from stays where it is.": "将从所有已启用的 Agent 中移除,链接的原文件夹保持不动。", "It is taken out of every agent it was given to, and its folder is moved to magpie's backups.": "将从所有已启用的 Agent 中移除,文件夹移到 magpie 的备份。", "Its folder is moved to magpie's backups.": "文件夹将移到 magpie 的备份。", @@ -1466,6 +1467,7 @@ magpie.strings({ "Kept as you changed them: {names}. Update each from its row to replace your changes.": "已保留你改動過的:{names}。如要用 GitHub 的版本取代,請在各自的列中單獨更新。", "Update from GitHub ({repo}, as CC Switch installed it)": "從 GitHub 更新({repo},CC Switch 安裝時的來源)", "Read {name}'s SKILL.md": "檢視 {name} 的 SKILL.md", + "Saved in the library: every agent given {name} gets it": "儲存在資料庫裡:每個裝了 {name} 的 Agent 都會拿到", "It is taken out of every agent it was given to. The folder it was linked from stays where it is.": "將從所有已啟用的 Agent 中移除,連結的原資料夾保持不動。", "It is taken out of every agent it was given to, and its folder is moved to magpie's backups.": "將從所有已啟用的 Agent 中移除,資料夾移到 magpie 的備份。", "Its folder is moved to magpie's backups.": "資料夾將移到 magpie 的備份。", @@ -2228,6 +2230,7 @@ magpie.strings({ "Kept as you changed them: {names}. Update each from its row to replace your changes.": "変更済みのため残しました:{names}。変更を置き換えるには、それぞれの行から更新してください。", "Update from GitHub ({repo}, as CC Switch installed it)": "GitHub からアップデート({repo}、CC Switch がインストールした取得元)", "Read {name}'s SKILL.md": "{name} の SKILL.md を読む", + "Saved in the library: every agent given {name} gets it": "ライブラリに保存:{name} を渡したすべてのエージェントに届きます", "It is taken out of every agent it was given to. The folder it was linked from stays where it is.": "渡していたすべてのエージェントから外されます。リンク元のフォルダはそのまま残ります。", "It is taken out of every agent it was given to, and its folder is moved to magpie's backups.": "渡していたすべてのエージェントから外され、フォルダは magpie のバックアップに移されます。", "Its folder is moved to magpie's backups.": "フォルダは magpie のバックアップに移されます。", @@ -2991,6 +2994,7 @@ magpie.strings({ "Kept as you changed them: {names}. Update each from its row to replace your changes.": "Behalten, wie du sie geändert hast: {names}. Aktualisiere jeden in seiner Zeile, um deine Änderungen zu ersetzen.", "Update from GitHub ({repo}, as CC Switch installed it)": "Von GitHub aktualisieren ({repo}, wie CC Switch es installiert hat)", "Read {name}'s SKILL.md": "SKILL.md von {name} lesen", + "Saved in the library: every agent given {name} gets it": "In der Bibliothek gespeichert: jeder Agent mit {name} bekommt es", "It is taken out of every agent it was given to. The folder it was linked from stays where it is.": "Er wird aus jedem Agenten entfernt, dem er gegeben wurde. Der Ordner, aus dem er verlinkt war, bleibt, wo er ist.", "It is taken out of every agent it was given to, and its folder is moved to magpie's backups.": "Er wird aus jedem Agenten entfernt, dem er gegeben wurde, und sein Ordner wird in die Backups von magpie verschoben.", "Its folder is moved to magpie's backups.": "Sein Ordner wird in die Backups von magpie verschoben.", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index eaf35a658..0933086bc 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -481,10 +481,24 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-reader { grid-template-columns: minmax(0, 1fr); } .lib-md { margin: 0; max-height: min(60vh, 520px); overflow: auto; font: var(--code-style, normal) var(--code-weight, 400) 12px/1.6 var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); color: var(--fg-2); white-space: pre-wrap; overflow-wrap: anywhere; background: var(--card-2); border-radius: 8px; padding: 12px 14px; user-select: text; -webkit-user-select: text; } .lib-reader .bar .lib-path { max-width: 70%; } +/* a skill's files: Markdown as it reads, its front matter as rows, edited in place */ +.lib-skillfile .ehead { min-width: 0; } +.lib-filepick { display: inline-flex; align-items: center; gap: 4px; min-width: 0; max-width: 50%; height: 24px; padding: 0 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--card); color: var(--fg-2); font: inherit; font-size: 12px; cursor: pointer; } +.lib-filepick span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.lib-filepick:hover { color: var(--fg); border-color: var(--line-2); } +.lib-mdview { max-height: min(60vh, 520px); overflow: auto; padding: 12px 14px; border: 1px solid var(--line); border-radius: 8px; background: var(--card); user-select: text; -webkit-user-select: text; } +.lib-fm { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 3px 12px; margin: 0 0 12px; padding: 0 0 10px; border-bottom: 1px solid var(--line-2); font-size: 12px; line-height: 1.5; } +.lib-fm dt { color: var(--faint); } +.lib-fm dd { margin: 0; color: var(--fg-2); overflow-wrap: anywhere; } +.lib-text.lib-skilltext { height: min(60vh, 520px); min-height: 200px; overflow: auto; border: 1px solid var(--line); border-radius: 8px; background: var(--card); } +.lib-text.lib-skilltext:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); } +.lib-skillfile .bar .lib-reaches { min-width: 0; flex: 0 1 auto; font-size: 11.5px; } .editor .editor-error:empty { display: none; } @media (max-width: 560px) { .lib-list .row { flex-wrap: wrap; } + .lib-skillfile .bar { flex-wrap: wrap; } + .lib-skillfile .bar .lib-reaches { flex-basis: 100%; } .lib-agents { max-width: 100%; } } diff --git a/internal/gui/library.go b/internal/gui/library.go index 692f26886..a3fbd4e16 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -152,12 +152,12 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { writeJSON(rw, v) }) mux.HandleFunc("GET /api/library/skill", func(rw http.ResponseWriter, r *http.Request) { - text, err := library.SkillText(r.URL.Query().Get("name")) + f, err := library.ReadSkillFile(r.URL.Query().Get("name"), r.URL.Query().Get("file")) if err != nil { fail(rw, err) return } - writeJSON(rw, map[string]string{"text": text, "path": library.SkillPath(r.URL.Query().Get("name"))}) + writeJSON(rw, f) }) // the market: what it offers for a search, and each skill's description // once asked for, which skills.sh gives one at a time @@ -469,6 +469,9 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { // Replace updates a skill changed here all the same, its // changed version kept with the backups (#1449) Replace bool + // a skill's file saved: its place in the skill, its new text, + // and what it held when the page opened it + File, Text, Was string library.InstructionsChange } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { @@ -550,6 +553,9 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.UpdateSomeSkills(in.Names) case "skills/agents": res, err = library.SkillAgents(in.Name, in.Agents) + case "skills/save": + // a skill's file edited in the page, given to its agents again + res, err = library.SaveSkillFile(in.Name, in.File, in.Text, in.Was) case "skills/here": res, err = library.SkillHere(in.Name, in.On) case "skills/agents-all": diff --git a/internal/gui/tests/skill-edit.test.cjs b/internal/gui/tests/skill-edit.test.cjs new file mode 100644 index 000000000..41abe0d27 --- /dev/null +++ b/internal/gui/tests/skill-edit.test.cjs @@ -0,0 +1,165 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// refeccd on Discord: skills handed over to magpie from ~/.agents/skills +// could no longer be edited, and their SKILL.md showed as raw text. A +// skill's row opens its SKILL.md drawn as Markdown, its front matter as +// rows; Edit gives its text to change, ⌘S or Save sends skills/save with +// the text it was opened with, and the skill's other text files are a menu +// away (the app's menu, no native select). A click never scrolls the page. +// In every language, in Chromium and WebKit, wide and narrow. No backend: +// the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/refeccd"; +const DIR = `${HOME}/.magpie/library/skills/writer`; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills` }); +const SKILL = "---\nname: writer\ndescription: >\n Write release notes\n people read\n---\n\n# Writer\n\nUse **short** lines.\n\n## Steps\n\n- Read the `diff`\n- Write it\n\n```sh\ngit log -1\n```\n"; +const lib = () => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("claude", "Claude Code"), agent("codex", "Codex")], + instructions: { agents: [] }, servers: [], foundServers: [], projects: [], foundSkills: [], newSkills: [], + skills: [{ name: "writer", description: "Write release notes people read", kind: "folder", source: DIR, agents: ["claude", "codex"] }], +}); + +function server(lang, posts, files) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/library") return route.fulfill({ json: lib() }); + if (url.pathname === "/api/library/skill") { + const file = url.searchParams.get("file") || "SKILL.md"; + return route.fulfill({ json: { file, text: files[file], path: DIR, files: Object.keys(files) } }); + } + if (url.pathname.startsWith("/api/library/skills/")) { + const body = req.postDataJSON(); + posts.push({ what: url.pathname.split("/").pop(), body }); + files[body.file] = body.text; + return route.fulfill({ json: { ...lib(), result: { changed: ["codex"] } } }); + } + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// a mouse press where the button is, once the dialog has stopped moving +const press = async (page, loc) => { + await page.waitForFunction(() => !document.getAnimations().some((a) => a.playState === "running" && a.effect?.target?.closest?.("#modal"))); + const b = await loc.boundingBox(); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); +}; +const scrolls = (page) => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop && !e.closest("#modal")).map((e) => (e.id || e.className) + ":" + e.scrollTop).concat("doc:" + document.scrollingElement.scrollTop).join(" ")); + +const words = { + en: { edit: "Edit", save: "Save", cancel: "Cancel", saved: "SKILL.md saved", reaches: "Saved in the library: every agent given writer gets it" }, + zh: { edit: "编辑", save: "保存", cancel: "取消", saved: "已保存 SKILL.md", reaches: "保存在资料库里:每个装了 writer 的 Agent 都会拿到" }, + "zh-TW": { edit: "編輯", save: "儲存", cancel: "取消", saved: "已儲存 SKILL.md", reaches: "儲存在資料庫裡:每個裝了 writer 的 Agent 都會拿到" }, + ja: { edit: "編集", save: "保存", cancel: "キャンセル", saved: "SKILL.md を保存しました", reaches: "ライブラリに保存:writer を渡したすべてのエージェントに届きます" }, + de: { edit: "Bearbeiten", save: "Speichern", cancel: "Abbrechen", saved: "SKILL.md gespeichert", reaches: "In der Bibliothek gespeichert: jeder Agent mit writer bekommt es" }, +}; + +const shots = process.env.ARTIFACT_DIR; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a skill's SKILL.md reads as Markdown and is edited and saved in the library", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + for (const width of [860, 400]) for (const lang of Object.keys(words)) { + await t.test(`${lang} at ${width}px`, async () => { + const w = words[lang], posts = []; + const files = { "SKILL.md": SKILL, "refs/style.md": "# Style\n", "scripts/run.sh": "echo hi\n" }; + const ctx = await browser.newContext({ viewport: { width, height: 900 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posts, files)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const row = page.locator("#view-library .lib-skill", { has: page.locator(".name", { hasText: /^writer/ }) }); + await row.waitFor(); + const before = await scrolls(page); + await press(page, row.locator(".who")); + const modal = page.locator("#modal .lib-skillfile"); + const view = modal.locator(".lib-mdview"); + await view.waitFor(); + + // drawn, not raw: headings, bold, code, a list; the front matter as rows + assert.equal((await view.locator("h3").first().textContent()).trim(), "Writer"); + assert.equal(await view.locator("strong", { hasText: "short" }).count(), 1); + assert.equal(await view.locator("li").count(), 2); + assert.equal((await view.locator("pre code").textContent()).trim(), "git log -1"); + assert.deepEqual(await view.locator(".lib-fm dt").allTextContents(), ["name", "description"]); + assert.equal((await view.locator(".lib-fm dd").nth(1).textContent()).trim(), "Write release notes people read"); + assert.equal(await view.innerText().then((s) => s.includes("---")), false, "the front matter's fences are shown"); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll"); + if (shots) await page.waitForTimeout(500); + if (shots) await page.screenshot({ path: path.join(shots, `skill-edit-view-${engine}-${lang}-${width}.png`) }); + + // Edit, then ⌘S: what it was opened with goes too + await press(page, modal.locator(".bar button", { hasText: w.edit })); + const ta = modal.locator("textarea.lib-skilltext"); + await ta.waitFor(); + assert.equal(await ta.inputValue(), SKILL); + assert.equal((await modal.locator(".bar .lib-reaches").textContent()).startsWith(w.reaches), true); + for (const b of await modal.locator(".bar button").all()) { + const box = await b.boundingBox(); + assert(box && box.x >= 0 && box.x + box.width <= width, `a button out of view: ${JSON.stringify(box)}`); + } + if (shots) await page.screenshot({ path: path.join(shots, `skill-edit-edit-${engine}-${lang}-${width}.png`) }); + await ta.evaluate((e) => e.setSelectionRange(e.value.length, e.value.length)); + await ta.type("\nKeep it brief.\n"); + await ta.press("ControlOrMeta+s"); + await view.waitFor(); + assert.deepEqual(posts, [{ what: "save", body: { name: "writer", file: "SKILL.md", text: SKILL + "\nKeep it brief.\n", was: SKILL } }]); + assert.equal((await page.locator("#status").textContent()).trim(), w.saved); + assert.equal(await view.locator("p", { hasText: "Keep it brief." }).count(), 1, "the saved text is what is shown"); + + // another file, from the app's menu; Cancel with nothing changed sends nothing + await press(page, modal.locator(".lib-filepick")); + const menu = page.locator(".proto-menu"); + await menu.waitFor(); + assert.deepEqual(await menu.locator(".pm-name").allTextContents(), ["SKILL.md", "refs/style.md", "scripts/run.sh"]); + await press(page, menu.locator(".pm-item", { hasText: "scripts/run.sh" })); + await modal.locator("pre.lib-md", { hasText: "echo hi" }).waitFor(); + await press(page, modal.locator(".bar button", { hasText: w.edit })); + await ta.waitFor(); + await press(page, modal.locator(".bar button", { hasText: w.cancel })); + await modal.locator("pre.lib-md").waitFor(); + assert.equal(posts.length, 1, "Cancel sent something"); + + // Save, the button, on a second file + await press(page, modal.locator(".lib-filepick")); + await press(page, menu.locator(".pm-item", { hasText: "refs/style.md" })); + await view.locator("h3", { hasText: "Style" }).waitFor(); + await press(page, modal.locator(".bar button", { hasText: w.edit })); + await ta.fill("# Style\n\nShort.\n"); + await press(page, modal.locator(".bar button.primary", { hasText: w.save })); + await view.locator("p", { hasText: "Short." }).waitFor(); + assert.deepEqual(posts[1], { what: "save", body: { name: "writer", file: "refs/style.md", text: "# Style\n\nShort.\n", was: "# Style\n" } }); + assert.equal(await scrolls(page), before, "a click moved the page"); + const border = await page.evaluate(() => [...document.querySelectorAll("#modal .lib-skillfile, #modal .lib-skillfile *")].filter((e) => parseFloat(getComputedStyle(e).borderLeftWidth) > 1 || getComputedStyle(e).backgroundImage.includes("gradient")).length); + assert.equal(border, 0, "a left-border stripe or a gradient"); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/library/skill_file.go b/internal/library/skill_file.go new file mode 100644 index 000000000..468516bf0 --- /dev/null +++ b/internal/library/skill_file.go @@ -0,0 +1,221 @@ +package library + +// A skill's files read and edited in the page (refeccd on Discord: skills +// handed over to magpie from ~/.agents/skills could no longer be edited +// there, where the user used to). What is saved goes into the library's +// folder of the skill, so every agent linked to it reads it at once, and +// the sync that follows makes each agent's copy again. A copy edited in an +// agent meanwhile loses to the newer save and is kept aside with the +// backups (takeEdits). A skill from GitHub saved here is changed here +// (editState): an update asks before it replaces the edit. + +import ( + "bytes" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "unicode/utf8" + + "github.com/yetone/magpie/internal/edit" +) + +const ( + skillFileMax = 1 << 20 // a text file larger than this is not opened in the page + skillFilesMax = 200 // the files listed of one skill +) + +// SkillFile is one file of a library skill as the page reads it. +type SkillFile struct { + File string `json:"file"` // its place in the skill's folder, with / + Text string `json:"text"` // what it holds + Path string `json:"path"` // the skill's folder + Files []string `json:"files"` // the skill's text files, SKILL.md first +} + +// ReadSkillFile is the file of a library skill at file (SKILL.md when +// empty), with the skill's other text files listed. +func ReadSkillFile(name, file string) (*SkillFile, error) { + if err := checkName("skill", name); err != nil { + return nil, err + } + if file == "" { + file = "SKILL.md" + } + root := realDir(skillDir(name)) + p, err := skillFilePath(root, file) + if err != nil { + return nil, err + } + text, err := readSkillText(p) + if err != nil { + if file == "SKILL.md" && errors.Is(err, fs.ErrNotExist) { + return nil, fmt.Errorf("%s has no SKILL.md in the library", name) + } + return nil, err + } + return &SkillFile{File: filepath.ToSlash(filepath.Clean(file)), Text: text, Path: skillDir(name), Files: skillTextFiles(root)}, nil +} + +// SaveSkillFile writes text into the file of a library skill at file, and +// gives the skill to its agents again. was is the text the page opened: +// when the file holds something else now (an agent, an update or the user +// changed it since), nothing is written, and the error says so. +func SaveSkillFile(name, file, text, was string) (*Result, error) { + if err := checkName("skill", name); err != nil { + return nil, err + } + return change(func(l *Library) error { + if l.skill(name) == nil { + return fmt.Errorf("no skill called %s", name) + } + p, err := skillFilePath(realDir(skillDir(name)), file) + if err != nil { + return err + } + cur, err := readSkillText(p) + if err != nil { + return err + } + if cur != was { + return fmt.Errorf("%s was changed since it was opened; open it again to see what it holds now", file) + } + // the line ends the file was written with: the page's text has \n + if strings.Contains(cur, "\r\n") { + text = strings.ReplaceAll(strings.ReplaceAll(text, "\r\n", "\n"), "\n", "\r\n") + } + if text == cur { + return nil + } + if len(text) > skillFileMax { + return fmt.Errorf("%s would be over %d KB", file, skillFileMax>>10) + } + return edit.WriteAtomic(p, []byte(text)) + }) +} + +// skillFilePath is the file at rel in the skill's folder root: a place in +// it, not a link, and none of the folders magpie leaves aside. +func skillFilePath(root, rel string) (string, error) { + rel = filepath.FromSlash(rel) + if rel == "" || !filepath.IsLocal(rel) { + return "", fmt.Errorf("%q is not a file of the skill", rel) + } + for _, part := range strings.Split(filepath.Clean(rel), string(filepath.Separator)) { + if skipInSkill(part) || installedDirs[part] { + return "", fmt.Errorf("%q is not a file of the skill", rel) + } + } + p := filepath.Join(root, rel) + fi, err := os.Lstat(p) + if err != nil { + return "", err + } + if !fi.Mode().IsRegular() { + return "", fmt.Errorf("%s is not a file magpie opens: it is a link or a folder", filepath.ToSlash(rel)) + } + // a folder in it that is a link leads out of the skill + if dir, err := filepath.EvalSymlinks(filepath.Dir(p)); err != nil { + return "", err + } else if r, err := filepath.EvalSymlinks(root); err != nil { + return "", err + } else if dir != r && !strings.HasPrefix(dir, r+string(filepath.Separator)) { + return "", fmt.Errorf("%s is outside the skill's folder", filepath.ToSlash(rel)) + } + return p, nil +} + +// readSkillText is the file at p as text: one too large, or not text, is +// refused rather than shown garbled or written back changed. +func readSkillText(p string) (string, error) { + f, err := os.Open(p) + if err != nil { + return "", err + } + defer f.Close() + b, err := io.ReadAll(io.LimitReader(f, skillFileMax+1)) + if err != nil { + return "", err + } + if len(b) > skillFileMax { + return "", fmt.Errorf("%s is over %d KB, too large to open here", filepath.Base(p), skillFileMax>>10) + } + if !isText(b) { + return "", fmt.Errorf("%s is not a text file", filepath.Base(p)) + } + return string(b), nil +} + +func isText(b []byte) bool { return utf8.Valid(b) && !bytes.Contains(b, []byte{0}) } + +// skillTextFiles lists the text files in the skill's folder, SKILL.md +// first, then by place; the folders installing it makes, version +// control's and links are left out. +func skillTextFiles(root string) []string { + var out []string + filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + if p == root { + return nil + } + name := d.Name() + if d.IsDir() { + if skipInSkill(name) || installedDirs[name] || strings.HasPrefix(name, ".") { + return filepath.SkipDir + } + return nil + } + if len(out) >= skillFilesMax { + return filepath.SkipAll + } + if !d.Type().IsRegular() || skipInSkill(name) || fromInstall(name, false, true) { + return nil + } + fi, err := d.Info() + if err != nil || fi.Size() > skillFileMax { + return nil + } + if !headIsText(p) { + return nil + } + rel, _ := filepath.Rel(root, p) + out = append(out, filepath.ToSlash(rel)) + return nil + }) + slices.SortStableFunc(out, func(a, b string) int { + if (a == "SKILL.md") != (b == "SKILL.md") { + if a == "SKILL.md" { + return -1 + } + return 1 + } + return strings.Compare(a, b) + }) + return out +} + +// headIsText is whether the file's first 8 KB read as text, a rune cut at +// the end allowed. +func headIsText(p string) bool { + f, err := os.Open(p) + if err != nil { + return false + } + defer f.Close() + b := make([]byte, 8<<10) + n, _ := io.ReadFull(f, b) + b = b[:n] + if bytes.Contains(b, []byte{0}) { + return false + } + for i := 0; i < utf8.UTFMax && len(b) > 0 && !utf8.Valid(b); i++ { + b = b[:len(b)-1] + } + return utf8.Valid(b) +} diff --git a/internal/library/skill_file_test.go b/internal/library/skill_file_test.go new file mode 100644 index 000000000..9c88d0a32 --- /dev/null +++ b/internal/library/skill_file_test.go @@ -0,0 +1,147 @@ +package library + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +// refeccd on Discord: skills kept in ~/.agents/skills, handed over to +// magpie, could no longer be edited where they had been. A file saved +// from the page goes into the library's folder, reaches the agent linked +// to it and the one given a copy, and stays through the syncs after. +func TestSavedSkillFileReachesEveryAgent(t *testing.T) { + h := sandbox(t) + noGoose(t, h) + shared := filepath.Join(h, ".agents/skills") + skill(t, filepath.Join(shared, "writer"), "writer", "Write well") + write(t, filepath.Join(shared, "writer/refs/style.md"), "# Style\n") + write(t, filepath.Join(shared, "writer/logo.png"), "\x89PNG\r\n\x1a\n\x00\x00") + ok(t)(ImportSkill("writer")) + ok(t)(HandOverSkills([]string{"writer"})) + ok(t)(SetSkillHow("codex", HowCopy)) + ok(t)(SetSkillHow("gemini", HowLink)) + cx, gm := filepath.Join(h, ".codex/skills/writer"), filepath.Join(h, ".gemini/skills/writer") + if !ours(cx, "writer") || isLink(t, cx) || !isLink(t, gm) { + t.Fatal("codex hasn't a copy, or gemini a link") + } + + f, err := ReadSkillFile("writer", "") + if err != nil { + t.Fatal(err) + } + if f.File != "SKILL.md" || !strings.Contains(f.Text, "description: Write well") { + t.Fatalf("read: %+v", f) + } + if want := []string{"SKILL.md", "refs/style.md", "scripts/run.sh"}; !slices.Equal(f.Files, want) { + t.Fatalf("files %v, want %v (the picture left out)", f.Files, want) + } + + time.Sleep(20 * time.Millisecond) + edited := strings.Replace(f.Text, "Write well", "Write well, briefly", 1) + ok(t)(SaveSkillFile("writer", "SKILL.md", edited, f.Text)) + for range 2 { // the save's sync, and the one of the next start + for _, p := range []string{skillDir("writer"), cx, gm} { + if s := read(t, filepath.Join(p, "SKILL.md")); s != edited { + t.Fatalf("%s:\n%s", p, s) + } + } + if !ours(cx, "writer") { + t.Fatal("codex's copy isn't magpie's any more") + } + ok(t)(Sync()) + } + + // another file of it + g, err := ReadSkillFile("writer", "refs/style.md") + if err != nil || g.Text != "# Style\n" { + t.Fatalf("refs/style.md: %+v %v", g, err) + } + ok(t)(SaveSkillFile("writer", "refs/style.md", "# Style\n\nShort.\n", g.Text)) + if s := read(t, filepath.Join(cx, "refs/style.md")); s != "# Style\n\nShort.\n" { + t.Fatalf("codex's refs/style.md: %q", s) + } +} + +// What the page opened has changed since (an agent's edit taken in, an +// update): the save writes nothing over it. +func TestSkillFileSaveRefusesAChangedFile(t *testing.T) { + h := sandbox(t) + src := filepath.Join(h, "src/skills") + skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") + ok(t)(InstallSkills(src, []string{"pdf"}, []string{"claude"})) + f, err := ReadSkillFile("pdf", "SKILL.md") + if err != nil { + t.Fatal(err) + } + now := strings.Replace(f.Text, "Read PDFs", "Changed meanwhile", 1) + write(t, filepath.Join(skillDir("pdf"), "SKILL.md"), now) + if _, err := SaveSkillFile("pdf", "SKILL.md", "mine", f.Text); err == nil || !strings.Contains(err.Error(), "changed since") { + t.Fatalf("saved over a changed file: %v", err) + } + if s := read(t, filepath.Join(skillDir("pdf"), "SKILL.md")); s != now { + t.Fatalf("written over: %q", s) + } + if _, err := SaveSkillFile("nope", "SKILL.md", "x", ""); err == nil { + t.Fatal("saved a skill the library hasn't") + } +} + +// Only the skill's own files: no way out of its folder, through .. or a +// link, and none of what magpie leaves aside. +func TestSkillFileStaysInTheSkill(t *testing.T) { + h := sandbox(t) + src := filepath.Join(h, "src/skills") + skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") + write(t, filepath.Join(h, "secret.txt"), "key=1\n") + write(t, filepath.Join(h, "outside/notes.md"), "out\n") + ok(t)(InstallSkills(src, []string{"pdf"}, []string{"claude"})) + dir := realDir(skillDir("pdf")) + symlink(t, filepath.Join(h, "secret.txt"), filepath.Join(dir, "link.txt")) + symlink(t, filepath.Join(h, "outside"), filepath.Join(dir, "out")) + write(t, filepath.Join(dir, "node_modules/x/README.md"), "dep\n") + for _, bad := range []string{"../../secret.txt", "/etc/hosts", "link.txt", "out/notes.md", "node_modules/x/README.md", ".magpie", "scripts", ""} { + if _, err := SaveSkillFile("pdf", bad, "x", ""); err == nil { + t.Errorf("saved %q", bad) + } + if bad != "" { + if _, err := ReadSkillFile("pdf", bad); err == nil { + t.Errorf("read %q", bad) + } + } + } + if s := read(t, filepath.Join(h, "secret.txt")); s != "key=1\n" { + t.Fatalf("written outside: %q", s) + } + f, err := ReadSkillFile("pdf", "") + if err != nil { + t.Fatal(err) + } + if want := []string{"SKILL.md", "scripts/run.sh"}; !slices.Equal(f.Files, want) { + t.Fatalf("files %v, want %v", f.Files, want) + } +} + +// A file written with Windows line ends keeps them: the page's text has +// \n alone. +func TestSkillFileKeepsLineEnds(t *testing.T) { + h := sandbox(t) + src := filepath.Join(h, "src/skills") + write(t, filepath.Join(src, "crlf/SKILL.md"), "---\r\nname: crlf\r\ndescription: CRLF\r\n---\r\n") + ok(t)(InstallSkills(src, []string{"crlf"}, []string{"claude"})) + f, err := ReadSkillFile("crlf", "") + if err != nil { + t.Fatal(err) + } + page := strings.ReplaceAll(f.Text, "\r\n", "\n") + "More.\n" + ok(t)(SaveSkillFile("crlf", "SKILL.md", page, f.Text)) + if s := read(t, filepath.Join(skillDir("crlf"), "SKILL.md")); s != f.Text+"More.\r\n" { + t.Fatalf("%q", s) + } + if _, err := os.Stat(filepath.Join(skillDir("crlf"), "SKILL.md")); err != nil { + t.Fatal(err) + } +} diff --git a/internal/library/skills.go b/internal/library/skills.go index f67707ce3..3b8de4de3 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -2667,17 +2667,5 @@ func sameFile(a, b string) (same, sure bool) { } } -// SkillText is a library skill's SKILL.md, for the page to show. -func SkillText(name string) (string, error) { - if err := checkName("skill", name); err != nil { - return "", err - } - b, err := os.ReadFile(filepath.Join(skillDir(name), "SKILL.md")) - if err != nil { - return "", fmt.Errorf("%s has no SKILL.md in the library", name) - } - return string(b), nil -} - // SkillPath is where a library skill's folder is. func SkillPath(name string) string { return skillDir(name) }