magpie icon indicating copy to clipboard operation
magpie copied to clipboard

Responses 流式回复末尾 output 为空时,网关请求钩子丢失已流出的输出(并漏处理 response.incomplete)

Open yyjsjsjx-png opened this issue 1 week ago • 3 comments

magpie version

v0.1.4811 (82127a850)

Where

Gateway only

OS

Ubuntu 24.04 (WSL2) / Windows 11

Agent, provider and model

Responses 流式回复经网关请求钩子观察(已用纯内存单元测试复现)

问题描述

当上游 OpenAI Responses 流式回复在前面的 SSE 事件(response.output_text.delta / response.output_item.done)里已经发出了文本或工具调用,而末尾 response.completed 里的 response.output 是空数组("output": [])时,internal/gateway/gateway_hooks.go 中的 gatewayReply 会把这个空 output 的终态对象原样返回。结果导致异步 onResponse 网关请求钩子收到 "output": [],丢掉了客户端实际收到的输出内容。

同一处的关联问题:gatewayReply 目前没有处理 response.incomplete(也未兼容事件类型只写在 SSE event: 行里、而 data 没写 type 的情况),遇到未完成流会直接报错 incomplete model stream,既丢失了终态里的 id/model/status/usage 和部分输出,也没有按 ctx.success = false 交给钩子。

对照仓库里已有的非流式收集路径 internal/gateway/gathered.go:它已经处理了 response.completed / response.incomplete,并且在终态 output 为空时通过 withStreamedOutput(resp, items) 回填流式收集的项;但 gateway_hooks.go 的 gatewayReply 目前缺失了这部分逻辑。

Steps to reproduce

在未修改的 v0.1.4811(82127a850)上,用以下两段合成 SSE 直接调用 gatewayReply(provider.Responses, ...) 即可复现:

用例 1:前面有文本增量和完整工具项,末尾 response.completed 的 output 为 []

data: {"type":"response.output_text.delta","output_index":0,"delta":"he"}

data: {"type":"response.output_text.delta","output_index":0,"content_index":1,"delta":"B"}

data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"llo"}

data: {"type":"response.output_item.done","output_index":2,"item":{"type":"function_call","call_id":"call_s","name":"sample","arguments":"{}"}}

data: {"type":"response.completed","response":{"id":"resp_s","status":"completed","model":"actual","usage":{"output_tokens":17},"output":[]}}

用例 2:前面有部分文本增量,末尾为 response.incomplete(且事件名仅在 SSE event: 行给出)

data: {"type":"response.output_text.delta","output_index":0,"delta":"partial"}

event: response.incomplete
data: {"response":{"id":"resp_inc","status":"incomplete","model":"actual","usage":{"output_tokens":17},"output":[]}}

What happened, and what you expected

  • 用例 1 实际结果(v0.1.4811 / 82127a850): gatewayReply 返回 {"id":"resp_s","status":"completed","model":"actual","usage":{"output_tokens":17},"output":[]},前面流出的文本块和工具调用项全部丢失。
  • 用例 1 期望结果: 保留终态的 id、model、status、usage,并在 output 为空时按 output_index 与 content_index 从前序事件回填文本块和完整工具项(若终态 output 本身非空,则仍以终态为准)。
  • 用例 2 实际结果(v0.1.4811 / 82127a850): gatewayReply 直接返回错误 incomplete model stream,终态元数据和已输出文本全部丢失。
  • 用例 2 期望结果: 保留 status: "incomplete"、终态元数据与已收集的部分输出,同时向钩子传递 ctx.success = false。
  • 异常终态(response 为 null、[] 或 {}): 应当返回错误拒绝,而不是当作有效终态继续合并。

原因定位

internal/gateway/gateway_hooks.go 的 gatewayReply 中:

  1. 只识别 e.Type == "response.completed" 且直接 return completed, nil,没有收集前序 response.output_item.done / response.output_text.delta,也没有复用 withStreamedOutput。
  2. readSSE 回调忽略了 SSE event 参数,也未处理 response.incomplete。
  3. 仅检查 len(e.Response) > 0,没有校验它是非空 JSON 对象。

参考修复与验证

下方附最小补丁,仅改动 internal/gateway/gateway_hooks.go 和 internal/gateway/gateway_hook_test.go,直接复用已有的 withStreamedOutput:

  • 按 output_index 收集 response.output_item.done,按 (output_index, content_index) 收集 response.output_text.delta(保留 item_id),忽略非预期结构的无关事件;
  • 同时支持 response.completed 与 response.incomplete(data.type 缺失时回退取 SSE event: 名),校验 response 为非空 JSON 对象,并在 response.incomplete 时补齐 status: "incomplete";
  • 仅对未被 output_item.done 覆盖的索引拼出文本消息项,再调用 withStreamedOutput(completed, items)(终态本身非空时保持原样优先);
  • 抽出 gatewayReplySucceeded,确保 incomplete 与 failed 统一向 run.Finish 传递 success = false。

在 v0.1.4811(82127a850,Go 1.26.8,WSL2 Ubuntu 24.04)上的实测结果:

  • 修复前(未打补丁的 82127a850,改前必红):
    • 用例 1 失败:got={"id":"resp_s","status":"completed","model":"actual","usage":{"output_tokens":17},"output":[]}
    • 用例 2 失败:err=incomplete model stream
  • 修复后(补丁在 82127a850 上 git apply 零冲突通过):
    • go test -tags nogui -count=1 -v -run '^TestGatewayHookResponsesStreamedOutput$' ./internal/gateway/ — 全部通过(0.01s,覆盖 empty、whole、incomplete、ignores_unexpected_event_shapes 及 null/[]/{} 异常终态拒绝)
    • go test -tags nogui -count=1 -run '^TestGatewayHook' ./internal/gateway/ — 3 项钩子测试全过(0.575s)
    • go vet -tags nogui ./internal/gateway/ 与 GOOS=windows go vet ./internal/gateway/ — 均退出码 0
  • 同类路径核对:internal/gateway/gathered.go 已有对应处理;面向客户端的流式透传未作改动。
  • 未验证项:macOS 编译/vet、-race、全仓测试、以及真实上游账号流量(纯内存 SSE 解析修复)。
基于 82127a850 的参考补丁(git apply)
diff --git a/internal/gateway/gateway_hook_test.go b/internal/gateway/gateway_hook_test.go
index 9944c45c6..eefbe4199 100644
--- a/internal/gateway/gateway_hook_test.go
+++ b/internal/gateway/gateway_hook_test.go
@@ -710,3 +710,71 @@ export async function onResponse(body,ctx){await fetch(ctx.options.url,{method:"
 		}
 	}
 }
+
+func TestGatewayHookResponsesStreamedOutput(t *testing.T) {
+	for _, tc := range []struct {
+		name, eventType, status, terminal, want string
+		extra                                   []string
+	}{
+		{"empty", "response.completed", "completed", "[]", "hello", nil},
+		{"whole", "response.completed", "completed", `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"whole"}]}]`, "whole", nil},
+		{"incomplete", "response.incomplete", "incomplete", "[]", "hello", nil},
+		{"ignores unexpected event shapes", "response.completed", "completed", "[]", "hello", []string{`data: {"type":"response.custom","output_index":"non-int","delta":{"nested":true}}`}},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			lines := []string{
+				`data: {"type":"response.output_text.delta","output_index":0,"delta":"he"}`,
+				`data: {"type":"response.output_text.delta","output_index":0,"content_index":1,"delta":"B"}`,
+				`data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"llo"}`,
+			}
+			lines = append(lines, tc.extra...)
+			lines = append(lines,
+				`data: {"type":"response.output_item.done","output_index":2,"item":{"type":"function_call","call_id":"call_s","name":"sample","arguments":"{}"}}`,
+				`data: {"type":"`+tc.eventType+`","response":{"id":"resp_s","status":"`+tc.status+`","model":"actual","usage":{"output_tokens":17},"output":`+tc.terminal+`}}`)
+			if tc.name == "incomplete" {
+				// Some send the event type only in the SSE event field.
+				lines[len(lines)-1] = "event: response.incomplete\n" + strings.Replace(lines[len(lines)-1], `"type":"response.incomplete",`, "", 1)
+			}
+			input := sse(lines...)
+			got, err := gatewayReply(provider.Responses, []byte(input))
+			if err != nil {
+				t.Fatal(err)
+			}
+			var r struct {
+				ID, Model, Status string
+				Output            []json.RawMessage
+				Usage             struct {
+					Tokens int `json:"output_tokens"`
+				}
+			}
+			if err := json.Unmarshal(got, &r); err != nil {
+				t.Fatal(err)
+			}
+			if r.ID != "resp_s" || r.Model != "actual" || r.Status != tc.status || r.Usage.Tokens != 17 || len(r.Output) == 0 || !strings.Contains(string(r.Output[0]), tc.want) {
+				t.Fatalf("hook response %s", got)
+			}
+			if gatewayReplySucceeded(got) != (tc.status == "completed") {
+				t.Fatalf("unexpected hook success for %s", got)
+			}
+			if tc.name != "whole" {
+				var message struct{ Content []struct{ Text string } }
+				if err := json.Unmarshal(r.Output[0], &message); err != nil || len(message.Content) != 2 || message.Content[0].Text != "hello" || message.Content[1].Text != "B" {
+					t.Fatalf("unpreserved text blocks: %s", r.Output[0])
+				}
+			}
+			if tc.name == "whole" {
+				if len(r.Output) != 1 {
+					t.Fatalf("output %s", got)
+				}
+			} else if len(r.Output) != 2 || !strings.Contains(string(r.Output[1]), "call_s") {
+				t.Fatalf("output %s", got)
+			}
+		})
+	}
+	for _, terminal := range []string{"null", "[]", "{}"} {
+		input := sse(`data: {"type":"response.output_text.delta","delta":"x"}`, `data: {"type":"response.completed","response":`+terminal+`}`)
+		if got, err := gatewayReply(provider.Responses, []byte(input)); err == nil || got != nil {
+			t.Fatalf("terminal %s accepted as %s", terminal, got)
+		}
+	}
+}
diff --git a/internal/gateway/gateway_hooks.go b/internal/gateway/gateway_hooks.go
index 80b95ade7..4ef384cfe 100644
--- a/internal/gateway/gateway_hooks.go
+++ b/internal/gateway/gateway_hooks.go
@@ -4,7 +4,10 @@ import (
 	"bytes"
 	"encoding/json"
 	"errors"
+	"maps"
 	"net/http"
+	"slices"
+	"strings"
 
 	"github.com/yetone/magpie/internal/plugin"
 	"github.com/yetone/magpie/internal/provider"
@@ -29,13 +32,19 @@ func gatewayResponse(w http.ResponseWriter, r *http.Request, proto provider.Prot
 			return
 		}
 		reply, err := gatewayReply(proto, output)
-		var response obj
-		json.Unmarshal(reply, &response)
-		success := err == nil && (len(response["error"]) == 0 || string(response["error"]) == "null") && str(response, "status") != "failed" && str(response, "status") != "incomplete"
-		run.Finish(r.Context(), reply, success, body)
+		run.Finish(r.Context(), reply, err == nil && gatewayReplySucceeded(reply), body)
 	}
 }
 
+func gatewayReplySucceeded(reply json.RawMessage) bool {
+	var response obj
+	if json.Unmarshal(reply, &response) != nil || response == nil {
+		return false
+	}
+	status := str(response, "status")
+	return (len(response["error"]) == 0 || string(response["error"]) == "null") && status != "failed" && status != "incomplete"
+}
+
 // gatewayReply is the reply the client got as one whole reply in its API: a
 // whole body as it is, and a stream read through the protocol's decoder into
 // the reply the gateway would have rendered. A Responses stream's completed
@@ -51,9 +60,15 @@ func gatewayReply(proto provider.Protocol, body []byte) (json.RawMessage, error)
 	}
 	var c collector
 	var completed json.RawMessage
+	items := map[int]json.RawMessage{}
+	type messageText struct {
+		id    string
+		parts map[int]*strings.Builder
+	}
+	texts := map[int]*messageText{}
 	decode := decoder(proto)
 	ended := false
-	err := readSSE(bytes.NewReader(body), func(_ string, data string) error {
+	err := readSSE(bytes.NewReader(body), func(event string, data string) error {
 		if data == "[DONE]" {
 			ended = true
 			return nil
@@ -62,12 +77,56 @@ func gatewayReply(proto provider.Protocol, body []byte) (json.RawMessage, error)
 			return errors.New("invalid model stream")
 		}
 		if proto == provider.Responses {
-			var e struct {
-				Type     string          `json:"type"`
-				Response json.RawMessage `json:"response"`
+			var e obj
+			if err := json.Unmarshal([]byte(data), &e); err != nil || e == nil {
+				return errors.New("invalid Responses stream event")
+			}
+			kind := str(e, "type")
+			if kind == "" && event != "" {
+				kind = event
+				e["type"] = raw(kind)
+				data = string(raw(e)) // the shared decoder uses the payload type
 			}
-			if json.Unmarshal([]byte(data), &e) == nil && e.Type == "response.completed" && len(e.Response) > 0 {
-				completed = e.Response
+			switch kind {
+			case "response.completed", "response.incomplete":
+				var terminal obj
+				if json.Unmarshal(e["response"], &terminal) != nil || len(terminal) == 0 {
+					return errors.New("missing Responses terminal object")
+				}
+				completed = e["response"]
+				if kind == "response.incomplete" && str(terminal, "status") != "incomplete" {
+					terminal["status"] = raw("incomplete")
+					completed = raw(terminal)
+				}
+				ended = true
+			case "response.output_item.done", "response.output_text.delta":
+				var part struct {
+					Output  int `json:"output_index"`
+					Content int `json:"content_index"`
+				}
+				if json.Unmarshal([]byte(data), &part) != nil || part.Output < 0 || part.Content < 0 {
+					break
+				}
+				if kind == "response.output_item.done" {
+					if item := e["item"]; len(item) > 0 && item[0] == '{' {
+						items[part.Output] = item
+					}
+					break
+				}
+				if delta := str(e, "delta"); delta != "" {
+					msg := texts[part.Output]
+					if msg == nil {
+						msg = &messageText{parts: make(map[int]*strings.Builder)}
+						texts[part.Output] = msg
+					}
+					if msg.id == "" {
+						msg.id = str(e, "item_id")
+					}
+					if msg.parts[part.Content] == nil {
+						msg.parts[part.Content] = new(strings.Builder)
+					}
+					msg.parts[part.Content].WriteString(delta)
+				}
 			}
 		}
 		return decode(data, func(e Event) {
@@ -87,7 +146,23 @@ func gatewayReply(proto provider.Protocol, body []byte) (json.RawMessage, error)
 		return nil, errors.New(c.err)
 	}
 	if completed != nil {
-		return completed, nil
+		// The terminal object owns the id, model, status and usage. Some
+		// Codex replies deliver all output in earlier events.
+		for index, text := range texts {
+			if _, done := items[index]; done {
+				continue
+			}
+			var content []map[string]string
+			for _, part := range slices.Sorted(maps.Keys(text.parts)) {
+				content = append(content, map[string]string{"type": "output_text", "text": text.parts[part].String()})
+			}
+			msg := map[string]any{"type": "message", "role": "assistant", "content": content}
+			if text.id != "" {
+				msg["id"] = text.id
+			}
+			items[index] = raw(msg)
+		}
+		return withStreamedOutput(completed, items), nil
 	}
 	res := c.finish()
 	return render(proto, res, &Request{Model: res.Model}), nil

Assisted-by: Gemini 4 Neon (Antigravity, design & coordination), GPT-6.2-Astra (Codex, cross-review & implementation)

yyjsjsjx-png avatar Nov 25 '26 19:11 yyjsjsjx-png

I have a proposed fix: https://github.com/yetone/magpie/compare/main...joei4cm:magpie:fix/7760-hook-streamed-output

gatewayReply now keeps a Responses stream's output for the onResponse hook: a response.completed naming an empty output is filled from the stream's output_item.done items, the same way the gathered non-stream path does (withStreamedOutput). response.incomplete is taken as the reply a cut stream ends with, so the hook gets its id, model, status and usage instead of an incomplete model stream error, and an event type written only on the event: line is read. gatewayResponse already reports success = false for a reply whose status is incomplete.

go test ./internal/gateway -run 'TestGatewayReply|Hook' -count=1 and go vet ./internal/gateway passed; both new tests failed on the old code. The full suite and a real hook against a vendor were not run locally.

joei4cm avatar Nov 25 '26 19:11 joei4cm

Correction to my earlier comment: the first branch head did not handle the exact examples in the report. I have updated the same branch to ba394a5c0:

https://github.com/yetone/magpie/compare/main...joei4cm:magpie:fix/7760-hook-streamed-output

It now also reconstructs text deltas by output and content index alongside completed tool items, handles a terminal whose type is only on the SSE event line, and rejects null, array and empty-object terminal responses. The report's mixed text/tool example failed on the previous branch head and now passes in go test ./internal/gateway -run 'TestGatewayReply|TestGatewayHook' -count=1. Full suite and real vendor use were not run. Thank you for the detailed reproduction and reference patch.

joei4cm avatar Nov 25 '26 20:11 joei4cm

Panel integration is available in L0NE-6/magpie-panel as a1450b7 (audit note 8e0dbbd). The hook reply now fills an empty response.completed.output from the streamed output_item.done items, treats response.incomplete as the terminal reply for a cut stream, and recognizes an event type carried only on the event: line.

Verified with focused hook tests, 5 race iterations, go vet, and git diff --check. Boundary: synthetic SSE fixtures; a live vendor hook was not exercised. This is a panel integration, not an upstream merge.

L0NE-6 avatar Nov 25 '26 20:11 L0NE-6