diff --git a/packages/outpost/ai/src/generator.test.ts b/packages/outpost/ai/src/generator.test.ts index 943ab54..61c23a0 100644 --- a/packages/outpost/ai/src/generator.test.ts +++ b/packages/outpost/ai/src/generator.test.ts @@ -1,10 +1,11 @@ -import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'; +import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'; import type Anthropic from '@anthropic-ai/sdk'; import { LLMock } from '@copilotkit/aimock'; import { GROUNDING_RULES, SYSTEM_PROMPT_PREFIX, ResponseGenerator, + EmptyModelResponseError, buildChannelGuidance, extractResponseText, } from './generator.js'; @@ -564,15 +565,89 @@ describe('ResponseGenerator', () => { expect(chunks.length).toBeGreaterThanOrEqual(1); }); - it('should yield error message on stream failure', async () => { - mock.nextRequestError(500, { message: 'Stream interrupted' }); + it.each(['', ' \n '])( + 'rejects a completed stream with no usable text (%j)', + async (content) => { + mock.onMessage(/./, { + content, + usage: { input_tokens: 100, output_tokens: 2 }, + }); + + const chunks: string[] = []; + await expect( + (async () => { + for await (const chunk of generator.generateStream( + { question: 'test' }, + sampleSources, + )) { + chunks.push(chunk); + } + })(), + ).rejects.toThrow(EmptyModelResponseError); + expect(chunks.join('').trim()).toBe(''); + }, + ); + + it('rethrows provider stream failures instead of yielding them as content', async () => { + const client = ( + generator as unknown as { + client: { messages: { stream: (...args: unknown[]) => unknown } }; + } + ).client; + const stream = vi.spyOn(client.messages, 'stream').mockImplementation(() => { + throw new Error('Stream interrupted'); + }); - const chunks: string[] = []; - for await (const chunk of generator.generateStream({ question: 'test' }, [])) { - chunks.push(chunk); + try { + const chunks: string[] = []; + await expect( + (async () => { + for await (const chunk of generator.generateStream( + { question: 'test' }, + [], + )) { + chunks.push(chunk); + } + })(), + ).rejects.toThrow('Stream interrupted'); + expect(chunks.join('')).not.toContain('Error generating response'); + } finally { + stream.mockRestore(); } + }); - expect(chunks.join('')).toContain('Error generating response'); + it('rethrows a provider failure after partial text without converting it to content', async () => { + const client = ( + generator as unknown as { + client: { messages: { stream: (...args: unknown[]) => unknown } }; + } + ).client; + const stream = vi.spyOn(client.messages, 'stream').mockReturnValue( + (async function* () { + yield { + type: 'content_block_delta', + delta: { type: 'text_delta', text: 'partial draft' }, + }; + throw new Error('Stream interrupted mid-response'); + })() as never, + ); + + try { + const chunks: string[] = []; + await expect( + (async () => { + for await (const chunk of generator.generateStream( + { question: 'test' }, + [], + )) { + chunks.push(chunk); + } + })(), + ).rejects.toThrow('Stream interrupted mid-response'); + expect(chunks).toEqual(['partial draft']); + } finally { + stream.mockRestore(); + } }); }); }); diff --git a/packages/outpost/ai/src/generator.ts b/packages/outpost/ai/src/generator.ts index f1783c4..7cf6f99 100644 --- a/packages/outpost/ai/src/generator.ts +++ b/packages/outpost/ai/src/generator.ts @@ -156,6 +156,14 @@ export function extractResponseText(content: Anthropic.ContentBlock[]): string { .join('\n\n'); } +/** A completed model stream produced no publishable text. */ +export class EmptyModelResponseError extends Error { + constructor(message = 'Model response contained no usable text') { + super(message); + this.name = 'EmptyModelResponseError'; + } +} + /** * Claude response generator for the AI support pipeline. * @@ -248,6 +256,11 @@ export class ResponseGenerator { /** * Generate a response in streaming mode, yielding text chunks as they arrive. + * + * A completed stream with no usable text rejects with + * {@link EmptyModelResponseError}; provider failures reject with the original + * error. Neither case is response content: callers that buffer the stream + * must not publish an empty success or a raw provider error as the answer. */ async *generateStream( pipelineContext: PipelineContext, @@ -256,6 +269,7 @@ export class ResponseGenerator { ): AsyncIterable { const systemPrompt = this.buildSystemPrompt(sources, pipelineContext.source); const messages = this.buildMessages(pipelineContext, conversationHistory); + let hasUsableText = false; try { const stream = this.client.messages.stream({ @@ -268,11 +282,17 @@ export class ResponseGenerator { for await (const event of stream) { if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') { + hasUsableText ||= event.delta.text.trim().length > 0; yield event.delta.text; } } + + if (!hasUsableText) { + throw new EmptyModelResponseError(); + } } catch (error) { - yield `\n\n_Error generating response: ${error instanceof Error ? error.message : String(error)}_`; + console.error(`[Generator] Streaming response generation failed:`, error); + throw error; } } diff --git a/packages/outpost/ai/src/pipeline.test.ts b/packages/outpost/ai/src/pipeline.test.ts index 9f628a2..0dc4c49 100644 --- a/packages/outpost/ai/src/pipeline.test.ts +++ b/packages/outpost/ai/src/pipeline.test.ts @@ -29,6 +29,7 @@ vi.mock('./config.js', async (importOriginal) => ({ import { AI_CONFIDENCE } from '@copilotkit/outpost/shared'; import { AIPipeline, SUPPRESSED_RESPONSE_TEXT } from './pipeline.js'; +import { EmptyModelResponseError } from './generator.js'; import { assessGroundedness } from './groundedness.js'; import { describeVerdict, lintDraft } from './eval/linter.js'; import { AI_DISCLAIMER, AI_DISCLAIMER_ESCALATED, AI_DISCLAIMER_REVIEWED } from './formatter.js'; @@ -1410,6 +1411,41 @@ describe('AIPipeline', () => { expect(chunks).toEqual([SUPPRESSED_RESPONSE_TEXT]); }); + it('replaces an empty completed stream with the handoff', async () => { + mockGenerateStream.mockReturnValue( + (async function* (): AsyncIterable { + yield* streamOf(); + throw new EmptyModelResponseError(); + })(), + ); + + const chunks = await collect( + pipeline.generateStreamingResponse('q', { source: 'web' }), + ); + expect(chunks).toEqual([SUPPRESSED_RESPONSE_TEXT]); + }); + + it('propagates provider stream failures without publishing a partial draft', async () => { + mockGenerateStream.mockReturnValue( + (async function* (): AsyncIterable { + yield 'partial draft'; + throw new Error('provider stream failed'); + })(), + ); + + const chunks: string[] = []; + await expect( + (async () => { + for await (const chunk of pipeline.generateStreamingResponse('q', { + source: 'web', + })) { + chunks.push(chunk); + } + })(), + ).rejects.toThrow('provider stream failed'); + expect(chunks).toEqual([]); + }); + it('passes the retrieved sources and history through to the generator', async () => { mockGenerateStream.mockReturnValue(streamOf('ok')); const history = [{ role: 'user' as const, content: 'hi' }]; diff --git a/packages/outpost/ai/src/pipeline.ts b/packages/outpost/ai/src/pipeline.ts index 129d617..787fee6 100644 --- a/packages/outpost/ai/src/pipeline.ts +++ b/packages/outpost/ai/src/pipeline.ts @@ -20,7 +20,7 @@ import { import { supportReplyText } from './support-reply.js'; import type { SupportReply } from './support-reply.js'; import { lintDraft, describeVerdict } from './eval/linter.js'; -import { ResponseGenerator } from './generator.js'; +import { EmptyModelResponseError, ResponseGenerator } from './generator.js'; import { ConfidenceScorer } from './confidence.js'; import { TicketClassifier } from './classifier.js'; import { @@ -541,12 +541,23 @@ export class AIPipeline { // Buffer the whole draft — the gate needs the complete text. const chunks: string[] = []; - for await (const chunk of this.legacyGenerator().generateStream( - pipelineContext, - searchResults, - options.conversationHistory, - )) { - chunks.push(chunk); + try { + for await (const chunk of this.legacyGenerator().generateStream( + pipelineContext, + searchResults, + options.conversationHistory, + )) { + chunks.push(chunk); + } + } catch (error) { + if (!(error instanceof EmptyModelResponseError)) { + // Provider/transport failures keep the worker retry contract. + throw error; + } + // An empty completed stream has no draft to gate. Publish only the + // handoff rather than a successful empty response. + yield SUPPRESSED_RESPONSE_TEXT; + return; } const text = chunks.join('');