gateway: Gemini's reasoning streams as it comes on the last candidate, so Codex isn't left with nothing for the whole of its thinking (LuckymanJC on Discord)

LuckymanJC and kkgg: through magpie the first turn of a Codex session on
a Gemini model was very slow or seemed stalled. Measured with fake
upstreams through the gateway (Codex Responses -> Chat DeepSeek, Gemini;
OpenCode Chat; Anthropic passthrough), first content came within 1-50ms
on every path but one: a Gemini model's reasoning was held even on the
last candidate (`|| last && modelFamily(c.model) != ""` left Gemini out),
so Codex got nothing at all, not even response.created, until the text
began, while Claude's and GPT's has gone as it comes there since
iTianbao's report.

It was held there for #667, a reply that only reasoned being asked
again. That re-ask happens in place in streamTranslated, keeping the
reasoning the agent has, so it doesn't need the hold. But with the try
passing, emptyRetries counted it as past the request's own re-asks and
asked only streamRetries (2) times, and TestGeminiEmptyRepliesAskedAgain
(three empty replies running) went red. A held try that went through on
its reasoning alone (holdWriter.thoughtThrough) is now asked once more in
place (streamRetries+1); a never-answering model still makes at most 4
calls (the test's bound is 6).

Tests: TestThinkingStreamsWithNoOneElse gets "gemini" (Gemini upstream)
and "chat gemini" cases, to Claude Code and Codex. With the old line
restored they go red ("thinking held: first thought only 1.75us before
the text"). With emptyRetries' new branch broken by hand
(streamRetries+0), TestGeminiEmptyRepliesAskedAgain goes red with
"an empty reply"; green with both.
Run: go test -run 'TestGeminiEmpty|TestThinkingStreams|TestThinkingHeld|TestUncountedEmpty|TestReasoningLoop' ./internal/gateway: ok.
Break check repeated at push: the old `|| last && modelFamily(c.model)
!= ""` turns
TestThinkingStreamsWithNoOneElse/{gemini,chat_gemini}/v1/{messages,responses} red ("thinking held: first thought only 1.458µs before the text").
Full suite (go1.26.8 darwin-arm64, rebased on 0fe039f14): go test
-timeout 45m ./... gave 63 packages ok; internal/agent and
internal/gateway timed out at 45m with no test failed (load ~110 from
other sessions; deadline in TestJcode and TestVertexGeminiClients,
#2544 and #2870 seen again) and passed alone at that head: ok
internal/agent 1644.560s, ok internal/gateway 1397.712s. Rebased on
origin/main 4ae6c06dc, every package its new commits touch run in full
there: ok internal/agent 465.353s, internal/gateway 648.172s,
internal/sessions, internal/gui, internal/cli, internal/codexsummary;
gofmt -l on the changed files empty; go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./... clean; go build for
darwin, linux (nogui) and windows ok (at 0fe039f14).
Then rebased on origin/main 2201b6628 (one line in
internal/provider/migrate_qoder.go): ok internal/provider 608.249s; go
vet of internal/provider, internal/agent and internal/gateway clean.
This commit is contained in:
yetone
2026-10-21 03:40:27 +08:00
parent 5206177704
commit 592899467b
5 changed files with 47 additions and 9 deletions
File diff suppressed because one or more lines are too long
+9 -2
View File
@@ -40,11 +40,18 @@ const streamRetries = 2
// again on the same account before it fails: once while its stream is
// held, which the request then asks again, or of another account — or the
// group of its next member — and as often as a cut reply once the client
// has the stream, when nobody asks again after it.
// has the stream, when nobody asks again after it. A held try whose
// reasoning went through as it came (Gemini's on the last candidate,
// LuckymanJC on Discord) is past the request's asking again, so it is
// asked once more here in its place.
func emptyRetries(w http.ResponseWriter, ctx context.Context) int {
if h, ok := w.(*holdWriter); ok && h.mayAskAgain() || inGroupTry(ctx) {
h, ok := w.(*holdWriter)
if ok && h.mayAskAgain() || inGroupTry(ctx) {
return 1
}
if ok && h.thoughtOnly() {
return streamRetries + 1
}
return streamRetries
}
+13
View File
@@ -1612,6 +1612,10 @@ type holdWriter struct {
// thinkingShown: the model's vendor never refuses after reasoning
// (refusesAfterThinking), so its reasoning goes through as it comes
thinkingShown bool
// thoughtThrough: the try went through on its reasoning alone
// (thinkingShown) while the request could still have asked again, so
// an empty reply is asked again in place as often (emptyRetries)
thoughtThrough bool
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
@@ -2025,6 +2029,7 @@ func (h *holdWriter) scan() {
continue
case eventThinking:
if h.thinkingShown && !h.wantWhole {
h.thoughtThrough = h.hold
h.flow()
return
}
@@ -2340,6 +2345,14 @@ func (h *holdWriter) mayAskAgain() bool {
return h.hold && !h.passing
}
// thoughtOnly tells whether the try went through on its reasoning while
// it was still held for the request to ask again (thoughtThrough).
func (h *holdWriter) thoughtOnly() bool {
h.mu.Lock()
defer h.mu.Unlock()
return h.thoughtThrough
}
// handBack sends a refusal held with nothing said as the vendor's own
// reply, a 200 that ends with its stop reason, and says whether it could:
// not a refusal said as an error status or event, which is no reply.
+7 -3
View File
@@ -2380,9 +2380,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// while another candidate could answer instead: the last one's
// refusal isn't asked again, so holding it only kept a lone relay's
// thinking from Claude Code and Codex until the text began, all at
// once (iTianbao on X). Gemini's stays held on the last one too,
// for a reply that only reasoned to be asked again (#667).
hw.thinkingShown = !refusesAfterThinking(c.model) || last && modelFamily(c.model) != ""
// once (iTianbao on X). Gemini's goes as it comes there too: a
// reply that only reasoned is asked again in place, its reasoning
// kept and the next try's after it (streamTranslated, #667), so
// holding it kept Codex on a Gemini model with nothing at all,
// not even response.created, for the whole of its thinking
// (LuckymanJC on Discord).
hw.thinkingShown = !refusesAfterThinking(c.model) || last
hw.ctx, hw.alive, hw.streams = r.Context(), kept, streams
report := cacheReport
if c.p.Account == nil || c.p.Account.Agent != "claude" {
+17 -3
View File
@@ -127,8 +127,9 @@ func TestThinkingStreamsThroughGroup(t *testing.T) {
}
}
// Claude's reasoning is still held for a refusal after it (#248), and so
// are OpenAI's and Gemini's; anybody else's is let through.
// Claude's reasoning is still held for a refusal after it (#248) while
// another candidate could answer, and so are OpenAI's and Gemini's;
// anybody else's is let through.
func TestThinkingHeldFor(t *testing.T) {
for model, held := range map[string]bool{
"claude-opus-5-5": true, "anthropic/claude-sonnet-4.5": true, "gpt-5.2-codex": true, "o3": true,
@@ -146,8 +147,17 @@ func TestThinkingHeldFor(t *testing.T) {
// agent anyway, as the last candidate's does, a relay's Claude showed
// Claude Code its thinking all at once with the text, and Codex none until
// then (iTianbao on X). Each of the relay's APIs, to Claude Code and
// Codex.
// Codex. Gemini's too, which a reply that only reasoned no longer needs
// held for (it is asked again in place, #667): held, Codex on a Gemini
// model had nothing, not even response.created, until the text began
// (LuckymanJC on Discord).
func TestThinkingStreamsWithNoOneElse(t *testing.T) {
geminiThinks := []string{
`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"first thought","thought":true}]}}],"modelVersion":"gemini-3-pro"}`,
`data: {"candidates":[{"content":{"role":"model","parts":[{"text":" second thought","thought":true}]}}],"modelVersion":"gemini-3-pro"}`,
`data: {"candidates":[{"content":{"role":"model","parts":[{"text":" third thought","thought":true}]}}],"modelVersion":"gemini-3-pro"}`,
`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"done"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1,"thoughtsTokenCount":8},"modelVersion":"gemini-3-pro"}`,
}
responsesThinks := []string{
`event: response.created` + "\n" + `data: {"type":"response.created","response":{"id":"resp_1","status":"in_progress","output":[]}}`,
`event: response.output_item.added` + "\n" + `data: {"type":"response.output_item.added","output_index":0,"item":{"id":"rs_1","type":"reasoning","summary":[]}}`,
@@ -171,6 +181,8 @@ func TestThinkingStreamsWithNoOneElse(t *testing.T) {
{"chat", provider.Chat, glmChatThinksSlowly, "claude-opus-5-5"},
{"chat gpt", provider.Chat, glmChatThinksSlowly, "gpt-5.2"},
{"responses", provider.Responses, responsesThinks, "gpt-5.2"},
{"gemini", provider.Gemini, geminiThinks, "gemini-3-pro"},
{"chat gemini", provider.Chat, glmChatThinksSlowly, "gemini-3-pro"},
} {
for _, ask := range []struct{ path, body, thought, text string }{
{"/v1/messages", claudeAsks, `"thinking_delta"`, `"text_delta"`},
@@ -187,6 +199,8 @@ func TestThinkingStreamsWithNoOneElse(t *testing.T) {
p.Anthropic = vendor.URL
case provider.Chat:
p.Chat = vendor.URL + "/v1"
case provider.Gemini:
p.Gemini = vendor.URL + "/v1beta"
default:
p.Responses = vendor.URL + "/v1"
}