Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
library: RTK for agents in WSL, with the distro's own rtk (lex on Discord)
yetone3ce2a9819faf
diff --git a/docs/subsystems/library.md b/docs/subsystems/library.mdindex d8b1a5f05..5dcae54d9 100644--- a/docs/subsystems/library.md+++ b/docs/subsystems/library.md@@ -31,6 +31,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.| Subagents | A `Subagent` (#2283) is a name (lowercase letters, digits and -), a one-line description, a prompt, and the library's skills and MCP servers it uses, given to the agents ticked for it. `syncSubagents` writes it as a file of its own in each agent's user-level folder, in that agent's format (`subagentSpecOf`): Markdown with YAML front matter in `~/.claude/agents` (with `skills` and `mcpServers`), `~/.factory/droids` (with `mcpServers`), `~/.config/opencode/agents` (`mode: subagent`), `~/.gemini/agents`, `~/.qwen/agents`, `~/.grok/agents`, `~/.cursor/agents` and `~/.copilot/agents` (`<name>.agent.md`); a TOML role (`name`, `description`, `developer_instructions`) in `$CODEX_HOME/agents`. Skills and servers are named only where the agent's file can name them, and only those the library has. The page lists, per agent, whether it binds skills and servers (`SubagentAgentView`) and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) || Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) || RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off). The page's No RTK hook tag gives each agent's own reason and rtk-ai/rtk issue (`rtkNoHookWhy` in plugins/library/client.js: dsh #3847, Grok Build and Grok App #2136), and an agent with no entry gets no link; `TestRTKNoHookIssuesAreEachAgents` fails when the page and `rtkNoHook` cite different issues, or two agents cite the same ones without a reason in `sharedRTKIssues`. | [`rtk.go`](../../internal/library/rtk.go) |+| RTK in WSL | An agent in a WSL distro (`claude@wsl:Ubuntu`) is listed by its kind (`rtkKind`), and its hook runs in the distro, where Windows' rtk.exe is no command, so it gets the distro's own rtk (lex on Discord). `rtkDistroOf` asks the distro with `wsl.exe -d <distro> -e sh -lc` where rtk is (a login or interactive shell's PATH; else `~/.local/bin` or `~/.cargo/bin`, `offPath`), kept 15s; `ReadRTK` lists one `RTKDistro` for each distro its agents are in. Install RTK in WSL `<distro>` (`InstallRTKIn`, `POST /api/library/rtk/install` with `distro`, `magpie library rtk install <distro>`) runs RTK's own Linux installer in the distro (`curl -fsSL …/install.sh \| sh`, wget where there's no curl). Switching an agent on runs the distro's rtk there (`rtkInstallWSL`: `rtk init -g …` with its folder on PATH, Claude Code pointed at a folder of its own for the OpenCode and Cursor installers), and reads and edits its files under the distro's home as magpie opens it (`rtkClaudeDir`, `rtkCodexDir`, `rtkHome`). A distro that isn't running is never started (#3896): `rtkWSLLive` and `rtkDistroOf` check `agent.WSLRunning` first, its agents are listed `asleep` with the switch off, and switching or installing says to start it (`TestRTKWSLAsleep`). The page gives each distro a card (`rtkDistroCard` in plugins/library/client.js; library-rtk-wsl.test.cjs). | [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) |## Runtime path@@ -89,6 +90,8 @@ go test -tags nogui ./internal/cli -run 'TestLibrarySkillRm|TestLibrarySkillHandgo test -race ./internal/mcpauthgo test -tags nogui ./internal/librarygo test -tags nogui ./internal/library -run 'TestWSLStopped'+go test -tags nogui ./internal/library -run 'TestRTKWSL'+node --test internal/gui/tests/library-rtk-wsl.test.cjsnode --test internal/gui/tests/library-wsl-asleep.test.cjsnode --test internal/gui/tests/skill-off-here.test.cjs internal/gui/tests/skill-handover.test.cjsnode --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-mcp-hub.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-gone.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/library-mcp-health-wsl.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjsdiff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.goindex b3765b465..41f7f6339 100644--- a/internal/cli/library_cli.go+++ b/internal/cli/library_cli.go@@ -41,6 +41,7 @@ const libraryUsage = `magpie library what the library givesmagpie library rtk which agents run their shell commands through RTK (rtk-ai.app), to save tokensmagpie library rtk on|off <agent> switch it (on with RTK's own installer; off works with RTK gone)magpie library rtk install install RTK (Homebrew, winget, or RTK's own script)+ magpie library rtk install <distro> install RTK in a WSL distro, for the agents there (RTK's own script, run there)magpie library rtk upgrade bring RTK up to its latest release, the way it was installedmagpie library rtk path put RTK on the PATH the agents get, when it isn't (their hooks run it by name)`@@ -501,6 +502,12 @@ func rtkCmd(args []string) error {if v, err = library.InstallRTK(); err != nil {return err}+ case len(args) == 2 && args[0] == "install":+ fmt.Println(muted.Render("installing rtk in WSL " + args[1] + "…"))+ var err error+ if v, err = library.InstallRTKIn(args[1]); err != nil {+ return err+ }case len(args) == 1 && args[0] == "path":var err errorif v, err = library.PathRTK(); err != nil {@@ -572,17 +579,42 @@ func rtkCmd(args []string) error {fmt.Println(muted.Render(" Codex runs its commands in its Windows sandbox, which can't write RTK's history, so what RTK saves there isn't counted"))}}+ // an agent in WSL runs its distro's rtk+ wslRTK := map[string]library.RTKDistro{}+ for _, d := range v.WSL {+ wslRTK[d.Name] = d+ switch {+ case d.Asleep:+ fmt.Println(muted.Render(" WSL " + d.Name + " isn't running: its agents are left as they are, and magpie doesn't start it"))+ case d.Path == "" && d.Install != "":+ fmt.Println(amber.Render(" rtk isn't installed in WSL "+d.Name), muted.Render("— magpie library rtk install "+d.Name+" runs there: "+d.Install))+ case d.Path == "":+ fmt.Println(amber.Render(" magpie couldn't look for rtk in WSL " + d.Name))+ case d.OffPath:+ fmt.Println(bold.Render(" WSL "+d.Name), muted.Render(d.Version+" · "+d.Path))+ fmt.Println(amber.Render(" rtk isn't on the PATH of WSL "+d.Name+"'s shells"), muted.Render("— add "+d.Path[:strings.LastIndex(d.Path, "/")]+" to PATH in your shell profile there"))+ default:+ fmt.Println(bold.Render(" WSL "+d.Name), muted.Render(d.Version+" · "+d.Path))+ }+ }for _, a := range v.Agents {mark := muted.Render("off")note := ""if a.NoHook {mark, note = muted.Render(" – "), muted.Render(" — "+a.Blocked)}+ path, offPath := v.Path, v.OffPath+ if a.WSL != "" {+ path, offPath = wslRTK[a.WSL].Path, wslRTK[a.WSL].OffPath+ }+ if a.Asleep {+ mark, note = muted.Render(" ? "), muted.Render(" — WSL "+a.WSL+" isn't running")+ }if a.On {mark = green.Render("on ")- if v.Path == "" {+ if path == "" {mark, note = amber.Render("on "), muted.Render(" — its hook calls rtk, which isn't installed: install it, or switch this off")- } else if v.OffPath {+ } else if offPath {mark, note = amber.Render("on "), muted.Render(" — its hook can't find rtk on PATH, so it does nothing")}}diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.jsindex 6b3900f90..faceb0205 100644--- a/internal/gui/assets/plugins/library/client.js+++ b/internal/gui/assets/plugins/library/client.js@@ -982,6 +982,8 @@ magpie.plugin("library", (ctx) => {card.append(acts);}body.append(card);+ // an agent in WSL runs its distro's own RTK (rtk_wsl.go): one card each+ for (const d of rtk.wsl || []) body.append(rtkDistroCard(d));const rh = el("div", "row-head");rh.append(el("span", "label", t("Agents")), el("span", "grow"), el("span", "note", t("restart an agent after switching it")));body.append(rh);@@ -992,22 +994,31 @@ magpie.plugin("library", (ctx) => {const who = el("div", "who");who.append(el("div", "name", a.name));row.append(icon(a.icon), who, el("span", "grow"));+ // an agent in WSL: its distro's RTK, not this computer's+ const kind = a.id.split("@")[0];+ const d = a.wsl ? (rtk.wsl || []).find((x) => x.name === a.wsl) : null;+ const path = a.wsl ? d?.path : rtk.path, offPath = a.wsl ? d?.offPath : rtk.offPath;+ if (a.asleep) row.append(tag(t("Not running"), "", t("WSL {distro} isn't running: magpie doesn't start it to read or change {agent}. Start the distro, then Check again.", { distro: a.wsl, agent: a.name })));// its hook calls an rtk that isn't there: switching it off still works- if (a.on && !rtk.path) row.append(tag(t("RTK missing"), "warn", t("{agent}'s hook calls rtk, which isn't installed, so its shell commands fail. Install RTK, or switch this off.", { agent: a.name })));+ else if (a.on && !path) row.append(tag(t("RTK missing"), "warn", a.wsl+ ? t("{agent}'s hook calls rtk, which isn't installed in WSL {distro}, so its shell commands fail. Install RTK there, or switch this off.", { agent: a.name, distro: a.wsl })+ : t("{agent}'s hook calls rtk, which isn't installed, so its shell commands fail. Install RTK, or switch this off.", { agent: a.name })));// …or one that is, off the PATH the agent gets- else if (a.on && rtk.offPath) row.append(tag(t("Not on PATH"), "warn", t("{agent}'s hook runs rtk by name and can't find it, so RTK does nothing for it. Put RTK on PATH above.", { agent: a.name })));+ else if (a.on && offPath) row.append(tag(t("Not on PATH"), "warn", a.wsl+ ? t("{agent}'s hook runs rtk by name and can't find it in WSL {distro}, so RTK does nothing for it. Add RTK's folder to PATH there.", { agent: a.name, distro: a.wsl })+ : t("{agent}'s hook runs rtk by name and can't find it, so RTK does nothing for it. Put RTK on PATH above.", { agent: a.name })));// an agent RTK has no hook for (rtkNoHook in rtk.go): listed, with its own whyif (a.noHook) row.append(tag(t("No RTK hook"), "warn", rtkNoHookWhy(a)));// RTK before 0.51 installs Antigravity's hook only per project- else if (a.blocked && a.id === "agy") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.51 or newer: older ones install it only per project. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name })));- else if (a.blocked && a.id !== "opencode") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.50 or newer: older ones only add @RTK.md to AGENTS.md, which rewrites no command. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name })));+ else if (a.blocked && kind === "agy") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.51 or newer: older ones install it only per project. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name })));+ else if (a.blocked && kind !== "opencode") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.50 or newer: older ones only add @RTK.md to AGENTS.md, which rewrites no command. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name })));// OpenCode 2 loads only the plugin RTK 0.52 on writes (rtk-ai/rtk#4187);// an older one's, already there, can be switched offelse if (a.blocked) row.append(tag(t("Update RTK"), "warn", a.on? t("OpenCode 2 refuses to load this plugin: RTK before 0.52 writes it for OpenCode 1. Update RTK (brew upgrade rtk, or its installer again) and switch it on again, or switch this off."): t("OpenCode 2 needs RTK 0.52 or newer: older ones write a plugin for OpenCode 1, which OpenCode 2 refuses to load. Update RTK (brew upgrade rtk, or its installer again), then switch it on.")));const sw = toggle(a.on, t("{agent} runs its commands through RTK", { agent: a.name }), (on) => setRTK(a, on));- if ((!rtk.path && !a.on) || (a.blocked && !a.on) || rtkBusy.has(a.id) || rtkInstalling || rtkUpgrading) sw.disabled = true;+ if ((!path && !a.on) || a.asleep || (a.blocked && !a.on) || rtkBusy.has(a.id) || rtkInstalling || rtkInstallingIn || rtkUpgrading) sw.disabled = true;row.append(sw);list.append(row);}@@ -1021,7 +1032,7 @@ magpie.plugin("library", (ctx) => {// two together. An agent with no entry gets no reason and no link.function rtkNoHookWhy(a) {const agent = a.name;- switch (a.id) {+ switch (a.id.split("@")[0]) {case "dsh": return t("RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).", { agent });case "grok": return t("RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).", { agent });case "grok-app": return t("RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).", { agent });@@ -1144,6 +1155,61 @@ magpie.plugin("library", (ctx) => {rtkPathing = false;render();}+ // RTK in a WSL distro: its agents' hooks run there, so they run its own+ // rtk, installed by RTK's own Linux script run in the distro. A distro+ // that isn't running is never started for it.+ let rtkInstallingIn = "";+ const rtkInstallErrIn = {};+ function rtkDistroCard(d) {+ const card = el("div", "list lib-card lib-rtk-wsl");+ const ttl = el("div", "lib-cardhead");+ ttl.append(el("b", "", t("RTK in WSL {distro}", { distro: d.name })), el("span", "grow"));+ if (d.path) ttl.append(el("span", "note mono", d.version ? "v" + d.version : d.path));+ card.append(ttl);+ const acts = el("div", "lib-acts");+ const again = (cls) => button(t("Check again"), cls, () => { rtk = null; render(); });+ if (d.asleep) {+ card.append(el("p", "lib-rtk-gain", t("WSL {distro} isn't running: magpie doesn't start it to look for RTK or change its agents. Start the distro, then Check again.", { distro: d.name })));+ acts.append(again("action"));+ } else if (!d.path) {+ const installing = rtkInstallingIn === d.name;+ card.append(el("p", "lib-rtk-gain", installing+ ? t("Installing RTK in WSL {distro}… this can take a minute.", { distro: d.name })+ : d.install+ ? t("RTK isn't installed in WSL {distro}. Agents there run their hooks in the distro, so they need RTK there: magpie can run RTK's own installer in it.", { distro: d.name })+ : t("magpie couldn't look for RTK in WSL {distro}.", { distro: d.name })));+ if (d.install) card.append(el("p", "lib-rtk-cmd", d.install));+ if (rtkInstallErrIn[d.name] && !installing) card.append(el("p", "lib-rtk-note lib-rtk-err lib-rtk-install-err", t("The install failed: {why}", { why: rtkInstallErrIn[d.name] })));+ if (d.install) {+ const ib = button(installing ? t("Installing…") : t("Install RTK in WSL {distro}", { distro: d.name }), "action", () => installRTKIn(d.name));+ ib.disabled = !!rtkInstallingIn || rtkInstalling;+ acts.append(ib);+ }+ acts.append(again(d.install ? "" : "action"));+ } else if (d.offPath) {+ const dir = d.path.replace(/\/[^/]*$/, "");+ card.append(el("p", "lib-rtk-note lib-rtk-offpath", t("RTK is in {dir} in WSL {distro}, which isn't on its shells' PATH. Agents there run rtk by name, so they can't find it. Add {dir} to PATH in your shell profile there, then Check again.", { dir, distro: d.name })));+ acts.append(again("action"));+ } else {+ card.append(el("p", "lib-rtk-gain", t("Agents in WSL {distro} run its own RTK, at {path}. What it saves there is in its own count (rtk gain in the distro), not the one above.", { distro: d.name, path: d.path })));+ }+ if (acts.childNodes.length) card.append(acts);+ return card;+ }+ async function installRTKIn(distro) {+ rtkInstallingIn = distro;+ delete rtkInstallErrIn[distro];+ render();+ try {+ rtk = await api("library/rtk/install", { distro });+ status(t("RTK is installed in WSL {distro} — switch it on for its agents below", { distro }), "ok", 6000);+ } catch (e) {+ rtkInstallErrIn[distro] = e.message;+ status(e.message, "err", 10000);+ }+ rtkInstallingIn = "";+ render();+ }let rtkInstalling = false, rtkInstallErr = "";async function installRTK() {rtkInstalling = true;diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.jsindex d6f22f6d9..2090c7e55 100644--- a/internal/gui/assets/plugins/library/i18n.js+++ b/internal/gui/assets/plugins/library/i18n.js@@ -230,6 +230,19 @@ magpie.strings({"Nothing run through RTK in this time": "这段时间没有命令经过 RTK","RTK is installed — switch it on for your agents below": "RTK 已安装 — 在下方为你的 agent 打开","RTK missing": "RTK 缺失",+ "Not running": "未运行",+ "WSL {distro} isn't running: magpie doesn't start it to read or change {agent}. Start the distro, then Check again.": "WSL {distro} 未运行:magpie 不会为读取或更改 {agent} 而启动它。请先启动该发行版,再点“重新检测”。",+ "{agent}'s hook calls rtk, which isn't installed in WSL {distro}, so its shell commands fail. Install RTK there, or switch this off.": "{agent} 的钩子会调用 rtk,但 WSL {distro} 里没有安装 rtk,所以它的 shell 命令会失败。请在那里安装 RTK,或关闭此项。",+ "{agent}'s hook runs rtk by name and can't find it in WSL {distro}, so RTK does nothing for it. Add RTK's folder to PATH there.": "{agent} 的钩子按名称运行 rtk,但在 WSL {distro} 里找不到它,所以 RTK 对它不起作用。请把 RTK 所在的文件夹加入那里的 PATH。",+ "RTK in WSL {distro}": "WSL {distro} 中的 RTK",+ "WSL {distro} isn't running: magpie doesn't start it to look for RTK or change its agents. Start the distro, then Check again.": "WSL {distro} 未运行:magpie 不会为查找 RTK 或更改其中的 Agent 而启动它。请先启动该发行版,再点“重新检测”。",+ "Installing RTK in WSL {distro}… this can take a minute.": "正在 WSL {distro} 中安装 RTK…可能需要一分钟。",+ "RTK isn't installed in WSL {distro}. Agents there run their hooks in the distro, so they need RTK there: magpie can run RTK's own installer in it.": "WSL {distro} 中没有安装 RTK。那里的 Agent 在发行版内运行钩子,所以需要那里的 RTK:magpie 可以在其中运行 RTK 自己的安装脚本。",+ "magpie couldn't look for RTK in WSL {distro}.": "magpie 无法在 WSL {distro} 中查找 RTK。",+ "Install RTK in WSL {distro}": "在 WSL {distro} 中安装 RTK",+ "RTK is in {dir} in WSL {distro}, which isn't on its shells' PATH. Agents there run rtk by name, so they can't find it. Add {dir} to PATH in your shell profile there, then Check again.": "RTK 位于 WSL {distro} 的 {dir},但它不在那里的 shell 的 PATH 中。那里的 Agent 按名称运行 rtk,所以找不到它。请在那里的 shell 配置文件中把 {dir} 加入 PATH,再点“重新检测”。",+ "Agents in WSL {distro} run its own RTK, at {path}. What it saves there is in its own count (rtk gain in the distro), not the one above.": "WSL {distro} 中的 Agent 使用它自己的 RTK({path})。它在那里节省的量记在它自己的统计里(在发行版中运行 rtk gain),不在上面的统计中。",+ "RTK is installed in WSL {distro} — switch it on for its agents below": "RTK 已安装到 WSL {distro} — 在下方为其中的 Agent 打开它","{agent}'s hook calls rtk, which isn't installed, so its shell commands fail. Install RTK, or switch this off.": "{agent} 的 hook 会调用未安装的 rtk,导致其 shell 命令失败。请安装 RTK,或关闭此开关。","Not on PATH": "不在 PATH 中","{agent}'s hook runs rtk by name and can't find it, so RTK does nothing for it. Put RTK on PATH above.": "{agent} 的 hook 按名称调用 rtk 但找不到,RTK 对它不起作用。请在上方将 RTK 加入 PATH。",@@ -939,6 +952,19 @@ magpie.strings({"Nothing run through RTK in this time": "這段時間沒有命令經過 RTK","RTK is installed — switch it on for your agents below": "RTK 已安裝 — 在下方為你的 agent 開啟","RTK missing": "RTK 缺失",+ "Not running": "未執行",+ "WSL {distro} isn't running: magpie doesn't start it to read or change {agent}. Start the distro, then Check again.": "WSL {distro} 未執行:magpie 不會為了讀取或變更 {agent} 而啟動它。請先啟動該發行版,再點「重新檢測」。",+ "{agent}'s hook calls rtk, which isn't installed in WSL {distro}, so its shell commands fail. Install RTK there, or switch this off.": "{agent} 的鉤子會呼叫 rtk,但 WSL {distro} 裡沒有安裝 rtk,所以它的 shell 命令會失敗。請在那裡安裝 RTK,或關閉此項。",+ "{agent}'s hook runs rtk by name and can't find it in WSL {distro}, so RTK does nothing for it. Add RTK's folder to PATH there.": "{agent} 的鉤子依名稱執行 rtk,但在 WSL {distro} 裡找不到它,所以 RTK 對它不起作用。請把 RTK 所在的資料夾加入那裡的 PATH。",+ "RTK in WSL {distro}": "WSL {distro} 中的 RTK",+ "WSL {distro} isn't running: magpie doesn't start it to look for RTK or change its agents. Start the distro, then Check again.": "WSL {distro} 未執行:magpie 不會為了尋找 RTK 或變更其中的 Agent 而啟動它。請先啟動該發行版,再點「重新檢測」。",+ "Installing RTK in WSL {distro}… this can take a minute.": "正在 WSL {distro} 中安裝 RTK…可能需要一分鐘。",+ "RTK isn't installed in WSL {distro}. Agents there run their hooks in the distro, so they need RTK there: magpie can run RTK's own installer in it.": "WSL {distro} 中沒有安裝 RTK。那裡的 Agent 在發行版內執行鉤子,所以需要那裡的 RTK:magpie 可以在其中執行 RTK 自己的安裝腳本。",+ "magpie couldn't look for RTK in WSL {distro}.": "magpie 無法在 WSL {distro} 中尋找 RTK。",+ "Install RTK in WSL {distro}": "在 WSL {distro} 中安裝 RTK",+ "RTK is in {dir} in WSL {distro}, which isn't on its shells' PATH. Agents there run rtk by name, so they can't find it. Add {dir} to PATH in your shell profile there, then Check again.": "RTK 位於 WSL {distro} 的 {dir},但它不在那裡的 shell 的 PATH 中。那裡的 Agent 依名稱執行 rtk,所以找不到它。請在那裡的 shell 設定檔中把 {dir} 加入 PATH,再點「重新檢測」。",+ "Agents in WSL {distro} run its own RTK, at {path}. What it saves there is in its own count (rtk gain in the distro), not the one above.": "WSL {distro} 中的 Agent 使用它自己的 RTK({path})。它在那裡節省的量記在它自己的統計裡(在發行版中執行 rtk gain),不在上面的統計中。",+ "RTK is installed in WSL {distro} — switch it on for its agents below": "RTK 已安裝到 WSL {distro} — 在下方為其中的 Agent 開啟它","{agent}'s hook calls rtk, which isn't installed, so its shell commands fail. Install RTK, or switch this off.": "{agent} 的 hook 會呼叫未安裝的 rtk,導致其 shell 命令失敗。請安裝 RTK,或關閉此開關。","Not on PATH": "不在 PATH 中","{agent}'s hook runs rtk by name and can't find it, so RTK does nothing for it. Put RTK on PATH above.": "{agent} 的 hook 按名稱呼叫 rtk 但找不到,RTK 對它不起作用。請在上方將 RTK 加入 PATH。",@@ -1643,6 +1669,19 @@ magpie.strings({"Nothing run through RTK in this time": "この期間に RTK を通ったコマンドはありません","RTK is installed — switch it on for your agents below": "RTK はインストール済みです — 下でエージェントごとにオンにしてください","RTK missing": "RTK がありません",+ "Not running": "停止中",+ "WSL {distro} isn't running: magpie doesn't start it to read or change {agent}. Start the distro, then Check again.": "WSL {distro} は起動していません。magpie は {agent} を読んだり変更したりするために起動しません。ディストリビューションを起動してから「再確認」を押してください。",+ "{agent}'s hook calls rtk, which isn't installed in WSL {distro}, so its shell commands fail. Install RTK there, or switch this off.": "{agent} のフックは rtk を呼び出しますが、WSL {distro} に rtk がインストールされていないため、シェルコマンドが失敗します。そこに RTK をインストールするか、これをオフにしてください。",+ "{agent}'s hook runs rtk by name and can't find it in WSL {distro}, so RTK does nothing for it. Add RTK's folder to PATH there.": "{agent} のフックは rtk を名前で実行しますが、WSL {distro} で見つからないため、RTK は効きません。RTK のフォルダをそこの PATH に追加してください。",+ "RTK in WSL {distro}": "WSL {distro} の RTK",+ "WSL {distro} isn't running: magpie doesn't start it to look for RTK or change its agents. Start the distro, then Check again.": "WSL {distro} は起動していません。magpie は RTK を探したりエージェントを変更したりするために起動しません。ディストリビューションを起動してから「再確認」を押してください。",+ "Installing RTK in WSL {distro}… this can take a minute.": "WSL {distro} に RTK をインストール中… 1 分ほどかかることがあります。",+ "RTK isn't installed in WSL {distro}. Agents there run their hooks in the distro, so they need RTK there: magpie can run RTK's own installer in it.": "WSL {distro} に RTK がインストールされていません。そこのエージェントはディストリビューション内でフックを実行するため、そこに RTK が必要です。magpie はその中で RTK 公式のインストーラを実行できます。",+ "magpie couldn't look for RTK in WSL {distro}.": "magpie は WSL {distro} で RTK を探せませんでした。",+ "Install RTK in WSL {distro}": "WSL {distro} に RTK をインストール",+ "RTK is in {dir} in WSL {distro}, which isn't on its shells' PATH. Agents there run rtk by name, so they can't find it. Add {dir} to PATH in your shell profile there, then Check again.": "RTK は WSL {distro} の {dir} にありますが、そこのシェルの PATH にありません。そこのエージェントは rtk を名前で実行するため見つけられません。そこのシェルのプロファイルで {dir} を PATH に追加してから「再確認」を押してください。",+ "Agents in WSL {distro} run its own RTK, at {path}. What it saves there is in its own count (rtk gain in the distro), not the one above.": "WSL {distro} のエージェントはその中の RTK({path})を使います。そこで節約した分はその RTK 自身の集計(ディストリビューション内の rtk gain)にあり、上の集計には含まれません。",+ "RTK is installed in WSL {distro} — switch it on for its agents below": "WSL {distro} に RTK をインストールしました — 下でそのエージェントをオンにしてください","{agent}'s hook calls rtk, which isn't installed, so its shell commands fail. Install RTK, or switch this off.": "{agent} のフックは rtk を呼び出しますが、インストールされていないため、シェルコマンドが失敗します。RTK をインストールするか、これをオフにしてください。","Not on PATH": "PATH にありません","{agent}'s hook runs rtk by name and can't find it, so RTK does nothing for it. Put RTK on PATH above.": "{agent} のフックは rtk を名前で実行しますが見つからないため、RTK は何もしません。上で RTK を PATH に追加してください。",@@ -2350,6 +2389,19 @@ magpie.strings({"Nothing run through RTK in this time": "In diesem Zeitraum lief nichts über RTK","RTK is installed — switch it on for your agents below": "RTK ist installiert – schalten Sie es unten für Ihre Agenten ein","RTK missing": "RTK fehlt",+ "Not running": "Läuft nicht",+ "WSL {distro} isn't running: magpie doesn't start it to read or change {agent}. Start the distro, then Check again.": "WSL {distro} läuft nicht: magpie startet sie nicht, um {agent} zu lesen oder zu ändern. Starte die Distribution und klicke dann auf Erneut prüfen.",+ "{agent}'s hook calls rtk, which isn't installed in WSL {distro}, so its shell commands fail. Install RTK there, or switch this off.": "Der Hook von {agent} ruft rtk auf, das in WSL {distro} nicht installiert ist, daher schlagen seine Shell-Befehle fehl. Installiere RTK dort oder schalte dies aus.",+ "{agent}'s hook runs rtk by name and can't find it in WSL {distro}, so RTK does nothing for it. Add RTK's folder to PATH there.": "Der Hook von {agent} startet rtk über den Namen und findet es in WSL {distro} nicht, daher wirkt RTK dort nicht. Füge den Ordner von RTK dort zum PATH hinzu.",+ "RTK in WSL {distro}": "RTK in WSL {distro}",+ "WSL {distro} isn't running: magpie doesn't start it to look for RTK or change its agents. Start the distro, then Check again.": "WSL {distro} läuft nicht: magpie startet sie nicht, um RTK zu suchen oder ihre Agents zu ändern. Starte die Distribution und klicke dann auf Erneut prüfen.",+ "Installing RTK in WSL {distro}… this can take a minute.": "RTK wird in WSL {distro} installiert… das kann eine Minute dauern.",+ "RTK isn't installed in WSL {distro}. Agents there run their hooks in the distro, so they need RTK there: magpie can run RTK's own installer in it.": "RTK ist in WSL {distro} nicht installiert. Die Agents dort führen ihre Hooks in der Distribution aus und brauchen RTK daher dort: magpie kann das eigene Installationsskript von RTK darin ausführen.",+ "magpie couldn't look for RTK in WSL {distro}.": "magpie konnte in WSL {distro} nicht nach RTK suchen.",+ "Install RTK in WSL {distro}": "RTK in WSL {distro} installieren",+ "RTK is in {dir} in WSL {distro}, which isn't on its shells' PATH. Agents there run rtk by name, so they can't find it. Add {dir} to PATH in your shell profile there, then Check again.": "RTK liegt in WSL {distro} unter {dir}, das nicht im PATH ihrer Shells ist. Die Agents dort starten rtk über den Namen und finden es daher nicht. Füge {dir} dort in deinem Shell-Profil zum PATH hinzu und klicke dann auf Erneut prüfen.",+ "Agents in WSL {distro} run its own RTK, at {path}. What it saves there is in its own count (rtk gain in the distro), not the one above.": "Agents in WSL {distro} nutzen deren eigenes RTK unter {path}. Was es dort spart, steht in dessen eigener Zählung (rtk gain in der Distribution), nicht in der oben.",+ "RTK is installed in WSL {distro} — switch it on for its agents below": "RTK ist in WSL {distro} installiert — schalte es unten für ihre Agents ein","{agent}'s hook calls rtk, which isn't installed, so its shell commands fail. Install RTK, or switch this off.": "Der Hook von {agent} ruft rtk auf, das nicht installiert ist, daher schlagen seine Shell-Befehle fehl. Installieren Sie RTK oder schalten Sie dies aus.","Not on PATH": "Nicht im PATH","{agent}'s hook runs rtk by name and can't find it, so RTK does nothing for it. Put RTK on PATH above.": "Der Hook von {agent} ruft rtk über den Namen auf und findet es nicht, daher bewirkt RTK dort nichts. Nehmen Sie RTK oben in den PATH auf.",diff --git a/internal/gui/library.go b/internal/gui/library.goindex 9bae365d1..7ae4d6eb2 100644--- a/internal/gui/library.go+++ b/internal/gui/library.go@@ -3,6 +3,7 @@ package guiimport ("encoding/json""errors"+ "io""net/http""os""path/filepath"@@ -290,8 +291,21 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {}writeJSON(rw, v)})+ // distro: in that WSL distro, by rtk's own Linux installer run theremux.HandleFunc("POST /api/library/rtk/install", func(rw http.ResponseWriter, r *http.Request) {- v, err := library.InstallRTK()+ var in struct{ Distro string }+ // {} or no body: this computer; a body that can't be read, nowhere+ if err := json.NewDecoder(r.Body).Decode(&in); err != nil && !errors.Is(err, io.EOF) {+ http.Error(rw, "bad body", http.StatusBadRequest)+ return+ }+ var v *library.RTKView+ var err error+ if in.Distro != "" {+ v, err = library.InstallRTKIn(in.Distro)+ } else {+ v, err = library.InstallRTK()+ }if err != nil {fail(rw, err)returndiff --git a/internal/gui/tests/library-rtk-wsl.test.cjs b/internal/gui/tests/library-rtk-wsl.test.cjsnew file mode 100644index 000000000..4bedfe164--- /dev/null+++ b/internal/gui/tests/library-rtk-wsl.test.cjs@@ -0,0 +1,123 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// lex on Discord: Claude Code in WSL couldn't have the RTK of magpie on+// Windows. An agent in a WSL distro is listed, with its distro's own RTK in+// a card of its own: one not installed there has Install RTK in WSL+// <distro> (RTK's own Linux installer, run in the distro), and the agent's+// switch waits for it; a distro that isn't running says so, and its agents'+// switches are off limits, since magpie never starts it. In every language,+// both engines, at a phone's width too. 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 = "C:\\Users\\lex";+const lib = () => ({+ dir: `${HOME}\\.magpie\\library`, backups: `${HOME}\\.magpie\\backups`, home: HOME,+ agents: [{ id: "claude", name: "Claude Code", icon: "", skills: `${HOME}\\.claude\\skills`, mcp: `${HOME}\\.claude.json` }],+ instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [],+});+const INSTALL = "curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh";+const rtkView = (installed) => ({+ path: `${HOME}\\.local\\bin\\rtk.exe`, version: "0.52.0", url: "https://www.rtk-ai.app",+ agents: [+ { id: "claude", name: "Claude Code", icon: "", on: false },+ { id: "claude@wsl:Ubuntu", name: "Claude Code · WSL Ubuntu", icon: "", on: false, wsl: "Ubuntu" },+ { id: "codex@wsl:Arch", name: "Codex · WSL Arch", icon: "", on: false, wsl: "Arch", asleep: true },+ ],+ wsl: [+ installed ? { name: "Ubuntu", path: "/home/lex/.local/bin/rtk", version: "0.52.0" } : { name: "Ubuntu", install: INSTALL },+ { name: "Arch", asleep: true },+ ],+});++function server(lang, calls) {+ let installed = false;+ 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/plugins") return route.fulfill({ json: { plugins: [] } });+ if (url.pathname === "/api/library") return route.fulfill({ json: lib() });+ if (url.pathname === "/api/library/rtk") return route.fulfill({ json: rtkView(installed) });+ if (url.pathname === "/api/library/rtk/install") {+ calls.push(req.postDataJSON());+ installed = true;+ return route.fulfill({ json: rtkView(true) });+ }+ 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 });+ };+}++const words = {+ en: { title: "RTK in WSL Ubuntu", button: "Install RTK in WSL Ubuntu", asleep: "Not running", stopped: "WSL Arch isn't running", done: "RTK is installed in WSL Ubuntu — switch it on for its agents below" },+ zh: { title: "WSL Ubuntu 中的 RTK", button: "在 WSL Ubuntu 中安装 RTK", asleep: "未运行", stopped: "WSL Arch 未运行", done: "RTK 已安装到 WSL Ubuntu — 在下方为其中的 Agent 打开它" },+ "zh-TW": { title: "WSL Ubuntu 中的 RTK", button: "在 WSL Ubuntu 中安裝 RTK", asleep: "未執行", stopped: "WSL Arch 未執行", done: "RTK 已安裝到 WSL Ubuntu — 在下方為其中的 Agent 開啟它" },+ ja: { title: "WSL Ubuntu の RTK", button: "WSL Ubuntu に RTK をインストール", asleep: "停止中", stopped: "WSL Arch は起動していません", done: "WSL Ubuntu に RTK をインストールしました — 下でそのエージェントをオンにしてください" },+ de: { title: "RTK in WSL Ubuntu", button: "RTK in WSL Ubuntu installieren", asleep: "Läuft nicht", stopped: "WSL Arch läuft nicht", done: "RTK ist in WSL Ubuntu installiert — schalte es unten für ihre Agents ein" },+};++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(engine + ": an agent in WSL gets its distro's own RTK", 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 lang of Object.keys(words)) for (const width of [980, 380]) {+ await t.test(`${lang} at ${width}px`, async () => {+ const w = words[lang], calls = [];+ const ctx = await browser.newContext({ viewport: { width, height: 900 } });+ await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "rtk"); } catch {} });+ const page = await ctx.newPage();+ page.setDefaultTimeout(5000);+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", server(lang, calls));+ await page.goto("http://magpie.test/");+ await page.locator('button[data-view="library"]').click();+ const v = page.locator("#view-library");+ const cards = v.locator(".lib-rtk-wsl");+ await cards.first().waitFor();+ assert.equal(await cards.count(), 2);+ const ubuntu = cards.nth(0), arch = cards.nth(1);+ assert.equal(await ubuntu.locator(".lib-cardhead b").textContent(), w.title);+ assert.equal(await ubuntu.locator(".lib-rtk-cmd").textContent(), INSTALL);+ assert((await arch.locator(".lib-rtk-gain").textContent()).startsWith(w.stopped), await arch.locator(".lib-rtk-gain").textContent());+ // a stopped distro offers no install: that would start it+ assert.equal(await arch.getByRole("button", { name: w.button.replace("Ubuntu", "Arch"), exact: true }).count(), 0);++ const row = (name) => v.locator(".lib-row").filter({ has: page.locator(".name", { hasText: name }) });+ const sw = (name) => row(name).getByRole("switch");+ // Windows' rtk is there for Windows' Claude Code, not the distro's+ assert.equal(await sw("Claude Code").first().isDisabled(), false);+ assert.equal(await sw("Claude Code · WSL Ubuntu").isDisabled(), true);+ assert.equal(await sw("Codex · WSL Arch").isDisabled(), true);+ assert.deepEqual(await row("Codex · WSL Arch").locator(".lib-tag").allTextContents(), [w.asleep]);++ await ubuntu.getByRole("button", { name: w.button, exact: true }).click();+ await page.waitForFunction((want) => document.querySelector("#status").textContent === want, w.done).catch(() => {});+ assert.equal(await page.locator("#status").textContent(), w.done);+ assert.deepEqual(calls, [{ distro: "Ubuntu" }]);+ assert.equal(await sw("Claude Code · WSL Ubuntu").isDisabled(), false);+ assert.equal(await sw("Codex · WSL Arch").isDisabled(), true);+ assert.equal(await ubuntu.locator(".note.mono").textContent(), "v0.52.0");+ // nothing runs off the side at a phone's width+ const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);+ assert(over <= 0, `the page scrolls sideways by ${over}px`);+ await ctx.close();+ });+ }+ assert.deepEqual(errors, []);+ });+}diff --git a/internal/library/rtk.go b/internal/library/rtk.goindex 1e0fcb0f0..aa2ef8db2 100644--- a/internal/library/rtk.go+++ b/internal/library/rtk.go@@ -61,8 +61,8 @@ type rtkSpec struct {// environment, so it writes where the agent readsenv func(a *agent.Agent) []string// blocked says why rtk's installer mustn't be run for the agent as it- // is on this machine, "" when it can be- blocked func() string+ // is where it lives (this machine, or its WSL distro), "" when it can be+ blocked func(a *agent.Agent) string}func contains(path, s string) bool {@@ -85,59 +85,61 @@ func rtkRef(line string) bool {var rtkSpecs = map[string]rtkSpec{"claude": {patch: true,- has: func(*agent.Agent) bool {- return contains(filepath.Join(claudeDir(), "settings.json"), "rtk hook claude")+ has: func(a *agent.Agent) bool {+ return contains(filepath.Join(rtkClaudeDir(a), "settings.json"), "rtk hook claude")},- files: func(*agent.Agent) []string {- d := claudeDir()+ files: func(a *agent.Agent) []string {+ d := rtkClaudeDir(a)return []string{filepath.Join(d, "settings.json"), filepath.Join(d, "CLAUDE.md"), filepath.Join(d, "RTK.md")}},- remove: func(*agent.Agent) error {- d := claudeDir()+ remove: func(a *agent.Agent) error {+ d := rtkClaudeDir(a)return errors.Join(dropHook(filepath.Join(d, "settings.json"), "hooks.PreToolUse", "rtk hook claude"),dropLines(filepath.Join(d, "CLAUDE.md"), rtkRef),rm(filepath.Join(d, "RTK.md")))},- dir: func(*agent.Agent) string { return claudeDir() },+ dir: func(a *agent.Agent) string { return rtkClaudeDir(a) },},"codex": {flags: []string{"--codex"},blocked: codexBlocked,- has: func(*agent.Agent) bool { return contains(filepath.Join(codexDir(), "hooks.json"), "rtk hook codex") },- files: func(*agent.Agent) []string {- d := codexDir()+ has: func(a *agent.Agent) bool {+ return contains(filepath.Join(rtkCodexDir(a), "hooks.json"), "rtk hook codex")+ },+ files: func(a *agent.Agent) []string {+ d := rtkCodexDir(a)return []string{filepath.Join(d, "hooks.json"), filepath.Join(d, "AGENTS.md"), filepath.Join(d, "RTK.md")}},- remove: func(*agent.Agent) error {- d := codexDir()+ remove: func(a *agent.Agent) error {+ d := rtkCodexDir(a)return errors.Join(dropHook(filepath.Join(d, "hooks.json"), "hooks.PreToolUse", "rtk hook codex"),dropLines(filepath.Join(d, "AGENTS.md"), rtkRef),rm(filepath.Join(d, "RTK.md")))},- dir: func(*agent.Agent) string { return codexDir() },+ dir: func(a *agent.Agent) string { return rtkCodexDir(a) },},"gemini": {// --hook-only: without it the installer writes its own GEMINI.md// over the user'sflags: []string{"--gemini", "--hook-only"}, patch: true,- has: func(*agent.Agent) bool {- return contains(filepath.Join(home(), ".gemini", "settings.json"), "rtk-hook-gemini")+ has: func(a *agent.Agent) bool {+ return contains(filepath.Join(rtkHome(a), ".gemini", "settings.json"), "rtk-hook-gemini")},- files: func(*agent.Agent) []string {- d := filepath.Join(home(), ".gemini")+ files: func(a *agent.Agent) []string {+ d := filepath.Join(rtkHome(a), ".gemini")return []string{filepath.Join(d, "settings.json"), filepath.Join(d, "hooks", "rtk-hook-gemini.sh"), filepath.Join(d, "hooks", ".rtk-hook.sha256")}},- remove: func(*agent.Agent) error {- d := filepath.Join(home(), ".gemini")+ remove: func(a *agent.Agent) error {+ d := filepath.Join(rtkHome(a), ".gemini")err := errors.Join(dropHook(filepath.Join(d, "settings.json"), "hooks.BeforeTool", "rtk-hook-gemini"),rm(filepath.Join(d, "hooks", "rtk-hook-gemini.sh"), filepath.Join(d, "hooks", ".rtk-hook.sha256")))os.Remove(filepath.Join(d, "hooks")) // when nothing else is in itreturn err},- dir: func(*agent.Agent) string { return filepath.Join(home(), ".gemini") },+ dir: func(a *agent.Agent) string { return filepath.Join(rtkHome(a), ".gemini") },},"opencode": {flags: []string{"--opencode"}, patch: true, withClaude: true, blocked: openCodeBlocked,@@ -148,29 +150,31 @@ var rtkSpecs = map[string]rtkSpec{},"cursor": {flags: []string{"--agent", "cursor"}, patch: true, withClaude: true,- has: func(*agent.Agent) bool {- return contains(filepath.Join(home(), ".cursor", "hooks.json"), "rtk hook cursor")+ has: func(a *agent.Agent) bool {+ return contains(filepath.Join(rtkHome(a), ".cursor", "hooks.json"), "rtk hook cursor")},- files: func(*agent.Agent) []string { return []string{filepath.Join(home(), ".cursor", "hooks.json")} },- remove: func(*agent.Agent) error {- return dropHook(filepath.Join(home(), ".cursor", "hooks.json"), "hooks.preToolUse", "rtk hook cursor")+ files: func(a *agent.Agent) []string { return []string{filepath.Join(rtkHome(a), ".cursor", "hooks.json")} },+ remove: func(a *agent.Agent) error {+ return dropHook(filepath.Join(rtkHome(a), ".cursor", "hooks.json"), "hooks.preToolUse", "rtk hook cursor")},- dir: func(*agent.Agent) string { return filepath.Join(home(), ".cursor") },+ dir: func(a *agent.Agent) string { return filepath.Join(rtkHome(a), ".cursor") },},"copilot": {flags: []string{"--copilot"}, patch: true,- has: func(*agent.Agent) bool { return exists(filepath.Join(home(), ".copilot", "hooks", "rtk-rewrite.json")) },- files: func(*agent.Agent) []string {- d := filepath.Join(home(), ".copilot")+ has: func(a *agent.Agent) bool {+ return exists(filepath.Join(rtkHome(a), ".copilot", "hooks", "rtk-rewrite.json"))+ },+ files: func(a *agent.Agent) []string {+ d := filepath.Join(rtkHome(a), ".copilot")return []string{filepath.Join(d, "hooks", "rtk-rewrite.json"), filepath.Join(d, "copilot-instructions.md")}},- remove: func(*agent.Agent) error {- d := filepath.Join(home(), ".copilot")+ remove: func(a *agent.Agent) error {+ d := filepath.Join(rtkHome(a), ".copilot")return errors.Join(rm(filepath.Join(d, "hooks", "rtk-rewrite.json")),dropBlock(filepath.Join(d, "copilot-instructions.md"), "<!-- rtk-instructions", "<!-- /rtk-instructions -->"))},- dir: func(*agent.Agent) string { return filepath.Join(home(), ".copilot") },+ dir: func(a *agent.Agent) string { return filepath.Join(rtkHome(a), ".copilot") },},// Antigravity CLI (agy): rtk 0.51 on writes a plugin of its own into// Antigravity's global customization folder, ~/.gemini/config, shared@@ -182,15 +186,15 @@ var rtkSpecs = map[string]rtkSpec{// (rtk-ai/rtk#3404), so the folder is taken out by magpie."agy": {flags: []string{"--agent", "antigravity"}, blocked: agyBlocked,- has: func(*agent.Agent) bool {- return contains(filepath.Join(agyPlugin(), "hooks.json"), "rtk hook antigravity")+ has: func(a *agent.Agent) bool {+ return contains(filepath.Join(agyPlugin(a), "hooks.json"), "rtk hook antigravity")},- files: func(*agent.Agent) []string {- d := agyPlugin()+ files: func(a *agent.Agent) []string {+ d := agyPlugin(a)return []string{filepath.Join(d, "plugin.json"), filepath.Join(d, "hooks.json"), filepath.Join(d, "rules", "AGENTS.md")}},- remove: func(*agent.Agent) error { return os.RemoveAll(agyPlugin()) },- dir: func(*agent.Agent) string { return filepath.Dir(filepath.Dir(agyPlugin())) },+ remove: func(a *agent.Agent) error { return os.RemoveAll(agyPlugin(a)) },+ dir: func(a *agent.Agent) string { return filepath.Dir(filepath.Dir(agyPlugin(a))) },},"pi": extensionSpec("pi"),"omp": extensionSpec("omp"),@@ -251,12 +255,12 @@ func opencodePlugin(a *agent.Agent) string {// setup() beside OpenCode 1's server(). So with an OpenCode 2 here, rtk is// given to OpenCode only by an rtk of 0.52 or newer; an older one, or one// that doesn't say its version, would only add a plugin that fails to load.-func openCodeBlocked() string {- v := openCodeVersion()+func openCodeBlocked(a *agent.Agent) string {+ v := openCodeVersionOf(a)if !openCode2(v) {return ""}- r := rtkVersion()+ r := rtkVersionOf(a)if r != "" && !older(r, 0, 52) {return ""}@@ -283,17 +287,17 @@ func openCodeHas(a *agent.Agent) bool {if !exists(p) {return false}- if contains(p, "setup(") || !openCode2(openCodeVersion()) {+ if contains(p, "setup(") || !openCode2(openCodeVersionOf(a)) {return true}- return openCodeBlocked() != ""+ return openCodeBlocked(a) != ""}// codexBlocked: rtk has a hook for Codex from 0.50.0 on (rtk hook codex in// hooks.json); before that rtk init --codex only puts @RTK.md in AGENTS.md,// which rewrites no command, so an older rtk isn't run for Codex.-func codexBlocked() string {- v := rtkVersion()+func codexBlocked(a *agent.Agent) string {+ v := rtkVersionOf(a)if v == "" || !older(v, 0, 50) {return ""}@@ -301,13 +305,15 @@ func codexBlocked() string {}// agyPlugin is the folder rtk's installer writes its Antigravity plugin to.-func agyPlugin() string { return filepath.Join(home(), ".gemini", "config", "plugins", "rtk") }+func agyPlugin(a *agent.Agent) string {+ return filepath.Join(rtkHome(a), ".gemini", "config", "plugins", "rtk")+}// agyBlocked: rtk installs for Antigravity globally from 0.51.0 on; 0.50// knows it only per project and fails rtk init -g --agent antigravity// ("Antigravity is project-scoped"), so an older rtk isn't run for it.-func agyBlocked() string {- v := rtkVersion()+func agyBlocked(a *agent.Agent) string {+ v := rtkVersionOf(a)if v == "" || !older(v, 0, 51) {return ""}@@ -378,13 +384,13 @@ func hermesPlugin(a *agent.Agent) string { return filepath.Join(a.Dir, "plugins"// extensionSpec is pi's and omp's: an extension of rtk's own, and nothing else.func extensionSpec(id string) rtkSpec {- ext := func() string { return filepath.Join(home(), "."+id, "agent", "extensions", "rtk.ts") }+ ext := func(a *agent.Agent) string { return filepath.Join(rtkHome(a), "."+id, "agent", "extensions", "rtk.ts") }return rtkSpec{flags: []string{"--agent", id}, patch: true,- has: func(*agent.Agent) bool { return exists(ext()) },- files: func(*agent.Agent) []string { return []string{ext()} },- remove: func(*agent.Agent) error { return rm(ext()) },- dir: func(*agent.Agent) string { return filepath.Join(home(), "."+id, "agent") },+ has: func(a *agent.Agent) bool { return exists(ext(a)) },+ files: func(a *agent.Agent) []string { return []string{ext(a)} },+ remove: func(a *agent.Agent) error { return rm(ext(a)) },+ dir: func(a *agent.Agent) string { return filepath.Join(rtkHome(a), "."+id, "agent") },}}@@ -553,6 +559,12 @@ type RTKAgent struct {Blocked string `json:"blocked,omitempty"`// NoHook: rtk has no hook for it at all (rtkNoHook), and Blocked says whyNoHook bool `json:"noHook,omitempty"`+ // WSL is the distro an agent in WSL lives in: its hook runs the rtk+ // of that distro (RTKView.WSL), not this machine's+ WSL string `json:"wsl,omitempty"`+ // Asleep: its distro isn't running, so its files aren't read (that+ // would start it) and On isn't known+ Asleep bool `json:"asleep,omitempty"`}// RTKGain is what rtk says it saved, over every command it has recorded.@@ -618,7 +630,9 @@ type RTKView struct {PathLink bool `json:"pathLink,omitempty"`OffPath bool `json:"offPath,omitempty"`Agents []RTKAgent `json:"agents"`- URL string `json:"url"`+ // WSL is the rtk of each WSL distro an agent listed lives in+ WSL []RTKDistro `json:"wsl,omitempty"`+ URL string `json:"url"`// Install is the command Install RTK runs, shown before it is clickedInstall string `json:"install,omitempty"`// Restart are the agents a change reached, to be restarted to see it@@ -700,7 +714,7 @@ func rtkAgents(agents []*agent.Agent) []*agent.Agent {}var out []*agent.Agentfor _, a := range agents {- sp, ok := rtkSpecs[a.ID]+ sp, ok := rtkSpecs[rtkKind(a.ID)]// an uninstall that left the folder behind (#2254) isn't given rtk,// as the library gives it nothing (Targets); one with rtk's hook// still shows, so the hook can be taken out@@ -723,18 +737,26 @@ func ReadRTK() *RTKView {// the agents are detected once and the two passes below share themagents := detected()for _, a := range rtkAgents(agents) {- sp := rtkSpecs[a.ID]- ra := RTKAgent{ID: a.ID, Name: a.Name, Icon: a.Icon, On: sp.has(a)}+ sp := rtkSpecs[rtkKind(a.ID)]+ ra := RTKAgent{ID: a.ID, Name: a.Name, Icon: a.Icon, WSL: a.WSL}+ // a stopped distro's files aren't opened: that starts it (#3896)+ if a.WSL != "" && !rtkWSLLive(a) {+ ra.Asleep = true+ v.Agents = append(v.Agents, ra)+ continue+ }+ ra.On = sp.has(a)if sp.blocked != nil {- ra.Blocked = sp.blocked()+ ra.Blocked = sp.blocked(a)}v.Agents = append(v.Agents, ra)}for _, a := range agents {- if why, ok := rtkNoHook[a.ID]; ok && !a.CLIMissing() {- v.Agents = append(v.Agents, RTKAgent{ID: a.ID, Name: a.Name, Icon: a.Icon, Blocked: why, NoHook: true})+ if why, ok := rtkNoHook[rtkKind(a.ID)]; ok && !a.CLIMissing() {+ v.Agents = append(v.Agents, RTKAgent{ID: a.ID, Name: a.Name, Icon: a.Icon, Blocked: why, NoHook: true, WSL: a.WSL})}}+ v.WSL = rtkDistros(v.Agents)if v.Path == "" {return v}@@ -890,24 +912,37 @@ func SetRTK(id string, on bool) (*RTKView, error) {a = x}}- sp, ok := rtkSpecs[id]+ kind := rtkKind(id)+ sp, ok := rtkSpecs[kind]switch {- case !ok && rtkNoHook[id] != "":- return nil, errors.New(rtkNoHook[id])+ case !ok && rtkNoHook[kind] != "":+ return nil, errors.New(rtkNoHook[kind])case !ok:return nil, fmt.Errorf("rtk has no hook for %s", id)case a == nil:return nil, fmt.Errorf("%s isn't installed", id)+ case a.WSL != "" && !rtkWSLLive(a):+ // nothing in it is read or run: that would start it (#3896)+ return nil, fmt.Errorf("WSL %s isn't running, and magpie doesn't start it to change RTK for %s: start the distro (open its terminal), then switch it again", a.WSL, a.Name)case sp.has(a) == on:return ReadRTK(), nil}if on && sp.blocked != nil {- if why := sp.blocked(); why != "" {+ if why := sp.blocked(a); why != "" {return nil, errors.New(why)}}- bin := rtkPath()- if on && bin == "" {+ bin := ""+ if a.WSL != "" {+ // the hook runs in the distro, so it is the distro's rtk that is+ // run for it: a Windows rtk.exe is no path there+ if on {+ d := rtkDistroOf(a.WSL, true)+ if bin = d.Path; bin == "" {+ return nil, fmt.Errorf("RTK isn't installed in WSL %s — install it there first (magpie library rtk install %s)", a.WSL, a.WSL)+ }+ }+ } else if bin = rtkPath(); on && bin == "" {return nil, fmt.Errorf("rtk isn't installed — install it first (%s)", RTKURL)}b := newBackups()@@ -937,10 +972,13 @@ func SetRTK(id string, on bool) (*RTKView, error) {}func rtkInstall(bin string, a *agent.Agent) error {- sp := rtkSpecs[a.ID]+ sp := rtkSpecs[rtkKind(a.ID)]if err := os.MkdirAll(sp.dir(a), 0o755); err != nil {return err}+ if a.WSL != "" {+ return rtkInstallWSL(bin, a, sp)+ }args := append([]string{"init", "-g"}, sp.flags...)if sp.patch {args = append(args, "--auto-patch")@@ -1072,10 +1110,10 @@ func RTKTakes(q string) (string, error) {if err != nil {return "", err}- if why := rtkNoHook[a.ID]; why != "" {+ if why := rtkNoHook[rtkKind(a.ID)]; why != "" {return "", errors.New(why)}- if _, ok := rtkSpecs[a.ID]; !ok {+ if _, ok := rtkSpecs[rtkKind(a.ID)]; !ok {var ids []stringfor id := range rtkSpecs {ids = append(ids, id)diff --git a/internal/library/rtk_wsl.go b/internal/library/rtk_wsl.gonew file mode 100644index 000000000..21328aed2--- /dev/null+++ b/internal/library/rtk_wsl.go@@ -0,0 +1,280 @@+package library++import (+ "errors"+ "fmt"+ "os/exec"+ "path/filepath"+ "slices"+ "strings"+ "sync"+ "time"++ "github.com/yetone/magpie/internal/agent"+ "github.com/yetone/magpie/internal/wslrun"+)++// RTK for an agent in a WSL distro (lex on Discord: Claude Code in WSL+// couldn't have the RTK of a magpie on Windows). Its hook runs in the+// distro, where a Windows rtk.exe is no command, so it is the distro's own+// rtk that is installed (rtk's own Linux script, run there), found, and+// run for rtk init, with its files under the distro's home as magpie+// opens it (\\wsl.localhost\<distro>\home\<user>). A distro that isn't+// running is never started for it: its agents are listed asleep.++// RTKDistro is the rtk of one WSL distro an agent listed lives in.+type RTKDistro struct {+ Name string `json:"name"`+ // Path is rtk's inside the distro, "" when it isn't installed there+ Path string `json:"path,omitempty"`+ Version string `json:"version,omitempty"`+ // OffPath: found where its installer puts it, but not on the PATH of+ // the distro's shells, which its hooks run rtk by+ OffPath bool `json:"offPath,omitempty"`+ // Install is the command Install RTK runs in the distro+ Install string `json:"install,omitempty"`+ // Asleep: the distro isn't running, and isn't looked in+ Asleep bool `json:"asleep,omitempty"`+}++// rtkKind is the rtkSpecs (and rtkNoHook) key of agent id: the id itself,+// or one in WSL's (claude@wsl:Ubuntu) before its @wsl:.+func rtkKind(id string) string {+ k, _, _ := strings.Cut(id, "@wsl:")+ return k+}++// rtkHome is the home rtk's installer writes under for a: the distro's for+// one in WSL, as magpie opens it; this machine's otherwise.+func rtkHome(a *agent.Agent) string {+ if a != nil && a.WSL != "" {+ return a.Home+ }+ return home()+}++// rtkClaudeDir is Claude Code's folder for a: ~/.claude in a distro, whose+// CLAUDE_CONFIG_DIR magpie can't read (as wslTargetOf).+func rtkClaudeDir(a *agent.Agent) string {+ if a != nil && a.WSL != "" {+ return filepath.Join(a.Home, ".claude")+ }+ return claudeDir()+}++// rtkCodexDir is Codex's folder for a: ~/.codex in a distro.+func rtkCodexDir(a *agent.Agent) string {+ if a != nil && a.WSL != "" {+ return filepath.Join(a.Home, ".codex")+ }+ return codexDir()+}++// rtkVersionOf is the version of the rtk a's hook runs: its distro's for+// one in WSL.+func rtkVersionOf(a *agent.Agent) string {+ if a != nil && a.WSL != "" {+ return rtkDistroOf(a.WSL, false).Version+ }+ return rtkVersion()+}++// openCodeVersionOf is the version of a's OpenCode: for one in WSL what the+// distro's probe found, "" when it didn't ask.+func openCodeVersionOf(a *agent.Agent) string {+ if a != nil && a.WSL != "" {+ return a.InstalledVersion()+ }+ return openCodeVersion()+}++// rtkWSLLive is whether a's distro runs now and its files can be opened+// without starting it.+func rtkWSLLive(a *agent.Agent) bool {+ return a.Home != "" && agent.WSLRunning(a.WSL)+}++// rtkWSLRun runs wsl.exe with args; a var for tests.+var rtkWSLRun = wslrun.Run++// rtkWSLProbe prints where rtk is in the distro: on the PATH of a login+// shell, or an interactive one's (where .bashrc puts it), "on:1"; else+// where its installers put it, "on:0". A Windows rtk.exe seen through+// /mnt isn't the distro's.+const rtkWSLProbe = `p=$(command -v rtk 2>/dev/null); ` ++ `case "$p" in /*) ;; *) p=$(bash -ic 'command -v rtk' 2>/dev/null </dev/null | tail -n1);; esac; ` ++ `on=1; case "$p" in /mnt/*|"") p=""; on=0; ` ++ `for c in "$HOME/.local/bin/rtk" "$HOME/.cargo/bin/rtk"; do [ -x "$c" ] && { p=$c; break; }; done;; /*) ;; *) p=""; on=0;; esac; ` ++ `[ -n "$p" ] || exit 0; echo "bin:$p"; echo "on:$on"; ` ++ `echo "version:$("$p" --version 2>/dev/null | head -n1)"`++// rtkWSLScript is rtk's own Linux installer, run in the distro: it puts rtk+// in ~/.local/bin. curl, or wget where a distro has no curl.+const rtkWSLScript = `set -e; u=` + rtkScript + `; ` ++ `if command -v curl >/dev/null 2>&1; then s=$(curl -fsSL "$u"); ` ++ `elif command -v wget >/dev/null 2>&1; then s=$(wget -qO- "$u"); ` ++ `else echo "neither curl nor wget is installed in this distro" >&2; exit 1; fi; ` ++ `printf '%s\n' "$s" | sh`++// rtkWSLShown is how Install RTK names what it runs in a distro.+const rtkWSLShown = "curl -fsSL " + rtkScript + " | sh"++var rtkDistros_ struct {+ sync.Mutex+ at map[string]time.Time+ got map[string]RTKDistro+}++// rtkDistroAge is how long a distro's answer is kept: an rtk installed in+// it by hand is seen within it.+const rtkDistroAge = 15 * time.Second++// rtkDistroOf is the rtk of distro, which is asked (never started) unless+// it answered within rtkDistroAge; fresh asks it again.+func rtkDistroOf(distro string, fresh bool) RTKDistro {+ d := RTKDistro{Name: distro}+ if !agent.WSLRunning(distro) {+ d.Asleep = true+ return d+ }+ rtkDistros_.Lock()+ at, ok := rtkDistros_.at[distro]+ kept := rtkDistros_.got[distro]+ rtkDistros_.Unlock()+ if ok && !fresh && time.Since(at) < rtkDistroAge {+ return kept+ }+ // asked with no lock held: a distro slow to answer holds no other read+ out, err := rtkWSLRun(30*time.Second, "-d", distro, "-e", "sh", "-lc", rtkWSLProbe)+ if err != nil {+ // not known: not kept, and not offered an install either+ return d+ }+ for _, l := range strings.Split(string(out), "\n") {+ k, val, _ := strings.Cut(strings.TrimSpace(l), ":")+ switch val = strings.TrimSpace(val); k {+ case "bin":+ d.Path = val+ case "on":+ d.OffPath = val == "0"+ case "version":+ if m := semver.FindStringSubmatch(val); m != nil {+ d.Version = m[1]+ }+ }+ }+ if !strings.HasPrefix(d.Path, "/") {+ d.Path, d.OffPath, d.Version = "", false, ""+ }+ if d.Path == "" {+ d.Install = rtkWSLShown+ }+ rtkDistros_.Lock()+ defer rtkDistros_.Unlock()+ if rtkDistros_.at == nil {+ rtkDistros_.at, rtkDistros_.got = map[string]time.Time{}, map[string]RTKDistro{}+ }+ rtkDistros_.at[distro], rtkDistros_.got[distro] = time.Now(), d+ return d+}++// rtkDistros is the rtk of each distro an agent of list lives in.+func rtkDistros(list []RTKAgent) []RTKDistro {+ var names []string+ for _, a := range list {+ if a.WSL != "" && !a.NoHook && !slices.Contains(names, a.WSL) {+ names = append(names, a.WSL)+ }+ }+ var out []RTKDistro+ for _, n := range names {+ out = append(out, rtkDistroOf(n, false))+ }+ return out+}++// shq is s quoted for sh.+func shq(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }++// rtkInstallWSL runs rtk's installer in a's distro, by the distro's rtk+// (bin, its path there). It runs in a login shell, with what that gives the+// distro's agents; HOME is the distro's, so it writes under the home magpie+// reads a's files at. Claude Code is pointed at a folder of its own made+// and taken away there, as on this machine. An agent's folder variable+// (HERMES_HOME) isn't set: the distro's own, if any, is what its agent+// reads too.+func rtkInstallWSL(bin string, a *agent.Agent, sp rtkSpec) error {+ run, args := rtkInitWSL(bin, sp)+ out, err := rtkWSLRun(time.Minute, "-d", a.WSL, "-e", "sh", "-lc", run)+ if err != nil {+ said := installerSaid(string(out)+"\n"+exitSaid(err), 3)+ return fmt.Errorf("rtk %s in WSL %s: %s", strings.Join(args, " "), a.WSL, said)+ }+ if !sp.has(a) {+ return fmt.Errorf("rtk's installer didn't add its hook to %s: %s", a.Name, installerSaid(string(out), 3))+ }+ return nil+}++// rtkInitWSL is the sh command that runs the distro's rtk (bin) for sp's+// agent, and rtk init's arguments.+func rtkInitWSL(bin string, sp rtkSpec) (string, []string) {+ args := append([]string{"init", "-g"}, sp.flags...)+ if sp.patch {+ args = append(args, "--auto-patch")+ }+ q := make([]string, len(args))+ for i, s := range args {+ q[i] = shq(s)+ }+ run := "PATH=" + shq(bin[:strings.LastIndex(bin, "/")]) + `:"$PATH" ` + shq(bin) + " " + strings.Join(q, " ") + " </dev/null 2>&1"+ if sp.withClaude {+ run = `t=$(mktemp -d) || exit 1; CLAUDE_CONFIG_DIR="$t" ` + run + `; s=$?; rm -rf "$t"; exit $s`+ }+ return run, args+}++// exitSaid is what a failed wsl.exe wrote to stderr, or the error.+func exitSaid(err error) string {+ var ee *exec.ExitError+ if errors.As(err, &ee) && len(ee.Stderr) > 0 {+ return string(ee.Stderr)+ }+ return err.Error()+}++// InstallRTKIn installs rtk in WSL distro with rtk's own Linux installer,+// run there, when the user asks for it. A distro that isn't running isn't+// started for it.+func InstallRTKIn(distro string) (*RTKView, error) {+ rtkMu.Lock()+ known := false+ for _, a := range rtkAgents(detected()) {+ known = known || strings.EqualFold(a.WSL, distro)+ if strings.EqualFold(a.WSL, distro) {+ distro = a.WSL+ }+ }+ if !known {+ rtkMu.Unlock()+ return nil, fmt.Errorf("no agent RTK has a hook for is in a WSL distro named %q", distro)+ }+ if !agent.WSLRunning(distro) {+ rtkMu.Unlock()+ return nil, fmt.Errorf("WSL %s isn't running, and magpie doesn't start it to install RTK: start the distro (open its terminal), then install again", distro)+ }+ if d := rtkDistroOf(distro, true); d.Path != "" {+ rtkMu.Unlock()+ return ReadRTK(), nil+ }+ out, err := rtkWSLRun(5*time.Minute, "-d", distro, "-e", "sh", "-lc", rtkWSLScript+" 2>&1")+ d := rtkDistroOf(distro, true)+ rtkMu.Unlock()+ if err != nil {+ return nil, fmt.Errorf("RTK's installer failed in WSL %s: %s", distro, installerSaid(string(out)+"\n"+exitSaid(err), 3))+ }+ if d.Path == "" {+ return nil, fmt.Errorf("RTK's installer ran in WSL %s, but rtk still isn't found there: %s", distro, installerSaid(string(out), 3))+ }+ return ReadRTK(), nil+}diff --git a/internal/library/rtk_wsl_test.go b/internal/library/rtk_wsl_test.gonew file mode 100644index 000000000..5b2a4b31e--- /dev/null+++ b/internal/library/rtk_wsl_test.go@@ -0,0 +1,169 @@+package library++import (+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/agent"+ "github.com/yetone/magpie/internal/testenv"+)++// fakeDistroRTK stands in for wsl.exe -d <distro> -e sh -lc <script> on the+// distros of wslSandbox: the script runs here, with the distro's home as+// HOME and a PATH with no rtk on it, except RTK's installer, which isn't+// fetched (a test never reaches the network): it puts fakeRTK where the+// real one puts rtk, ~/.local/bin. It counts what ran in each distro.+func fakeDistroRTK(t *testing.T, home string) *sync.Map {+ t.Helper()+ ran := &sync.Map{}+ old := rtkWSLRun+ rtkWSLRun = func(_ time.Duration, args ...string) ([]byte, error) {+ if len(args) != 6 || args[0] != "-d" || args[2] != "-e" || args[3] != "sh" || args[4] != "-lc" {+ return nil, errors.New("unexpected wsl.exe " + strings.Join(args, " "))+ }+ n, _ := ran.LoadOrStore(args[1], new(int))+ *n.(*int)+++ if args[5] == rtkWSLScript+" 2>&1" {+ bin := filepath.Join(home, ".local", "bin", "rtk")+ if err := os.MkdirAll(filepath.Dir(bin), 0o755); err != nil {+ return nil, err+ }+ return []byte("installed\n"), os.WriteFile(bin, []byte(fakeRTK), 0o755)+ }+ cmd := exec.Command("/bin/sh", "-c", args[5])+ cmd.Env = []string{"HOME=" + home, "PATH=/usr/bin:/bin"}+ return cmd.Output()+ }+ forget := func() {+ rtkDistros_.Lock()+ rtkDistros_.at, rtkDistros_.got = nil, nil+ rtkDistros_.Unlock()+ }+ forget()+ t.Cleanup(func() { rtkWSLRun = old; forget() })+ return ran+}++func runsIn(ran *sync.Map, distro string) int {+ if n, ok := ran.Load(distro); ok {+ return *n.(*int)+ }+ return 0+}++func rtkRow(t *testing.T, v *RTKView, id string) RTKAgent {+ t.Helper()+ for _, a := range v.Agents {+ if a.ID == id {+ return a+ }+ }+ t.Fatalf("%s isn't on the RTK page: %+v", id, v.Agents)+ return RTKAgent{}+}++// Claude Code in a WSL distro gets RTK (lex on Discord): listed, with the+// distro's own rtk, installed there by RTK's installer and run there for+// the hook, which lands in the distro's ~/.claude, not this machine's.+func TestRTKWSL(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("the fake distro runs sh")+ }+ h := wslSandbox(t)+ ran := fakeDistroRTK(t, h)+ const distro = "Ubuntu-24.04"+ hooked := func(dir string) bool {+ b, _ := os.ReadFile(filepath.Join(dir, "settings.json"))+ return strings.Contains(string(b), "rtk hook claude")+ }++ v := ReadRTK()+ if a := rtkRow(t, v, wslClaude); a.WSL != distro || a.On || a.Asleep {+ t.Fatalf("WSL Claude Code's row: %+v", a)+ }+ if len(v.WSL) != 1 || v.WSL[0].Name != distro || v.WSL[0].Path != "" || v.WSL[0].Install != rtkWSLShown || v.WSL[0].Asleep {+ t.Fatalf("the distro's RTK, with none installed: %+v", v.WSL)+ }+ // no rtk in the distro: nothing to switch it on with+ if _, err := SetRTK(wslClaude, true); err == nil || !strings.Contains(err.Error(), "isn't installed in WSL "+distro) {+ t.Fatalf("switched on with no rtk in the distro: %v", err)+ }+ if _, err := InstallRTKIn("no-such-distro"); err == nil {+ t.Fatal("installed in a distro no agent is in")+ }+ // the distro's name as the user types it+ v, err := InstallRTKIn(strings.ToLower(distro))+ if err != nil {+ t.Fatal(err)+ }+ bin := filepath.Join(h, ".local", "bin", "rtk")+ if d := v.WSL[0]; d.Path != bin || d.Version != "9.9.9" || !d.OffPath || d.Install != "" {+ t.Fatalf("the distro's RTK after the install: %+v", d)+ }+ if _, err := SetRTK(wslClaude, true); err != nil {+ t.Fatal(err)+ }+ if !hooked(filepath.Join(h, ".claude")) {+ t.Fatal("no hook in the distro's ~/.claude/settings.json")+ }+ if hooked(filepath.Join(os.Getenv("HOME"), ".claude")) {+ t.Fatal("the hook went into this machine's Claude Code")+ }+ if a := rtkRow(t, ReadRTK(), wslClaude); !a.On {+ t.Fatalf("switched on, yet the row is off: %+v", a)+ }+ // this machine's Claude Code is its own+ if a := rtkRow(t, ReadRTK(), "claude"); a.On || a.WSL != "" {+ t.Fatalf("this machine's Claude Code: %+v", a)+ }+ if _, err := SetRTK(wslClaude, false); err != nil {+ t.Fatal(err)+ }+ if hooked(filepath.Join(h, ".claude")) {+ t.Fatal("switched off, the hook is still there")+ }+ if runsIn(ran, distro) == 0 {+ t.Fatal("nothing ran in the distro")+ }+}++// A distro that isn't running is never started for RTK (#3896): its agents+// are listed asleep, and switching or installing says to start it.+func TestRTKWSLAsleep(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("the fake distro runs sh")+ }+ h := wslSandbox(t)+ ran := fakeDistroRTK(t, h)+ const distro = "Ubuntu-24.04"+ testenv.Program(t, filepath.Join(h, ".local", "bin", "rtk"), fakeRTK)+ // seen while it ran, then stopped+ if a := rtkRow(t, ReadRTK(), wslClaude); a.Asleep {+ t.Fatalf("running, yet asleep: %+v", a)+ }+ agent.StopFakeWSL(distro)+ before := runsIn(ran, distro)+ v := ReadRTK()+ if a := rtkRow(t, v, wslClaude); !a.Asleep || a.On || a.WSL != distro {+ t.Fatalf("a stopped distro's Claude Code: %+v", a)+ }+ if len(v.WSL) != 1 || !v.WSL[0].Asleep || v.WSL[0].Path != "" {+ t.Fatalf("a stopped distro's RTK: %+v", v.WSL)+ }+ if _, err := SetRTK(wslClaude, true); err == nil || !strings.Contains(err.Error(), "isn't running") {+ t.Fatalf("switched in a stopped distro: %v", err)+ }+ if _, err := InstallRTKIn(distro); err == nil || !strings.Contains(err.Error(), "isn't running") {+ t.Fatalf("installed in a stopped distro: %v", err)+ }+ if n := runsIn(ran, distro) - before; n != 0 {+ t.Fatalf("%d commands ran in the stopped distro, each starting it", n)+ }+}