proc, agent: magpie finds an agent CLI under the Node nvm's default names, not the folder whose name sorts last (v9 after v22)
proc.UserPath added "the newest-looking" nvm Node to magpie's PATH, the
last folder of ~/.nvm/versions/node/*/bin in string order. That isn't
the Node a terminal gets, and string order puts v9.11.2 after v22.12.0
and v22.3.0 after v22.12.0. So magpie could find, run and update a
codex/claude/gemini under a Node the user's terminal doesn't use (found
while answering 悠悠哥 on Discord, 9f407cafa). UserBinDirs (FindTool,
the Codex executable, nodeHere) took every version in reverse name
order, with the same flaw.
Now (internal/proc/nodever_other.go) the nvm folder is $NVM_DIR or
~/.nvm, and its default is resolved as nvm.sh does on load (nvm_auto
use -> nvm_resolve_local_alias default, read from nvm v0.40.3's
source): alias/default and each alias it names in turn (lts/* ->
lts/jod -> v22.x, lts/-N as nvm_normalize_lts counts it, user aliases),
a cycle being none; node/stable the highest installed; a partial
version (22, v20, 22.3) the highest installed it starts; an exact one
when its bin/node is installed. UserPath adds that one; with no usable
default (unset, not installed, cycle, iojs/unstable) the highest
version by number; with "system" none of nvm's, since the terminal then
runs the system Node. UserBinDirs lists the default first, then the
rest highest first.
Siblings:
- mise's installs and fnm's node-versions (UserBinDirs only) were in
reverse name order too: now by number, fnm's aliases/default first
(and $FNM_DIR looked in). mise's active Node is reached through its
shims, which come earlier.
- volta, asdf and mise shims, and n (one copy in /usr/local/bin), pick
the version themselves: no change.
- Windows (path_windows.go) lists no per-version folder: nvm-windows'
current Node is its NVM_SYMLINK on the registry PATH. No change.
- The WSL probe's wslbin (internal/agent/wsl.go) globbed
"$HOME"/.nvm/versions/node/*/bin, first in name order (v18 before the
default v22). It now asks nvm itself (nvm.sh sourced by bash with
--no-use, nvm_version default), then the rest highest first.
- NVM_DIR and FNM_DIR join agentenv.Vars: test sandboxes clear them, and
UserPath takes them from the login shell like the agents' variables.
Run: TestUserPathNvmDefault (15 real nvm layouts: v9 vs v22, lts/*,
lts/iron, lts/-1, 22, v20, exact v9, node, stable, a user alias, a
default not installed, lts/* naming a line not installed, a cycle,
system direct and through an alias), TestFindToolNvmDefaultFirst,
TestUserPathNvmDir, TestUserBinDirsFnmMise, TestWSLProbeNvmDefault.
With the old path_other.go 14 of the 15 nvm cases go red (v9.11.2
picked; the exact-v9 default passes), as do the other three; with the
default ignored by hand 9 go red; with the old probe line all 3 WSL
cases go red. Cross-checked nvmDefault against
nvm v0.40.3's own nvm_version default on 19 alias layouts: same version
each time (nvm says N/A where magpie falls back, and N/A for system
with no system node). The new probe run with the real nvm.sh under
/bin/sh and /bin/dash resolved lts/*, lts/iron and 18 right. go test
./internal/proc ./internal/agent ./internal/agentenv ./internal/provider
./internal/testenv; full go test -tags nogui ./...; gofmt -l; go vet,
GOOS=linux and GOOS=windows go vet -tags nogui on the touched packages.
All under a temp HOME; no real ~/.nvm read.
This commit is contained in:
@@ -67,7 +67,7 @@ something else shows up as drift.
|
||||
- Tuned settings are written only on the user's click, never by Sync or Connect. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.
|
||||
- A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. What each key held before the first write is stashed under `plugin:<id>:<path>`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-<id>` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`).
|
||||
- StepCode config root resolves to the parent of an absolute `STEP_CODING_AGENT_DIR` (agent resources directory differs from config root; relative values ignored), or `STEPCODE_CONFIG_DIR` under home when native, defaulting to `~/.stepcode` ([`stepcode.go`](../../internal/agent/stepcode.go)). Project configs override global configs in StepCode, but magpie manages global configuration only (`config.toml` and `models.json`). Detection is strictly directory-only via `agentDir`, avoiding collision with Smallstep's bare `step` command on `PATH`. Wiring performs an atomic two-file edit (`models.json` provider block and `config.toml` top-level defaults/scope) backed by `stash.json`. Custom fields within `providers.magpie` are preserved during sync, and the original provider block is restored on disconnect. Disconnect restores original defaults, preserves user native changes and custom scope edits, and removes newly created files only when empty.
|
||||
- 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, nvm's newest Node, 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.
|
||||
- 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.
|
||||
- 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`.
|
||||
|
||||
## Verification
|
||||
|
||||
@@ -55,7 +55,7 @@ type CLI struct {
|
||||
// reached it
|
||||
Path string `json:"path,omitempty"`
|
||||
// OffPath says the CLI was found in a folder magpie adds to its own
|
||||
// PATH (proc.UserPath: ~/.local/bin, npm's prefixes, nvm's newest
|
||||
// PATH (proc.UserPath: ~/.local/bin, npm's prefixes, nvm's default
|
||||
// Node, bun, Homebrew, ...) that a terminal opened now doesn't have,
|
||||
// so that `which` there doesn't find it. A row of an agent the user
|
||||
// believed uninstalled, with a version and nothing to say where it
|
||||
|
||||
+11
-1
@@ -1117,8 +1117,18 @@ const wslProbeVersion = 2
|
||||
// nvm's installers add theirs to PATH (whqtian on Discord: a WSL omp from
|
||||
// bun was never asked its version, so its models still offered xhigh).
|
||||
// It is asked with its own folder on PATH, where bun's script finds bun.
|
||||
//
|
||||
// Of nvm's Nodes, the one a terminal there gets is looked in first: the
|
||||
// version nvm's default alias resolves to, asked of nvm itself
|
||||
// (nvm_version default, nvm.sh read by bash with --no-use), then the rest
|
||||
// highest first. The glob this replaced took them in name order, so a
|
||||
// command under v18 was found before the default v22's, and v9's after
|
||||
// both (as proc.UserPath did on a Mac or Linux, 9f407cafa).
|
||||
var wslProbeScript = func() string {
|
||||
s := `wslbin() { for d in "$HOME/.bun/bin" "$HOME/.local/bin" "$HOME/.npm-global/bin" "$HOME/.volta/bin" "$HOME/.local/share/pnpm" "$HOME"/.nvm/versions/node/*/bin "$HOME/.local/share/mise/shims" "$HOME/.asdf/shims"; do [ -x "$d/$1" ] && { echo "$d/$1"; return 0; }; done; return 1; }; `
|
||||
s := `nv="${NVM_DIR:-$HOME/.nvm}"; nd=; [ -s "$nv/nvm.sh" ] && command -v bash >/dev/null 2>&1 && nd=$(NVM_DIR="$nv" timeout 10 bash -c '. "$NVM_DIR/nvm.sh" --no-use >/dev/null 2>&1; nvm_version default 2>/dev/null' </dev/null 2>/dev/null); ` +
|
||||
`wslbin() { for d in "$HOME/.bun/bin" "$HOME/.local/bin" "$HOME/.npm-global/bin" "$HOME/.volta/bin" "$HOME/.local/share/pnpm"; do [ -x "$d/$1" ] && { echo "$d/$1"; return 0; }; done; ` +
|
||||
`for v in $nd $(ls "$nv/versions/node" 2>/dev/null | sort -t. -k1.2,1nr -k2,2nr -k3,3nr); do d="$nv/versions/node/$v/bin"; [ -x "$d/$1" ] && { echo "$d/$1"; return 0; }; done; ` +
|
||||
`for d in "$HOME/.local/share/mise/shims" "$HOME/.asdf/shims"; do [ -x "$d/$1" ] && { echo "$d/$1"; return 0; }; done; return 1; }; `
|
||||
s += `echo "home:$HOME"; `
|
||||
for _, k := range wslKinds {
|
||||
if k.dir != "" {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// A command the WSL probe finds only under nvm is the one under the Node a
|
||||
// terminal there gets: nvm's default, as nvm itself resolves it, else the
|
||||
// highest version. The probe's glob took nvm's folders in name order, so
|
||||
// a codex under v18 was taken for the default v22's, and v9's came last.
|
||||
func TestWSLProbeNvmDefault(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("the probe runs in a Linux distro")
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name, nvmSh, want string
|
||||
}{
|
||||
{"no nvm.sh: the highest, not the first by name", "", "v22.12.0"},
|
||||
// a stand-in for nvm.sh: the probe asks nvm_version default, which
|
||||
// the real one resolves through alias/default
|
||||
{"nvm's default", "nvm_version() { [ \"$1\" = default ] && echo v9.11.2; }\n", "v9.11.2"},
|
||||
{"nvm's default not installed: the highest", "nvm_version() { echo N/A; }\n", "v22.12.0"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
sys := filepath.Join(home, "sys") // PATH: nothing of codex's
|
||||
os.MkdirAll(sys, 0o755)
|
||||
nvm := filepath.Join(home, ".nvm")
|
||||
for _, v := range []string{"v18.20.4", "v22.12.0", "v9.11.2"} {
|
||||
bin := filepath.Join(nvm, "versions", "node", v, "bin")
|
||||
os.MkdirAll(bin, 0o755)
|
||||
testenv.Program(t, filepath.Join(bin, "codex"), "#!/bin/sh\n")
|
||||
}
|
||||
if c.nvmSh != "" {
|
||||
to, err := exec.LookPath("timeout")
|
||||
if err != nil {
|
||||
t.Skip("no timeout(1)")
|
||||
}
|
||||
if err := os.Symlink(to, filepath.Join(sys, "timeout")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(nvm, "nvm.sh"), []byte(c.nvmSh), 0o644)
|
||||
}
|
||||
cmd := exec.Command("/bin/sh", "-c", wslProbeScript)
|
||||
cmd.Env = []string{"HOME=" + home, "PATH=" + sys + ":/usr/bin:/bin"}
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
t.Fatalf("%v: %s", err, out)
|
||||
}
|
||||
want := "bin:codex " + filepath.Join(nvm, "versions", "node", c.want, "bin", "codex") + "\n"
|
||||
if !strings.Contains(string(out), want) {
|
||||
t.Fatalf("probe said:\n%s\nwant %q", out, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,9 @@ var Vars = []string{
|
||||
// Droid's home, Windsurf's API server, ZCode's credential seed: what
|
||||
// makes an account or an installation visible that the test didn't make
|
||||
"FACTORY_HOME_OVERRIDE", "WINDSURF_API_SERVER_URL", "ZCODE_CREDENTIAL_SECRET",
|
||||
// nvm's and fnm's folders, which hold the Node versions an agent's CLI
|
||||
// is installed under, and which of them a terminal uses
|
||||
"NVM_DIR", "FNM_DIR",
|
||||
// Google Cloud's credentials file and gcloud's folder, which Vertex AI's
|
||||
// tokens are minted from (and Gemini CLI's own, on Vertex AI)
|
||||
"GOOGLE_APPLICATION_CREDENTIALS", "CLOUDSDK_CONFIG",
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//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
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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
|
||||
}
|
||||
|
||||
func isDir(p string) bool {
|
||||
st, err := os.Stat(p)
|
||||
return err == nil && st.IsDir()
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//go:build !windows
|
||||
|
||||
package proc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// nvmHome lays out nvm as it is on disk: versions/node/vX.Y.Z/bin/node
|
||||
// for each of versions, and alias/<name> holding what `nvm alias` writes
|
||||
// (the target and a newline), lts/<name> among them as `nvm ls-remote`
|
||||
// writes them. It gives the home, with NVM_DIR unset and PATH launchd's.
|
||||
func nvmHome(t *testing.T, versions []string, aliases map[string]string) (home, nvm string) {
|
||||
t.Helper()
|
||||
home = t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("NVM_DIR", "")
|
||||
t.Setenv("FNM_DIR", "")
|
||||
t.Setenv("PATH", "/usr/bin:/bin")
|
||||
nvm = filepath.Join(home, ".nvm")
|
||||
for _, v := range versions {
|
||||
bin := filepath.Join(nvm, "versions", "node", v, "bin")
|
||||
if err := os.MkdirAll(bin, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
testenv.Program(t, filepath.Join(bin, "node"), "#!/bin/sh\necho "+v+"\n")
|
||||
testenv.Program(t, filepath.Join(bin, "codex"), "#!/bin/sh\necho codex under "+v+"\n")
|
||||
}
|
||||
for name, to := range aliases {
|
||||
p := filepath.Join(nvm, "alias", filepath.FromSlash(name))
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(to+"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return home, nvm
|
||||
}
|
||||
|
||||
// lts is what `nvm install --lts` leaves in alias/: lts/* naming the newest
|
||||
// LTS line, each line naming its newest release, and the default it set.
|
||||
var lts = map[string]string{
|
||||
"default": "lts/*",
|
||||
"lts/*": "lts/jod",
|
||||
"lts/hydrogen": "v18.20.4",
|
||||
"lts/iron": "v20.18.0",
|
||||
"lts/jod": "v22.12.0",
|
||||
}
|
||||
|
||||
func with(m map[string]string, k, v string) map[string]string {
|
||||
out := map[string]string{k: v}
|
||||
for a, b := range m {
|
||||
if a != k {
|
||||
out[a] = b
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// magpie's PATH gets the nvm Node a terminal gets — the one nvm's default
|
||||
// alias resolves to, as nvm.sh resolves it — not the folder whose name
|
||||
// sorts last: in string order v9.11.2 comes after v22.12.0, so a codex
|
||||
// under a Node the terminal doesn't use was found and run.
|
||||
func TestUserPathNvmDefault(t *testing.T) {
|
||||
all := []string{"v9.11.2", "v18.20.4", "v20.18.0", "v22.3.0", "v22.12.0"}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
versions []string
|
||||
aliases map[string]string
|
||||
want string // "" for no nvm Node at all
|
||||
}{
|
||||
{"no default: the highest, v22 over v9", []string{"v9.11.2", "v22.12.0"}, nil, "v22.12.0"},
|
||||
{"lts/* through lts/jod", all, lts, "v22.12.0"},
|
||||
{"lts/iron", all, with(lts, "default", "lts/iron"), "v20.18.0"},
|
||||
{"lts/-1, the line before the newest", all, with(lts, "default", "lts/-1"), "v20.18.0"},
|
||||
{"a partial version: the newest 22.x, not v22.3.0", all, map[string]string{"default": "22"}, "v22.12.0"},
|
||||
{"v20, prefixed", all, map[string]string{"default": "v20"}, "v20.18.0"},
|
||||
{"an exact old version", all, map[string]string{"default": "v9.11.2"}, "v9.11.2"},
|
||||
{"node: the highest", all, map[string]string{"default": "node"}, "v22.12.0"},
|
||||
{"stable: the highest", all, map[string]string{"default": "stable"}, "v22.12.0"},
|
||||
{"a user alias in between", all, map[string]string{"default": "work", "work": "18"}, "v18.20.4"},
|
||||
{"a default that isn't installed: the highest", []string{"v9.11.2", "v22.12.0"}, map[string]string{"default": "v18.20.4"}, "v22.12.0"},
|
||||
{"lts/* naming a line not installed: the highest", []string{"v9.11.2", "v20.18.0"}, lts, "v20.18.0"},
|
||||
{"an alias cycle: the highest", all, map[string]string{"default": "a", "a": "b", "b": "a"}, "v22.12.0"},
|
||||
{"system: none of nvm's", all, map[string]string{"default": "system"}, ""},
|
||||
{"system through an alias", all, map[string]string{"default": "mine", "mine": "system"}, ""},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
_, nvm := nvmHome(t, c.versions, c.aliases)
|
||||
var got []string
|
||||
for _, d := range userDirs(false) {
|
||||
if strings.HasPrefix(d, nvm) {
|
||||
got = append(got, d)
|
||||
}
|
||||
}
|
||||
var want []string
|
||||
if c.want != "" {
|
||||
want = []string{filepath.Join(nvm, "versions", "node", c.want, "bin")}
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("nvm's on PATH: %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A codex found off PATH is the one under nvm's default Node; the other
|
||||
// Nodes follow it highest first, so a codex only an older Node has is
|
||||
// still found.
|
||||
func TestFindToolNvmDefaultFirst(t *testing.T) {
|
||||
_, nvm := nvmHome(t, []string{"v9.11.2", "v20.18.0", "v22.3.0", "v22.12.0"}, with(lts, "default", "lts/iron"))
|
||||
bin := func(v string) string { return filepath.Join(nvm, "versions", "node", v, "bin") }
|
||||
if got, want := FindTool("codex"), filepath.Join(bin("v20.18.0"), "codex"); got != want {
|
||||
t.Fatalf("found %q, want the default's %q", got, want)
|
||||
}
|
||||
var got []string
|
||||
for _, d := range UserBinDirs() {
|
||||
if strings.HasPrefix(d, nvm) {
|
||||
got = append(got, d)
|
||||
}
|
||||
}
|
||||
want := []string{bin("v20.18.0"), bin("v22.12.0"), bin("v22.3.0"), bin("v9.11.2")}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("nvm's folders in order %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// NVM_DIR names nvm's folder when the profile sets it.
|
||||
func TestUserPathNvmDir(t *testing.T) {
|
||||
home, nvm := nvmHome(t, []string{"v9.11.2", "v22.12.0"}, map[string]string{"default": "9"})
|
||||
moved := filepath.Join(home, ".config", "nvm")
|
||||
os.MkdirAll(filepath.Dir(moved), 0o755)
|
||||
if err := os.Rename(nvm, moved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("NVM_DIR", moved)
|
||||
want := filepath.Join(moved, "versions", "node", "v9.11.2", "bin")
|
||||
if !slices.Contains(userDirs(false), want) {
|
||||
t.Fatalf("%q not in %q", want, userDirs(false))
|
||||
}
|
||||
}
|
||||
|
||||
// fnm's default alias (a link to the version's folder) comes first, and
|
||||
// mise's and fnm's other versions by number, not name.
|
||||
func TestUserBinDirsFnmMise(t *testing.T) {
|
||||
home, _ := nvmHome(t, nil, nil)
|
||||
fnm := filepath.Join(home, ".local", "share", "fnm")
|
||||
fbin := func(v string) string { return filepath.Join(fnm, "node-versions", v, "installation", "bin") }
|
||||
mise := filepath.Join(home, ".local", "share", "mise", "installs", "node")
|
||||
for _, d := range []string{fbin("v9.11.2"), fbin("v20.18.0"), fbin("v22.12.0"),
|
||||
filepath.Join(mise, "9.11.2", "bin"), filepath.Join(mise, "22.12.0", "bin"), filepath.Join(fnm, "aliases")} {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// as fnm and mise make them
|
||||
os.Symlink(filepath.Join(fnm, "node-versions", "v20.18.0", "installation"), filepath.Join(fnm, "aliases", "default"))
|
||||
os.Symlink("22.12.0", filepath.Join(mise, "lts"))
|
||||
var got []string
|
||||
for _, d := range UserBinDirs() {
|
||||
if strings.HasPrefix(d, filepath.Join(home, ".local", "share")) {
|
||||
got = append(got, d)
|
||||
}
|
||||
}
|
||||
want := []string{filepath.Join(mise, "22.12.0", "bin"), filepath.Join(mise, "9.11.2", "bin"), filepath.Join(mise, "lts", "bin"),
|
||||
fbin("v20.18.0"), fbin("v22.12.0"), fbin("v9.11.2")}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("got %q\nwant %q", got, want)
|
||||
}
|
||||
}
|
||||
+25
-16
@@ -21,7 +21,9 @@ import (
|
||||
// or codex installed with a custom npm prefix (~/.npm-global/bin), nvm, bun,
|
||||
// volta or asdf wasn't found: the agent wasn't seen and its subscription
|
||||
// couldn't be used. The folders those tools use are added at once, when they
|
||||
// exist; the login shell's own PATH is asked for after.
|
||||
// exist; the login shell's own PATH is asked for after. Of nvm's Nodes only
|
||||
// the one a terminal gets is added: its default alias's, not the folder
|
||||
// whose name sorts last (nvmBins).
|
||||
//
|
||||
// The same call brings the agents' own variables (agentenv.Vars:
|
||||
// PI_CODING_AGENT_DIR, CODEX_HOME, CLAUDE_CONFIG_DIR, ...) the profile sets
|
||||
@@ -96,7 +98,9 @@ func LoginPath() []string {
|
||||
// UserBinDirs are the folders a user's command-line tools are installed in
|
||||
// that exist here — npm's prefixes, each Node version of nvm, fnm and mise,
|
||||
// bun, volta, pnpm, asdf, the standalone installers' ~/.local/bin,
|
||||
// Homebrew — for finding one PATH doesn't reach.
|
||||
// Homebrew — for finding one PATH doesn't reach. A manager's Node versions
|
||||
// come in the order a terminal would reach them: its default first, then
|
||||
// the highest version (v22 before v9).
|
||||
func UserBinDirs() []string { return userDirs(true) }
|
||||
|
||||
func userDirs(everyNode bool) []string {
|
||||
@@ -105,24 +109,29 @@ func userDirs(everyNode bool) []string {
|
||||
for _, d := range []string{".local/bin", ".npm-global/bin", ".npm/bin", ".bun/bin", ".volta/bin", ".asdf/shims", ".local/share/mise/shims", ".cargo/bin", ".deno/bin", "Library/pnpm"} {
|
||||
known = append(known, filepath.Join(home, d))
|
||||
}
|
||||
nodes := func(pattern string) {
|
||||
vs, _ := filepath.Glob(filepath.Join(home, pattern))
|
||||
if len(vs) == 0 {
|
||||
return
|
||||
// nvm's Node a terminal gets: its default, or with none usable the
|
||||
// highest installed; none when the default is the system's Node
|
||||
if nvm := nvmDir(home); nvm != "" {
|
||||
bins, def, system := nvmBins(nvm)
|
||||
switch {
|
||||
case everyNode:
|
||||
known = append(known, bins...)
|
||||
case def != "":
|
||||
known = append(known, def)
|
||||
case !system && len(bins) > 0:
|
||||
known = append(known, bins[0])
|
||||
}
|
||||
if !everyNode {
|
||||
known = append(known, vs[len(vs)-1])
|
||||
return
|
||||
}
|
||||
slices.Reverse(vs)
|
||||
known = append(known, vs...)
|
||||
}
|
||||
nodes(".nvm/versions/node/*/bin")
|
||||
if everyNode {
|
||||
known = append(known, filepath.Join(home, ".local/share/pnpm"), npmPrefix(home))
|
||||
nodes(".local/share/mise/installs/node/*/bin")
|
||||
nodes(".local/share/fnm/node-versions/*/installation/bin")
|
||||
nodes("Library/Application Support/fnm/node-versions/*/installation/bin")
|
||||
known = append(known, nodeBins(filepath.Join(home, ".local/share/mise/installs/node"))...)
|
||||
fnm := []string{filepath.Join(home, ".local/share/fnm"), filepath.Join(home, "Library/Application Support/fnm")}
|
||||
if d := os.Getenv("FNM_DIR"); filepath.IsAbs(d) {
|
||||
fnm = append([]string{d}, fnm...)
|
||||
}
|
||||
for _, d := range slices.Compact(fnm) {
|
||||
known = append(known, fnmBins(d)...)
|
||||
}
|
||||
}
|
||||
known = append(known, SystemDirs("/opt/homebrew/bin", "/usr/local/bin")...)
|
||||
var have []string
|
||||
|
||||
Reference in New Issue
Block a user