fix(client): harden chat and agent SSE reliability

This commit is contained in:
coconut-yc
2026-06-21 02:40:25 +08:00
committed by lyingbug
parent 1661827d6e
commit 238297e2c5
10 changed files with 458 additions and 40 deletions
+14 -1
View File
@@ -47,6 +47,7 @@ const (
AgentResponseTypeAnswer AgentResponseType = "answer"
AgentResponseTypeReflection AgentResponseType = "reflection"
AgentResponseTypeError AgentResponseType = "error"
AgentResponseTypeComplete AgentResponseType = "complete"
)
// AgentStreamResponse agent streaming response
@@ -85,7 +86,7 @@ func (c *Client) AgentQAStreamWithRequest(ctx context.Context,
}
path := fmt.Sprintf("/api/v1/agent-chat/%s", sessionID)
resp, err := c.doRequest(ctx, http.MethodPost, path, request, nil)
resp, err := c.doRequestStream(ctx, http.MethodPost, path, request, nil)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
@@ -103,6 +104,11 @@ func (c *Client) AgentQAStreamWithRequest(ctx context.Context,
// processAgentSSEStream processes the SSE stream and invokes callback for each event
func (c *Client) processAgentSSEStream(reader io.Reader, callback AgentEventCallback) error {
scanner := bufio.NewScanner(reader)
// Default 64KiB per-line cap truncates large SSE data lines (the
// references event bundles chunk contents that can reach hundreds of
// KiB). Raise the cap so those lines parse instead of erroring with
// "bufio.Scanner: token too long".
scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
var dataBuffer string
for scanner.Scan() {
@@ -119,6 +125,13 @@ func (c *Client) processAgentSSEStream(reader io.Reader, callback AgentEventCall
if err := callback(&streamResponse); err != nil {
return err
}
// A terminal error frame is the stream's final outcome even if a
// buggy/proxied server leaves the HTTP connection open and never
// follows it with `complete` or EOF. Deliver it to the callback
// first, then terminate the SDK call with an error.
if streamResponse.ResponseType == AgentResponseTypeError && streamResponse.Done {
return fmt.Errorf("SSE stream error: %s", streamResponse.Content)
}
dataBuffer = ""
}
continue