proc: with no WSL distro registered, or after wsl.exe asks to be updated, magpie starts no wsl.exe (TraderX219 on X)
TraderX219 on Windows: while magpie ran, a console window "WSL 必须更新到 最新版本……按任意键安装" came up every 20 to 30 seconds. magpie asked wsl.exe for its distros (the running list retries every 30s after a failure), and Windows' inbox wsl.exe answers each run on a computer without a current WSL package by starting `wsl.exe --update --confirm --prompt-before-exit` in a console of its own. proc.Command, CommandContext and ProbeContext are where every wsl.exe magpie runs is made (agent's wslRun/wslExec, wslrun, claudetui, the library's rtk and MCP checks, the gateway's TUI helper), so both gates sit in wslOff beside #1264's ErrWSLOff: - The registry is read first (HKCU\...\CurrentVersion\Lxss, one subkey with a DistributionName per distro). With the key there or gone and no distro in it, wsl.exe isn't started: ErrNoWSLDistro. agent's wslList and wslrun's running list read that as "no distros", not as a failure or a hang, so nothing is retried every 30s. It is read at every start, so a distro installed later is seen at once. A read that fails is unknown: wsl.exe is asked as before. - When a run's output (UTF-16LE or UTF-8, stdout and stderr) says WSL must be updated or installed, proc.WSLSaid writes settings' wsl-update mark (atomic, like wsl-hung) and no magpie process starts wsl.exe for 6h: ErrWSLNeedsUpdate. The mark holds the WSL package version (HKLM Lxss\MSI Version) and the registered distros; a change to either clears it. A refused listing is unknown, so wsl.seen, WSLKept values and links are kept, never removed. docs/subsystems/agent-wiring.md describes both. Run: - mote: gofmt -l (clean); go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...; go build for darwin, linux (nogui), windows: all ok. - mote: go test -count=1 of internal/proc, agent, wslrun, library, sessions, claudetui at base191f3c0af: all ok. - mote, full suite through suite.lock (go test -count=1 -timeout 45m ./...) at base191f3c0af: 88 packages ok, none failed. - xiaomi-gpu (Windows 11, win-run): go test -count=1 ./internal/agent/... ./internal/proc/... ./internal/wslrun/...: proc and wslrun ok; agent has 25 reds, the same 25 by name on untouched origin/main191f3c0af. 24 were filed (#4115, #4786, #5068 and others); TestCodexOwnModelsFollowPicks wasn't, now #5605. - xiaomi-gpu, read-only: TestWSLRegistryLive (MAGPIE_WSL_REGISTRY_LIVE=1) read the real Lxss key (magpie-fedora, Ubuntu, docker-desktop, magpie-3896, magpie-desktop; package 2.6.1.0) and ran `wsl.exe -l -q` (docker-desktop, magpie-fedora, Ubuntu, magpie-desktop): every listed distro is registered, so the gate never reads none while wsl.exe has some. magpie-3896 is registered in State 4 (uninstalling) and not listed, which only keeps wsl.exe being asked. No distro was stopped or changed. - At the pushed head (rebased onf13d5f16f, which touches gateway and provider only), mote: go test of proc, wslrun, provider ok. agent's TestWSLMoreAgentsPick failed with "no space left on device" (mote's data volume was at 100%). Rerun: -count=3 -run 'TestWSLMoreAgents|WSL' ./internal/agent/ ok, and -run History ./internal/gateway/ ok.abe7b0063(gateway) ande4fdf9ed3(gui) landed after that run and were rebased onto unrun; they touch no file this change does. Broken by hand, each red: - registry check off: TestNoWSLDistroStartsNoWSL ("wsl.exe wasn't refused") and TestNoWSLDistroRunsNoWSL ("no distro registered read as wsl.exe failing"). - WSLSaid left out of agent's wslRun: TestWSLUpdateKeepsDistros ("wsl.exe -l -q was started: exit status 1"). - wslList's ErrNoWSLDistro as listed: TestNoWSLDistroRunsNoWSL. - wslUpdateLately always false: TestWSLUpdateBacksOff ("wsl.exe run again after it asked for an update"). Not tried: - The stub's window itself: xiaomi-gpu has a current WSL and distros, so it doesn't pop there. The fix wasn't run on the reporter's machine. - The registry key missing (ErrNotExist) on a real Windows without WSL. - The stub's real exit code and stdout: the update text is matched from the inbox wsl.exe's .mui strings (en, zh-CN) and the reporter's words. - A wsl.exe that times out is not taken as asking for an update; the existing wsl-hung back-off still covers it.
This commit is contained in:
@@ -29,7 +29,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/<name>` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#<name>` on Windows, `omp#<name>@wsl:<distro>` 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, `<id>@wsl:<distro>`, edited through `\\wsl.localhost\<distro>`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). The probe runs `sh -l`, which reads `~/.profile` but not `~/.bashrc`, so a command off its PATH is looked for where Node's managers and installers keep one, as `proc.UserBinDirs` does here (`wslbin`): bun, `~/.local/bin`, volta, pnpm, nvm's default then the highest, fnm's default then the highest (`FNM_DIR`, `~/.local/share/fnm`, `~/.fnm`), mise's installs and shims, asdf, `~/.npmrc`'s prefix, cargo, deno and Homebrew (千里不再 on Discord: a Pi from fnm, not run yet so with no `~/.pi`, wasn't found). One on a Windows drive, which WSL's PATH reaches first when the distro's isn't on it, is looked past rather than taken as the only one (`wslcmd`, `wslwin`; `TestWSLProbeFindsNodeManagersBins`, `TestWSLProbeLooksPastWindowsCommand`). The shell isn't asked interactively for `~/.bashrc`'s PATH: under `timeout` such a bash stops itself on WSL and outlives the timeout. 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`, `-<agent>` 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 twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `<id>@wsl:<distro>`, edited through `\\wsl.localhost\<distro>`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). The probe runs `sh -l`, which reads `~/.profile` but not `~/.bashrc`, so a command off its PATH is looked for where Node's managers and installers keep one, as `proc.UserBinDirs` does here (`wslbin`): bun, `~/.local/bin`, volta, pnpm, nvm's default then the highest, fnm's default then the highest (`FNM_DIR`, `~/.local/share/fnm`, `~/.fnm`), mise's installs and shims, asdf, `~/.npmrc`'s prefix, cargo, deno and Homebrew (千里不再 on Discord: a Pi from fnm, not run yet so with no `~/.pi`, wasn't found). One on a Windows drive, which WSL's PATH reaches first when the distro's isn't on it, is looked past rather than taken as the only one (`wslcmd`, `wslwin`; `TestWSLProbeFindsNodeManagersBins`, `TestWSLProbeLooksPastWindowsCommand`). The shell isn't asked interactively for `~/.bashrc`'s PATH: under `timeout` such a bash stops itself on WSL and outlives the timeout. 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`, `-<agent>` 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`). With detection on, the same gate refuses wsl.exe with `proc.ErrNoWSLDistro` while the registry has no distro for the user (`HKCU\Software\Microsoft\Windows\CurrentVersion\Lxss`, a key with a `DistributionName` each, read at every start, so one installed later is listed at once; a read that fails is unknown and wsl.exe is asked as before), and agent's and wslrun's listings take that as none (TraderX219 on X: Windows' own wsl.exe without WSL's package put up its update console every 20 to 30 seconds). A failed run whose output says WSL must be installed or updated (`wsl.exe --update`, the inbox prompt, the optional component missing; `proc.WSLSaid`, told by agent's and wslrun's runners) writes `wsl-update` beside settings.json, and wsl.exe is then refused with `proc.ErrWSLNeedsUpdate` for six hours, by every magpie process, unless WSL's package version or the registered distros change; a refused listing is unknown, so nothing remembered of a distro is forgotten (`TestNoWSLDistroStartsNoWSL`, `TestWSLUpdateBacksOff`, `TestNoWSLDistroRunsNoWSL`, `TestWSLUpdateKeepsDistros`). | [`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/<user>/.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\<user>\.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`), each model's tokens weighed at what magpie bills them where the agent asked for a model magpie wrote (a provider/model id resolves as the gateway resolves it and is weighed at that provider's price, `pricedWeights`, so a Claude model on Copilot has its 1-hour cache write at the 5-minute one Copilot bills, #3435), else at its maker's list ratios (`tune.WeightsFor`); `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.<model>.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:<id>:<path>` (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) |
|
||||
|
||||
+12
-2
@@ -5,6 +5,7 @@ import (
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
@@ -1276,7 +1277,10 @@ var wslRun = func(timeout time.Duration, args ...string) ([]byte, error) {
|
||||
cmd := proc.CommandContext(ctx, "wsl.exe", args...)
|
||||
// wsl.exe speaks UTF-16 unless told otherwise; either is read
|
||||
cmd.Env = append(os.Environ(), "WSL_UTF8=1")
|
||||
return cmd.Output()
|
||||
out, err := cmd.Output()
|
||||
// one that says WSL must be updated isn't run again for hours
|
||||
proc.WSLSaid(out, err)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// wslRoot is where magpie opens a running distro's / from; a var for tests.
|
||||
@@ -1608,9 +1612,15 @@ func wslCodexStandIn() string {
|
||||
}
|
||||
|
||||
// wslList is the names wsl.exe lists with args; ok is false when it
|
||||
// couldn't say (no WSL, or none installed).
|
||||
// couldn't say (no WSL, or none installed). With no distro registered at
|
||||
// all wsl.exe isn't run (proc.ErrNoWSLDistro), and that is an answer:
|
||||
// none. One refused while WSL asks to be updated is not, so nothing
|
||||
// remembered of a distro is forgotten for it.
|
||||
func wslList(args ...string) (names []string, ok bool) {
|
||||
b, err := wslRun(10*time.Second, args...)
|
||||
if errors.Is(err, proc.ErrNoWSLDistro) {
|
||||
return nil, true
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/wslrun"
|
||||
)
|
||||
|
||||
// wslRealRuns has WSL on and agent's and wslrun's real wsl.exe runners
|
||||
// (testenv's failing stand-in on PATH) wrapped to note each run's arguments and
|
||||
// error; what magpie remembers of WSL starts empty.
|
||||
func wslRealRuns(t *testing.T) (runs func() map[string][]error) {
|
||||
t.Helper()
|
||||
syncHome(t)
|
||||
on, run, ron, rrun := wslOn, wslRun, wslrun.On, wslrun.Run
|
||||
var mu sync.Mutex
|
||||
got := map[string][]error{}
|
||||
wslOn, wslrun.On = true, true
|
||||
wslrun.Run = func(d time.Duration, args ...string) ([]byte, error) {
|
||||
out, err := rrun(d, args...)
|
||||
mu.Lock()
|
||||
k := "wslrun " + strings.Join(args, " ")
|
||||
got[k] = append(got[k], err)
|
||||
mu.Unlock()
|
||||
return out, err
|
||||
}
|
||||
wslRun = func(d time.Duration, args ...string) ([]byte, error) {
|
||||
out, err := run(d, args...)
|
||||
mu.Lock()
|
||||
k := strings.Join(args, " ")
|
||||
got[k] = append(got[k], err)
|
||||
mu.Unlock()
|
||||
return out, err
|
||||
}
|
||||
reset := func() {
|
||||
wsl.Lock()
|
||||
wsl.seen, wsl.at, wsl.runAt, wsl.names, wsl.running, wsl.probed, wsl.failed, wsl.dirty, wsl.listed, wsl.runOK = nil, time.Time{}, time.Time{}, nil, nil, nil, nil, false, false, false
|
||||
wsl.Unlock()
|
||||
}
|
||||
reset()
|
||||
t.Cleanup(func() { wslOn, wslRun, wslrun.On, wslrun.Run = on, run, ron, rrun; wslrun.Forget(); reset() })
|
||||
return func() map[string][]error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
out := map[string][]error{}
|
||||
for k, v := range got {
|
||||
out[k] = append([]error(nil), v...)
|
||||
}
|
||||
clear(got)
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
// TraderX219 on X: magpie on a Windows with no WSL distro put up Windows'
|
||||
// "WSL must be updated… press any key to install" console every 20 to 30
|
||||
// seconds, from wsl.exe -l --running. With none registered no listing,
|
||||
// running list, link or run in a distro starts wsl.exe, and the distros
|
||||
// read as none, an answer rather than a failure (no hang is noted). A
|
||||
// distro registered later is listed at the next listing.
|
||||
func TestNoWSLDistroRunsNoWSL(t *testing.T) {
|
||||
runs := wslRealRuns(t)
|
||||
restore := proc.FakeWSLRegistry(nil, true, "")
|
||||
defer func() { restore() }()
|
||||
|
||||
if ds := wslDistros(); len(ds) != 0 {
|
||||
t.Fatalf("no distro registered, read %+v", ds)
|
||||
}
|
||||
wsl.Lock()
|
||||
listed := wsl.listed
|
||||
wsl.runAt = time.Time{}
|
||||
wsl.Unlock()
|
||||
if !listed {
|
||||
t.Fatal("no distro registered read as wsl.exe failing")
|
||||
}
|
||||
if wslHungLately() {
|
||||
t.Fatal("no distro registered noted as a hung wsl.exe")
|
||||
}
|
||||
if wslUp("Ubuntu") {
|
||||
t.Fatal("a distro runs with none registered")
|
||||
}
|
||||
wslExec("Ubuntu", "true")
|
||||
if _, ok := wslReach("Ubuntu", "http://127.0.0.1:3425"); ok {
|
||||
t.Fatal("reached into a distro with none registered")
|
||||
}
|
||||
wslrun.Forget()
|
||||
if wslrun.Up("Ubuntu") {
|
||||
t.Fatal("wslrun: a distro runs with none registered")
|
||||
}
|
||||
got := runs()
|
||||
if len(got) == 0 {
|
||||
t.Fatal("nothing asked: the test tests nothing")
|
||||
}
|
||||
for args, errs := range got {
|
||||
for _, err := range errs {
|
||||
if !errors.Is(err, proc.ErrNoWSLDistro) {
|
||||
t.Errorf("no distro registered, wsl.exe %s was started: %v", args, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// installed later: the next listing asks wsl.exe
|
||||
restore()
|
||||
restore = proc.FakeWSLRegistry([]string{"Ubuntu"}, true, "")
|
||||
wsl.Lock()
|
||||
wsl.at = time.Time{}
|
||||
wsl.Unlock()
|
||||
wslDistros()
|
||||
if errs := runs()["-l -q"]; len(errs) == 0 || errors.Is(errs[0], proc.ErrNoWSLDistro) {
|
||||
t.Fatalf("a distro registered later wasn't listed: %v", errs)
|
||||
}
|
||||
}
|
||||
|
||||
// A wsl.exe that says WSL must be updated isn't asked again, and what
|
||||
// magpie remembers of a distro is kept while it isn't: its refusal is
|
||||
// unknown, not "no distro".
|
||||
func TestWSLUpdateKeepsDistros(t *testing.T) {
|
||||
runs := wslRealRuns(t)
|
||||
defer proc.FakeWSLRegistry([]string{"Ubuntu"}, true, "2.6.1.0")()
|
||||
wsl.Lock()
|
||||
wsl.seen = map[string]*distro{"Ubuntu": {Name: "Ubuntu", Home: "/home/me", Has: map[string]bool{"dir:.codex": true}, Probe: wslProbeVersion, Values: map[string]string{"k": "v"}}}
|
||||
wsl.probed, wsl.failed = map[string]bool{}, map[string]time.Time{}
|
||||
wsl.Unlock()
|
||||
|
||||
say := "Windows Subsystem for Linux must be updated to the latest version to proceed. You can update by running 'wsl.exe --update'."
|
||||
if runtime.GOOS == "windows" {
|
||||
// a script can't stand in for wsl.exe here (testenv's own stands
|
||||
// first, and isn't a program): proc is told as the runner tells it
|
||||
proc.WSLSaid([]byte(say), errors.New("exit status 1"))
|
||||
} else {
|
||||
// a wsl.exe that says so, as the inbox one does, before testenv's
|
||||
bin := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(bin, "wsl.exe"), []byte("#!/bin/sh\necho \""+say+"\"\nexit 1\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
}
|
||||
wslDistros()
|
||||
first := runs()
|
||||
if runtime.GOOS != "windows" && len(first["-l -q"]) != 1 {
|
||||
t.Fatalf("the first listing wasn't wsl.exe's: %v", first)
|
||||
}
|
||||
wsl.Lock()
|
||||
kept := wsl.seen["Ubuntu"] != nil
|
||||
wsl.at, wsl.runAt = time.Time{}, time.Time{}
|
||||
wsl.Unlock()
|
||||
if !kept {
|
||||
t.Fatal("a distro was forgotten while WSL asked to be updated")
|
||||
}
|
||||
if WSLKept("Ubuntu", "k") != "v" {
|
||||
t.Fatal("a distro's kept values were lost")
|
||||
}
|
||||
wslDistros()
|
||||
got := runs()
|
||||
if len(got) == 0 {
|
||||
t.Fatal("nothing asked: the test tests nothing")
|
||||
}
|
||||
for args, errs := range got {
|
||||
for _, err := range errs {
|
||||
if !errors.Is(err, proc.ErrWSLNeedsUpdate) {
|
||||
t.Errorf("WSL asked to be updated, wsl.exe %s was started: %v", args, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+175
-1
@@ -1,10 +1,19 @@
|
||||
package proc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
@@ -12,6 +21,18 @@ import (
|
||||
// Detect agents in WSL is off.
|
||||
var ErrWSLOff = errors.New("not run: Detect agents in WSL is off in Settings")
|
||||
|
||||
// ErrNoWSLDistro is what a wsl.exe start ends with, unrun, while Windows
|
||||
// has no WSL distro registered for this user: there is nothing it could
|
||||
// list or run, and on a computer without WSL's package Windows' own
|
||||
// wsl.exe answers each run with a console window of its own asking to
|
||||
// install it (TraderX219 on X: one every 20 to 30 seconds).
|
||||
var ErrNoWSLDistro = errors.New("not run: WSL has no distribution installed")
|
||||
|
||||
// ErrWSLNeedsUpdate is what a wsl.exe start ends with, unrun, for a while
|
||||
// after wsl.exe said WSL must be installed or updated (WSLSaid): each run
|
||||
// would put the same window up again.
|
||||
var ErrWSLNeedsUpdate = errors.New("not run: wsl.exe said lately that WSL must be updated (wsl.exe --update)")
|
||||
|
||||
// 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
|
||||
@@ -19,9 +40,25 @@ var ErrWSLOff = errors.New("not run: Detect agents in WSL is off in Settings")
|
||||
// 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).
|
||||
//
|
||||
// For the same window it is refused with detection on too: while the
|
||||
// registry says no distro is registered (wslRegistered), and for
|
||||
// wslUpdateAge after wsl.exe said WSL must be updated (WSLSaid).
|
||||
func wslOff(cmd *exec.Cmd, name string) {
|
||||
if isWSL(name) && settings.Shared().NoWSLAgents {
|
||||
if !isWSL(name) {
|
||||
return
|
||||
}
|
||||
if settings.Shared().NoWSLAgents {
|
||||
cmd.Err = ErrWSLOff
|
||||
return
|
||||
}
|
||||
names, ok := wslRegistered()
|
||||
if ok && len(names) == 0 {
|
||||
cmd.Err = ErrNoWSLDistro
|
||||
return
|
||||
}
|
||||
if wslUpdateLately(names, ok) {
|
||||
cmd.Err = ErrWSLNeedsUpdate
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,3 +67,140 @@ func isWSL(name string) bool {
|
||||
base := name[strings.LastIndexAny(name, `/\`)+1:]
|
||||
return strings.EqualFold(base, "wsl.exe") || strings.EqualFold(base, "wsl")
|
||||
}
|
||||
|
||||
// wslRegistered is the WSL distros registered for this user, as the
|
||||
// registry has them (HKCU\Software\Microsoft\Windows\CurrentVersion\Lxss,
|
||||
// a key with a DistributionName for each), read without running wsl.exe;
|
||||
// ok is false when that can't be told (off Windows, or a read failed), and
|
||||
// wsl.exe is asked as before. It is read at every start, which costs
|
||||
// little beside wsl.exe's own: a distro installed later is seen at once.
|
||||
// A var for tests.
|
||||
var wslRegistered = registeredDistros
|
||||
|
||||
// wslPackage is the installed WSL package's version, as its installer
|
||||
// registered it (HKLM's Lxss\MSI Version), "" for none or unknown. A var
|
||||
// for tests.
|
||||
var wslPackage = wslPackageVersion
|
||||
|
||||
// wslUpdateAge is how long wsl.exe isn't run again after it said WSL must
|
||||
// be updated, unless WSL changes meanwhile (wslSig).
|
||||
const wslUpdateAge = 6 * time.Hour
|
||||
|
||||
// wslUpdatePath, while recent, says wsl.exe answered that WSL must be
|
||||
// installed or updated: every magpie process (the app, a CLI, the Claude
|
||||
// Code helper) reads it.
|
||||
func wslUpdatePath() string { return filepath.Join(settings.Dir(), "wsl-update") }
|
||||
|
||||
type wslUpdateMark struct {
|
||||
At time.Time `json:"at"`
|
||||
Sig string `json:"sig"`
|
||||
}
|
||||
|
||||
// wslSig is what the update mark holds of WSL, so that a change to it (the
|
||||
// package updated or installed, a distro added or removed) has wsl.exe
|
||||
// asked again at once rather than wslUpdateAge on. "" when the distros
|
||||
// can't be read: such a mark stands its whole age.
|
||||
func wslSig(names []string, ok bool) string {
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
names = slices.Clone(names)
|
||||
slices.Sort(names)
|
||||
return wslPackage() + "|" + strings.Join(names, "\n")
|
||||
}
|
||||
|
||||
func wslUpdateLately(names []string, ok bool) bool {
|
||||
b, err := os.ReadFile(wslUpdatePath())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
var m wslUpdateMark
|
||||
// a mark that doesn't parse isn't one: wsl.exe is asked, and says again
|
||||
if json.Unmarshal(b, &m) != nil || m.At.IsZero() {
|
||||
return false
|
||||
}
|
||||
if age := time.Since(m.At); age < 0 || age >= wslUpdateAge {
|
||||
return false
|
||||
}
|
||||
return m.Sig == "" || !ok || m.Sig == wslSig(names, ok)
|
||||
}
|
||||
|
||||
// WSLSaid is told what a wsl.exe run printed and how it ended. When that
|
||||
// says WSL must be installed or updated, wsl.exe isn't run again for
|
||||
// wslUpdateAge (wslOff), by any magpie process, unless WSL changes. Every
|
||||
// runner of magpie's that reads wsl.exe's output tells it.
|
||||
func WSLSaid(out []byte, err error) {
|
||||
if !wslWantsUpdate(out, err) {
|
||||
return
|
||||
}
|
||||
names, ok := wslRegistered()
|
||||
b, _ := json.Marshal(wslUpdateMark{At: time.Now().UTC(), Sig: wslSig(names, ok)})
|
||||
if edit.WriteAtomic(wslUpdatePath(), b) == nil {
|
||||
log.Printf("wsl.exe says WSL must be updated or installed (%s): not run again for %s, or until WSL changes", firstLine(wslText(out, err)), wslUpdateAge)
|
||||
}
|
||||
}
|
||||
|
||||
// wslUpdateSays are what wsl.exe prints when it can't run until WSL is
|
||||
// installed or updated, in any language: the commands it names stay in
|
||||
// English (Locked in WSL's own strings), as do its error codes. The inbox
|
||||
// wsl.exe's own prompt is in its .mui (English and Chinese below), and the
|
||||
// last is the reporter's.
|
||||
var wslUpdateSays = []string{
|
||||
"wsl.exe --update", "wsl --update", "--prompt-before-exit",
|
||||
"--install --no-distribution", // the optional component is missing
|
||||
"WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED",
|
||||
"Press any key to install Windows Subsystem for Linux",
|
||||
"按任意键安装适用于 Linux 的 Windows 子系统",
|
||||
"必须更新到最新版本",
|
||||
}
|
||||
|
||||
// wslWantsUpdate is whether a wsl.exe run that failed said WSL must be
|
||||
// installed or updated. One that succeeded is never taken so, whatever it
|
||||
// printed: a distro's own output may name those commands.
|
||||
func wslWantsUpdate(out []byte, err error) bool {
|
||||
if err == nil || errors.Is(err, ErrWSLOff) || errors.Is(err, ErrNoWSLDistro) || errors.Is(err, ErrWSLNeedsUpdate) {
|
||||
return false
|
||||
}
|
||||
s := strings.ToLower(wslText(out, err))
|
||||
for _, w := range wslUpdateSays {
|
||||
if strings.Contains(s, strings.ToLower(w)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// wslText is what a wsl.exe run wrote, stdout and stderr, UTF-16LE (as
|
||||
// wsl.exe writes unless WSL_UTF8 is set, which the inbox one may not
|
||||
// read) or UTF-8.
|
||||
func wslText(out []byte, err error) string {
|
||||
var ee *exec.ExitError
|
||||
if errors.As(err, &ee) {
|
||||
return decodeWSL(out) + "\n" + decodeWSL(ee.Stderr)
|
||||
}
|
||||
return decodeWSL(out)
|
||||
}
|
||||
|
||||
func decodeWSL(b []byte) string {
|
||||
// UTF-8 text has no NUL: one says UTF-16
|
||||
if !bytes.HasPrefix(b, []byte{0xff, 0xfe}) && bytes.IndexByte(b, 0) < 0 {
|
||||
return string(b)
|
||||
}
|
||||
b = bytes.TrimPrefix(b, []byte{0xff, 0xfe})
|
||||
u := make([]uint16, len(b)/2)
|
||||
for i := range u {
|
||||
u[i] = uint16(b[2*i]) | uint16(b[2*i+1])<<8
|
||||
}
|
||||
return string(utf16.Decode(u))
|
||||
}
|
||||
|
||||
func firstLine(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if i := strings.IndexAny(s, "\r\n"); i >= 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
if len(s) > 200 {
|
||||
s = s[:200]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package proc
|
||||
|
||||
// FakeWSLRegistry, for tests, has the registry read as listing names for
|
||||
// the WSL distros registered (ok false: it can't be read) and pkg as WSL's
|
||||
// package version; the returned func puts the real reads back.
|
||||
func FakeWSLRegistry(names []string, ok bool, pkg string) func() {
|
||||
reg, p := wslRegistered, wslPackage
|
||||
wslRegistered = func() ([]string, bool) { return names, ok }
|
||||
wslPackage = func() string { return pkg }
|
||||
return func() { wslRegistered, wslPackage = reg, p }
|
||||
}
|
||||
@@ -2,10 +2,13 @@ package proc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
@@ -16,6 +19,8 @@ import (
|
||||
// offering to install it.
|
||||
func TestWSLOffStartsNoWSL(t *testing.T) {
|
||||
t.Cleanup(func() { settings.Save(settings.Settings{}) })
|
||||
// a distro registered: only the setting refuses it
|
||||
defer FakeWSLRegistry([]string{"Ubuntu"}, true, "")()
|
||||
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{
|
||||
@@ -63,3 +68,127 @@ func TestWSLOffStartsNoWSL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TraderX219 on X: with no WSL distro registered, nothing magpie makes
|
||||
// starts wsl.exe, which on a computer without WSL's package put up a
|
||||
// console window asking to install it every 20 to 30 seconds. The registry
|
||||
// that can't be read, or that has a distro, starts it as before, and a
|
||||
// distro registered later is run at once.
|
||||
func TestNoWSLDistroStartsNoWSL(t *testing.T) {
|
||||
defer FakeWSLRegistry(nil, true, "")()
|
||||
for _, n := range []string{"wsl.exe", "WSL.EXE", `C:\Windows\System32\wsl.exe`} {
|
||||
c := Command(n, "-l", "--running", "-q")
|
||||
if !errors.Is(c.Err, ErrNoWSLDistro) {
|
||||
t.Fatalf("no distro, %q wasn't refused: %v", n, c.Err)
|
||||
}
|
||||
if _, err := c.Output(); !errors.Is(err, ErrNoWSLDistro) || c.Process != nil {
|
||||
t.Fatalf("no distro, %q started: %v", n, err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
if c := ProbeContext(ctx, n, "-l", "-q"); !errors.Is(c.Err, ErrNoWSLDistro) {
|
||||
t.Fatalf("no distro, probe of %q wasn't refused: %v", n, c.Err)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
if c := Command("git", "version"); c.Err != nil {
|
||||
t.Fatalf("git refused: %v", c.Err)
|
||||
}
|
||||
|
||||
defer FakeWSLRegistry(nil, false, "")()
|
||||
if c := Command("wsl.exe", "-l", "-q"); c.Err != nil {
|
||||
t.Fatalf("registry unread, wsl.exe refused: %v", c.Err)
|
||||
}
|
||||
defer FakeWSLRegistry([]string{"Ubuntu"}, true, "")()
|
||||
if c := Command("wsl.exe", "-l", "-q"); c.Err != nil {
|
||||
t.Fatalf("a distro registered, wsl.exe refused: %v", c.Err)
|
||||
}
|
||||
}
|
||||
|
||||
func utf16le(s string) []byte {
|
||||
var b []byte
|
||||
for _, r := range utf16.Encode([]rune(s)) {
|
||||
b = append(b, byte(r), byte(r>>8))
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// A wsl.exe that says WSL must be updated isn't run again for hours, by
|
||||
// any route, unless WSL's package or distros change; a failure that says
|
||||
// something else, or a run that succeeded, holds nothing back.
|
||||
func TestWSLUpdateBacksOff(t *testing.T) {
|
||||
t.Cleanup(func() { os.Remove(wslUpdatePath()) })
|
||||
defer FakeWSLRegistry([]string{"Ubuntu"}, true, "2.6.1.0")()
|
||||
refused := func() bool {
|
||||
return errors.Is(Command("wsl.exe", "-l", "--running", "-q").Err, ErrWSLNeedsUpdate)
|
||||
}
|
||||
fail := errors.New("exit status 1")
|
||||
|
||||
// what doesn't ask for an update
|
||||
WSLSaid([]byte("run wsl.exe --update yourself\n"), nil)
|
||||
WSLSaid(utf16le("There is no distribution with the supplied name.\r\nError code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n"), fail)
|
||||
WSLSaid(nil, ErrNoWSLDistro)
|
||||
if refused() {
|
||||
t.Fatal("refused after runs that didn't ask for an update")
|
||||
}
|
||||
|
||||
says := map[string][]byte{
|
||||
"utf-16": utf16le("Windows Subsystem for Linux must be updated to the latest version to proceed. You can update by running 'wsl.exe --update'.\r\n"),
|
||||
// the reporter's words, as the screenshot has them
|
||||
"chinese": utf16le("\ufeffWSL 必须更新到最新版本……按任意键安装\r\n"),
|
||||
"prompt": []byte("\r\n按任意键安装适用于 Linux 的 Windows 子系统。\r\n按 CTRL-C 或关闭此窗口以取消。\r\n"),
|
||||
"stderr": nil,
|
||||
}
|
||||
for name, out := range says {
|
||||
os.Remove(wslUpdatePath())
|
||||
err := fail
|
||||
if out == nil {
|
||||
err = &exec.ExitError{Stderr: []byte("This application requires the Windows Subsystem for Linux Optional Component.\nInstall it by running: wsl.exe --install --no-distribution\n")}
|
||||
}
|
||||
WSLSaid(out, err)
|
||||
if !refused() {
|
||||
t.Fatalf("%s: wsl.exe run again after it asked for an update", name)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
if c := CommandContext(ctx, "wsl.exe", "-d", "Ubuntu", "-e", "true"); !errors.Is(c.Err, ErrWSLNeedsUpdate) {
|
||||
t.Fatalf("%s: a run in a distro wasn't refused: %v", name, c.Err)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
|
||||
// the package updated, or a distro added: asked again at once
|
||||
restore := FakeWSLRegistry([]string{"Ubuntu"}, true, "2.6.2.0")
|
||||
if refused() {
|
||||
t.Fatal("refused after WSL's package changed")
|
||||
}
|
||||
restore()
|
||||
restore = FakeWSLRegistry([]string{"Ubuntu", "Debian"}, true, "2.6.1.0")
|
||||
if refused() {
|
||||
t.Fatal("refused after a distro was added")
|
||||
}
|
||||
restore()
|
||||
if !refused() {
|
||||
t.Fatal("not refused for WSL as it was")
|
||||
}
|
||||
// the registry unread: the mark stands
|
||||
restore = FakeWSLRegistry(nil, false, "")
|
||||
if !refused() {
|
||||
t.Fatal("registry unread, the mark didn't stand")
|
||||
}
|
||||
restore()
|
||||
|
||||
// its age runs out
|
||||
b, _ := json.Marshal(wslUpdateMark{At: time.Now().Add(-wslUpdateAge - time.Minute), Sig: wslSig([]string{"Ubuntu"}, true)})
|
||||
if err := os.WriteFile(wslUpdatePath(), b, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if refused() {
|
||||
t.Fatal("refused past wslUpdateAge")
|
||||
}
|
||||
// a mark that doesn't parse isn't one
|
||||
if err := os.WriteFile(wslUpdatePath(), []byte("{"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if refused() {
|
||||
t.Fatal("refused for a mark that doesn't parse")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !windows
|
||||
|
||||
package proc
|
||||
|
||||
// registeredDistros can't be told off Windows: there is no WSL here, and
|
||||
// a test's wsl.exe is its own.
|
||||
func registeredDistros() ([]string, bool) { return nil, false }
|
||||
|
||||
func wslPackageVersion() string { return "" }
|
||||
@@ -0,0 +1,59 @@
|
||||
package proc
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
const lxss = `Software\Microsoft\Windows\CurrentVersion\Lxss`
|
||||
|
||||
// registeredDistros reads HKCU's Lxss key, where WSL registers each of the
|
||||
// user's distros as a key with its DistributionName. No key at all is no
|
||||
// distro; any other failure, or a distro's key that can't be read, is
|
||||
// unknown.
|
||||
func registeredDistros() ([]string, bool) {
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, lxss, registry.ENUMERATE_SUB_KEYS)
|
||||
if errors.Is(err, registry.ErrNotExist) {
|
||||
return nil, true
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
defer k.Close()
|
||||
ids, err := k.ReadSubKeyNames(-1)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
var names []string
|
||||
for _, id := range ids {
|
||||
d, err := registry.OpenKey(k, id, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
n, _, err := d.GetStringValue("DistributionName")
|
||||
d.Close()
|
||||
switch {
|
||||
case errors.Is(err, registry.ErrNotExist):
|
||||
// a key that isn't a distro's (WSL keeps others here, e.g. MSI
|
||||
// on some versions)
|
||||
case err != nil:
|
||||
return nil, false
|
||||
case n != "":
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
return names, true
|
||||
}
|
||||
|
||||
// wslPackageVersion is the WSL package's version, as its installer
|
||||
// registered it.
|
||||
func wslPackageVersion() string {
|
||||
k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows\CurrentVersion\Lxss\MSI`, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer k.Close()
|
||||
v, _, _ := k.GetStringValue("Version")
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package proc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// On a real Windows with WSL (MAGPIE_WSL_REGISTRY_LIVE set): every distro
|
||||
// wsl.exe -l -q lists (which reads and starts nothing) is one the registry
|
||||
// has, so the gate never reads none while wsl.exe has some. The registry
|
||||
// may have more: a distro being installed or uninstalled (its State), which
|
||||
// wsl.exe leaves out, keeps wsl.exe asked.
|
||||
func TestWSLRegistryLive(t *testing.T) {
|
||||
if os.Getenv("MAGPIE_WSL_REGISTRY_LIVE") == "" {
|
||||
t.Skip("MAGPIE_WSL_REGISTRY_LIVE not set")
|
||||
}
|
||||
names, ok := registeredDistros()
|
||||
if !ok {
|
||||
t.Fatal("the registry couldn't be read")
|
||||
}
|
||||
t.Logf("registered: %q, package %q", names, wslPackageVersion())
|
||||
// the real wsl.exe, not testenv's stand-in, and not through Command
|
||||
cmd := exec.Command(filepath.Join(os.Getenv("SystemRoot"), "System32", "wsl.exe"), "-l", "-q")
|
||||
cmd.Env = append(os.Environ(), "WSL_UTF8=1")
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
t.Fatalf("wsl.exe -l -q: %v", err)
|
||||
}
|
||||
var listed []string
|
||||
for _, l := range strings.Split(decodeWSL(out), "\n") {
|
||||
if l = strings.TrimSpace(l); l != "" {
|
||||
listed = append(listed, l)
|
||||
}
|
||||
}
|
||||
if len(listed) == 0 {
|
||||
t.Fatal("wsl.exe lists no distro: nothing to compare")
|
||||
}
|
||||
for _, n := range listed {
|
||||
if !slices.Contains(names, n) {
|
||||
t.Errorf("wsl.exe lists %q, the registry hasn't it (%q)", n, names)
|
||||
}
|
||||
}
|
||||
t.Logf("wsl.exe lists %q", listed)
|
||||
if wslPackageVersion() == "" {
|
||||
t.Fatal("no WSL package version read")
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,10 @@ var Run = func(timeout time.Duration, args ...string) ([]byte, error) {
|
||||
defer cancel()
|
||||
cmd := proc.CommandContext(ctx, "wsl.exe", args...)
|
||||
cmd.Env = append(os.Environ(), "WSL_UTF8=1")
|
||||
return cmd.Output()
|
||||
out, err := cmd.Output()
|
||||
// one that says WSL must be updated isn't run again for hours
|
||||
proc.WSLSaid(out, err)
|
||||
return out, err
|
||||
}
|
||||
|
||||
var found struct {
|
||||
@@ -203,7 +206,8 @@ func running() (names []string, ok bool) {
|
||||
}
|
||||
if up.at.IsZero() || time.Since(up.at) > age {
|
||||
b, err := Run(10*time.Second, "-l", "--running", "-q")
|
||||
up.names, up.ok, up.at = Distros(b), err == nil, time.Now()
|
||||
// no distro registered at all is an answer: none runs
|
||||
up.names, up.ok, up.at = Distros(b), err == nil || errors.Is(err, proc.ErrNoWSLDistro), time.Now()
|
||||
if err != nil {
|
||||
up.names = nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user