Files
magpie/internal/gateway/plugin_thinking_stream_test.go
T
yetone 06944e065b gateway: a reply that begins as an event stream is read as one whatever its Content-Type (uk.jent)
uk.jent (Discord, #feedback): MiniMax Code's plugin (0.1.7) served as
Anthropic Messages to Grok Build 1.0.74. The first token took minutes
(5-6 at worst), then hundreds of characters came at once, and every
thinking block said "Thought for 0.0s".

Cause: eventStream decided a reply was a stream by its Content-Type
alone, unless the type was empty or text/plain. A stream sent under
any other type (application/octet-stream, say) was read as a whole
reply. On the Messages passthrough, sigFieldTidy, anthropicTextCalls
and the other tidies hold a whole reply until it ends, so the agent got
the turn only at its end, every block at once. On Chat and Responses
(translated) the same reply failed "did not stream". Under
application/json, notAnAPIReply turned it into a 502 ("isn't JSON").
The plugin itself passes MiniMax's body through untouched, and the host
streams it chunk by chunk, so neither is the cause.

Fix:
- eventStream reads the body's first bytes under any Content-Type that
  isn't text/event-stream. A body that begins as an event stream
  (event:, data:, a ":" comment) is one, and its Content-Type is set to
  text/event-stream for the agent. A JSON or binary body never begins
  that way.
- notAnAPIReply lets a JSON-labelled body that begins as an event
  stream through (eventsStart, shared with eventStream).
- docs/subsystems/gateway-routing.md says the rule.

Test: TestPluginThinkingStreamsAsItComes. The fake MiniMax plugin is
put in front of a vendor that sends its first thinking and then waits
until the agent has heard it (or gives up after 10s). It covers
messages, messages with tools (as Grok Build sends them), chat and
responses, each under text/event-stream, application/json, text/plain,
no type and application/octet-stream.

Run on mote:
- On origin/main d73f2254d: gofmt -l internal/gateway clean; go vet
  -tags nogui ./internal/gateway with GOOS=linux and GOOS=windows ok;
  go test -tags nogui -timeout 45m ./internal/gateway ./internal/plugin:
  internal/gateway ok (742s), internal/plugin ok (136s).
- Rebased on origin/main 441a2b6b1, which brought the #4775 upload
  changes into internal/gateway: gofmt and both vets again ok; go test
  -run 'TestPluginThinkingStreamsAsItComes|NotAnAPIReply|
  APIReplyUntouched|Upload|Unrouted|Streamless|PluginStream|QuietWhole|
  Thinking|Signed|Passthrough|Continuation' ./internal/gateway: ok
  (108s). The whole package was not re-run at this head.

Broken by hand:
- With eventStream at the old code, the octet-stream cases go red in
  all four shapes: messages "reached the agent only once the vendor
  had finished"; chat and responses "FakeCo did not stream".
- The application/json cases go red with eventStream alone fixed and
  notAnAPIReply at the old code ("the thought never reached the agent",
  a 502 after 90s).
- text/event-stream, text/plain and no type pass on the old code.

Not tried:
- a real MiniMax Code account or a capture of the mavis endpoint's real
  reply headers. There is none here, so the cause is the class that
  fits the symptom, not MiniMax's literal bytes.
- a real Grok Build run.
- a stream that comes compressed (Content-Encoding).
2026-11-03 13:50:05 +08:00

110 lines
3.9 KiB
Go

package gateway
import (
"bufio"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
)
// heldThinker is an Anthropic vendor that says its first thought and then
// says nothing more until the agent has heard it (heard closed), or until
// giveUp passes. A gateway that holds the thinking until the reply ends
// lets the agent hear it only after giveUp, all at once.
type heldThinker struct {
ct []string // the reply's Content-Type: none when empty
heard chan struct{}
giveUp time.Duration
mu sync.Mutex
waited bool // the vendor gave up waiting: nothing reached the agent
}
func (v *heldThinker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
w.Header()["Content-Type"] = v.ct
f := w.(http.Flusher)
say := func(evs ...string) {
for _, ev := range evs {
io.WriteString(w, ev+"\n\n")
}
f.Flush()
}
say(glmThinksSlowly[0], glmThinksSlowly[1], glmThinksSlowly[2])
select {
case <-v.heard:
case <-time.After(v.giveUp):
v.mu.Lock()
v.waited = true
v.mu.Unlock()
case <-r.Context().Done():
return
}
say(glmThinksSlowly[3:]...)
}
// uk.jent on Discord: MiniMax Code's plugin, served as Anthropic Messages
// to Grok Build, showed nothing for minutes and then the whole reply at
// once, each thinking block "Thought for 0.0s". A plugin's thinking reaches
// the agent while the vendor is still thinking, on every caller's shape.
func TestPluginThinkingStreamsAsItComes(t *testing.T) {
t.Setenv("FAKE_MINIMAX", "1")
tools := `,"tools":[{"name":"read_file","description":"Read a file","input_schema":{"type":"object","properties":{"path":{"type":"string"}}}}]`
for _, ct := range []string{"text/event-stream", "application/json", "text/plain; charset=utf-8", "", "application/octet-stream"} {
for _, ask := range []struct{ name, path, body, thought string }{
{"messages", "/v1/messages", `{"model":"MODEL","max_tokens":32000,"stream":true,"thinking":{"type":"enabled","budget_tokens":10000},"messages":[{"role":"user","content":"hi"}]}`, `"thinking_delta"`},
{"messages-tools", "/v1/messages", `{"model":"MODEL","max_tokens":32000,"stream":true,"thinking":{"type":"enabled","budget_tokens":10000},"messages":[{"role":"user","content":"hi"}]` + tools + `}`, `"thinking_delta"`},
{"chat", "/v1/chat/completions", `{"model":"MODEL","stream":true,"reasoning_effort":"high","messages":[{"role":"user","content":"hi"}]}`, `first thought`},
{"responses", "/v1/responses", `{"model":"MODEL","stream":true,"reasoning":{"effort":"high","summary":"auto"},"input":"hi"}`, `first thought`},
} {
t.Run(ask.name+"/"+ct, func(t *testing.T) {
up := &heldThinker{heard: make(chan struct{}), giveUp: 10 * time.Second}
if ct != "" {
up.ct = []string{ct}
}
pid := besideFake(t, "minimax-code", up)
gw := httptest.NewServer(New().Handler())
t.Cleanup(gw.Close)
req, _ := http.NewRequest("POST", gw.URL+ask.path, strings.NewReader(strings.Replace(ask.body, "MODEL", pid+"/MiniMax-M3.1-Flash", 1)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("anthropic-version", "2023-06-01")
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
b, _ := io.ReadAll(res.Body)
t.Fatalf("%d %s", res.StatusCode, b)
}
var all strings.Builder
rd := bufio.NewReader(res.Body)
heard := false
for {
ln, err := rd.ReadString('\n')
all.WriteString(ln)
if !heard && strings.Contains(ln, ask.thought) {
heard = true
close(up.heard)
}
if err != nil {
break
}
}
up.mu.Lock()
waited := up.waited
up.mu.Unlock()
if !heard {
t.Fatalf("the thought never reached the agent:\n%s", all.String())
}
if waited {
t.Fatalf("the first thought reached the agent only once the vendor had finished:\n%s", all.String())
}
})
}
}
}