mirror of
https://github.com/supabase/supabase.git
synced 2026-10-05 17:35:10 +03:00
## Problem
- Assistant responses were capped at 120 seconds and 10 steps, which is
too short for longer reasoning or multi-step tool work.
- When the hosting platform ended a request at that limit, the
connection just dropped. The user got no explanation, and "Thinking…"
and tool rows kept spinning.
- Studio's own tools ignored the request's abort signal, so a stop,
disconnect or deadline couldn't cancel their in-flight requests.
- Aborted responses never closed their Braintrust span. Under TanStack
Start, the remote MCP client was only released on `res.on('close')`,
which the adapter never emits.
## Solution
Uses AI SDK options instead of custom stream handling:
- `maxDuration` goes to 300s and the step limit to 20. `streamText({
timeout: { totalMs } })` stops the response at 270s, leaving time to
finish the stream before the platform cutoff.
- `toUIMessageStream({ messageMetadata })` marks an aborted response
`timedOut: true`. `Chat` ignores `abort` chunks, so the client reads
this flag instead and shows a timeout alert with Retry. The flag is
saved with the message, so the alert survives a reload.
- `toUIMessageStream({ onEnd })` aborts the request whenever the stream
ends, releasing the MCP client on both runtimes. `streamText({ onAbort
})` ends the Braintrust span.
- Studio tools pass the SDK's `abortSignal` to their fetches. MCP tools
already did.
- Reasoning and server-tool rows that never finished show "Response
interrupted" instead of a spinner or "Ran X ✓".
There's no per-tool timeout. Approved SQL and migrations can
legitimately run longer, and aborting the HTTP request doesn't stop the
query in Postgres.
## Review instructions
1. Run the unit tests: `cd apps/studio && pnpm vitest run
lib/api/generate-v4.test.ts lib/ai components/ui/AIAssistantPanel`
2. To see a timeout without waiting 4.5 minutes, temporarily set
`ASSISTANT_TIMEOUT_MS` in `apps/studio/lib/ai/assistant-timeout.ts` to
`15_000` and run `pnpm dev:studio`.
3. Ask the Assistant something that needs several tool calls or long
reasoning, for example "Audit my schema for missing indexes and RLS
gaps, then write the fixes."
4. After 15 seconds, check that:
- the response stops and a "Assistant response timed out" alert appears
with Retry
- any in-progress reasoning or tool row shows "Response interrupted"
instead of spinning
- Retry starts a new response
- reloading the page still shows the alert on that chat
5. Stop a response with the Stop button before the deadline. It should
stop without the timeout alert.
6. With the default 270s, confirm that a normal response completes as
before.
## Checklist
Check all before review:
- [ ] 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 references
[WORD_LIST](https://github.com/supabase/supabase/blob/master/apps/docs/WORD_LIST.md)
and the docs
[CONTRIBUTING](https://github.com/supabase/supabase/blob/master/apps/docs/CONTRIBUTING.md)
guide
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Improvements**
* AI assistant responses can now run for up to five minutes, supporting
longer requests.
* When a response times out, the assistant displays a message suggesting
you retry or ask for a smaller change.
* Incomplete responses now show a “Response interrupted” notice, and
loading indicators stop when generation ends.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
183 lines
5.7 KiB
TypeScript
183 lines
5.7 KiB
TypeScript
import { safeSql } from '@supabase/pg-meta'
|
|
import { pipeUIMessageStreamToResponse, streamText, UIMessage } from 'ai'
|
|
import { expect, test, vi } from 'vitest'
|
|
|
|
import generateV4 from '../../pages/api/ai/sql/generate-v4'
|
|
import { ASSISTANT_TIMEOUT_MS } from '@/lib/ai/assistant-timeout'
|
|
import { getTools } from '@/lib/ai/tools'
|
|
import { sanitizeMessagePart } from '@/lib/ai/tools/tool-sanitizer'
|
|
|
|
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,
|
|
region: 'us-east-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,
|
|
streamText: vi.fn().mockImplementation(() => ({
|
|
stream: new ReadableStream({
|
|
start(controller) {
|
|
controller.enqueue({ type: 'start' })
|
|
controller.close()
|
|
},
|
|
}),
|
|
})),
|
|
// Consume the response, as the real Node response writer does.
|
|
pipeUIMessageStreamToResponse: vi.fn(async ({ stream }) => {
|
|
const chunks: unknown[] = []
|
|
const reader = stream.getReader()
|
|
while (true) {
|
|
const { done, value } = await reader.read()
|
|
if (done) return chunks
|
|
chunks.push(value)
|
|
}
|
|
}),
|
|
}
|
|
})
|
|
|
|
function createMocks() {
|
|
const mockReq = {
|
|
method: 'POST',
|
|
headers: {
|
|
authorization: 'Bearer test-token',
|
|
},
|
|
body: {
|
|
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,
|
|
},
|
|
on: vi.fn(),
|
|
}
|
|
|
|
const mockRes = {
|
|
status: vi.fn(() => mockRes),
|
|
json: vi.fn(() => mockRes),
|
|
setHeader: vi.fn(() => mockRes),
|
|
on: vi.fn(),
|
|
}
|
|
|
|
return { mockRes, callGenerateV4: () => generateV4(mockReq as any, mockRes as any) }
|
|
}
|
|
|
|
test('generateV4 calls the tool sanitizer', async () => {
|
|
const { mockRes, callGenerateV4 } = createMocks()
|
|
|
|
await callGenerateV4()
|
|
expect(pipeUIMessageStreamToResponse).toHaveBeenCalledOnce()
|
|
await vi.mocked(pipeUIMessageStreamToResponse).mock.results[0].value
|
|
expect(mockRes.status).not.toHaveBeenCalledWith(500)
|
|
|
|
expect(sanitizeMessagePart).toHaveBeenCalled()
|
|
expect(getTools).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
supportMode: true,
|
|
})
|
|
)
|
|
// The response 'close' event must be wired up so the remote MCP connection
|
|
// opened in getTools is torn down when the stream finishes or the client drops
|
|
expect(mockRes.on).toHaveBeenCalledWith('close', expect.any(Function))
|
|
})
|
|
|
|
test('generateV4 streams a tool result that continues the previous assistant message', async () => {
|
|
vi.mocked(streamText).mockClear()
|
|
vi.mocked(pipeUIMessageStreamToResponse).mockClear()
|
|
// 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 } = createMocks()
|
|
|
|
await callGenerateV4()
|
|
const chunks = await vi.mocked(pipeUIMessageStreamToResponse).mock.results[0].value
|
|
|
|
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).mockClear()
|
|
vi.mocked(pipeUIMessageStreamToResponse).mockClear()
|
|
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 } = createMocks()
|
|
|
|
await callGenerateV4()
|
|
const chunks = await vi.mocked(pipeUIMessageStreamToResponse).mock.results[0].value
|
|
|
|
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))
|
|
})
|