diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index edbed9565..9c048638a 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -10,7 +10,7 @@ meet it. ## Which Claude Code runs `claudeBinary` (and the sign-in's `claudeExecutable`) take -`claudecode.Find`: the machine's own `claude` (`proc.FindTool`), else the +`claudecode.Find`: the machine's own `claude` (`claudecode.Own`), else the one `magpie claude-code install` downloaded into `/claude-code//` (`internal/claudecode`), else, on Windows, one in WSL. The download is Anthropic's native build from @@ -32,6 +32,24 @@ magpie downloaded none, when the machine has its own `claude`, or when download stayed at its first version across image updates). A failed look keeps the download as it is and is logged. +When the machine has more than one `claude` (`proc.FindTools`: every +folder of PATH, then where installers put it), `claudecode.Own` runs the +newest: an old npm install first on PATH and the one `claude update` +updated after it (zi_xiang5806 on X) ran 2.1.38, which has no +`auth login --claudeai`. The first is passed over only for one whose +version is known and newer; a version that can't be read is unknown, not +old. Each version is first read where it is installed, running nothing +(`installedVersion`: npm's package.json, the native installer's +`versions/`, Homebrew's `Caskroom/claude-code/`). Only +when one is known that way is another asked with `--version` +(`VersionOf`, kept per file until it changes, an unreadable one for a +minute); with none known, or one `claude`, nothing is run, so a script +named `claude` (a test's fake) is never run for its version. The +Agents page still shows the first on PATH, the one a terminal runs. A +sign-in whose Claude Code says "unknown option" or "unknown command" says +it is too old, with its version and path, and how to update it +(`claudeTooOld`). + A run is started with `--dangerously-skip-permissions` (`claudeCLIArgs`): its only tools are magpie's MCP ones, answered by the client, and Anthropic's web search. Claude Code run as root refuses that flag ("cannot diff --git a/internal/claudecode/claudecode.go b/internal/claudecode/claudecode.go index addbabbcf..bce568b6a 100644 --- a/internal/claudecode/claudecode.go +++ b/internal/claudecode/claudecode.go @@ -34,7 +34,6 @@ import ( "github.com/yetone/magpie/internal/lazyre" "github.com/yetone/magpie/internal/libc" "github.com/yetone/magpie/internal/netproxy" - "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/stall" ) @@ -92,10 +91,10 @@ func newer(a, b string) bool { } // Find is the Claude Code to run on this machine: the user's own (on PATH -// or where its installers put it, proc.FindTool), else the one magpie -// downloaded; "" when there is neither. +// or where its installers put it, the newest of them: Own), else the one +// magpie downloaded; "" when there is neither. func Find() string { - if p := proc.FindTool("claude"); p != "" { + if p := Own(); p != "" { return p } p, _ := Downloaded() diff --git a/internal/claudecode/keep.go b/internal/claudecode/keep.go index e543ebcc9..03382ab8d 100644 --- a/internal/claudecode/keep.go +++ b/internal/claudecode/keep.go @@ -6,8 +6,6 @@ import ( "log" "os" "time" - - "github.com/yetone/magpie/internal/proc" ) // When KeepCurrent first looks, and how often after that; vars for tests. @@ -21,7 +19,7 @@ var keep = struct { own func() string latest func(context.Context) (Release, error) }{ - own: func() string { return proc.FindTool("claude") }, + own: Own, latest: Latest, } diff --git a/internal/claudecode/own.go b/internal/claudecode/own.go new file mode 100644 index 000000000..554d3f733 --- /dev/null +++ b/internal/claudecode/own.go @@ -0,0 +1,171 @@ +package claudecode + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/lazyre" + "github.com/yetone/magpie/internal/proc" +) + +// own is what Own reads of the machine; tests stand in for it. +var own = struct { + first func() string // the one a terminal runs (proc.FindTool) + all func() []string // every one (proc.FindTools) + read func(string) string // the version where it is installed, run nothing + version func(string) string // what --version says (proc.Version) +}{ + first: func() string { return proc.FindTool("claude") }, + all: func() []string { return proc.FindTools("claude") }, + read: installedVersion, + version: proc.Version, +} + +// Own is this machine's own Claude Code, the newest of them when it has +// more than one: a machine can have an old one first on PATH and a newer +// one after it, two npm installs in two Node versions, of which `claude +// update` updated the second while `claude` still ran the first +// (zi_xiang5806 on X: magpie's sign-in ran 2.1.38, which has no +// --claudeai). One is passed over only for one whose version is known and +// newer: a version that can't be read is unknown, not old, and the first +// stays when no other is known to be newer. "" when there is none. +func Own() string { + first := own.first() + all := own.all() + if len(all) == 0 || len(all) == 1 && (first == "" || all[0] == first) { + return first + } + cands := make([]string, 0, len(all)+1) + if first != "" { + cands = append(cands, first) + } + for _, p := range all { + if p != first { + cands = append(cands, p) + } + } + // what each is, read where it is installed; one is asked its version + // only when another's is known: with none known there is nothing to + // compare it with, and a program that isn't Claude Code (a test's + // stand-in, a launcher of the user's) is not run for nothing + vers := make([]string, len(cands)) + known := false + for i, p := range cands { + if vers[i] = semverOf(own.read(p)); vers[i] != "" { + known = true + } + } + if !known { + return cands[0] + } + var wg sync.WaitGroup + for i, p := range cands { + if vers[i] != "" { + continue + } + wg.Add(1) + go func() { + defer wg.Done() + vers[i] = VersionOf(p) + }() + } + wg.Wait() + best, bv := cands[0], vers[0] + if bv == "" { + // the first's version is unknown: it stays + return best + } + for i, v := range vers[1:] { + if v != "" && newer(v, bv) { + best, bv = cands[i+1], v + } + } + return best +} + +// semver is a version in what `claude --version` says ("2.1.38 (Claude +// Code)"). +var semver = lazyre.New(`\b(\d+\.\d+\.\d+)\b`) + +func semverOf(s string) string { + if m := semver.FindStringSubmatch(s); m != nil { + return m[1] + } + return "" +} + +// installedVersion is the version of the Claude Code at path as where it +// is installed says, running nothing: an npm install's package.json +// (proc.PackageVersion), the native installer's +// ~/.local/share/claude/versions/, or Homebrew's +// Caskroom/claude-code//. "" when it says none. +func installedVersion(path string) string { + if v := proc.PackageVersion(path); v != "" { + return v + } + real, err := proc.RealPath(path) + if err != nil { + return "" + } + dir, name := filepath.Dir(real), filepath.Base(real) + if filepath.Base(dir) == "versions" && versionRe.MatchString(name) { + return name + } + if parts := strings.Split(filepath.ToSlash(real), "/"); len(parts) >= 3 { + for i := 0; i+2 < len(parts); i++ { + if parts[i] == "Caskroom" && parts[i+1] == "claude-code" && versionRe.MatchString(parts[i+2]) { + return parts[i+2] + } + } + } + return "" +} + +// VersionOf is the version of the Claude Code at path, as `claude +// --version` says it (proc.Version, which reads an npm install's +// package.json rather than run it), "" when it can't be read. Own asks it +// only of one whose version isn't read where it is installed. It is kept +// while the binary is the same file, so asking again costs a stat; one +// that couldn't be read is asked again after a minute. +func VersionOf(path string) string { + if path == "" { + return "" + } + st, err := os.Stat(path) + if err != nil { + return "" + } + real := path + if r, err := proc.RealPath(path); err == nil { + real = r + if rs, err := os.Stat(r); err == nil { + st = rs + } + } + stamp := fmt.Sprint(real, st.Size(), st.ModTime().UnixNano()) + versions.Lock() + e, ok := versions.m[path] + versions.Unlock() + if ok && e.stamp == stamp && (e.v != "" || time.Since(e.at) < time.Minute) { + return e.v + } + v := semverOf(own.version(path)) + versions.Lock() + versions.m[path] = versionEntry{stamp: stamp, v: v, at: time.Now()} + versions.Unlock() + return v +} + +type versionEntry struct { + stamp, v string + at time.Time +} + +var versions = struct { + sync.Mutex + m map[string]versionEntry +}{m: map[string]versionEntry{}} diff --git a/internal/claudecode/own_test.go b/internal/claudecode/own_test.go new file mode 100644 index 000000000..3ddd7de3b --- /dev/null +++ b/internal/claudecode/own_test.go @@ -0,0 +1,195 @@ +package claudecode + +import ( + "os" + "path/filepath" + "runtime" + "sync" + "testing" + "time" +) + +// stubOwn has Own see these Claude Codes, first on PATH first, each of +// the version vers gives ("" for one that can't be read), where it is +// installed and when it is run, and counts the runs. +func stubOwn(t *testing.T, paths []string, vers map[string]string) map[string]int { + t.Helper() + was := own + reads := map[string]int{} + var mu sync.Mutex + own.first = func() string { + if len(paths) == 0 { + return "" + } + return paths[0] + } + own.all = func() []string { return paths } + own.read = func(p string) string { return vers[p] } + own.version = func(p string) string { + mu.Lock() + reads[p]++ + mu.Unlock() + return vers[p] + } + versions.Lock() + versions.m = map[string]versionEntry{} + versions.Unlock() + t.Cleanup(func() { + own = was + versions.Lock() + versions.m = map[string]versionEntry{} + versions.Unlock() + }) + return reads +} + +func programs(t *testing.T, names ...string) []string { + t.Helper() + d := t.TempDir() + var out []string + for _, n := range names { + p := filepath.Join(d, n, "claude") + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + out = append(out, p) + } + return out +} + +// Of two Claude Codes, the newer runs, whichever comes first on PATH +// (zi_xiang5806 on X: 2.1.38 first, 2.1.325 after it); a version that +// can't be read is unknown, never taken for old or new. +func TestOwnIsTheNewest(t *testing.T) { + p := programs(t, "a", "b", "c") + cases := []struct { + name string + vers map[string]string + want string + }{ + {"older first", map[string]string{p[0]: "2.1.38 (Claude Code)", p[1]: "2.1.325 (Claude Code)"}, p[1]}, + {"newer first", map[string]string{p[0]: "2.1.325 (Claude Code)", p[1]: "2.1.38 (Claude Code)"}, p[0]}, + {"newest last", map[string]string{p[0]: "2.1.38", p[1]: "2.1.100", p[2]: "2.1.325"}, p[2]}, + {"same version", map[string]string{p[0]: "2.1.325", p[1]: "2.1.325"}, p[0]}, + {"first unknown", map[string]string{p[1]: "2.1.325"}, p[0]}, + {"other unknown", map[string]string{p[0]: "2.1.38", p[1]: "error: something"}, p[0]}, + {"none known", map[string]string{}, p[0]}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + stubOwn(t, p, c.vers) + if got := Own(); got != c.want { + t.Errorf("Own() = %q, want %q", got, c.want) + } + }) + } +} + +// One Claude Code is run without asking its version, and none is "". +func TestOwnAsksNothingOfOne(t *testing.T) { + p := programs(t, "a") + reads := stubOwn(t, p, map[string]string{p[0]: "2.1.38"}) + if got := Own(); got != p[0] { + t.Errorf("Own() = %q", got) + } + if len(reads) != 0 { + t.Errorf("versions read for one Claude Code: %v", reads) + } + stubOwn(t, nil, nil) + if got := Own(); got != "" { + t.Errorf("Own() with none = %q", got) + } +} + +// A version is read once while the binary is the same file, and again +// when it changes (an update); one that couldn't be read is asked again +// after a minute, not on every look. +func TestOwnVersionIsKept(t *testing.T) { + p := programs(t, "a", "b") + vers := map[string]string{p[0]: "2.1.38", p[1]: ""} + reads := stubOwn(t, p, vers) + // the first's version is where it is installed; the second is run + own.read = func(path string) string { + if path == p[0] { + return "2.1.38" + } + return "" + } + for range 5 { + Own() + } + if reads[p[0]] != 0 || reads[p[1]] != 1 { + t.Fatalf("reads after 5 looks: %v", reads) + } + vers[p[1]] = "2.1.325" + if got := Own(); got != p[0] { + t.Fatalf("an unknown read again before its minute: Own() = %q", got) + } + // the second is updated: a new file + os.WriteFile(p[1], []byte("#!/bin/sh\n# 2.1.325\n"), 0o755) + later := time.Now().Add(time.Second) + os.Chtimes(p[1], later, later) + if got := Own(); got != p[1] { + t.Fatalf("after the update Own() = %q, want %q", got, p[1]) + } + if reads[p[0]] != 0 || reads[p[1]] != 2 { + t.Fatalf("reads: %v", reads) + } +} + +// When no Claude Code's version is known where it is installed, none is +// run to ask it: there is nothing to compare it with, and the first on +// PATH runs (a test's stand-in or fake is never run for its version). +func TestOwnRunsNoneWhenNoneIsKnown(t *testing.T) { + p := programs(t, "a", "b") + reads := stubOwn(t, p, map[string]string{p[0]: "2.1.38", p[1]: "2.1.325"}) + own.read = func(string) string { return "" } + if got := Own(); got != p[0] { + t.Errorf("Own() = %q, want the first", got) + } + if len(reads) != 0 { + t.Errorf("run for their versions: %v", reads) + } +} + +// Where each installer puts Claude Code says its version: npm's +// package.json, the native installer's versions/, Homebrew's +// Caskroom/claude-code/; a script elsewhere says none. +func TestInstalledVersion(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlinks") + } + root := t.TempDir() + write := func(rel, body string) string { + p := filepath.Join(root, rel) + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, []byte(body), 0o755); err != nil { + t.Fatal(err) + } + return p + } + link := func(target, rel string) string { + p := filepath.Join(root, rel) + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.Symlink(target, p); err != nil { + t.Fatal(err) + } + return p + } + cli := write("npm/lib/node_modules/@anthropic-ai/claude-code/cli.js", "#!/usr/bin/env node\n") + write("npm/lib/node_modules/@anthropic-ai/claude-code/package.json", `{"name":"@anthropic-ai/claude-code","version":"2.1.38"}`) + native := write("home/.local/share/claude/versions/2.1.316", "binary") + cask := write("brew/Caskroom/claude-code/2.1.325/claude", "binary") + cases := map[string]string{ + link(cli, "npm/bin/claude"): "2.1.38", + link(native, "home/.local/bin/claude"): "2.1.316", + link(cask, "brew/bin/claude"): "2.1.325", + write("other/claude", "#!/bin/sh\nexit 1\n"): "", + } + for p, want := range cases { + if got := installedVersion(p); got != want { + t.Errorf("installedVersion(%s) = %q, want %q", p, got, want) + } + } +} diff --git a/internal/cli/claude_code_cli.go b/internal/cli/claude_code_cli.go index 312df7a19..352fa951d 100644 --- a/internal/cli/claude_code_cli.go +++ b/internal/cli/claude_code_cli.go @@ -13,7 +13,6 @@ import ( "github.com/yetone/magpie/internal/claudecode" "github.com/yetone/magpie/internal/gateway" - "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/settings" ) @@ -214,7 +213,7 @@ var claudeCode = struct { install func(context.Context, claudecode.Release, func(int64)) (string, error) gateway func() string // the running magpie's gateway, asked for its runs }{ - own: func() string { return proc.FindTool("claude") }, + own: claudecode.Own, downloaded: claudecode.Downloaded, latest: claudecode.Latest, install: claudecode.Install, diff --git a/internal/proc/find.go b/internal/proc/find.go index fafc7d86f..22454dc50 100644 --- a/internal/proc/find.go +++ b/internal/proc/find.go @@ -4,6 +4,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "strings" "github.com/yetone/magpie/internal/lazyre" @@ -140,3 +141,61 @@ func bunBin() string { } return "" } + +// FindTools is every program for the command-line tool name this machine +// has, in the order FindTool ranks them: each of PATH's folders, then the +// folders a user's tools are installed in. One program found twice (a +// link to it in two folders) is given once, where it comes first; a +// version manager's wrapper script is given as the program it runs +// (Unwrap). A machine can have two: a Claude Code installed with npm in +// two Node versions, the first on PATH an old one `claude update` no +// longer reaches (zi_xiang5806 on X). Kept as FindTool's answer is. +func FindTools(name string) []string { + a := looked("findall\x00"+name, func() lookAnswer { + dirs := pathDirs() + if hung := hungDirs(dirs); hung != nil { + dirs = slices.DeleteFunc(slices.Clone(dirs), func(d string) bool { return hung[d] }) + } + var found []string + seen := map[string]bool{} + add := func(p string) { + if p == "" { + return + } + key := p + if r, err := RealPath(p); err == nil { + key = r + } + if !seen[key] { + seen[key] = true + found = append(found, p) + } + } + if mayBeIn(name, dirs) { + for _, d := range dirs { + if d == "" || d == "." { + continue + } + if p, err := execLookPath(filepath.Join(d, name)); err == nil { + add(p) + } + } + } + if more := findDirs(); mayBeIn(name, more) { + for _, d := range more { + add(toolIn(name, runtime.GOOS, []string{d})) + } + } + return lookAnswer{path: strings.Join(found, "\x00")} + }) + if a.path == "" { + return nil + } + var out []string + for _, p := range strings.Split(a.path, "\x00") { + if p = Unwrap(name, p); !slices.Contains(out, p) { + out = append(out, p) + } + } + return out +} diff --git a/internal/proc/find_test.go b/internal/proc/find_test.go index 273cb8036..c3bb9aa76 100644 --- a/internal/proc/find_test.go +++ b/internal/proc/find_test.go @@ -128,3 +128,43 @@ func TestToolInNPMShShimAlone(t *testing.T) { t.Errorf("linux: %q", got) } } + +// Every claude on the machine is found, first on PATH first, one program +// linked from two folders once, and FindTool's is the first of them: an +// old npm install first on PATH and a newer one after it (zi_xiang5806 +// on X) are both there to choose from. +func TestFindTools(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Unix names") + } + d := t.TempDir() + a, b, c := filepath.Join(d, "a"), filepath.Join(d, "b"), filepath.Join(d, "c") + for _, x := range []string{a, b, c} { + os.MkdirAll(x, 0o755) + } + os.WriteFile(filepath.Join(a, "claude"), []byte("#!/bin/sh\n"), 0o755) + os.WriteFile(filepath.Join(b, "claude"), []byte("#!/bin/sh\n"), 0o644) // not a program + os.WriteFile(filepath.Join(c, "claude"), []byte("#!/bin/sh\n# c\n"), 0o755) + os.Symlink(filepath.Join(a, "claude"), filepath.Join(b, "link")) + os.Symlink(filepath.Join(a, "claude"), filepath.Join(c, "claude-a")) + t.Setenv("PATH", strings.Join([]string{a, b, c}, string(os.PathListSeparator))) + Forget() + t.Cleanup(Forget) + want := []string{filepath.Join(a, "claude"), filepath.Join(c, "claude")} + if got := FindTools("claude"); !slices.Equal(got, want) { + t.Errorf("FindTools = %q, want %q", got, want) + } + if got := FindTool("claude"); got != want[0] { + t.Errorf("FindTool = %q, want %q", got, want[0]) + } + // a link in a later folder to the first is the same program + os.Remove(filepath.Join(c, "claude")) + os.Symlink(filepath.Join(a, "claude"), filepath.Join(c, "claude")) + Forget() + if got := FindTools("claude"); !slices.Equal(got, want[:1]) { + t.Errorf("a link to the same program: FindTools = %q", got) + } + if got := FindTools("nope"); got != nil { + t.Errorf("FindTools(nope) = %q", got) + } +} diff --git a/internal/proc/version.go b/internal/proc/version.go index 00fc09536..65368b5c0 100644 --- a/internal/proc/version.go +++ b/internal/proc/version.go @@ -142,3 +142,17 @@ func shimVersion(real string) string { } return p.Version } + +// PackageVersion is the version of the npm package the CLI at bin is a +// file of, or that the npm shim at bin starts, read from its package.json +// without running anything; "" when bin is in no package. +func PackageVersion(bin string) string { + real, err := RealPath(bin) + if err != nil { + real = bin + } + if v := npmVersion(real); v != "" { + return v + } + return shimVersion(real) +} diff --git a/internal/provider/claude_signin.go b/internal/provider/claude_signin.go index 34bc61a58..ce685d4f4 100644 --- a/internal/provider/claude_signin.go +++ b/internal/provider/claude_signin.go @@ -229,6 +229,9 @@ func startClaudeSignIn(s *signInFlow) error { if n := len(tail); n > 0 { msg = tail[n-1] } + if old := claudeTooOld(cli, tail); old != "" { + msg = old + } if err == nil { l, lerr := claudeSignedIn(cli, dir, s.proxy) if lerr == nil { @@ -432,3 +435,31 @@ func (s *signInFlow) claudePaste(raw string) error { } return errors.New("the sign-in was canceled") } + +// claudeTooOld is what a sign-in says when the Claude Code it ran doesn't +// know `auth login --claudeai`: that Claude Code is too old, which one, and +// how to update it, rather than its own "error: unknown option +// '--claudeai'" (zi_xiang5806 on X: 2.1.38 first on PATH). "" when what it +// said is something else. +func claudeTooOld(cli claudeCLI, said []string) string { + var why string + for _, l := range said { + if lo := strings.ToLower(l); strings.Contains(lo, "unknown option") || strings.Contains(lo, "unknown command") { + why = l + break + } + } + if why == "" { + return "" + } + which := "Claude Code" + if cli.wsl != nil { + which += " in WSL (" + cli.wsl.Distro + ")" + } else if cli.path != "" { + if v := claudecode.VersionOf(cli.path); v != "" { + which += " " + v + } + which += " at " + cli.path + } + return fmt.Sprintf("%s is too old to sign in to Claude (it said %q): update it with `claude update`, or `npm install -g @anthropic-ai/claude-code@latest` when npm installed it, then try again", which, why) +} diff --git a/internal/provider/signin_claude_newest_test.go b/internal/provider/signin_claude_newest_test.go new file mode 100644 index 000000000..4089f4670 --- /dev/null +++ b/internal/provider/signin_claude_newest_test.go @@ -0,0 +1,104 @@ +package provider + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/claudecode" + "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/testenv" +) + +// npmClaude installs a Claude Code of version v as npm does in a Node +// version's folder (nvm's layout: bin/claude a link to +// lib/node_modules/@anthropic-ai/claude-code/cli.js beside its +// package.json) and gives bin's folder. cli.js runs body. +func npmClaude(t *testing.T, root, v, body string) string { + t.Helper() + pkg := filepath.Join(root, "lib", "node_modules", "@anthropic-ai", "claude-code") + bin := filepath.Join(root, "bin") + for _, d := range []string{pkg, bin} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(pkg, "package.json"), []byte(`{"name":"@anthropic-ai/claude-code","version":"`+v+`"}`), 0o644); err != nil { + t.Fatal(err) + } + testenv.Program(t, filepath.Join(pkg, "cli.js"), body) + if err := os.Symlink("../lib/node_modules/@anthropic-ai/claude-code/cli.js", filepath.Join(bin, "claude")); err != nil { + t.Fatal(err) + } + return bin +} + +// oldClaude is Claude Code 2.1.38 as zi_xiang5806 (X) had it first on +// PATH: its `auth login` has no --claudeai. +const oldClaude = "#!/bin/sh\n[ \"$1\" = --version ] && { echo '2.1.38 (Claude Code)'; exit 0; }\necho \"error: unknown option '--claudeai'\" >&2\nexit 1\n" + +// claudeOnPath makes PATH these Claude Codes, first to last, and the +// system's own folders (none of the machine's own claude), and has the +// sign-in look Claude Code up as magpie does (claudecode.Find). +func claudeOnPath(t *testing.T, bins ...string) { + t.Helper() + t.Setenv("PATH", strings.Join(append(bins, "/usr/bin", "/bin"), string(os.PathListSeparator))) + proc.Forget() + t.Cleanup(proc.Forget) + old := claudeExecutable + claudeExecutable = claudecode.Find + t.Cleanup(func() { claudeExecutable = old }) +} + +// With two Claude Codes on PATH, an old one first and the one `claude +// update` updated after it, the sign-in runs the newer one and adds the +// account, rather than failing on the old one's unknown --claudeai. +func TestClaudeSignInRunsTheNewestClaudeCode(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("sh scripts and npm's Unix layout") + } + claudeHome(t) + noAnthropic(t) + exe := fakeClaudeLogin(t, fakeClaudeAccount{email: "newest@example.com", plan: "max", refresh: "sk-ant-ort01-newest"}, "", false) + d := t.TempDir() + oldBin := npmClaude(t, filepath.Join(d, "node18"), "2.1.38", oldClaude) + newBin := npmClaude(t, filepath.Join(d, "node22"), "2.1.325", fmt.Sprintf("#!/bin/sh\nexec '%s' \"$@\"\n", exe)) + claudeOnPath(t, oldBin, newBin) + + st, err := StartSignIn("claude") + if err != nil { + t.Fatal(err) + } + if err := SubmitSignInCallback(st.ID, "the-code#st"); err != nil { + t.Fatal(err) + } + if st = waitDone(t, st.ID); st.State != "done" || st.User != "newest@example.com" { + t.Fatalf("state %+v", st) + } +} + +// When the only Claude Code is too old for `auth login --claudeai`, the +// sign-in says so, with its version and where it is, and how to update it. +func TestClaudeSignInSaysClaudeCodeIsTooOld(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("sh scripts and npm's Unix layout") + } + claudeHome(t) + noAnthropic(t) + fakeClaudeLogin(t, fakeClaudeAccount{email: "x@example.com", plan: "pro", refresh: "sk-ant-ort01-x"}, "", false) + oldBin := npmClaude(t, filepath.Join(t.TempDir(), "node18"), "2.1.38", oldClaude) + claudeOnPath(t, oldBin) + + _, err := StartSignIn("claude") + if err == nil { + t.Fatal("signed in through a Claude Code with no --claudeai") + } + for _, want := range []string{"too old", "2.1.38", filepath.Join(oldBin, "claude"), "claude update", "unknown option '--claudeai'"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q doesn't say %q", err, want) + } + } +}