Files
supabase/apps/studio/lib/ai/assistant-message-metadata.test.ts
T
Saxon FletcherandClaude Opus 5.5 5e59b6047e chore(studio): extend Assistant response time and handle timeouts (#50892)
## 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>
2026-09-28 12:44:39 +10:00

112 lines
4.1 KiB
TypeScript

import type { UIMessage } from 'ai'
import { describe, expect, it } from 'vitest'
import {
assistantMessageMetadataSchema,
isTimedOutMessage,
messagesIncludeLogsSnippets,
} from '@/lib/ai/assistant-message-metadata'
function userMessage(id: string, text: string, metadata?: unknown): UIMessage {
return { id, role: 'user', parts: [{ type: 'text', text }], metadata } as UIMessage
}
function assistantMessage(id: string, text: string, metadata?: unknown): UIMessage {
return { id, role: 'assistant', parts: [{ type: 'text', text }], metadata } as UIMessage
}
describe('assistantMessageMetadataSchema', () => {
// safeValidateUIMessages applies this schema to EVERY message's metadata, so a
// message with none (i.e. every message written before this field existed) has to
// pass — otherwise an existing conversation 400s on its next turn.
it('accepts a message with no metadata', () => {
expect(assistantMessageMetadataSchema.safeParse(undefined).success).toBe(true)
})
it('accepts metadata flagging attached logs queries', () => {
const result = assistantMessageMetadataSchema.safeParse({ containsLogsSnippets: true })
expect(result.success).toBe(true)
expect(result.data?.containsLogsSnippets).toBe(true)
})
it('rejects a non-boolean flag', () => {
expect(assistantMessageMetadataSchema.safeParse({ containsLogsSnippets: 'yes' }).success).toBe(
false
)
})
})
describe('messagesIncludeLogsSnippets', () => {
it('detects a message that attached a logs query', () => {
expect(
messagesIncludeLogsSnippets([
userMessage('1', 'show me 500s', { containsLogsSnippets: true }),
])
).toBe(true)
})
it('stays true once any earlier message attached a logs query', () => {
expect(
messagesIncludeLogsSnippets([
userMessage('1', 'show me 500s', { containsLogsSnippets: true }),
assistantMessage('2', 'select ...'),
userMessage('3', 'now count my users', { containsLogsSnippets: false }),
])
).toBe(true)
})
it('is false for a conversation that only attached database queries', () => {
expect(
messagesIncludeLogsSnippets([
userMessage('1', 'count my users', { containsLogsSnippets: false }),
assistantMessage('2', 'select ...'),
])
).toBe(false)
})
it('is false when no message carries metadata', () => {
expect(messagesIncludeLogsSnippets([userMessage('1', 'hello')])).toBe(false)
expect(messagesIncludeLogsSnippets([userMessage('1', 'hello', {})])).toBe(false)
expect(messagesIncludeLogsSnippets([])).toBe(false)
})
// Only the user states which query they attached; an assistant message must not be
// able to talk the server into a different dialect.
it('ignores metadata on assistant messages', () => {
const assistantWithMetadata = {
id: '1',
role: 'assistant',
parts: [{ type: 'text', text: 'hi' }],
metadata: { containsLogsSnippets: true },
} as UIMessage
expect(messagesIncludeLogsSnippets([assistantWithMetadata])).toBe(false)
})
it('is false rather than throwing on malformed persisted metadata', () => {
expect(
messagesIncludeLogsSnippets([userMessage('1', 'hi', { containsLogsSnippets: 'yes' })])
).toBe(false)
expect(messagesIncludeLogsSnippets([userMessage('1', 'hi', 'not an object')])).toBe(false)
})
})
describe('isTimedOutMessage', () => {
it('detects an assistant response the server stopped at the deadline', () => {
expect(isTimedOutMessage(assistantMessage('1', 'partial', { timedOut: true }))).toBe(true)
})
it('is false for a completed response', () => {
expect(isTimedOutMessage(assistantMessage('1', 'done'))).toBe(false)
expect(isTimedOutMessage(assistantMessage('1', 'done', { timedOut: false }))).toBe(false)
})
it('ignores the flag on user messages', () => {
expect(isTimedOutMessage(userMessage('1', 'hi', { timedOut: true }))).toBe(false)
})
it('is false rather than throwing on a missing message or malformed metadata', () => {
expect(isTimedOutMessage(undefined)).toBe(false)
expect(isTimedOutMessage(assistantMessage('1', 'partial', { timedOut: 'yes' }))).toBe(false)
})
})