mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
## Problem Studio's AI API routes under `routes/api/ai/**` still run legacy Next Pages Router handlers through `compat/next/api.ts`. Part 2 of 7 for [FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the) migrates the active AI routes to native TanStack Start (`Request` → `Response`) handlers and drops 3 unused AI endpoints. ## Solution **Changed:** - Migrated 8 active AI routes (`ai/code/complete`, `ai/feedback/{classify,rate}`, and `ai/sql/{check-api-key,cron-v2,filter-v1,generate-v4,title-v2}`) to `createApiHandlers` and `parseJsonBody` - Replaced Node `pipeUIMessageStreamToResponse` in `ai/sql/generate-v4.ts` with native `createUIMessageStreamResponse`, preserving the `x-braintrust-span-id` header - Replaced `req.on`/`res.on` in `ai/sql/generate-v4.ts` with `AbortSignal.any([request.signal, done.signal])` and a `TransformStream` whose `flush`/`cancel` tear down the MCP connection opened in `getTools` on stream completion, cancellation, or setup error - Removed the custom malformed-JSON handling in `ai/code/complete.ts` in favor of the wrapper's `400` - Updated `lib/api/generate-v4.test.ts` to assert against the real native SSE `Response` stream instead of mocking `pipeUIMessageStreamToResponse`, with a shared `mockOpenStream()` helper, a stream-cancellation abort test, and a Braintrust tracing test asserting `x-braintrust-span-id` matches the exported root span - Updated `lib/ai/README.md` to drop references to removed endpoints **Removed:** - Removed 3 unused AI routes (`routes/api/ai/onboarding/design.ts`, `routes/api/ai/sql/parse-client-code.ts`, and `routes/api/ai/sql/policy.ts`), dropped them from `lib/hosted-api-allowlist.ts`, and regenerated `routeTree.gen.ts` - Removed the now-unused `withoutApprovalTools` helper from `lib/ai/tool-filter.ts` and its test from `lib/ai/tool-filter.test.ts` **Behavior changes vs master:** - `ai/code/complete` returns the wrapper's `400` JSON `{ error: { message: 'Invalid JSON' } }` for malformed bodies - Unused `ai/onboarding/design`, `ai/sql/parse-client-code`, and `ai/sql/policy` endpoints have been removed ## Review instructions 1. Run `pnpm --filter studio exec vitest run lib/api/generate-v4.test.ts lib/api/rate.test.ts lib/ai/tool-filter.test.ts`. 2. Send a prompt in the AI Assistant panel, verify streaming output, and cancel mid-stream. 3. Trigger SQL title, cron, and filter generation as well as AI code completion. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
297 lines
9.5 KiB
TypeScript
297 lines
9.5 KiB
TypeScript
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<typeof streamText>
|
|
)
|
|
}
|
|
|
|
async function readSseChunks(response: Response): Promise<unknown[]> {
|
|
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<typeof streamText>
|
|
)
|
|
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<typeof streamText>
|
|
)
|
|
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<User>({
|
|
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<typeof import('common')>()),
|
|
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()
|
|
}
|
|
})
|