diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 9aa852eda..d9fbb27ad 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -386,8 +386,16 @@ reading's error was "exit status 1" alone. A run that still says nothing is "Claude Code's interactive mode said nothing before magpie stopped waiting for it" (`oneOffErr`), and the card says the reason (`quotaError`'s "Allowance unavailable: {why}"), its full text kept for the -tooltip. The `-p` asks keep a temp folder each, which they remove: `-p` -asks nothing about trust. +tooltip. A question about trust left unanswered at the deadline is named +with its folder ("Claude Code asked whether to trust , not answered +in the 16.8s …"), where it said "showed no prompt" before (#4830). A failed +run also goes to app.log (`logOneOff`: "claude: a /usage read of saved +account failed: …"), with the helper's whole reason, which the card +clips to 300 bytes, on one line: the home folder and any +`/Users/` or `C:\Users\` become `~`, secrets go through +`redact.Scrub`, and past 800 bytes it keeps the first 300 and the last 500, +so the end of the last screen stays. The `-p` asks keep a temp folder +each, which they remove: `-p` asks nothing about trust. The Claude Code provider editor's "Claude Code runs as" row (`claudeModeRow` in app.js, drawn by claudemode.js, which it loads with diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index 6add7089b..c163194d8 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -400,6 +400,14 @@ func (s *shim) ready() error { // being drawn again, and nothing then draws it once more shownAt := map[string]time.Time{} pressed := map[string]int{} + // the folder the trust question is about, for the reason a run that + // ends on it gives: "showed no prompt" said nothing of the question + // a saved account's reads waited out on (#4830, mydosu) + folder, _ := os.Getwd() + if folder == "" { + folder = "the folder it runs in" + } + asking := "asked whether to trust " + folder + ", not answered" onboard := func(screen, key string) error { if shownAt[screen].IsZero() { shownAt[screen] = time.Now() @@ -419,6 +427,11 @@ func (s *shim) ready() error { for { p := s.plain() words := strings.Join(strings.Fields(p), " ") + doing := "showed no prompt" + if strings.Contains(p, "trust this folder") { + doing = asking + } + s.doing.Store(doing) switch { case strings.Contains(p, "trust this folder") && os.Getenv(TrustEnv) != "1": return errUntrusted @@ -489,7 +502,8 @@ func (s *shim) ready() error { if prompted { return fmt.Errorf("Claude Code showed its prompt, but hadn't listed the tools of magpie's tool server in %s", readyWait) } - return fmt.Errorf("Claude Code showed no prompt in %s: %s", readyWait, s.lastScreen()) + doing, _ := s.doing.Load().(string) + return fmt.Errorf("Claude Code %s in %s: %s", doing, readyWait, s.lastScreen()) } } } diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index 7d7da337e..383898b6c 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -39,7 +39,9 @@ func TestMain(m *testing.M) { // fakeTrust asks whether to trust the folder as Claude Code 2.1.314 does: // its words placed by cursor moves, "No, exit" chosen, and drawn again on // No once it listens, the keys before that lost. Enter on No exits. -func fakeTrust(r *bufio.Reader) { +// With always, it never listens, as a question whose answer never goes +// through. +func fakeTrust(r *bufio.Reader, always bool) { var mu sync.Mutex yes, deaf := false, true draw := func() { @@ -48,6 +50,9 @@ func fakeTrust(r *bufio.Reader) { } draw() time.AfterFunc(150*time.Millisecond, func() { + if always { + return + } mu.Lock() defer mu.Unlock() deaf, yes = false, false @@ -174,8 +179,8 @@ func fakeClaude(args []string) { if v := os.Getenv("FAKE_ONBOARD"); v != "" { fakeOnboard(r, v) } - if os.Getenv("FAKE_TRUST") == "1" { - fakeTrust(r) + if v := os.Getenv("FAKE_TRUST"); v != "" { + fakeTrust(r, v == "deaf") } // what it was started with, for the test to read _ = os.WriteFile(filepath.Join(os.Getenv("CLAUDE_CONFIG_DIR"), "args"), []byte(strings.Join(args, "\n")), 0o600) @@ -621,11 +626,15 @@ func TestShimGoesThroughOnboarding(t *testing.T) { // at the caller's deadline instead, it said nothing, and the reading's // error was "exit status 1" (#4830, mydosu, Windows). func TestShimEndsAtItsCallersDeadline(t *testing.T) { + wd, _ := os.Getwd() for _, c := range []struct { name, line, why, screen string env []string }{ {"no prompt", `{"type":"user","message":{"role":"user","content":"hello"}}`, "showed no prompt in the", "Starting up", []string{"FAKE_STALL=1"}}, + // the question a saved account's reads waited out on (#4830, + // mydosu): said, with the folder, never "showed no prompt" + {"trust unanswered", `{"type":"user","message":{"role":"user","content":"hello"}}`, "asked whether to trust " + wd + ", not answered in the", "trust this folder", []string{"FAKE_TRUST=deaf", TrustEnv + "=1"}}, // FAKE_USAGE names no panel: nothing is drawn for /usage {"no /usage panel", `{"type":"command","command":"/usage"}`, "hadn't drawn /usage's panel in the", "", []string{"FAKE_USAGE=" + filepath.Join(t.TempDir(), "none")}}, } { diff --git a/internal/gateway/claude_oneoff_log_test.go b/internal/gateway/claude_oneoff_log_test.go new file mode 100644 index 000000000..db1bc6163 --- /dev/null +++ b/internal/gateway/claude_oneoff_log_test.go @@ -0,0 +1,78 @@ +package gateway + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/claudetui" + "github.com/yetone/magpie/internal/testenv" +) + +// A one-off interactive run that fails says why in app.log: the reason +// the helper gave and the end of Claude Code's last screen, which the +// card clips to its start. mydosu (#4830) found nothing there to say why +// every read of a saved account failed. Secrets and the user's folders +// don't go in. +func TestClaudeOneOffFailureLogged(t *testing.T) { + for _, c := range []struct { + name, what string + run func(ctx context.Context, cfg string) error + }{ + {"usage", "a /usage read", func(ctx context.Context, cfg string) error { _, err := claudeUsage(ctx, cfg); return err }}, + {"test", "a test on haiku", func(ctx context.Context, cfg string) error { return askClaude(ctx, cfg, "haiku") }}, + } { + t.Run(c.name, func(t *testing.T) { + fakeWarmClaude(t, `{}`, 0) + claudeTUIRuns = true + t.Cleanup(func() { claudeTUIRuns = false }) + t.Setenv("TMPDIR", t.TempDir()) + cfg := savedClaudeDir(t) + home, _ := os.UserHomeDir() + token := "sk-ant-oat01-" + strings.Repeat("Q7x", 20) + // the helper's reason, as it says it at its caller's deadline, + // with a long last screen that ends on what Claude Code drew last + screen := "Do you trust this folder? " + strings.Repeat("─", 400) + " C:\\Users\\mydosu\\AppData\\Local\\Temp\\magpie-claude-work token " + token + " ❯ No, exit END-OF-SCREEN" + reason := "claude-tui: Claude Code asked whether to trust " + filepath.Join(home, "AppData", "magpie-claude-work") + ", not answered in the 16.8s its caller waits for it: " + screen + helper := filepath.Join(t.TempDir(), "magpie") + testenv.Program(t, helper, `#!/bin/sh +[ "$1" = "`+claudetui.Command+`" ] || exit 9 +printf '%s\n' '`+reason+`' >&2 +exit 1 +`) + claudeTUIHelper = helper + t.Cleanup(func() { claudeTUIHelper = "" }) + logs := keepLog(t) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if err := c.run(ctx, cfg); err == nil { + t.Fatal("the run didn't fail") + } + var line string + for _, l := range strings.Split(logs.String(), "\n") { + if strings.Contains(l, "claude: "+c.what+" of saved account 0123456789abcdef failed: ") { + line = l + } + } + if line == "" { + t.Fatalf("app.log says nothing of the failure:\n%s", logs.String()) + } + for _, want := range []string{"asked whether to trust ~", "not answered in the 16.8s", "END-OF-SCREEN"} { + if !strings.Contains(line, want) { + t.Errorf("the line lacks %q: %s", want, line) + } + } + for _, gone := range []string{home, "mydosu", strings.Repeat("Q7x", 20)} { + if strings.Contains(line, gone) { + t.Errorf("the line has %q: %s", gone, line) + } + } + if len(line) > 1200 { + t.Errorf("the line is %d bytes: %s", len(line), line) + } + }) + } +} diff --git a/internal/gateway/claude_warmup.go b/internal/gateway/claude_warmup.go index f3ea917bb..59e25db83 100644 --- a/internal/gateway/claude_warmup.go +++ b/internal/gateway/claude_warmup.go @@ -11,16 +11,19 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "runtime" "slices" "strconv" "strings" "time" + "unicode/utf8" "github.com/yetone/magpie/internal/claudetui" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/redact" "golang.org/x/text/unicode/norm" ) @@ -131,7 +134,9 @@ func askClaudeTUI(ctx context.Context, binary claudeCLI, configDir, model string } return nil } - return oneOffErr(ctx, stderr.String(), runErr) + err = oneOffErr(ctx, stderr.String(), runErr) + logOneOff("a test on "+model, configDir, stderr.String(), err) + return err } // resultLines reads the helper's stream-json for its first result, and @@ -285,7 +290,9 @@ func claudeUsageTUI(ctx context.Context, binary claudeCLI, configDir string) (st } return out.res.Result, nil } - return "", oneOffErr(ctx, stderr.String(), runErr) + err = oneOffErr(ctx, stderr.String(), runErr) + logOneOff("a /usage read", configDir, stderr.String(), err) + return "", err } // oneOffDir is the folder a one-off interactive run (a test, a /usage) @@ -394,6 +401,54 @@ func oneOffErr(ctx context.Context, stderr string, runErr error) error { return errors.New("Claude Code ended with no answer") } +// logOneOff writes to app.log why a one-off interactive run (what) of +// the account in configDir failed (err): the reason the helper gave on +// stderr and the end of Claude Code's last screen, which err, the card's +// text, clips to its first 300 bytes. mydosu (#4830) found nothing in +// app.log to say why every read of a saved account failed. Secrets and +// the user's folders are taken out (logSafe). +func logOneOff(what, configDir, stderr string, err error) { + if err == nil { + return + } + why := strings.TrimSpace(stderr) + if why == "" { + why = err.Error() + } + who := "the account Claude Code is signed in to" + if configDir != "" { + who = "saved account " + filepath.Base(configDir) + } + log.Printf("claude: %s of %s failed: %s", what, who, logSafe(why)) +} + +// homePath is a user's home folder in a path, on Windows, a Mac or +// Linux, with either slash: what follows it is kept, the user's name not. +var homePath = regexp.MustCompile(`(?i)(?:\b[a-z]:)?[\\/]+(?:users|home)[\\/]+[^\\/\s"'│:]+`) + +// logSafe is s for app.log: secrets out (redact.Scrub), this user's home +// folder and any other home folder in it written ~, its spaces +// collapsed, and only its start and end kept when it is long. +func logSafe(s string) string { + s = strings.Join(strings.Fields(s), " ") + if home, err := os.UserHomeDir(); err == nil && len(home) > 1 { + for _, h := range []string{home, filepath.ToSlash(home), strings.ReplaceAll(home, "/", `\`)} { + s = strings.ReplaceAll(s, h, "~") + } + } + s = homePath.ReplaceAllString(s, "~") + s = redact.Scrub(s) + const head, tail = 300, 500 + if len(s) > head+tail { + i := head + for i > 0 && !utf8.RuneStart(s[i]) { + i-- + } + s = s[:i] + " " + clipTail(s, tail) + } + return s +} + // runClaudeTree runs a one-off Claude Code (a test, a /usage) and ends, // with it, whatever it started: its context ending kills only the // process magpie started, and on Windows that is cmd.exe running npm's