gateway: a Gemini reply that says nothing is asked again on the same account before it fails, so a long conversation that ends with only reasoning a few times running goes on instead of stopping the agent (#667, tianshuo886)

antigravity/gemini-3.8-flash, deep into a long Pi session, ended its turn with only its reasoning three times in a row; the request's own tries (3, 1s and 2s apart) ran out, Pi got "an empty reply" and stopped until the user typed continue. streamTranslated now asks such a reply again in place: once while the stream is still held (the request's tries and the next account still follow), up to twice once the agent has the stream, when nothing else would. A model that never answers is asked at most 6 times and still ends with the error. What reasoning the agent already has stays; the next try's follows it in the same message.

TestGeminiEmptyRepliesAskedAgain (chat and Anthropic: three empties running end in "hello", one message_start; one that never answers errors within 6 calls) is new and fails without the change. go vet, go build (GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
This commit is contained in:
yetone
2026-10-06 01:14:50 +08:00
parent 86f48071cc
commit 8d3cf5f86e
3 changed files with 109 additions and 0 deletions
+30
View File
@@ -34,6 +34,18 @@ import (
// ends with the error, as it used to at once.
const streamRetries = 2
// emptyRetries is how many times a reply that said nothing (#667) is asked
// 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.
func emptyRetries(w http.ResponseWriter, ctx context.Context) int {
if h, ok := w.(*holdWriter); ok && h.mayAskAgain() || inGroupTry(ctx) {
return 1
}
return streamRetries
}
// errStreamCut ends a reply's read once its error event is in hand,
// without waiting on a vendor that keeps the connection open after it.
var errStreamCut = errors.New("stream cut mid-reply")
@@ -239,6 +251,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
var failedStatus int
var cut, errSent bool
var empty bool // a reply in this protocol that says nothing fails (#667)
empties := 0 // the times such a reply was asked again here
said, stop := false, ""
var kept []Event // the reply's end, while nothing is said in it
var before, this Usage // what the tries before this one billed, and this try
@@ -374,6 +387,23 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
held()
}
if empty && !said && answersNothing(stop) {
if empties < emptyRetries(w, r.Context()) && r.Context().Err() == nil {
// asked again here first, for the agent to have the
// answer rather than the error: Gemini on a long
// conversation now and then ends with only its
// reasoning several times running, and an agent told
// the error stops its run (#667, Pi). What reasoning
// the client has stays, the next try's follows it.
empties++
before, this = before.plus(this, false), Usage{}
kept, stop = nil, ""
enc.keepalive()
select {
case <-time.After(retryPause << (empties - 1)):
case <-r.Context().Done():
}
continue
}
// as an error it is asked again, or of another account,
// and an agent told it tries again rather than end its
// turn (#667); a reply that said nothing has nothing to
+8
View File
@@ -1244,6 +1244,14 @@ func (h *holdWriter) failed() bool {
return !h.passing && h.code() >= 400 && retryable(h.code(), h.errBody())
}
// mayAskAgain tells whether a failure now is still held, for the request
// to ask again or of another: nothing of the try has reached the agent.
func (h *holdWriter) mayAskAgain() bool {
h.mu.Lock()
defer h.mu.Unlock()
return h.hold && !h.passing
}
// release sends a held reply after all: nobody else is left to try.
func (h *holdWriter) release() {
if h.passing || h.status == 0 {
@@ -2,6 +2,8 @@ package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
@@ -89,3 +91,72 @@ func TestGeminiEmptyReplyIsAnError(t *testing.T) {
}
}
}
// A Gemini reply that says nothing several times running is asked again
// on the same account before the request's own tries run out: on a long
// conversation antigravity/gemini-3.8-flash ended with only its reasoning
// three times in a row, the error stopped Pi's run, and the user had to
// type "continue" (#667, tianshuo886). One that never says anything still
// ends with the error, asked a bounded number of times.
func TestGeminiEmptyRepliesAskedAgain(t *testing.T) {
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"))
t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
calls, emptyFor := 0, 0
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
calls++
w.Header().Set("Content-Type", "text/event-stream")
if calls <= emptyFor {
io.WriteString(w, `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"Let me see.","thought":true}]}}]}`+"\n\n"+
`data: {"candidates":[{"content":{"role":"model","parts":[{"text":""}]},"finishReason":"STOP"}]}`+"\n\n")
return
}
io.WriteString(w, `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]},"finishReason":"STOP"}]}`+"\n\n")
}))
t.Cleanup(up.Close)
t.Cleanup(provider.FactoryBaseForTest(up.URL, up.URL+"/eu"))
auth, _ := json.Marshal(map[string]any{
"accessToken": "tok", "refreshToken": "r",
"expiresAt": time.Now().Add(time.Hour).UnixMilli(),
"orgId": "org_D", "activeOrganizationId": "fac_D", "email": "d@example.com",
})
dir := filepath.Dir(provider.Path())
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal([]map[string]any{{
"agent": "factory", "user": "d@example.com", "plan": "pro", "on": true, "auth": json.RawMessage(auth),
}})
if err := os.WriteFile(filepath.Join(dir, "logins.json"), raw, 0o600); err != nil {
t.Fatal(err)
}
const model = "factory/gemini-3.8-flash"
for _, a := range []struct{ name, path, body string }{
{"chat", "/v1/chat/completions", `{"model":"` + model + `","stream":true,"messages":[{"role":"user","content":"hi"}]}`},
{"anthropic", "/v1/messages", `{"model":"` + model + `","stream":true,"max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`},
} {
calls, emptyFor = 0, 3
code, body := post(t, a.path, a.body)
if code != 200 || !strings.Contains(body, "hello") || strings.Contains(body, "an empty reply") {
t.Errorf("%s: three empty replies running weren't asked past: %d calls, %d %s", a.name, calls, code, body)
}
if a.name == "anthropic" && strings.Count(body, "event: message_start") != 1 {
t.Errorf("%s: not one message: %s", a.name, body)
}
calls, emptyFor = 0, 1<<20
code, body = post(t, a.path, a.body)
if !strings.Contains(body, "an empty reply") {
t.Errorf("%s: a model that never answers isn't told as the error: %d %s", a.name, code, body)
}
if calls > 6 {
t.Errorf("%s: a model that never answers asked %d times", a.name, calls)
}
}
}