Files
magpie/internal/proc/path_other.go
T
yetone 9848a9062a library: RTK says when rtk isn't on the PATH the agents get, and puts it there when asked (#601, Moody-Sin: magpie好像没有正确安装RTK — Pi said "RTK disabled: rtk binary not found in PATH" while the Library showed RTK working) — rtk's hooks run it by name (Pi's extension probes rtk --version and turns itself off when that fails; Claude Code's and Codex's are rtk hook …; the commands they rewrite to are rtk git status and so on), but magpie looked for rtk in more places than an agent's PATH: ~/.local/bin and ~/.cargo/bin, which the app adds to its own PATH whether the user's shell has them or not (rtk's own install.sh puts it in ~/.local/bin and only warns when that isn't on PATH), and WinGet\Links on Windows, which winget doesn't always link into. So rtk was "installed", the agents were switched on with it by its whole path, and none of them could run it. Now the PATH a terminal opened now has is read — the login shell's (proc.LoginPath, the one UserPath already asks for, kept a minute) or on Windows the registry's (moved from provider's registryPath) — and when rtk isn't in it the RTK card says so, with what Put RTK on PATH will do, and each agent that has rtk is tagged Not on PATH (不在 PATH 中). Put RTK on PATH (magpie library rtk path) links rtk into the first of ~/.local/bin, ~/bin, /opt/homebrew/bin, /usr/local/bin, linuxbrew's bin, ~/.cargo/bin that is on that PATH and writable, or on Windows adds rtk's own folder to the user's PATH in the registry (a link needs Developer Mode, and a copy is left behind when winget upgrades rtk; winget's package folder doesn't change across upgrades) and tells Explorer; with no such folder it says which folder to add to PATH in the shell profile — shell profiles are never edited. rtk is also found in winget's package folder (WinGet\Packages\rtk-ai.rtk_*), and rtk's script upgrades a linked rtk where the link points, not over the link. TestRTKOffPath and library-rtk-path.test.cjs (en, zh) fail without the change. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build and vet, go test -tags nogui -count=1 ./... under a temp HOME pass but the known TestFXInState flake. The Windows registry path is built, not run on Windows.
2026-10-03 02:38:17 +08:00

169 lines
4.7 KiB
Go

//go:build !windows
package proc
import (
"context"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
)
// UserPath gives the desktop app the PATH a terminal of the user's has. One
// opened from the Finder, the Dock or a login item gets launchd's
// /usr/bin:/bin:/usr/sbin:/sbin and nothing a shell profile adds, so a claude
// 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 in the background and
// added after, since a slow profile mustn't hold the window up.
func UserPath() {
addPath(userDirs(false))
go func() {
if p := shellPath(); p != "" {
addPath(filepath.SplitList(p))
login.Lock()
login.dirs, login.at = filepath.SplitList(p), time.Now()
login.Unlock()
}
}()
}
var login struct {
sync.Mutex
dirs []string
at time.Time
}
// LoginPath is the PATH a terminal opened now has — the login shell's — for
// telling whether a command an agent runs by name is found there, which
// the app's own PATH can't: UserPath adds folders the shell may not have.
// nil when the shell doesn't say; asked again after a minute.
func LoginPath() []string {
login.Lock()
defer login.Unlock()
if login.dirs != nil && time.Since(login.at) < time.Minute {
return login.dirs
}
p := shellPath()
if p == "" {
return nil
}
login.dirs, login.at = filepath.SplitList(p), time.Now()
return login.dirs
}
// 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.
func UserBinDirs() []string { return userDirs(true) }
func userDirs(everyNode bool) []string {
home, _ := os.UserHomeDir()
var known []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
}
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, "/opt/homebrew/bin", "/usr/local/bin")
var have []string
for _, d := range known {
if st, err := os.Stat(d); d != "" && err == nil && st.IsDir() {
have = append(have, d)
}
}
return have
}
// npmPrefix is the bin folder of the npm prefix ~/.npmrc names, "" when it
// names none.
func npmPrefix(home string) string {
b, err := os.ReadFile(filepath.Join(home, ".npmrc"))
if err != nil {
return ""
}
for _, line := range strings.Split(string(b), "\n") {
k, v, ok := strings.Cut(line, "=")
if !ok || strings.TrimSpace(k) != "prefix" {
continue
}
v = strings.Trim(strings.TrimSpace(v), `"'`)
if strings.HasPrefix(v, "~/") {
v = filepath.Join(home, v[2:])
}
if filepath.IsAbs(v) {
return filepath.Join(v, "bin")
}
}
return ""
}
// shellPath asks the user's login shell for its PATH; "" when it can't say
// within a few seconds.
func shellPath() string {
sh := os.Getenv("SHELL")
if sh == "" || !filepath.IsAbs(sh) {
sh = "/bin/zsh"
if _, err := os.Stat(sh); err != nil {
sh = "/bin/sh"
}
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// interactive too, since many put PATH in .zshrc/.bashrc; the marker
// tells PATH apart from whatever the profile prints
const mark = "__magpie_path__"
cmd := CommandContext(ctx, sh, "-ilc", "printf '"+mark+"%s"+mark+"' \"$PATH\"")
cmd.Stdin = nil
out, _ := cmd.Output()
s := string(out)
i := strings.Index(s, mark)
if i < 0 {
return ""
}
s = s[i+len(mark):]
j := strings.Index(s, mark)
if j < 0 {
return ""
}
return s[:j]
}
// 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)))
}