diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 4a5dd6767..ccca3f4c4 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -7,7 +7,6 @@ import ( "fmt" "io/fs" "os" - "os/exec" "path/filepath" "reflect" "runtime" @@ -19,6 +18,7 @@ import ( "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/sessions" "github.com/yetone/magpie/internal/settings" @@ -1088,7 +1088,7 @@ func gooseIn(at place, cfg string) *Agent { if agentDir(filepath.Dir(path)) { return true } - bin, err := exec.LookPath("goose") + bin, err := proc.Look("goose") return err == nil && !goProgram(bin) }, Fields: []Field{{ diff --git a/internal/agent/cliupdate.go b/internal/agent/cliupdate.go index da4811a5d..90e83f191 100644 --- a/internal/agent/cliupdate.go +++ b/internal/agent/cliupdate.go @@ -16,7 +16,6 @@ import ( "io" "net/http" "os" - "os/exec" "path/filepath" "regexp" "runtime" @@ -206,7 +205,7 @@ func howInstalled(spec cliSpec, bin string) *updater { prefix := slash[:strings.Index(slash, m[0])] brew := filepath.FromSlash(prefix + "/bin/brew") if !isFile(brew) { - if brew, err = exec.LookPath("brew"); err != nil { + if brew, err = proc.Look("brew"); err != nil { return nil } } @@ -242,13 +241,13 @@ func fromNodeModules(pkg, bin, real string) *updater { bun := filepath.Join(filepath.Dir(bin), exe("bun")) if !isFile(bun) { var err error - if bun, err = exec.LookPath("bun"); err != nil { + if bun, err = proc.Look("bun"); err != nil { return nil } } return &updater{via: "bun", pkg: pkg, cmd: []string{bun, "add", "-g", pkg + "@latest"}} case strings.Contains(lower, "/pnpm/") || strings.Contains(lower, "/.pnpm/"): - pnpm, err := exec.LookPath("pnpm") + pnpm, err := proc.Look("pnpm") if err != nil { return nil } @@ -284,7 +283,7 @@ func fromNodeModules(pkg, bin, real string) *updater { u.path = filepath.Dir(npm) // its own node, not another on PATH } else { var err error - if npm, err = exec.LookPath("npm"); err != nil { + if npm, err = proc.Look("npm"); err != nil { return nil } } diff --git a/internal/agent/cliupdate_shim.go b/internal/agent/cliupdate_shim.go index c8d7345ec..e761c4d36 100644 --- a/internal/agent/cliupdate_shim.go +++ b/internal/agent/cliupdate_shim.go @@ -16,7 +16,6 @@ import ( "context" "errors" "os" - "os/exec" "path/filepath" "regexp" "runtime" @@ -114,7 +113,7 @@ func sameFolder(a, b string) bool { // lookTool is name on PATH, else the first of at that is a file. func lookTool(name string, at ...string) string { - if p, err := exec.LookPath(name); err == nil { + if p, err := proc.Look(name); err == nil { return p } for _, p := range at { diff --git a/internal/agent/gemini.go b/internal/agent/gemini.go index f6e3fbc34..3f5e526eb 100644 --- a/internal/agent/gemini.go +++ b/internal/agent/gemini.go @@ -2,12 +2,12 @@ package agent import ( "fmt" - "os/exec" "path/filepath" "strings" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/provider" ) @@ -198,7 +198,7 @@ func geminiIn(at place) *Agent { if Taken(dir) { return false } - _, err := exec.LookPath("gemini") + _, err := proc.Look("gemini") return err == nil }, Check: func() string { diff --git a/internal/agent/install.go b/internal/agent/install.go index b5575ba1b..918f45d7d 100644 --- a/internal/agent/install.go +++ b/internal/agent/install.go @@ -17,7 +17,6 @@ import ( "context" "errors" "os" - "os/exec" "path/filepath" "runtime" "slices" @@ -147,7 +146,7 @@ func npmInstall(pkg, goos string, node bool) InstallCmd { // Homebrew's, …) or, on Windows, in the PATH a terminal opened now has // and in Node.js's installer's own folder. func nodeHere() bool { - if _, err := exec.LookPath("npm"); err == nil { + if _, err := proc.Look("npm"); err == nil { return true } dirs := proc.UserBinDirs() @@ -206,7 +205,7 @@ var npmPrefixes memo // npmGlobalPrefix is where npm install -g puts packages (npm prefix -g), // "" when that isn't known. func npmGlobalPrefix() string { - npm, err := exec.LookPath("npm") + npm, err := proc.Look("npm") if err != nil { npm = filepath.Join(os.Getenv("ProgramFiles"), "nodejs", "npm.cmd") if os.Getenv("ProgramFiles") == "" || !isFile(npm) { diff --git a/internal/agent/reasonix_detect.go b/internal/agent/reasonix_detect.go index 347cd3cf5..45e39ba97 100644 --- a/internal/agent/reasonix_detect.go +++ b/internal/agent/reasonix_detect.go @@ -4,7 +4,6 @@ import ( "context" "debug/buildinfo" "os" - "os/exec" "path/filepath" "runtime" "strings" @@ -31,7 +30,7 @@ func reasonixDetected(home string) bool { } case "linux": for _, bin := range []string{"reasonix-studio", "reasonix-studio-electron"} { - if path, err := exec.LookPath(bin); err == nil { + if path, err := proc.Look(bin); err == nil { if resolved, err := filepath.EvalSymlinks(path); err == nil { path = resolved } @@ -41,7 +40,7 @@ func reasonixDetected(home string) bool { } } } - path, err := exec.LookPath("reasonix") + path, err := proc.Look("reasonix") return err == nil && reasonixCLI(path) } diff --git a/internal/agent/rescan.go b/internal/agent/rescan.go index ed0d5d47f..5fcc8d8d7 100644 --- a/internal/agent/rescan.go +++ b/internal/agent/rescan.go @@ -1,6 +1,10 @@ package agent -import "time" +import ( + "time" + + "github.com/yetone/magpie/internal/proc" +) // Rescan forgets what was found of the agents on this machine a while ago, // so the next read of them looks again at once: the reader asked for it with @@ -8,8 +12,10 @@ import "time" // removed one, or changed its settings outside magpie. What is read from an // agent's files every time needs nothing forgotten; these are the answers // kept for a while because asking was slow (the apps folder, wsl.exe, Alma's -// server). +// server), and where each command was found on PATH (proc.LookPath). func Rescan() { + proc.Forget() + cursorLocalSeen.Lock() cursorLocalSeen.at = time.Time{} cursorLocalSeen.Unlock() diff --git a/internal/agent/vscode.go b/internal/agent/vscode.go index 30082d84c..64b12b139 100644 --- a/internal/agent/vscode.go +++ b/internal/agent/vscode.go @@ -31,7 +31,6 @@ package agent import ( "encoding/json" "os" - "os/exec" "path/filepath" "runtime" "strconv" @@ -40,6 +39,7 @@ import ( "github.com/tidwall/gjson" "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/proc" ) // vscodeDefault is chat.defaultModel, a key with a dot in it, escaped for @@ -215,7 +215,7 @@ func vscodeKindAt(k vscodeKind, dir string) *Agent { if isDir(dir) { return true } - bin, err := exec.LookPath(k.bin) + bin, err := proc.Look(k.bin) return err == nil && vscodeCodeBinary(bin) }, Notice: func() string { diff --git a/internal/agent/zed_credential_other.go b/internal/agent/zed_credential_other.go index 2f5687582..926d4331d 100644 --- a/internal/agent/zed_credential_other.go +++ b/internal/agent/zed_credential_other.go @@ -6,7 +6,6 @@ import ( "context" "fmt" "os" - "os/exec" "path/filepath" "runtime" "strings" @@ -89,7 +88,7 @@ func executablePath(name string) (string, error) { } return name, nil } - return exec.LookPath(name) + return proc.Look(name) } const secretService = "org.freedesktop.Secret.Service" diff --git a/internal/library/rtk.go b/internal/library/rtk.go index 136c7a83d..bc92942d7 100644 --- a/internal/library/rtk.go +++ b/internal/library/rtk.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "os" - "os/exec" "path/filepath" "regexp" "runtime" @@ -271,7 +270,7 @@ var openCodeVersion = func() string { if runtime.GOOS == "windows" { name = "opencode.exe" } - bin, err := exec.LookPath("opencode") + bin, err := proc.Look("opencode") if err != nil { bin = filepath.Join(home(), ".opencode", "bin", name) if !exists(bin) { @@ -547,7 +546,7 @@ var rtkMu sync.Mutex // winget could make the link. Found there, it may not be on the PATH the // agents get: see rtkReached. func rtkPath() string { - if p, err := exec.LookPath("rtk"); err == nil { + if p, err := proc.Look("rtk"); err == nil { return p } name, dirs := "rtk", []string{filepath.Join(home(), ".local", "bin"), filepath.Join(home(), ".cargo", "bin")} @@ -856,15 +855,15 @@ const rtkScript = "https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/maste // one, winget on Windows, else rtk's own script; nil when there's no way. func rtkInstaller() []string { if runtime.GOOS == "windows" { - if _, err := exec.LookPath("winget"); err == nil { + if _, err := proc.Look("winget"); err == nil { return []string{"winget", "install", "--id", "rtk-ai.rtk", "--exact", "--silent", "--accept-package-agreements", "--accept-source-agreements", "--disable-interactivity"} } return nil } - if _, err := exec.LookPath("brew"); err == nil { + if _, err := proc.Look("brew"); err == nil { return []string{"brew", "install", "rtk"} } - if _, err := exec.LookPath("curl"); err == nil { + if _, err := proc.Look("curl"); err == nil { return []string{"sh", "-c", "curl -fsSL " + rtkScript + " | sh"} } return nil diff --git a/internal/proc/find.go b/internal/proc/find.go index ca0449d1f..b1b92922e 100644 --- a/internal/proc/find.go +++ b/internal/proc/find.go @@ -15,16 +15,16 @@ import ( // Claude sign-in said Claude Code wasn't installed, its installer having // put claude.exe in ~/.local/bin after magpie started). A version // manager's wrapper script found there is given as the program it runs -// (Unwrap). "" when none. +// (Unwrap). "" when none. Where it is on PATH is kept while those folders +// are unchanged (LookPath); Unwrap keeps its own answer by the script's +// size and time. func FindTool(name string) string { - if p, err := exec.LookPath(name); err == nil { - return Unwrap(name, p) - } - dirs := UserBinDirs() - if runtime.GOOS == "windows" { - dirs = append(dirs, SystemDirs(LoginPath()...)...) - } - return Unwrap(name, toolIn(name, runtime.GOOS, dirs)) + return Unwrap(name, looked("find\x00"+name, func() lookAnswer { + if p, err := exec.LookPath(name); err == nil { + return lookAnswer{path: p} + } + return lookAnswer{path: toolIn(name, runtime.GOOS, findDirs())} + }).path) } // sandboxVar is testenv.Marker, which proc can't import: the home a test diff --git a/internal/proc/look.go b/internal/proc/look.go new file mode 100644 index 000000000..92b86fd72 --- /dev/null +++ b/internal/proc/look.go @@ -0,0 +1,147 @@ +package proc + +import ( + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "time" +) + +// Looking a command up on PATH stats every candidate name in every PATH +// folder: on Windows 47 folders × PATHEXT's 11 extensions took 111ms for +// one that isn't there, and the pages asked once per known agent (59) and +// once per Pi session (297) on every request, so every page's first load +// took seconds and Sessions half a minute (#1771). LookPath and FindTool +// keep their answers while the folders they look in are unchanged: a tool +// installed or removed changes its folder's modification time, a changed +// PATH is another key, and Forget (the Agents page's refresh) looks again +// at once. + +// lookFresh is how long the folders' stamp is trusted before it is taken +// again; within it an answer kept is given without a stat. +const lookFresh = 2 * time.Second + +// lookFreshInTests is lookFresh in a test binary testenv isolated: none, +// so a test that installs a tool finds it at once, unless a test says. +var lookFreshInTests time.Duration + +var looks struct { + sync.Mutex + gen int + env string // PATH and PATHEXT the stamp was taken with + stamp string + checked time.Time + m map[string]lookAnswer +} + +type lookAnswer struct { + path string + err error +} + +// LookPath is exec.LookPath, with a version manager's wrapper script found +// there given as the program it runs (Unwrap). Where it is on PATH is kept +// while the PATH folders are unchanged (Look); Unwrap keeps its own answer +// by the script's size and time. +func LookPath(name string) (string, error) { + p, err := Look(name) + if err != nil { + return p, err + } + return Unwrap(name, p), nil +} + +// Look is exec.LookPath as it is, a wrapper script given as itself, the +// answer kept while the PATH folders are unchanged. +func Look(name string) (string, error) { + a := looked("look\x00"+name, func() lookAnswer { + p, err := exec.LookPath(name) + return lookAnswer{p, err} + }) + return a.path, a.err +} + +// Forget drops every answer kept by LookPath and FindTool, so the next +// asks again: the reader asked to look for agents again. +func Forget() { + looks.Lock() + looks.m, looks.env, looks.stamp, looks.checked = nil, "", "", time.Time{} + looks.gen++ + looks.Unlock() +} + +// looked is the answer kept for key, or ask's, kept. +func looked(key string, ask func() lookAnswer) lookAnswer { + env := os.Getenv("PATH") + "\x00" + os.Getenv("PATHEXT") + looks.Lock() + if looks.env != env || looks.checked.IsZero() || time.Since(looks.checked) >= lookWindow() { + looks.Unlock() + stamp := lookStamp() // a few stats, not under the lock + looks.Lock() + if stamp != looks.stamp { + looks.m, looks.stamp = nil, stamp + } + looks.env, looks.checked = env, time.Now() + } + if a, ok := looks.m[key]; ok { + looks.Unlock() + return a + } + gen, stamp := looks.gen, looks.stamp + looks.Unlock() + a := ask() + looks.Lock() + // an answer asked across a Forget or a change of the folders isn't kept + if looks.gen == gen && looks.stamp == stamp { + if looks.m == nil { + looks.m = map[string]lookAnswer{} + } + looks.m[key] = a + } + looks.Unlock() + return a +} + +// lookWindow is lookFresh, or lookFreshInTests in a test binary. +func lookWindow() time.Duration { + if os.Getenv(sandboxVar) != "" { + return lookFreshInTests + } + return lookFresh +} + +// lookStamp names what the answers depend on: PATH, PATHEXT, and each +// folder looked in with its modification time. +func lookStamp() string { + var b strings.Builder + b.WriteString(os.Getenv("PATH")) + b.WriteByte(0) + b.WriteString(os.Getenv("PATHEXT")) + dirs := filepath.SplitList(os.Getenv("PATH")) + dirs = append(dirs, findDirs()...) + for _, d := range dirs { + if d == "" { + continue + } + b.WriteByte(0) + b.WriteString(d) + if st, err := os.Stat(d); err == nil { + b.WriteByte('@') + b.WriteString(strconv.FormatInt(st.ModTime().UnixNano(), 36)) + } + } + return b.String() +} + +// findDirs are the folders FindTool looks in after PATH. +func findDirs() []string { + dirs := UserBinDirs() + if runtime.GOOS == "windows" { + dirs = append(dirs, SystemDirs(LoginPath()...)...) + } + return dirs +} diff --git a/internal/proc/look_test.go b/internal/proc/look_test.go new file mode 100644 index 000000000..ca87da5e4 --- /dev/null +++ b/internal/proc/look_test.go @@ -0,0 +1,134 @@ +package proc + +import ( + "os" + "path/filepath" + "runtime" + "sync" + "testing" + "time" +) + +// installTool writes an executable name into dir, as an installer would. +func installTool(t *testing.T, dir, name string) string { + t.Helper() + if runtime.GOOS == "windows" { + name += ".exe" + } + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + return p +} + +// lookWindowFor sets the window a test binary trusts the folders' stamp +// for, as the app does (lookFresh), and puts it back after. +func lookWindowFor(t *testing.T, d time.Duration) { + old := lookFreshInTests + lookFreshInTests = d + Forget() + t.Cleanup(func() { lookFreshInTests = old; Forget() }) +} + +// A command looked up again while PATH's folders are unchanged isn't +// looked for again: every page asked once per agent and once per Pi +// session, each miss 111ms of stats on a Windows PATH of 47 folders, so +// pages took seconds and Sessions half a minute (#1771). +func TestLookPathAsksOnceWhileFoldersAreUnchanged(t *testing.T) { + dir := t.TempDir() + t.Setenv("PATH", dir) + // within the app's window, and past it with the folders unchanged + for _, window := range []time.Duration{lookFresh, 0} { + lookWindowFor(t, window) + asks := 0 + for i := 0; i < 300; i++ { + looked("look\x00omp", func() lookAnswer { asks++; return lookAnswer{} }) + } + if asks != 1 { + t.Fatalf("window %v: 300 lookups of one command asked %d times, want 1", window, asks) + } + } +} + +// A tool installed or removed is seen at the next lookup once the stamp is +// taken again: its folder's modification time changed. +func TestLookPathSeesAnInstallAndARemoval(t *testing.T) { + dir := t.TempDir() + t.Setenv("PATH", dir) + lookWindowFor(t, 0) + if p, err := LookPath("magpie-fake-agent"); err == nil { + t.Fatalf("found %q before it was installed", p) + } + if p := FindTool("magpie-fake-agent"); p != "" { + t.Fatalf("FindTool found %q before it was installed", p) + } + time.Sleep(20 * time.Millisecond) // a folder time a coarse clock tells apart + want := installTool(t, dir, "magpie-fake-agent") + if p, err := LookPath("magpie-fake-agent"); err != nil || p != want { + t.Fatalf("after installing: %q, %v; want %q", p, err, want) + } + if p := FindTool("magpie-fake-agent"); p != want { + t.Fatalf("FindTool after installing: %q, want %q", p, want) + } + time.Sleep(20 * time.Millisecond) + os.Remove(want) + if p, err := LookPath("magpie-fake-agent"); err == nil { + t.Fatalf("after removing it, still found %q", p) + } + if p := FindTool("magpie-fake-agent"); p != "" { + t.Fatalf("FindTool after removing it, still found %q", p) + } +} + +// Within the app's window an answer is kept without a stat; a changed PATH +// is asked about at once, and so is everything after Forget (the Agents +// page's "Look again"). +func TestLookPathWindowPathAndForget(t *testing.T) { + a, b := t.TempDir(), t.TempDir() + t.Setenv("PATH", a) + lookWindowFor(t, time.Hour) + if _, err := LookPath("magpie-fake-agent"); err == nil { + t.Fatal("found before installing") + } + inA := installTool(t, a, "magpie-fake-agent") + if p, err := LookPath("magpie-fake-agent"); err == nil { + t.Fatalf("within the window the miss is kept, found %q", p) + } + Forget() + if p, err := LookPath("magpie-fake-agent"); err != nil || p != inA { + t.Fatalf("after Forget: %q, %v; want %q", p, err, inA) + } + + inB := installTool(t, b, "magpie-fake-agent") + t.Setenv("PATH", b+string(os.PathListSeparator)+a) + if p, err := LookPath("magpie-fake-agent"); err != nil || p != inB { + t.Fatalf("after PATH changed: %q, %v; want %q", p, err, inB) + } +} + +// Lookups from many requests at once, with Forget among them, are safe. +func TestLookPathConcurrent(t *testing.T) { + dir := t.TempDir() + t.Setenv("PATH", dir) + installTool(t, dir, "magpie-fake-agent") + lookWindowFor(t, 0) + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + for j := 0; j < 50; j++ { + if i == 0 && j%10 == 0 { + Forget() + } + if _, err := LookPath("magpie-fake-agent"); err != nil { + t.Error(err) + return + } + FindTool("magpie-no-such-tool") + } + }(i) + } + wg.Wait() +} diff --git a/internal/proc/wrapper.go b/internal/proc/wrapper.go index 19d3089e1..c24b31d80 100644 --- a/internal/proc/wrapper.go +++ b/internal/proc/wrapper.go @@ -21,16 +21,6 @@ import ( "time" ) -// LookPath is exec.LookPath, with a version manager's wrapper script found -// there given as the program it runs (Unwrap). -func LookPath(name string) (string, error) { - p, err := exec.LookPath(name) - if err != nil { - return p, err - } - return Unwrap(name, p), nil -} - // Unwrap is the program path stands for when it is a small script that // runs name through mise (`mise x … -- name`, `mise exec`, rtx's old // name): what `mise which name` says. path itself otherwise, and when mise diff --git a/internal/sessions/carry.go b/internal/sessions/carry.go index 9fc812a01..341a34e7b 100644 --- a/internal/sessions/carry.go +++ b/internal/sessions/carry.go @@ -14,9 +14,10 @@ package sessions import ( "os" - "os/exec" "runtime" "strings" + + "github.com/yetone/magpie/internal/proc" ) // Carry is another agent a session can be carried on in, and the shell @@ -29,7 +30,7 @@ type Carry struct { // ompThere says whether oh-my-pi is installed: its command, or its folder. // A var so tests can say. var ompThere = func() bool { - if _, err := exec.LookPath("omp"); err == nil { + if _, err := proc.Look("omp"); err == nil { return true } _, err := os.Stat(OmpDir())