diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 37330935d..04fe66f36 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -646,6 +646,20 @@ as the helper waited, and every try was answered 502 "Claude Code has not answered magpie's initialize request in 10s" (#4504). A helper that answers nothing even then is ended (`tuiNoStart`), and the turn fails saying the interactive mode didn't start; the next turn tries it again. +So does a helper that ends saying why Claude Code didn't come up ("claude-tui: +…"), unless Claude Code ended itself first (`claudetui.EndedEarly`, as one +that can't load its session does): a new Claude Code told the whole +conversation waits on the same thing, and the turn was answered 502 after +twice 45s (sowhynot). `TestClaudeTUINoPromptNotTriedAgain` holds both. +A Claude Code that drew nothing in that time (0 bytes read) is said with +what it runs meanwhile, from `ps` (`undrawn`, macOS and Linux): its +Keychain read of its sign-in, `security find-generic-password`, has no +time limit in Claude Code, and one held by a Keychain window or a locked +keychain is named with what to do; any other command is named by its +program alone, never its arguments. The helper doesn't end early on 0 +bytes: a Keychain window may still be answered, and Claude Code bounds its +own network waits (about 30s) before it draws. +`TestShimSaysWhatAnUndrawnClaudeWaitsOn` holds it. ## Why turns go on in one run diff --git a/internal/claudetui/command.go b/internal/claudetui/command.go index 90c87feef..6175fcfda 100644 --- a/internal/claudetui/command.go +++ b/internal/claudetui/command.go @@ -33,6 +33,14 @@ const DeadlineEnv = "MAGPIE_CLAUDE_TUI_BY" // folder of magpie's. const Untrusted = "Claude Code asks whether to trust the folder" +// EndedEarly begins what the helper says as it ends over a Claude Code +// that ended itself before it showed its prompt, as one that can't load +// the session it was told to go on with does. Every other way the +// interactive mode doesn't come up (no prompt in ReadyWait, a sign-in or +// a question only its user answers) is the same for a new Claude Code +// told the whole conversation: the bridge tries one again only on this. +const EndedEarly = "Claude Code ended before it showed its prompt" + // WSLEnv holds, as JSON (WSL), how to run a Claude Code that is in a WSL // distro: the helper, on Windows, runs wsl.exe in its pseudo console. const WSLEnv = "MAGPIE_CLAUDE_TUI_WSL" diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index 149bbed6a..ad8954816 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -438,7 +438,14 @@ func (s *shim) lastScreen() string { p = strings.Join(strings.Fields(now), " ") } if p == "" { - return fmt.Sprintf("nothing on its screen (%d bytes read)", s.nread.Load()) + n := s.nread.Load() + why := fmt.Sprintf("nothing on its screen (%d bytes read)", n) + if n == 0 { + if w := s.undrawn(); w != "" { + why += "; " + w + } + } + return why } if len(p) > 600 { p = p[len(p)-600:] @@ -647,7 +654,7 @@ func (s *shim) ready() error { case <-s.changed: case <-time.After(200 * time.Millisecond): case <-s.exited: - return fmt.Errorf("Claude Code ended before it showed its prompt (%v): %s", s.exit, s.lastScreen()) + return fmt.Errorf(EndedEarly+" (%v): %s", s.exit, s.lastScreen()) case <-deadline: if prompted { return fmt.Errorf("Claude Code showed its prompt, but hadn't listed the tools of magpie's tool server in %s", readyWait) diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index d43a3c752..4869f0529 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -243,6 +243,19 @@ func fakeClaude(args []string) { time.Sleep(time.Minute) os.Exit(0) } + if v := os.Getenv("FAKE_KEYCHAIN"); v != "" { + // reads its Keychain sign-in before it draws anything, as Claude + // Code does, and the read never answers (sowhynot) + c := exec.Command(v, "find-generic-password", "-a", "u", "-w", "-s", "Claude Code-credentials") + c.Stdin = os.Stdin + _ = c.Run() + os.Exit(1) + } + if os.Getenv("FAKE_SILENT") == "1" { + // draws nothing, and runs nothing meanwhile + time.Sleep(time.Minute) + os.Exit(1) + } if os.Getenv("FAKE_LOGIN") == "1" { // signed in for -p alone: the interactive mode asks how to sign in fmt.Print("\r\nSelect login method:\r\n\r\n ❯ 1. Claude account with subscription\r\n 2. Anthropic Console account\r\n") diff --git a/internal/claudetui/waiting.go b/internal/claudetui/waiting.go new file mode 100644 index 000000000..be182044c --- /dev/null +++ b/internal/claudetui/waiting.go @@ -0,0 +1,91 @@ +package claudetui + +import ( + "fmt" + "path/filepath" + "strings" + "time" +) + +// running is a command Claude Code runs, and how long it has run. +type running struct { + age time.Duration + args string +} + +// undrawn is why a Claude Code that drew nothing hasn't: what it runs +// meanwhile. Claude Code reads its macOS Keychain sign-in with `security +// find-generic-password` before it draws anything, and one read has no +// time limit: a Keychain that waits for its user to allow the read, or to +// be unlocked, held it with nothing on its screen, and the error said +// only "0 bytes read" (sowhynot). +func (s *shim) undrawn() string { + cmds, rss, ok := s.waiting() + if !ok { + return "" + } + for _, c := range cmds { + if svc, ok := keychainRead(c.args); ok { + return fmt.Sprintf("it waits on the macOS Keychain, whose `security find-generic-password` read of %q hasn't answered in %s: a Keychain window may be asking to allow it, or the login keychain is locked. Answer it (Always Allow), or unlock the keychain in Keychain Access, and try again", svc, c.age.Round(time.Second)) + } + } + if len(cmds) == 0 { + return fmt.Sprintf("it runs no command, %d MiB resident", rss>>10) + } + var names []string + for _, c := range cmds[:min(len(cmds), 3)] { + names = append(names, fmt.Sprintf("%s (for %s)", program(c.args), c.age.Round(time.Second))) + } + return fmt.Sprintf("it waits on %s, %d MiB resident", strings.Join(names, ", "), rss>>10) +} + +// keychainRead is whether args are a `security find-generic-password` +// read, a script named security too, and the item's service (-s). +func keychainRead(args string) (string, bool) { + f := strings.Fields(args) + at := -1 + for i := 1; i < len(f); i++ { + if f[i] == "find-generic-password" && filepath.Base(f[i-1]) == "security" { + at = i + break + } + } + if at < 0 { + return "", false + } + svc := "its item" + for i := at + 1; i+1 < len(f); i++ { + if f[i] == "-s" { + // ps joins the arguments with spaces: the service is the rest, + // up to the next flag + var w []string + for _, v := range f[i+1:] { + if strings.HasPrefix(v, "-") { + break + } + w = append(w, v) + } + svc = strings.Trim(strings.Join(w, " "), `"`) + break + } + } + return svc, true +} + +// program is the name of the program args run, and of the script an +// interpreter runs: never the rest of its arguments, which can carry a +// secret. +func program(args string) string { + f := strings.Fields(args) + if len(f) == 0 { + return "a command" + } + name := filepath.Base(f[0]) + switch strings.TrimRight(name, "0123456789.") { + case "sh", "bash", "zsh", "dash", "node", "bun", "python", "ruby", "perl": + if len(f) > 1 && !strings.HasPrefix(f[1], "-") { + name += " " + filepath.Base(f[1]) + } + } + return name +} diff --git a/internal/claudetui/waiting_unix.go b/internal/claudetui/waiting_unix.go new file mode 100644 index 000000000..cdbeccb09 --- /dev/null +++ b/internal/claudetui/waiting_unix.go @@ -0,0 +1,97 @@ +//go:build darwin || linux + +package claudetui + +import ( + "fmt" + "slices" + "strconv" + "strings" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// waiting is what Claude Code is doing while it has drawn nothing: the +// commands it runs (its descendants, the longest-running first) and how +// much memory it holds, read from ps. ok is false when ps can't say. +func (s *shim) waiting() (cmds []running, rssKiB int64, ok bool) { + if s.cmd == nil || s.cmd.Process == nil { + return nil, 0, false + } + out, err := proc.Command("ps", "-A", "-o", "pid=,ppid=,rss=,etime=,command=").Output() + if err != nil { + return nil, 0, false + } + return descendants(string(out), s.cmd.Process.Pid) +} + +// descendants reads ps's lines (pid, ppid, rss, etime, command) for root's +// descendants and root's own rss. +func descendants(ps string, root int) (cmds []running, rssKiB int64, ok bool) { + type row struct { + pid, ppid int + rss int64 + age time.Duration + args string + } + var rows []row + for _, line := range strings.Split(ps, "\n") { + f := strings.Fields(line) + if len(f) < 5 { + continue + } + pid, err1 := strconv.Atoi(f[0]) + ppid, err2 := strconv.Atoi(f[1]) + rss, err3 := strconv.ParseInt(f[2], 10, 64) + age, err4 := etime(f[3]) + if err1 != nil || err2 != nil || err3 != nil || err4 != nil { + continue + } + rows = append(rows, row{pid, ppid, rss, age, strings.Join(f[4:], " ")}) + if pid == root { + rssKiB, ok = rss, true + } + } + if !ok { + return nil, 0, false + } + in := map[int]bool{root: true} + for grew := true; grew; { + grew = false + for _, r := range rows { + if in[r.ppid] && !in[r.pid] { + in[r.pid] = true + cmds = append(cmds, running{r.age, r.args}) + grew = true + } + } + } + slices.SortStableFunc(cmds, func(a, b running) int { return int(b.age - a.age) }) + return cmds, rssKiB, true +} + +// etime reads ps's elapsed time, [[dd-]hh:]mm:ss. +func etime(v string) (time.Duration, error) { + days := 0 + if d, rest, ok := strings.Cut(v, "-"); ok { + n, err := strconv.Atoi(d) + if err != nil { + return 0, err + } + days, v = n, rest + } + parts := strings.Split(v, ":") + if len(parts) < 2 || len(parts) > 3 { + return 0, fmt.Errorf("elapsed time %q", v) + } + secs := 0 + for _, p := range parts { + n, err := strconv.Atoi(p) + if err != nil { + return 0, err + } + secs = secs*60 + n + } + return time.Duration(days)*24*time.Hour + time.Duration(secs)*time.Second, nil +} diff --git a/internal/claudetui/waiting_unix_test.go b/internal/claudetui/waiting_unix_test.go new file mode 100644 index 000000000..5ad41f8ba --- /dev/null +++ b/internal/claudetui/waiting_unix_test.go @@ -0,0 +1,114 @@ +//go:build darwin || linux + +package claudetui + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +// A Claude Code that draws nothing is told by what it waits on. One whose +// macOS Keychain read never answered held 45s with nothing on its screen, +// and the error said only "0 bytes read" (sowhynot): it now names the +// Keychain, the item and what to do. +func TestShimSaysWhatAnUndrawnClaudeWaitsOn(t *testing.T) { + sec := filepath.Join(t.TempDir(), "security") + if err := os.WriteFile(sec, []byte("#!/bin/sh\nread x\n"), 0o755); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + name string + env []string + want []string + }{ + {"keychain", []string{"FAKE_KEYCHAIN=" + sec}, []string{"(0 bytes read); it waits on the macOS Keychain", `read of "Claude Code-credentials"`, "Always Allow"}}, + {"silent", []string{"FAKE_SILENT=1"}, []string{"(0 bytes read); it runs no command,", "MiB resident"}}, + } { + t.Run(c.name, func(t *testing.T) { + by := time.Now().Add(3 * time.Second).UnixMilli() + out, stderr, err := runEnds(t, t.TempDir(), append(c.env, DeadlineEnv+"="+strconv.FormatInt(by, 10))) + if err == nil || strings.Contains(out, `"type":"result"`) { + t.Fatalf("ended %v, wrote %q", err, out) + } + for _, w := range c.want { + if !strings.Contains(stderr, w) { + t.Fatalf("stderr lacks %q: %q", w, stderr) + } + } + }) + } +} + +func TestDescendants(t *testing.T) { + ps := ` 1 0 1000 10-01:00:00 /sbin/launchd + 100 1 43000 00:52 /usr/local/bin/claude --mcp-config x + 101 100 2000 00:50 /usr/bin/security find-generic-password -a me -w -s Claude Code-credentials + 102 101 100 00:10 /bin/sleep 5 + 103 1 100 01:00 /bin/other + bad line +` + cmds, rss, ok := descendants(ps, 100) + if !ok || rss != 43000 || len(cmds) != 2 { + t.Fatalf("%v %d %v", cmds, rss, ok) + } + if cmds[0].age != 50*time.Second || !strings.HasPrefix(cmds[0].args, "/usr/bin/security") || cmds[1].age != 10*time.Second { + t.Fatalf("%v", cmds) + } + if _, _, ok := descendants(ps, 999); ok { + t.Fatal("a pid ps doesn't list read as known") + } +} + +func TestEtime(t *testing.T) { + for v, want := range map[string]time.Duration{ + "00:05": 5 * time.Second, + "01:02:03": time.Hour + 2*time.Minute + 3*time.Second, + "2-00:00:01": 48*time.Hour + time.Second, + "10-01:00:00": 241 * time.Hour, + } { + if d, err := etime(v); err != nil || d != want { + t.Errorf("%s: %s %v", v, d, err) + } + } + for _, v := range []string{"5", "a:b", "1:2:3:4", "x-00:01"} { + if _, err := etime(v); err == nil { + t.Errorf("%s read", v) + } + } +} + +func TestKeychainRead(t *testing.T) { + for args, want := range map[string]string{ + `/usr/bin/security find-generic-password -a me -w -s Claude Code-credentials`: "Claude Code-credentials", + `security find-generic-password -a me -w -s "Claude Code" -x`: "Claude Code", + `/bin/sh /tmp/x/security find-generic-password -a u -w -s Claude Code-credentials`: "Claude Code-credentials", + `security find-generic-password -a me -w`: "its item", + } { + if svc, ok := keychainRead(args); !ok || svc != want { + t.Errorf("%s: %q %v", args, svc, ok) + } + } + for _, args := range []string{"security list-keychains", "/bin/grep find-generic-password x", "find-generic-password"} { + if _, ok := keychainRead(args); ok { + t.Errorf("%s read as a Keychain read", args) + } + } +} + +func TestProgramNamesNoArguments(t *testing.T) { + for args, want := range map[string]string{ + "/usr/bin/git config --get user.token=SECRET": "git", + "/bin/zsh -c echo SECRET": "zsh", + "/usr/bin/python3 /opt/helper.py SECRET": "python3 helper.py", + "node /x/apiKeyHelper.js --key SECRET": "node apiKeyHelper.js", + "": "a command", + } { + if got := program(args); got != want { + t.Errorf("%q: %q", args, got) + } + } +} diff --git a/internal/claudetui/waiting_windows.go b/internal/claudetui/waiting_windows.go new file mode 100644 index 000000000..3a2f644c3 --- /dev/null +++ b/internal/claudetui/waiting_windows.go @@ -0,0 +1,7 @@ +package claudetui + +// waiting is not read on Windows: ok is false, and a run that drew +// nothing says only that. +func (s *shim) waiting() (cmds []running, rssKiB int64, ok bool) { + return nil, 0, false +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 1e38cc20c..b054a49a0 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -1339,6 +1339,14 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, // the helper hung: the turn fails (start) return nil, nil, &tuiNoStart{err} } + if tui && run.saidOnEnd("claude-tui: ") && !run.saidOnEnd(claudetui.EndedEarly) { + // the helper ended saying why Claude Code didn't come up, + // and Claude Code hadn't ended itself, as one that can't + // load the session does: a new one told the whole + // conversation waited out the same 45s, and the turn was + // answered 502 after twice that (sowhynot) + return nil, nil, &tuiNoStart{err} + } return nil, nil, err } } diff --git a/internal/gateway/claude_tui_start_test.go b/internal/gateway/claude_tui_start_test.go index c9ffce87a..3cab3aa85 100644 --- a/internal/gateway/claude_tui_start_test.go +++ b/internal/gateway/claude_tui_start_test.go @@ -112,3 +112,36 @@ pwd >> '`+cwds+`'`) t.Fatalf("the helper started %d times, want three: the caller's folder was asked about again", n) } } + +// An interactive mode that doesn't come up for what Claude Code waits on +// is the same for a new Claude Code told the whole conversation: the turn +// fails once, saying why. It was tried again, waited out another 45s, and +// was answered 502 after twice that (sowhynot). A Claude Code that ended +// itself before its prompt, as one that can't load the session it was +// told to go on with does, is still tried again told the whole +// conversation. +func TestClaudeTUINoPromptNotTriedAgain(t *testing.T) { + for _, c := range []struct { + name, said string + starts int + }{ + {"no prompt", "Claude Code showed no prompt in 45s: nothing on its screen (0 bytes read)", 1}, + {"ended itself", claudetui.EndedEarly + " (exit status 1): No conversation found", 2}, + } { + t.Run(c.name, func(t *testing.T) { + h, started := tuiHelperHarness(t, `echo "claude-tui: `+c.said+`" >&2 +exit 1`) + // a conversation no run here has had: replayed from a transcript + code, msg := h.askCode("rules", "hi", "again", "more") + if code == 200 || !strings.Contains(msg, c.said) { + t.Fatalf("%d %s", code, msg) + } + if n := helperStarts(started); n != c.starts { + t.Fatalf("the helper started %d times, want %d", n, c.starts) + } + if runs := h.runs(); len(runs) != 0 { + t.Fatalf("a -p Claude Code ran: %v", runs) + } + }) + } +}