diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index ec5808f15..73256861f 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -16,7 +16,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | 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) | | 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. 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. | [`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, Hooks and Subagents pages leave a stopped distro's agents out still (#4182, #4237, #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) | +| 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 and Subagents pages leave a stopped distro's agents out still (#4237, #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, 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 and Cline. 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) 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, and what it made is listed in the project's `.gitignore`. | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go) | | Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). A set can be kept in a file of the user's own instead of `instruction-sets/` (`InstrSet.File`, 新v学员 on Discord): `~/.agents/AGENTS.md`, which Droid and omp read too. `textPath` reads it, `putText` keeps it aside and writes it but never removes it, removing the set lets go of it, and `linkable` refuses a file magpie writes into (an agent's own instructions, a file with the marker line), the library's own and another set's. The app's `KeepLinked` looks at the file every 30 s and writes a change into the agents (`SyncLinked`). A set's text is read without magpie's part (`setText`), and an agent whose instructions file is, links followed, the file the set on is kept in (`isSetFile`: `instructions.md` linked to `~/.claude/CLAUDE.md`, or both linked to one dotfile) gets no part written into it, and one written before is taken out with every part nested in it: read with its part, each sync wrote the whole file into that part again and it doubled, to gigabytes (#2349, `TestInstructionsSetLinkedToAgentsFile`). `Collect` carries the set's text, not where its file is; `Put` keeps this computer's file for the set and never empties it for a text not carried. Alma's file is `~/.config/alma/USER.md`, which its main chat reads into its system prompt as its owner's profile (0.4.164's `out/main/index.js`; a workspace's `USER.md` is read instead), and whose leading front matter (`name`, `telegram_id`, `discord_id`) is who its bots answer to (#2315, Jie211). The target is a `Profile`: magpie's part goes after the user's, so the front matter stays first, and `ImportInstructions` refuses it, as moving it out would take that front matter out of the file and into every agent's (`TestAlmaInstructionsKeepTheProfile`, `TestAlmaProfileIsNotImported`, `library-alma-profile.test.cjs`). | [`instructions.go`](../../internal/library/instructions.go) | diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index e24e76cf1..45bbbc3a0 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -77,9 +77,10 @@ magpie.plugin("library", (ctx) => { // has of the hub, and can't be read without starting it const hubAgents = () => mcpAgents().filter((a) => !a.asleep); // one line for each stopped WSL distro the page lists agents of: they - // show what magpie last saw, and a change waits for the distro to run - function asleepAsides() { - const seen = lib.agents.filter((a) => a.asleep && !isHidden(a)); + // show what magpie last saw, and a change waits for the distro to run. + // The Instructions page passes its own rows' agents ({asleep, unseen, + // name}). + function asleepAsides(seen = lib.agents.filter((a) => a.asleep && !isHidden(a))) { return [...new Set(seen.map((a) => a.asleep))].map((d) => { const unseen = seen.filter((a) => a.asleep === d && a.unseen).map((a) => a.name); const p = el("p", "lib-aside lib-asleep", t("WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.", { distro: d })); @@ -1334,8 +1335,11 @@ magpie.plugin("library", (ctx) => { for (const a of rows) list.append(...instructionsRow(a)); if (!rows.length) list.append(el("div", "lib-none", t("None of your agents reads a user-wide instructions file magpie knows."))); body.append(list); + // a stopped WSL distro's agents are rows above when magpie saw their + // file; one it didn't see isn't said to keep none const skip = shownAgents().filter((a) => !a.instructions && !a.asleep); if (skip.length) body.append(el("p", "lib-aside", t(skip.length > 1 ? "{agents} keep no user-wide instructions file." : "{agents} keeps no user-wide instructions file.", { agents: skip.map((a) => a.name).join(", ") }))); + body.append(...asleepAsides(rows.filter((a) => a.asleep))); body.append(bar); } @@ -1463,14 +1467,20 @@ magpie.plugin("library", (ctx) => { return row; } + // An agent in a stopped WSL distro (asleep) is its row as magpie last saw + // it, greyer: its file isn't read or shown in the file manager, either of + // which would start WSL (#3896), and a switch is written there the next + // time it runs. One whose file magpie never saw (unseen) is listed only + // while it is on, its switch kept as it is (#4182). function instructionsRow(a) { const isOpen = open.has(a.agent); - const row = el("div", "row lib-row click" + (isOpen ? " open" : "")); + const row = el("div", "row lib-row click" + (isOpen ? " open" : "") + (a.asleep ? " asleep" : "")); const who = el("div", "who"); const name = el("div", "name", a.name); who.append(name); const sub = el("div", "sub"); - sub.append(pathLink(a.path)); + if (a.asleep) { if (a.path) sub.append(el("span", "lib-path", tilde(a.path))); } + else sub.append(pathLink(a.path)); who.append(sub); const tags = el("div", "lib-tags"); const extra = extras[a.agent] ?? a.extra; @@ -1480,7 +1490,8 @@ magpie.plugin("library", (ctx) => { if (a.own) tags.append(tag(a.own === 1 ? t("1 line of its own") : t("{n} lines of its own", { n: a.own }), "", t("The file has instructions besides magpie's part — they stay, and the agent reads both"))); const chev = el("span", "chev"); chev.append(svg(CHEV_R, 11, 1.7)); - row.append(icon(a.icon), who, tags, toggle(a.on, t("{agent} reads the shared instructions", { agent: a.name }), (on) => { + const sw = toggle(a.on, t("{agent} reads the shared instructions", { agent: a.name }), (on) => { + if (a.unseen) return; const agents = lib.instructions.agents.filter((x) => (x.agent === a.agent ? on : x.on)).map((x) => x.agent); let done = t("Taken out of {agent}'s file", { agent: a.name }); if (on && dirty()) done = t("{agent} is on — save to write the new text into its file", { agent: a.name }); @@ -1491,8 +1502,13 @@ magpie.plugin("library", (ctx) => { : t("{agent} is on — it gets the shared instructions once there are some", { agent: a.name }); } else if (on) done = t("{agent} reads the shared instructions now", { agent: a.name }); + if (a.asleep) done = asleepSaid; change("instructions/save", { agents }, done); - }), chev); + }); + const asleepSaid = a.asleep && t("WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.", { distro: a.asleep }); + if (a.unseen) { sw.setAttribute("aria-disabled", "true"); sw.title = t("WSL {distro} isn't running, and magpie hasn't seen {agent}'s files there yet: start the distro to change this", { distro: a.asleep, agent: a.name }); } + else if (a.asleep) sw.title = asleepSaid; + row.append(icon(a.icon), who, tags, sw, chev); row.onclick = () => { if (isOpen) open.delete(a.agent); else open.add(a.agent); render(); }; if (!isOpen) return [row]; diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index 7e7fbfb82..04ab3192f 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -316,7 +316,9 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-ag.blocked { opacity: .35; } .lib-ag.blocked:hover { background: none; } /* a stopped WSL distro's agent: shown as last seen, quietly greyer */ -.lib-ag.asleep .ic { opacity: .55; filter: grayscale(1); } +.lib-ag.asleep .ic, .lib-row.asleep > .ic { opacity: .55; filter: grayscale(1); } +.lib-row.asleep .lib-path:hover { color: var(--muted); text-decoration: none; } +.lib-row.asleep .lib-switch[aria-disabled="true"] { opacity: .35; cursor: default; } .lib-ag:active:not(.blocked) { transform: scale(.92); } .editor .lib-agents { max-width: none; justify-content: flex-start; gap: 5px; } .editor .lib-ag { padding: 0 9px 0 6px; border-color: var(--line); } diff --git a/internal/gui/tests/library-wsl-asleep.test.cjs b/internal/gui/tests/library-wsl-asleep.test.cjs index c25179efc..b6e6b83c3 100644 --- a/internal/gui/tests/library-wsl-asleep.test.cjs +++ b/internal/gui/tests/library-wsl-asleep.test.cjs @@ -7,9 +7,10 @@ // next runs. One whose places magpie never saw (unseen) is only on the // rows that name it, greyed out, kept by every click on the row, and a // click on it says why. One line under the list names the distro. Nothing -// here starts WSL (#3896): the page only reads /api/library. Chromium and -// WebKit, 1100px and 390px, in en, zh, zh-TW, ja and de. No backend: the -// API is faked here. +// here starts WSL (#3896): the page only reads /api/library. The +// Instructions page lists them the same way (#4182). Chromium and WebKit, +// 1100px and 390px, in en, zh, zh-TW, ja and de. No backend: the API is +// faked here. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -21,14 +22,24 @@ const assets = path.resolve(__dirname, "../assets"); const HOME = "/Users/me", D = "Ubuntu-24.04"; const CX = "codex@wsl:" + D, PI = "pi@wsl:" + D; const srv = (name, agents, more = {}) => ({ name, transport: "stdio", command: "uvx", args: [name], agents, ...more }); -const lib = (servers) => ({ +const lib = (servers, instructions = { agents: [] }) => ({ dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, agents: [ - { id: "claude", name: "Claude Code", icon: "", mcp: `${HOME}/.claude.json`, skills: `${HOME}/.claude/skills` }, + { id: "claude", name: "Claude Code", icon: "", instructions: `${HOME}/.claude/CLAUDE.md`, mcp: `${HOME}/.claude.json`, skills: `${HOME}/.claude/skills` }, { id: CX, name: "Codex · WSL " + D, icon: "", mcp: "\\\\wsl.localhost\\" + D + "\\home\\me\\.codex\\config.toml", skills: "\\\\wsl.localhost\\" + D + "\\home\\me\\.codex\\skills", noSSE: true, mustCopy: true, how: "copy", asleep: D }, { id: PI, name: "Pi · WSL " + D, icon: "", asleep: D, unseen: true }, ], - instructions: { agents: [] }, servers, skills: [], foundServers: [], projects: [], foundSkills: [], problems: [], + instructions, servers, skills: [], foundServers: [], projects: [], foundSkills: [], problems: [], +}); +// the Instructions page's rows: Claude Code here, Codex in the stopped +// distro at the file magpie last saw, and Pi on there, its file never seen +const instr = (on) => ({ + shared: "Be brief.", sets: [{ id: "default", name: "", active: true, text: "Be brief." }], + agents: [ + { agent: "claude", name: "Claude Code", icon: "", path: `${HOME}/.claude/CLAUDE.md`, on: on.includes("claude"), extra: "" }, + { agent: CX, name: "Codex · WSL " + D, icon: "", path: "\\\\wsl.localhost\\" + D + "\\home\\me\\.codex\\AGENTS.md", on: on.includes(CX), extra: "", asleep: D }, + { agent: PI, name: "Pi · WSL " + D, icon: "", path: "", on: on.includes(PI), extra: "", asleep: D, unseen: true }, + ], }); let I18N; @@ -48,10 +59,15 @@ function server(lang, state, posts) { 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.servers)); - if (url.pathname.startsWith("/api/library/") && req.method() === "POST" && !url.pathname.endsWith("/reveal") && !url.pathname.includes("/check")) { + if (url.pathname === "/api/library") return json(lib(state.servers, state.instr)); + if (url.pathname === "/api/library/reveal") { (state.reveals ||= []).push(req.postDataJSON()); return json({}); } + if (url.pathname.startsWith("/api/library/") && req.method() === "POST" && !url.pathname.includes("/check")) { const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", ""); posts.push({ what, body }); + if (what === "instructions/save" && state.instr) { + state.instr = instr(body.agents); + return json({ part: "instructions", instructions: state.instr, result: { changed: [] } }); + } if (what === "servers/agents") { state.servers = state.servers.map((s) => (s.name === body.name ? { ...s, agents: [...body.agents].sort() } : s)); return json({ ...lib(state.servers), result: { changed: [] } }); @@ -156,3 +172,81 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", } }); } + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + // #4182: the Instructions page leaves them out no more. Codex's row is + // at the file magpie last saw, greyer, its path no button (the file + // manager would start WSL); its switch says the distro isn't running and + // is sent as any is. Pi, on, whose file magpie never saw, is greyed out + // and kept on by every switch: before, a switch sent the agents without + // the stopped distro's, which took them off. + test(engine + ": a stopped WSL distro's agents are on the Instructions page as last seen", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + I18N = strings().I18N; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + for (const 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 = { servers: [], instr: instr(["claude", PI]) }; + const posts = [], errors = []; + const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "instructions"); } 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-row:not(.lib-set)").filter({ has: page.locator(".name", { hasText: new RegExp("^" + name) }) }); + const sw = (name) => row(name).locator(".lib-switch"); + const asleep = w("WSL {distro} isn't running: its agents show what magpie last saw there, and what you change is written there the next time it runs.", { distro: D }); + await row("Codex").waitFor(); + + assert.doesNotMatch(await row("Claude Code").getAttribute("class"), /\basleep\b/); + assert.match(await row("Codex").getAttribute("class"), /\basleep\b/); + assert.equal(await row("Codex").locator(".lib-path").evaluate((e) => e.tagName), "SPAN"); + assert.equal(await sw("Codex").getAttribute("aria-checked"), "false"); + assert.equal(await sw("Codex").getAttribute("aria-disabled"), null); + assert.equal(await sw("Codex").getAttribute("title"), asleep); + assert.match(await row("Pi").getAttribute("class"), /\basleep\b/); + assert.equal(await row("Pi").locator(".lib-path").count(), 0); + assert.equal(await sw("Pi").getAttribute("aria-checked"), "true"); + assert.equal(await sw("Pi").getAttribute("aria-disabled"), "true"); + assert.equal(await sw("Pi").getAttribute("title"), w("WSL {distro} isn't running, and magpie hasn't seen {agent}'s files there yet: start the distro to change this", { distro: D, agent: "Pi · WSL " + D })); + // one line for the distro, naming Pi; neither is said to keep no + // instructions file + const aside = v.locator(".lib-asleep"); + assert.equal(await aside.count(), 1); + assert.equal(await aside.textContent(), asleep + " " + w("{agents} can be changed once it runs.", { agents: "Pi · WSL " + D })); + for (const x of await v.locator(".lib-aside:not(.lib-asleep)").allTextContents()) assert.doesNotMatch(x, /WSL/); + assert.deepEqual(await sideways(page), [], "sideways with the rows"); + + // Codex's path clicked: no file manager asked for + await row("Codex").locator(".lib-path").click(); + await page.waitForTimeout(200); + assert.deepEqual(state.reveals || [], []); + // Pi's switch clicked: nothing sent + await sw("Pi").click({ force: true }); + await page.waitForTimeout(200); + assert.deepEqual(posts, []); + // Codex switched on while its distro is stopped: sent, Pi kept on, + // and the status says when it is written + await sw("Codex").click(); + await page.waitForFunction((want) => document.querySelector("#status").textContent === want, asleep).catch(() => {}); + assert.deepEqual(posts.map((p) => p.what), ["instructions/save"]); + assert.deepEqual(posts[0].body, { agents: ["claude", CX, PI] }); + assert.equal(await page.locator("#status").textContent(), asleep); + assert.equal(await sw("Codex").getAttribute("aria-checked"), "true"); + // Claude Code switched off: both of the stopped distro's stay on + await sw("Claude Code").click(); + await page.waitForTimeout(300); + assert.deepEqual(posts[1], { what: "instructions/save", body: { agents: [CX, PI] } }); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/library/instructions.go b/internal/library/instructions.go index 1e7611f4f..8132efecd 100644 --- a/internal/library/instructions.go +++ b/internal/library/instructions.go @@ -14,6 +14,7 @@ import ( "sync" "time" + "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/edit" ) @@ -305,6 +306,12 @@ type AgentInstructions struct { Edited bool `json:"edited,omitempty"` // magpie's part was changed in the file Override string `json:"override,omitempty"` // a file the agent reads instead Profile bool `json:"profile,omitempty"` // the file is the user's profile to the agent (Target.Profile) + // Asleep is the WSL distro, not running now, the agent is in: its row + // is what magpie last knew of it (asleepInstructions), its file isn't + // read, and a change is written there when the distro next runs. + // Unseen: magpie never saw where it keeps its instructions + Asleep string `json:"asleep,omitempty"` + Unseen bool `json:"unseen,omitempty"` } // InstructionsView is the Instructions page. @@ -331,13 +338,14 @@ func ReadInstructions() (*InstructionsView, error) { if err != nil { return nil, err } - return l.instructionsView(Targets()), nil + return l.instructionsView(targetsAsleep(false)), nil } -// instructionsView is the Instructions page for these agents. They are -// passed in: finding them looks through every agent's folders, in WSL too, -// which one read of the Library did three times over (#1624). -func (l *Library) instructionsView(targets []*Target) *InstructionsView { +// instructionsView is the Instructions page for these agents, and those in +// stopped WSL distros (asleep). They are passed in: finding them looks +// through every agent's folders, in WSL too, which one read of the Library +// did three times over (#1624). +func (l *Library) instructionsView(targets []*Target, asleep []*agent.Agent) *InstructionsView { v := &InstructionsView{Shared: setText(l.sharedPath()), Agents: []AgentInstructions{}} for _, s := range l.sets() { v.Sets = append(v.Sets, SetView{ID: s.ID, Name: s.Name, Text: setText(l.textPath(s.ID)), Active: s.ID == l.active(), File: s.File}) @@ -361,6 +369,13 @@ func (l *Library) instructionsView(targets []*Target) *InstructionsView { } v.Agents = append(v.Agents, ai) } + // a stopped WSL distro's agents, by what magpie last knew of them: + // nothing of theirs is opened, which would start the distro (#3896) + for _, a := range asleep { + if ai, ok := l.asleepInstructions(a); ok { + v.Agents = append(v.Agents, ai) + } + } return v } diff --git a/internal/library/sync.go b/internal/library/sync.go index a3a158b99..538aa6d7d 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -546,7 +546,7 @@ func readView(problems []Problem, glance bool) (*View, error) { // the agents are found once for the whole read: finding them looks // through every agent's folders, in WSL too (#1624) targets, asleep := targetsAsleep(false) - v := &View{Agents: []AgentView{}, Servers: []ServerView{}, Skills: []SkillView{}, FoundSkills: []FoundSkill{}, Instructions: l.instructionsView(targets), Dir: Dir(), Backups: BackupDir(), CopySkills: l.CopySkills, MCPHub: l.MCPHub, HubPath: gateway.HubMCPPath, Partial: glance} + v := &View{Agents: []AgentView{}, Servers: []ServerView{}, Skills: []SkillView{}, FoundSkills: []FoundSkill{}, Instructions: l.instructionsView(targets, asleep), Dir: Dir(), Backups: BackupDir(), CopySkills: l.CopySkills, MCPHub: l.MCPHub, HubPath: gateway.HubMCPPath, Partial: glance} for _, t := range targets { av := AgentView{ID: t.Agent.ID, Name: t.Agent.Name, Icon: t.Agent.Icon, Instructions: t.Instructions, Skills: t.Skills, SkillsAlso: t.SkillsAlso, Note: t.Note, MCPVia: t.MCPVia, ProjectSkills: ProjectSkillsDir(t.Agent.ID), ProjectMCP: ProjectMCPFile(t.Agent.ID), diff --git a/internal/library/targets.go b/internal/library/targets.go index 0c4947a96..f29f1f9aa 100644 --- a/internal/library/targets.go +++ b/internal/library/targets.go @@ -917,9 +917,10 @@ func Takes(q, kind string) (string, error) { t := targetOf(a) var has bool if t == nil && isAsleep(a) { - // one magpie saw it give MCP servers or skills a place to is - // recorded, and given them when the distro next runs (Woken) - if sh := shapeOf(a); sh != nil && (kind == "mcp" && sh.MCP != "" || kind == "skills" && sh.Skills != "") { + // one magpie saw it give instructions, MCP servers or skills a + // place to is recorded, and given them when the distro next runs + // (Woken) + if sh := shapeOf(a); sh != nil && (kind == "instructions" && sh.Instructions != "" || kind == "mcp" && sh.MCP != "" || kind == "skills" && sh.Skills != "") { return a.ID, nil } return "", fmt.Errorf("WSL %s isn't running: start it, and %s can be given %s", a.WSL, a.Name, what) diff --git a/internal/library/wsl_asleep.go b/internal/library/wsl_asleep.go index bf2ccaff5..7e71b17f2 100644 --- a/internal/library/wsl_asleep.go +++ b/internal/library/wsl_asleep.go @@ -15,25 +15,28 @@ import ( // can't be opened without starting the distro (#3896). The page lists them // all the same (cybercaius on Discord: the MCP page knew a distro's agents // only once WSL had started), from what magpie learnt of them while the -// distro ran — the places it gives each one MCP servers and skills, kept -// in wsl.json beside the probe's memory (shape) — with the ticks the -// library has for them. A tick there is kept as any is, in library.json, -// and written into the distro the next time it runs (Woken): nothing is -// opened while it is stopped, and nothing starts it but the user. +// distro ran (the places it gives each one instructions, MCP servers and +// skills, kept in wsl.json beside the probe's memory: shape), with the +// ticks the library has for them. A tick there is kept as any is, in +// library.json, and written into the distro the next time it runs (Woken): +// nothing is opened while it is stopped, and nothing starts it but the +// user. -// shape is what the library last knew of where a WSL agent keeps its MCP -// servers and skills, and what its MCP file can take: an AgentView's, so -// the page can show the agent's ticks while its distro is stopped. +// shape is what the library last knew of where a WSL agent keeps its +// instructions, MCP servers and skills, and what its MCP file can take: an +// AgentView's, so the page can show the agent's ticks while its distro is +// stopped. type shape struct { - MCP string `json:"mcp,omitempty"` - Skills string `json:"skills,omitempty"` - SkillsAlso []string `json:"skillsAlso,omitempty"` - MCPVia string `json:"mcpVia,omitempty"` - NoSSE bool `json:"noSSE,omitempty"` - NoRemote bool `json:"noRemote,omitempty"` - NoEnvRefs bool `json:"noEnvRefs,omitempty"` - ToolsOff bool `json:"toolsOff,omitempty"` - Startup bool `json:"startup,omitempty"` + Instructions string `json:"instructions,omitempty"` + MCP string `json:"mcp,omitempty"` + Skills string `json:"skills,omitempty"` + SkillsAlso []string `json:"skillsAlso,omitempty"` + MCPVia string `json:"mcpVia,omitempty"` + NoSSE bool `json:"noSSE,omitempty"` + NoRemote bool `json:"noRemote,omitempty"` + NoEnvRefs bool `json:"noEnvRefs,omitempty"` + ToolsOff bool `json:"toolsOff,omitempty"` + Startup bool `json:"startup,omitempty"` } // shapeKey is the key a WSL agent's shape is kept under in its distro's @@ -46,7 +49,7 @@ func shapeKey(id string) string { // keepShape remembers t's shape, t being an agent in a running distro. func keepShape(t *Target) { a := t.Agent - sh := shape{Skills: t.Skills, SkillsAlso: t.SkillsAlso, MCPVia: t.MCPVia} + sh := shape{Instructions: t.Instructions, Skills: t.Skills, SkillsAlso: t.SkillsAlso, MCPVia: t.MCPVia} if t.MCP != nil { sh.MCP = t.MCP.Path sh.NoSSE = t.MCP.supports(&Server{Transport: "sse"}) != nil @@ -65,10 +68,11 @@ func keepShape(t *Target) { } // shapeOf is the shape kept for a, an agent in a stopped distro; nil when -// magpie never saw it with an MCP file or a skills folder. +// magpie never saw it with an instructions file, an MCP file or a skills +// folder. func shapeOf(a *agent.Agent) *shape { var sh shape - if json.Unmarshal([]byte(agent.WSLKept(a.WSL, shapeKey(a.ID))), &sh) != nil || sh.MCP == "" && sh.Skills == "" { + if json.Unmarshal([]byte(agent.WSLKept(a.WSL, shapeKey(a.ID))), &sh) != nil || sh.Instructions == "" && sh.MCP == "" && sh.Skills == "" { return nil } return &sh @@ -118,6 +122,27 @@ func (l *Library) asleepView(a *agent.Agent) (AgentView, bool) { return av, true } +// asleepInstructions is a stopped distro's agent as the Instructions page +// lists it: at the file magpie last saw it read, switched on as the +// library has it, with what it gets besides (kept in magpie's own folder); +// what its file holds isn't read. One switched on whose file magpie never +// saw is listed as Unseen, to be kept on; false for one the page leaves +// out. +func (l *Library) asleepInstructions(a *agent.Agent) (AgentInstructions, bool) { + on := slices.Contains(l.Instructions.Agents, a.ID) + sh := shapeOf(a) + if (sh == nil || sh.Instructions == "") && !on { + return AgentInstructions{}, false + } + ai := AgentInstructions{Agent: a.ID, Name: a.Name, Icon: a.Icon, On: on, Extra: readText(extraPath(a.ID)), Asleep: a.WSL} + if sh != nil && sh.Instructions != "" { + ai.Path = sh.Instructions + } else { + ai.Unseen = true + } + return ai, true +} + // names says whether the library gives the agent id anything, or holds // something it gave it. func (l *Library) names(id string) bool { @@ -128,7 +153,8 @@ func (l *Library) names(id string) bool { slices.ContainsFunc(l.MCP, func(s *Server) bool { return slices.Contains(s.Agents, id) }) } -// distrosNamed are the WSL distros the library names an agent in. +// distrosNamed are the WSL distros the library names an agent in: one it +// gives anything, instructions included, or holds anything it gave. func (l *Library) distrosNamed() []string { in := map[string]bool{} add := func(id string) { @@ -136,11 +162,14 @@ func (l *Library) distrosNamed() []string { in[d] = true } } - for id := range l.Applied { - if l.names(id) { + for id, a := range l.Applied { + if l.names(id) || a != nil && a.Instructions { add(id) } } + for _, id := range l.Instructions.Agents { + add(id) + } for _, s := range l.Skills { for _, id := range s.Agents { add(id) diff --git a/internal/library/wsl_test.go b/internal/library/wsl_test.go index 495947f59..d0363302f 100644 --- a/internal/library/wsl_test.go +++ b/internal/library/wsl_test.go @@ -433,6 +433,141 @@ func TestWSLStoppedUnseen(t *testing.T) { } } +// instrRow is the agent id's row on the Instructions page, nil for none. +func instrRow(t *testing.T, id string) *AgentInstructions { + t.Helper() + iv, err := ReadInstructions() + if err != nil { + t.Fatal(err) + } + v, err := Read(nil) + if err != nil { + t.Fatal(err) + } + // the page's whole read and the one after an instructions change agree + if len(v.Instructions.Agents) != len(iv.Agents) { + t.Errorf("Read lists %d instructions rows, ReadInstructions %d", len(v.Instructions.Agents), len(iv.Agents)) + } + for _, a := range iv.Agents { + if a.Agent == id { + return &a + } + } + return nil +} + +// #4182: the Instructions page left a stopped distro's agents out, so +// none could be switched on until WSL ran, and a switch on the page sent +// the agents without them. They are listed at the file magpie last saw +// them read, switched as the library has them, and a switch is written +// into the distro once it runs (Woken), on or off. Nothing of the distro +// is opened or run while it is stopped (#3896): not even its file, whose +// own lines aren't counted then. +func TestWSLStoppedInstructions(t *testing.T) { + const distro = "Ubuntu-24.04" + h := wslSandbox(t) + agentsMD := filepath.Join(h, ".codex", "AGENTS.md") + write(t, agentsMD, "Mine.\n") + shared := "Be brief." + // the distro seen running, nothing of the library given to it + ok(t)(SaveInstructions(InstructionsChange{Shared: &shared, Agents: []string{"claude"}})) + if r := instrRow(t, wslCodex); r == nil || r.Asleep != "" || r.Own != 1 { + t.Fatalf("Codex while running: %+v", r) + } + root := filepath.Dir(filepath.Dir(h)) + away := root + ".away" + stop := func() { + t.Helper() + agent.StopFakeWSL(distro) + // the distro's files gone from reach: anything opened there fails, + // anything written there makes its folder again + if err := os.Rename(root, away); err != nil { + t.Fatal(err) + } + if res, err := Woken(); res != nil || err != nil { + t.Errorf("a sync while the distro is stopped: %+v %v", res, err) + } + } + start := func() { + t.Helper() + if _, err := os.Stat(root); !os.IsNotExist(err) { + t.Errorf("something was written into the stopped distro: %v", err) + } + if err := os.Rename(away, root); err != nil { + t.Fatal(err) + } + agent.StartFakeWSL(distro) + if res, err := Woken(); err != nil || res == nil { + t.Fatalf("no sync once the distro ran: %+v %v", res, err) + } + } + stop() + runs := agent.FakeWSLRuns(distro) + cx := instrRow(t, wslCodex) + if cx == nil { + t.Fatal("a stopped distro's Codex isn't on the Instructions page") + } + if cx.Asleep != distro || cx.Unseen || cx.On || cx.Path != agentsMD || cx.Own != 0 || cx.Edited || cx.Override != "" { + t.Errorf("Codex while stopped: %+v", *cx) + } + if cl := instrRow(t, wslClaude); cl == nil || cl.Asleep != distro || cl.Path != filepath.Join(h, ".claude", "CLAUDE.md") { + t.Errorf("Claude Code while stopped: %+v", cl) + } + if id, err := Takes("Codex · WSL "+distro, "instructions"); err != nil || id != wslCodex { + t.Errorf("Takes while stopped: %s %v", id, err) + } + // switched on while stopped: kept, and on the page as on + ok(t)(SaveInstructions(InstructionsChange{Agents: []string{"claude", wslCodex}})) + if l, _ := load(); !slices.Equal(l.Instructions.Agents, []string{"claude", wslCodex}) { + t.Errorf("the agents: %v", l.Instructions.Agents) + } + if r := instrRow(t, wslCodex); r == nil || !r.On { + t.Errorf("Codex switched on while stopped: %+v", r) + } + if n := agent.FakeWSLRuns(distro); n != runs { + t.Errorf("%d commands ran in the stopped distro", n-runs) + } + start() + if s := read(t, agentsMD); !strings.HasPrefix(s, "Mine.\n") || !strings.Contains(s, "Be brief.") { + t.Errorf("codex@wsl AGENTS.md once the distro ran:\n%s", s) + } + if r := instrRow(t, wslCodex); r == nil || r.Asleep != "" || !r.On || r.Own != 1 { + t.Errorf("Codex once running: %+v", r) + } + // switched off while stopped: the part is taken out once it runs, + // though no agent of the distro is on any more + stop() + ok(t)(SaveInstructions(InstructionsChange{Agents: []string{"claude"}})) + start() + if s := read(t, agentsMD); s != "Mine.\n" { + t.Errorf("codex@wsl AGENTS.md once switched off and run:\n%s", s) + } +} + +// One the library switched on in a distro that stopped before magpie +// saw its file is listed as on, unseen, to be kept on; one never seen and +// not on isn't listed. +func TestWSLStoppedInstructionsUnseen(t *testing.T) { + const distro = "Ubuntu-24.04" + wslSandbox(t) + agent.All() // the probe, while it runs; no target is made + agent.StopFakeWSL(distro) + runs := agent.FakeWSLRuns(distro) + ok(t)(SaveInstructions(InstructionsChange{Agents: []string{wslPi}})) + if r := instrRow(t, wslPi); r == nil || !r.Unseen || !r.On || r.Asleep != distro || r.Path != "" { + t.Errorf("Pi switched on while stopped: %+v", r) + } + if r := instrRow(t, wslCodex); r != nil { + t.Errorf("Codex on nowhere, never seen: %+v", r) + } + if _, err := Takes("Codex · WSL "+distro, "instructions"); err == nil || !strings.Contains(err.Error(), "isn't running") { + t.Errorf("Takes of an unseen agent: %v", err) + } + if n := agent.FakeWSLRuns(distro); n != runs { + t.Errorf("%d commands ran in the stopped distro", n-runs) + } +} + func TestLinuxHome(t *testing.T) { for in, want := range map[string]string{ `\\wsl.localhost\Ubuntu\home\me`: "/home/me",