Files
magpie/internal/gateway/deepseek_step_lead_test.go
T
JoeyWu-tech 5f3146be09 gateway: OpenRouter takes a DeepSeek tool turn (signature "") and a turn's effort is asked again without (#3696, #2883)
What changed: on a DeepSeek model behind an Anthropic Messages endpoint
(anthropicReplaysThinking), magpie gives each tool turn that has no
thinking a block of its own, {"type":"thinking","thinking":" "}
(withThinkingOnToolTurns), and replays a turn's unsigned thinking as its
text (anthropicBody with replay). Both went out with no signature field:
aBlock's Signature is omitempty. OpenRouter's /api/v1/messages holds a
thinking block's signature to a string, so become2206's Claude Desktop
conversation on openrouter/deepseek/deepseek-v4.1-flash-1017 was turned
away after its first tool call ("OpenRouter: Invalid Anthropic Messages
API request", metadata path [..., 0, "signature"], "expected string,
received undefined"), on every retry. The reporter's capture shows the
same body with only "signature": "" added getting 200.

aBlock.MarshalJSON already writes a thinking block's "thinking" even
when empty; it now writes "signature" the same way. That is the one
place both blocks above are written, so the placeholder, a redacted
block turned into it, and replayed reasoning all carry "signature": "".
A signed block goes as before. Claude's own models and api.anthropic.com
are never replayed and are sent only signed thinking (anthropicBody), so
nothing changes for them.

Tests: TestOpenRouterDeepSeekThinkingHasASignature sends Claude
Desktop's Messages turns (relayed, gateway.go's withThinkingOnToolTurns)
and a Chat client's translated turns with reasoning_content to a fake
upstream that answers as #2883 quotes OpenRouter when a thinking block
has no string signature. The three tests that pinned the old bytes
(TestDeepSeekAnthropicToolTurnsGetThinking, TestDeepSeekAnthropicNoThinkingField,
TestAnthropicReplyAfterToolGetsThinking) now expect "signature":"".

Run:
- Breaks: with aBlock.MarshalJSON reverted,
  TestOpenRouterDeepSeekThinkingHasASignature fails at the Messages case,
  "messages: 400 after 1 calls: {"error":{"message":"OpenRouter: Invalid
  Anthropic Messages API request",...". With a narrower fix that only
  gives the placeholder in withThinkingOnToolTurns a signature, it fails
  at the Chat case, "chat: 400 after 1 calls: ... Invalid Anthropic
  Messages API request", so the replayed-reasoning path is held too.
  Both pass restored.
- gofmt -l clean on the three files. go vet ./... for linux -tags nogui,
  windows, and darwin -tags nogui: ok. go build for the same three: ok.
- Full `go test -tags nogui -timeout 45m ./...` on Linux amd64, go1.26.8,
  at base c483feadf (origin/main as of 10-19 05:33 UTC) + this: 57
  packages ok (20 of them from Go's test cache, unchanged since a first
  full run of this tree that lacked only the
  TestAnthropicReplyAfterToolGetsThinking line), 20 with no tests. Every
  red is in a test this change doesn't reach, and each was run on
  unmodified c483feadf:
  - umask 077 on this box: edit's TestWriteAtomicReadOnlyHardLink and
    testenv's TestProgram (fixtures written 0444/0755 come out
    0400/0700). Both pass with umask 022.
  - a broken /tmp/.git left on this shared box: agent's
    TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout ("error obtaining VCS
    status: exit status 128" building their fixture).
  - red on c483feadf too, cause not pinned (this box's PATH and proxy
    setup): agent's TestInstalledVersion, TestOmpDetectedWithPiDir,
    TestCopilotFolderFromAnIDEPluginIsNotTheCLI (3 of 3),
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI/qoder-cn (3 of 3),
    TestCursorFolderFromTheEditorIsNotTheCLI (1 of 3) and TestZedAppPath
    (2 of 3); claudebridge's TestCallbackGoesPastTheAgentsProxy;
    gateway's TestClaudeToolCallbackOnANonLoopbackAddress; gui's
    TestGatewayHeldByAContainer.
  - red only in a full run, ok alone 3 of 3: davsync's TestSync, and
    imagemcp's TestStalledDownloadSaysWhereTheImageIs (red in the first
    full run only).
  internal/gateway run again alone at the final tree: ok but for
  TestClaudeToolCallbackOnANonLoopbackAddress, as above.

Real DeepSeek: on 2026-10-19, api.deepseek.com/anthropic,
deepseek-flash, a conversation whose assistant turn calls a tool and the
next user turn answers it, the assistant turn sent five ways: with no
thinking block, 400 "The `content[].thinking` in the thinking mode must
be passed back to the API"; with {"thinking":" "} (magpie before this),
with {"thinking":" ","signature":""} (after), with replayed text and no
signature, and with replayed text and "signature":"": each 200 with a
thinking block and the answer. So DeepSeek's own endpoint takes the
empty signature.

Not tried: OpenRouter itself (no account here); the fix rests on the
reporter's single-field experiment against it. darwin with the GUI
(cgo, Wails) wasn't vetted, as it can't be cross-built from Linux.

Review (yetone/magpie maintainer agent), for #3696 (magicseek), which is
#2883's problem A plus a problem B this patch didn't look at:

B: Claude Code 2.1.302 puts a turn's effort as output_config on a
{role: "system"} message; OpenRouter takes it as a configuration_update
and answers 400 "Mid-conversation reasoning effort (configuration_update)
is not supported on <model>" on DeepSeek and GLM. magpie already learns a
relay's refusal of exactly this field ("messages.1.output_config: Extra
inputs are not permitted", refuseShapes/shapeTurnEffort) and asks again
without it, keeping the request's own output_config and the system
message's text, then never sends that provider it again while it runs.
turnEffortRefused now also matches OpenRouter's wording, so the same
mend runs there. It is learned per provider, so a Claude model on the
same OpenRouter provider loses its per-turn effort too, as Claude Code
itself does after such a 400; the request's top-level effort stays.

Not done from the report: re-roling system messages to user, and pinning
a conversation's effort. The report's row "system message, no
output_config, DeepSeek: 400 Invalid Anthropic Messages API request" is
footnoted as the A/B combination, and OpenRouter's generic 400 names no
field magpie could learn from without also catching A's; asked on the
issue for that error's metadata path.

Tests: TestOpenRouterTurnEffortLeftOut sends the report's minimal
conversation plus Claude Code's system message with output_config, on
deepseek/deepseek-v4.1-flash-1017 and z-ai/glm-5.3-flash, to a fake that
answers the report's literal 400 for a message's output_config and
openRouterRefuseAnthropic's for an unsigned thinking block: 200 on the
second call, and the next request goes on the first.

Run at 810b00d07 + this on b92cb2f59 (origin/main), macOS, go1.27:
- red with turnEffortRefused reverted: both subtests "400 after 1 calls"
  with OpenRouter's Mid-conversation message. Red with aBlock.MarshalJSON
  reverted and B kept: the deepseek subtest "400 after 2 calls ...
  Invalid Anthropic Messages API request", and
  TestOpenRouterDeepSeekThinkingHasASignature. Green restored.
- go test -tags nogui ./internal/gateway -run
  'Shape|Refus|OpenRouter|DeepSeek|Thinking|Effort|SystemMessage': ok.
- gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet
  ./internal/gateway: ok.
- full go test -tags nogui -timeout 45m ./internal/gateway at 136f96b22
  (on 47175a68f): ok (549s).

Not tried: OpenRouter itself (no account here); both halves rest on the
reporter's captures.
2026-10-27 16:17:53 +08:00

199 lines
11 KiB
Go

package gateway
import (
"encoding/json"
"fmt"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// stepShape lists a Responses input's items by type, a reasoning item with
// its reasoning_text and a message with its role.
func stepShape(input []map[string]any) string {
var got []string
for _, it := range input {
s, _ := it["type"].(string)
switch s {
case "reasoning":
content, _ := it["content"].([]any)
for _, c := range content {
if m, _ := c.(map[string]any); m["type"] == "reasoning_text" {
s += fmt.Sprintf("=%q", m["text"])
}
}
case "message":
s += ":" + fmt.Sprint(it["role"])
}
got = append(got, s)
}
return strings.Join(got, ",")
}
// TestDeepSeekStepSaysBeforeItsCall (#1822, Codex → OpenCode Go's DeepSeek;
// #1592 and #1687 on DeepSeek's own API): a step of Codex's history that
// said something and then made a call, with no reasoning item (another
// model's turn), was sent [message, reasoning " ", call]: magpie put the
// reasoning it made up right before the call. DeepSeek reads a step as one
// assistant message whose thinking is the item it starts with, so it
// refused the request with "The `reasoning_text` in the thinking mode must
// be passed back to the API", while a step with only a call was taken. Each
// step now leads with its reasoning: its own moved ahead of what it said,
// else a space.
func TestDeepSeekStepSaysBeforeItsCall(t *testing.T) {
fresh(t)
up := &deepseekResponses{}
srv := httptest.NewServer(up)
defer srv.Close()
if err := provider.Save(provider.Provider{ID: "opencode-go", Name: "OpenCode Go", Key: "k", Models: []string{"deepseek-v4.1-flash"}, Responses: srv.URL + "/zen/go/v1"}); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Preset: "deepseek", Key: "k", Models: []string{"deepseek-flash"}, Responses: srv.URL + "/v1"}); err != nil {
t.Fatal(err)
}
if err := provider.SaveGroup(provider.Group{ID: "codex-brain", Name: "codex-brain", Members: []string{"opencode-go/deepseek-v4.1-flash"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
user := `{"type":"message","role":"user","content":[{"type":"input_text","text":"fix the login bug"}]}`
said := func(text string) string {
return `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"` + text + `"}]}`
}
call := func(id string) string {
return `{"type":"function_call","call_id":"` + id + `","name":"shell","arguments":"{\"command\":[\"ls\"]}"},
{"type":"function_call_output","call_id":"` + id + `","output":"main.go"}`
}
sealed := `{"type":"reasoning","id":"rs_0d1f","summary":[],"content":null,"encrypted_content":"gAAAAABpZm9vYmFy"}`
summed := `{"type":"reasoning","id":"rs_2","summary":[{"type":"summary_text","text":"Run the tests."}],"content":null,"encrypted_content":null}`
for _, c := range []struct{ name, input, want string }{
{"the reporter's: said, then called, no reasoning",
user + `,` + sealed + `,` + call("c1") + `,` + said("I'll run the tests.") + `,` + call("c2"),
`message:user,reasoning=" ",function_call,function_call_output,reasoning=" ",message:assistant,function_call,function_call_output`},
{"said, reasoning, called",
user + `,` + said("Looking.") + `,` + summed + `,` + call("c1"),
`message:user,reasoning="Run the tests.",message:assistant,function_call,function_call_output`},
{"said after a tool output",
user + `,` + call("c1") + `,` + said("It passes."),
`message:user,reasoning=" ",function_call,function_call_output,reasoning=" ",message:assistant`},
{"a step that leads with its reasoning",
user + `,` + summed + `,` + said("Looking.") + `,` + call("c1"),
`message:user,reasoning="Run the tests.",message:assistant,function_call,function_call_output`},
} {
for _, model := range []string{"opencode-go/deepseek-v4.1-flash", "deepseek/deepseek-flash", "group/codex-brain"} {
for _, stream := range []string{"true", "false"} {
code, b := post(t, "/v1/responses", `{"model":"`+model+`","stream":`+stream+`,"store":false,"reasoning":{"effort":"high","summary":"auto"},"include":["reasoning.encrypted_content"],
"tools":[{"type":"function","name":"shell","parameters":{"type":"object","properties":{"command":{"type":"array","items":{"type":"string"}}}}}],"input":[`+c.input+`]}`)
if code != 200 {
t.Errorf("%s, %s, stream %s: %d %s", c.name, model, stream, code, b)
continue
}
if got := stepShape(up.last()); got != c.want {
t.Errorf("%s, %s: sent\n%s\nwant\n%s", c.name, model, got, c.want)
}
for _, it := range up.last() {
if it["id"] == "rs_0d1f" && it["encrypted_content"] != "gAAAAABpZm9vYmFy" {
t.Errorf("%s: the sealed item lost its encrypted_content: %v", c.name, it)
}
}
}
}
}
}
// withReasoningText leaves a body whose steps all lead with reasoning text
// byte for byte, and a reply to the user (no call, no tool output before
// it) without reasoning, as DeepSeek takes it.
func TestWithReasoningTextLedStepsUnchanged(t *testing.T) {
for _, b := range []string{
`{"model":"deepseek-flash","input":[{"type":"message","role":"user","content":"hi"},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Hello!"}]},{"type":"message","role":"user","content":"ls"}]}`,
`{"model":"deepseek-flash", "input":[{"type":"message","role":"user","content":"ls"},{"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":"x"}]},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Looking."}]},{"type":"function_call","call_id":"c1","name":"sh","arguments":"{}"},{"type":"function_call_output","call_id":"c1","output":"ok"},{"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":"y"}]},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Done."}]}]}`,
} {
if got := string(withReasoningText([]byte(b))); got != b {
t.Errorf("%s\nbecame %s", b, got)
}
}
}
// Translated to DeepSeek's Responses API (an agent of another protocol, or
// Codex's web_search), an assistant turn that said something before its
// call goes with its reasoning first too (#1822).
func TestTranslatedDeepSeekStepLeadsWithReasoning(t *testing.T) {
for _, c := range []struct{ input, want string }{
{`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Looking."}]},
{"type":"function_call","call_id":"c1","name":"sh","arguments":"{}"}`,
`message:user,reasoning=" ",message:assistant,function_call,function_call_output`},
{`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Looking."}]},
{"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":"Need ls."}]},
{"type":"function_call","call_id":"c1","name":"sh","arguments":"{}"}`,
`message:user,reasoning="Need ls.",message:assistant,function_call,function_call_output`},
} {
r, err := parseResponses([]byte(`{"model":"m","input":[{"type":"message","role":"user","content":"ls"},` + c.input + `,
{"type":"function_call_output","call_id":"c1","output":"ok"}]}`))
if err != nil {
t.Fatal(err)
}
var q struct {
Input []map[string]any `json:"input"`
}
json.Unmarshal(buildResponses(r, "deepseek-flash", "api.deepseek.com", false), &q)
if got := stepShape(q.Input); got != c.want {
t.Errorf("sent %s\nwant %s", got, c.want)
}
if b := buildResponses(r, "gpt-5.4", "relay.example", false); strings.Contains(string(b), `"reasoning_text"`) {
t.Errorf("gpt-5.4 was given reasoning: %s", b)
}
}
}
// A Chat request to a DeepSeek model whose last reply answers a tool result
// with no reasoning_content gets one, relayed or translated: DeepSeek's
// Chat API refuses it as it does a bare call (checked 2026-10-12, #1822).
func TestChatReplyAfterToolGetsReasoning(t *testing.T) {
f := &fake{t: t, reply: chatWholeOK, ctype: "application/json", refuse: deepseekRefuseToolTurns}
up := setup(t, provider.Chat, f)
chatProvider(t, up.URL, provider.Provider{ID: "go", Models: []string{"deepseek-v4.1-flash"}})
srv := New()
code, body := postTo(t, srv, "/v1/chat/completions", `{"model":"go/deepseek-v4.1-flash","stream":false,"messages":[
{"role":"user","content":"what time is it?"},
{"role":"assistant","content":null,"tool_calls":[`+timeCall+`],"reasoning_content":"Ask."},
{"role":"tool","tool_call_id":"call_1","content":"12:00"},
{"role":"assistant","content":"It is 12:00."}]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("relayed: %d after %d calls: %s", code, f.calls, body)
}
sameJSON(t, sentMessages(t, f.got)[3], `{"role":"assistant","content":"It is 12:00.","reasoning_content":" "}`)
f.calls = 0
f.reply, f.ctype = `data: {"id":"c1","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{"role":"assistant","content":"Yes."},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n", ""
code, body = postTo(t, srv, "/v1/responses", `{"model":"go/deepseek-v4.1-flash","stream":false,"input":[
{"type":"message","role":"user","content":[{"type":"input_text","text":"what time is it?"}]},
{"type":"function_call","call_id":"call_1","name":"get_time","arguments":"{}"},
{"type":"function_call_output","call_id":"call_1","output":"12:00"},
{"type":"message","role":"assistant","content":[{"type":"output_text","text":"It is 12:00."}]}]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("translated: %d after %d calls: %s", code, f.calls, body)
}
}
// The same on DeepSeek's Anthropic endpoint: a reply to tool results alone
// goes with a thinking block (checked 2026-10-12, #1822); a reply to the
// user goes as it was.
func TestAnthropicReplyAfterToolGetsThinking(t *testing.T) {
b := `{"model":"deepseek-flash","messages":[
{"role":"user","content":"ls"},
{"role":"assistant","content":[{"type":"thinking","thinking":"x"},{"type":"tool_use","id":"t","name":"n","input":{}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"t","content":"ok"}]},
{"role":"assistant","content":[{"type":"text","text":"Done."}]},
{"role":"user","content":[{"type":"text","text":"thanks"}]},
{"role":"assistant","content":[{"type":"text","text":"You're welcome."}]}]}`
if code, msg := deepseekRefuseAnthropic([]byte(b)); code == 0 {
t.Fatal("the fake took a reply to tool results with no thinking")
} else if code, msg = deepseekRefuseAnthropic(withThinkingOnToolTurns([]byte(b))); code != 0 {
t.Fatalf("%d %s", code, msg)
}
ms := sentAnthropicMessages(t, withThinkingOnToolTurns([]byte(b)))
sameJSON(t, ms[3], `{"role":"assistant","content":[{"type":"thinking","thinking":" ","signature":""},{"type":"text","text":"Done."}]}`)
sameJSON(t, ms[5], `{"role":"assistant","content":[{"type":"text","text":"You're welcome."}]}`)
}