From 3eae3ee7fbbd7f77c3ac2875b35ea6e9a479f1ea Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 4 Oct 2026 14:08:35 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20a=20Claude=20stream=20held=20for=20i?= =?UTF-8?q?ts=20reasoning=20keeps=20the=20agent=20alive=20with=20SSE=20com?= =?UTF-8?q?ments,=20and=20a=20request=20whose=20agent=20went=20away=20is?= =?UTF-8?q?=20recorded=20as=20canceled,=20not=20as=20a=20200=20done=20(#75?= =?UTF-8?q?1,=20margbug01=20on=20v0.1.679:=20Alma=20=E2=86=92=20magpie=20?= =?UTF-8?q?=E2=86=92=20Claude=20Code=20(Claude=20Max,=20claude-opus-5-5)?= =?UTF-8?q?=20ended=20with=20"No=20LLM=20streaming=20data=20for=20240000ms?= =?UTF-8?q?",=20while=20the=20routing=20record=20said=20200,=20about=20240?= =?UTF-8?q?000=20ms,=20TTFT=20about=204.3=20s,=208=20tokens=20out,=20done?= =?UTF-8?q?=20with=20no=20error)=20=E2=80=94=20for=20a=20Claude=20model,?= =?UTF-8?q?=20refusesAfterThinking,=20a=20stream=20that=20holds=20nothing?= =?UTF-8?q?=20but=20reasoning=20is=20held=20for=20up=20to=20holdThinking?= =?UTF-8?q?=20(4=20minutes)=20so=20that=20a=20refusal=20after=20it=20can?= =?UTF-8?q?=20still=20go=20to=20another=20account=20(#248).=20Everything?= =?UTF-8?q?=20written=20meanwhile=20was=20held=20with=20it:=20message=5Fst?= =?UTF-8?q?art,=20the=20thinking=20deltas=20and=20the=20protocol=20keepali?= =?UTF-8?q?ves=20relay=20sends=20every=2015s=20(#436).=20The=20agent=20got?= =?UTF-8?q?=20no=20byte=20at=20all,=20and=20Alma's=20idle=20timeout=20for?= =?UTF-8?q?=20a=20reasoning=20model=20(60s=20=C3=974=20=3D=20240s,=20reset?= =?UTF-8?q?=20by=20any=20SSE=20line,=20comments=20included)=20ran=20out=20?= =?UTF-8?q?first.=20The=20hold=20is=20on=20for=20nearly=20every=20first=20?= =?UTF-8?q?try=20(!last=20||=20again=20<=20retries=20||=20=E2=80=A6),=20so?= =?UTF-8?q?=20one=20Claude=20account=20alone=20was=20enough.=20The=20TTFT?= =?UTF-8?q?=20on=20the=20record=20is=20the=20held=20stream's=20first=20eve?= =?UTF-8?q?nt,=20not=20a=20byte=20delivered.=20Now,=20once=20a=20stream=20?= =?UTF-8?q?has=20been=20held=20for=20its=20thinking=20or=20safety=20buffer?= =?UTF-8?q?ing=20past=20keepHeldAfter=20(holdLongest,=2015s),=20holdWriter?= =?UTF-8?q?.keepAlive=20sends=20the=20agent=20the=20stream's=20200=20and?= =?UTF-8?q?=20headers=20once,=20then=20a=20":=20keepalive"=20comment=20eve?= =?UTF-8?q?ry=20keepaliveEvery=20while=20the=20stream=20stays=20held.=20Th?= =?UTF-8?q?e=20comment=20is=20not=20an=20event=20in=20any=20protocol=20and?= =?UTF-8?q?=20says=20nothing=20of=20the=20reasoning,=20and=20no=20model=20?= =?UTF-8?q?text=20is=20made=20up.=20The=20keptAlive=20is=20the=20request's?= =?UTF-8?q?=20and=20is=20shared=20by=20its=20tries.=20A=20refusal=20after?= =?UTF-8?q?=20the=20comments=20still=20goes=20to=20the=20next=20member:=20?= =?UTF-8?q?its=20pass()=20skips=20the=20headers=20already=20sent,=20and=20?= =?UTF-8?q?its=20stream=20follows=20in=20the=20same=20response.=20Once=20h?= =?UTF-8?q?eaders=20are=20out,=20a=20failure=20can=20no=20longer=20be=20a?= =?UTF-8?q?=20status,=20so=20the=20gateway's=20writeErrors=20inside=20the?= =?UTF-8?q?=20try=20loop=20go=20through=20failTo=20and=20holdWriter.releas?= =?UTF-8?q?e=20goes=20through=20streamError,=20which=20tell=20it=20as=20th?= =?UTF-8?q?e=20stream's=20own=20error=20event=20(Anthropic=20event:=20erro?= =?UTF-8?q?r,=20Responses=20response.failed,=20Chat's=20error=20chunk).=20?= =?UTF-8?q?The=20last=20try's=20writer=20is=20held=20too=20once=20headers?= =?UTF-8?q?=20are=20out.=20A=20Responses=20agent=20(Codex)=20doesn't=20cou?= =?UTF-8?q?nt=20comments,=20but=20its=20300s=20timeout=20outlasts=20the=20?= =?UTF-8?q?4-minute=20hold.=20When=20the=20agent=20went=20away,=20serveSub?= =?UTF-8?q?scription's=20AfterFunc=20stopped=20Claude=20Code,=20but=20rela?= =?UTF-8?q?y=20still=20called=20enc.finish(),=20which=20wrote=20message=5F?= =?UTF-8?q?stop=20to=20the=20gone=20writer.=20holdWriter.see=20took=20that?= =?UTF-8?q?=20as=20the=20reply=20made=20whole=20(ended),=20so=20serve's=20?= =?UTF-8?q?`r.Context().Err()=20!=3D=20nil=20&&=20!hw.ended`=20check,=20wh?= =?UTF-8?q?ich=20records=20499=20"the=20agent=20canceled=20the=20request"?= =?UTF-8?q?=20with=20Fail=20canceled,=20was=20skipped=20and=20the=20reques?= =?UTF-8?q?t=20was=20recorded=20as=20200=20done.=20see=20now=20ignores=20a?= =?UTF-8?q?=20stream=20end=20written=20once=20the=20request's=20context=20?= =?UTF-8?q?is=20done,=20and=20the=20bridge=20logs=20"Claude=20Code=20run?= =?UTF-8?q?=20on=20=20stopped:=20the=20client=20went=20away=20?= =?UTF-8?q?=20into=20the=20reply".=20TestHeldThinkingKeepsTheAgentAlive=20?= =?UTF-8?q?sends=20claude-opus-5-5=20thinking=20that=20goes=20on=20(pings?= =?UTF-8?q?=20every=2010ms=20until=20the=20client=20hears=20a=20keepalive,?= =?UTF-8?q?=20else=203s)=20through=20a=20group=20over=20a=20real=20HTTP=20?= =?UTF-8?q?gateway.=20It=20covers=20three=20cases:=20a=20refusal=20after?= =?UTF-8?q?=20it,=20where=20the=20client=20gets=20":=20keepalive"=20before?= =?UTF-8?q?=20b's=20answer=20in=20the=20same=20stream,=20with=20one=20mess?= =?UTF-8?q?age=5Fstart,=20no=20reasoning=20text=20and=20Tries[0]=20refused?= =?UTF-8?q?;=20an=20answer=20after=20it,=20which=20arrives=20whole=20after?= =?UTF-8?q?=20the=20comments;=20and=20a=20refusal=20with=20nobody=20left,?= =?UTF-8?q?=20which=20arrives=20as=20a=20200=20stream=20with=20event:=20er?= =?UTF-8?q?ror.=20TestClientGoneRecordedAsCanceled=20checks=20a=20holdWrit?= =?UTF-8?q?er=20whose=20context=20is=20canceled=20before=20message=5Fstop,?= =?UTF-8?q?=20and=20a=20fake=20Claude=20Code=20run=20(fakeClaudeCalling's?= =?UTF-8?q?=20hang)=20stopped=20mid-reply=20through=20serveClaudeSubscript?= =?UTF-8?q?ion=20writing=20to=20a=20holdWriter.=20With=20keepAlive's=20cal?= =?UTF-8?q?l=20and=20see's=20context=20check=20taken=20out,=20both=20fail:?= =?UTF-8?q?=20the=20client=20heard=20nothing=20until=20the=20upstream=20ga?= =?UTF-8?q?ve=20up=20waiting=20at=203s,=20and=20ended=20was=20set.=20go=20?= =?UTF-8?q?vet,=20builds=20(darwin,=20GOOS=3Dlinux,=20GOOS=3Dwindows),=20g?= =?UTF-8?q?o=20test=20-tags=20nogui=20-count=3D1=20./...=20under=20a=20tem?= =?UTF-8?q?p=20HOME,=20and=20-race=20on=20the=20gateway's=20refusal,=20thi?= =?UTF-8?q?nking,=20keepalive=20and=20cancel=20tests=20all=20pass.=20Not?= =?UTF-8?q?=20tried=20with=20real=20Claude=20Code,=20a=20real=20Claude=20M?= =?UTF-8?q?ax=20account=20or=20Alma.=20Not=20changed:=20--thinking-display?= =?UTF-8?q?=20summarized=20is=20passed=20only=20when=20the=20request=20nam?= =?UTF-8?q?es=20an=20effort,=20so=20Claude=20Code's=20own=20thinking=20dis?= =?UTF-8?q?play=20is=20otherwise=20left=20at=20the=20API's=20default;=20re?= =?UTF-8?q?lay's=20keepalives=20stop=205=20minutes=20after=20the=20last=20?= =?UTF-8?q?event=20(keepaliveLongest);=20and=20Gemini=20clients=20get=20no?= =?UTF-8?q?=20keepalive.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/claude_subscription.go | 7 +- internal/gateway/fallback.go | 71 +++++++++- internal/gateway/gateway.go | 42 +++++- internal/gateway/held_keepalive_test.go | 181 ++++++++++++++++++++++++ 4 files changed, 292 insertions(+), 9 deletions(-) create mode 100644 internal/gateway/held_keepalive_test.go diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index b8203c01b..8a1e557ec 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -1775,7 +1775,12 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from // a caller gone before the reply is whole won't carry it on: its agent // is stopped at once, not left to answer no one and wait on tool calls // it never handed over - gone := context.AfterFunc(r.Context(), run.abort) + began := time.Now() + gone := context.AfterFunc(r.Context(), func() { + // said in the log, as the routing trace says it with a 499 (#751) + log.Printf("%s run on %s stopped: the client went away %s into the reply", name, model, time.Since(began).Round(time.Millisecond)) + run.abort() + }) defer gone() return relay(w, r, from, name, req, events, usage, run.abort, func(said, stop string, ok bool) { gone() diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index dc675b557..345874594 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -15,8 +15,10 @@ package gateway import ( "bytes" + "context" "encoding/json" "fmt" + "io" "net/http" "regexp" "slices" @@ -857,6 +859,14 @@ type holdWriter struct { ended bool // the stream's last event was written: the reply is whole tail []byte // the end of the last write, for a marker split across two + // ctx is the agent's request: a stream's last event written once it + // has gone reached nobody, and doesn't make the reply whole (#751) + ctx context.Context + + // alive is the request's, shared by its tries: a stream held for its + // reasoning keeps the agent from its idle timeout with SSE comments + // meanwhile (#751) + alive *keptAlive first firstToken // when its first content and text came (#196) @@ -894,6 +904,11 @@ func (h *holdWriter) WriteHeader(code int) { } func (h *holdWriter) pass() { + if h.alive != nil && h.alive.sent { + // the agent has the stream's headers already, from keepAlive + h.passing = true + return + } dst := h.w.Header() for k, v := range h.header { if k != resetsHeader && k != refusedHeader { // magpie's own notes, for restAfter and settle @@ -931,7 +946,7 @@ var streamEnds = [][]byte{ // see notes a stream's last event going by. An agent may hang up as soon as // it has that — Codex does — and a reply it had whole is not canceled. func (h *holdWriter) see(b []byte) { - if h.ended { + if h.ended || h.ctx != nil && h.ctx.Err() != nil { return } buf := append(h.tail, b...) @@ -1029,6 +1044,54 @@ func (h *holdWriter) scan() { } if h.held.Len() > holdMost || time.Since(h.since) > longest { h.flow() + return + } + if (h.thinking || h.buffered) && time.Since(h.since) >= keepHeldAfter { + h.keepAlive() + } +} + +// keepHeldAfter is how long a stream held for its reasoning waits before +// its agent is first kept alive, as long as a stream with nothing in it +// is held (holdLongest); a refusal after it still goes to another account, +// whose stream follows the comments in the same response. +var keepHeldAfter = holdLongest + +// keptAlive is what a request's held streams have sent its agent ahead of +// a reply: the stream's headers and SSE comments, nothing of the reply. +type keptAlive struct { + proto provider.Protocol + sent bool // the stream's 200 and headers went out + at time.Time // the last comment +} + +// keepAlive tells the agent of a stream held past keepHeldAfter for its +// reasoning that it goes on, every keepaliveEvery: held for up to +// holdThinking (4 minutes), the agent heard nothing at all, and Alma's +// idle timeout for a reasoning model, 240s, ended the turn first (#751). A +// comment is no event in any protocol, so another account may still answer +// after it, its stream going on in the same response (pass). +func (h *holdWriter) keepAlive() { + a := h.alive + if a == nil || time.Since(a.at) < keepaliveEvery { + return + } + if !a.sent { + dst := h.w.Header() + for k, v := range h.header { + if k != resetsHeader && k != refusedHeader && k != "Content-Length" { + dst[k] = v + } + } + dst.Set("Content-Type", "text/event-stream; charset=utf-8") + h.w.WriteHeader(http.StatusOK) + a.sent = true + } + // no blank line after it, as sseWriter.comment + _, _ = io.WriteString(h.w, ": keepalive\n") + a.at = time.Now() + if f, ok := h.w.(http.Flusher); ok { + f.Flush() } } @@ -1101,6 +1164,12 @@ func (h *holdWriter) release() { if h.passing || h.status == 0 { return } + if h.alive != nil && h.alive.sent && !h.stream { + // an error status, once the agent has a stream: told as its error + h.passing = true + streamError(h.w, h.alive.proto, h.status, provider.APIError(h.held.Bytes(), http.StatusText(h.status))) + return + } h.pass() h.w.Write(h.held.Bytes()) h.Flush() diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index eb20f8a41..600a00162 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1343,13 +1343,18 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro providerKeyID, providerKeyName, providerAccount := "", "", "" var other *Try // the first failure that wasn't an allowance run out autoReset := false // a Codex or Claude reset looked at, once a request + // what the tries' held streams sent the agent ahead of a reply (#751) + kept := &keptAlive{proto: from} for i := 0; i < len(cands); i++ { c := cands[i] last := i == len(cands)-1 // the last one's failure is held too when an earlier one failed, // for its allowance running out to be told as that one's error - hw := newHoldWriter(w, !last || again < max(lastRetries, rateRetries) || other != nil) + // and once the agent has the stream's headers from an earlier try's + // keepalives, for a failure to be told as the stream's error + hw := newHoldWriter(w, !last || again < max(lastRetries, rateRetries) || other != nil || kept.sent) hw.thinkingShown = !refusesAfterThinking(c.model) + hw.ctx, hw.alive = r.Context(), kept call.Provider, call.To, call.Usage = c.p.ID, "", Usage{} model = c.model where = c.p.Where() @@ -1381,7 +1386,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } see, _ := seeing() call.Status = 502 - writeError(w, from, 502, fmt.Sprintf("model %q can't see images, and %s couldn't describe the image for it: %v", c.p.ID+"/"+c.model, see, err)) + failTo(w, kept, from, 502, fmt.Sprintf("model %q can't see images, and %s couldn't describe the image for it: %v", c.p.ID+"/"+c.model, see, err)) break } attemptBody = b @@ -1623,7 +1628,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro continue } call.Status, call.Error = http.StatusBadRequest, effortError(c, sent, takes, call.Error) - writeError(w, from, call.Status, call.Error) + failTo(w, kept, from, call.Status, call.Error) break } } @@ -1756,7 +1761,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // nobody is left: the agent is told it was refused, as a // request it shouldn't send again as it is, not handed an empty // reply it would ask again for, paying for each - writeError(w, from, refusedStatus, call.Error) + failTo(w, kept, from, refusedStatus, call.Error) } else if f := failure(call.Status, []byte(call.Error)); other != nil && !hw.passing && call.Status >= 400 && (f == failQuota || f == failCredit) { // the last one left is out of its allowance, but one before it // failed otherwise: the agent is told that one's error, not @@ -1766,14 +1771,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro try.Fail = f s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) call.Status, call.Error = other.Status, other.Error - writeError(w, from, call.Status, call.Error) + failTo(w, kept, from, call.Status, call.Error) break } else if outgrew { // in the agent's own words for it, for it to compact - writeError(w, from, call.Status, hw.failMsg) + failTo(w, kept, from, call.Status, hw.failMsg) } else if !hw.passing && hw.code() == http.StatusRequestEntityTooLarge { // No member left took the body; only now add the byte-limit hint. - writeError(w, from, call.Status, call.Error) + failTo(w, kept, from, call.Status, call.Error) } else { hw.release() if hw.passing { @@ -3801,6 +3806,29 @@ func writeJSON(w http.ResponseWriter, status int, v any) { enc.Encode(v) } +// failTo answers the agent with an error: as writeError does, or as its +// stream's error once a held stream sent it the stream's headers to keep +// it alive (keepAlive), where a status can no longer be said. +func failTo(w http.ResponseWriter, a *keptAlive, proto provider.Protocol, status int, msg string) int { + if a == nil || !a.sent { + return writeError(w, proto, status, msg) + } + streamError(w, proto, status, msg) + return status +} + +// streamError writes an error as an event of the client's stream, its +// headers already sent. +func streamError(w http.ResponseWriter, proto provider.Protocol, status int, msg string) { + sw := newSSEWriter(w) + sw.begun = true + ev := Event{Kind: KError, Text: msg, Status: status} + if tooLong(status, msg) { + ev.Code = "context_length_exceeded" + } + makeEncoder(proto, sw, &Request{}).event(ev) +} + // writeError answers in the client's own error shape. func writeError(w http.ResponseWriter, proto provider.Protocol, status int, msg string) int { typ := "api_error" diff --git a/internal/gateway/held_keepalive_test.go b/internal/gateway/held_keepalive_test.go new file mode 100644 index 000000000..85fde0410 --- /dev/null +++ b/internal/gateway/held_keepalive_test.go @@ -0,0 +1,181 @@ +package gateway + +import ( + "bufio" + "context" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// thinkingOn serves Claude thinking at length: its first events, then +// Anthropic's pings until heard is closed (or 3s), then the rest of reply. +func thinkingOn(t *testing.T, id, reply string, heard <-chan struct{}) { + t.Helper() + events := strings.SplitAfter(reply, "\n\n") + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + f := w.(http.Flusher) + io.WriteString(w, events[0]+events[1]+events[2]) + f.Flush() + for wait := time.After(3 * time.Second); ; { + select { + case <-heard: + case <-wait: + case <-time.After(10 * time.Millisecond): + io.WriteString(w, "event: ping\ndata: {\"type\": \"ping\"}\n\n") + f.Flush() + continue + } + break + } + for _, ev := range events[3:] { + io.WriteString(w, ev) + } + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: id, Name: strings.ToUpper(id), Key: "k", Models: []string{"claude-opus-5-5"}, Anthropic: up.URL}); err != nil { + t.Fatal(err) + } +} + +// ask posts claudeCodeAsk to the gateway over HTTP and reads the reply as +// it comes, closing heard once a keepalive arrived. +func ask(t *testing.T, s *Server, heard chan struct{}) (int, string) { + t.Helper() + gw := httptest.NewServer(s.Handler()) + t.Cleanup(gw.Close) + resp, err := http.Post(gw.URL+"/v1/messages", "application/json", strings.NewReader(claudeCodeAsk)) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var once sync.Once + var body strings.Builder + rd := bufio.NewReader(resp.Body) + for { + line, err := rd.ReadString('\n') + body.WriteString(line) + if strings.HasPrefix(line, ": keepalive") { + once.Do(func() { close(heard) }) + } + if err != nil { + break + } + } + return resp.StatusCode, body.String() +} + +// Claude thinking for longer than the agent's idle timeout through a +// group, where its stream is held for a refusal to go to another account +// (#248): the agent heard nothing for up to four minutes, and Alma's 240s +// timeout for a reasoning model ended the turn first (#751). It is kept +// alive with comments meanwhile, which say nothing of the reasoning, and a +// refusal after them still goes to the next member, whose answer follows +// in the same stream. +func TestHeldThinkingKeepsTheAgentAlive(t *testing.T) { + fresh(t) + keepFast(t, keepaliveGap, 20*time.Millisecond, keepaliveLongest) + k := keepHeldAfter + keepHeldAfter = 30 * time.Millisecond + t.Cleanup(func() { keepHeldAfter = k }) + + heard := make(chan struct{}) + thinkingOn(t, "a", anthropicThoughtThenRefused, heard) + b := &scripted{replies: []reply{{200, "text/event-stream", anthropicAnswer}}} + scriptedOn(t, "b", provider.Anthropic, b) + refusalGroup(t, "a/claude-opus-5-5", "b/m") + s := New() + code, body := ask(t, s, heard) + alive := strings.Index(body, ": keepalive") + if code != 200 || alive < 0 || !strings.Contains(body[alive:], "from b") || strings.Contains(body, "user wants") || strings.Contains(body, `"refusal"`) || b.n != 1 { + t.Fatalf("%d %q (b %d)", code, body, b.n) + } + if strings.Count(body, "event: message_start") != 1 { + t.Fatalf("one reply in the stream: %q", body) + } + r := lastRoute(s) + if len(r.Tries) != 2 || r.Tries[0].Fail != failRefused || r.Status != 200 { + t.Fatalf("tries: %+v", r.Tries) + } + + // thinking that goes on to its answer comes through whole after them + fresh(t) + heard = make(chan struct{}) + thinkingOn(t, "a", anthropicThoughtThenAnswered, heard) + scriptedOn(t, "b", provider.Anthropic, &scripted{replies: []reply{{200, "text/event-stream", anthropicAnswer}}}) + refusalGroup(t, "a/claude-opus-5-5", "b/m") + code, body = ask(t, New(), heard) + alive = strings.Index(body, ": keepalive") + if code != 200 || alive < 0 || !strings.Contains(body[alive:], `"thinking":"hm"`) || !strings.Contains(body, "from a") || strings.Contains(body, "from b") { + t.Fatalf("answered: %d %q", code, body) + } + + // refused with nobody left: the stream's error, as its 200 went out + fresh(t) + heard = make(chan struct{}) + thinkingOn(t, "a", anthropicThoughtThenRefused, heard) + refusalGroup(t, "a/claude-opus-5-5") + code, body = ask(t, New(), heard) + if code != 200 || !strings.Contains(body, ": keepalive") || !strings.Contains(body, "event: error") || strings.Contains(body, "user wants") { + t.Fatalf("refused, nobody left: %d %q", code, body) + } +} + +// A stream's last event written after the agent went away reached nobody: +// the reply isn't whole, and the request is recorded as canceled (499), not +// as a 200 done (#751, a Claude Code run stopped by Alma's timeout). +func TestClientGoneRecordedAsCanceled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + h := newHoldWriter(httptest.NewRecorder(), false) + h.ctx = ctx + h.Header().Set("Content-Type", "text/event-stream") + h.Write([]byte(sse(`event: message_start` + "\n" + `data: {"type":"message_start","message":{"id":"m"}}`))) + cancel() + h.Write([]byte(sse(`event: message_stop` + "\n" + `data: {"type":"message_stop"}`))) + if h.ended { + t.Fatal("a stream ended after its agent left taken as whole") + } + + // Claude Code's run stopped mid-reply, written to the holdWriter the + // gateway gives it: relay still ends the stream it was encoding + // (message_stop), which isn't the reply made whole + dir := fakeClaudeCalling(t) + s := New() + t.Cleanup(s.subscription.abortAll) + ctx, cancel = context.WithCancel(context.Background()) + defer cancel() + go func() { + for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) { + b, _ := os.ReadFile(filepath.Join(dir, "hang.pid")) + if pid, _ := strconv.Atoi(strings.TrimSpace(string(b))); pid != 0 { + time.Sleep(200 * time.Millisecond) // its reply under way + break + } + } + cancel() + }() + rec := httptest.NewRecorder() + h = newHoldWriter(rec, false) + h.ctx = ctx + p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}} + body := `{"model":"claude-sonnet-5","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"hang on"}]}` + var u Usage + s.serveClaudeSubscription(h, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)).WithContext(ctx), provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u) + if !strings.Contains(rec.Body.String(), "thinking it over") || !strings.Contains(rec.Body.String(), "message_stop") { + t.Fatalf("the run's reply: %q", rec.Body.String()) + } + if h.ended { + t.Fatal("a Claude Code run stopped as its agent left taken as a whole reply, recorded as a 200") + } +}