From 238297e2c592e4857e79a42b677555f6d34a2679 Mon Sep 17 00:00:00 2001 From: coconut-yc <646687501@qq.com> Date: Sun, 21 Jun 2026 02:40:25 +0800 Subject: [PATCH] fix(client): harden chat and agent SSE reliability --- cli/CHANGELOG.md | 12 + cli/cmd/session/ask_test.go | 2 +- cli/internal/mcp/tools_test.go | 4 +- cli/internal/sse/agent_accumulator.go | 10 +- cli/internal/sse/agent_accumulator_test.go | 43 ++++ client/agent.go | 15 +- client/client.go | 63 ++++- client/knowledgebase.go | 48 ++-- client/session.go | 18 +- client/streaming_test.go | 283 +++++++++++++++++++++ 10 files changed, 458 insertions(+), 40 deletions(-) create mode 100644 cli/internal/sse/agent_accumulator_test.go create mode 100644 client/streaming_test.go diff --git a/cli/CHANGELOG.md b/cli/CHANGELOG.md index 4a71f9cf..280a9287 100644 --- a/cli/CHANGELOG.md +++ b/cli/CHANGELOG.md @@ -10,6 +10,18 @@ of the WeKnora server / frontend release cadence. CLI history before v0.3 is recorded in the project root [CHANGELOG.md](../CHANGELOG.md) under the release that introduced the CLI. +## [Unreleased] + +### Fixed +- Streaming SDK calls are no longer cut off by the client's default 30-second + timeout (explicit `WithTimeout` values remain honored), and SSE data lines + up to 4 MiB are accepted. +- Terminal `response_type=error, done=true` frames now end SDK stream calls + even when the server leaves the HTTP connection open. +- Agent accumulation now waits for `response_type=complete` instead of treating + per-event `done:true` markers as completion of the whole run. +- Reference `parent_chunk_id` / `sub_chunk_id` fields now survive SDK unmarshal. + ## [0.9.0] - 2026-06-10 ### v0.9 — auth/profile model harmonization + flag cleanup diff --git a/cli/cmd/session/ask_test.go b/cli/cmd/session/ask_test.go index 160a222a..e67dc464 100644 --- a/cli/cmd/session/ask_test.go +++ b/cli/cmd/session/ask_test.go @@ -47,7 +47,7 @@ func answerEvent(content string) *sdk.AgentStreamResponse { return &sdk.AgentStreamResponse{ResponseType: sdk.AgentResponseTypeAnswer, Content: content} } func doneEvent() *sdk.AgentStreamResponse { - return &sdk.AgentStreamResponse{ResponseType: sdk.AgentResponseTypeAnswer, Done: true} + return &sdk.AgentStreamResponse{ResponseType: sdk.AgentResponseTypeComplete, Done: true} } func toolCallEvent(id, name string) *sdk.AgentStreamResponse { return &sdk.AgentStreamResponse{ diff --git a/cli/internal/mcp/tools_test.go b/cli/internal/mcp/tools_test.go index 89c94e5b..c75401f2 100644 --- a/cli/internal/mcp/tools_test.go +++ b/cli/internal/mcp/tools_test.go @@ -477,7 +477,7 @@ func TestMCP_SessionAskToolReturnsToolCalls(t *testing.T) { {ResponseType: sdk.AgentResponseTypeThinking, Content: "agent thinks"}, {ResponseType: sdk.AgentResponseTypeToolCall, ID: "tc1", Content: "knowledge_search"}, {ResponseType: sdk.AgentResponseTypeAnswer, Content: "agent answer"}, - {Done: true}, + {ResponseType: sdk.AgentResponseTypeComplete, Done: true}, }, } c, _ := newTestServer(t, svc) @@ -523,7 +523,7 @@ func TestTool_SessionAsk(t *testing.T) { agentEvents: []*sdk.AgentStreamResponse{ {ResponseType: sdk.AgentResponseTypeAnswer, Content: "result"}, {ResponseType: sdk.AgentResponseTypeToolCall, ID: "c1", Content: "knowledge_search"}, - {Done: true}, + {ResponseType: sdk.AgentResponseTypeComplete, Done: true}, }, } c, _ := newTestServer(t, svc) diff --git a/cli/internal/sse/agent_accumulator.go b/cli/internal/sse/agent_accumulator.go index dcdd22a4..961c1bd5 100644 --- a/cli/internal/sse/agent_accumulator.go +++ b/cli/internal/sse/agent_accumulator.go @@ -22,8 +22,9 @@ type AgentToolEvent struct { // AgentAccumulator buffers an AgentQAStream callback sequence. Distinct // from Accumulator (KnowledgeQAStream) because the agent event model is // wider - events include thinking / reflection / tool_call / tool_result -// / answer / references / error, with a flat `Done bool` on each frame -// rather than the ResponseType=complete sentinel KnowledgeQAStream emits. +// / answer / references / error / complete. Done is scoped to an individual +// event stream (thinking, reflection, answer, etc.); only response_type=complete +// terminates the whole agent stream. // // Zero value is ready to use. Not safe for concurrent Append calls - the // SDK callback contract is sequential on a single goroutine. @@ -80,7 +81,10 @@ func (a *AgentAccumulator) Append(r *sdk.AgentStreamResponse) { if r.KnowledgeReferences != nil { a.References = r.KnowledgeReferences } - if r.Done { + // Thinking / reflection / answer streams each emit their own Done=true + // marker before later events arrive. Only the explicit complete frame is + // terminal for the whole agent run. + if r.ResponseType == sdk.AgentResponseTypeComplete { a.done = true } } diff --git a/cli/internal/sse/agent_accumulator_test.go b/cli/internal/sse/agent_accumulator_test.go new file mode 100644 index 00000000..1dae149f --- /dev/null +++ b/cli/internal/sse/agent_accumulator_test.go @@ -0,0 +1,43 @@ +package sse_test + +import ( + "testing" + + "github.com/Tencent/WeKnora/cli/internal/sse" + sdk "github.com/Tencent/WeKnora/client" +) + +func TestAgentAccumulator_FinalizesOnlyOnComplete(t *testing.T) { + a := &sse.AgentAccumulator{} + preTerminal := []*sdk.AgentStreamResponse{ + {ResponseType: sdk.AgentResponseTypeThinking, Content: "think", Done: true}, + {ResponseType: sdk.AgentResponseTypeToolCall, ID: "call_1", Content: "search"}, + {ResponseType: sdk.AgentResponseTypeReflection, Content: "reflect", Done: true}, + {ResponseType: sdk.AgentResponseTypeAnswer, Content: "final answer", Done: true}, + } + for _, event := range preTerminal { + a.Append(event) + if a.Done() { + t.Fatalf("%s Done=true terminated the whole stream", event.ResponseType) + } + } + + a.Append(&sdk.AgentStreamResponse{ResponseType: sdk.AgentResponseTypeComplete, Done: true}) + if !a.Done() { + t.Fatal("complete event did not terminate the stream") + } + if got := a.Answer(); got != "final answer" { + t.Errorf("answer=%q, want final answer", got) + } + if got := a.Thinking(); got != "thinkreflect" { + t.Errorf("thinking=%q, want thinkreflect", got) + } + if len(a.ToolEvents) != 1 { + t.Errorf("tool_events=%d, want 1", len(a.ToolEvents)) + } + + a.Append(&sdk.AgentStreamResponse{ResponseType: sdk.AgentResponseTypeAnswer, Content: "late"}) + if got := a.Answer(); got != "final answer" { + t.Errorf("post-complete event was appended: %q", got) + } +} diff --git a/client/agent.go b/client/agent.go index 18d2530b..b3dbc449 100644 --- a/client/agent.go +++ b/client/agent.go @@ -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 diff --git a/client/client.go b/client/client.go index 120e6b5e..9e6c7e0e 100644 --- a/client/client.go +++ b/client/client.go @@ -24,20 +24,27 @@ import ( // HTTP layer. The legacy WithToken is kept as an alias for WithAPIKey for two // minor versions of compatibility. type Client struct { - baseURL string - httpClient *http.Client - apiKey string - bearerToken string - tenantID *uint64 + baseURL string + httpClient *http.Client + // streamTimeout is zero by default so long-lived SSE responses are not + // severed by the ordinary request timeout. An explicit WithTimeout option + // sets both timeouts, preserving the public option's all-request semantics. + streamTimeout time.Duration + apiKey string + bearerToken string + tenantID *uint64 } // ClientOption defines client configuration options type ClientOption func(*Client) -// WithTimeout sets the HTTP client timeout +// WithTimeout sets the timeout for ordinary and streaming HTTP requests. +// Streaming requests have no timeout by default; callers that set this option +// explicitly are asking for the same upper bound to apply to SSE streams. func WithTimeout(timeout time.Duration) ClientOption { return func(c *Client) { c.httpClient.Timeout = timeout + c.streamTimeout = timeout } } @@ -109,10 +116,12 @@ func NewClient(baseURL string, options ...ClientOption) *Client { return client } -// doRequest executes an HTTP request -func (c *Client) doRequest(ctx context.Context, +// buildRequest constructs the authenticated *http.Request shared by doRequest +// and doRequestStream: serializes the JSON body, composes URL + query, and +// applies auth headers. +func (c *Client) buildRequest(ctx context.Context, method, path string, body interface{}, query url.Values, -) (*http.Response, error) { +) (*http.Request, error) { var reqBody io.Reader if body != nil { jsonData, err := json.Marshal(body) @@ -122,22 +131,52 @@ func (c *Client) doRequest(ctx context.Context, reqBody = bytes.NewBuffer(jsonData) } - url := fmt.Sprintf("%s%s", c.baseURL, path) + u := fmt.Sprintf("%s%s", c.baseURL, path) if len(query) > 0 { - url = fmt.Sprintf("%s?%s", url, query.Encode()) + u = fmt.Sprintf("%s?%s", u, query.Encode()) } - req, err := http.NewRequestWithContext(ctx, method, url, reqBody) + req, err := http.NewRequestWithContext(ctx, method, u, reqBody) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } req.Header.Set("Content-Type", "application/json") c.applyAuthHeaders(ctx, req) + return req, nil +} +// doRequest executes an HTTP request subject to the client's blanket Timeout +// (default 30s). Use for ordinary request/response calls. +func (c *Client) doRequest(ctx context.Context, + method, path string, body interface{}, query url.Values, +) (*http.Response, error) { + req, err := c.buildRequest(ctx, method, path, body, query) + if err != nil { + return nil, err + } return c.httpClient.Do(req) } +// doRequestStream executes a streaming (SSE) request without the client's +// default 30-second blanket Timeout. http.Client.Timeout covers reading the +// response body, so applying that default would sever long-running chat / +// session-ask / continue-stream responses. Stream lifetime is governed by ctx +// unless the caller explicitly supplied WithTimeout, in which case that upper +// bound is preserved. The Transport is shared with c.httpClient so connection +// pooling is unaffected. +func (c *Client) doRequestStream(ctx context.Context, + method, path string, body interface{}, query url.Values, +) (*http.Response, error) { + req, err := c.buildRequest(ctx, method, path, body, query) + if err != nil { + return nil, err + } + sc := *c.httpClient // shallow copy: shares Transport, override Timeout + sc.Timeout = c.streamTimeout + return sc.Do(req) +} + // applyAuthHeaders sets X-API-Key, Authorization, X-Request-ID, and X-Tenant-ID // on req based on client config and ctx values. Used by doRequest and any // caller that builds its own *http.Request (currently CreateKnowledgeFromFile, diff --git a/client/knowledgebase.go b/client/knowledgebase.go index 1a10cbf9..f9415f6b 100644 --- a/client/knowledgebase.go +++ b/client/knowledgebase.go @@ -14,24 +14,24 @@ import ( // KnowledgeBase represents a knowledge base type KnowledgeBase struct { - ID string `json:"id"` - Name string `json:"name"` // Name must be unique within the same tenant - Type string `json:"type"` - IsTemporary bool `json:"is_temporary"` - IsPinned bool `json:"is_pinned"` - Description string `json:"description"` - TenantID uint64 `json:"tenant_id"` - ChunkingConfig ChunkingConfig `json:"chunking_config"` - ImageProcessingConfig ImageProcessingConfig `json:"image_processing_config"` - FAQConfig *FAQConfig `json:"faq_config"` - EmbeddingModelID string `json:"embedding_model_id"` - SummaryModelID string `json:"summary_model_id"` + ID string `json:"id"` + Name string `json:"name"` // Name must be unique within the same tenant + Type string `json:"type"` + IsTemporary bool `json:"is_temporary"` + IsPinned bool `json:"is_pinned"` + Description string `json:"description"` + TenantID uint64 `json:"tenant_id"` + ChunkingConfig ChunkingConfig `json:"chunking_config"` + ImageProcessingConfig ImageProcessingConfig `json:"image_processing_config"` + FAQConfig *FAQConfig `json:"faq_config"` + EmbeddingModelID string `json:"embedding_model_id"` + SummaryModelID string `json:"summary_model_id"` VLMConfig VLMConfig `json:"vlm_config"` StorageProviderConfig *StorageProviderConfig `json:"storage_provider_config"` StorageConfig StorageConfig `json:"storage_config"` ExtractConfig *ExtractConfig `json:"extract_config"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` // Computed fields (not stored in database) KnowledgeCount int64 `json:"knowledge_count"` ChunkCount int64 `json:"chunk_count"` @@ -116,8 +116,8 @@ type ParserEngineRule struct { // QuestionGenerationConfig controls LLM-generated questions per chunk during parsing. type QuestionGenerationConfig struct { - Enabled bool `json:"enabled"` - QuestionCount int `json:"question_count"` + Enabled bool `json:"enabled"` + QuestionCount int `json:"question_count"` } // ASRConfig represents automatic speech recognition settings for audio files. @@ -209,6 +209,16 @@ type SearchResult struct { // MatchedContent is the actual content that was matched in vector search // For FAQ: this is the matched question text (standard or similar question) MatchedContent string `json:"matched_content,omitempty"` + // KnowledgeBaseID identifies the KB that produced this hit. It is required + // for agent runs that search more than one knowledge base. + KnowledgeBaseID string `json:"knowledge_base_id,omitempty"` + // ParentChunkID / SubChunkID describe the chunk hierarchy: a retrieval + // "hit" id may be a sub-chunk, while the parent holds the self-contained + // passage an agent fetches via `chunk view `. The server + // ships these in the references event; without fields here Go silently + // drops them during unmarshal. + ParentChunkID string `json:"parent_chunk_id,omitempty"` + SubChunkID []string `json:"sub_chunk_id,omitempty"` } // HybridSearchResponse hybrid search response @@ -349,9 +359,9 @@ func (c *Client) ClearKnowledgeBaseContents(ctx context.Context, knowledgeBaseID } var response struct { - Success bool `json:"success"` - Message string `json:"message"` - Data ClearKnowledgeBaseContentsResponse `json:"data"` + Success bool `json:"success"` + Message string `json:"message"` + Data ClearKnowledgeBaseContentsResponse `json:"data"` } if err := parseResponse(resp, &response); err != nil { diff --git a/client/session.go b/client/session.go index ebc1a619..317b5b25 100644 --- a/client/session.go +++ b/client/session.go @@ -272,7 +272,7 @@ func (c *Client) KnowledgeQAStream( path := fmt.Sprintf("/api/v1/knowledge-chat/%s", sessionID) debugLogger.Debug("knowledge_qa_stream_start", "session_id", sessionID, "query", request.Query) - resp, err := c.doRequest(ctx, http.MethodPost, path, request, nil) + resp, err := c.doRequestStream(ctx, http.MethodPost, path, request, nil) if err != nil { debugLogger.Debug("request_failed", "error", err) return err @@ -290,6 +290,11 @@ func (c *Client) KnowledgeQAStream( // Use bufio to read SSE data line by line scanner := bufio.NewScanner(resp.Body) + // 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 var eventType string messageCount := 0 @@ -315,6 +320,9 @@ func (c *Client) KnowledgeQAStream( debugLogger.Debug("sse_callback_failed", "error", err) return err } + if streamResponse.ResponseType == ResponseTypeError && streamResponse.Done { + return fmt.Errorf("SSE stream error: %s", streamResponse.Content) + } dataBuffer = "" eventType = "" } @@ -354,7 +362,7 @@ func (c *Client) ContinueStream( queryParams := url.Values{} queryParams.Add("message_id", messageID) - resp, err := c.doRequest(ctx, http.MethodGet, path, nil, queryParams) + resp, err := c.doRequestStream(ctx, http.MethodGet, path, nil, queryParams) if err != nil { return err } @@ -367,6 +375,9 @@ func (c *Client) ContinueStream( // Use bufio to read SSE data line by line scanner := bufio.NewScanner(resp.Body) + // See KnowledgeQAStream: raise the per-line cap so large SSE data lines + // (references event) parse instead of erroring with "token too long". + scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024) var dataBuffer string var eventType string @@ -384,6 +395,9 @@ func (c *Client) ContinueStream( if err := callback(&streamResponse); err != nil { return err } + if streamResponse.ResponseType == ResponseTypeError && streamResponse.Done { + return fmt.Errorf("SSE stream error: %s", streamResponse.Content) + } dataBuffer = "" eventType = "" } diff --git a/client/streaming_test.go b/client/streaming_test.go new file mode 100644 index 00000000..1b1881c1 --- /dev/null +++ b/client/streaming_test.go @@ -0,0 +1,283 @@ +package client + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// agentSSEEvent serializes resp as one SSE frame — a `data:` line followed by +// the empty line that dispatches it — matching the wire shape the SDK +// streaming endpoints and processAgentSSEStream consume. +func agentSSEEvent(t *testing.T, w io.Writer, resp AgentStreamResponse) { + t.Helper() + b, err := json.Marshal(resp) + if err != nil { + t.Fatalf("marshal agent event: %v", err) + } + fmt.Fprintf(w, "data: %s\n\n", b) +} + +func knowledgeSSEEvent(t *testing.T, w io.Writer, resp StreamResponse, eventType string) { + t.Helper() + b, err := json.Marshal(resp) + if err != nil { + t.Fatalf("marshal knowledge event: %v", err) + } + if eventType != "" { + fmt.Fprintf(w, "event:%s\n", eventType) + } + fmt.Fprintf(w, "data:%s\n\n", b) +} + +// TestProcessAgentSSEStream_DataLineLimits locks in the 4 MiB bufio.Scanner +// cap raised from the 64 KiB default: a `references` event bundling chunk +// contents reaches hundreds of KiB and previously errored "token too long". +func TestProcessAgentSSEStream_DataLineLimits(t *testing.T) { + cases := []struct { + name string + content int // bytes of Content placed in the single data line + wantErr bool + }{ + {"256KiB_above_old_default_parses", 256 * 1024, false}, + {"4MiB_minus_16KiB_just_under_cap_parses", 4*1024*1024 - 16*1024, false}, + {"5MiB_over_cap_errors", 5 * 1024 * 1024, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var buf strings.Builder + agentSSEEvent(t, &buf, AgentStreamResponse{ + ResponseType: AgentResponseTypeAnswer, + Content: strings.Repeat("a", tc.content), + }) + frame := buf.String() + + c := &Client{} + var got int + err := c.processAgentSSEStream(strings.NewReader(frame), func(*AgentStreamResponse) error { + got++ + return nil + }) + switch { + case tc.wantErr && err == nil: + t.Fatal("expected token-too-long error, got nil") + case tc.wantErr && !strings.Contains(err.Error(), "token too long"): + t.Errorf("err = %q, want it to contain 'token too long'", err) + case !tc.wantErr && err != nil: + t.Fatalf("unexpected error: %v", err) + case !tc.wantErr && got != 1: + t.Errorf("callbacks=%d, want 1", got) + } + }) + } +} + +func TestKnowledgeQAStream_LargeReferenceLineParses(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + knowledgeSSEEvent(t, w, StreamResponse{ + ResponseType: ResponseTypeReferences, + KnowledgeReferences: []*SearchResult{{ + ID: "c1", + Content: strings.Repeat("a", 256*1024), + }}, + }, "") + })) + defer srv.Close() + + c := NewClient(srv.URL) + var contentLen int + err := c.KnowledgeQAStream(context.Background(), "sess", &KnowledgeQARequest{Query: "q"}, + func(e *StreamResponse) error { + contentLen = len(e.KnowledgeReferences[0].Content) + return nil + }) + if err != nil { + t.Fatalf("large knowledge stream event failed: %v", err) + } + if contentLen != 256*1024 { + t.Errorf("content bytes=%d, want %d", contentLen, 256*1024) + } +} + +func TestContinueStream_LargeReferenceLineParses(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + knowledgeSSEEvent(t, w, StreamResponse{ + ResponseType: ResponseTypeReferences, + KnowledgeReferences: []*SearchResult{{ + ID: "c1", + Content: strings.Repeat("a", 256*1024), + }}, + }, "message") + })) + defer srv.Close() + + c := NewClient(srv.URL) + var contentLen int + err := c.ContinueStream(context.Background(), "sess", "msg", func(e *StreamResponse) error { + contentLen = len(e.KnowledgeReferences[0].Content) + return nil + }) + if err != nil { + t.Fatalf("large continue-stream event failed: %v", err) + } + if contentLen != 256*1024 { + t.Errorf("content bytes=%d, want %d", contentLen, 256*1024) + } +} + +// TestAgentQAStreamWithRequest_DefaultBlanketTimeoutDoesNotCutStream is the +// regression test for doRequestStream: the client's ordinary default Timeout +// must NOT apply to SSE streams. Shrink that default to 100ms in-package so the +// test remains fast; the server completes at 300ms. +func TestAgentQAStreamWithRequest_DefaultBlanketTimeoutDoesNotCutStream(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + time.Sleep(300 * time.Millisecond) + agentSSEEvent(t, w, AgentStreamResponse{ResponseType: AgentResponseTypeComplete, Done: true}) + })) + defer srv.Close() + + c := NewClient(srv.URL) + c.httpClient.Timeout = 100 * time.Millisecond // simulate a short ordinary-request default + var gotComplete bool + err := c.AgentQAStreamWithRequest(context.Background(), "sess", + &AgentQARequest{Query: "q", AgentEnabled: true}, + func(e *AgentStreamResponse) error { + if e.ResponseType == AgentResponseTypeComplete { + gotComplete = true + } + return nil + }) + if err != nil { + t.Fatalf("stream cut by blanket timeout: %v", err) + } + if !gotComplete { + t.Error("complete event never arrived") + } +} + +// TestAgentQAStreamWithRequest_ExplicitTimeoutStillApplies preserves the +// public WithTimeout contract: callers that explicitly request an upper bound +// get it for streaming calls as well as ordinary requests. +func TestAgentQAStreamWithRequest_ExplicitTimeoutStillApplies(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + time.Sleep(300 * time.Millisecond) + agentSSEEvent(t, w, AgentStreamResponse{ResponseType: AgentResponseTypeComplete, Done: true}) + })) + defer srv.Close() + + c := NewClient(srv.URL, WithTimeout(100*time.Millisecond)) + err := c.AgentQAStreamWithRequest(context.Background(), "sess", + &AgentQARequest{Query: "q", AgentEnabled: true}, + func(*AgentStreamResponse) error { return nil }) + if err == nil { + t.Fatal("expected explicit WithTimeout to stop the stream") + } + if !errors.Is(err, context.DeadlineExceeded) && !strings.Contains(err.Error(), "Client.Timeout") { + t.Errorf("err = %v, want a client-timeout error", err) + } +} + +// TestAgentQAStreamWithRequest_TerminalErrorEndsStream verifies that a +// response_type=error, done=true frame terminates the SDK call even when the +// server leaves the HTTP connection open and never sends `complete` or EOF. +func TestAgentQAStreamWithRequest_TerminalErrorEndsStream(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + flusher, _ := w.(http.Flusher) + w.Header().Set("Content-Type", "text/event-stream") + agentSSEEvent(t, w, AgentStreamResponse{ResponseType: AgentResponseTypeError, Content: "boom", Done: true}) + if flusher != nil { + flusher.Flush() + } + <-r.Context().Done() // hold open until the client disconnects + })) + defer srv.Close() + + c := NewClient(srv.URL) + var got int + start := time.Now() + err := c.AgentQAStreamWithRequest(context.Background(), "sess", + &AgentQARequest{Query: "q", AgentEnabled: true}, + func(*AgentStreamResponse) error { + got++ + return nil + }) + elapsed := time.Since(start) + + if err == nil { + t.Fatal("expected terminal SSE error, got nil") + } + if !strings.Contains(err.Error(), "SSE stream error: boom") { + t.Errorf("err = %v, want terminal SSE error", err) + } + if elapsed > time.Second { + t.Errorf("stream hung: elapsed=%v", elapsed) + } + if got != 1 { + t.Errorf("callbacks=%d, want 1 (error event delivered before return)", got) + } +} + +func TestKnowledgeQAStream_TerminalErrorEndsStream(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + flusher, _ := w.(http.Flusher) + w.Header().Set("Content-Type", "text/event-stream") + knowledgeSSEEvent(t, w, StreamResponse{ + ResponseType: ResponseTypeError, + Content: "boom", + Done: true, + }, "") + if flusher != nil { + flusher.Flush() + } + <-r.Context().Done() + })) + defer srv.Close() + + c := NewClient(srv.URL) + var got int + start := time.Now() + err := c.KnowledgeQAStream(context.Background(), "sess", &KnowledgeQARequest{Query: "q"}, + func(*StreamResponse) error { + got++ + return nil + }) + if err == nil || !strings.Contains(err.Error(), "SSE stream error: boom") { + t.Fatalf("err = %v, want terminal SSE error", err) + } + if elapsed := time.Since(start); elapsed > time.Second { + t.Errorf("stream hung: elapsed=%v", elapsed) + } + if got != 1 { + t.Errorf("callbacks=%d, want 1", got) + } +} + +// TestSearchResult_DecodesReferenceIndexes guards the KB and chunk-hierarchy +// fields used by the CLI's bounded reference projection. +func TestSearchResult_DecodesReferenceIndexes(t *testing.T) { + raw := `{"id":"c1","knowledge_base_id":"kb1","parent_chunk_id":"p1","sub_chunk_id":["s1","s2"],"content":"x"}` + var r SearchResult + if err := json.Unmarshal([]byte(raw), &r); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if r.ParentChunkID != "p1" { + t.Errorf("ParentChunkID=%q, want p1", r.ParentChunkID) + } + if r.KnowledgeBaseID != "kb1" { + t.Errorf("KnowledgeBaseID=%q, want kb1", r.KnowledgeBaseID) + } + if len(r.SubChunkID) != 2 || r.SubChunkID[0] != "s1" || r.SubChunkID[1] != "s2" { + t.Errorf("SubChunkID=%v, want [s1 s2]", r.SubChunkID) + } +}