Files
supabase/apps/studio/routes/api/ai/sql/title-v2.ts
Alaister YoungandAlaister Young c5fca0a0d7 [FE-5114] (part 2) – refactor(studio): migrate AI API routes (#54029)
## 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>
2026-12-01 21:36:38 +08:00

80 lines
2.4 KiB
TypeScript

import { createFileRoute } from '@tanstack/react-router'
import { generateText, Output } from 'ai'
import { source } from 'common-tags'
import { z } from 'zod'
import { getModel } from '@/lib/ai/model'
import { DEFAULT_COMPLETION_MODEL } from '@/lib/ai/model.utils'
import { parseJsonBody } from '@/lib/api/apiHelpers'
import { createApiHandlers, type ApiHandlerContext } from '@/lib/api/apiWrapper'
const titleSchema = z.object({
title: z
.string()
.describe(
'The generated title for the SQL snippet (short and concise). Omit these words: "SQL", "Postgres", "Query", "Database"'
),
description: z.string().describe('The generated description for the SQL snippet.'),
})
async function handlePost({ request }: ApiHandlerContext) {
const { sql } = await parseJsonBody<{ sql?: string }>(request)
if (!sql) {
return Response.json({ error: 'SQL query is required' }, { status: 400 })
}
try {
const { modelParams, error: modelError } = await getModel({
provider: 'openai',
modelEntry: DEFAULT_COMPLETION_MODEL,
})
if (modelError) {
return Response.json({ error: modelError.message }, { status: 500 })
}
const result = await generateText({
...modelParams,
output: Output.object({ schema: titleSchema }),
prompt: source`
Generate a short title and summarized description for this Postgres SQL snippet:
${sql}
The description should describe why this table was created (eg. "Table to track todos") or what the query does.
`,
})
return Response.json(result.output)
} catch (error) {
if (error instanceof Error) {
console.error(`AI title generation failed: ${error.message}`)
// Check for context length error
if (error.message.includes('context_length') || error.message.includes('too long')) {
return Response.json(
{
error:
'Your SQL query is too large for Supabase Assistant to ingest. Try splitting it into smaller queries.',
},
{ status: 400 }
)
}
} else {
console.log(`Unknown error: ${error}`)
}
return Response.json(
{ error: 'There was an unknown error generating the snippet title. Please try again.' },
{ status: 500 }
)
}
}
export const Route = createFileRoute('/api/ai/sql/title-v2')({
server: {
handlers: createApiHandlers({ POST: handlePost }, { withAuth: true }),
},
})