Files
magpie/internal/gateway/chat_empty_assistant_test.go
T
yetoneandggbdpq ed0335f75c gateway: an assistant turn cut off before it said anything is left out of what a Chat upstream is sent (#2599)
timonwong (#2599): after the user stops a reply while the model is still
thinking, the agent keeps a turn with no text and no calls and sends it
again on every later turn. Translated (buildChat) or relayed, it reached
the Chat upstream as {"role":"assistant","content":""} (reasoning_content
alone, on DeepSeek), and DeepSeek and Kimi turned every request of the
conversation away: "Invalid assistant message: content or tool_calls must
be set".

One rule, withoutSilentAssistants (chat.go), runs on both Chat routes:
buildChat before pairToolMessages (Claude Code, Codex and Gemini clients,
and the plugins fed by buildChat), and silentAssistantsOut in passthrough
next to developerAsSystem (a Chat client's own body). An assistant
message with no content or only blank text parts, and no tool_calls or
function_call, is left out; the user messages it stood between join into
one (texts with a blank line, else their parts in order), so no two user
messages stand in a row. A prefill (prefix, partial, a Resume), a legacy
function_call, a refusal and an audio reply stay. A relayed body without
such a turn goes byte for byte. TestChatThinkingOnlyAssistantKeptOutside-
Exchange pinned the old pass-through; it now expects the joined message.

Built on ggbdpq's patch (cb438ebb on their fork) and its fake upstream,
written again because the review found it missed shapes the issue names:
- after a tool result it kept the empty turn ("a strict template wants the
  reply behind its tool message"), so the interruption mid tool loop still
  sent content "" and still got the 400. tool then user is what any agent
  sends when the user writes after a tool result; it is now left out.
- the relay dropped an assistant with a legacy function_call or a refusal
  and empty content, and a client's own prefix/partial prefill;
  kept blank text-part arrays (still refused); joined only string users;
  re-marshalled with HTML escaping.
- its Resume check compared a joinSplitCalls turn index with
  len(r.Messages)-1.

Verified (sandbox HOME, pinned caches, go1.26.8 darwin/arm64, base
origin/main 72d6103e2):
- The fake upstream refuses with the issue's literal 400 body any
  assistant without content or tool_calls, plus DeepSeek's #1462/#1822
  reasoning rule. On main's product code 18 subtests of the new tests go
  red with that 400 (Claude Code: thinking, redacted, empty text,
  thinking+empty text, [], "", after a tool result; Codex: lone reasoning,
  empty output_text, no content; Gemini thought-only; relay: "", null, no
  content, blank parts, after a tool result; relay keeps-what-speaks), and
  TestChatThinkingOnlyAssistantLeftOutOutsideExchange. With ggbdpq's
  product files instead, after-a-tool-result (both routes), blank parts
  and TestChatRelaySilentAssistantsOnly are red. With this change all
  pass; TestChatResumeEmptyPrefillKept is a guard, green before and after.
- gofmt -l: clean. go vet -tags nogui ./... for darwin, linux, windows:
  ok. Full suite with both this and the #2575 test change in the tree,
  set -o pipefail; go test -tags nogui -timeout 45m ./... : 66 packages
  ok, none failed (internal/gateway 825s, internal/provider 266s).
- Rebased onto origin/main ec6454395 (claude_subscription, ir.go):
  gofmt clean, vet darwin/linux/windows on internal/gateway and
  internal/settings ok; go test -tags nogui -timeout 45m
  ./internal/gateway ./internal/settings: ok (gateway 668s).
- Not tried against real DeepSeek or Kimi (the fake answers with the
  issue's bytes). Gemini and Responses upstreams are not changed; the
  Messages build already drops an empty turn and merges same-role
  neighbours (anthropicBody's push).

Co-authored-by: ggbdpq <67929842+ggbdpq@users.noreply.github.com>
2026-10-17 05:15:16 +08:00

267 lines
12 KiB
Go

package gateway
import (
"bytes"
"encoding/json"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// dsRefuseEmptyAssistant answers as DeepSeek's and Kimi's Chat APIs do,
// in the bytes of #2599, for a turn the agent cut off before it said
// anything: an assistant message with neither content nor tool_calls is
// invalid however much reasoning_content it carries, and the whole request
// is turned away. DeepSeek's rule for a tool turn without its reasoning
// (#1462, #1822) holds as well.
func dsRefuseEmptyAssistant(body []byte) (int, string) {
var q struct {
Messages []map[string]json.RawMessage `json:"messages"`
}
json.Unmarshal(body, &q)
for _, m := range q.Messages {
if string(m["role"]) != `"assistant"` {
continue
}
var calls []json.RawMessage
if json.Unmarshal(m["tool_calls"], &calls) == nil && len(calls) > 0 {
continue
}
var s string
var parts []struct {
Text string `json:"text"`
}
empty := m["content"] == nil || string(m["content"]) == "null"
if json.Unmarshal(m["content"], &s) == nil {
empty = strings.TrimSpace(s) == ""
} else if json.Unmarshal(m["content"], &parts) == nil {
empty = true
for _, p := range parts {
empty = empty && strings.TrimSpace(p.Text) == ""
}
}
if empty {
return 400, `{"error":{"message":"Invalid assistant message: content or tool_calls must be set","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}`
}
}
return deepseekRefuseToolTurns(body)
}
const emptyOKStream = `data: {"id":"c1","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{"role":"assistant","content":"Yes."},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2,"total_tokens":7}}` + "\n\ndata: [DONE]\n\n"
// dsUpstream is a DeepSeek-strict Chat upstream behind provider "ds".
func dsUpstream(t *testing.T) *fake {
f := &fake{t: t, reply: emptyOKStream, refuse: dsRefuseEmptyAssistant}
up := setup(t, provider.Chat, f)
chatProvider(t, up.URL, provider.Provider{ID: "ds", Models: []string{"deepseek-v4.1-flash", "glm-5.2"}})
return f
}
// sentRoles is the roles of the messages an upstream was sent, with the
// last one's content.
func sentRoles(t *testing.T, got []byte) (string, string) {
t.Helper()
var roles []string
var last string
for _, raw := range sentMessages(t, got) {
var m struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
}
json.Unmarshal(raw, &m)
roles = append(roles, m.Role)
last = string(m.Content)
}
return strings.Join(roles, " "), last
}
// A reply Claude Code's user cut off before it said anything — only its
// thinking, only an empty text, nothing at all — stays in its history and
// is sent again with every later turn. Translated to a Chat upstream it
// went out as an assistant message with "content": "", and DeepSeek and
// Kimi turned every request of the conversation away. It is left out, and
// the two user messages around it join into one. After a tool result the
// user's message follows the tool message, as when they write there.
func TestChatEmptyAssistantLeftOutFromAnthropic(t *testing.T) {
f := dsUpstream(t)
for name, turn := range map[string]string{
"thinking": `[{"type":"thinking","thinking":"mid-thought","signature":"sig"}]`,
"redacted": `[{"type":"redacted_thinking","data":"gAAAAABpZm9vYmFy"}]`,
"empty text": `[{"type":"text","text":""}]`,
"thinking + text": `[{"type":"thinking","thinking":"mid-thought","signature":"sig"},{"type":"text","text":""}]`,
"no blocks": `[]`,
"empty string": `""`,
} {
t.Run(name, func(t *testing.T) {
f.calls = 0
code, body := postTo(t, New(), "/v1/messages", `{"model":"ds/deepseek-v4.1-flash","max_tokens":32,"messages":[
{"role":"user","content":"hi"},
{"role":"assistant","content":`+turn+`},
{"role":"user","content":"continue"}]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("%d after %d calls, sent %s: %s", code, f.calls, f.got, body)
}
if shape, last := sentRoles(t, f.got); shape != "user" || last != `"hi\n\ncontinue"` {
t.Fatalf("sent %s", f.got)
}
})
}
t.Run("after a tool result", func(t *testing.T) {
f.calls = 0
code, body := postTo(t, New(), "/v1/messages", `{"model":"ds/deepseek-v4.1-flash","max_tokens":32,
"tools":[{"name":"get_time","input_schema":{"type":"object","properties":{}}}],"messages":[
{"role":"user","content":"what time is it?"},
{"role":"assistant","content":[{"type":"thinking","thinking":"Ask the clock.","signature":"sig"},{"type":"tool_use","id":"toolu_1","name":"get_time","input":{}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"12:00"}]},
{"role":"assistant","content":[{"type":"thinking","thinking":"It is noon, so","signature":"sig"}]},
{"role":"user","content":"continue"}]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("%d after %d calls, sent %s: %s", code, f.calls, f.got, body)
}
if shape, last := sentRoles(t, f.got); shape != "user assistant tool user" || last != `"continue"` {
t.Fatalf("sent %s", f.got)
}
})
}
// The same from Codex: a cut-off reply is an isolated reasoning item, or
// an assistant message with an empty output_text.
func TestChatEmptyAssistantLeftOutFromResponses(t *testing.T) {
f := dsUpstream(t)
for name, turn := range map[string]string{
"reasoning": `{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"mid-thought"}]}`,
"empty text": `{"type":"message","role":"assistant","content":[{"type":"output_text","text":""}]}`,
"no contents": `{"type":"message","role":"assistant","content":[]}`,
} {
t.Run(name, func(t *testing.T) {
f.calls = 0
code, body := postTo(t, New(), "/v1/responses", `{"model":"ds/deepseek-v4.1-flash","stream":false,"input":[
{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]},
`+turn+`,
{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]}]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("%d after %d calls, sent %s: %s", code, f.calls, f.got, body)
}
if shape, last := sentRoles(t, f.got); shape != "user" || last != `"hi\n\ncontinue"` {
t.Fatalf("sent %s", f.got)
}
})
}
}
// And from Gemini CLI: a model turn with only its thought.
func TestChatEmptyAssistantLeftOutFromGemini(t *testing.T) {
f := dsUpstream(t)
code, body := postTo(t, New(), "/v1beta/models/ds/deepseek-v4.1-flash:streamGenerateContent?alt=sse", `{"contents":[
{"role":"user","parts":[{"text":"hi"}]},
{"role":"model","parts":[{"text":"mid-thought","thought":true}]},
{"role":"user","parts":[{"text":"continue"}]}]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("%d after %d calls, sent %s: %s", code, f.calls, f.got, body)
}
if shape, last := sentRoles(t, f.got); shape != "user" || last != `"hi\n\ncontinue"` {
t.Fatalf("sent %s", f.got)
}
}
// A Chat agent (OpenCode, Kimi Code) keeps the turn it cut off as it
// came, {"role":"assistant","content":""} or null with reasoning_content
// alone, and its request is relayed as it sent it: the turn is left out
// there too, whichever model, and the user messages around it join.
func TestChatRelayLeavesOutEmptyAssistant(t *testing.T) {
f := dsUpstream(t)
srv := New()
for _, c := range []struct{ name, model, turns, shape, last string }{
{"empty", "ds/deepseek-v4.1-flash", `{"role":"user","content":"hi"},{"role":"assistant","content":"","reasoning_content":"halfway"},{"role":"user","content":"continue"}`,
"user", `"hi\n\ncontinue"`},
{"null", "ds/glm-5.2", `{"role":"user","content":"hi"},{"role":"assistant","content":null,"reasoning_content":"halfway"},{"role":"user","content":"continue"}`,
"user", `"hi\n\ncontinue"`},
{"no content", "ds/glm-5.2", `{"role":"user","content":"hi"},{"role":"assistant"},{"role":"user","content":"continue"}`,
"user", `"hi\n\ncontinue"`},
{"blank parts", "ds/glm-5.2", `{"role":"user","content":"hi"},{"role":"assistant","content":[{"type":"text","text":""}]},{"role":"user","content":[{"type":"text","text":"continue"}]}`,
"user", `[{"text":"hi","type":"text"},{"text":"continue","type":"text"}]`},
{"after a tool result", "ds/deepseek-v4.1-flash", `{"role":"user","content":"what time is it?"},
{"role":"assistant","content":null,"reasoning_content":"Ask.","tool_calls":[` + timeCall + `]},
{"role":"tool","tool_call_id":"call_1","content":"12:00"},
{"role":"assistant","content":"","reasoning_content":"It is noon, so"},
{"role":"user","content":"continue"}`,
"user assistant tool user", `"continue"`},
} {
t.Run(c.name, func(t *testing.T) {
f.calls = 0
code, body := postTo(t, srv, "/v1/chat/completions", `{"model":"`+c.model+`","stream":true,"messages":[`+c.turns+`]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("%d after %d calls, sent %s: %s", code, f.calls, f.got, body)
}
if shape, last := sentRoles(t, f.got); shape != c.shape || last != c.last {
t.Fatalf("sent %s", f.got)
}
})
}
}
// What says something stays as the client sent it: a body without a
// silent turn byte for byte, and in one with, a legacy function_call, a
// prefill to go on from, a refusal, and a turn of text.
func TestChatRelaySilentAssistantsOnly(t *testing.T) {
clean := []byte(`{"model":"m","messages":[{"role":"user","content":"a <b> & c"},{"role":"assistant","content":"x","n":1.50},{"role":"user","content":"go"}]}`)
if got := silentAssistantsOut(clean); !bytes.Equal(got, clean) {
t.Fatalf("a clean body was rewritten: %s", got)
}
body := []byte(`{"model":"m","temperature":0.70,"messages":[
{"role":"user","content":"a <b> & c"},
{"role":"assistant","content":null,"function_call":{"name":"f","arguments":"{}"}},
{"role":"function","name":"f","content":"1"},
{"role":"assistant","content":"","refusal":"I can't."},
{"role":"user","content":"then"},
{"role":"assistant","content":"","reasoning_content":"cut"},
{"role":"user","content":"go"},
{"role":"assistant","content":"","prefix":true}]}`)
got := silentAssistantsOut(body)
var q struct {
Temperature json.RawMessage `json:"temperature"`
Messages []json.RawMessage `json:"messages"`
}
if err := json.Unmarshal(got, &q); err != nil {
t.Fatal(err)
}
if string(q.Temperature) != "0.70" || !bytes.Contains(got, []byte(`"a <b> & c"`)) {
t.Errorf("the rest of the body changed: %s", got)
}
want := []string{
`{"role":"user","content":"a <b> & c"}`,
`{"role":"assistant","content":null,"function_call":{"name":"f","arguments":"{}"}}`,
`{"role":"function","name":"f","content":"1"}`,
`{"role":"assistant","content":"","refusal":"I can't."}`,
`{"role":"user","content":"then\n\ngo"}`,
`{"role":"assistant","content":"","prefix":true}`,
}
if len(q.Messages) != len(want) {
t.Fatalf("sent %s", got)
}
for i, w := range want {
sameJSON(t, q.Messages[i], w)
}
}
// A Resume's prefill, magpie's own ask to go on from a reply cut short,
// stays however little of the reply there was: without it the upstream
// would answer from the start instead of going on.
func TestChatResumeEmptyPrefillKept(t *testing.T) {
r := &Request{Resume: true, Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "go on"}}},
{Role: "assistant", Parts: []Part{{Kind: Thinking, Text: "half"}}},
}}
var q struct {
Messages []map[string]any `json:"messages"`
}
if err := json.Unmarshal(buildChat(r, "deepseek-chat", "api.deepseek.com", false), &q); err != nil {
t.Fatal(err)
}
last := q.Messages[len(q.Messages)-1]
if last["role"] != "assistant" || last["prefix"] != true || last["reasoning_content"] != "half" {
t.Fatalf("prefill = %v, want it kept with its prefix and reasoning", last)
}
}