diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index f8f706a7c..f65f97527 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -189,11 +189,27 @@ back, an effort change. A run given up on (`letGo`) is not taken back, since the interactive mode can't answer a control request to stop a turn. If the interactive Claude Code doesn't start or show its prompt within 45 -seconds, the helper becomes `claude -p` with the same arguments -(`printMode`, `exec` on the same pid, its input still unread), so the -turn is answered all the same, and it writes -`/magpie/claude-tui-broken`: for 30 minutes after, every run goes -to `-p` at once. A folder not trusted goes to `-p` without the mark. +seconds (`claudetui.ReadyWait`), or asks how to sign in (`signIn`: a +Claude Code signed in for `-p` only, as in a container given +`CLAUDE_CODE_OAUTH_TOKEN`), the helper becomes `claude -p` with the same +arguments (`printMode`, `exec` on the same pid, its input still unread), +so the turn is answered all the same, and it writes +`/magpie/claude-tui-broken`, which holds the number of failed +starts in a row. For 30 minutes after one, doubled with each one after +to a day (`brokenFor`), every run goes to `-p` at once: the helper is +not started (`claudePrintWhy`, "the interactive mode failed to start +lately"). A start that shows its prompt removes the mark. A folder not +trusted goes to `-p` without the mark. + +The helper answers the bridge's `initialize` only once the prompt is +shown, or as `-p` after the fallback, so the bridge waits for it +`tuiInitWait` (`ReadyWait` and twice a control request's 10s), not the +10s of any other control request. With 10s, a Claude Code slower than +that to start (2 vCPU in Docker) was ended as the helper waited, before +it could become `-p`, 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, the mark is written, and `start` +starts the turn again as `-p`. ## Why turns go on in one run diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index e264973cc..249b9bd62 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -34,10 +34,17 @@ import ( "time" ) +// ReadyWait is how long Claude Code may take to show its prompt before +// the helper becomes -p (printMode). The bridge's wait for the helper's +// answer to its initialize request is longer by as much as -p takes to +// answer it (#4504): a wait shorter than this one ended the helper as it +// waited, before it became -p, and the turn was answered 502. +const ReadyWait = 45 * time.Second + // how long Claude Code may take to show its prompt, a pasted message to // show in it, and a sent one to reach its transcript var ( - readyWait = 45 * time.Second + readyWait = ReadyWait pasteWait = 10 * time.Second sentWait = 3 * time.Second // rows of one message are written together: a message is whole once @@ -89,7 +96,7 @@ func Run(args []string) error { return errors.New("usage: magpie " + Command + " [claude -p's arguments]") } path, pargs := args[0], args[1:] - if since, ok := brokenSince(); ok { + if since, ok := BrokenSince(); ok { fmt.Fprintf(os.Stderr, "claude-tui: Claude Code's interactive mode failed to start %s ago; this run is -p\n", time.Since(since).Round(time.Second)) return printMode(path, pargs) } @@ -117,7 +124,7 @@ func Run(args []string) error { } } if err := s.start(path, args); err != nil { - markBroken() + MarkBroken() fmt.Fprintf(os.Stderr, "claude-tui: Claude Code's interactive mode could not start (%v); this run is -p\n", err) return printMode(path, pargs) } @@ -134,13 +141,14 @@ func Run(args []string) error { }() if err := s.ready(); err != nil { if !errors.Is(err, errUntrusted) { - markBroken() + MarkBroken() } signal.Reset() s.stop() fmt.Fprintf(os.Stderr, "claude-tui: %v; this run is -p\n", err) return printMode(path, pargs) } + clearBroken() s.emit(map[string]any{"type": "system", "subtype": "init", "session_id": s.sid}) go s.tail(from) return s.input(os.Stdin) @@ -250,6 +258,11 @@ func lastAt(re *regexp.Regexp, p string) int { var errUntrusted = errors.New("Claude Code asks whether to trust the folder, which only its user answers") +// signIn is what Claude Code's interactive mode shows where it is not +// signed in, as -p may be (CLAUDE_CODE_OAUTH_TOKEN, a container whose +// ~/.claude.json has no onboarding done): nothing the helper may answer. +var signIn = regexp.MustCompile(`Select login method|Log in with your Claude account|claude\.ai/oauth/authorize`) + // ready waits for Claude Code's prompt. Asked whether to trust the folder // it runs in, it is told yes, as a person would, when TrustEnv says so. func (s *shim) ready() error { @@ -261,6 +274,8 @@ func (s *shim) ready() error { switch { case strings.Contains(p, "trust this folder") && os.Getenv(TrustEnv) != "1": return errUntrusted + case signIn.MatchString(p): + return fmt.Errorf("Claude Code's interactive mode asks to sign in: %s", s.lastScreen()) case strings.Contains(p, "trust this folder") && answered < 3: // the choice is the last one drawn after ❯, "No, exit" at // first. A key sent as the question is first drawn can be lost @@ -760,8 +775,9 @@ func interactiveArgs(pargs []string) []string { return append(out, "--permission-mode", "default", "--allowedTools", strings.Join(allowed, ","), "--no-chrome") } -// broken is where a failed start is kept: for brokenFor after it, runs go -// straight to -p, rather than each waiting out readyWait. +// broken is where a failed start is kept: for a while after it +// (brokenFor), runs go straight to -p, rather than each waiting out +// readyWait. It holds how many starts in a row failed. func broken() string { dir, err := os.UserCacheDir() if err != nil { @@ -770,27 +786,66 @@ func broken() string { return filepath.Join(dir, "magpie", "claude-tui-broken") } -const brokenFor = 30 * time.Minute - -func brokenSince() (time.Time, bool) { - p := broken() - if p == "" { - return time.Time{}, false +// brokenFor is how long runs go to -p after the interactive mode failed +// to start n times in a row: 30 minutes, doubled with each failure after, +// to a day. A machine where it never starts (a container whose Claude Code +// is signed in for -p only, #4504) waits out readyWait about once a day. +func brokenFor(n int) time.Duration { + d := 30 * time.Minute + for i := 1; i < n && d < 24*time.Hour; i++ { + d *= 2 } - fi, err := os.Stat(p) - if err != nil || time.Since(fi.ModTime()) > brokenFor { - return time.Time{}, false - } - return fi.ModTime(), true + return min(d, 24*time.Hour) } -func markBroken() { +func brokenRead() (time.Time, int, bool) { + p := broken() + if p == "" { + return time.Time{}, 0, false + } + fi, err := os.Stat(p) + if err != nil { + return time.Time{}, 0, false + } + b, _ := os.ReadFile(p) + n, err := strconv.Atoi(strings.TrimSpace(string(b))) + if err != nil || n < 1 { + // a mark from before the count, or one half written + n = 1 + } + return fi.ModTime(), n, true +} + +// BrokenSince is when the interactive mode last failed to start, while +// runs go to -p for it. +func BrokenSince() (time.Time, bool) { + at, n, ok := brokenRead() + if !ok || time.Since(at) > brokenFor(n) { + return time.Time{}, false + } + return at, true +} + +// MarkBroken notes that the interactive mode failed to start: by the +// helper, and by the bridge when the helper didn't answer in time. +func MarkBroken() { p := broken() if p == "" { return } + n := 1 + if _, was, ok := brokenRead(); ok { + n = was + 1 + } _ = os.MkdirAll(filepath.Dir(p), 0o700) - _ = os.WriteFile(p, nil, 0o600) + _ = os.WriteFile(p, []byte(strconv.Itoa(n)), 0o600) now := time.Now() _ = os.Chtimes(p, now, now) } + +// clearBroken forgets failed starts once one shows its prompt. +func clearBroken() { + if p := broken(); p != "" { + _ = os.Remove(p) + } +} diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index 92d1256ab..012f35f24 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -92,6 +92,12 @@ func fakeClaude(args []string) { fmt.Print("something went wrong\n") os.Exit(3) } + 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") + time.Sleep(time.Minute) + os.Exit(0) + } sid := "" if i := slices.Index(args, "--session-id"); i >= 0 { sid = args[i+1] @@ -359,6 +365,8 @@ func TestShimFallsBackToPrint(t *testing.T) { }{ {"failed start", []string{"FAKE_FAIL=1"}, true}, {"untrusted folder", []string{"FAKE_TRUST=1"}, false}, + // at once, not after readyWait: runShim waits 30s (#4504) + {"asks to sign in", []string{"FAKE_LOGIN=1"}, true}, } { t.Run(c.name, func(t *testing.T) { out := runShim(t, c.env, append([]string{fakePath(t)}, pArgs...), []string{"hello"}, 1) @@ -375,6 +383,67 @@ func TestShimFallsBackToPrint(t *testing.T) { } } +// Each failed start in a row keeps runs on -p longer, to a day; one that +// shows its prompt forgets them. +func TestBrokenGrows(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, "cache")) + t.Setenv("LOCALAPPDATA", filepath.Join(home, "cache")) + for n, want := range map[int]time.Duration{1: 30 * time.Minute, 2: time.Hour, 3: 2 * time.Hour, 6: 16 * time.Hour, 7: 24 * time.Hour, 40: 24 * time.Hour} { + if got := brokenFor(n); got != want { + t.Errorf("brokenFor(%d) = %s, want %s", n, got, want) + } + } + if _, ok := BrokenSince(); ok { + t.Fatal("broken with no mark") + } + MarkBroken() + MarkBroken() + if _, n, _ := brokenRead(); n != 2 { + t.Fatalf("count %d, want 2", n) + } + // 45 minutes ago: past one failure's 30 minutes, within two's hour + old := time.Now().Add(-45 * time.Minute) + _ = os.Chtimes(broken(), old, old) + if _, ok := BrokenSince(); !ok { + t.Fatal("two failures 45 minutes ago went back to the interactive mode") + } + _ = os.WriteFile(broken(), nil, 0o600) // a mark from before the count + _ = os.Chtimes(broken(), old, old) + if _, ok := BrokenSince(); ok { + t.Fatal("an old mark 45 minutes ago still holds") + } + clearBroken() + if _, _, ok := brokenRead(); ok { + t.Fatal("cleared, the mark stayed") + } +} + +// A start that shows its prompt removes the mark of earlier failures, so +// the next failure counts from one. +func TestShimStartClearsBroken(t *testing.T) { + home := t.TempDir() + env := []string{"HOME=" + home, "XDG_CACHE_HOME=" + filepath.Join(home, "cache"), "LOCALAPPDATA=" + filepath.Join(home, "cache")} + for _, e := range env { + k, v, _ := strings.Cut(e, "=") + t.Setenv(k, v) + } + // three failures, the last a day and a half ago: past its 2 hours + MarkBroken() + MarkBroken() + MarkBroken() + old := time.Now().Add(-36 * time.Hour) + _ = os.Chtimes(broken(), old, old) + out := runShim(t, env, append([]string{fakePath(t)}, pArgs...), []string{"hello"}, 3) + if out[0]["subtype"] != "init" { + t.Fatalf("got %v, want an interactive turn", out) + } + if _, _, ok := brokenRead(); ok { + t.Fatal("a start that showed its prompt left the mark") + } +} + func TestShimTrustsWhenTold(t *testing.T) { out := runShim(t, []string{"FAKE_TRUST=1", TrustEnv + "=1"}, append([]string{fakePath(t)}, pArgs...), []string{"hello"}, 3) if out[0]["subtype"] != "init" || out[1]["type"] != "assistant" { diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 396aa3aa1..fa491c883 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -664,6 +664,13 @@ const claudeMCPPath = "/_magpie/claude-mcp/" // (FrierenF on Discord). func (b *subscriptionBridge) start(ctx context.Context, req *Request, model, configDir, owner string, from *savedSession) (*subscriptionRun, <-chan Event, error) { run, events, err := b.startRun(ctx, req, model, configDir, owner, from) + var noStart *tuiNoStart + if errors.As(err, &noStart) && ctx.Err() == nil { + // marked broken, the next run is -p (claudePrintWhy); from was let + // go with the run + log.Printf("claude: Claude Code's interactive mode did not start (%v); the turn goes to -p", err) + return b.startRun(ctx, req, model, configDir, owner, nil) + } var full *claudeFull var refused *cliSchemaRefused if err != nil && from != nil && !errors.As(err, &full) && !errors.As(err, &refused) && ctx.Err() == nil { @@ -822,7 +829,11 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, tui := claudeTUI(req, binary, prompt) var cmd *exec.Cmd if tui { - cmd = proc.CommandContext(context.Background(), exe, append([]string{claudetui.Command, binary.path}, args...)...) + helper := exe + if claudeTUIHelper != "" { + helper = claudeTUIHelper + } + cmd = proc.CommandContext(context.Background(), helper, append([]string{claudetui.Command, binary.path}, args...)...) } else { cmd = binary.command(context.Background(), args...) } @@ -917,8 +928,24 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, // it has loaded the session, and one that can't exits instead // (start tells a new one the whole conversation): told the turn // first, it ended with no reply. - if err := run.cliControl(map[string]any{"subtype": "initialize"}); err != nil { + // The interactive mode's helper answers it once Claude Code shows + // its prompt, or, when it doesn't in claudetui.ReadyWait, once + // the helper has become -p: the wait is that long and -p's after + // it. 10s ended the helper as it waited, before it became -p, and + // every try of the turn was answered 502 (#4504). + wait := controlWait + if tui { + wait = tuiInitWait + } + if err := run.cliControlWithin(ctx, map[string]any{"subtype": "initialize"}, wait); err != nil { run.abort() + var unanswered *controlUnanswered + if tui && errors.As(err, &unanswered) { + // the helper hung: runs here are -p for a while, this + // turn's next try too (start) + claudetui.MarkBroken() + return nil, nil, &tuiNoStart{err} + } return nil, nil, err } } @@ -942,6 +969,32 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, return run, segment, nil } +// claudeTUIHelper, when set, is run as the interactive mode's helper in +// place of magpie's executable: a test's stand-in. +var claudeTUIHelper string + +// controlWait is how long Claude Code may take to answer a control +// request; tuiInitWait the interactive mode's helper its initialize: as +// long as Claude Code may take to show its prompt, and then -p's +// controlWait with room, for the helper become -p to answer it. +var ( + controlWait = 10 * time.Second + tuiInitWait = claudetui.ReadyWait + 2*controlWait +) + +// controlUnanswered is a control request Claude Code took and didn't +// answer in time. +type controlUnanswered struct{ what string } + +func (e *controlUnanswered) Error() string { return "Claude Code has not " + e.what } + +// tuiNoStart is a run whose interactive mode's helper never answered its +// initialize request: start tries the turn again as -p. +type tuiNoStart struct{ err error } + +func (e *tuiNoStart) Error() string { return e.err.Error() } +func (e *tuiNoStart) Unwrap() error { return e.err } + // claudeTUIRuns is false where magpie's executable has no shim to run: // the gateway's tests, whose fake Claude Codes are -p ones. var claudeTUIRuns = true @@ -989,6 +1042,7 @@ func claudePrintWhy(req *Request, binary claudeCLI, prompt []map[string]any) str {len(req.Format.schema()) > 0, "a JSON schema"}, {urlImages(req.Messages) > 0, "an image known by its URL"}, {settings.Load().ClaudePrintMode, "the interactive mode is turned off"}, + {tuiBroken(), "the interactive mode failed to start lately"}, {len(b) > tuiPromptMost, "a first message over 400KB"}, } { if c.is { @@ -1044,9 +1098,22 @@ func (r *subscriptionRun) setSafeguards(req *Request) error { return err } +// tuiBroken is whether the interactive mode failed to start on this +// machine lately (claudetui.BrokenSince): a run is -p at once, rather +// than its helper's finding so after it starts. +func tuiBroken() bool { + _, ok := claudetui.BrokenSince() + return ok +} + // cliControl shares the SDK reply dispatcher with rewind, so unrelated or // late control responses cannot acknowledge a safety-context update. func (r *subscriptionRun) cliControl(request map[string]any) error { + return r.cliControlWithin(context.Background(), request, controlWait) +} + +// cliControlWithin is cliControl, answered within wait, while ctx lasts. +func (r *subscriptionRun) cliControlWithin(ctx context.Context, request map[string]any, wait time.Duration) error { id := randomToken() ch := make(chan controlReply, 1) // one that ended says how, and the last it wrote to stderr: "Claude @@ -1071,7 +1138,7 @@ func (r *subscriptionRun) cliControl(request map[string]any) error { if err := r.tell(line); err != nil { return err } - t := time.NewTimer(10 * time.Second) + t := time.NewTimer(wait) defer t.Stop() select { case reply, ok := <-ch: @@ -1082,8 +1149,10 @@ func (r *subscriptionRun) cliControl(request map[string]any) error { return fmt.Errorf("Claude settings: %s", reply.Error) } return nil + case <-ctx.Done(): + return ctx.Err() case <-t.C: - return fmt.Errorf("Claude Code has not %s in 10s", what) + return &controlUnanswered{fmt.Sprintf("%s in %s", what, wait)} } } diff --git a/internal/gateway/claude_tui_start_test.go b/internal/gateway/claude_tui_start_test.go new file mode 100644 index 000000000..9c68e970d --- /dev/null +++ b/internal/gateway/claude_tui_start_test.go @@ -0,0 +1,79 @@ +package gateway + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/claudetui" + "github.com/yetone/magpie/internal/testenv" +) + +// tuiHelperHarness is a script harness whose runs in Claude Code's +// interactive mode start a stand-in for magpie's claude-tui-helper: it +// notes each start in started, waits as hold says (a shell command), and +// becomes the -p Claude Code it was handed, as the helper does when the +// interactive Claude Code doesn't show its prompt in time. +func tuiHelperHarness(t *testing.T, hold string) (*resumeHarness, string) { + t.Helper() + h := newReplyHarness(t, "ok") + claudeTUIRuns = true + t.Cleanup(func() { claudeTUIRuns = false }) + started := filepath.Join(t.TempDir(), "started") + helper := filepath.Join(t.TempDir(), "magpie") + testenv.Program(t, helper, `#!/bin/sh +[ "$1" = "`+claudetui.Command+`" ] || exit 9 +echo start >> '`+started+`' +`+hold+` +shift; claude=$1; shift +exec "$claude" "$@" +`) + claudeTUIHelper = helper + t.Cleanup(func() { claudeTUIHelper = "" }) + return h, started +} + +func helperStarts(path string) int { + b, _ := os.ReadFile(path) + return strings.Count(string(b), "start") +} + +// An interactive Claude Code that takes longer than a control request's +// 10s to show its prompt is waited for: the bridge gave the helper 10s to +// answer initialize and ended it as it waited, before it became -p on its +// own (claudetui.ReadyWait, 45s), and every try was answered 502 "Claude +// Code has not answered magpie's initialize request in 10s" (#4504, +// derrors: 2 vCPU, Claude Code in Docker). +func TestClaudeTUISlowStartAnswered(t *testing.T) { + h, started := tuiHelperHarness(t, "sleep 12") + h.ask("rules", "hi") // fails the test on anything but 200 + if n := helperStarts(started); n != 1 { + t.Fatalf("the helper started %d times, want once", n) + } + if _, ok := claudetui.BrokenSince(); ok { + t.Fatal("a slow start that answered was marked broken") + } +} + +// A helper that never answers initialize is let go, the machine is marked +// as one whose interactive mode doesn't start, and the turn is answered by +// -p: the turn, and the next, never wait on the interactive mode again. +func TestClaudeTUIHungHelperGoesPrint(t *testing.T) { + was := tuiInitWait + tuiInitWait = time.Second + t.Cleanup(func() { tuiInitWait = was }) + h, started := tuiHelperHarness(t, "exec sleep 600") + h.ask("rules", "hi") + if n := helperStarts(started); n != 1 { + t.Fatalf("the helper started %d times, want once", n) + } + if _, ok := claudetui.BrokenSince(); !ok { + t.Fatal("a helper that never answered left no mark") + } + h.ask("other rules", "hello") + if n := helperStarts(started); n != 1 { + t.Fatalf("the helper started %d times, want once: a run after the mark went to the interactive mode", n) + } +}