agent, proc: where each command is on PATH is looked up once while its folders are unchanged, so a Windows page doesn't stat PATH per agent and per session (#1771)

oxyuan profiled every page's first load on Windows at seconds (4-7s), and
Sessions, Usage → Sessions and Context at 26-45s: 96-98% of the samples
were os.Stat under exec.LookPath and proc.FindTool. A failed lookup stats
every PATHEXT candidate in every PATH folder (111ms there), and the pages
asked once per known agent (Detected → binAt) and once per Pi session
(sessions.carries → ompThere) on every request.

proc.Look (new, look.go) is exec.LookPath with its answers kept. The
proc.LookPath that 1bf722e28 added (exec.LookPath, then Unwrap of a mise
wrapper script) is now Look then Unwrap, and FindTool keeps its PATH
answer the same way before Unwrap. Unwrap keeps its own answer by the
script's size and time, and on Windows it returns at once. The PATH
answers are keyed on PATH and PATHEXT,
and dropped when a looked-in folder's modification time changes (an
install or removal), checked at most every 2s, every time in a test binary
testenv isolated. proc.Forget drops them all and agent.Rescan (the Agents
page's refresh) calls it. Every exec.LookPath that a page or the gateway
reaches now goes through one of them. The sites 1bf722e28 made unwrap keep
LookPath: agent (agent, air, nativemodels) and provider (codex models,
cursor, devin, kiro). The rest keep exec.LookPath's answer as it was,
through Look: agent (agents, cliupdate, the shim, gemini, install,
reasonix, vscode, zed), sessions/carry and library/rtk. Those left
on exec.LookPath run once per user action (update's pkexec, the
secret-tool read, installers, rtk upgrade) or in tests.

Run:
- look_test.go: asks once while folders are unchanged, sees an install and
  a removal, a changed PATH and Forget, concurrent lookups under -race. The
  first goes red with LookPath calling exec.LookPath directly.
- On the Windows box (yeton@10.0.0.132, amd64 probe, sandbox USERPROFILE):
  Detected with 4 agents 252ms → 7ms per call after the first, 297x
  LookPath(omp) 879ms → 1.1ms; drift over Detected 274ms → 42ms; Titles
  for 6 sessions 23ms → 4ms. The first call is the same (it looks).
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., sandboxed go test ./... at the rebased head.
Not run: the reporter's own machine (47 PATH folders, 59 agents).
This commit is contained in:
yetone
2026-10-12 22:55:22 +08:00
parent f36e744c30
commit 8bfe33f1f4
15 changed files with 322 additions and 50 deletions
+2 -2
View File
@@ -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{{
+4 -5
View File
@@ -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
}
}
+1 -2
View File
@@ -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 {
+2 -2
View File
@@ -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 {
+2 -3
View File
@@ -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) {
+2 -3
View File
@@ -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)
}
+8 -2
View File
@@ -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()
+2 -2
View File
@@ -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 {
+1 -2
View File
@@ -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"
+5 -6
View File
@@ -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
+9 -9
View File
@@ -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
+147
View File
@@ -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
}
+134
View File
@@ -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()
}
-10
View File
@@ -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
+3 -2
View File
@@ -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())