Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
library: a stopped WSL distro's agents are listed, and a tick for one is written there once it runs (cybercaius on Discord)
yetonec1da9ccda32d
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex 163a1d0c0..f26ba2c38 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -120,7 +120,7 @@ something else shows up as drift.- `Reapply` on `unwired` sets again every field on one of magpie's models and every field set to magpie itself (`magpieID`, as `Wired` takes it): Claude Desktop's drift shows on a tier, and its `provider` field is what writes the gateway back (dumplings on Discord). Claude Desktop's `Check` judges only the set of folders whose Claude-3p it ran in last (`desktopRead`, by `desktopdir.LastRun`), every set when it ran in none: magpie writes both of an MSIX install's sets, and 2.31226 reads the real `%LOCALAPPDATA%\Claude-3p`, so the package's copy being emptied is not Desktop off magpie.- `unreachable` never sets anything: the config is right, and the page's pill only says what has to listen. The exception is an address a WSL distro reached Windows at before (`distro.Was`, kept in `wsl.json`) while it reaches Windows at another now: the pill offers that one, and `Reapply` moves the config there (`Agent.move`, Codex's `codexMoveGateway`). An address no distro was seen at is the user's own and is never moved. An unknown answer (no probe yet) and a gateway down on loopback too are not drift. Tests stub `reachProbe` in `TestMain`. A WSL twin's address on a WSL network is asked from inside the running distro (`reachFrom`, `wslReach`: curl, wget or bash's /dev/tcp), never from Windows, where the gateway's own listener answers whatever the firewall keeps out. A distro that can't connect is told the firewall rule that lets it in (`wslFirewallCommand`). A stopped distro is never run to be asked, and one with nothing to ask with is not drift.- `proxied` (Muma102kMichael on X: every project and every new chat 502 after magpie took Codex over) is this machine's Codex sending its requests for the gateway through a proxy that doesn't pass them on, while the gateway answers here ([`codex_proxy.go`](../../internal/agent/codex_proxy.go)). Codex's reqwest takes `HTTP_PROXY`, else the system's proxy for `http://` (macOS' HTTP entry alone, never its HTTPS or SOCKS one; Windows' `ProxyServer` only when it is one address for every protocol), else `ALL_PROXY`, and lets only an exact IP or a CIDR in `NO_PROXY` (on Windows, with no `NO_PROXY`, the bypass list with `*.` taken out) keep 127.0.0.1 off it: `127.*` and `localhost` don't, and macOS' exceptions aren't read. With `[features] respect_system_proxy` it asks the system alone, matching its list itself, wildcards and `<local>` included, and goes direct when no proxy is set there; a macOS SOCKS entry alone it can't use, and takes `HTTP_PROXY`/`ALL_PROXY` then (codex-rs `outbound_proxy`; tried with codex-cli 0.162.1). Its reqwest has no SOCKS, so a `socks5://` proxy is spoken to as an HTTP one, and the probe does the same. The environment is Codex's: the login shell's `*_PROXY` (`proc.LoginEnv`, which a terminal's Codex and the ChatGPT app's both have; only exported ones, as the probe asks a child `/bin/sh` for them, so fish's unexported universal `http_proxy` doesn't count, #2627) over magpie's own, which a magpie opened from the Dock lacks (liu_dyj on X: a `NO_PROXY=127.0.0.1` in the profile, or a macOS proxy with no HTTP entry, warned while Codex went direct). `codexProxyFor` works out that proxy the same way, and a `GET /` through it must come back as magpie's (`proxyProbe`), tried as `reachable` is. Its pill says how to fix it, as `unreachable`'s does, naming the proxy and the variable it was read from, `http_proxy` or `HTTP_PROXY` as it is (`Addr`, `Detail`), through `netproxy.Redact`, without its user and password (#1886), while the probe goes through it whole, and the dialog has Disconnect from magpie. Account failover, which magpie writes uninvited, waits for that probe (`codexProxyOK`) and isn't written while the proxy doesn't pass Codex on, and one it wrote goes again. Tests stub the env, the system proxy and `proxyProbe` in `TestMain`.-- Listing never starts a stopped WSL distro. A stopped distro's agent shows what was last seen there (`asleep`, `wsl.json`); setting one of its fields writes its files, which starts the distro.+- Listing never starts a stopped WSL distro. A stopped distro's agent shows what was last seen there (`asleep`, `wsl.json`); setting one of its fields writes its files, which starts the distro. The Library keeps what it last saw of each agent's places there in the same memory (`WSLKeep`, `WSLKept`; see [library](library.md)), and lists a stopped distro's agents from it.- Codex's sign-in (`login`) is ChatGPT (`""`, the default), Always ChatGPT (`chatgpt`) or magpie API (`api`). With ChatGPT, magpie's models join Codex's own beside the sign-in (`openai_base_url`), and while the Codex app holds the ChatGPT account Codex is signed in to (`codexUsedUp`, `provider.CodexUsedUp`: OpenAI no longer allows the account and it has no credits left, a workspace still within its overage excepted), magpie is made Codex's provider (`codex.out`): the Codex app sends nothing at all on an account it holds, a magpie model's turn included (#540), and as a provider of its own magpie is past that. A window at 100% with credits left doesn't count, and Codex stays signed in. Sync puts it back beside the sign-in once the account has room. Always ChatGPT never does that: Codex stays in its ChatGPT state, and the Codex app may send nothing till the account has room, while Codex CLI's turns still reach magpie by the base URL, and its routing and other accounts serve them. Codex's app-server answers `account/read` and `getAuthStatus` with no account and no token for a provider without `requires_openai_auth`, and the Codex app then switches to an identity of no account: its ChatGPT mode's chats and projects ("Work") are gone, with its Chrome control (#1824) and cloud tasks, while magpie's models still answer (Qyburn3 on X). So `[model_providers.magpie]` says `requires_openai_auth = true` while Codex has a ChatGPT sign-in with room (`openaiAuth`: `codexChatGPTKnown` and not `codexUsedUp`), magpie API included; Codex still sends magpie's key (`experimental_bearer_token`) and no ChatGPT-Account-ID, with the same tools (tried with ChatGPT.app 26.1021 and its codex 0.164.0-alpha.11 against a capturing server). Not for an API key alone (Codex drops its image tool for a provider requiring OpenAI auth, `uses_openai_actor_authorization`), no sign-in (the app would ask for one), or a sign-in the Codex app holds: the app would read its rate limit again and grey Send for magpie's models too, which `codex.out` exists to get past. Sync writes the key in or takes it out as the sign-in or the allowance changes, an older magpie's table included (`authStale`), and the key is part of the app-server's route (`codexAppRoute`), so the Codex app is restarted onto its account (`TestCodexMagpieProviderKeepsChatGPTAccount`, `TestCodexAppRouteFollowsOpenAIAuth`). While magpie is Codex's provider for `codex.out` the app has no account till the reset, so the Agents row opened over that takeover names browser use among what is off and offers Keep on ChatGPT right there (`keepChatGPT`, posting `login` = `chatgpt`); picked on one of Codex's own models taken over (`codex/<model>`), `set` puts Codex back on its sign-in at once, `model_provider` and `model_catalog_json` gone, where it had left magpie the provider (eddie.zhan on Discord, `TestCodexOwnModelOutThenKeptOnChatGPT`). While magpie is Codex's provider (magpie API, or `codex.out`), `Joined` reports false although the `codex.joined` mark stays for Sync's way back: the Agents row said Codex's own models stay in `/model` beside magpie's, the ChatGPT state the Codex app blocks sending in, and the app only leaves that state once it is restarted (#2267, `TestCodexProviderIsNotJoined`). A Codex that reaches the gateway from another machine (a WSL distro under NAT, or `MAGPIE_ADDR` pinned beyond loopback, `onAnotherMachine(at.gw())`) is wired as one with no ChatGPT sign-in (`chatGPT()` is false there): never joined or beside, since beside its sign-in it would send its ChatGPT token to `/backend-api/codex`, and from there the gateway takes a named key alone, so every request was a 401 (#2145, `TestCodexBeyondLoopbackNotJoined`). magpie is its provider and it sends `gwKey()`, the LAN sharing key; one of its own models picked goes straight to OpenAI on its sign-in.- Whether Codex is signed in to ChatGPT is read from its auth.json or keychain item (`codexChatGPTKnown`, `provider.CodexSignInKnown`). Codex rewrites auth.json in place when it refreshes its tokens (codex-rs `FileAuthStorage::save` opens it with truncate), so a read in that moment finds it empty or cut off, and a keychain read can fail for a moment. Such a read is unknown, and Codex is taken to be as magpie last wired it (joined, beside, or `codex.out`); only a sign-in that isn't there (no auth.json, no item) or holds no ChatGPT token is "not signed in". Taking an unknown read for "not signed in" made Sync or a pick move Codex from beside its sign-in to magpie as its provider, with no `codex.out` to bring it back, and the Codex app showed "magpie" for its account and magpie's catalog for its models, on and off (lucy on Discord, v0.1.1394; `TestCodexHalfWrittenAuthKeepsSignIn`, `TestCodexHalfWrittenAuthKeepsOut`, `TestCodexSignInKnown`).- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next — never for a Codex that reaches the gateway from another machine, where that path takes a named key alone and the failed-over turn came back a 401 (#2145, `TestCodexFailoverBeyondLoopbackNotWritten`); Sync takes one it wrote before off again. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). So does every thread already open, in the Codex app above all: each turn went to the closed port, and a system proxy in between answered `503 Service Unavailable: Unknown error, url: http://127.0.0.1:3425/backend-api/codex/responses` until magpie was opened again (idkatbro on X; without a proxy Codex says "Connection refused" and reconnects). Masking plays no part: it runs only in the gateway, and its own 503 says why. When `EndCodexFailover` took failover out, the gateway's address is this computer's and Codex runs (`provider.CodexPIDs`: the app's app-server, the daemon, the CLI's sessions, an editor's codex), `OnShutdown` starts `magpie codex-relay` apart from itself (`agent.RelayOpenCodex`, `codexrelay.Start`; Setsid, or a detached process on Windows). It waits up to 60 s for the gateway to let go of the port, then serves only `/backend-api/codex/*` from Codex on this computer (a loopback Host, no Origin) and passes each request to the ChatGPT backend as the gateway passes a turn of Codex's own: the same item-id, compaction and Claude-seal rewrites, zstd and proxy, signed by the caller's own Authorization (`gateway.CodexRelay`). A magpie model, a turn on one of magpie's accounts, and a turn masking would have masked are refused with a readable 400 instead (Codex retries a 5xx five times over and shows a 4xx at once); anything else says magpie isn't running, never as magpie (`ServedBy`). It ends once every Codex process it was left for has and nothing is in flight, and the next magpie to serve the gateway asks it to leave (`codexrelay.Leave` in `ListenAndServe` and `serveGatewayLocked`; a POST with the token from `codex-relay.json`, 0600 in magpie's folder): it closes its listener at once and finishes the turns it streams, up to 30 minutes. `TestCodexRelay*`, `TestLeaveFreesPortAndFinishesStream`, `TestEndsWhenCodexGone`, `TestLeaveNeedsToken`. Not covered: a connected Codex (magpie's models, left pointed at magpie by design), a Codex in a WSL distro, and a magpie that ends without quitting. Every restart magpie makes runs `codex app-server daemon restart` as its own responsible process on macOS (`proc.CombinedOutputOwn`, a disclaimed `posix_spawn`): the daemon works in the folder of each codex attached to it, and as magpie's child the first codex in ~/Desktop had macOS ask for the Desktop folder in magpie's name (reformed9448 on Discord; `TestRestartedCodexDaemonIsNotMagpies`). A magpie built without cgo (the CLI) still restarts it as its own child. A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place.diff --git a/docs/subsystems/library.md b/docs/subsystems/library.mdindex 95140f255..d8b1a5f05 100644--- a/docs/subsystems/library.md+++ b/docs/subsystems/library.md@@ -16,6 +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:<kind>`). While it is stopped, `Read` lists its agents from that (`asleepView`, `asleep: <distro>`), 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) || 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) |@@ -87,6 +88,8 @@ go test -tags nogui ./internal/davsync -run 'TestSkillOffHereThroughSync'go test -tags nogui ./internal/cli -run 'TestLibrarySkillRm|TestLibrarySkillHandOver'go test -race ./internal/mcpauthgo test -tags nogui ./internal/library+go test -tags nogui ./internal/library -run 'TestWSLStopped'+node --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.cjs```diff --git a/internal/agent/wsl.go b/internal/agent/wsl.goindex 6411056d0..1c7768db6 100644--- a/internal/agent/wsl.go+++ b/internal/agent/wsl.go@@ -1296,6 +1296,20 @@ func wslRemember(name, key, v string) {wsl.dirty = true}+// WSLKeep has magpie remember v under key for the WSL distro name, in+// wsl.json beside what its probe found, for while the distro is stopped:+// what another package learnt of the distro's files while it ran (the+// library's places for each agent there), which it can't read again then+// without starting it (#3896). Nothing is kept for a distro never found.+func WSLKeep(name, key, v string) {+ wslRemember(name, key, v)+ wslSave()+}++// WSLKept is what WSLKeep last kept under key for the distro; "" for+// nothing.+func WSLKept(name, key string) string { return wslLastSeen(name, key) }+func wslLastSeen(name, key string) string {wsl.Lock()defer wsl.Unlock()diff --git a/internal/agent/wsl_fake.go b/internal/agent/wsl_fake.goindex 4878556a9..a9da94475 100644--- a/internal/agent/wsl_fake.go+++ b/internal/agent/wsl_fake.go@@ -3,6 +3,7 @@ package agentimport ("errors""strings"+ "sync""time")@@ -26,12 +27,15 @@ func FakeWSL(probes, roots map[string]string) func() {}list := []byte(strings.Join(names, "\n"))stopped := map[string]bool{}- fakeStop = func(name string) {+ fakeStop = func(name string, stop bool) {wsl.Lock()- stopped[name] = true+ stopped[name] = stopwsl.runAt = time.Time{}wsl.Unlock()}+ fakeCalls.Lock()+ fakeCalls.in = map[string]int{}+ fakeCalls.Unlock()wslOn = truewslRun = func(_ time.Duration, args ...string) ([]byte, error) {switch strings.Join(args, " ") {@@ -47,6 +51,9 @@ func FakeWSL(probes, roots map[string]string) func() {return []byte(strings.Join(run, "\n")), nil}if len(args) > 2 && args[0] == "-d" {+ fakeCalls.Lock()+ fakeCalls.in[args[1]]+++ fakeCalls.Unlock()if p, ok := probes[args[1]]; ok {return []byte(p), nil}@@ -61,13 +68,36 @@ func FakeWSL(probes, roots map[string]string) func() {}}-var fakeStop func(string)+var fakeStop func(string, bool)++// fakeCalls counts, for each of FakeWSL's distros, the commands run in it+// (wsl.exe -d name …): each one would start a stopped distro.+var fakeCalls struct {+ sync.Mutex+ in map[string]int+}// StopFakeWSL, for other packages' tests, has FakeWSL's distro name stop,// as the user stopping it (wsl --shutdown) does: wsl.exe lists it as not// running from now on.func StopFakeWSL(name string) {if fakeStop != nil {- fakeStop(name)+ fakeStop(name, true)+ }+}++// StartFakeWSL has a distro StopFakeWSL stopped run again, as the user+// opening a WSL shell does.+func StartFakeWSL(name string) {+ if fakeStop != nil {+ fakeStop(name, false)}}++// FakeWSLRuns is how many commands magpie ran in FakeWSL's distro name+// (wsl.exe -d name …), each of which starts a stopped distro.+func FakeWSLRuns(name string) int {+ fakeCalls.Lock()+ defer fakeCalls.Unlock()+ return fakeCalls.in[name]+}diff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.goindex 22f2b8039..b3765b465 100644--- a/internal/cli/library_cli.go+++ b/internal/cli/library_cli.go@@ -344,6 +344,11 @@ func libraryAgents(s, kind string) ([]string, error) {if err != nil {return nil, err}+ // one in a stopped WSL distro is recorded, and written there once+ // the distro runs: asking would start it (#3896)+ if d := library.AsleepIn(id); d != "" {+ fmt.Fprintln(os.Stderr, amber.Render("!"), muted.Render("WSL "+d+" isn't running: "+id+" is recorded, and magpie writes it there once it sees the distro running"))+ }out = append(out, id)}return out, nildiff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.jsindex 882e6a18b..6b3900f90 100644--- a/internal/gui/assets/plugins/library/client.js+++ b/internal/gui/assets/plugins/library/client.js@@ -65,11 +65,31 @@ magpie.plugin("library", (ctx) => {// One gone from this computer (gone: uninstalled, or its CLI) is listed// only on the rows of what it still has (withGone), for that to be taken// out: an agent that isn't installed was on every row (@jiahao_jayden).- const shownAgents = () => lib.agents.filter((a) => !a.gone && !isHidden(a));- const withGone = (all, on) => [...all, ...lib.agents.filter((a) => a.gone && (on || []).includes(a.id) && !all.some((x) => x.id === a.id))];+ // An agent in a stopped WSL distro (asleep) is listed by what magpie last+ // knew of it, its ticks kept for when the distro next runs; one whose+ // places magpie never saw (unseen) only on the rows that name it, like+ // a gone one, its chip greyed out: opening its files would start WSL+ // (#3896, cybercaius on Discord).+ const shownAgents = () => lib.agents.filter((a) => !a.gone && !a.unseen && !isHidden(a));+ const withGone = (all, on) => [...all, ...lib.agents.filter((a) => (a.gone || a.unseen && !isHidden(a)) && (on || []).includes(a.id) && !all.some((x) => x.id === a.id))];const mcpAgents = () => shownAgents().filter((a) => a.mcp).map((a) => a.mcpVia ? { ...a, aside: t("{agent} reads MCP servers through the {ext} extension", { agent: a.name, ext: a.mcpVia }) } : a);const skillAgents = () => shownAgents().filter((a) => a.skills);+ // the MCP hub's agents: not a stopped distro's, whose files say what it+ // 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));+ 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 }));+ if (unseen.length) p.append(" " + t("{agents} can be changed once it runs.", { agents: unseen.join(", ") }));+ p.dataset.distro = d;+ return p;+ });+ }function glyph(d, cls = "lib-glyph") {const g = el("span", cls);@@ -266,6 +286,12 @@ magpie.plugin("library", (ctx) => {// grey chip for a remote server and nothing said whyif (blocked) { c.classList.add("blocked"); c.setAttribute("aria-disabled", "true"); tip = blocked; }if (a.gone) { c.classList.add("gone"); tip = t("{agent} isn't installed here — click to take it away", { agent: a.name }); }+ if (a.unseen) { c.classList.add("asleep", "unseen", "blocked"); c.setAttribute("aria-disabled", "true"); tip = 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) {+ c.classList.add("asleep");+ const v = { distro: a.asleep, agent: a.name };+ if (!problem && !blocked) tip = has ? t("WSL {distro} isn't running: {agent} has it — click to take it away, and magpie writes the change there the next time it runs", v) : t("WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs", v);+ }c.title = a.aside && !problem && !blocked ? tip + "\n" + a.aside : tip;c.setAttribute("aria-pressed", has ? "true" : "false");// What's lit is read off the chips clicked, not the list they were@@ -293,12 +319,13 @@ magpie.plugin("library", (ctx) => {// The agents a row's chips have lit by a click: not one lit because it// has the item whatever is ticked.function litOf(box) {- return [...box.children].filter((x) => x.dataset.agent && !x.classList.contains("always") && x.getAttribute("aria-pressed") === "true").map((x) => x.dataset.agent);+ return [...box.children].filter((x) => x.dataset.agent && !x.classList.contains("always") && !x.classList.contains("unseen") && x.getAttribute("aria-pressed") === "true").map((x) => x.dataset.agent);}- // What a click leaves as it was: an agent not shown, and one that has the- // item whatever is ticked, whose chip can't be clicked.+ // What a click leaves as it was: an agent not shown, one that has the+ // item whatever is ticked, whose chip can't be clicked, and one in a+ // stopped distro magpie can't show the ticks of (unseen).function keptOf(box, all, on) {- const fixed = [...box.children].filter((x) => x.classList.contains("always")).map((x) => x.dataset.agent);+ const fixed = [...box.children].filter((x) => x.classList.contains("always") || x.classList.contains("unseen")).map((x) => x.dataset.agent);return on.filter((id) => !all.some((x) => x.id === id) || fixed.includes(id));}@@ -1230,7 +1257,7 @@ 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);- const skip = shownAgents().filter((a) => !a.instructions);+ 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(bar);}@@ -1529,6 +1556,7 @@ magpie.plugin("library", (ctx) => {if (lib.servers.length || lib.projects.length) renderProjects(body, "mcp");const skip = shownAgents().filter((a) => !a.mcp);if (skip.length) body.append(el("p", "lib-aside", t("{agents} has no MCP servers magpie can write.", { agents: skip.map((a) => a.name).join(", ") })));+ body.append(...asleepAsides());// WorkBuddy connects a server only once it is trusted there, again// after its command or address changes (#1266)for (const wb of shownAgents().filter((a) => (a.id === "workbuddy" || a.id === "workbuddy-ai") && a.mcp)) {@@ -1571,7 +1599,7 @@ magpie.plugin("library", (ctx) => {connect.classList.add("lib-hubconnect");at.append(glyph(GLYPH.web), aw, copyBtn(hubURL(), t("Address")), connect);list.append(at);- const names = (why) => mcpAgents().filter((a) => a.hub === why).map((a) => a.name).join(", ");+ const names = (why) => hubAgents().filter((a) => a.hub === why).map((a) => a.name).join(", ");const why = [["no-remote", "{agents} reaches no MCP server over HTTP, so it keeps each server's own entry."],["taken", "A server in the library is called magpie, so {agents} keeps each server's own entry: give that server another name for the hub to be used."],@@ -1598,7 +1626,7 @@ magpie.plugin("library", (ctx) => {const n = known.reduce((sum, s) => sum + Math.max(0, (health.get(s.name).h.tools || 0) - (s.disabledTools?.length || 0)), 0);parts.push(n === 1 ? t("1 tool") : t("{n} tools", { n }));}- const given = mcpAgents().filter((a) => a.hub === "on").map((a) => a.name);+ const given = hubAgents().filter((a) => a.hub === "on").map((a) => a.name);if (given.length) parts.push(t("in {agents}", { agents: given.length > 3 ? t("{first} and {n} more", { first: given.slice(0, 2).join(", "), n: given.length - 2 }) : given.join(", ") }));return parts.join(" · ");}@@ -1726,7 +1754,7 @@ magpie.plugin("library", (ctx) => {};const drawAgents = () => {- const all = mcpAgents();+ const all = hubAgents();const st = (a) => a.hub || (a.noRemote ? "no-remote" : "");const can = all.filter((a) => st(a) === "on" || !st(a));const on = can.filter((a) => st(a) === "on");@@ -1835,7 +1863,7 @@ magpie.plugin("library", (ctx) => {pane.scrollTop = top;if (focus) { const i = pane.querySelector("#lib-hubq"); i.focus(); i.setSelectionRange(i.value.length, i.value.length); }// the one primary action: Connect all while there are agents to connect- const rest = hubTab === "agents" && served().length ? mcpAgents().filter((a) => !a.hub && !a.noRemote) : [];+ const rest = hubTab === "agents" && served().length ? hubAgents().filter((a) => !a.hub && !a.noRemote) : [];bar.replaceChildren(el("span", "grow lib-hubnote", changed ? t("Restart an agent for it to read the change") : ""), done);done.className = "text" + (rest.length ? "" : " primary");done.disabled = false;@@ -3148,6 +3176,7 @@ magpie.plugin("library", (ctx) => {if (lib.skills.length || lib.projects.length) renderProjects(body, "skills");const skip = shownAgents().filter((a) => !a.skills);if (skip.length) body.append(el("p", "lib-aside", t("{agents} has no skills folder.", { agents: skip.map((a) => a.name).join(", ") })));+ body.append(...asleepAsides());// Desktop reads its skills list again only when its window is reloaded (#638)if (shownAgents().some((a) => a.id === "claude-desktop" && a.skills)) {body.append(el("p", "lib-aside", t("Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.", { keys: /^Mac/.test(navigator.platform) ? "⌘R" : "Ctrl+R" })));diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.jsindex c604d14cf..d6f22f6d9 100644--- a/internal/gui/assets/plugins/library/i18n.js+++ b/internal/gui/assets/plugins/library/i18n.js@@ -702,6 +702,11 @@ magpie.strings({"{agent} isn't installed here — click to take it away": "本机没有安装 {agent}——点一下把它移除","Not installed here": "本机未安装","Not installed here: it isn't given anything new, and what it has can be taken out here": "本机没有安装:不会再分配新的内容,已有的可以在这里移除",+ "WSL {distro} isn't running, and magpie hasn't seen {agent}'s files there yet: start the distro to change this": "WSL {distro} 未运行,magpie 还没见过 {agent} 在那里的文件:启动该发行版后才能修改",+ "WSL {distro} isn't running: {agent} has it — click to take it away, and magpie writes the change there the next time it runs": "WSL {distro} 未运行:{agent} 已启用——点一下移除,magpie 会在它下次运行时写入",+ "WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} 未运行:点一下,{agent} 会在该发行版下次运行时启用",+ "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.": "WSL {distro} 未运行:其中的 Agent 显示的是 magpie 上次看到的内容,你的修改会在它下次运行时写入。",+ "{agents} can be changed once it runs.": "{agents} 要等它运行后才能修改。",},"zh-TW": {"Move into the library": "移入資源庫",@@ -1404,6 +1409,11 @@ magpie.strings({"{agent} isn't installed here — click to take it away": "本機沒有安裝 {agent}——點一下把它移除","Not installed here": "本機未安裝","Not installed here: it isn't given anything new, and what it has can be taken out here": "本機沒有安裝:不會再分配新的內容,已有的可以在這裡移除",+ "WSL {distro} isn't running, and magpie hasn't seen {agent}'s files there yet: start the distro to change this": "WSL {distro} 未執行,magpie 還沒見過 {agent} 在那裡的檔案:啟動該發行版後才能修改",+ "WSL {distro} isn't running: {agent} has it — click to take it away, and magpie writes the change there the next time it runs": "WSL {distro} 未執行:{agent} 已啟用——點一下移除,magpie 會在它下次執行時寫入",+ "WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} 未執行:點一下,{agent} 會在該發行版下次執行時啟用",+ "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.": "WSL {distro} 未執行:其中的 Agent 顯示的是 magpie 上次看到的內容,你的修改會在它下次執行時寫入。",+ "{agents} can be changed once it runs.": "{agents} 要等它執行後才能修改。",},ja: {"Move into the library": "ライブラリへ移す",@@ -2106,6 +2116,11 @@ magpie.strings({"{agent} isn't installed here — click to take it away": "{agent} はこのコンピューターにインストールされていません — クリックして外します","Not installed here": "このパソコンに未インストール","Not installed here: it isn't given anything new, and what it has can be taken out here": "このコンピューターにはインストールされていません:新しいものは割り当てられず、すでにあるものはここで外せます",+ "WSL {distro} isn't running, and magpie hasn't seen {agent}'s files there yet: start the distro to change this": "WSL {distro} は起動していません。magpie はまだそこにある {agent} のファイルを見ていません。変更するにはディストリビューションを起動してください",+ "WSL {distro} isn't running: {agent} has it — click to take it away, and magpie writes the change there the next time it runs": "WSL {distro} は起動していません。{agent} は有効です — クリックで外します。変更は次に起動したときに magpie が書き込みます",+ "WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} は起動していません。クリックすると、ディストリビューションが次に起動したときに {agent} に追加されます",+ "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.": "WSL {distro} は起動していません。そのエージェントは magpie が最後に見た内容で表示され、変更は次に起動したときに書き込まれます。",+ "{agents} can be changed once it runs.": "{agents} は起動後に変更できます。",},de: {"Move into the library": "In die Bibliothek verschieben",@@ -2808,5 +2823,10 @@ magpie.strings({"{agent} isn't installed here — click to take it away": "{agent} ist hier nicht installiert – klicken, um es zu entfernen","Not installed here": "Hier nicht installiert","Not installed here: it isn't given anything new, and what it has can be taken out here": "Hier nicht installiert: Es erhält nichts Neues, und was es hat, kann hier entfernt werden",+ "WSL {distro} isn't running, and magpie hasn't seen {agent}'s files there yet: start the distro to change this": "WSL {distro} läuft nicht, und magpie hat die Dateien von {agent} dort noch nicht gesehen: Starte die Distribution, um das zu ändern",+ "WSL {distro} isn't running: {agent} has it — click to take it away, and magpie writes the change there the next time it runs": "WSL {distro} läuft nicht: {agent} hat es – klicken, um es zu entfernen; magpie schreibt die Änderung beim nächsten Start dorthin",+ "WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs": "WSL {distro} läuft nicht: Ein Klick gibt es {agent}, sobald die Distribution das nächste Mal läuft",+ "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.": "WSL {distro} läuft nicht: Seine Agenten zeigen, was magpie dort zuletzt gesehen hat, und Änderungen werden beim nächsten Start dorthin geschrieben.",+ "{agents} can be changed once it runs.": "{agents} lässt sich ändern, sobald sie läuft.",},});diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.cssindex 9fe883a4e..19084a151 100644--- a/internal/gui/assets/plugins/library/library.css+++ b/internal/gui/assets/plugins/library/library.css@@ -307,6 +307,8 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col.lib-ag.warn::after { content: ""; position: absolute; top: -2px; right: -2px; width: 7px; height: 7px; border-radius: 50%; background: var(--amber); box-shadow: 0 0 0 2px var(--card); }.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: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.cjsnew file mode 100644index 000000000..49fa98d76--- /dev/null+++ b/internal/gui/tests/library-wsl-asleep.test.cjs@@ -0,0 +1,157 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// cybercaius on Discord: with WSL not started, the Library's MCP page+// didn't list the agents installed in it. A stopped distro's agents+// (asleep) are listed by what magpie last saw there: a chip is lit as the+// library has it, quietly greyer, and says the distro isn't running; a+// click is sent as any is, and magpie writes it there when the distro+// 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.+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 { strings } = require("./strings.cjs");++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) => ({+ 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: 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: [],+});++let I18N;+function tr(lang, key, vars = {}) {+ let s = key;+ if (lang !== "en") {+ assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`);+ s = I18N[lang][key];+ }+ return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));+}++function server(lang, state, posts) {+ return async (route) => {+ const req = route.request(), url = new URL(req.url());+ const json = (data, status = 200) => route.fulfill({ status, json: data });+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });+ if (url.pathname === "/api/library") return json(lib(state.servers));+ if (url.pathname.startsWith("/api/library/") && req.method() === "POST" && !url.pathname.endsWith("/reveal") && !url.pathname.includes("/check")) {+ const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", "");+ posts.push({ what, body });+ 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: [] } });+ }+ return json(lib(state.servers));+ }+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname === "/api/usage/quotas") return json([]);+ if (url.pathname === "/api/groups") return json({ groups: [] });+ if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });+ if (url.pathname.startsWith("/api/")) return json({});+ if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];+ try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }+ };+}++const sideways = (page) => page.evaluate(() => {+ const over = [];+ const w = document.documentElement.clientWidth;+ if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth);+ for (const e of document.querySelectorAll("#view-library .lib-server, #view-library .lib-agents, #view-library .lib-asleep")) {+ const r = e.getBoundingClientRect();+ if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "–" + Math.round(r.right));+ }+ return over;+});++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(engine + ": a stopped WSL distro's agents are on the MCP 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: [srv("fetch", [CX, PI]), srv("git", ["claude"]), srv("events", [], { transport: "sse", command: "", url: "https://example.invalid/sse" })] };+ const posts = [], errors = [];+ const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });+ await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } 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-server").filter({ has: page.locator(".name", { hasText: new RegExp("^" + name) }) });+ const chips = (name) => row(name).locator(":scope > .lib-agents > .lib-ag[data-agent]").evaluateAll((cs) => cs.map((c) => c.dataset.agent));+ const chip = (name, id) => row(name).locator(`.lib-ag[data-agent="${id}"]`);+ await row("git").waitFor();++ // Codex in the stopped distro is on every row, Pi only on fetch's+ assert.deepEqual(await chips("fetch"), ["claude", CX, PI]);+ assert.deepEqual(await chips("git"), ["claude", CX]);+ assert.deepEqual(await chips("events"), ["claude", CX]);+ const cx = chip("fetch", CX);+ assert.match(await cx.getAttribute("class"), /\basleep\b/);+ assert.equal(await cx.getAttribute("aria-pressed"), "true");+ assert.equal(await cx.getAttribute("aria-disabled"), null);+ assert.equal(await cx.getAttribute("title"), w("WSL {distro} isn't running: {agent} has it — click to take it away, and magpie writes the change there the next time it runs", { distro: D, agent: "Codex · WSL " + D }));+ assert.equal(await chip("git", CX).getAttribute("title"), w("WSL {distro} isn't running: a click gives it to {agent} the next time the distro runs", { distro: D, agent: "Codex · WSL " + D }));+ // what it can't take says so, as on any chip: no SSE for Codex+ assert.match(await chip("events", CX).getAttribute("class"), /\bblocked\b/);+ assert.notEqual(await chip("events", CX).getAttribute("title"), await chip("git", CX).getAttribute("title"));+ const pi = chip("fetch", PI);+ assert.match(await pi.getAttribute("class"), /\bunseen\b/);+ assert.equal(await pi.getAttribute("aria-disabled"), "true");+ assert.equal(await pi.getAttribute("aria-pressed"), "true");+ const unseen = 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 });+ assert.equal(await pi.getAttribute("title"), unseen);+ // one line for the distro, naming Pi; the line of agents with no+ // MCP servers doesn't+ const aside = v.locator(".lib-asleep");+ assert.equal(await aside.count(), 1);+ assert.equal(await aside.textContent(), 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 }) + " " + w("{agents} can be changed once it runs.", { agents: "Pi · WSL " + D }));+ assert.equal(await v.locator(".lib-aside").filter({ hasText: w("{agents} has no MCP servers magpie can write.", { agents: "Pi · WSL " + D }) }).count(), 0);+ assert.deepEqual(await sideways(page), [], "sideways with the rows");++ // Pi's chip clicked: nothing sent, the reason shown+ await row("fetch").locator(":scope > .lib-agents").hover();+ await pi.click({ force: true });+ await page.waitForTimeout(200);+ assert.deepEqual(posts, []);+ // Claude Code given fetch: Pi keeps it, as Codex does+ await chip("fetch", "claude").click();+ await page.waitForTimeout(300);+ assert.deepEqual(posts.map((p) => p.what), ["servers/agents"]);+ assert.deepEqual([...posts[0].body.agents].sort(), ["claude", CX, PI]);+ // Codex given git while its distro is stopped: sent, kept+ await row("git").locator(":scope > .lib-agents").hover();+ await chip("git", CX).click();+ await page.waitForTimeout(300);+ assert.deepEqual(posts[1], { what: "servers/agents", body: { name: "git", agents: ["claude", CX] } });+ assert.deepEqual(errors, []);+ await ctx.close();+ });+ }+ });+}diff --git a/internal/library/instructions.go b/internal/library/instructions.goindex 746a75c51..1e7611f4f 100644--- a/internal/library/instructions.go+++ b/internal/library/instructions.go@@ -675,7 +675,8 @@ func SyncLinked() (*Result, error) {return changeInstructions(func(*Library) error { return nil })}-// KeepLinked runs SyncLinked every interval, for as long as the app runs.+// KeepLinked runs SyncLinked, and Woken, every interval, for as long as+// the app runs.func KeepLinked(interval time.Duration) {for {if res, err := SyncLinked(); err != nil {@@ -685,6 +686,8 @@ func KeepLinked(interval time.Duration) {log.Println("library: linked instructions:", p.Agent, p.What, p.Error)}}+ // what was ticked for a stopped WSL distro's agents, once it runs+ keepWoken()time.Sleep(interval)}}diff --git a/internal/library/sync.go b/internal/library/sync.goindex 334b0652d..557f0d881 100644--- a/internal/library/sync.go+++ b/internal/library/sync.go@@ -403,6 +403,13 @@ type AgentView struct {// Gone: not installed here any more, and listed only for what magpie// gave it to be taken out (held); it is given nothing newGone bool `json:"gone,omitempty"`+ // Asleep is the WSL distro, not running now, the agent is in: it is+ // listed by what magpie last knew of it (wsl_asleep.go), and a change+ // for it is written there when the distro next runs. Unseen: magpie+ // never saw where it keeps its MCP servers or skills, so its ticks+ // can't be shown or changed until the distro runs+ Asleep string `json:"asleep,omitempty"`+ Unseen bool `json:"unseen,omitempty"`}// ServerView is a library server, and what each agent it's on made of it.@@ -519,7 +526,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 := Targets()+ 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}for _, t := range targets {av := AgentView{ID: t.Agent.ID, Name: t.Agent.Name, Icon: t.Agent.Icon, Instructions: t.Instructions, Skills: t.Skills,@@ -564,6 +571,13 @@ func readView(problems []Problem, glance bool) (*View, error) {}v.Agents = append(v.Agents, av)}+ // 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 av, ok := l.asleepView(a); ok {+ v.Agents = append(v.Agents, av)+ }+ }of := func(what string) map[string]string {m := map[string]string{}for _, p := range problems {@@ -751,12 +765,20 @@ func serversAgents(names, agents []string, on bool) (*Result, error) {}}mcp := map[string]*mcpFile{}+ // a stopped distro's agents, by what magpie last knew of them+ shapes := map[string]*shape{}if on {- for _, t := range Targets() {+ ts, asleep := targetsAsleep(false)+ for _, t := range ts {if t.MCP != nil {mcp[t.Agent.ID] = t.MCP}}+ for _, a := range asleep {+ if sh := shapeOf(a); sh != nil {+ shapes[a.ID] = sh+ }+ }}for _, s := range l.MCP {if names != nil && !slices.Contains(names, s.Name) {@@ -764,7 +786,7 @@ func serversAgents(names, agents []string, on bool) (*Result, error) {}kept := slices.DeleteFunc(slices.Clone(s.Agents), func(a string) bool { return slices.Contains(agents, a) })for _, a := range agents {- if on && mcp[a] != nil && mcp[a].supports(s) == nil {+ if on && mcp[a] != nil && mcp[a].supports(s) == nil || on && shapes[a] != nil && shapes[a].reaches(s) {kept = append(kept, a)} else if on && slices.Contains(s.Agents, a) {kept = append(kept, a) // one it has already stays, whatever it says of itdiff --git a/internal/library/targets.go b/internal/library/targets.goindex 68a02aaf7..0c4947a96 100644--- a/internal/library/targets.go+++ b/internal/library/targets.go@@ -744,7 +744,17 @@ func Targets() []*Target { return targets(false) }func everyTarget() []*Target { return targets(true) }func targets(gone bool) []*Target {+ out, _ := targetsAsleep(gone)+ return out+}++// targetsAsleep is targets, and the agents in WSL distros that aren't+// running now: none is a target, as its files can't be opened without+// starting the distro, but the page lists them (asleepView). Each running+// one's places are kept for when it is stopped (keepShape).+func targetsAsleep(gone bool) ([]*Target, []*agent.Agent) {var out []*Target+ var asleep []*agent.Agentown := map[string]bool{}for _, a := range apps() {own[a.ID] = true@@ -767,6 +777,11 @@ func targets(gone bool) []*Target {if !gone && a.CLIMissing() {continue}+ if isAsleep(a) {+ asleep = append(asleep, a)+ noteUp(a.WSL, false)+ continue+ }if t := targetOf(a); t != nil && t.open() {out = append(out, t)}@@ -780,7 +795,12 @@ func targets(gone bool) []*Target {}}readsWith(out)- return out+ for _, t := range out {+ if t.Agent.WSL != "" {+ keepShape(t)+ }+ }+ return out, asleep}// held are the agents not among have (Targets) — uninstalled, or gone for@@ -896,7 +916,12 @@ func Takes(q, kind string) (string, error) {}t := targetOf(a)var has bool- if t == nil && a.WSL != "" && (a.Home == "" || !agent.WSLRunning(a.WSL)) {+ 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 != "") {+ 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)}if t != nil {diff --git a/internal/library/wsl_asleep.go b/internal/library/wsl_asleep.gonew file mode 100644index 000000000..bf2ccaff5--- /dev/null+++ b/internal/library/wsl_asleep.go@@ -0,0 +1,225 @@+package library++import (+ "encoding/json"+ "log"+ "maps"+ "slices"+ "strings"+ "sync"++ "github.com/yetone/magpie/internal/agent"+)++// A stopped WSL distro's agents are no targets (wslTargetOf): their files+// 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.++// 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.+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"`+}++// shapeKey is the key a WSL agent's shape is kept under in its distro's+// memory: one for each kind of agent (codex, omp#work).+func shapeKey(id string) string {+ kind, _, _ := strings.Cut(id, "@")+ return "library:" + kind+}++// 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}+ if t.MCP != nil {+ sh.MCP = t.MCP.Path+ sh.NoSSE = t.MCP.supports(&Server{Transport: "sse"}) != nil+ sh.NoRemote = t.MCP.supports(&Server{Transport: "http"}) != nil+ sh.NoEnvRefs = t.MCP.refsOf() == envSyntax{}+ sh.ToolsOff = toolsOffOf(t) != toolsNone+ sh.Startup = t.MCP.Format == fmtCodex+ }+ b, err := json.Marshal(sh)+ if err != nil {+ return+ }+ if string(b) != agent.WSLKept(a.WSL, shapeKey(a.ID)) {+ agent.WSLKeep(a.WSL, shapeKey(a.ID), string(b))+ }+}++// 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.+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 == "" {+ return nil+ }+ return &sh+}++// reaches says whether the agent can be given s, as far as its shape+// tells (the page's reaches): what its file was found to read when the+// distro last ran. The rest (a header Codex reads only whole) is said by+// the sync that writes it, as for any agent.+func (sh *shape) reaches(s *Server) bool {+ switch {+ case sh.MCP == "":+ return false+ case s.Transport == "sse" && sh.NoSSE, s.Remote() && sh.NoRemote:+ return false+ case sh.NoEnvRefs && (s.Remote() && hasRef(s.Headers) || !s.Remote() && hasRef(s.Env)):+ return false+ case !s.Remote() && windowsPath.MatchString(s.Command) && !isSelf(s):+ return false+ }+ return true+}++// isAsleep says whether a is an agent in a WSL distro that isn't running+// now: wslTargetOf's nil.+func isAsleep(a *agent.Agent) bool {+ return a.WSL != "" && (a.Home == "" || !agent.WSLRunning(a.WSL))+}++// asleepView is a stopped distro's agent as the page lists it: by its+// shape, or, with none known and the library naming it, as one whose+// ticks can't be shown (Unseen); false for one the page leaves out.+func (l *Library) asleepView(a *agent.Agent) (AgentView, bool) {+ av := AgentView{ID: a.ID, Name: a.Name, Icon: a.Icon, Asleep: a.WSL}+ sh := shapeOf(a)+ if sh == nil {+ av.Unseen = true+ return av, l.names(a.ID)+ }+ av.MCP, av.Skills, av.SkillsAlso, av.MCPVia = sh.MCP, sh.Skills, sh.SkillsAlso, sh.MCPVia+ av.NoSSE, av.NoRemote, av.NoEnvRefs, av.ToolsOff, av.Startup = sh.NoSSE, sh.NoRemote, sh.NoEnvRefs, sh.ToolsOff, sh.Startup+ if sh.Skills != "" {+ // a WSL agent takes copies only (Target.Copy)+ _, av.HowOwn = l.SkillHow[a.ID]+ av.How, av.MustCopy = HowCopy, true+ }+ return av, true+}++// names says whether the library gives the agent id anything, or holds+// something it gave it.+func (l *Library) names(id string) bool {+ if a := l.Applied[id]; a != nil && (len(a.Skills) > 0 || len(a.MCP) > 0 || len(a.Hooks) > 0) {+ return true+ }+ return slices.ContainsFunc(l.Skills, func(s *Skill) bool { return slices.Contains(s.Agents, id) }) ||+ 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.+func (l *Library) distrosNamed() []string {+ in := map[string]bool{}+ add := func(id string) {+ if _, d, ok := strings.Cut(id, "@wsl:"); ok && d != "" {+ in[d] = true+ }+ }+ for id := range l.Applied {+ if l.names(id) {+ add(id)+ }+ }+ for _, s := range l.Skills {+ for _, id := range s.Agents {+ add(id)+ }+ }+ for _, s := range l.MCP {+ for _, id := range s.Agents {+ add(id)+ }+ }+ return slices.Sorted(maps.Keys(in))+}++// wake is which distros were last seen stopped (false) or running (true),+// by Woken and by the reads that left a stopped one's agents out.+var wake struct {+ sync.Mutex+ up map[string]bool+}++func noteUp(distro string, up bool) {+ wake.Lock()+ defer wake.Unlock()+ if wake.up == nil {+ wake.up = map[string]bool{}+ }+ wake.up[distro] = up+}++// Woken writes the library into the agents of each distro it names that+// was seen stopped and runs now: what was ticked for them while it was+// stopped, kept in library.json, reaches them once the user starts it.+// Asking whether a distro runs (wsl.exe -l --running) doesn't start it.+// nil, nil when no such distro started.+func Woken() (*Result, error) {+ mu.Lock()+ l, err := load()+ mu.Unlock()+ if err != nil {+ return nil, err+ }+ started := false+ for _, d := range l.distrosNamed() {+ up := agent.WSLRunning(d)+ wake.Lock()+ was, seen := wake.up[d]+ wake.Unlock()+ noteUp(d, up)+ if up && seen && !was {+ started = true+ }+ }+ if !started {+ return nil, nil+ }+ return Sync()+}++// keepWoken is Woken for KeepLinked's loop, which logs what it couldn't do.+func keepWoken() {+ res, err := Woken()+ if err != nil {+ log.Println("library: a WSL distro that started:", err)+ return+ }+ if res != nil {+ for _, p := range res.Problems {+ log.Println("library: a WSL distro that started:", p.Agent, p.What, p.Error)+ }+ }+}++// AsleepIn is the WSL distro, not running now, of the agent with id; ""+// for any other. A change the library makes for it is written there the+// next time it runs.+func AsleepIn(id string) string {+ _, d, ok := strings.Cut(id, "@wsl:")+ if !ok || d == "" || agent.WSLRunning(d) {+ return ""+ }+ return d+}diff --git a/internal/library/wsl_test.go b/internal/library/wsl_test.goindex 67d02dfe4..bbb8d9d2f 100644--- a/internal/library/wsl_test.go+++ b/internal/library/wsl_test.go@@ -291,6 +291,137 @@ func TestWSLStoppedSinceNoTarget(t *testing.T) {}}+// viewOf is the agent id as Read lists it, nil for none.+func viewOf(t *testing.T, id string) *AgentView {+ t.Helper()+ v, err := Read(nil)+ if err != nil {+ t.Fatal(err)+ }+ for _, a := range v.Agents {+ if a.ID == id {+ return &a+ }+ }+ return nil+}++// cybercaius on Discord: with WSL not started, the MCP page didn't list+// the distro's agents at all. A stopped distro's agents are listed by+// what magpie last saw of them there, their ticks as the library has+// them; a tick is kept, and written into the distro once it runs (Woken).+// Nothing of the distro is opened or run while it is stopped (#3896).+func TestWSLStoppedListedAndQueued(t *testing.T) {+ const distro = "Ubuntu-24.04"+ h := wslSandbox(t)+ ok(t)(SaveServer("", Server{Name: "fetch", Transport: "stdio", Command: "uvx", Args: []string{"mcp-server-fetch"}, Agents: []string{wslCodex}}))+ ok(t)(SaveServer("", Server{Name: "events", Transport: "sse", URL: "https://example.invalid/sse"}))+ agent.StopFakeWSL(distro)+ // the distro's files gone from reach: anything opened there fails,+ // anything written there makes its folder again+ root := filepath.Dir(filepath.Dir(h))+ away := root + ".away"+ if err := os.Rename(root, away); err != nil {+ t.Fatal(err)+ }+ runs := agent.FakeWSLRuns(distro)+ cx := viewOf(t, wslCodex)+ if cx == nil {+ t.Fatal("a stopped distro's Codex isn't listed")+ }+ if cx.Asleep != distro || cx.Unseen || cx.MCP != filepath.Join(h, ".codex", "config.toml") || cx.Skills != filepath.Join(h, ".codex", "skills") || !cx.NoSSE || !cx.MustCopy || cx.How != HowCopy {+ t.Errorf("Codex while stopped: %+v", *cx)+ }+ if cl := viewOf(t, wslClaude); cl == nil || cl.Asleep != distro || cl.MCP != filepath.Join(h, ".claude.json") || cl.NoSSE {+ t.Errorf("Claude Code while stopped: %+v", cl)+ }+ for _, tg := range Targets() {+ if tg.Agent.WSL != "" {+ t.Errorf("%s is a target while its distro is stopped", tg.Agent.ID)+ }+ }+ // ticked while stopped: kept, and given only what it can take (no SSE+ // for OmO, as its chip says)+ ok(t)(ServerAgents("fetch", []string{wslCodex, wslClaude}))+ ok(t)(EveryServerAgents([]string{wslOmO}, true))+ l, err := load()+ if err != nil {+ t.Fatal(err)+ }+ if got := l.server("fetch").Agents; !slices.Equal(got, []string{wslClaude, wslCodex, wslOmO}) {+ t.Errorf("fetch's agents: %v", got)+ }+ if got := l.server("events").Agents; len(got) != 0 {+ t.Errorf("an SSE server given to a stopped agent that takes none: %v", got)+ }+ if id, err := Takes("Claude Code · WSL "+distro, "mcp"); err != nil || id != wslClaude {+ t.Errorf("Takes while stopped: %s %v", id, err)+ }+ if AsleepIn(wslClaude) != distro || AsleepIn("claude") != "" {+ t.Errorf("AsleepIn: %q", AsleepIn(wslClaude))+ }+ if _, err := os.Stat(root); !os.IsNotExist(err) {+ t.Errorf("something was written into the stopped distro: %v", err)+ }+ if n := agent.FakeWSLRuns(distro); n != runs {+ t.Errorf("%d commands ran in the stopped distro", n-runs)+ }+ if res, err := Woken(); res != nil || err != nil {+ t.Errorf("a sync while the distro is stopped: %+v %v", res, err)+ }+ // the user starts it: what was ticked is written there+ if err := os.Rename(away, root); err != nil {+ t.Fatal(err)+ }+ agent.StartFakeWSL(distro)+ res, err := Woken()+ if err != nil || res == nil {+ t.Fatalf("no sync once the distro ran: %+v %v", res, err)+ }+ if s := read(t, filepath.Join(h, ".claude.json")); !strings.Contains(s, `"fetch"`) {+ t.Errorf("claude@wsl .claude.json:\n%s", s)+ }+ if s := read(t, filepath.Join(h, ".omo", "agent", "mcp.json")); !strings.Contains(s, `"fetch"`) {+ t.Errorf("omo@wsl mcp.json:\n%s", s)+ }+ if res, err := Woken(); res != nil || err != nil {+ t.Errorf("a second sync with nothing started: %+v %v", res, err)+ }+ if v := viewOf(t, wslCodex); v == nil || v.Asleep != "" {+ t.Errorf("Codex once running: %+v", v)+ }+}++// An agent the library names in a distro that stopped before magpie ever+// saw its places is listed on its rows as one whose ticks can't be shown+// (Unseen); one it names nothing for isn't listed, and neither can be+// given anything until the distro runs.+func TestWSLStoppedUnseen(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)(SaveServer("", Server{Name: "fetch", Transport: "stdio", Command: "uvx", Agents: []string{wslPi}}))+ if v := viewOf(t, wslPi); v == nil || !v.Unseen || v.Asleep != distro || v.MCP != "" {+ t.Errorf("Pi named while stopped: %+v", v)+ }+ if v := viewOf(t, wslCodex); v != nil {+ t.Errorf("Codex named nowhere, never seen: %+v", v)+ }+ if _, err := Takes("Codex · WSL "+distro, "mcp"); err == nil || !strings.Contains(err.Error(), "isn't running") {+ t.Errorf("Takes of an unseen agent: %v", err)+ }+ ok(t)(EveryServerAgents([]string{wslCodex}, true))+ l, _ := load()+ if got := l.server("fetch").Agents; !slices.Equal(got, []string{wslPi}) {+ t.Errorf("fetch's agents: %v", got)+ }+ 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",