proc: magpie on Windows finds fnm's node and npx (#2685)
What changed
- fnm puts its Node on a terminal's PATH from the shell profile
(`fnm env | Invoke-Expression`), never in the registry, so magpie
started from the Start menu had no node: a Library MCP server run by
bare npx was "notfound", and one run by npx.cmd's full path (the
reporter's C:\Users\...\fnm\aliases\default\npx.cmd, alone or under
`cmd /c`) exited 1 with cmd's "'node' is not recognized", since the
package npx fetched runs node by name.
- Windows UserPath (no-op before) adds the folder fnm's default alias
names, after what PATH has. UserBinDirs (FindTool) gets each fnm
Node: the default alias first, then installations newest by number.
- fnm's Windows layout, checked against Schniz/fnm master (config.rs,
directories.rs, version.rs, fs.rs, commands/env.rs): root FNM_DIR,
else etcetera's Windows data_dir\fnm (home\AppData\Roaming, APPDATA),
else legacy ~\.fnm; versions in node-versions\<v>\installation with
node.exe/npx.cmd directly in it (no bin on Windows); aliases\default
a junction to an installation folder; the "system" alias points at
Z:\_fnm_\..., read as none. XDG vars on Windows only move fnm's
multishell links, not its versions. LOCALAPPDATA isn't used for them.
- The shared node-version helpers (nodeVersions, parseNodeVersion,
nodeVersionLess, isDir) and addPath moved from the !windows files to
nodever.go unchanged; fnmWin* there take home/APPDATA/FNM_DIR as
arguments so the tests run them on every OS.
- The Library check (checkStdioAt, this machine only) starts a bare
command PATH lacks from where proc.FindTool finds it and puts that
folder on the child's PATH (stdioProgram, withPath), as the owner's
plan on the issue said. Docs: agent-wiring.md, library.md.
Run
- macOS: go test -count=1 ./internal/proc/ ./internal/library/ ok
(TestNoCommandBypassesProc and the other proc guards included);
gofmt -l clean; go vet GOOS=windows/darwin for proc, library, cli,
daemon; GOOS=linux vet proc, library and (-tags nogui) cli, daemon;
GOOS=windows test binaries for proc and library build.
- Windows box (Win 11 x64), cross-compiled amd64 test binaries:
TestUserPathFnmNode (real junction via mklink /J, npx.cmd that runs
node by name) red on origin/main 4a1cd7765's code ("PATH after
UserPath = [C:\windows\System32], want fnm's default alias"), green
here; TestFnmWin* green.
- Real fnm 1.39.0 + Node v24.22.1 installed into a sandbox
(USERPROFILE/APPDATA under C:\Users\yeton\fnm-2685, no FNM_DIR,
registry PATH without node). A throwaway probe calling UserPath then
library.CheckServer on chrome-devtools-mcp@latest:
4a1cd7765: npx -> notfound; ...\aliases\default\npx.cmd -> exited 1;
cmd /c ...npx.cmd -> exited 1 (the reporter's case).
This commit: all three ok, 32 tools.
- Broken by hand: stdioProgram without FindTool ->
TestStdioProgramFindsWhatPathLacks red; fnmWinBins without the
default alias -> TestFnmWinBins red; Windows UserPath as before ->
TestUserPathFnmNode red (above).
- Windows full proc/library binaries: TestNoCommandBypassesProc,
TestGoneAgentListedToTakeOut, TestCheckMixedServerEachSide,
TestCheckKeepsToolNames and TestRTKNoHookIssuesAreEachAgents fail
the same with 4a1cd7765's binaries run the same way; the guard and
two of them read the source tree, which a binary run outside a
checkout doesn't have; the other two are in #1827.
Not tried
- The desktop GUI on Windows with the reporter's fnm (the probe runs
the same UserPath and CheckServer calls the app does).
- magpie serve/web/tui on Windows don't call UserPath (as on macOS), so
there an absolute npx.cmd still lacks node on PATH; a bare npx is
covered by the check's FindTool.
- Agents magpie starts get the new PATH only from the GUI/daemon.
Refs #2685
Co-authored-by: Edward4226 <234070868+Edward4226@users.noreply.github.com>
This commit is contained in:
@@ -121,7 +121,7 @@ something else shows up as drift.
|
||||
- MothX's folder is `$MOTHX_DIR` as it is (no `~`), else `%APPDATA%\mothx` on Windows, else `~/.mothx`; a WSL distro's is its `~/.mothx` ([`mothx.go`](../../internal/agent/mothx.go)). Its `thinkingFormat` is `openai` unless the user set one: with it empty, MothX picks Qwen's `enable_thinking`, DeepSeek's `thinking` or Doubao's levels by the model id, which for magpie's ids says nothing of the vendor that serves them. MothX's `/model` and `/statusline … global` rewrite the whole file, so Disconnect after one takes out magpie's provider, the pick and a `providers` left empty (MothX omits an empty one), and keeps the rest.
|
||||
- PenguinHarness's file is `$PENGUIN_HOME` (else `~/.penguin/data`, on Windows too) `/<project>/.project_config.toml`, the Project `$PENGUIN_PROJECT_ID` when it is a folder's name (`agentenv.NotPaths`, so a relative name isn't dropped as a path), else `default_project`; a WSL distro's is its `~/.penguin/data/default_project` ([`penguin.go`](../../internal/agent/penguin.go)). Magpie's models are `[[models]]` array entries with `provider = "magpie"`, replaced together where the first one was by `edit.SetTOMLArrayTables`, which leaves the user's entries, the blank lines between them and the file's time alone when nothing changed (Penguin's server reads the file again on every mtime change). `default_model` is spelled `{ provider = …, model_id = … }` as Penguin's own writer (smol-toml) spells it; that writer rewrites the whole file, so Disconnect takes out magpie's provider, entries and a vision model on them rather than putting back a copy. A default naming no entry is refused by Penguin, so entries go in before `default_model` and out after it.
|
||||
- Zoo Code's provider profiles are in VS Code's secret storage, so magpie writes a settings file for it (`magpie-import.json` in Zoo Code's `globalStorage/zoocodeorganization.zoo-code/settings`, not magpie's folder, so a sync keeps an address the user moved it to) and points Zoo Code's `zoo-code.autoImportSettingsPath` at it in VS Code's `settings.json` and each profile's, a user's own path stashed and put back ([`zoocode.go`](../../internal/agent/zoocode.go)). Zoo Code imports it on each start (`importSettingsFromPath`), merging it over the user's profiles and making `magpie` the current one. Disconnect stops the import and deletes the file; the profile already imported stays in Zoo Code, where magpie can't reach it.
|
||||
- An agent is detected by its config file, its folder, or its command on magpie's PATH (`Detected`). That PATH is the login shell's plus the folders users' tools go in (`proc.UserPath`: `~/.local/bin`, npm's prefixes, the Node nvm's default alias resolves to (the highest installed when it names none), bun, Homebrew, ...), so a CLI a terminal doesn't find can still be found and listed: an npm install under a Node the terminal no longer uses. `/api/agents/cli` then gives where it is (`path`) and `offPath` when the login shell's PATH (`proc.LoginPath`) lacks its folder, and the Agents row says "Not on your terminal's PATH", its tip naming the file (悠悠哥 on Discord: Codex 0.162.1 listed with no codex on PATH and no `~/.codex`). An unknown login PATH says nothing. A folder another tool writes too doesn't count (`dirShared`): Pi's for omp, `~/.copilot` for the Copilot CLI, which GitHub Copilot's JetBrains and VS Code plugins also write, and Qoder's and Qoder CN's, which Qoder's JetBrains plugin fills, and `~/.cursor` for Cursor CLI, which the Cursor editor makes on its own (`TestCursorFolderFromTheEditorIsNotTheCLI`, @G_Z_Y on X); only `cli-config.json` or `cursor-agent` finds Cursor CLI. A config file another tool writes first counts only when `pathOwn` says it is the agent's: Qoder's `settings.json` holding `enabledPlugins` alone is the plugin's (`qoderPluginOnly`; #1495, `TestCopilotFolderFromAnIDEPluginIsNotTheCLI`, `TestQoderSettingsFromAnIDEPluginIsNotTheCLI`). The Qoder app (the desktop app, which runs Qoder's CLI as its agent with the same folder) is found by the `.qoder-app-status.json` it writes there (`sign`, `qoderApp`; #2138, `TestQoderAppIsQoder`), as its `settings.json` can be its bundled plugin's `enabledPlugins` alone. Only the GUI and `daemon install` widen the PATH so; `magpie serve`, `web`, `tui` and the CLI keep the one they were started with, so an agent's CLI (`cliBin`, which its version and `omp`'s max effort are read from) is looked for in those folders (`proc.FindTool`) on every system when it isn't on the PATH, not only on Windows (whqtian on Discord: omp under `~/.bun/bin` on Ubuntu read as no version and offered xhigh in place of max; `TestOmpVersionOffPath`).
|
||||
- An agent is detected by its config file, its folder, or its command on magpie's PATH (`Detected`). That PATH is the login shell's plus the folders users' tools go in (`proc.UserPath`: `~/.local/bin`, npm's prefixes, the Node nvm's default alias resolves to (the highest installed when it names none), bun, Homebrew, ...; on Windows the registry's PATH plus the Node fnm's default alias names, `%APPDATA%\fnm\aliases\default` or under `FNM_DIR`, which fnm puts on a terminal's PATH from the shell profile and never in the registry, #2685), so a CLI a terminal doesn't find can still be found and listed: an npm install under a Node the terminal no longer uses. `/api/agents/cli` then gives where it is (`path`) and `offPath` when the login shell's PATH (`proc.LoginPath`) lacks its folder, and the Agents row says "Not on your terminal's PATH", its tip naming the file (悠悠哥 on Discord: Codex 0.162.1 listed with no codex on PATH and no `~/.codex`). An unknown login PATH says nothing. A folder another tool writes too doesn't count (`dirShared`): Pi's for omp, `~/.copilot` for the Copilot CLI, which GitHub Copilot's JetBrains and VS Code plugins also write, and Qoder's and Qoder CN's, which Qoder's JetBrains plugin fills, and `~/.cursor` for Cursor CLI, which the Cursor editor makes on its own (`TestCursorFolderFromTheEditorIsNotTheCLI`, @G_Z_Y on X); only `cli-config.json` or `cursor-agent` finds Cursor CLI. A config file another tool writes first counts only when `pathOwn` says it is the agent's: Qoder's `settings.json` holding `enabledPlugins` alone is the plugin's (`qoderPluginOnly`; #1495, `TestCopilotFolderFromAnIDEPluginIsNotTheCLI`, `TestQoderSettingsFromAnIDEPluginIsNotTheCLI`). The Qoder app (the desktop app, which runs Qoder's CLI as its agent with the same folder) is found by the `.qoder-app-status.json` it writes there (`sign`, `qoderApp`; #2138, `TestQoderAppIsQoder`), as its `settings.json` can be its bundled plugin's `enabledPlugins` alone. Only the GUI and `daemon install` widen the PATH so; `magpie serve`, `web`, `tui` and the CLI keep the one they were started with, so an agent's CLI (`cliBin`, which its version and `omp`'s max effort are read from) is looked for in those folders (`proc.FindTool`) on every system when it isn't on the PATH, not only on Windows (whqtian on Discord: omp under `~/.bun/bin` on Ubuntu read as no version and offered xhigh in place of max; `TestOmpVersionOffPath`).
|
||||
- Detection goes by an agent's folder, which an uninstall leaves behind, so an agent found by that alone is shown as gone (`CLIMissing`; #843, #2177, #2173): its CLI is on no PATH and in none of `proc.FindTool`'s folders nor where its own installer puts it (`~/.claude/local`, `~/.codex/packages/standalone`, `~/.opencode/bin`, Hermes' `hermes-agent` checkout), and nothing else that reads the folder is here (`cliHeld`): its desktop app (`HasApp`), an editor's extension (`~/.<editor>/extensions/<id>-*`: `anthropic.claude-code`, `openai.chatgpt`, `saoudrizwan.claude-dev`), Claude.app, OpenCode.app and Goose.app on a Mac, a JetBrains IDE's settings (its AI Assistant's agents and Cline's plugin) or Zed's `external_agents` (its Claude Code and Codex adapters). Where magpie can't tell (every shared folder, `cliShared`, on Windows, whose readers can be a Store app, a portable editor or a PATH only a shell profile sets, #1482, and there too one a desktop app of the agent's reads, `desktopApps`: DeepSeek Harness Desktop installs to any folder and puts its `dsh.cmd` in one the user picks, #2300, #2304; OpenCode and Goose off a Mac, Gemini, an agent detected its own way or by a command name other tools share, one with no install command but `cliOnly`'s Hermes), it is never gone. A gone row in the GUI shows "CLI not found" and none of its settings, nor Apply again; while connected it keeps its switch and Disconnect, and it folds under Not set up once not. Get started never offers it (`connectKind` is "no"). The TUI leaves it out and `magpie ls` says "CLI not found" (`TestCLIMissing*`, `agent-cli-missing.test.cjs`, `getting-started.test.cjs`).
|
||||
- Tests never touch the real machine. `TestMain` uses `testenv`, which points HOME, USERPROFILE, the XDG folders and APPDATA into a temporary folder, clears `agentenv.Vars` and puts failing stand-ins for keychain tools and agent CLIs on PATH. Agent-specific side effects (Aside, the Zed keychain, Codex's usage check) are also stubbed in `TestMain`.
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -13,6 +13,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -491,6 +492,43 @@ func checkStdio(ctx context.Context, s *Server) ServerHealth {
|
||||
return *first
|
||||
}
|
||||
|
||||
// stdioProgram is the program checkStdio starts for a server's command,
|
||||
// and the folder it was found in when magpie's PATH lacks it. A bare name
|
||||
// PATH doesn't have is looked for as a terminal would find it
|
||||
// (proc.FindTool: the folders a user's tools are installed in, fnm's Nodes
|
||||
// among them, #2685), and that folder goes on the child's PATH, as it is
|
||||
// on a terminal's: npx's package runs the node beside it by name. A path
|
||||
// is taken as it is.
|
||||
func stdioProgram(name string) (prog, found string) {
|
||||
if name == "" || strings.ContainsAny(name, `/\`) {
|
||||
return name, ""
|
||||
}
|
||||
if _, err := exec.LookPath(name); err == nil {
|
||||
return name, ""
|
||||
}
|
||||
if p := proc.FindTool(name); p != "" {
|
||||
return p, filepath.Dir(p)
|
||||
}
|
||||
return name, ""
|
||||
}
|
||||
|
||||
// withPath is env with dir after the folders its PATH has (Path, as
|
||||
// Windows spells it, too).
|
||||
func withPath(env []string, dir string) []string {
|
||||
out := slices.Clone(env)
|
||||
for i := len(out) - 1; i >= 0; i-- {
|
||||
k, v, ok := strings.Cut(out[i], "=")
|
||||
if ok && (k == "PATH" || runtime.GOOS == "windows" && strings.EqualFold(k, "PATH")) {
|
||||
if v != "" {
|
||||
v += string(os.PathListSeparator)
|
||||
}
|
||||
out[i] = k + "=" + v + dir
|
||||
return out
|
||||
}
|
||||
}
|
||||
return append(out, "PATH="+dir)
|
||||
}
|
||||
|
||||
// checkStdioAt starts the command on this machine, or in WSL distro.
|
||||
func checkStdioAt(ctx context.Context, s *Server, distro string) ServerHealth {
|
||||
// started as the agents start it: in the environment magpie has, with
|
||||
@@ -502,8 +540,11 @@ func checkStdioAt(ctx context.Context, s *Server, distro string) ServerHealth {
|
||||
var cmd *exec.Cmd
|
||||
var t wslrun.Tool
|
||||
stop := func() {}
|
||||
found := ""
|
||||
if distro == "" {
|
||||
cmd = proc.Command(s.Command, s.Args...)
|
||||
var prog string
|
||||
prog, found = stdioProgram(s.Command)
|
||||
cmd = proc.Command(prog, s.Args...)
|
||||
} else {
|
||||
var err error
|
||||
t, err = wslrun.In(distro, s.Command)
|
||||
@@ -537,6 +578,9 @@ func checkStdioAt(ctx context.Context, s *Server, distro string) ServerHealth {
|
||||
cmd.Env = append(cmd.Env, "PWD="+d)
|
||||
}
|
||||
}
|
||||
if found != "" {
|
||||
cmd.Env = withPath(cmd.Env, found)
|
||||
}
|
||||
var names []string
|
||||
for k, v := range env {
|
||||
cmd.Env = append(cmd.Env, k+"="+v)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// #2685: a bare npx the check's PATH lacks is the one a terminal would run
|
||||
// (proc.FindTool, the folders a user's tools are installed in, fnm's
|
||||
// Nodes on Windows among them), and its folder goes on the child's PATH,
|
||||
// where the node it runs by name is. A path, and a name PATH has, are
|
||||
// started as they are.
|
||||
func TestStdioProgramFindsWhatPathLacks(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
proc.Forget()
|
||||
bin := filepath.Join(home, ".local", "bin")
|
||||
name := "magpie-fake-npx"
|
||||
file := name
|
||||
if runtime.GOOS == "windows" {
|
||||
file += ".cmd"
|
||||
}
|
||||
testenv.Program(t, filepath.Join(bin, file), "#!/bin/sh\necho hi\n")
|
||||
prog, found := stdioProgram(name)
|
||||
if !strings.EqualFold(prog, filepath.Join(bin, file)) || !strings.EqualFold(found, bin) {
|
||||
t.Fatalf("stdioProgram(%q) = %q, %q; want %q found in %q", name, prog, found, filepath.Join(bin, file), bin)
|
||||
}
|
||||
abs := filepath.Join(home, "elsewhere", file)
|
||||
if prog, found := stdioProgram(abs); prog != abs || found != "" {
|
||||
t.Fatalf("a path: stdioProgram = %q, %q; want it as it is", prog, found)
|
||||
}
|
||||
if prog, found := stdioProgram("magpie-no-such-tool"); prog != "magpie-no-such-tool" || found != "" {
|
||||
t.Fatalf("nowhere: stdioProgram = %q, %q; want the name, for notfound", prog, found)
|
||||
}
|
||||
t.Setenv("PATH", bin)
|
||||
proc.Forget()
|
||||
if prog, found := stdioProgram(name); prog != name || found != "" {
|
||||
t.Fatalf("on PATH: stdioProgram = %q, %q; want the name as it is", prog, found)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithPath(t *testing.T) {
|
||||
sep := string(os.PathListSeparator)
|
||||
key := "PATH"
|
||||
if runtime.GOOS == "windows" {
|
||||
key = "Path" // as os.Environ spells it there
|
||||
}
|
||||
got := withPath([]string{"A=1", key + "=x" + sep + "y"}, "z")
|
||||
if want := []string{"A=1", key + "=x" + sep + "y" + sep + "z"}; !slices.Equal(got, want) {
|
||||
t.Fatalf("withPath = %q, want %q", got, want)
|
||||
}
|
||||
if got := withPath([]string{"A=1"}, "z"); !slices.Equal(got, []string{"A=1", "PATH=z"}) {
|
||||
t.Fatalf("no PATH: withPath = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package proc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Node version managers' folders read the same on every system: the
|
||||
// version folders a manager keeps, highest first, and fnm's Windows layout
|
||||
// (fnmWin*), which magpie's own PATH and FindTool use on Windows and the
|
||||
// tests take on any system.
|
||||
|
||||
// nodeVersions are the names of the version folders under root that have
|
||||
// a folder bin (root/<version>/<bin>), highest version first (nodeVersionLess); a name that is
|
||||
// no version (mise's "lts", "latest") after every one that is.
|
||||
func nodeVersions(root, bin string) []string {
|
||||
es, _ := os.ReadDir(root)
|
||||
var names []string
|
||||
for _, e := range es {
|
||||
if st, err := os.Stat(filepath.Join(root, e.Name(), bin)); err == nil && st.IsDir() {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(names, func(a, b string) int {
|
||||
switch {
|
||||
case nodeVersionLess(b, a):
|
||||
return -1
|
||||
case nodeVersionLess(a, b):
|
||||
return 1
|
||||
}
|
||||
return strings.Compare(a, b)
|
||||
})
|
||||
return names
|
||||
}
|
||||
|
||||
// parseNodeVersion reads v22.12.0 (or 22.12.0, mise's, or 22, a partial
|
||||
// one) as its numbers; false for a name that isn't one.
|
||||
func parseNodeVersion(s string) ([3]int, int, bool) {
|
||||
var v [3]int
|
||||
parts := strings.Split(strings.TrimPrefix(s, "v"), ".")
|
||||
if len(parts) > 3 || parts[0] == "" {
|
||||
return v, 0, false
|
||||
}
|
||||
for i, p := range parts {
|
||||
n, err := strconv.Atoi(p)
|
||||
if err != nil || n < 0 {
|
||||
return v, 0, false
|
||||
}
|
||||
v[i] = n
|
||||
}
|
||||
return v, len(parts), true
|
||||
}
|
||||
|
||||
// nodeVersionLess says a is a lower version than b, by number: v9 before
|
||||
// v22. A name that is no version is lower than one that is.
|
||||
func nodeVersionLess(a, b string) bool {
|
||||
va, _, oka := parseNodeVersion(a)
|
||||
vb, _, okb := parseNodeVersion(b)
|
||||
if oka != okb {
|
||||
return okb
|
||||
}
|
||||
return oka && slices.Compare(va[:], vb[:]) < 0
|
||||
}
|
||||
|
||||
func isDir(p string) bool {
|
||||
st, err := os.Stat(p)
|
||||
return err == nil && st.IsDir()
|
||||
}
|
||||
|
||||
// fnm on Windows (#2685). A version's programs are in its installation
|
||||
// folder itself — node-versions\<v>\installation\node.exe, npx.cmd — with
|
||||
// no bin under it as on macOS and Linux, and aliases\default is a junction
|
||||
// to the default version's installation folder (fnm's symlink_dir is
|
||||
// junction::create there). A terminal set up with `fnm env` has its own
|
||||
// link to aliases\default first on PATH, so its node, npx and the npm
|
||||
// shims beside them are found; magpie, started from the Start menu, has
|
||||
// the registry's PATH only and had none of them. An npx.cmd run by its
|
||||
// full path started too, but the package it fetched runs `node` from
|
||||
// PATH, and the server died with cmd's "'node' is not recognized".
|
||||
|
||||
// fnmWinRoots are the folders fnm keeps its Node versions in on Windows
|
||||
// that exist here, the one fnm uses first: FNM_DIR, else its default,
|
||||
// the data folder's fnm (etcetera's Windows data_dir, home\AppData\Roaming,
|
||||
// which APPDATA names), else the legacy ~\.fnm.
|
||||
func fnmWinRoots(home, appdata, fnmDir string) []string {
|
||||
var roots []string
|
||||
if filepath.IsAbs(fnmDir) {
|
||||
roots = append(roots, fnmDir)
|
||||
}
|
||||
if filepath.IsAbs(appdata) {
|
||||
roots = append(roots, filepath.Join(appdata, "fnm"))
|
||||
}
|
||||
if filepath.IsAbs(home) {
|
||||
roots = append(roots, filepath.Join(home, "AppData", "Roaming", "fnm"), filepath.Join(home, ".fnm"))
|
||||
}
|
||||
var have []string
|
||||
for _, r := range roots {
|
||||
if isDir(r) && !slices.ContainsFunc(have, func(h string) bool { return strings.EqualFold(h, r) }) {
|
||||
have = append(have, r)
|
||||
}
|
||||
}
|
||||
return have
|
||||
}
|
||||
|
||||
// fnmWinBins are the folders of the Node versions fnm keeps in dir on
|
||||
// Windows: the default alias's (aliases\default, as it stands: a junction
|
||||
// Stat follows) first, then each installation folder, newest first.
|
||||
func fnmWinBins(dir string) []string {
|
||||
var bins []string
|
||||
if def := filepath.Join(dir, "aliases", "default"); isDir(def) {
|
||||
bins = append(bins, def)
|
||||
}
|
||||
root := filepath.Join(dir, "node-versions")
|
||||
for _, n := range nodeVersions(root, "installation") {
|
||||
bins = append(bins, filepath.Join(root, n, "installation"))
|
||||
}
|
||||
return bins
|
||||
}
|
||||
|
||||
// fnmWinUse is the folder of fnm's Node in dir a terminal gets on Windows:
|
||||
// the default alias's; with no default alias, the highest installed. ""
|
||||
// when the default leads nowhere: fnm's "system" alias points at a folder
|
||||
// that can't exist (Z:\_fnm_\...), and such a terminal runs the system's
|
||||
// Node, which PATH has already.
|
||||
func fnmWinUse(dir string) string {
|
||||
def := filepath.Join(dir, "aliases", "default")
|
||||
if isDir(def) {
|
||||
return def
|
||||
}
|
||||
if _, err := os.Lstat(def); err == nil {
|
||||
return ""
|
||||
}
|
||||
root := filepath.Join(dir, "node-versions")
|
||||
if ns := nodeVersions(root, "installation"); len(ns) > 0 {
|
||||
return filepath.Join(root, ns[0], "installation")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// fnmWinPath is the folder of fnm's Node a terminal gets, in the root fnm
|
||||
// uses (fnmWinRoots, fnmWinUse); none when fnm isn't here.
|
||||
func fnmWinPath(home, appdata, fnmDir string) []string {
|
||||
if roots := fnmWinRoots(home, appdata, fnmDir); len(roots) > 0 {
|
||||
if d := fnmWinUse(roots[0]); d != "" {
|
||||
return []string{d}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// addPath adds the folders PATH lacks, after the ones it has.
|
||||
func addPath(dirs []string) {
|
||||
cur := filepath.SplitList(os.Getenv("PATH"))
|
||||
seen := map[string]bool{}
|
||||
for _, d := range cur {
|
||||
seen[d] = true
|
||||
}
|
||||
for _, d := range dirs {
|
||||
if d != "" && filepath.IsAbs(d) && !seen[d] {
|
||||
seen[d] = true
|
||||
cur = append(cur, d)
|
||||
}
|
||||
}
|
||||
os.Setenv("PATH", strings.Join(cur, string(os.PathListSeparator)))
|
||||
}
|
||||
@@ -49,58 +49,6 @@ func nvmBins(dir string) (bins []string, def string, system bool) {
|
||||
return bins, def, system
|
||||
}
|
||||
|
||||
// nodeVersions are the names of the version folders under root that have
|
||||
// a folder bin (root/<version>/<bin>), highest version first (nodeVersionLess); a name that is
|
||||
// no version (mise's "lts", "latest") after every one that is.
|
||||
func nodeVersions(root, bin string) []string {
|
||||
es, _ := os.ReadDir(root)
|
||||
var names []string
|
||||
for _, e := range es {
|
||||
if st, err := os.Stat(filepath.Join(root, e.Name(), bin)); err == nil && st.IsDir() {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(names, func(a, b string) int {
|
||||
switch {
|
||||
case nodeVersionLess(b, a):
|
||||
return -1
|
||||
case nodeVersionLess(a, b):
|
||||
return 1
|
||||
}
|
||||
return strings.Compare(a, b)
|
||||
})
|
||||
return names
|
||||
}
|
||||
|
||||
// parseNodeVersion reads v22.12.0 (or 22.12.0, mise's, or 22, a partial
|
||||
// one) as its numbers; false for a name that isn't one.
|
||||
func parseNodeVersion(s string) ([3]int, int, bool) {
|
||||
var v [3]int
|
||||
parts := strings.Split(strings.TrimPrefix(s, "v"), ".")
|
||||
if len(parts) > 3 || parts[0] == "" {
|
||||
return v, 0, false
|
||||
}
|
||||
for i, p := range parts {
|
||||
n, err := strconv.Atoi(p)
|
||||
if err != nil || n < 0 {
|
||||
return v, 0, false
|
||||
}
|
||||
v[i] = n
|
||||
}
|
||||
return v, len(parts), true
|
||||
}
|
||||
|
||||
// nodeVersionLess says a is a lower version than b, by number: v9 before
|
||||
// v22. A name that is no version is lower than one that is.
|
||||
func nodeVersionLess(a, b string) bool {
|
||||
va, _, oka := parseNodeVersion(a)
|
||||
vb, _, okb := parseNodeVersion(b)
|
||||
if oka != okb {
|
||||
return okb
|
||||
}
|
||||
return oka && slices.Compare(va[:], vb[:]) < 0
|
||||
}
|
||||
|
||||
// nvmDefault is the installed version (one of names, highest first) nvm's
|
||||
// default alias resolves to, as nvm.sh does when a shell loads it
|
||||
// (nvm_auto use → nvm_resolve_local_alias default): alias/default, then
|
||||
@@ -235,8 +183,3 @@ func nodeBins(root string) []string {
|
||||
}
|
||||
return bins
|
||||
}
|
||||
|
||||
func isDir(p string) bool {
|
||||
st, err := os.Stat(p)
|
||||
return err == nil && st.IsDir()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package proc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fnmWin lays fnm out at root as it is on Windows (#2685): each version's
|
||||
// programs in node-versions\<v>\installation itself, no bin, and
|
||||
// aliases\default leading to def's installation folder (a junction there,
|
||||
// a symlink here; a folder of its own where neither can be made). "" for
|
||||
// def leaves the alias out.
|
||||
func fnmWin(t *testing.T, root, def string, versions ...string) {
|
||||
t.Helper()
|
||||
for _, v := range versions {
|
||||
inst := filepath.Join(root, "node-versions", v, "installation")
|
||||
if err := os.MkdirAll(inst, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, f := range []string{"node.exe", "npx.cmd"} {
|
||||
if err := os.WriteFile(filepath.Join(inst, f), nil, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if def == "" {
|
||||
return
|
||||
}
|
||||
alias := filepath.Join(root, "aliases", "default")
|
||||
if err := os.MkdirAll(filepath.Dir(alias), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(root, "node-versions", def, "installation"), alias); err != nil {
|
||||
if err := os.MkdirAll(alias, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fnm's Windows folders in the order a terminal reaches them: the default
|
||||
// alias's, as it stands (where the reporter's npx.cmd is), then each
|
||||
// installation folder by version number, v24 before v9.
|
||||
func TestFnmWinBins(t *testing.T) {
|
||||
root := filepath.Join(t.TempDir(), "fnm")
|
||||
fnmWin(t, root, "v20.18.0", "v9.11.2", "v24.19.0", "v20.18.0")
|
||||
if err := os.MkdirAll(filepath.Join(root, "node-versions", "v25.0.0"), 0o755); err != nil {
|
||||
t.Fatal(err) // being installed: no installation folder yet
|
||||
}
|
||||
inst := func(v string) string { return filepath.Join(root, "node-versions", v, "installation") }
|
||||
want := []string{filepath.Join(root, "aliases", "default"), inst("v24.19.0"), inst("v20.18.0"), inst("v9.11.2")}
|
||||
if got := fnmWinBins(root); !slices.Equal(got, want) {
|
||||
t.Fatalf("fnmWinBins = %q\nwant %q", got, want)
|
||||
}
|
||||
if got, want := fnmWinUse(root), filepath.Join(root, "aliases", "default"); got != want {
|
||||
t.Fatalf("fnmWinUse = %q, want the default alias %q", got, want)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(fnmWinUse(root), "node.exe")); err != nil {
|
||||
t.Fatalf("no node.exe in the default alias's folder: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// With no default alias a terminal's fnm has no Node of its own; magpie
|
||||
// takes the highest installed, as it does for nvm. A default that leads
|
||||
// nowhere is fnm's "system" alias (Z:\_fnm_\...): the system's Node, which
|
||||
// PATH has already, so none.
|
||||
func TestFnmWinUseWithoutDefault(t *testing.T) {
|
||||
root := filepath.Join(t.TempDir(), "fnm")
|
||||
fnmWin(t, root, "", "v9.11.2", "v22.12.0")
|
||||
if got, want := fnmWinUse(root), filepath.Join(root, "node-versions", "v22.12.0", "installation"); got != want {
|
||||
t.Fatalf("no default: fnmWinUse = %q, want %q", got, want)
|
||||
}
|
||||
alias := filepath.Join(root, "aliases", "default")
|
||||
if err := os.MkdirAll(filepath.Dir(alias), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(t.TempDir(), "_fnm_", "Nothing", "installation"), alias); err != nil {
|
||||
t.Skipf("no symlink here: %v", err)
|
||||
}
|
||||
if got := fnmWinUse(root); got != "" {
|
||||
t.Fatalf(`"system" default: fnmWinUse = %q, want none`, got)
|
||||
}
|
||||
}
|
||||
|
||||
// fnm's root on Windows: FNM_DIR, else %APPDATA%\fnm (etcetera's
|
||||
// data_dir), else the legacy ~\.fnm; the folder a terminal gets is the
|
||||
// default alias's in the first of them. Given as Windows sets them, under
|
||||
// a temp folder.
|
||||
func TestFnmWinPath(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
appdata := filepath.Join(home, "AppData", "Roaming")
|
||||
roaming := filepath.Join(appdata, "fnm")
|
||||
if got := fnmWinPath(home, appdata, ""); got != nil {
|
||||
t.Fatalf("no fnm: fnmWinPath = %q", got)
|
||||
}
|
||||
fnmWin(t, roaming, "v24.19.0", "v24.19.0")
|
||||
if got, want := fnmWinPath(home, appdata, ""), []string{filepath.Join(roaming, "aliases", "default")}; !slices.Equal(got, want) {
|
||||
t.Fatalf("APPDATA's fnm: fnmWinPath = %q, want %q", got, want)
|
||||
}
|
||||
// APPDATA unset or relative: the home's AppData\Roaming, where etcetera
|
||||
// puts it
|
||||
if got := fnmWinRoots(home, "AppData", ""); !slices.Equal(got, []string{roaming}) {
|
||||
t.Fatalf("relative APPDATA: fnmWinRoots = %q, want %q", got, []string{roaming})
|
||||
}
|
||||
legacy := filepath.Join(home, ".fnm")
|
||||
fnmWin(t, legacy, "v18.0.0", "v18.0.0")
|
||||
moved := filepath.Join(home, "D", "fnm")
|
||||
fnmWin(t, moved, "v22.12.0", "v22.12.0")
|
||||
if got, want := fnmWinRoots(home, appdata, moved), []string{moved, roaming, legacy}; !slices.Equal(got, want) {
|
||||
t.Fatalf("fnmWinRoots = %q, want %q", got, want)
|
||||
}
|
||||
if got, want := fnmWinPath(home, appdata, moved), []string{filepath.Join(moved, "aliases", "default")}; !slices.Equal(got, want) {
|
||||
t.Fatalf("FNM_DIR: fnmWinPath = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -456,19 +456,3 @@ func parseShellEnv(s, mark string) (string, map[string]string) {
|
||||
}
|
||||
return f[0], vars
|
||||
}
|
||||
|
||||
// addPath adds the folders PATH lacks, after the ones it has.
|
||||
func addPath(dirs []string) {
|
||||
cur := filepath.SplitList(os.Getenv("PATH"))
|
||||
seen := map[string]bool{}
|
||||
for _, d := range cur {
|
||||
seen[d] = true
|
||||
}
|
||||
for _, d := range dirs {
|
||||
if d != "" && filepath.IsAbs(d) && !seen[d] {
|
||||
seen[d] = true
|
||||
cur = append(cur, d)
|
||||
}
|
||||
}
|
||||
os.Setenv("PATH", strings.Join(cur, string(os.PathListSeparator)))
|
||||
}
|
||||
|
||||
@@ -10,13 +10,22 @@ import (
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
)
|
||||
|
||||
// UserPath has nothing to do on Windows: an app started from the Start menu
|
||||
// gets the user's PATH from the registry, as a terminal does.
|
||||
func UserPath() {}
|
||||
// UserPath gives magpie, and what it starts, the Node a terminal has from
|
||||
// fnm (#2685). An app started from the Start menu gets the user's PATH from
|
||||
// the registry, as a terminal does, but fnm puts its Node on PATH from the
|
||||
// shell's profile (`fnm env | Invoke-Expression`) and never in the
|
||||
// registry: an MCP server run with npx, even by npx.cmd's full path, died
|
||||
// with "'node' is not recognized" once the package it fetched ran node.
|
||||
// The folder fnm's default alias names is added after the ones PATH has.
|
||||
func UserPath() {
|
||||
home, _ := os.UserHomeDir()
|
||||
addPath(fnmWinPath(home, appdir.Getenv("APPDATA"), os.Getenv("FNM_DIR")))
|
||||
}
|
||||
|
||||
// UserBinDirs are the folders a user's command-line tools are installed in
|
||||
// that exist here — npm's global one, bun's, volta's, pnpm's, mise's
|
||||
// shims, the standalone installers' — for finding one PATH doesn't reach.
|
||||
// shims, the standalone installers', each Node version of fnm's, its
|
||||
// default first — for finding one PATH doesn't reach.
|
||||
func UserBinDirs() []string {
|
||||
home, _ := os.UserHomeDir()
|
||||
// mise's data folder: MISE_DATA_DIR, else XDG_DATA_HOME's mise (which
|
||||
@@ -36,6 +45,9 @@ func UserBinDirs() []string {
|
||||
filepath.Join(appdir.Getenv("LOCALAPPDATA"), "pnpm"),
|
||||
filepath.Join(mise, "shims"),
|
||||
}
|
||||
for _, r := range fnmWinRoots(home, appdir.Getenv("APPDATA"), os.Getenv("FNM_DIR")) {
|
||||
known = append(known, fnmWinBins(r)...)
|
||||
}
|
||||
var have []string
|
||||
for _, d := range known {
|
||||
if st, err := os.Stat(d); filepath.IsAbs(d) && err == nil && st.IsDir() {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package proc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// #2685: an MCP server started by fnm's npx.cmd, by its full path, runs
|
||||
// the package it fetched, which runs `node` by name. A terminal's fnm put
|
||||
// node's folder on PATH; magpie's PATH, the registry's, didn't have it,
|
||||
// and the server exited 1 with cmd's "'node' is not recognized as an
|
||||
// internal or external command, operable program or batch file." After
|
||||
// UserPath the child finds fnm's node, and FindTool finds a bare npx.
|
||||
func TestUserPathFnmNode(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
appdata := filepath.Join(home, "AppData", "Roaming")
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("APPDATA", appdata)
|
||||
t.Setenv("FNM_DIR", "")
|
||||
sys := filepath.Join(os.Getenv("SystemRoot"), "System32")
|
||||
t.Setenv("PATH", sys)
|
||||
root := filepath.Join(appdata, "fnm")
|
||||
inst := filepath.Join(root, "node-versions", "v24.19.0", "installation")
|
||||
if err := os.MkdirAll(inst, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// npx's package bin, as npm's cmd shim runs it: node from PATH
|
||||
npx := filepath.Join(inst, "npx.cmd")
|
||||
for p, s := range map[string]string{npx: "@echo off\r\nnode %*\r\n", filepath.Join(inst, "node.cmd"): "@echo fnm node %*\r\n"} {
|
||||
if err := os.WriteFile(p, []byte(s), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
alias := filepath.Join(root, "aliases", "default")
|
||||
if err := os.MkdirAll(filepath.Dir(alias), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// a junction, as fnm makes it
|
||||
if out, err := Command("cmd", "/c", "mklink", "/J", alias, inst).CombinedOutput(); err != nil {
|
||||
t.Fatalf("mklink /J: %v %s", err, out)
|
||||
}
|
||||
run := func() (string, error) {
|
||||
cmd := Command(npx, "-y", "chrome-devtools-mcp@latest")
|
||||
cmd.Dir = t.TempDir() // cmd looks in its folder before PATH
|
||||
out, err := cmd.CombinedOutput()
|
||||
return strings.TrimSpace(string(out)), err
|
||||
}
|
||||
if out, err := run(); err == nil {
|
||||
t.Fatalf("before UserPath node was found already (%q): the test proves nothing", out)
|
||||
}
|
||||
|
||||
UserPath()
|
||||
if dirs := filepath.SplitList(os.Getenv("PATH")); !slices.Contains(dirs, alias) {
|
||||
t.Fatalf("PATH after UserPath = %q, want fnm's default alias %q on it", dirs, alias)
|
||||
}
|
||||
if out, err := run(); err != nil || out != "fnm node -y chrome-devtools-mcp@latest" {
|
||||
t.Fatalf("npx.cmd by its full path: %v %q, want fnm's node run", err, out)
|
||||
}
|
||||
t.Setenv("PATH", sys)
|
||||
Forget()
|
||||
if got := FindTool("npx"); !strings.EqualFold(got, filepath.Join(alias, "npx.cmd")) {
|
||||
t.Fatalf("FindTool(npx) = %q, want the default alias's %q", got, filepath.Join(alias, "npx.cmd"))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user