From f4068ccc255a4e44fee7df47e063b7426cbd3298 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 6 Nov 2026 21:28:16 +0800 Subject: [PATCH] proc: with Detect agents in WSL off, no wsl.exe is started on any path (#4872) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With Settings' Detect agents in WSL off (noWSLAgents), every Claude request still reached wsl.exe: wslReady (wslClaudeStandIn, wslCodexStandIn) and wslClaudeClassifier listed the running distros without asking wslLooks, the gate #1264 put on wslAgents, wslHomes and WSLRunning. wslrun's Up, In and running weren't gated either (only Find was). On a computer without WSL, Windows' inbox wsl.exe answers each ask with a window offering to install WSL, one per request. The fix is at the one choke point every command magpie starts goes through (TestNoCommandBypassesProc): proc.Command and CommandContext (and so ProbeContext, wslrun.Tool.Command/Probe, the Claude TUI helper's ConPTY start, which checks cmd.Err) refuse wsl.exe by any name or path (wsl, WSL.EXE, C:\Windows\System32\wsl.exe) with proc.ErrWSLOff while the setting is off, as a probe of an app's own program is refused. The paths that reach it: agent's wslRun/wslExec (lists, probes, links, chmod, reach), wslrun.Run/Find/In/Up/Stop, library's cmdvars, mcp_wsl, mcp_check and rtk_wsl, claudetui's wslread, the gateway's Claude Code in WSL. The settings read is settings.Shared() and only for a wsl name. Not gated: the Sessions page's resume line for a WSL session (a string a terminal runs on the user's click), whose sessions aren't listed with detection off. skygunner/vincent's stand-in fix is kept as well, so the stand-in and classifier return before taking wsl's lock or recording a failed list. Run: - mote-run: go vet ./internal/proc ./internal/agent ./internal/wslrun; GOOS=windows go vet of proc, agent, wslrun, claudetui, library, gateway; GOOS=linux go vet of proc, agent, wslrun, claudetui: clean. go test -count=1 ./internal/proc ./internal/wslrun ./internal/claudetui: ok; -run 'WSL|Wsl|Dsh' ./internal/agent ./internal/library ./internal/sessions: ok. gofmt -l: nothing. - win-run on xiaomi-gpu (Windows 11, real wsl.exe present): the four new tests plus TestWSLDetectionOff, TestWSLClaudeStandIn, TestWSLCodexStandIn, TestNoCommandBypassesProc: ok; -v shows each new test PASS; go test ./internal/proc ./internal/wslrun whole: ok. TestWSLRunnerRefusedWhenOff runs agent's real wslRun there. Broken by hand (wslOff's check made `if false && …`, agent/wsl.go at origin/main, new tests kept), on mote: TestWSLOffStartsNoWSL red for every name and maker, TestRunRefusedWhenOff "Run ran wsl.exe: exit status 1", TestWSLRunnerRefusedWhenOff red, TestWSLStandInAsksNothing WhenOff red with three "-l --running -q" asks. Not tried: the reporter's own Windows without WSL (the install window itself); the full suite runs after the push under the suite lock. Reported-by: 陌离 (Discord) Co-authored-by: vincent --- docs/subsystems/agent-wiring.md | 2 +- internal/agent/wsl.go | 11 +++++- internal/agent/wsl_off_test.go | 68 +++++++++++++++++++++++++++++++++ internal/agent/wsl_test.go | 7 +++- internal/proc/proc.go | 2 + internal/proc/wsl.go | 32 ++++++++++++++++ internal/proc/wsl_test.go | 65 +++++++++++++++++++++++++++++++ internal/wslrun/wslrun_test.go | 23 +++++++++++ 8 files changed, 207 insertions(+), 3 deletions(-) create mode 100644 internal/proc/wsl.go create mode 100644 internal/proc/wsl_test.go diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index db7cf7c11..eb307bf44 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -28,7 +28,7 @@ something else shows up as drift. | Codex instructions | Each magpie model's entry in Codex's catalog carries the instructions official Codex sends that model, Codex's own text word for word; magpie writes none of its own and never changes the identity line (`codexcat.officialFor`). The model's slug (the id's last path segment, lowercased) is matched as Codex matches one, by the longest prefix of an official slug (`longestPrefix`; `auto/gpt-6.1-sol` takes gpt-6.1-sol's, `s2a/openai/gpt-6-luna-2026-09-14` gpt-6-luna's): first against the entries the user's ChatGPT account handed this Codex (`CacheEntries`, models_cache.json), whose `base_instructions` (else `model_messages.instructions_template`) and `model_messages` go over as sent; then against Codex's bundled catalog (`codex_instructions.json`, each model's `instructions_template` from openai/codex rust-v0.166.0's models-manager/models.json), the text only, as an older Codex may not read that release's `model_messages`. Any other model, and a routing group (`group/`), which may hand a turn to any model, takes Codex's prompt for a model it doesn't know (`Prompt`, models-manager/prompt.md), which is what official Codex sends it (`model_info_from_slug`). An entry Codex was handed with no `base_instructions` (`ownEntry`) takes its `model_messages.instructions_template`, else `Official`, and magpie's own ChatGPT-backend requests fall back to `Official` too (`codexInstructions` in internal/provider). Until 11-01 every third-party model was handed gpt-5.2-codex_prompt.md ("You are Codex, based on GPT-5"), so a magpie GPT-6 model ran on a GPT-5.2-era prompt (#3759, #4008, #4783). The Codex files are in testdata (`testdata/codex-rust-v0.166.0`), and `TestBundledIsCodexOwn` fails when the embedded copies differ from them; on a new Codex release copy its two files there and rebuild `codex_instructions.json`. Real Codex 0.166 against a capturing gateway sends the official text as its first developer message for a GPT-6 model and prompt.md for DeepSeek. `TestThirdPartyModelsTakeCodexOwnInstructions`, `TestThirdPartyModelsTakeCachedEntry`, `TestOwnEntryInstructions`. Not read: the bundled catalog inside the user's installed Codex binary. | [`codexcat.go`](../../internal/codexcat/codexcat.go) | | Codex: DeepSeek models | A DeepSeek model's entry (`codexcat.deepSeek`: deepseek-v4*, -flash, -pro, -chat, -reasoner after any provider or relay prefix; not a routing group, not a distill) takes what DeepSeek's own Codex setup (cdn.deepseek.com/api-docs/codex-deepseek-setup-en.sh, its models.json) says of its models: `shell_type` `shell_command` (Codex 0.165 reads it as `unified_exec`, its only shell; older Codex had a one-shot `shell_command` tool), `support_verbosity` with `default_verbosity` low, `default_reasoning_summary` none (no `reasoning.summary` sent), `multi_agent_version` v2, and `supports_image_detail_original` on a model whose entry takes images. Not taken: its `base_instructions`/`model_messages` (magpie never rewrites a Codex prompt), its `auto_compact_token_limit` null (magpie's 272K default stays, from e950eb080's DeepSeek latency report; Full window or the model's Compact at gives the whole window), `supports_search_tool` false on v4-pro (#258), its reasoning levels (the provider's). `default_reasoning_summary` is tagged `keep:"unset"`, so a value the user put in another model's entry stays (`Keep`). Other vendors' entries are unchanged. `TestCodexCatalogDeepSeekAsDeepSeekSays`, `TestCodexCatalogKeepsUsersSummary`. | [`codexcat.go`](../../internal/codexcat/codexcat.go) | | Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#` on Windows, `omp#@wsl:` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) | -| WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `@wsl:`, edited through `\\wsl.localhost\`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Antigravity CLI is found by its own `~/.gemini/antigravity-cli` or its `agy` command (mimi001234 on Discord). Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go) | +| WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `@wsl:`, edited through `\\wsl.localhost\`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Antigravity CLI is found by its own `~/.gemini/antigravity-cli` or its `agy` command (mimi001234 on Discord). Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). With Settings' Detect agents in WSL off (`NoWSLAgents`, #1264) magpie starts no wsl.exe at all: `proc.Command`, `CommandContext` and `ProbeContext` refuse one by any name or path with `proc.ErrWSLOff` (`wslOff` in [`proc/wsl.go`](../../internal/proc/wsl.go)), where every command magpie runs is made, so a path past agent's and wslrun's own gates (a request's Claude Code stand-in and classifier, #4872: on a computer without WSL each ask put up Windows' install window) asks nothing either (`TestWSLOffStartsNoWSL`, `TestWSLRunnerRefusedWhenOff`, `TestRunRefusedWhenOff`, `TestWSLStandInAsksNothingWhenOff`). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go), [`proc/wsl.go`](../../internal/proc/wsl.go) | | WSL folders that are links | Through `\\wsl.localhost` Windows can't follow a link the distro has: with `~/.codex` a link to `/mnt/c/Users//.codex`, a mkdir of it says it exists and nothing below it can be made, written, read or listed (#4502, linusxiong). The probe asks `readlink -f` there where each agent folder, its `skills` and the folders beside them lead (`wslLinkPaths`, `distro.Links`; a `$HOME` that is itself through a link is left as it was) and which drive each Windows mount is (`distro.Drives`). `distro.open` opens a path at or below a link where it leads: on a Windows drive the drive's own path (`C:\Users\\.codex`), elsewhere in the distro through its root again; `native` spells such a path back through the link for the agent. A link `readlink -f` couldn't resolve is never guessed at: its agent is unreached (`Agent.Unreached`), says why in its notice and refuses each change and sync. Every writer goes through it: the agents' own files (`place.join`, `place.open`), the library's targets (`wslOpen`, a `wsl` problem per agent), RTK (`rtkAt`, `agent.WSLOpen`), the Sessions page's reads (`sessions.WSLHome.Open`) and the Copilot CLI's sign-in (`provider.CopilotWSLDirs`). Links deeper than the probed paths aren't resolved (`TestWSLOpenThroughLinks`, `TestWSLAgentFolderIsALink`, `TestWSLAgentFolderLinkUnresolved`, `TestWSLProbeLinks`, `TestWSLFolderIsALinkToC`, `TestRTKWSLFolderIsALink`). | [`wsl.go`](../../internal/agent/wsl.go), [`targets.go`](../../internal/library/targets.go), [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) | | Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings..autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated tokens against the setting now (fewer or more, the setting itself marked "Your setting now", hayden4608 on Discord), "Fewest tokens" beside the leanest, and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) | | Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. One whose agent keeps the model a new session starts on in a file apart from its provider list says so with `startup` (`config`, `format`, `model`, and `keys` written beside the model as they are) and has no `model`: PiG keeps its providers in `models.json` and `defaultProvider`/`defaultModel` in `settings.json` (str_ on Discord: its row only listed models, where Pi's picks the one it starts on). Its field is `model` again; picking one of magpie's writes `connect`'s keys into `config` and the model and `startup.keys` into `startup.config`, each file stashed under its own `plugin::` (the startup one marked by its first string key, so a model picked in the agent among magpie's, with `defaultProvider` still `magpie`, reads as magpie's). A model of the agent's own picked in it while `connect`'s keys are still in `config` is `Beside`: connected, not drift, and Disconnect leaves that pick and takes the rest out. A magpie without `startup` reads the same module as connect only (`TestPluggedStartupModel`, `TestPluggedStartupOwnPickKept`, `TestPluggedStartupRestoreGone`). `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`; a routing group's, `provider.GroupEndpoints`, the APIs every member relays as it is; carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) | diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index d62f41fef..4426d4e27 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -1533,7 +1533,13 @@ func wslLastSeen(name, key string) string { // with its mirrored networking settled, ready for a read of its files. // Only magpie's memory of them and which run (wslRunningLocked) are // asked — nothing is probed, and a stopped distro is never opened. +// Detection off (wslLooks) reads none: a request's stand-in asks wsl.exe +// nothing, which on a machine without WSL would answer with a console +// window asking to install it (#4872). func wslReady(kind string) []distro { + if !wslLooks() { + return nil + } wsl.Lock() wslRunningLocked() var ds []distro @@ -1564,8 +1570,11 @@ func wslClaudeStandIn(model string) string { } // wslClaudeClassifier is ClassifierStandIn for a Claude Code in a running -// distro, known by the same User-Agent. +// distro, known by the same User-Agent. Detection off reads none (#4872). func wslClaudeClassifier(model string) string { + if !wslLooks() { + return "" + } wsl.Lock() wslRunningLocked() var ds []distro diff --git a/internal/agent/wsl_off_test.go b/internal/agent/wsl_off_test.go index d55db88d1..6bb7e9e86 100644 --- a/internal/agent/wsl_off_test.go +++ b/internal/agent/wsl_off_test.go @@ -1,12 +1,15 @@ package agent import ( + "errors" "os" "path/filepath" "strings" "testing" "time" + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/sessions" "github.com/yetone/magpie/internal/settings" ) @@ -86,3 +89,68 @@ func TestWSLDetectionOff(t *testing.T) { t.Fatal("turned on again, the distro's agent isn't back") } } + +// #4872: with Settings' Detect agents in WSL off, the stand-in and +// classifier paths of a request ask wsl.exe nothing either: wslReady (for +// wslClaudeStandIn and wslCodexStandIn) and wslClaudeClassifier listed the +// running distros on their own, and on a machine without WSL Windows' +// inbox wsl.exe answers each of those with a console window asking to +// install it — one per Claude request. +func TestWSLStandInAsksNothingWhenOff(t *testing.T) { + root, home := claudeDistroHome(t, "") + fakeWSL(t, "Debian\r\n", "Debian\r\n", map[string]string{ + "Debian": "home:/home/me\ndir:.claude\nroute:default via 172.20.0.1 dev eth0\n", + }, map[string]string{"Debian": root}) + nat := "http://172.20.0.1:" + gateway.Port() + if err := os.WriteFile(filepath.Join(home, ".claude", "settings.json"), + []byte(`{"env":{"ANTHROPIC_BASE_URL":"`+nat+`","ANTHROPIC_MODEL":"a/main","ANTHROPIC_DEFAULT_HAIKU_MODEL":"a/small"}}`), 0o644); err != nil { + t.Fatal(err) + } + // every wsl.exe ask, the distro lists among them, not only a probe + var asks []string + run := wslRun + wslRun = func(d time.Duration, args ...string) ([]byte, error) { + asks = append(asks, strings.Join(args, " ")) + return run(d, args...) + } + + // detection on: the distro's Claude Code's stand-in is found + wslDistros() + if got := wslClaudeStandIn("claude-haiku-4-5-20251001"); got != "a/small" { + t.Fatalf("detection on, no stand-in: %q", got) + } + + t.Cleanup(func() { settings.Save(settings.Settings{}) }) + if err := settings.Save(settings.Settings{NoWSLAgents: true}); err != nil { + t.Fatal(err) + } + asks = nil + // the running list is asked again once it is older than wslRunningAge; + // each of the three paths would ask it on its own + stale := func() { wsl.Lock(); wsl.runAt = time.Time{}; wsl.Unlock() } + stale() + wslClaudeStandIn("claude-haiku-4-5-20251001") + stale() + wslCodexStandIn() + stale() + wslClaudeClassifier("claude-haiku-4-5-20251001") + if len(asks) != 0 { + t.Fatalf("wsl.exe asked with detection off: %q", asks) + } +} + +// #4872: agent's own wsl.exe runner (every list, probe, link and reach +// of a distro's) is refused at proc with detection off, past any gate of +// agent's that a path skips. +func TestWSLRunnerRefusedWhenOff(t *testing.T) { + t.Cleanup(func() { settings.Save(settings.Settings{}) }) + if err := settings.Save(settings.Settings{NoWSLAgents: true}); err != nil { + t.Fatal(err) + } + if _, err := wslRun(5*time.Second, "-l", "--running", "-q"); !errors.Is(err, proc.ErrWSLOff) { + t.Fatalf("detection off, wslRun ran wsl.exe: %v", err) + } + if _, err := wslExec("Debian", "true"); !errors.Is(err, proc.ErrWSLOff) { + t.Fatalf("detection off, wslExec ran wsl.exe: %v", err) + } +} diff --git a/internal/agent/wsl_test.go b/internal/agent/wsl_test.go index 43d7fd837..e3d5af108 100644 --- a/internal/agent/wsl_test.go +++ b/internal/agent/wsl_test.go @@ -182,12 +182,17 @@ func TestWSLAgentsElsewhere(t *testing.T) { // whose files were opened. func fakeWSL(t *testing.T, installed, running string, probes, roots map[string]string) (asked, opened *[]string) { t.Helper() + // the fake stands in for wsl.exe, so there is WSL to look in: the + // stand-in and classifier paths of a request are gated on wslLooks + // (#4872) and must run here as they do on Windows + on := wslOn + wslOn = true run, root := wslRun, wslRoot reset := func() { wsl.seen, wsl.at, wsl.runAt, wsl.names, wsl.running, wsl.dirty = nil, time.Time{}, time.Time{}, nil, nil, false wsl.runOK = false } - t.Cleanup(func() { wslRun, wslRoot = run, root; reset() }) + t.Cleanup(func() { wslRun, wslRoot, wslOn = run, root, on; reset() }) reset() asked, opened = &[]string{}, &[]string{} wslRun = func(_ time.Duration, args ...string) ([]byte, error) { diff --git a/internal/proc/proc.go b/internal/proc/proc.go index fa5273f80..7c050250a 100644 --- a/internal/proc/proc.go +++ b/internal/proc/proc.go @@ -23,6 +23,7 @@ import ( // Command is exec.Command, with no window of its own on Windows. func Command(name string, args ...string) *exec.Cmd { cmd := exec.Command(name, args...) + wslOff(cmd, name) batch(cmd) hide(cmd) return cmd @@ -32,6 +33,7 @@ func Command(name string, args ...string) *exec.Cmd { // Windows. func CommandContext(ctx context.Context, name string, args ...string) *exec.Cmd { cmd := exec.CommandContext(ctx, name, args...) + wslOff(cmd, name) // the context ending kills the command, but not what it started: a CLI // that is a script running node leaves node holding the output, and // Output waited for it however long it took (#123) — its pipes are diff --git a/internal/proc/wsl.go b/internal/proc/wsl.go new file mode 100644 index 000000000..21d2a5a81 --- /dev/null +++ b/internal/proc/wsl.go @@ -0,0 +1,32 @@ +package proc + +import ( + "errors" + "os/exec" + "strings" + + "github.com/yetone/magpie/internal/settings" +) + +// ErrWSLOff is what a wsl.exe start ends with, unrun, while Settings' +// Detect agents in WSL is off. +var ErrWSLOff = errors.New("not run: Detect agents in WSL is off in Settings") + +// wslOff refuses cmd when it is wsl.exe and Settings' Detect agents in WSL +// is off (#1264). Every command magpie starts is made here, so this is the +// one place that holds for all of them: a request's Claude Code stand-in +// and classifier asked wsl.exe which distros run past the gates in agent +// and wslrun, and on a computer without WSL Windows' own wsl.exe answers +// each ask with a console window offering to install it, one per request +// (#4872). +func wslOff(cmd *exec.Cmd, name string) { + if isWSL(name) && settings.Shared().NoWSLAgents { + cmd.Err = ErrWSLOff + } +} + +// isWSL is whether name is wsl.exe, by name or path, in any case. +func isWSL(name string) bool { + base := name[strings.LastIndexAny(name, `/\`)+1:] + return strings.EqualFold(base, "wsl.exe") || strings.EqualFold(base, "wsl") +} diff --git a/internal/proc/wsl_test.go b/internal/proc/wsl_test.go new file mode 100644 index 000000000..7fe3238e6 --- /dev/null +++ b/internal/proc/wsl_test.go @@ -0,0 +1,65 @@ +package proc + +import ( + "context" + "errors" + "os/exec" + "testing" + "time" + + "github.com/yetone/magpie/internal/settings" +) + +// #4872: with Settings' Detect agents in WSL off, nothing magpie makes +// starts wsl.exe, by any name or path: a request's stand-in asked it past +// agent's gates, and on a computer without WSL each ask put up a window +// offering to install it. +func TestWSLOffStartsNoWSL(t *testing.T) { + t.Cleanup(func() { settings.Save(settings.Settings{}) }) + names := []string{"wsl.exe", "WSL.EXE", "wsl", `C:\Windows\System32\wsl.exe`, "/mnt/c/Windows/System32/wsl.exe"} + // each is only started while it is refused: on, wsl.exe isn't run + makers := map[string]func(name string) *exec.Cmd{ + "Command": func(n string) *exec.Cmd { return Command(n, "-l", "--running", "-q") }, + "CommandContext": func(n string) *exec.Cmd { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + return CommandContext(ctx, n, "-l", "-q") + }, + "ProbeContext": func(n string) *exec.Cmd { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + return ProbeContext(ctx, n, "-l", "-q") + }, + } + + if err := settings.Save(settings.Settings{NoWSLAgents: true}); err != nil { + t.Fatal(err) + } + for how, mk := range makers { + for _, n := range names { + c := mk(n) + if !errors.Is(c.Err, ErrWSLOff) { + t.Errorf("detection off, %s(%q) wasn't refused: %v", how, n, c.Err) + continue + } + if _, err := c.Output(); !errors.Is(err, ErrWSLOff) || c.Process != nil { + t.Errorf("detection off, %s(%q) started: %v", how, n, err) + } + } + // only wsl.exe itself + for _, n := range []string{"wslconfig.exe", "notwsl.exe", `C:\wsl\git.exe`} { + if c := mk(n); errors.Is(c.Err, ErrWSLOff) { + t.Errorf("%s(%q) refused as wsl.exe", how, n) + } + } + } + + if err := settings.Save(settings.Settings{}); err != nil { + t.Fatal(err) + } + for how, mk := range makers { + if c := mk("wsl.exe"); errors.Is(c.Err, ErrWSLOff) { + t.Errorf("detection on, %s(wsl.exe) refused", how) + } + } +} diff --git a/internal/wslrun/wslrun_test.go b/internal/wslrun/wslrun_test.go index 8031bbc0c..5ab07c901 100644 --- a/internal/wslrun/wslrun_test.go +++ b/internal/wslrun/wslrun_test.go @@ -1,12 +1,15 @@ package wslrun import ( + "context" "errors" + "os/exec" "strings" "testing" "time" "unicode/utf16" + "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/settings" ) @@ -346,3 +349,23 @@ func TestFindWithDetectionOff(t *testing.T) { t.Fatalf("Find with detection on = %+v %v", tool, ok) } } + +// #4872: Run, and a Tool's commands (Claude Code in a distro, its +// pseudo-console helper's line), are refused at proc with detection off. +func TestRunRefusedWhenOff(t *testing.T) { + t.Cleanup(func() { settings.Save(settings.Settings{}) }) + if err := settings.Save(settings.Settings{NoWSLAgents: true}); err != nil { + t.Fatal(err) + } + if _, err := Run(5*time.Second, "-l", "--running", "-q"); !errors.Is(err, proc.ErrWSLOff) { + t.Fatalf("detection off, Run ran wsl.exe: %v", err) + } + tool := Tool{Distro: "Ubuntu", Path: "/home/me/.local/bin/claude", Mount: "/mnt/"} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + for _, c := range []*exec.Cmd{tool.Command(ctx, "-v"), tool.Probe(ctx, "-v")} { + if !errors.Is(c.Err, proc.ErrWSLOff) { + t.Fatalf("detection off, %q not refused: %v", c.Args, c.Err) + } + } +}