Files
magpie/internal/gateway/chattidy_test.go
T
JoeyWu-tech ba4b754b22 gateway: a relayed Chat stream's tool call with no index is given its call's (#3386)
xianfeng-zhu (#3386): Cursor's Private Inference on magpie's
/v1/chat/completions, a Gemini model behind it, failed every turn that
made a tool call with AI_TypeValidationError at
choices[0].delta.tool_calls[0].index ("expected number, received
undefined"), then a 499 loop; turns without tools went fine. Gemini's
OpenAI-compatible API sends its calls with no index (Linka's frames in
gemini_compat_cut_test.go have none either), where the OpenAI contract
has one on every fragment, and a relayed stream went on without one.
The AI SDK's OpenAI provider, which the report names as what Cursor
reads Chat with, checks every chunk and turns that one away, so the call
is never made. OpenAI's own node SDK, through its stream helper, keeps
no call at all.

chatTidy, which already mends a relayed Chat stream's empty ids, empty
names and "stop" after calls, now gives a fragment with no index (none,
or null) the index of its call (streamCallIndexes.give). A fragment with
an id other than the open call's, or after the first in its delta,
starts the next call, as chatDecoder reads a new id; any other goes on
with the open one. So two calls in chunks of their own are 0 and 1.
Given both 0, as their place in the delta would give them, OpenAI's
node SDK merged them into one call with both arguments run together. A
fragment with an index keeps it, and a stream whose calls have theirs
goes as it came. It runs before the ids are mended, so a call with no id
either (#3386's chunk) gets both.

Not changed: the translations write an index already (chatEncoder,
chatWholeEvents), and a whole reply's message needs none. Nor is a call
given a type: Gemini's frames have "type": "function". The report's
chunk has neither an id nor a type, and is taken as cut short: magpie
gives a call with no id one (#2611, v0.1.1277), so the chunk it sent
would have had one.

What was run (tree e6023c66, on a93190ae, go1.26.8):
  a real run: magpie built at a93190ae and at this commit (go build
  -tags nogui), magpie serve in a sandbox HOME, its provider's Chat URL
  a local server replaying Linka's frames (the call, its signature and
  the usage in one chunk, then "stop", then [DONE]) under
  gemini-4-argon, so the Gemini paths run as for Google's host
  (geminiCompat). Clients on magpie's /v1/chat/completions, with the
  tool codemode:
    curl, the chunk magpie sends on: main, the call with no index; this
    change, index 0 (0 and 1 with the second call below)
    @ai-sdk/openai 2.0.136 (ai 5.0.281), streamText:
      main: AI_TypeValidationError, path choices, 0, delta, tool_calls,
      0, index, "Invalid input: expected number, received undefined";
      no tool-call
      this change: tool-call codemode {"code":"run()"}, finish
      tool-calls
    @ai-sdk/openai 2.0.48 and 2.0.122, older releases that turn away a
    new call with no id (2.0.48 one with no type too): main, the same
    validation error; this change, the call
    openai 5.23.2, chat.completions.stream and finalChatCompletion:
      main: no tool_calls (finish_reason tool_calls)
      this change: call_1 codemode {"code":"run()"}
    @ai-sdk/openai-compatible 1.0.59, which gives a missing index the
    call's place in its delta: the call, on main and with this change
    with a second call in a chunk of its own (made up from Linka's
    frame, id call_2):
      @ai-sdk/openai 2.0.48, 2.0.122 and 2.0.136: main, the validation
      error for each; this change, both calls
      openai: main, no tool_calls; this change, call_1 {"code":"run()"}
      and call_2 {"code":"two()"}
      @ai-sdk/openai-compatible: both calls, on main and with this
      change
    the replay sending both calls at index 0, as their place in the
    delta would give them: openai keeps one call, id call_2, arguments
    {"code":"run()"}{"code":"two()"}, on main and with this change,
    which keeps an index the upstream sent
    #3386's chunk as the report shows it, the call with no id and no
    type: this change sends it on with index 0 and an id (#2611's);
    @ai-sdk/openai 2.0.122 and 2.0.136 make the call, 2.0.48 throws
    "Expected 'function' type." and openai "tool call snapshot missing
    `type`"
    two such calls, each in a chunk of its own: nothing tells them
    apart, here as in chatDecoder, so both go with index 0 (the second
    is given its id after, where its signature is carried);
    @ai-sdk/openai 2.0.136 makes both calls, 2.0.122 the first only,
    2.0.48 and openai throw as above
  broken by hand, with this change: chatTidy without the give step:
    TestChatTidyGivesCallsAnIndex: no line's calls have an index
    ("line 4: indexes [[-1 -1]], want [[1 2]]")
    TestGeminiCompatRelayedCallsHaveAnIndex: every case, "call 0 went
    with index <nil>, want 0"
  go test -race -count=20 -cpu 1,2 of those two, TestChatTidy* and
  TestStreamedCallGivenAnID: ok
  gofmt -l internal/gateway: nothing; GOOS=linux, darwin, windows go vet
  -tags nogui ./internal/gateway: exit 0; CGO_ENABLED=0 GOOS=darwin and
  windows go build -tags nogui .: exit 0
  full suite, go test -tags nogui -count=1 -timeout 45m ./... (475 s):
  63 packages ok. 14 tests red in 7 packages, none in a file this
  change touches:
    internal/agent TestHowInstalled, TestOmpDetectedWithPiDir,
    TestZedAppPath, TestCopilotFolderFromAnIDEPluginIsNotTheCLI and
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI (qoder-cn): proc.Look
    keeps "not found" for a tool written in the tick of its folder's
    last change (#3141).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress (the
    package's only red), internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
Not tried: Google's own endpoint with a key (the frames are Linka's, as
the repo keeps them), Cursor itself, macOS, Windows.
2026-10-24 21:33:06 +08:00

208 lines
10 KiB
Go

package gateway
import (
"bytes"
"encoding/json"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// WorkBuddy's stream goes on sending an empty reasoning_content with the
// text once thinking is over; it reaches the agent without it, the
// thinking and the rest as they came.
func TestChatRelayDropsEmptyReasoning(t *testing.T) {
fresh(t)
up := sse(`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"The user said hi."}}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hi","reasoning_content":""}}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"!","reasoning_content":""}}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"reasoning_content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`,
`data: [DONE]`)
a := &scripted{replies: []reply{{200, "text/event-stream", up}}}
scriptedOn(t, "a", provider.Chat, a)
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions",
strings.NewReader(`{"model":"a/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)))
body := rec.Body.String()
if rec.Code != 200 || strings.Contains(body, `"reasoning_content":""`) ||
!strings.Contains(body, `"reasoning_content":"The user said hi."`) ||
!strings.Contains(body, `"content":"Hi"`) || !strings.Contains(body, `"content":"!"`) ||
!strings.Contains(body, `"finish_reason":"stop"`) || !strings.Contains(body, `"total_tokens":5`) ||
!strings.HasSuffix(strings.TrimSpace(body), "data: [DONE]") {
t.Fatalf("%d %s", rec.Code, body)
}
}
// CodeBuddy CN's own stream shapes, verified against copilot.tencent.com:
// every chunk that hasn't finished says "finish_reason": "" where the
// contract has null, and every tool-call argument fragment after the
// first repeats "function": {"name": ""}. Both reach the agent mended —
// null, and no empty name — with the real name and the arguments as they
// came.
func TestChatRelayTidiesCodeBuddyStream(t *testing.T) {
fresh(t)
up := sse(
`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"","reasoning_content":"The user","tool_calls":[]},"finish_reason":""}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"","reasoning_content":"","tool_calls":[]},"finish_reason":""}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"","tool_calls":[{"id":"call_1","type":"function","function":{"name":"grep","arguments":""},"index":0}]},"finish_reason":""}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"","tool_calls":[{"function":{"name":"","arguments":"{\"pat"},"index":0}]},"finish_reason":""}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"","tool_calls":[{"function":{"name":"","arguments":"tern\"}"},"index":0}]},"finish_reason":"tool_calls"}]}`,
`data: [DONE]`)
a := &scripted{replies: []reply{{200, "text/event-stream", up}}}
scriptedOn(t, "a", provider.Chat, a)
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions",
strings.NewReader(`{"model":"a/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)))
body := rec.Body.String()
if rec.Code != 200 || strings.Contains(body, `"finish_reason":""`) || strings.Contains(body, `"name":""`) ||
strings.Contains(body, `"reasoning_content":""`) ||
!strings.Contains(body, `"finish_reason":null`) || !strings.Contains(body, `"finish_reason":"tool_calls"`) ||
!strings.Contains(body, `"reasoning_content":"The user"`) ||
!strings.Contains(body, `"name":"grep"`) ||
!strings.Contains(body, `"arguments":"{\"pat`) || !strings.Contains(body, `"arguments":"tern\"}"`) ||
!strings.HasSuffix(strings.TrimSpace(body), "data: [DONE]") {
t.Fatalf("%d %s", rec.Code, body)
}
}
// Lines split across reads come out whole; one without an empty
// reasoning_content comes out byte for byte.
func TestChatTidySplitLines(t *testing.T) {
in := "data: {\"choices\":[{\"delta\":{\"content\":\"a\",\"reasoning_content\":\"\"}}]}\n\n" +
"data: {\"choices\":[{\"delta\":{\"content\":\"b\"}}], \"x\":1}\r\n\r\ndata: [DONE]"
var tidy chatTidy
var out []byte
for i := 0; i < len(in); i += 7 {
out = append(out, tidy.write([]byte(in[i:min(i+7, len(in))]))...)
}
out = append(out, tidy.flush()...)
want := "data: {\"choices\":[{\"delta\":{\"content\":\"a\"}}]}\n\n" +
"data: {\"choices\":[{\"delta\":{\"content\":\"b\"}}], \"x\":1}\r\n\r\ndata: [DONE]"
if string(out) != want {
t.Fatalf("got %q", out)
}
}
// The empty finish_reason of an unfinished chunk becomes null, on every
// choice; a real one and an already null one pass as they came.
func TestChatTidyFinishReason(t *testing.T) {
var tidy chatTidy
in := `data: {"choices":[{"index":0,"delta":{"content":"a"},"finish_reason":""},{"index":1,"delta":{"content":"b"},"finish_reason":""}]}` + "\n"
out := string(tidy.write([]byte(in)))
if strings.Contains(out, `"finish_reason":""`) || strings.Count(out, `"finish_reason":null`) != 2 {
t.Fatalf("got %q", out)
}
same := "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n" +
"data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":null}]}\n"
if got := string(tidy.write([]byte(same))) + string(tidy.flush()); got != same {
t.Fatalf("got %q", got)
}
}
// A tool-call fragment's repeated empty name is dropped while the first
// fragment's real name stands, and a last-wins merge of the mended
// fragments assembles the call as it was meant.
func TestChatTidyToolCallNames(t *testing.T) {
fragments := []string{
`{"id":"call_1","type":"function","function":{"name":"grep","arguments":""},"index":0}`,
`{"function":{"name":"","arguments":"{\"pat"},"index":0}`,
`{"function":{"name":"","arguments":"tern\"}"},"index":0}`,
}
var tidy chatTidy
name, args := "", ""
for _, frag := range fragments {
line := `data: {"choices":[{"index":0,"delta":{"tool_calls":[` + frag + `]}}]}` + "\n"
out := string(tidy.write([]byte(line)))
if strings.Contains(out, `"name":""`) {
t.Fatalf("empty name left in %q", out)
}
var chunk struct {
Choices []struct {
Delta struct {
ToolCalls []struct {
Function struct {
Name *string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
} `json:"tool_calls"`
} `json:"delta"`
} `json:"choices"`
}
if err := json.Unmarshal([]byte(strings.TrimPrefix(strings.TrimSpace(out), "data:")), &chunk); err != nil {
t.Fatalf("unreadable %q: %v", out, err)
}
fn := chunk.Choices[0].Delta.ToolCalls[0].Function
if fn.Name != nil { // a last-wins client overwrites with any name present
name = *fn.Name
}
args += fn.Arguments
}
if name != "grep" || args != `{"pattern"}` {
t.Fatalf("merged %q %q", name, args)
}
// every empty name of a multi-call, multi-choice chunk goes
multi := `data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"name":"","arguments":"a"}},{"index":1,"function":{"name":"","arguments":"b"}}]}},{"index":1,"delta":{"tool_calls":[{"index":0,"function":{"name":"","arguments":"c"}}]}}]}` + "\n"
out := string(tidy.write([]byte(multi)))
if strings.Contains(out, `"name":""`) || !strings.Contains(out, `"arguments":"a"`) ||
!strings.Contains(out, `"arguments":"b"`) || !strings.Contains(out, `"arguments":"c"`) {
t.Fatalf("got %q", out)
}
}
// A streamed call with no index is given its call's (#3386): one index for
// a call's fragments, the next for the next call (a new id, or a later
// place in its delta), each choice its own, a null index none. A stream
// whose calls have their index goes as it came.
func TestChatTidyGivesCallsAnIndex(t *testing.T) {
var tidy chatTidy
for i, c := range []struct {
choices string
want [][]float64 // each choice's calls' indexes
}{
{`[{"index":0,"delta":{"tool_calls":[{"id":"a","type":"function","function":{"name":"grep","arguments":""}}]}}]`, [][]float64{{0}}},
{`[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"{\"pat"}}]}}]`, [][]float64{{0}}},
{`[{"index":1,"delta":{"tool_calls":[{"id":"x","type":"function","function":{"name":"ls","arguments":"{}"}}]}}]`, [][]float64{{0}}},
{`[{"index":0,"delta":{"tool_calls":[{"id":"a","function":{"arguments":"tern\"}"}}]}}]`, [][]float64{{0}}},
{`[{"index":0,"delta":{"tool_calls":[{"id":"b","type":"function","function":{"name":"ls","arguments":"{}"}},{"type":"function","function":{"name":"cat","arguments":"{"}}]}}]`, [][]float64{{1, 2}}},
{`[{"index":0,"delta":{"tool_calls":[{"index":null,"function":{"arguments":"}"}}]}}]`, [][]float64{{2}}},
{`[{"index":0,"delta":{"tool_calls":[{"id":"d","type":"function","function":{"name":"pwd","arguments":"{}"}}]}},{"index":1,"delta":{"tool_calls":[{"id":"y","type":"function","function":{"name":"pwd","arguments":"{}"}}]}}]`, [][]float64{{3}, {1}}},
} {
out := tidy.write([]byte(`data: {"choices":` + c.choices + "}\n"))
var chunk struct {
Choices []struct {
Delta struct {
ToolCalls []map[string]any `json:"tool_calls"`
} `json:"delta"`
} `json:"choices"`
}
if err := json.Unmarshal(bytes.TrimPrefix(bytes.TrimSpace(out), []byte("data:")), &chunk); err != nil {
t.Fatalf("line %d unreadable %q: %v", i, out, err)
}
var got [][]float64
for _, ch := range chunk.Choices {
var idx []float64
for _, tc := range ch.Delta.ToolCalls {
n, ok := tc["index"].(float64)
if !ok {
n = -1
}
idx = append(idx, n)
}
got = append(got, idx)
}
if !reflect.DeepEqual(got, c.want) {
t.Errorf("line %d: indexes %v, want %v: %s", i, got, c.want, out)
}
}
indexed := `data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"ls","arguments":"{}"}},{"index":1,"id":"call_2","type":"function","function":{"name":"pwd","arguments":"{}"}}]}}]}` + "\n"
var other chatTidy
if out := string(other.write([]byte(indexed))); out != indexed {
t.Fatalf("a stream with its indexes changed: %q", out)
}
}