import type { User } from '@supabase/auth-js' import { safeSql } from '@supabase/pg-meta' import { streamText, UIMessage } from 'ai' import { http, HttpResponse } from 'msw' import { beforeEach, expect, test, vi } from 'vitest' import { ASSISTANT_TIMEOUT_MS } from '@/lib/ai/assistant-timeout' import { getTools } from '@/lib/ai/tools' import { sanitizeMessagePart } from '@/lib/ai/tools/tool-sanitizer' import { Route } from '@/routes/api/ai/sql/generate-v4' import { mswServer } from '@/tests/lib/msw' import { callRoute } from '@/tests/lib/server-route' vi.mock('@/lib/ai/tools/tool-sanitizer', () => ({ sanitizeMessagePart: vi.fn((part) => part), })) vi.mock('@/lib/ai/ai-details', () => ({ getAIDetails: vi.fn().mockResolvedValue({ aiOptInLevel: 'schema_and_log_and_data', hasAccessToAdvanceModel: true, orgId: 1, }), })) vi.mock('@/lib/ai/model', () => ({ getModel: vi.fn().mockResolvedValue({ modelParams: { model: {} }, systemProviderOptions: {}, }), })) vi.mock('@/data/sql/execute-sql-mutation', () => ({ executeSql: vi.fn().mockResolvedValue({ result: [] }), })) vi.mock('@/lib/ai/tools', () => ({ getTools: vi.fn().mockResolvedValue({}), })) vi.mock('ai', async () => { const actual = await vi.importActual('ai') return { ...actual, // Braintrust reads this property to check whether `ai` is a language model. // Vitest throws if the mock omits it. specificationVersion: undefined, streamText: vi .fn() .mockImplementation( (options?: { onEnd?: (arg: { steps: never[]; finishReason: string }) => void }) => ({ stream: new ReadableStream({ start(controller) { controller.enqueue({ type: 'start' }) controller.close() options?.onEnd?.({ steps: [], finishReason: 'stop' }) }, }), }) ), } }) beforeEach(() => { vi.clearAllMocks() }) /** Makes the next streamText call return a stream that never ends on its own. */ function mockOpenStream() { vi.mocked(streamText).mockImplementationOnce( () => ({ stream: new ReadableStream() }) as unknown as ReturnType ) } async function readSseChunks(response: Response): Promise { const text = await response.text() const chunks: unknown[] = [] for (const line of text.split('\n')) { if (!line.startsWith('data: ')) continue const payload = line.slice('data: '.length) if (payload === '[DONE]') continue chunks.push(JSON.parse(payload)) } return chunks } function createJwt(sub: string): string { const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url') const payload = Buffer.from( JSON.stringify({ sub, aud: 'authenticated', role: 'authenticated', exp: Math.floor(Date.now() / 1000) + 3600, }) ).toString('base64url') const signature = Buffer.from('test-signature').toString('base64url') return `${header}.${payload}.${signature}` } function createRequest(authorization = 'Bearer test-token') { const clientConnection = new AbortController() const request = new Request('http://localhost/api/ai/sql/generate-v4', { method: 'POST', headers: { Authorization: authorization, 'Content-Type': 'application/json', }, body: JSON.stringify({ messages: [ { id: 'test-msg-id', role: 'assistant', parts: [ { type: 'tool-execute_sql', state: 'output-available', toolCallId: 'test-tool-call-id', input: { sql: safeSql`SELECT * FROM users` }, output: [{ id: 1, name: 'test-output' }], }, ], }, ] satisfies UIMessage[], projectRef: 'test-project', connectionString: 'test-connection', orgSlug: 'test-org', supportMode: true, }), signal: clientConnection.signal, }) return { request, disconnectClient: () => clientConnection.abort(), callGenerateV4: () => callRoute(Route, request), } } test('generateV4 calls the tool sanitizer and aborts MCP tools on client disconnect', async () => { // Keep the stream open so only the client disconnect can release the request. mockOpenStream() const { disconnectClient, callGenerateV4 } = createRequest() const response = await callGenerateV4() expect(response.status).toBe(200) expect(response.headers.get('content-encoding')).toBe('none') expect(sanitizeMessagePart).toHaveBeenCalled() expect(getTools).toHaveBeenCalledWith( expect.objectContaining({ supportMode: true, }) ) // A client disconnect must tear down the remote MCP connection opened in getTools const { signal } = vi.mocked(getTools).mock.calls[0][0] expect(signal?.aborted).toBe(false) disconnectClient() expect(signal?.aborted).toBe(true) await response.body?.cancel() }) test('generateV4 aborts MCP tools when the response stream is canceled', async () => { // Keep the stream open so only canceling the response body can release the request. mockOpenStream() const { callGenerateV4 } = createRequest() const response = await callGenerateV4() expect(response.status).toBe(200) const { signal } = vi.mocked(getTools).mock.calls[0][0] expect(signal?.aborted).toBe(false) await response.body?.cancel() await vi.waitFor(() => expect(signal?.aborted).toBe(true)) }) test('generateV4 streams a tool result that continues the previous assistant message', async () => { // After an approval, streamText runs the approved tool first and streams its result into the // assistant message the client already has, so the tool call never appears in this stream. vi.mocked(streamText).mockImplementationOnce( () => ({ stream: new ReadableStream({ start(controller) { controller.enqueue({ type: 'start' }) controller.enqueue({ type: 'tool-result', toolCallId: 'test-tool-call-id', toolName: 'render_page', input: {}, output: { status: 'ready' }, }) controller.close() }, }), }) as unknown as ReturnType ) const { callGenerateV4 } = createRequest() const response = await callGenerateV4() const chunks = await readSseChunks(response) expect(chunks).toContainEqual( expect.objectContaining({ type: 'tool-output-available', toolCallId: 'test-tool-call-id' }) ) }) test('generateV4 flags a response the deadline stopped and releases the request', async () => { vi.mocked(streamText).mockImplementationOnce( () => ({ stream: new ReadableStream({ start(controller) { controller.enqueue({ type: 'start' }) controller.enqueue({ type: 'abort', reason: 'signal timed out' }) controller.close() }, }), }) as unknown as ReturnType ) const { callGenerateV4 } = createRequest() const response = await callGenerateV4() const chunks = await readSseChunks(response) expect(chunks).toContainEqual({ type: 'message-metadata', messageMetadata: { timedOut: true } }) const params = vi.mocked(streamText).mock.calls[0][0] expect(params.timeout).toEqual({ totalMs: expect.any(Number) }) const { totalMs } = params.timeout as { totalMs: number } expect(totalMs).toBeGreaterThan(0) expect(totalMs).toBeLessThanOrEqual(ASSISTANT_TIMEOUT_MS) // Ending the stream aborts the request signal, which closes the remote MCP client. await vi.waitFor(() => expect(params.abortSignal?.aborted).toBe(true)) }) test('generateV4 sets the x-braintrust-span-id response header when tracing is enabled', async () => { const gotrueUrl = 'https://auth.example.test' const token = createJwt('user-1') mswServer.use( http.get(`${gotrueUrl}/user`, () => HttpResponse.json({ id: 'user-1', aud: 'authenticated', app_metadata: {}, user_metadata: {}, created_at: '2026-01-01T00:00:00Z', }) ) ) vi.resetModules() vi.stubEnv('NEXT_PUBLIC_IS_PLATFORM', 'true') vi.stubEnv('NEXT_PUBLIC_GOTRUE_URL', gotrueUrl) vi.stubEnv('BRAINTRUST_API_KEY', 'test-api-key') vi.stubEnv('BRAINTRUST_PROJECT_ID', '00000000-0000-4000-8000-000000000000') vi.doMock('common', async (importOriginal) => ({ ...(await importOriginal()), IS_PLATFORM: true, })) try { const braintrust = await import('braintrust') const { setInitialTestState, simulateLoginForTests, useTestBackgroundLogger } = braintrust._exportsForTestingOnly setInitialTestState() await simulateLoginForTests() const uploads = useTestBackgroundLogger() const { Route: TracedRoute } = await import('@/routes/api/ai/sql/generate-v4') // Use a named test project to avoid a network lookup. braintrust.initLogger({ projectId: process.env.BRAINTRUST_PROJECT_ID, projectName: 'test', }) const { request } = createRequest(`Bearer ${token}`) const response = await callRoute(TracedRoute, request) expect(response.status).toBe(200) const spanId = response.headers.get('x-braintrust-span-id') expect(spanId).toBeTruthy() await response.text() await braintrust.flush() expect(await uploads.drain()).toContainEqual( expect.objectContaining({ id: spanId, span_attributes: expect.objectContaining({ name: 'generateAssistantResponse' }), }) ) } finally { vi.doUnmock('common') vi.unstubAllEnvs() vi.resetModules() } })