claude: a turn Claude Code ends with no answer is a 502 saying why, not a 200 with content null
steven_4422 (Discord) sent 18 PNG frames as image_url parts to
claude/claude-sonnet-5-5 in a Chat request, not streamed, and got 200
with {"message":{"content":null},"finish_reason":"stop"} and zero
usage; 17 were answered. Whatever ended Claude Code's turn, the bridge
took an end with nothing said as the answer:
- a run that exits with a request waiting and nothing begun (the
interactive helper at its deadline, or failing to send the message,
exits 1 with the reason on stderr) closed the segment empty;
- a turn whose result came with no message, or only a <synthetic> one
of Claude Code's own words, left the segment open to be closed empty
by the exit or the run's timeout;
- relay finished a reply whose events ended with neither a KStop nor a
KError: the collector's empty result went as a 200, a stream ended
as a finished reply.
Now readOutput ends such a turn with a 502 carrying Claude Code's own
words, else its result's, else "said nothing of why"; the exit
goroutine emits "Claude Code ended before it answered" with its exit
and stderr; relay turns an unended reply into a 502 (whole) or an
error event (stream) in every protocol. A 5xx lets another account
take over, as other bridge failures do.
Claude Code itself (2.1.316, read from its binary and run on mote
against a fake Messages API) has no image-count limit: it passed 18,
24 and 40 images through, by -p and by the interactive helper, and
turns the API's refusal of an image into an is_error result, already
a 4xx/5xx here. So 18+ images are passed through, and what refused or
dropped the reporter's turn is upstream of magpie; the client now gets
its reason instead of an empty answer.
Run (mote, at this head, rebased on 0f8c3d867):
- go test -tags nogui -race -count=1 -timeout 45m ./internal/gateway/
./internal/claudetui/: ok (gateway 1607s,
claudetui 131s), no races.
- GOOS=linux and GOOS=windows go vet of both packages: ok; gofmt -l clean.
- Full suite: not run at push.
Broken by hand: with claude_subscription.go at its parent and the new
tests kept, all 36 TestClaudeSilentTurnFails cases and all 4
TestRelayUnendedReplyFails cases are red: the exit variant, not
streamed, gives the reporter's body byte for byte (200, content null,
zero usage); streamed, a 502 with no reason; the result and synthetic
variants hang until the test's 20s deadline.
Not tried: a real Claude account at 18+ images (no credentials on
mote, and the Keychain is off-limits), so the upstream reason for the
reporter's turn is unknown; the interactive mode through the gateway
against real Claude Code (the helper alone was run with 18 and 40
images against a fake API).
Reported-by: steven_4422 (Discord)
This commit is contained in:
@@ -0,0 +1,209 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/claudetui"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// claudeSilentAt is a Claude subscription with one account whose Claude
|
||||
// Code answers a message of at most 17 images, saying how many it got,
|
||||
// and one of 18 or more with past's shell lines. Control requests (the
|
||||
// interactive mode's initialize) are acknowledged.
|
||||
func claudeSilentAt(t *testing.T, past string) {
|
||||
t.Helper()
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a shell script stands in for Claude Code")
|
||||
}
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
restingUntil.Lock()
|
||||
restingUntil.m = map[string]time.Time{}
|
||||
restingUntil.Unlock()
|
||||
far := time.Now().Add(24 * time.Hour).UnixMilli()
|
||||
oauth := map[string]any{"claudeAiOauth": map[string]any{"accessToken": "tok-me", "refreshToken": "r", "expiresAt": far, "subscriptionType": "max"}}
|
||||
os.MkdirAll(filepath.Join(home, ".claude"), 0o755)
|
||||
os.WriteFile(filepath.Join(home, ".claude", ".credentials.json"), mustJSON(oauth), 0o600)
|
||||
os.WriteFile(filepath.Join(home, ".claude.json"), mustJSON(map[string]any{
|
||||
"oauthAccount": map[string]any{"emailAddress": "me@example.com", "accountUuid": "u-me"}}), 0o600)
|
||||
os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
|
||||
os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), mustJSON([]map[string]any{
|
||||
{"agent": "claude", "user": "me@example.com", "plan": "max", "on": true, "seen": time.Now(), "auth": oauth},
|
||||
}), 0o600)
|
||||
dir := t.TempDir()
|
||||
script := `#!/bin/sh
|
||||
if [ "$1" = auth ]; then echo '{"loggedIn":true,"authMethod":"oauth_token","apiProvider":"firstParty"}'; exit 0; fi
|
||||
while read -r line; do
|
||||
case $line in *'"type":"control_request"'*)
|
||||
id=$(printf '%s' "$line" | sed 's/.*"request_id":"\([^"]*\)".*/\1/')
|
||||
echo '{"type":"control_response","response":{"subtype":"success","request_id":"'$id'"}}'
|
||||
continue ;;
|
||||
esac
|
||||
n=$(printf '%s' "$line" | grep -o '"type":"image"' | wc -l | tr -d ' ')
|
||||
if [ "$n" -le 17 ]; then
|
||||
echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5-5","usage":{"input_tokens":22933}}}}'
|
||||
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"saw '$n' frames"}}}'
|
||||
echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":4}}}'
|
||||
echo '{"type":"stream_event","event":{"type":"message_stop"}}'
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
|
||||
else
|
||||
` + past + ` fi
|
||||
done
|
||||
`
|
||||
testenv.Program(t, filepath.Join(dir, "claude"), script)
|
||||
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
provider.ForgetAccounts()
|
||||
t.Cleanup(provider.ForgetAccounts)
|
||||
runsEndWithTest(t, dir)
|
||||
}
|
||||
|
||||
// The reporter's request, in each protocol: n copies of a small PNG, as
|
||||
// data URLs in Chat's image_url parts (steven_4422's), and as each other
|
||||
// protocol carries an image.
|
||||
func manyImages(path string, n int, stream bool) string {
|
||||
const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
|
||||
var parts []string
|
||||
switch path {
|
||||
case "/v1/chat/completions":
|
||||
parts = append(parts, `{"type":"text","text":"Describe each frame."}`)
|
||||
for range n {
|
||||
parts = append(parts, `{"type":"image_url","image_url":{"url":"data:image/png;base64,`+png+`"}}`)
|
||||
}
|
||||
return fmt.Sprintf(`{"model":"claude/claude-sonnet-5-5","stream":%v,"messages":[{"role":"user","content":[%s]}]}`, stream, strings.Join(parts, ","))
|
||||
case "/v1/messages":
|
||||
parts = append(parts, `{"type":"text","text":"Describe each frame."}`)
|
||||
for range n {
|
||||
parts = append(parts, `{"type":"image","source":{"type":"base64","media_type":"image/png","data":"`+png+`"}}`)
|
||||
}
|
||||
return fmt.Sprintf(`{"model":"claude/claude-sonnet-5-5","max_tokens":100,"stream":%v,"messages":[{"role":"user","content":[%s]}]}`, stream, strings.Join(parts, ","))
|
||||
default:
|
||||
parts = append(parts, `{"type":"input_text","text":"Describe each frame."}`)
|
||||
for range n {
|
||||
parts = append(parts, `{"type":"input_image","image_url":"data:image/png;base64,`+png+`"}`)
|
||||
}
|
||||
return fmt.Sprintf(`{"model":"claude/claude-sonnet-5-5","stream":%v,"input":[{"role":"user","content":[%s]}]}`, stream, strings.Join(parts, ","))
|
||||
}
|
||||
}
|
||||
|
||||
// A Claude subscription turn Claude Code ends with no message is a
|
||||
// failure that says why, in every protocol, streamed or not, by -p and
|
||||
// by the interactive mode. steven_4422 sent 18 PNGs to
|
||||
// claude/claude-sonnet-5-5 in a Chat request not streamed and was
|
||||
// answered 200 with content null and no usage, as if that were the
|
||||
// answer; 17 were answered. Claude Code's run had ended the turn with
|
||||
// nothing said: the bridge closed the reply with nothing in it.
|
||||
func TestClaudeSilentTurnFails(t *testing.T) {
|
||||
pasts := []struct{ name, lines, why string }{
|
||||
// its result says it succeeded, with no message before it
|
||||
{"result", ` echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
|
||||
`, "ended the turn without an answer"},
|
||||
// only words of its own, a message no model wrote
|
||||
{"synthetic", ` echo '{"type":"assistant","message":{"id":"s1","model":"<synthetic>","role":"assistant","content":[{"type":"text","text":"No response requested."}]}}'
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":"No response requested."}'
|
||||
`, "No response requested."},
|
||||
// it exits, saying why on its stderr only
|
||||
{"exit", ` echo 'claude-tui: Claude Code did not take the message' >&2
|
||||
exit 1
|
||||
`, "did not take the message"},
|
||||
}
|
||||
asks := []string{"/v1/chat/completions", "/v1/messages", "/v1/responses"}
|
||||
for _, tui := range []bool{false, true} {
|
||||
for _, past := range pasts {
|
||||
for _, path := range asks {
|
||||
for _, stream := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("tui=%v/%s%s/stream=%v", tui, past.name, path, stream), func(t *testing.T) {
|
||||
claudeSilentAt(t, past.lines)
|
||||
if tui {
|
||||
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\nshift; claude=$1; shift\nexec \"$claude\" \"$@\"\n")
|
||||
claudeTUIHelper = helper
|
||||
t.Cleanup(func() { claudeTUIHelper = "" })
|
||||
}
|
||||
s := New()
|
||||
t.Cleanup(s.subscription.abortAll)
|
||||
send := func(n int) (int, string) {
|
||||
type answer struct {
|
||||
code int
|
||||
body string
|
||||
}
|
||||
done := make(chan answer, 1)
|
||||
go func() {
|
||||
code, body := sendTo(s, path, manyImages(path, n, stream))
|
||||
done <- answer{code, body}
|
||||
}()
|
||||
select {
|
||||
case a := <-done:
|
||||
return a.code, a.body
|
||||
case <-time.After(20 * time.Second):
|
||||
t.Fatalf("%d images: the reply waited on a turn that had ended", n)
|
||||
}
|
||||
return 0, ""
|
||||
}
|
||||
// 17 reach Claude Code, all of them, and are answered
|
||||
if code, body := send(17); code != 200 || !strings.Contains(body, "saw 17 frames") {
|
||||
t.Fatalf("17 images: status %d: %s", code, body)
|
||||
}
|
||||
code, body := send(18)
|
||||
if code != 502 || !strings.Contains(body, past.why) {
|
||||
t.Fatalf("18 images: status %d, not a 502 saying %q:\n%s", code, past.why, body)
|
||||
}
|
||||
if strings.Contains(body, `"content":null`) || strings.Contains(body, "saw 18") {
|
||||
t.Fatalf("18 images: an answer of nothing:\n%s", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A reply whose events end with neither its stop nor an error — a run
|
||||
// ended by magpie (its timeout) with nothing said, or cut part way — is
|
||||
// a failure, not a finished reply of nothing, streamed or not.
|
||||
func TestRelayUnendedReplyFails(t *testing.T) {
|
||||
for _, said := range []string{"", "half an ans"} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("said=%q/stream=%v", said, stream), func(t *testing.T) {
|
||||
events := make(chan Event, 4)
|
||||
events <- Event{Kind: KStart, Model: "claude-sonnet-5-5"}
|
||||
if said != "" {
|
||||
events <- Event{Kind: KText, Text: said}
|
||||
}
|
||||
close(events)
|
||||
rec := httptest.NewRecorder()
|
||||
r := httptest.NewRequest("POST", "/v1/chat/completions", nil)
|
||||
var u Usage
|
||||
var ok bool
|
||||
aborted := false
|
||||
code, msg := relay(rec, r, provider.Chat, "Claude Code", &Request{Model: "claude-sonnet-5-5", Stream: stream}, events, &u,
|
||||
func() { aborted = true }, nil, func(_, _ string, o bool) { ok = o })
|
||||
if msg == "" || ok {
|
||||
t.Fatalf("status %d, failed %q, ended ok %v:\n%s", code, msg, ok, rec.Body.String())
|
||||
}
|
||||
if stream {
|
||||
if !strings.Contains(rec.Body.String(), `"error":{`) || strings.Contains(rec.Body.String(), "[DONE]") {
|
||||
t.Fatalf("a stream finished as a reply:\n%s", rec.Body.String())
|
||||
}
|
||||
return
|
||||
}
|
||||
if code != 502 || !aborted || strings.Contains(rec.Body.String(), `"choices"`) {
|
||||
t.Fatalf("status %d, aborted %v:\n%s", code, aborted, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3793,6 +3793,14 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
// message, as after Claude Code's own call. Only once a reply: told
|
||||
// again, the words go to the client as written.
|
||||
var calls textCalls
|
||||
// A turn whose result came with no message begun since the last one:
|
||||
// Claude Code took the user's message and answered nothing, or only
|
||||
// in words of its own (<synthetic>). Its segment, left open, was
|
||||
// closed empty when the run ended, and a reply asked for whole went
|
||||
// as a 200 with no content and no usage, which the client took for
|
||||
// the answer (steven_4422, 18 images to claude-sonnet-5-5).
|
||||
begun := false // a message began since the turn's last result
|
||||
aside := "" // what Claude Code said in its own words this turn
|
||||
retell := false // the run is told to make its calls once this turn's result is in
|
||||
answerAsked := false // the interactive mode's turn was asked for its answer tool's call
|
||||
retold := false // this reply was told so
|
||||
@@ -3908,6 +3916,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
return
|
||||
}
|
||||
replyModel = model
|
||||
begun = true
|
||||
before, this = lateUsage.gateway(), Usage{}
|
||||
lateUsage = cliUsage{}
|
||||
calls, retold = textCalls{}, false
|
||||
@@ -4169,6 +4178,8 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
}
|
||||
if envelope.Type == "result" {
|
||||
retell, answerAsked = false, false
|
||||
silent, said := !begun, aside
|
||||
begun, aside = false, ""
|
||||
// a turn that failed — out of quota, rate limited — ends with
|
||||
// this and no message_stop, the CLI waiting on its next input:
|
||||
// the reply ends here, or it would wait with it (#177)
|
||||
@@ -4210,9 +4221,19 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
case waiting:
|
||||
r.emit(Event{Kind: KError, Text: "Claude Code ended the turn with no answer fitting the schema", RequestID: reqID})
|
||||
r.endSegment()
|
||||
case silent && r.waitingOnReply():
|
||||
r.emit(Event{Kind: KError, Text: noAnswer(said, envelope.Result), Status: http.StatusBadGateway, RequestID: reqID})
|
||||
r.endSegment()
|
||||
}
|
||||
return
|
||||
}
|
||||
if envelope.Type == "assistant" && whole.Model == "<synthetic>" {
|
||||
for _, c := range whole.Content {
|
||||
if c.Type == "text" && strings.TrimSpace(c.Text) != "" {
|
||||
aside = strings.TrimSpace(c.Text)
|
||||
}
|
||||
}
|
||||
}
|
||||
if envelope.Type == "assistant" {
|
||||
// a failure says how it failed here, before its result
|
||||
if envelope.RequestID != "" {
|
||||
@@ -4426,6 +4447,29 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
}
|
||||
}
|
||||
|
||||
// waitingOnReply is whether a request waits on the run's segment.
|
||||
func (r *subscriptionRun) waitingOnReply() bool {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.segment != nil
|
||||
}
|
||||
|
||||
// noAnswer is the error of a turn Claude Code ended with no message:
|
||||
// what it said in its own words, else its result's, else that it said
|
||||
// nothing.
|
||||
func noAnswer(said, result string) string {
|
||||
why := "Claude Code ended the turn without an answer"
|
||||
for _, w := range []string{said, strings.TrimSpace(result)} {
|
||||
if len(w) > 300 {
|
||||
w = strings.ToValidUTF8(w[:300], "") + "…"
|
||||
}
|
||||
if w != "" {
|
||||
return why + ": " + w
|
||||
}
|
||||
}
|
||||
return why + ", and said nothing of why"
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -5974,6 +6018,12 @@ func (r *subscriptionRun) launch() error {
|
||||
}
|
||||
if err := r.schemaEnded(); err != nil {
|
||||
r.emit(Event{Kind: KError, Text: err.Error(), Status: http.StatusBadRequest})
|
||||
} else if r.waitingOnReply() {
|
||||
// it ended with a request waiting on it and nothing of the
|
||||
// reply begun (a reply begun is readOutput's): closed as it
|
||||
// was, the segment went as an answer of nothing. Its exit
|
||||
// and stderr say why, the interactive helper's its deadline
|
||||
r.emit(Event{Kind: KError, Text: "Claude Code " + r.endedBefore("answered").Error(), Status: http.StatusBadGateway})
|
||||
}
|
||||
r.finish()
|
||||
}()
|
||||
@@ -6829,6 +6879,15 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro
|
||||
return code, msg
|
||||
}
|
||||
|
||||
// unansweredWhy is the error of a bridged reply that ended with neither
|
||||
// its stop nor an error: nothing said, or its words cut short.
|
||||
func unansweredWhy(said string) string {
|
||||
if said == "" {
|
||||
return "it ended without an answer"
|
||||
}
|
||||
return errEndedShort.Error()
|
||||
}
|
||||
|
||||
// bridgeFailed is the status and words a client is answered with when an
|
||||
// agent's run ended in an error before any answer: the status the agent
|
||||
// got, else a guess from the words, else 502.
|
||||
@@ -7154,6 +7213,12 @@ func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name
|
||||
see(ev)
|
||||
return true
|
||||
})
|
||||
// a reply that ended with neither its stop nor an error was cut
|
||||
// short, or never said: finished, it went as the turn's end, the
|
||||
// client taking nothing, or part of the answer, for the answer
|
||||
if failed == "" && stop == "" && r.Context().Err() == nil {
|
||||
see(Event{Kind: KError, Text: name + ": " + unansweredWhy(said), Status: http.StatusBadGateway})
|
||||
}
|
||||
// before the reply's last event, which the agent may answer at once
|
||||
ended(said, stop, failed == "" && r.Context().Err() == nil)
|
||||
// an error event already ended the reply in the client's protocol
|
||||
@@ -7173,6 +7238,12 @@ func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name
|
||||
}
|
||||
col.add(ev)
|
||||
}
|
||||
if col.err == "" && stop == "" && r.Context().Err() == nil {
|
||||
// as in a stream: an answer of nothing, the reply's segment
|
||||
// closed with nothing said, went as a 200 with content null and
|
||||
// no usage (steven_4422)
|
||||
col.err, col.errStatus = unansweredWhy(said), http.StatusBadGateway
|
||||
}
|
||||
if col.err != "" {
|
||||
abort()
|
||||
// a status, as in a stream, so another account can take over;
|
||||
|
||||
Reference in New Issue
Block a user