diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 85f8c7a08..7355a66e3 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -608,6 +608,22 @@ exit status and the end of its stderr (`endedBefore`), as one that ends before it reads its input is (`whyEnded`). The tool-results path and `resume` already start a new run when the one they found has ended. +A Claude Code whose output ends after its reply began (a `KStart` on the +segment) and before the reply ended (its stop, a refusal, a result or an +error) exited mid-reply: only the `message_start`, or part of the text, +was heard. `readOutput` ends the segment with an error, "Claude Code +exited before it ended its reply" and the end of its stderr +(`replyUnended`, #4822), in `-p` and the interactive mode alike. Before +it, the closed segment was a 200 with nothing or the words so far, as a +reply that ended. Now `relay` answers a stream with nothing sent yet, and +any reply not streamed, a 502, so the spare account may answer (the cut +try keeps its usage row as handed on). A stream already sent ends in the +protocol's error event: Anthropic's `error`, chat's `error` chunk with no +`[DONE]`, Responses' `response.failed`. A reply not streamed whose words +came before any failure is a failure too, as a translated reply cut short +is (`errEndedShort`). `TestClaudeSubscriptionRunExitedMidReplyFails` +holds it on all three protocols, streamed and not, `-p` and interactive. + magpie ends a run (`abort`) by asking Claude Code to end with SIGTERM (`proc.Tree.Stop`) and kills its tree only once it has exited or `stopGrace` (5s) has passed; Windows kills the job at once. Claude Code diff --git a/internal/gateway/claude_cut_run_test.go b/internal/gateway/claude_cut_run_test.go new file mode 100644 index 000000000..6e510f50d --- /dev/null +++ b/internal/gateway/claude_cut_run_test.go @@ -0,0 +1,112 @@ +package gateway + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/claudetui" + "github.com/yetone/magpie/internal/testenv" + "github.com/yetone/magpie/internal/usage" +) + +// A Claude subscription run whose Claude Code exits after its reply +// began, with no message_stop nor a result, is a failure the agent sees, +// in every protocol a Claude subscription is served on, by -p and by the +// interactive mode. It was a 200 with nothing, or the words so far, as a +// reply that ended (#4822). Exited after its message_start alone, the +// spare account answers, as for any failure before the answer. Exited +// part way through the text, a stream already sent has the protocol's +// error event and no end, and the account isn't asked again; a reply not +// streamed has had nothing sent, and is a failure the spare answers. +func TestClaudeSubscriptionRunExitedMidReplyFails(t *testing.T) { + start := ` echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m1","model":"claude-sonnet-5","usage":{"input_tokens":3,"cache_creation_input_tokens":900}}}}' +` + text := start + ` echo '{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}' + echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"half an ans"}}}' +` + asks := []struct{ path, body string }{ + {"/v1/messages", `{"model":"claude/claude-sonnet-5","max_tokens":50,"stream":%v,"messages":[{"role":"user","content":"ping"}]}`}, + {"/v1/chat/completions", `{"model":"claude/claude-sonnet-5","stream":%v,"messages":[{"role":"user","content":"ping"}]}`}, + {"/v1/responses", `{"model":"claude/claude-sonnet-5","stream":%v,"input":[{"role":"user","content":[{"type":"input_text","text":"ping"}]}]}`}, + } + // what each protocol's stream ends a reply with, and fails one with + ends := map[string][2]string{ + "/v1/messages": {"event: message_stop", "event: error"}, + "/v1/chat/completions": {"data: [DONE]", `"error":{`}, + "/v1/responses": {"response.completed", "response.failed"}, + } + for _, tui := range []bool{false, true} { + for _, cut := range []string{"start", "text"} { + for _, ask := range asks { + for _, stream := range []bool{true, false} { + t.Run(fmt.Sprintf("tui=%v/%s/%s/stream=%v", tui, cut, ask.path, stream), func(t *testing.T) { + first := start + if cut == "text" { + first = text + } + log := claudeSubscriptionFirstSays(t, first+" exit 0\n") + helped := filepath.Join(t.TempDir(), "helped") + if tui { + // the interactive mode, its helper a stand-in + // running the Claude Code it was handed + claudeTUIRuns = true + t.Cleanup(func() { claudeTUIRuns = false }) + helper := filepath.Join(t.TempDir(), "magpie") + testenv.Program(t, helper, "#!/bin/sh\n[ \"$1\" = \""+claudetui.Command+"\" ] || exit 9\necho start >> '"+helped+"'\nshift; claude=$1; shift\nexec \"$claude\" \"$@\"\n") + claudeTUIHelper = helper + t.Cleanup(func() { claudeTUIHelper = "" }) + } + s := New() + t.Cleanup(s.subscription.abortAll) + code, reply := sendTo(s, ask.path, fmt.Sprintf(ask.body, stream)) + b, _ := os.ReadFile(log) + runs := strings.Join(strings.Fields(string(b)), ",") + if tui { + if n := helperStarts(helped); n != strings.Count(runs, ",")+1 { + t.Fatalf("the helper started %d times for runs %q", n, runs) + } + } + if cut == "text" && stream { + // the words so far went out; the reply fails + // where it was cut, and no other run tells it + // again under them + end := ends[ask.path] + if code != 200 || !strings.Contains(reply, "half an ans") || !strings.Contains(reply, end[1]) || + strings.Contains(reply, end[0]) || strings.Contains(reply, "pong") || runs != "own" { + t.Fatalf("status %d (runs %q):\n%s", code, runs, reply) + } + if !strings.Contains(reply, "exited before it ended its reply") { + t.Fatalf("the error doesn't say why:\n%s", reply) + } + return + } + // nothing has reached the client: the spare answers + if code != 200 || !strings.Contains(reply, "pong") || strings.Contains(reply, "half an ans") || runs != "own,tok-spare" { + t.Fatalf("status %d (runs %q):\n%s", code, runs, reply) + } + r := lastRoute(s) + if len(r.Tries) != 2 || r.Tries[0].Status < 500 || !strings.Contains(r.Tries[0].Error, "exited before it ended its reply") { + t.Fatalf("tries: %+v", r.Tries) + } + // what the cut try billed keeps its row (d2a83de61) + var handed []usage.Record + for deadline := time.Now().Add(10 * time.Second); len(handed) == 0 && time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { + for _, u := range usage.Load(time.Time{}) { + if u.RouteID == r.ID && u.HandedOn { + handed = append(handed, u) + } + } + } + if len(handed) != 1 || handed[0].ProviderAccount != "me@example.com" || handed[0].CacheWrite != 900 { + t.Fatalf("the cut try's row: %+v", handed) + } + }) + } + } + } + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 327f08bae..aeb30809c 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -342,6 +342,10 @@ type subscriptionRun struct { // the client was told them: a client that names them by ids of its own // (AmpCode) has its results paired with them by position (remap) shown []shownCall + // unended is whether the segment's reply has begun (KStart) and not + // ended, by its stop or an error, under r.mu: a Claude Code whose + // output ends then exited mid-reply (readOutput) + unended bool // lines is where in its session each call of the client's tools its // replies made was written, by Claude Code's id for the call: a @@ -2908,6 +2912,7 @@ func (r *subscriptionRun) attach() chan Event { ch := make(chan Event, 64) r.segment = ch r.active = time.Now() + r.unended = false return ch } @@ -2919,7 +2924,9 @@ func (r *subscriptionRun) emit(ev Event) { if ch != nil { switch ev.Kind { case KStart: // a reply begins - r.shown = nil + r.shown, r.unended = nil, true + case KStop, KError: + r.unended = false case KToolStart: r.shown = append(r.shown, shownCall{id: ev.ID, name: ev.Name}) case KToolArgs: @@ -3592,9 +3599,26 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { failed("and Claude Code stopped") } else if refused { refusal() + } else if r.replyUnended() { + // Claude Code exited after its reply began, with no message_stop + // nor a result: only its message_start, or part of its text, was + // heard. Closed as it was, the segment went to the client as a + // reply that ended, a 200 with nothing or part of the answer, and + // the agent took it as done (#4822). It is a failure: a status + // before anything was sent, else the stream's error event + r.emit(Event{Kind: KError, Text: "Claude Code " + r.endedBefore("ended its reply").Error(), Status: http.StatusBadGateway, RequestID: reqID}) + r.endSegment() } } +// replyUnended is whether a reply was begun on the run's segment, which +// is still open, and hasn't ended. +func (r *subscriptionRun) replyUnended() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.segment != nil && r.unended +} + // unstreamedQuiet is how long a message told in whole messages is taken // as whole once none of its blocks come: Claude Code writes them all at // once. @@ -5935,10 +5959,15 @@ func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name } col.add(ev) } - if col.err != "" && !saidAnything(col.res.Parts) { + if col.err != "" { abort() // a status, as in a stream, so another account can take over; - // what the reply's start used is the failed try's + // what the reply's start used is the failed try's. Words said + // before the failure are no answer either: handed whole, they + // went as a 200, the turn's end, and the agent took a reply cut + // short for a finished one (#4822); nothing has reached the + // client yet, so it is told the failure, as a translated reply + // cut short is (errEndedShort) usage.add(col.res.Usage) usage.add(Usage{ErrType: col.errCode}) code, msg := bridgeFailed(name, col.err, col.errStatus) diff --git a/internal/gateway/refusal_accounts_test.go b/internal/gateway/refusal_accounts_test.go index 4ce8ef7af..bd7735a1b 100644 --- a/internal/gateway/refusal_accounts_test.go +++ b/internal/gateway/refusal_accounts_test.go @@ -235,7 +235,8 @@ func claudeSubscriptionRefusing(t *testing.T) string { } // claudeSubscriptionFirstSays is claudeSubscriptionRefusing with the first -// account's run writing first, shell lines, for each turn. +// account's run writing first, shell lines, for each turn. Control +// requests (the interactive mode's initialize) are acknowledged. func claudeSubscriptionFirstSays(t *testing.T, first string) string { t.Helper() if runtime.GOOS == "windows" { @@ -269,6 +270,12 @@ if [ "$1" = auth ]; then echo '{"loggedIn":true,"authMethod":"oauth_token","apiP TOK=; [ -n "$CLAUDE_CONFIG_DIR" ] && TOK=$(sed -n 's/.*"accessToken": *"\([^"]*\)".*/\1/p' "$CLAUDE_CONFIG_DIR/.credentials.json") echo "${TOK:-own}" >> ` + log + ` while read -r line; do + case $line in *'"type":"control_request"'*) + # acknowledged as Claude Code does: the interactive mode's initialize + id=$(printf '%s' "$line" | sed 's/.*"request_id":"\([^"]*\)".*/\1/') + echo '{"type":"control_response","response":{"subtype":"success","request_id":"'$id'"}}' + continue ;; + esac if [ -z "$TOK" ] || [ "$TOK" = tok-me ]; then ` + first + ` else echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}'