From 1bf722e289350471c298862dca3bfc999f7ed3ad Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 12 Oct 2026 19:12:32 +0800 Subject: [PATCH] proc, provider, agent: a claude (or other agent CLI) that is a mise wrapper script is run as the program mise names, and a Claude sign-in that gets no link says which program it ran (deluxe on Discord) deluxe (Omarchy Linux, magpie started from the desktop) never saw the Claude sign-in link. ~/.local/bin/claude was a script ending `exec mise x "claude" -- "claude" "$@"`; without the shell's mise environment, `mise x` looks claude up on PATH, finds the same script (~/.local/bin is before mise's shims) and it runs itself for ever. What changed: - proc.Unwrap / proc.LookPath (internal/proc/wrapper.go): a small #! script whose line is `[exec] mise|rtx x|exec [opts] [tool] -- ` is resolved with `mise which ` (then `mise which --tool `), run as a probe (process group killed) with a 5s timeout, magpie's environment and the home folder as cwd. The answer must be an executable file that isn't the wrapper or another wrapper; otherwise, or with no mise, the old path is kept. Answers are cached per file (path, mtime, size); a failed ask is retried after a minute. Windows is unchanged. - proc.FindTool (claude via claudecode.Find: the sign-in, the gateway's Claude subscription, `magpie claude-code`) unwraps what it finds. - The siblings that looked an agent CLI up with exec.LookPath use proc.LookPath: agent.binAt (detection, CLI version/update), codex, kiro-cli, devin, cursor-agent, Air's opencode, nativemodels' npm package lookup. - The Claude sign-in already gave up after linkWait (30s) with "claude auth login gave no link to open". It now adds the last line the CLI printed, or, when it printed nothing, the program it ran and to run ` auth login` in a terminal to see what it does. asdf shims (`exec asdf exec "claude" "$@"`) are left alone: asdf exec resolves the real program itself and doesn't recurse. Verified (macOS, sandbox HOME, Go caches pinned): - New tests: internal/proc/wrapper_test.go (wrapper -> mise's program; no mise -> wrapper; mise fails / names the wrapper / names a folder / hangs -> wrapper, and the hung mise's pid is gone; deluxe's own fixed script, a node launcher, a wrapper of another command, a commented line -> unchanged and mise never asked; parse cases; --tool retry), internal/provider/signin_claude_wrapper_test.go (the full Claude sign-in through the wrapper with a fake mise that really recurses: link shown, account added; with no `mise which`, the sign-in fails in linkWait naming the wrapper). - Break checks: with find.go put back, TestFindToolUnwrapsMiseWrapper and TestFindToolAsksWithWrappersTool FAIL (FindTool = the wrapper), and TestClaudeSignInThroughMiseWrapper FAILs with "claude auth login gave no link to open: .../local-bin/claude printed nothing in 5s". With the old error string, TestClaudeSignInWrapperThatNeverStarts FAILs. - gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; GOOS=linux go build -tags nogui; GOOS=windows go build. - go test -tags nogui ./...: every package ok except internal/agent and internal/gateway, which hit the default 10m timeout with the machine at load ~45 (different tests each run, none in the new code). Those two were rerun with -timeout 40m; origin/main 217d2f8f2's internal/agent alone took 2094s under the same load. - Rebased on 9964535ad, -timeout 40m: internal/agent ok (1689s), internal/proc ok, internal/provider ok (681s), internal/claudecode ok; internal/gateway FAIL in one test, TestCodexHeardWithinItsIdleTimeout (3.78s against its 3s wall-clock bound, body right, no retry taken). Alone with -count=5 it passes 5 of 5. Filed as #1800; unrelated to binary lookup. Not verified: no real mise or the reporter's Omarchy machine; the fake mise stands in for mise's which/x. The wrapper fixture is the line the reporter quoted, not their whole file. --- internal/agent/agent.go | 6 +- internal/agent/air.go | 4 +- internal/agent/nativemodels.go | 4 +- internal/proc/find.go | 8 +- internal/proc/wrapper.go | 252 ++++++++++++++++++ internal/proc/wrapper_test.go | 229 ++++++++++++++++ internal/provider/claude_signin.go | 31 ++- internal/provider/codex_models.go | 3 +- internal/provider/cursor.go | 3 +- internal/provider/devin.go | 3 +- internal/provider/kiro.go | 3 +- .../provider/signin_claude_wrapper_test.go | 96 +++++++ 12 files changed, 623 insertions(+), 19 deletions(-) create mode 100644 internal/proc/wrapper.go create mode 100644 internal/proc/wrapper_test.go create mode 100644 internal/provider/signin_claude_wrapper_test.go diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 90d7d352c..09cbf2a54 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -6,7 +6,6 @@ import ( "debug/buildinfo" "fmt" "os" - "os/exec" "path/filepath" "runtime" "slices" @@ -306,9 +305,10 @@ func (a *Agent) Detected() bool { // started before Claude Code's installer put claude.exe in ~/.local/bin // and added that to the user's PATH, or a self-update restarting with the // PATH it had then, never listed it, while the sign-in, which asked -// FindTool, found it (#839, #1482). "" when it is in none. +// FindTool, found it (#839, #1482). A mise wrapper script found there is +// given as the program it runs (proc.LookPath). "" when it is in none. func binAt(name string) string { - if p, err := exec.LookPath(name); err == nil { + if p, err := proc.LookPath(name); err == nil { return p } if runtime.GOOS == "windows" { diff --git a/internal/agent/air.go b/internal/agent/air.go index f4fdf5f2d..ea6f20582 100644 --- a/internal/agent/air.go +++ b/internal/agent/air.go @@ -33,13 +33,13 @@ package agent import ( "fmt" "os" - "os/exec" "path/filepath" "runtime" "strings" "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/proc" ) // airAgent is the name magpie's agent has in acp.json, and so in Air's @@ -65,7 +65,7 @@ func airDir(home, cfg string) string { // one OpenCode's installer puts in ~/.opencode/bin, as a full path, since // Air, an app, may not have the shell's PATH; "" when there is none. var airOpenCode = func(home string) string { - if p, err := exec.LookPath("opencode"); err == nil { + if p, err := proc.LookPath("opencode"); err == nil { if abs, err := filepath.Abs(p); err == nil { return abs } diff --git a/internal/agent/nativemodels.go b/internal/agent/nativemodels.go index a00825166..7549f5541 100644 --- a/internal/agent/nativemodels.go +++ b/internal/agent/nativemodels.go @@ -4,12 +4,12 @@ import ( "bytes" "encoding/json" "errors" - "os/exec" "path/filepath" "strings" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/filememo" + "github.com/yetone/magpie/internal/proc" ) // A Pi-family agent's built-in providers are the ones its own model @@ -26,7 +26,7 @@ import ( var nodeModulesOf = findNodeModules func findNodeModules(bin string, pkgs []string) []string { - path, err := exec.LookPath(bin) + path, err := proc.LookPath(bin) if err != nil { return nil } diff --git a/internal/proc/find.go b/internal/proc/find.go index 3bb2d9788..ca0449d1f 100644 --- a/internal/proc/find.go +++ b/internal/proc/find.go @@ -13,16 +13,18 @@ import ( // (UserBinDirs), else, on Windows, on the PATH the registry has now, which // a magpie started before the tool was installed doesn't have (#839: the // Claude sign-in said Claude Code wasn't installed, its installer having -// put claude.exe in ~/.local/bin after magpie started). "" when none. +// 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. func FindTool(name string) string { if p, err := exec.LookPath(name); err == nil { - return p + return Unwrap(name, p) } dirs := UserBinDirs() if runtime.GOOS == "windows" { dirs = append(dirs, SystemDirs(LoginPath()...)...) } - return toolIn(name, runtime.GOOS, dirs) + return Unwrap(name, toolIn(name, runtime.GOOS, dirs)) } // sandboxVar is testenv.Marker, which proc can't import: the home a test diff --git a/internal/proc/wrapper.go b/internal/proc/wrapper.go new file mode 100644 index 000000000..19d3089e1 --- /dev/null +++ b/internal/proc/wrapper.go @@ -0,0 +1,252 @@ +package proc + +// A tool's command can be a script of the user's that runs it through a +// version manager: `exec mise x "claude" -- "claude" "$@"` in +// ~/.local/bin/claude. Inside `mise x` the command is looked up on PATH +// again, and with ~/.local/bin before mise's own folders it is that same +// script: it runs itself until killed (deluxe on Discord, Omarchy Linux: a +// magpie started from the desktop, without the shell's mise environment, +// never showed the Claude sign-in link). The program such a script stands +// for is asked of mise, `mise which `, and run directly. + +import ( + "bytes" + "context" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "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 +// isn't here or doesn't say within a few seconds. +func Unwrap(name, path string) string { + if runtime.GOOS == "windows" || path == "" { + return path + } + st, err := os.Stat(path) + if err != nil || st.IsDir() || st.Size() > wrapperMax { + return path + } + key := unwrapKey{path, name, st.ModTime(), st.Size()} + unwrapped.Lock() + if e, ok := unwrapped.m[key]; ok && (e.real != "" || time.Since(e.at) < time.Minute) { + unwrapped.Unlock() + if e.real == "" { + return path + } + return e.real + } + unwrapped.Unlock() + real := "" + if b, err := os.ReadFile(path); err == nil { + if w, ok := parseMiseWrapper(b, name); ok { + real = miseWhich(w, name, path) + } + } + unwrapped.Lock() + unwrapped.m[key] = unwrapEntry{real: real, at: time.Now()} + unwrapped.Unlock() + if real == "" { + return path + } + return real +} + +// wrapperMax is the largest file read as a possible wrapper script; a +// program is bigger. +const wrapperMax = 8 << 10 + +type unwrapKey struct { + path, name string + mod time.Time + size int64 +} + +type unwrapEntry struct { + real string // "" when it isn't a wrapper or mise didn't say + at time.Time +} + +// unwrapped remembers what each file was found to stand for, until it +// changes; a failed ask is made again after a minute. +var unwrapped = struct { + sync.Mutex + m map[unwrapKey]unwrapEntry +}{m: map[unwrapKey]unwrapEntry{}} + +// miseWrapper is what a wrapper script's mise line says. +type miseWrapper struct { + mise string // the manager as the script names it: mise, /usr/bin/mise + tool string // the tool it asks for (`mise x claude@latest -- …`), "" when none +} + +// parseMiseWrapper reads b as a shell script whose line runs name through +// mise: `[exec] mise x|exec [options] [tool…] -- name args…`. A script +// running anything else after `--` (a path, "$bin") isn't one. +func parseMiseWrapper(b []byte, name string) (miseWrapper, bool) { + if !bytes.HasPrefix(b, []byte("#!")) || bytes.IndexByte(b, 0) >= 0 { + return miseWrapper{}, false + } + for _, line := range strings.Split(string(b), "\n") { + f := shellWords(line) + if len(f) > 0 && f[0] == "exec" { + f = f[1:] + } + if len(f) < 4 { + continue + } + if m := filepath.Base(f[0]); m != "mise" && m != "rtx" { + continue + } + if f[1] != "x" && f[1] != "exec" { + continue + } + var tool string + for i := 2; i < len(f); i++ { + if f[i] != "--" { + if !strings.HasPrefix(f[i], "-") { + tool = f[i] + } + continue + } + if i+1 < len(f) && f[i+1] == name { + return miseWrapper{mise: f[0], tool: tool}, true + } + break + } + } + return miseWrapper{}, false +} + +// shellWords splits a script's line into its words, as sh would without +// expanding anything: quotes taken off, a comment dropped. A word holding +// an expansion keeps its `$`, so it never equals a plain name. +func shellWords(line string) []string { + var words []string + var w strings.Builder + in, quote := false, byte(0) + for i := 0; i < len(line); i++ { + c := line[i] + switch { + case quote != 0: + if c == quote { + quote = 0 + } else { + w.WriteByte(c) + } + case c == '\'' || c == '"': + quote, in = c, true + case c == '#' && !in: + i = len(line) + case c == ' ' || c == '\t' || c == '\r' || c == ';': + if in { + words = append(words, w.String()) + w.Reset() + in = false + } + default: + w.WriteByte(c) + in = true + } + } + if in { + words = append(words, w.String()) + } + return words +} + +// miseWait is how long mise is given to say where the program is. +var miseWait = 5 * time.Second + +// miseWhich is the program `mise which name` names, run with magpie's +// environment (the shell's PATH UserPath took) from the home folder, whose +// mise config a terminal reads: with the wrapper's tool when plain +// `mise which` doesn't know it. "" when mise isn't here, fails, or names +// the wrapper itself or another wrapper. +func miseWhich(w miseWrapper, name, wrapper string) string { + mise := findMise(w.mise) + if mise == "" { + return "" + } + asks := [][]string{{"which", name}} + if w.tool != "" && w.tool != name { + asks = append(asks, []string{"which", "--tool", w.tool, name}) + } + home, _ := os.UserHomeDir() + for _, args := range asks { + ctx, cancel := context.WithTimeout(context.Background(), miseWait) + cmd := ProbeContext(ctx, mise, args...) + cmd.Dir = home + out, err := cmd.Output() + cancel() + if err != nil { + continue + } + p := strings.TrimSpace(string(out)) + if i := strings.IndexByte(p, '\n'); i >= 0 { + p = strings.TrimSpace(p[:i]) + } + if usableProgram(p, wrapper, name) { + return p + } + } + return "" +} + +// usableProgram is whether p, as mise named it, is a program to run in the +// wrapper's place: a file that isn't the wrapper, nor a wrapper itself. +func usableProgram(p, wrapper, name string) bool { + if !filepath.IsAbs(p) { + return false + } + st, err := os.Stat(p) + if err != nil || st.IsDir() || st.Mode()&0o111 == 0 { + return false + } + if ws, err := os.Stat(wrapper); err == nil && os.SameFile(st, ws) { + return false + } + if st.Size() <= wrapperMax { + if b, err := os.ReadFile(p); err == nil { + if _, ok := parseMiseWrapper(b, name); ok { + return false + } + } + } + return true +} + +// findMise is the mise a wrapper names: its own path, else mise (or rtx) +// on PATH or in the folders it is installed in. +func findMise(named string) string { + if filepath.IsAbs(named) { + if st, err := os.Stat(named); err == nil && !st.IsDir() { + return named + } + } + for _, n := range []string{filepath.Base(named), "mise"} { + if p, err := exec.LookPath(n); err == nil { + return p + } + if p := toolIn(n, runtime.GOOS, UserBinDirs()); p != "" { + return p + } + } + return "" +} diff --git a/internal/proc/wrapper_test.go b/internal/proc/wrapper_test.go new file mode 100644 index 000000000..4aff124ae --- /dev/null +++ b/internal/proc/wrapper_test.go @@ -0,0 +1,229 @@ +//go:build !windows + +package proc + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/testenv" +) + +// miseWrapperScript is the script deluxe (Discord, Omarchy Linux) had in +// ~/.local/bin/claude: its last line, as they gave it, runs claude +// through mise, and inside `mise x` that is the script again. +const miseWrapperScript = `#!/usr/bin/env bash +# claude, through mise +set -e +exec mise x "claude" -- "claude" "$@" +` + +// wrapperFixture is a machine with the wrapper first on PATH, mise's real +// claude in its installs folder, and, when withMise, a fake mise beside +// which answers `mise which claude` with it and writes down each ask. +type wrapperFixture struct { + dir, wrapper, real, asked string +} + +func newWrapperFixture(t *testing.T, wrapper, mise string) wrapperFixture { + t.Helper() + resetUnwrapped(t) + d := t.TempDir() + f := wrapperFixture{ + dir: d, + wrapper: filepath.Join(d, "local-bin", "claude"), + real: filepath.Join(d, "mise", "installs", "claude", "2.1.0", "bin", "claude"), + asked: filepath.Join(d, "asked"), + } + for _, x := range []string{filepath.Dir(f.wrapper), filepath.Dir(f.real), filepath.Join(d, "mise-bin")} { + if err := os.MkdirAll(x, 0o755); err != nil { + t.Fatal(err) + } + } + testenv.Program(t, f.wrapper, wrapper) + testenv.Program(t, f.real, "#!/bin/sh\necho 2.1.0 '(Claude Code)'\n") + path := filepath.Dir(f.wrapper) + if mise != "" { + mise = strings.NewReplacer("{asked}", f.asked, "{real}", f.real, "{wrapper}", f.wrapper).Replace(mise) + testenv.Program(t, filepath.Join(d, "mise-bin", "mise"), mise) + path += string(os.PathListSeparator) + filepath.Join(d, "mise-bin") + } + // /bin for the scripts' own sh, nothing of the host's mise + t.Setenv("PATH", path+string(os.PathListSeparator)+"/bin") + return f +} + +// fakeMise answers `mise which claude` with the real program; `mise x` +// does what mise does, running the command found on PATH, which is the +// wrapper again. +const fakeMise = `#!/bin/sh +echo "$*" >> '{asked}' +if [ "$1 $2" = "which claude" ]; then echo '{real}'; exit 0; fi +exit 1 +` + +func resetUnwrapped(t *testing.T) { + t.Helper() + clear := func() { + unwrapped.Lock() + unwrapped.m = map[unwrapKey]unwrapEntry{} + unwrapped.Unlock() + } + clear() + t.Cleanup(clear) +} + +func (f wrapperFixture) asks(t *testing.T) string { + t.Helper() + b, _ := os.ReadFile(f.asked) + return string(b) +} + +// The wrapper is run as the program mise says it stands for, which runs +// Claude Code, rather than as itself, which runs itself for ever. +func TestFindToolUnwrapsMiseWrapper(t *testing.T) { + f := newWrapperFixture(t, miseWrapperScript, fakeMise) + if got := FindTool("claude"); got != f.real { + t.Fatalf("FindTool(claude) = %q, want mise's %q", got, f.real) + } + if got, err := LookPath("claude"); err != nil || got != f.real { + t.Fatalf("LookPath(claude) = %q, %v, want %q", got, err, f.real) + } + // asked once; the answer is kept while the wrapper is unchanged + if a := f.asks(t); a != "which claude\n" { + t.Fatalf("mise was asked %q", a) + } +} + +// Without mise to ask, the wrapper is what it was before. +func TestFindToolKeepsWrapperWithoutMise(t *testing.T) { + f := newWrapperFixture(t, miseWrapperScript, "") + if got := FindTool("claude"); got != f.wrapper { + t.Fatalf("FindTool(claude) = %q, want the wrapper %q", got, f.wrapper) + } +} + +// A mise that fails, names the wrapper itself, or doesn't answer leaves +// the wrapper as it was; one that doesn't answer is killed. +func TestFindToolKeepsWrapperWhenMiseDoesntSay(t *testing.T) { + for name, mise := range map[string]string{ + "fails": "#!/bin/sh\necho \"$*\" >> '{asked}'\necho 'mise ERROR claude not installed' >&2\nexit 1\n", + "names it": "#!/bin/sh\necho \"$*\" >> '{asked}'\necho '{wrapper}'\n", + "names a dir": "#!/bin/sh\necho \"$*\" >> '{asked}'\necho /bin\n", + } { + t.Run(name, func(t *testing.T) { + f := newWrapperFixture(t, miseWrapperScript, mise) + if got := FindTool("claude"); got != f.wrapper { + t.Fatalf("FindTool(claude) = %q, want the wrapper %q", got, f.wrapper) + } + if f.asks(t) == "" { + t.Fatal("mise wasn't asked") + } + }) + } + t.Run("hangs", func(t *testing.T) { + was := miseWait + miseWait = 300 * time.Millisecond + t.Cleanup(func() { miseWait = was }) + f := newWrapperFixture(t, miseWrapperScript, "#!/bin/sh\necho $$ > '{asked}'\nexec sleep 60\n") + start := time.Now() + if got := FindTool("claude"); got != f.wrapper { + t.Fatalf("FindTool(claude) = %q, want the wrapper %q", got, f.wrapper) + } + if d := time.Since(start); d > 30*time.Second { + t.Fatalf("waited %s for a mise that doesn't answer", d) + } + pid := strings.TrimSpace(f.asks(t)) + if pid == "" { + t.Fatal("mise wasn't asked") + } + // the ask was killed with its group: nothing of it outlives the test + deadline := time.Now().Add(10 * time.Second) + for alive(pid) { + if time.Now().After(deadline) { + t.Fatalf("mise %s still running", pid) + } + time.Sleep(20 * time.Millisecond) + } + }) +} + +func alive(pid string) bool { + _, err := os.Stat("/proc/" + pid) + if err == nil { + return true + } + if !os.IsNotExist(err) || runtimeHasProcFS() { + return false + } + // no /proc (macOS): ps says + out, _ := Command("ps", "-o", "stat=", "-p", pid).Output() + s := strings.TrimSpace(string(out)) + return s != "" && !strings.HasPrefix(s, "Z") +} + +func runtimeHasProcFS() bool { + _, err := os.Stat("/proc/self") + return err == nil +} + +// A script that isn't such a wrapper is run as it is, and mise isn't +// asked: the user's own fix (the program `mise which` gave, in "$bin"), +// a launcher of node, a program. +func TestFindToolLeavesOtherScripts(t *testing.T) { + for name, script := range map[string]string{ + "deluxe's fix": "#!/usr/bin/env bash\nbin=$(mise which claude) || exit 1\nexec mise x \"claude\" -- \"$bin\" \"$@\"\n", + "node": "#!/bin/sh\nexec node /opt/claude/cli.js \"$@\"\n", + "another tool": "#!/bin/sh\nexec mise x node -- codex \"$@\"\n", + "commented": "#!/bin/sh\n# exec mise x claude -- claude \"$@\"\nexec /opt/claude/claude \"$@\"\n", + } { + t.Run(name, func(t *testing.T) { + f := newWrapperFixture(t, script, fakeMise) + if got := FindTool("claude"); got != f.wrapper { + t.Fatalf("FindTool(claude) = %q, want it as it is, %q", got, f.wrapper) + } + if a := f.asks(t); a != "" { + t.Fatalf("mise was asked %q", a) + } + }) + } +} + +// The ways a wrapper names mise and its command. +func TestParseMiseWrapper(t *testing.T) { + for _, c := range []struct { + script string + ok bool + mise, tool string + }{ + {miseWrapperScript, true, "mise", "claude"}, + {"#!/bin/sh\nexec mise exec claude@latest -- claude \"$@\"\n", true, "mise", "claude@latest"}, + {"#!/bin/sh\nexec /usr/bin/mise x -q 'npm:@anthropic-ai/claude-code' -- 'claude' \"$@\"\n", true, "/usr/bin/mise", "npm:@anthropic-ai/claude-code"}, + {"#!/bin/zsh\n exec rtx x claude -- claude \"$@\" # old name\n", true, "rtx", "claude"}, + {"#!/bin/sh\nmise x -- claude \"$@\"\n", true, "mise", ""}, + {"#!/bin/sh\nexec mise x claude -- /opt/claude \"$@\"\n", false, "", ""}, + {"#!/bin/sh\nexec mise run claude -- claude\n", false, "", ""}, + {"#!/bin/sh\nexec asdf exec \"claude\" \"$@\"\n", false, "", ""}, + } { + w, ok := parseMiseWrapper([]byte(c.script), "claude") + if ok != c.ok || w.mise != c.mise || w.tool != c.tool { + t.Errorf("%q: %+v %v, want %q %q %v", c.script, w, ok, c.mise, c.tool, c.ok) + } + } +} + +// When plain `mise which` doesn't know the command (the tool isn't in the +// home's config), the wrapper's own tool is asked for. +func TestFindToolAsksWithWrappersTool(t *testing.T) { + f := newWrapperFixture(t, "#!/bin/sh\nexec mise x claude@2.1.0 -- claude \"$@\"\n", + "#!/bin/sh\necho \"$*\" >> '{asked}'\n[ \"$*\" = \"which --tool claude@2.1.0 claude\" ] || exit 1\necho '{real}'\n") + if got := FindTool("claude"); got != f.real { + t.Fatalf("FindTool(claude) = %q, want %q", got, f.real) + } + if a := f.asks(t); a != "which claude\nwhich --tool claude@2.1.0 claude\n" { + t.Fatalf("mise was asked %q", a) + } +} diff --git a/internal/provider/claude_signin.go b/internal/provider/claude_signin.go index 29aa524db..2a21961cf 100644 --- a/internal/provider/claude_signin.go +++ b/internal/provider/claude_signin.go @@ -12,6 +12,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "io" "net/http" "net/url" @@ -187,6 +188,7 @@ func startClaudeSignIn(s *signInFlow) error { printed := make(chan string, 1) exited := make(chan string, 1) + var said lastSaid go func() { sc := bufio.NewScanner(out) var tail []string @@ -201,6 +203,7 @@ func startClaudeSignIn(s *signInFlow) error { } if line = strings.TrimSpace(strings.TrimPrefix(line, "Paste code here if prompted >")); line != "" { tail = append(tail, line) + said.set(line) } } err := cmd.Wait() @@ -252,7 +255,7 @@ func startClaudeSignIn(s *signInFlow) error { case <-grace: if link == "" { cancel() - return errors.New("claude auth login gave no link to open") + return claudeNoLink(cli, said.get()) } s.mu.Lock() s.st.URL, s.st.PasteCode = link, true @@ -263,6 +266,32 @@ func startClaudeSignIn(s *signInFlow) error { } } +// lastSaid is the last line a login command printed, which says why +// there's no link. +type lastSaid struct { + mu sync.Mutex + line string +} + +func (l *lastSaid) set(s string) { l.mu.Lock(); l.line = s; l.mu.Unlock() } + +func (l *lastSaid) get() string { l.mu.Lock(); defer l.mu.Unlock(); return l.line } + +// claudeNoLink is the error of a `claude auth login` that gave no link in +// linkWait: what it last printed, or, when it printed nothing at all, the +// program that was run, which may be a script that never starts Claude +// Code (deluxe on Discord: a mise wrapper running itself), and how to see +// what it does. +func claudeNoLink(cli claudeCLI, last string) error { + if last != "" { + return errors.New("claude auth login gave no link to open: " + last) + } + if cli.path == "" { + return fmt.Errorf("claude auth login gave no link to open and printed nothing in %s", linkWait) + } + return fmt.Errorf("claude auth login gave no link to open: %s printed nothing in %s; run `%s auth login` in a terminal to see what it does", cli.path, linkWait, cli.path) +} + // claudeCallbackPort is the port a Claude sign-in page sends the browser // back to on this machine, "" when it sends it elsewhere. func claudeCallbackPort(link string) string { diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.go index 0f4d0e3d8..6e41a8aaf 100644 --- a/internal/provider/codex_models.go +++ b/internal/provider/codex_models.go @@ -10,7 +10,6 @@ import ( "net/http" "net/url" "os" - "os/exec" "path/filepath" "runtime" "slices" @@ -164,7 +163,7 @@ func SawCodexClient(h http.Header) { // PATH it looks where npm, nvm, bun, volta, pnpm, mise and the standalone // installer put it, which a desktop app's PATH lacks. var codexExecutable = func() string { - if p, err := exec.LookPath("codex"); err == nil { + if p, err := proc.LookPath("codex"); err == nil { return p } names := []string{"codex"} diff --git a/internal/provider/cursor.go b/internal/provider/cursor.go index 86fcca473..cf35b5ea8 100644 --- a/internal/provider/cursor.go +++ b/internal/provider/cursor.go @@ -22,7 +22,6 @@ import ( "errors" "net/url" "os" - "os/exec" "path/filepath" "regexp" "runtime" @@ -41,7 +40,7 @@ import ( // CursorExecutable finds the cursor-agent CLI; a var so tests can fake it. var CursorExecutable = func() string { for _, name := range []string{"cursor-agent", "agent"} { - if p, err := exec.LookPath(name); err == nil && (name == "cursor-agent" || isCursorAgent(p)) { + if p, err := proc.LookPath(name); err == nil && (name == "cursor-agent" || isCursorAgent(p)) { return p } } diff --git a/internal/provider/devin.go b/internal/provider/devin.go index 6f309f21c..97561cd8b 100644 --- a/internal/provider/devin.go +++ b/internal/provider/devin.go @@ -20,7 +20,6 @@ import ( "errors" "fmt" "os" - "os/exec" "path/filepath" "regexp" "runtime" @@ -39,7 +38,7 @@ import ( // DevinExecutable finds the devin CLI; a var so tests can fake it. var DevinExecutable = func() string { - if p, err := exec.LookPath("devin"); err == nil { + if p, err := proc.LookPath("devin"); err == nil { return p } home, _ := os.UserHomeDir() diff --git a/internal/provider/kiro.go b/internal/provider/kiro.go index eeaa16c29..8d54f29d3 100644 --- a/internal/provider/kiro.go +++ b/internal/provider/kiro.go @@ -32,7 +32,6 @@ import ( "net/http" "net/url" "os" - "os/exec" "path/filepath" "runtime" "strings" @@ -51,7 +50,7 @@ import ( // tests can fake it. The installer puts it in ~/.local/bin, and on macOS // inside Kiro CLI.app as well. var KiroExecutable = func() string { - if p, err := exec.LookPath("kiro-cli"); err == nil { + if p, err := proc.LookPath("kiro-cli"); err == nil { return p } home, _ := os.UserHomeDir() diff --git a/internal/provider/signin_claude_wrapper_test.go b/internal/provider/signin_claude_wrapper_test.go new file mode 100644 index 000000000..9258092b6 --- /dev/null +++ b/internal/provider/signin_claude_wrapper_test.go @@ -0,0 +1,96 @@ +package provider + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/claudecode" + "github.com/yetone/magpie/internal/testenv" +) + +// miseWrapped puts deluxe's (Discord, Omarchy Linux) ~/.local/bin/claude +// first on PATH: a script ending `exec mise x "claude" -- "claude" "$@"`, +// beside a fake mise which, as mise does, runs the command it finds on +// PATH, so the script runs itself until killed. answers says whether the +// fake answers `mise which claude` with exe, Claude Code itself. The +// Claude found is the one magpie looks up, not a stand-in. +func miseWrapped(t *testing.T, exe string, answers bool) string { + t.Helper() + d := t.TempDir() + bin, miseBin := filepath.Join(d, "local-bin"), filepath.Join(d, "mise-bin") + os.MkdirAll(bin, 0o755) + os.MkdirAll(miseBin, 0o755) + wrapper := filepath.Join(bin, "claude") + testenv.Program(t, wrapper, "#!/bin/sh\nexec mise x \"claude\" -- \"claude\" \"$@\"\n") + which := "exit 1" + if answers { + which = fmt.Sprintf("echo '%s'; exit 0", exe) + } + testenv.Program(t, filepath.Join(miseBin, "mise"), fmt.Sprintf(`#!/bin/sh +if [ "$1 $2" = "which claude" ]; then %s; fi +[ "$1" = x ] || exit 1 +while [ $# -gt 0 ] && [ "$1" != "--" ]; do shift; done +shift +# the test is over: end rather than run on +[ -d '%s' ] || exit 3 +exec "$@" +`, which, d)) + t.Setenv("PATH", bin+string(os.PathListSeparator)+miseBin+string(os.PathListSeparator)+os.Getenv("PATH")) + claudeExecutable = claudecode.Find // fakeClaudeLogin's cleanup puts it back + return wrapper +} + +// The Claude sign-in runs the Claude Code mise names, and its link shows, +// rather than the wrapper, which never starts it. +func TestClaudeSignInThroughMiseWrapper(t *testing.T) { + claudeHome(t) + noAnthropic(t) + exe := fakeClaudeLogin(t, fakeClaudeAccount{email: "mise@example.com", plan: "max", refresh: "sk-ant-ort01-mise"}, "", false) + miseWrapped(t, exe, true) + was := linkWait + linkWait = 5 * time.Second + t.Cleanup(func() { linkWait = was }) + + st, err := StartSignIn("claude") + if err != nil { + t.Fatal(err) + } + if !st.PasteCode || !strings.Contains(st.URL, "platform.claude.com") { + t.Fatalf("state %+v", st) + } + if err := SubmitSignInCallback(st.ID, "the-code#st"); err != nil { + t.Fatal(err) + } + if st = waitDone(t, st.ID); st.State != "done" || st.User != "mise@example.com" { + t.Fatalf("state %+v", st) + } +} + +// When mise can't say, the wrapper is run as before; it prints nothing, +// and the sign-in ends after linkWait saying which program it ran and how +// to see what it does, not waiting for ever. +func TestClaudeSignInWrapperThatNeverStarts(t *testing.T) { + claudeHome(t) + noAnthropic(t) + exe := fakeClaudeLogin(t, fakeClaudeAccount{email: "x@example.com", plan: "pro", refresh: "sk-ant-ort01-x"}, "", false) + wrapper := miseWrapped(t, exe, false) + was := linkWait + linkWait = 2 * time.Second + t.Cleanup(func() { linkWait = was }) + + start := time.Now() + _, err := StartSignIn("claude") + if err == nil { + t.Fatal("signed in through a wrapper that never starts Claude Code") + } + if d := time.Since(start); d > 20*time.Second { + t.Fatalf("took %s", d) + } + if !strings.Contains(err.Error(), wrapper) || !strings.Contains(err.Error(), "printed nothing") || !strings.Contains(err.Error(), "in a terminal") { + t.Fatalf("error %q doesn't name %s and what to do", err, wrapper) + } +}