diff --git a/internal/claudetui/command.go b/internal/claudetui/command.go index 6175fcfda..79972f3db 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" +// Unanswered ends, in what the helper says as it ends, a question of +// Claude Code's it saw and answered without the answer going through +// (the trust question, the Bypass Permissions disclaimer, the Claude in +// Chrome offer): Claude Code asks it the same under every account, so +// the bridge doesn't ask the next account (@ahz2ygnhjmIJ0E0 on X: 502 +// after every account had waited out 45s on the trust question). +const Unanswered = ", not answered in " + // 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 diff --git a/internal/claudetui/testdata/trust-2.1.329.bin b/internal/claudetui/testdata/trust-2.1.329.bin new file mode 100644 index 000000000..875a89bf2 --- /dev/null +++ b/internal/claudetui/testdata/trust-2.1.329.bin @@ -0,0 +1,18 @@ +78[?25h[?25l[?2004h[?2031h[?1004h[>4;2m[?2026h +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +Accessingworkspace: + +/private/tmp/magpie-trust-fixture + +Quicksafetycheck:Isthisaprojectyoucreatedoroneyoutrust?(Likeyourowncode,awell-knownopensourceproject,orworkfromyourteam).Ifnot,takeamomenttoreviewwhat'sinthis +folderfirst. + +ClaudeCode'llbeabletoread,edit,andexecutefileshere. + +]8;id=zaxmda;https://code.claude.com/docs/en/security\Security guide]8;;\ + +❯No,exit +Yes,Itrustthisfolder + +Entertoconfirm·Esctocancel +[?2026l[>0q[?u]7501;?\ \ No newline at end of file diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index c8c5f18ce..2878bfd3e 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -522,27 +522,34 @@ func tailAfter(words string, end int) int { return utf8.RuneCountInString(words[end:]) } -// optionDialog is whether words end on a question: its heading, then its -// option rows, a No and the yes row, with only the dialog's footer under -// them. The question's words alone are not it: a resumed conversation's -// history can hold them (#, @alisenray: "Bypass Permissions mode" in the -// history failed every --resume at 45s with the prompt box showing). +// optionDialog is whether words end on a question: its option rows, a No +// and the yes row, with only the dialog's footer under them, and its +// words ask at most dialogBody before them or in them. The question's +// words alone are not it: a resumed conversation's history can hold them +// (#, @alisenray: "Bypass Permissions mode" in the history failed every +// --resume at 45s with the prompt box showing). Nor do the words come +// first: Claude Code (2.1.327, 2.1.329) heads the trust question "Quick +// safety check", and "trust this folder" is in its Yes row alone, under +// the No row. A check that wanted the words above both rows never saw +// the question, and every run of a saved account in a caller's folder +// waited out its 45s on it (@ahz2ygnhjmIJ0E0 on X). func optionDialog(words, ask string, yes *lazyre.RE) bool { - h := strings.Index(words, ask) - if h < 0 { - return false - } - end := -1 + start, end := len(words), -1 for _, re := range []*lazyre.RE{noRow, yes} { m := re.FindAllStringIndex(words, -1) - if len(m) == 0 || m[len(m)-1][0] < h { + if len(m) == 0 { return false } - if e := m[len(m)-1][1]; e > end { - end = e - } + start = min(start, m[len(m)-1][0]) + end = max(end, m[len(m)-1][1]) } - return tailAfter(words, end) <= dialogFoot + if tailAfter(words, end) > dialogFoot { + return false + } + // the words can end in the footer's reach: the Yes row "Yes, I + // trust" holds "trust this folder", past what the row matched + h := strings.LastIndex(words, ask) + return h >= 0 && (h >= start || tailAfter(words[:start], h) <= dialogBody) } // headingDialog is whether words end on a screen drawn under heading ask @@ -639,9 +646,11 @@ func (s *shim) ready() error { if folder == "" { folder = "the folder it runs in" } - asking := "asked whether to trust " + folder + ", not answered" - bypassAsking := "asked to accept running in Bypass Permissions mode, not answered" - chromeAsking := "asked whether to use Claude in Chrome, not answered" + // each said as "Claude Code in " (Unanswered) + unanswered := strings.TrimSuffix(Unanswered, " in ") + asking := "asked whether to trust " + folder + unanswered + bypassAsking := "asked to accept running in Bypass Permissions mode" + unanswered + chromeAsking := "asked whether to use Claude in Chrome" + unanswered onboard := func(screen, key string) error { if shownAt[screen].IsZero() { shownAt[screen] = time.Now() diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index ea825d991..36d3b4d35 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -3,6 +3,7 @@ package claudetui import ( "bufio" "bytes" + _ "embed" "encoding/base64" "encoding/json" "fmt" @@ -44,17 +45,33 @@ func TestMain(m *testing.M) { os.Exit(m.Run()) } -// 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. -// With always, it never listens, as a question whose answer never goes -// through. +// trustScreen is how Claude Code 2.1.329 first draws its trust question, +// as a real run drew it in a sandbox (its folder /private/tmp/ +// magpie-trust-fixture): headed "Quick safety check", the No row first, +// and "trust this folder" in the Yes row alone. +// +//go:embed testdata/trust-2.1.329.bin +var trustScreen []byte + +// fakeTrust asks whether to trust the folder as Claude Code 2.1.329 does +// (trustScreen): "No, exit" chosen, the keys before it listens lost, and +// nothing drawn again until a key moves the choice, when its two rows +// are, as 2.1.329 draws them. Enter on No exits. 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 + first := true draw := func() { - marks := map[bool]string{true: "\x1b[38;2;177;185;249m❯\x1b[39m", false: " "} - fmt.Printf("\x1b[2GDo\x1b[5Gyou\x1b[9Gtrust\x1b[15Gthis\x1b[20Gfolder?\r\n\x1b[2G%s\x1b[4GNo,\x1b[8Gexit\r\n\x1b[2G%s\x1b[4GYes,\x1b[9GI\x1b[11Gtrust\x1b[17Gthis\x1b[22Gfolder\r\n", marks[!yes], marks[yes]) + if first { + first = false + _, _ = os.Stdout.Write(trustScreen) + return + } + // 2.1.329's own redraw on a key (its cursor left on the No row + // it started from) + marks := map[bool]string{true: "\x1b[38;2;177;185;249m❯", false: " "} + fmt.Printf("\x1b[?2026h\x1b[1D\x1b[4B\r\x1b[1C\x1b[4A%s\x1b[4GNo, exit\x1b[39m\r\x1b[1C\x1b[1B%s\x1b[4GYes, I trust this folder\x1b[39m\r\r\n\r\n\r\n\x1b[1C\x1b[4A\x1b[?2026l", marks[!yes], marks[yes]) } draw() time.AfterFunc(150*time.Millisecond, func() { @@ -64,7 +81,6 @@ func fakeTrust(r *bufio.Reader, always bool) { mu.Lock() defer mu.Unlock() deaf, yes = false, false - draw() }) for { c, err := r.ReadByte() @@ -1171,6 +1187,31 @@ func TestShimDeclinesChromeOffer(t *testing.T) { } } +// Claude Code 2.1.329's trust question, as a real run drew it, is the +// question, read from what was drawn and from the screen alike, with "No, +// exit" chosen: its heading is "Quick safety check", and "trust this +// folder" is in its Yes row alone, under the No row. Read as a question +// with its words above both rows, it was none, and a run told to trust +// the folder waited out readyWait on it, 502 on every account +// (@ahz2ygnhjmIJ0E0 on X). +func TestTrustQuestionOf2_1_329(t *testing.T) { + s := &shim{screen: trustScreen, grid: newGrid(screenSize())} + s.grid.write(trustScreen) + now, _ := s.looks() + for name, p := range map[string]string{"drawn": s.plain(), "screen": now} { + words := strings.Join(strings.Fields(p), " ") + if !optionDialog(words, trustAsk, trustRow) { + t.Errorf("%s: not the trust question: %q", name, words) + } + if optionDialog(words, bypassAsk, bypassRow) { + t.Errorf("%s: read as the Bypass Permissions disclaimer", name) + } + } + if p := s.plain(); lastAt(trustNo, p) < 0 || lastAt(trustYes, p) >= 0 { + t.Errorf("No isn't the choice drawn: %q", p) + } +} + 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 4600ca85b..c757d152a 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -936,7 +936,15 @@ func (b *subscriptionBridge) start(ctx context.Context, req *Request, model, con var noStart *tuiNoStart if errors.As(err, &noStart) { // never tried again as -p (claudeTUIErr) - return nil, nil, claudeTUIErr("Claude Code's interactive mode didn't start: " + err.Error()) + err := claudeTUIErr("Claude Code's interactive mode didn't start: " + err.Error()) + if noStart.asked { + // a question Claude Code asks the same under every account: + // no account's fault, and the next isn't asked. A 502 was + // asked of each account in turn, each waiting out its 45s + // (@ahz2ygnhjmIJ0E0 on X) + return nil, nil, &tuiRefusal{err} + } + return nil, nil, err } var full *claudeFull var refused *cliSchemaRefused @@ -1453,7 +1461,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, var unanswered *controlUnanswered if tui && errors.As(err, &unanswered) { // the helper hung: the turn fails (start) - return nil, nil, &tuiNoStart{err} + return nil, nil, &tuiNoStart{err: err} } if tui && run.saidOnEnd("claude-tui: ") && !run.saidOnEnd(claudetui.EndedEarly) { // the helper ended saying why Claude Code didn't come up, @@ -1461,7 +1469,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, // 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, &tuiNoStart{err: err, asked: run.saidOnEnd(claudetui.Unanswered)} } return nil, nil, err } @@ -1541,8 +1549,13 @@ 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 fails the turn, saying so. -type tuiNoStart struct{ err error } +// initialize request: start fails the turn, saying so. asked is that the +// helper ended on a question of Claude Code's it couldn't get answered +// (claudetui.Unanswered). +type tuiNoStart struct { + err error + asked bool +} func (e *tuiNoStart) Error() string { return e.err.Error() } func (e *tuiNoStart) Unwrap() error { return e.err } diff --git a/internal/gateway/claude_tui_start_test.go b/internal/gateway/claude_tui_start_test.go index 3cab3aa85..e10d01edf 100644 --- a/internal/gateway/claude_tui_start_test.go +++ b/internal/gateway/claude_tui_start_test.go @@ -1,6 +1,7 @@ package gateway import ( + "net/http/httptest" "os" "path/filepath" "strings" @@ -8,6 +9,7 @@ import ( "time" "github.com/yetone/magpie/internal/claudetui" + "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/testenv" ) @@ -145,3 +147,28 @@ exit 1`) }) } } + +// A question Claude Code's interactive mode asked and the helper couldn't +// get answered (the trust question, which Claude Code 2.1.329 asked +// where the helper didn't see it) is asked the same under every account: +// the turn is a 400 no account rests for, and the next account isn't +// asked. It was a 502, and every account waited out its 45s in turn +// before the client had it (@ahz2ygnhjmIJ0E0 on X). +func TestClaudeTUIUnansweredQuestionIsNoAccountsFault(t *testing.T) { + said := "Claude Code asked whether to trust /work" + claudetui.Unanswered + "45s: Quick safety check ❯ No, exit Yes, I trust this folder" + h, started := tuiHelperHarness(t, `echo "claude-tui: `+said+`" >&2 +exit 1`) + body := `{"model":"claude-sonnet-5","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}` + var u Usage + rec := httptest.NewRecorder() + code, msg := h.s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u) + if code != 400 || !strings.Contains(msg, said) { + t.Fatalf("%d %.300s", code, msg) + } + if retryable(code, rec.Body.Bytes()) { + t.Fatalf("the unanswered question is asked of the next account: %s", rec.Body.String()) + } + if n := helperStarts(started); n != 1 { + t.Fatalf("the helper started %d times, want once", n) + } +}