Files
magpie/internal/proc/nodever_other.go
T
yetoneandEdward4226 5b4da5bee3 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>
2026-10-27 06:45:37 +08:00

186 lines
5.6 KiB
Go

//go:build !windows
package proc
import (
"os"
"path/filepath"
"slices"
"strconv"
"strings"
)
// A Node version manager keeps one folder per version, and a terminal runs
// the one it was told to use, not the one whose name sorts last. magpie
// picked nvm's "newest-looking" folder by name, and in plain string order
// v9.11.2 comes after v22.12.0: a codex, claude or gemini installed under a
// Node the terminal doesn't use was found, run and updated in place of the
// terminal's (found while answering 悠悠哥 on Discord, 9f407cafa). The
// folders are taken in the order a terminal would reach them instead: the
// manager's default first, then the highest version.
// nvmDir is nvm's folder: $NVM_DIR as the profile sets it, else ~/.nvm.
func nvmDir(home string) string {
if d := os.Getenv("NVM_DIR"); filepath.IsAbs(d) {
return d
}
if home == "" {
return ""
}
return filepath.Join(home, ".nvm")
}
// nvmBins are the bin folders of the Node versions nvm keeps in dir, the
// one a terminal gets first (nvmDefault), then the rest newest first.
// system is true when nvm's default is the system's Node, which a
// terminal then runs, and none of these.
func nvmBins(dir string) (bins []string, def string, system bool) {
root := filepath.Join(dir, "versions", "node")
names := nodeVersions(root, "bin")
def, system = nvmDefault(dir, names)
for _, n := range names {
bins = append(bins, filepath.Join(root, n, "bin"))
}
if def != "" {
def = filepath.Join(root, def, "bin")
bins = slices.DeleteFunc(bins, func(b string) bool { return b == def })
bins = append([]string{def}, bins...)
}
return bins, def, system
}
// 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
// each alias it names in turn (lts/* → lts/jod → v22.20.0, node, stable),
// a cycle being none; "node" and "stable" the highest installed; a partial
// version (22, v22.1) the highest installed that it starts; a full one
// itself when it is installed (its bin/node there). "" when the default
// isn't set or names nothing installed (nvm then puts no Node on PATH), or
// is the system's Node, which system says.
func nvmDefault(dir string, names []string) (string, bool) {
alias := filepath.Join(dir, "alias")
cur, seen := "default", map[string]bool{"default": true}
for {
next := nvmAlias(alias, cur)
if next == "" {
break
}
if seen[next] {
return "", false // nvm's ∞
}
seen[next] = true
cur = next
}
if cur == "default" {
return "", false
}
installed := func(n string) bool {
st, err := os.Stat(filepath.Join(dir, "versions", "node", n, "bin", "node"))
return err == nil && !st.IsDir() && st.Mode()&0o111 != 0
}
switch cur {
case "system":
return "", true
case "node", "stable":
for _, n := range names {
if _, _, ok := parseNodeVersion(n); ok && strings.HasPrefix(n, "v") {
return n, false
}
}
return "", false
}
// nvm_ensure_version_prefix: 22 → v22
if cur[0] >= '0' && cur[0] <= '9' {
cur = "v" + cur
}
if _, parts, ok := parseNodeVersion(cur); !ok || !strings.HasPrefix(cur, "v") {
return "", false // iojs, unstable, N/A, ∞: no Node of versions/node
} else if parts == 3 {
if installed(cur) {
return cur, false
}
return "", false
}
// nvm_ls v22 matches v22.*, v22.1 matches v22.1.*, newest last
for _, n := range names {
if strings.HasPrefix(n, strings.TrimSuffix(cur, ".")+".") {
return n, false
}
}
return "", false
}
// nvmAlias is what nvm's alias name holds, nvm_alias: the first line of
// alias/<name> with something on it, after nvm_normalize_lts turns
// lts/-1 into the LTS line before the newest. "" when there is no such
// alias.
func nvmAlias(alias, name string) string {
if n, ok := strings.CutPrefix(name, "lts/-"); ok {
k, err := strconv.Atoi(n)
if err != nil || k < 1 {
return ""
}
es, _ := os.ReadDir(filepath.Join(alias, "lts"))
var ls []string
for _, e := range es {
ls = append(ls, e.Name())
}
slices.Sort(ls) // `ls`, whose order nvm takes
i := len(ls) - (k + 1)
if i < 0 {
i = 0
}
if len(ls) == 0 || ls[i] == "*" {
return ""
}
name = "lts/" + ls[i]
}
if name == "" || strings.Contains(name, "..") {
return ""
}
b, err := os.ReadFile(filepath.Join(alias, filepath.FromSlash(name)))
if err != nil {
return ""
}
for _, l := range strings.Split(string(b), "\n") {
if l = strings.TrimSpace(l); l != "" {
return l
}
}
return ""
}
// fnmBins are the bin folders of the Node versions fnm keeps in dir, the
// default alias's (aliases/default, a link to the version's folder) first,
// then the rest newest first.
func fnmBins(dir string) []string {
root := filepath.Join(dir, "node-versions")
var bins []string
for _, n := range nodeVersions(root, filepath.Join("installation", "bin")) {
bins = append(bins, filepath.Join(root, n, "installation", "bin"))
}
if to, err := filepath.EvalSymlinks(filepath.Join(dir, "aliases", "default")); err == nil {
if real, err := filepath.EvalSymlinks(root); err == nil {
if rel, err := filepath.Rel(real, to); err == nil && !strings.HasPrefix(rel, "..") {
def := filepath.Join(root, rel, "bin")
if isDir(def) {
bins = slices.DeleteFunc(bins, func(b string) bool { return b == def })
bins = append([]string{def}, bins...)
}
}
}
}
return bins
}
// nodeBins are the bin folders of a manager that keeps each version as
// root/<version>/bin (mise's installs), newest first.
func nodeBins(root string) []string {
var bins []string
for _, n := range nodeVersions(root, "bin") {
bins = append(bins, filepath.Join(root, n, "bin"))
}
return bins
}