magpie icon indicating copy to clipboard operation
magpie copied to clipboard

copilot 的 OpenAI chat.completions 流式 chunk 缺少 object 字段,导致 Grok Build 解析失败(serialization error: missing field object)

Open gujunxiang opened this issue 2 weeks ago • 2 comments

magpie version

0.1.4250

Where

Gateway only

OS

macOS(Apple Silicon / arm64)

Agent, provider and model

Grok Build → copilot → claude-opus-5.5(经 group/smart-split 或 group/auto-claude-*-5-5 路由到 copilot)

Steps to reproduce

对本地网关直接请求 OpenAI 兼容的 chat.completions 流式接口,模型选择会路由到 copilot 的组(如 group/smart-split):

curl -sS -N http://127.0.0.1:3425/v1/chat/completions \
  -H 'Authorization: Bearer <key>' \
  -H 'Content-Type: application/json' \
  -d '{"model":"group/smart-split","max_tokens":8,"stream":true,"messages":[{"role":"user","content":"hi"}]}'

What happened, and what you expected

响应头显示实际路由到了 copilot:X-Magpie-Provider: copilot、X-Magpie-Model: copilot/claude-opus-5.5。但返回的 SSE chunk 缺少 object 字段:

data: {"choices":[{"index":0,"delta":{"content":"Hi","role":"assistant"}}],"created":1795011925,"id":"msg_011ChAYhfy7Q3dZMjKwwJMvv","model":"group/smart-split"}

对照:同样走 /v1/chat/completions,但模型路由到 workbuddy-ai(如 auto/deepseek-v4.1-flash)时,chunk 是标准格式、带 object:

data: {"choices":[...],"created":1795011923,"id":"6d185fa12067ce2a0c908859a8e12af8","model":"group/auto-deepseek-v4-1-flash","object":"chat.completion.chunk","usage":null}

期望:/v1/chat/completions 返回的每个流式 chunk 都包含 "object":"chat.completion.chunk"。

实际影响:Grok Build(OpenAI ChatCompletions 后端)按标准 ChatCompletionChunk 严格解析(要求 id/object/created/model/choices 齐全)。遇到 copilot 这条缺 object 的 chunk 时直接报:

serialization error: missing field `object` at line 1 column 163

整轮对话失败、只能手动重发。Claude Code 因为走 /v1/messages(Anthropic 协议),copilot 在该协议下输出正常,所以不受影响——问题只出在 copilot 的 OpenAI chat.completions 输出适配器。

Error text or logs

Grok Build 侧报错(kind=serialization、is_retryable=false):

serialization error: missing field `object` at line 1 column 163
serialization error: missing field `object` at line 1 column 167

定位猜测:copilot 适配器在把上游响应翻译成 OpenAI chunk 时漏写了 object 字段(注意其 id 仍是 Anthropic 风格的 msg_...)。workbuddy/其他 provider 的同一路径已有 object,建议在 copilot 的 OpenAI chunk 组装处补上 "object":"chat.completion.chunk"。

gujunxiang avatar Nov 18 '26 14:11 gujunxiang

我用本地假 Copilot 服务复现了同样的缺字段输出,下面提供待评审候选补丁,基于 cb96fcc3a04a9daee5b5ad4be110c671c11e59d3。发布前核对到 1e2287758c6d25ed1c3435bf39f8552e225be99b,相关 chattidy.go/gateway.go 尚无新变化,issue/PR 未发现重复修复。

路径和改动

这里至少有一条可复现路径是 Chat→Chat 原样转发,不是 chatEncoder 漏字段(该编码器已经写 object)。本地假上游按报告形状发出缺 object 的帧,经 Copilot 路由后,原代码仍把缺字段帧交给客户端。这不证明真实 Copilot 内部如何产生该帧,也没有访问真实账号。

补丁在 chatTidy 对合法 JSON、顶层 choices 为数组且 object 缺失的 SSE 帧补 "object":"chat.completion.chunk"。不覆盖已有 object(null 也保留),不改内容、finish_reason 或 usage;错误对象、坏 JSON、注释与 [DONE] 保持原样。逐行检查避免同一次网络读取内正常帧遮住缺字段帧。没有改非流式响应、翻译器、路由权限、凭据、依赖或工作流。

新测试覆盖:假 Copilot 完整服务路径、混合正常/缺字段帧的两种顺序、同批完整帧、逐字节分片、无末尾换行 flush、嵌套 object、usage-only 及不应修改的帧。五组旧测试的“合法流保持字节不变”fixture 补齐 object,原断言保留。子系统文档同步更新。

验证与限制

Linux amd64 / Go 1.26.8,临时 HOME、隔离 Go 缓存,仅本地假服务。

  • 原代码运行 go test -p 1 -tags nogui ./internal/gateway -run '^TestCopilotChatChunkObject$' -count=1,真实 FAIL:HTTP 200、有 Hi,但两个帧均缺 object(0.044s)。
  • 最终候选:go test -p 1 -tags nogui ./internal/gateway -run '^(TestCopilotChatChunkObject|TestChatObjectMixedReads|TestChatTidy.*|TestChatRelay.*|TestWorkBuddy.*|TestMistral.*)$' -count=20 -bench '^BenchmarkChatObjectNormalStream$' -benchtime=300ms 通过(25.055s)。
  • go vet -p 1 -tags nogui ./internal/gateway 通过;修改文件 gofmt、git diff --check 干净。独立只读审查无剩余阻断项。
  • 有额外正常流开销:同机正常单帧微基准,原代码(overlay 恢复 chattidy.go)3 次为 848.5 / 865.9 / 1606 ns/op,256 B/op、2 allocs/op;候选 20 次 979.5–1739 ns/op,280 B/op、3 allocs/op。耗时有噪声,不能宣称无性能回归;此基准增加 24 B/op、1 alloc/op,未做真实吞吐压测。
  • 未运行整个 gateway/仓库 suite、race、跨平台 build/vet、真实 Copilot 或 Grok Build;不是 release-ready 或已合入声明。尚无 PR/合并。

使用 @gujunxiang 的错误文本和帧形状,IDs/模型/账号数据在测试中换成占位和本地 fake。AI 辅助实现与验证。采用时请按项目规则保留报告者及补丁作者 credit: Co-authored-by: gujunxiang <[email protected]>

完整候选补丁(6 个文件)
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 95ecc7d..f46211d 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -381,6 +381,14 @@ the key's leaves the call as asked, with a log line (`compactRefused`).
 - A Responses request bound for anything but a ChatGPT sign-in has its tool exchanges mended in `attempt`, before it is relayed or translated, plugins included ([`responses.go`](../../internal/gateway/responses.go)). An item inside a run of calls and results (after one of the run's results and before the last, or before any result when the model didn't write it) moves to the end of that run (`joinToolRuns`, #1752, Edward4226): Codex writes its `<image_resize_notice>` right after each result whose image it resized, so a batch of two calls had it between their results, and a strict upstream answered 400 (OpenCode Go/DeepSeek "No tool output found for tool call …", Volcengine's "must be followed by tool messages", #1822); a Chat translation answered the second call with a synthetic result. An item carrying a `call_id` never moves, the model's own reasoning between its calls stays, and its text between them (an assistant message, with the reasoning right before it) goes ahead of the run's first call, so the step's calls stand together: OpenCode Go opens a new assistant message at such text and answered the call before it "No tool output found for tool call …" (#2100). A call opens a run only when a result after it answers it. A result with no call id becomes a user message after its run (`orphanedToolOutputs`), and a call nothing answers gets a synthetic result at the end of its run (`pairToolItems`, #1341). `TestRelayedCodexImageBatchKeepsItsResultsTogether`, `TestJoinToolRunsOnlyMovesWhatBreaksARun`, `TestRelayedTextBetweenABatchsCallsIsAnswered`.
 - A Chat client's own body relayed to a Chat upstream (`passthrough`) has its tool exchanges mended when they don't pair (`toolPairsOut` in [`chattidy.go`](../../internal/gateway/chattidy.go)), by the rule a translated one is built with (`pairToolMessages` in [`chat.go`](../../internal/gateway/chat.go)): Kimi's Chat API, like OpenAI's, turns the whole request away for an assistant's call the tool messages right after it don't answer ("an assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'…"), a user message between a call and its answer included, and for a tool message with no call before it ("tool_call_id  is not found"), both checked against api.kimi.com/coding on 2026-10-26. Qoder's chat forked at an earlier turn, its model switched to Kimi Code, was refused on every prompt (Paidaixinbao on X). A turn's calls split over consecutive assistant messages join into one first (`joinSplitChatCalls`); a call left unanswered gets the synthetic interrupted result; an answer to no call becomes the user's text, a parts content by its text parts. A body whose exchange pairs goes byte for byte, answers out of the calls' order included, which Kimi takes (`TestChatRelayPairsToolsForKimi`, `TestChatRelayPairedToolsUntouched`).
 - A Chat request has every tool call that came with no id (`""`, null or none) given one in `attempt`, before it is relayed or translated, plugins included (`chatCallIDs` in [`chat_call_ids.go`](../../internal/gateway/chat_call_ids.go), #2611, RunMintOn). An upstream that sometimes streams a call without an id (OpenCode Zen's free DeepSeek) has the agent keep it as `""`, which that upstream takes back, while WorkBuddy AI turns a streamed request carrying one away (400, code 11133) and Anthropic takes no empty `tool_use` id. The id is made from the call's place in the request, its name and its arguments, never at random, so the next turn's history goes byte for byte and the upstream's prompt cache holds; the tool messages after the call that answer with no `tool_call_id` take the made ids in the calls' order. A body whose calls all have ids goes as it came. On the reply side, a relayed Chat stream's call whose first fragment has no id is given one, and a later fragment's empty id is left out (`chatTidy`); a whole reply's call is given one too (`chatWhole`). `TestEmptyCallIDRelayedWithOne`, `TestEmptyCallIDReachesPluginWithOne`, `TestEmptyCallIDTranslatedWithOne`, `TestStreamedCallGivenAnID` in [`chat_call_ids_test.go`](../../internal/gateway/chat_call_ids_test.go).
+- A relayed Chat SSE chunk with a `choices` array and no top-level `object`
+  gets `object: "chat.completion.chunk"` (`chatTidy`, #7115): Copilot's
+  missing field makes strict Chat clients reject an otherwise valid reply.
+  Existing values are preserved, including null; non-Chat data, malformed
+  JSON, comments and `[DONE]` are not converted into chunks. The check is
+  per SSE line, including mixed network reads and the final partial line
+  (`TestCopilotChatChunkObject`, `TestChatObjectMixedReads`). Translated
+  streams already carry the field from `chatEncoder`.
 - A relayed Chat stream's tool call fragment with no `index` (none, or null) is given its call's (`streamCallIndexes` in [`chattidy.go`](../../internal/gateway/chattidy.go), #3386). Gemini's OpenAI-compatible API sends its calls with none, where the OpenAI contract has one on every fragment: the AI SDK's OpenAI provider (Cursor's Private Inference) turned the chunk away ("expected number, received undefined" at `tool_calls[0].index`), and OpenAI's node SDK's stream helper kept no call at all. A fragment with an id other than the open call's, or after the first in its delta, is the next call; any other goes on with the open one. So two calls in chunks of their own are 0 and 1, never both 0, which that helper merges into one call. A fragment with an index keeps it. `TestChatTidyGivesCallsAnIndex` in [`chattidy_test.go`](../../internal/gateway/chattidy_test.go), `TestGeminiCompatRelayedCallsHaveAnIndex` in [`gemini_compat_cut_test.go`](../../internal/gateway/gemini_compat_cut_test.go).
 - A translated Chat stream's tool calls are read by `index`, not as one after another (`chatDecoder.toolCall` in [`chat.go`](../../internal/gateway/chat.go)). An upstream may send several calls' fragments by turns (index 0, 1, 0, 1…), the first of each with its id and name; read as a new call at each change of index, two calls reached Codex as six `function_call` items, the first two with `{}` and four with no name (mysterious_dove on Discord). The open call streams as it comes; a call that starts while the open one's arguments aren't yet whole JSON is held by its index and given whole, in index order, at `finish_reason` or `[DONE]`. Every translation from Chat (Responses, Messages, Gemini, a whole reply) reads the stream through it. `TestInterleavedToolCallsToResponses`, `TestInterleavedToolCallsToAnthropic`, `TestInterleavedToolCallsWhole`, `TestToolCallsNamedFirstThenArgued` in [`translate_stream_test.go`](../../internal/gateway/translate_stream_test.go).
 - A relayed Chat reply whose choice made calls and ended `stop` ends `tool_calls`, streamed (`chatTidy`) and whole (`chatWhole`), as the translations' collector already ends it (`collector.finish`): told it stopped, a client that reads `finish_reason` ends its turn with the calls not run (喜欢一个人 on Discord, a relay in front of deepseek-v4.1-flash). Any other reason stays as it came. `TestChatCallsEndToolCalls` in [`chattidy_finish_test.go`](../../internal/gateway/chattidy_finish_test.go).
diff --git a/internal/gateway/chattidy.go b/internal/gateway/chattidy.go
index 7ee1c6f..28a8433 100644
--- a/internal/gateway/chattidy.go
+++ b/internal/gateway/chattidy.go
@@ -6,6 +6,8 @@ import (
 	"encoding/json"
 	"slices"
 	"strings"
+
+	"github.com/tidwall/gjson"
 )
 
 // chatTidy mends a Chat Completions stream relayed as it is. WorkBuddy's
@@ -168,7 +170,31 @@ func needsTidy(line []byte) bool {
 // needs is needsTidy, a finish_reason once a choice made a call, and a
 // usage that may tell its cache in names OpenAI's clients don't read.
 func (t *chatTidy) needs(b []byte) bool {
-	return needsTidy(b) || len(t.called) > 0 && bodyHasBytes(b, finishReasonField) || mayMendUsage(b)
+	return missingChatObject(b) || needsTidy(b) || len(t.called) > 0 && bodyHasBytes(b, finishReasonField) || mayMendUsage(b)
+}
+
+// missingChatObject checks each SSE line: a complete chunk in the same
+// network read must not hide a neighboring chunk missing its object (#7115).
+// Querying fields keeps the normal stream out of the map decoder.
+func missingChatObject(b []byte) bool {
+	for len(b) > 0 {
+		line, rest, found := bytes.Cut(b, []byte("\n"))
+		if !found {
+			rest = nil
+		}
+		b = rest
+		data, ok := bytes.CutPrefix(line, []byte("data:"))
+		if !ok {
+			continue
+		}
+		if gjson.GetBytes(data, "object").Exists() {
+			continue
+		}
+		if gjson.GetBytes(data, "choices").IsArray() {
+			return true
+		}
+	}
+	return false
 }
 
 var (
@@ -264,6 +290,11 @@ func (t *chatTidy) line(line []byte) []byte {
 	if decodeJSON(data, &chunk) != nil || chunk == nil {
 		return line
 	}
+	objectMended := false
+	if _, exists := chunk["object"]; !exists && gjson.GetBytes(data, "choices").IsArray() {
+		chunk["object"] = json.RawMessage(`"chat.completion.chunk"`)
+		objectMended = true
+	}
 	usageMended := false
 	if raw, ok := chunk["usage"]; ok {
 		chunk["usage"], usageMended = openAIUsage(raw)
@@ -367,7 +398,7 @@ func (t *chatTidy) line(line []byte) []byte {
 			}
 		}
 	}
-	if !changed && !usageMended {
+	if !changed && !usageMended && !objectMended {
 		return line
 	}
 	if changed {
diff --git a/internal/gateway/chattidy_test.go b/internal/gateway/chattidy_test.go
index 9c392ab..cc9e65b 100644
--- a/internal/gateway/chattidy_test.go
+++ b/internal/gateway/chattidy_test.go
@@ -71,16 +71,16 @@ func TestChatRelayTidiesCodeBuddyStream(t *testing.T) {
 // 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]"
+	in := "data: {\"object\":\"chat.completion.chunk\",\"choices\":[{\"delta\":{\"content\":\"a\",\"reasoning_content\":\"\"}}]}\n\n" +
+		"data: {\"object\":\"chat.completion.chunk\",\"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]"
+	want := "data: {\"choices\":[{\"delta\":{\"content\":\"a\"}}],\"object\":\"chat.completion.chunk\"}\n\n" +
+		"data: {\"object\":\"chat.completion.chunk\",\"choices\":[{\"delta\":{\"content\":\"b\"}}],  \"x\":1}\r\n\r\ndata: [DONE]"
 	if string(out) != want {
 		t.Fatalf("got %q", out)
 	}
@@ -95,8 +95,8 @@ func TestChatTidyFinishReason(t *testing.T) {
 	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"
+	same := "data: {\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n" +
+		"data: {\"object\":\"chat.completion.chunk\",\"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)
 	}
@@ -199,7 +199,7 @@ func TestChatTidyGivesCallsAnIndex(t *testing.T) {
 		}
 	}
 
-	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"
+	indexed := `data: {"object":"chat.completion.chunk","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)
diff --git a/internal/gateway/mistral_parts_test.go b/internal/gateway/mistral_parts_test.go
index d303518..8e41e43 100644
--- a/internal/gateway/mistral_parts_test.go
+++ b/internal/gateway/mistral_parts_test.go
@@ -107,7 +107,7 @@ func TestMistralPartsWholeFlattened(t *testing.T) {
 
 // Replies of other upstreams pass byte for byte, streamed or not.
 func TestChatRelayWithoutPartsUntouched(t *testing.T) {
-	line := `data: {"choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":null}]}` + "\n"
+	line := `data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":null}]}` + "\n"
 	if got := string(tidyLine([]byte(line))); got != line {
 		t.Fatalf("%s", got)
 	}
diff --git a/internal/gateway/workbuddy_blocks_test.go b/internal/gateway/workbuddy_blocks_test.go
index f1db4b1..4f7af87 100644
--- a/internal/gateway/workbuddy_blocks_test.go
+++ b/internal/gateway/workbuddy_blocks_test.go
@@ -53,7 +53,7 @@ func TestChatRelayDropsEmptyToolCalls(t *testing.T) {
 
 // A tool call's own list is left as it came.
 func TestChatTidyKeepsToolCalls(t *testing.T) {
-	line := `data: {"choices":[{"delta":{"content":"","tool_calls":[{"index":0,"id":"call_1","function":{"name":"grep","arguments":""}}]}}]}` + "\n"
+	line := `data: {"object":"chat.completion.chunk","choices":[{"delta":{"content":"","tool_calls":[{"index":0,"id":"call_1","function":{"name":"grep","arguments":""}}]}}]}` + "\n"
 	if got := string(tidyLine([]byte(line))); got != line {
 		t.Fatalf("%s", got)
 	}
diff --git a/internal/gateway/copilot_chunk_object_test.go b/internal/gateway/copilot_chunk_object_test.go
new file mode 100644
index 0000000..1b77cfd
--- /dev/null
+++ b/internal/gateway/copilot_chunk_object_test.go
@@ -0,0 +1,62 @@
+package gateway
+
+import (
+	"io"
+	"net/http"
+	"strings"
+	"testing"
+)
+
+// #7115's reported wire shape, with made-up IDs and no account data.
+func TestCopilotChatChunkObject(t *testing.T) {
+	copilotFake(t, "fixture-token", func(w http.ResponseWriter, r *http.Request) {
+		if r.URL.Path == "/models" {
+			io.WriteString(w, copilotStudentModels)
+			return
+		}
+		w.Header().Set("Content-Type", "text/event-stream")
+		io.WriteString(w, sse(`data: {"choices":[{"index":0,"delta":{"content":"Hi","role":"assistant"}}],"created":1795011925,"id":"msg_fixture","model":"gpt-4.1"}`, `data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"created":1795011925,"id":"msg_fixture","model":"gpt-4.1"}`, `data: [DONE]`))
+	})
+	code, body := postAs(t, New(), "", `{"model":"copilot/gpt-4.1","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
+	if code != 200 || !strings.Contains(body, `"content":"Hi"`) {
+		t.Fatalf("%d %s", code, body)
+	}
+	if strings.Count(body, `"object":"chat.completion.chunk"`) != 2 {
+		t.Fatalf("missing chunk object: %s", body)
+	}
+}
+
+func TestChatObjectMixedReads(t *testing.T) {
+	missing := `data: {"choices":[{"delta":{"content":"Hi","object":"nested"}}],"id":"c"}`
+	present := `data: {"object":"chat.completion.chunk","choices":[]}`
+	for _, input := range []string{present + "\n" + missing, missing + "\n" + present, present + "\n" + missing + "\n", missing + "\n" + present + "\n"} {
+		for _, step := range []int{1, len(input)} {
+			var tidy chatTidy
+			var out []byte
+			for i := 0; i < len(input); i += step {
+				out = append(out, tidy.write([]byte(input[i:min(i+step, len(input))]))...)
+			}
+			out = append(out, tidy.flush()...)
+			if strings.Count(string(out), `"object":"chat.completion.chunk"`) != 2 {
+				t.Fatal(string(out))
+			}
+		}
+	}
+	for _, line := range []string{`data: [DONE]`, `: keepalive`, `data: {"error":{"message":"no"}}`, `data: {"choices":null}`, `data: {"choices":[],"object":null}`, `data: {"choices":[],"object":"custom"}`, `data: {"choices":[] invalid}`} {
+		if got := string(tidyLine([]byte(line))); got != line {
+			t.Fatalf("changed %q to %q", line, got)
+		}
+	}
+	if got := string(tidyLine([]byte(`data: {"choices":[],"usage":{"prompt_tokens":1}}`))); !strings.Contains(got, `"object":"chat.completion.chunk"`) || !strings.Contains(got, `"prompt_tokens":1`) {
+		t.Fatal(got)
+	}
+}
+
+func BenchmarkChatObjectNormalStream(b *testing.B) {
+	line := []byte("data: {\"id\":\"c\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"m\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hello\"}}]}\n\n")
+	b.ReportAllocs()
+	for b.Loop() {
+		var tidy chatTidy
+		tidy.write(line)
+	}
+}

yhdhaidong avatar Nov 18 '26 15:11 yhdhaidong

把这份候选补丁在当前 main(d673d10dd)上验证了一遍,结论:代码可原样收取,只需 docs 一处三行冲突手工合。

套用:git apply --3way 于 d673d10dd——chattidy.go / chattidy_test.go / copilot_chunk_object_test.go(新)/ mistral_parts_test.go / workbuddy_blocks_test.go 五个代码文件干净套用;gateway-routing.md 因上游 #7941 期间在同列表位插了 BoundCallID bullet 冲突,两个 bullet 都保留即合。

验证(Windows x64,Go 1.26.8,-tags nogui):

  • TestCopilotChatChunkObject + TestChatObjectMixedReads(补丁新测试)→ PASS
  • TestChatTidy* / TestChatRelay* / TestWorkBuddy* / TestMistral* 四族 → ok(15s)
  • gofmt -l internal/gateway/ 无输出;go vet -p 1 -tags nogui ./internal/gateway 干净
  • fixture 改动核对:仅在原字节断言的 fixture 行头部补 "object":"chat.completion.chunk",,原断言原样保留,与补丁描述一致

实现核对:missingChatObject 用 gjson 逐行探测(避免整行 map 解码走常路径),line() 在顶层 object 缺失且 choices 为数组时补 "chat.completion.chunk",已有值(含 null)不动,objectMended 接进既有重编码判定——与评论里声明的行为逐条相符。gjson 已在 go.mod,无新依赖。

#8298(0.1.5133 复现的回归报告)与本题同一缺陷,这份补丁收取即两题同关。

Dopetaiga avatar Nov 30 '26 07:11 Dopetaiga