Files
supabase/apps/studio/lib/ai/generate-assistant-response.utils.test.ts
Charis a05e7ec1d7 refactor(studio): move self-hosted Assistant tools to contracts (#52468)
Stacked on supabase/supabase#52422.

## What

The self-hosted Assistant tools become contracts, so every tool the
Assistant can call now comes from the registry and the allowlist is
derived from it.

* The fallback tools (`getSchemaTables`, `getRlsKnowledge`,
`getFunctions`, `getEdgeFunctionKnowledge`) are deleted. Self-hosted now
gets the shared tools plus:
* `list_tables`: a local contract with the same input as the MCP tool
and a similar output, built from pg-meta. It shares its prompt guidance
with the remote contract, which moves to `list-tables.remote.ts`. On
platform the remote contract is still used.
  * `list_functions`: self-hosted only, filtered by schema in SQL.
  * `list_policies`: now available in both environments.
* `runPgMetaQuery` (`tool-sql.server.ts`) runs pg-meta-built SQL and
validates the rows with the builder's zod schema. Off platform it calls
`executeQuery` directly, because the default fetcher goes through a
relative API URL that doesn't resolve server-side.
* The allowlist comes from the registry:
* `ToolName` and the tool set validation schema are built from the
contract keys. The tool category map is removed.
* `mcp-tools.ts` keeps only tools with a remote contract, before opt-in
filtering, so `UI_EXECUTED_TOOLS` is gone. `EXPECTED_MCP_TOOLS` is
derived from the contracts and type-checked against the MCP package.
* Saved chats: the legacy contracts now trim replayed outputs.
`getRlsKnowledge` replays only the saved policy list, without the stale
RLS instructions. `getEdgeFunctionKnowledge` replays a pointer to
`load_knowledge`.
* The logs reference text no longer names `query_logs`.

## Behavior changes

* `list_policies` on platform validates rows before formatting, so a row
that fails pg-meta's schema now errors the tool call instead of
returning text.
* `list_tables` on self-hosted doesn't include the MCP tool's optional
`advisory` field.
* `list_functions` with an empty `schemas` list returns every non-system
schema.
* On platform, if the MCP tools fail to load, `list_tables` is dropped
from the tool set like the other remote tools.

## Tests

* Unit tests for `runPgMetaQuery`, the local `list_tables` and
`list_functions`, and the output mapping. The SQL boundary is mocked;
not yet run against a live self-hosted database.
* Legacy contract tests cover trimming, the empty and missing policy
cases, and that replaying an already-trimmed output leaves it unchanged.

## Checklist

Check all before review:

- [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>)
2026-10-31 07:44:36 -04:00

228 lines
7.1 KiB
TypeScript

import { convertToModelMessages, type ModelMessage, type ToolUIPart, type UIMessage } from 'ai'
import { describe, expect, it } from 'vitest'
import {
hideToolErrorsFromModel,
prepareMessagesForModel,
} from './generate-assistant-response.utils'
import { NO_DATA_ERROR } from './tools/execute-sql-output'
import { encodeNotebookToolError, NotebookToolError } from './tools/notebook-tool-error'
function assistantMessage(parts: UIMessage['parts']): UIMessage {
return { id: 'msg-1', role: 'assistant', parts }
}
function toolPart(overrides: Partial<ToolUIPart>): ToolUIPart {
return {
type: 'tool-update_notebook',
toolCallId: 'call-1',
state: 'output-available',
input: {},
...overrides,
} as ToolUIPart
}
describe('prepareMessagesForModel', () => {
it('filters out a plain output-error tool part', () => {
const messages = [
assistantMessage([toolPart({ state: 'output-error', errorText: 'Network error' })]),
]
const result = prepareMessagesForModel(messages, 'schema')
expect(result[0].parts).toEqual([])
})
it('keeps a stale-update_notebook conflict and rewrites errorText to the plain message', () => {
const error = new NotebookToolError('Notebook changed since expected_updated_at', {
exposeToAssistant: true,
})
const messages = [
assistantMessage([
toolPart({ state: 'output-error', errorText: encodeNotebookToolError(error)! }),
]),
]
const result = prepareMessagesForModel(messages, 'schema')
expect(result[0].parts).toEqual([
toolPart({ state: 'output-error', errorText: 'Notebook changed since expected_updated_at' }),
])
})
it('still filters out an unrelated update_notebook output-error', () => {
const messages = [
assistantMessage([
toolPart({ state: 'output-error', errorText: 'Unexpected upstream failure' }),
]),
]
const result = prepareMessagesForModel(messages, 'schema')
expect(result[0].parts).toEqual([])
})
it('still filters out JSON-shaped output-error text lacking the notebook_tool_error tag', () => {
const messages = [
assistantMessage([
toolPart({
state: 'output-error',
errorText: JSON.stringify({
exposeToAssistant: true,
message: 'not a real notebook error',
}),
}),
]),
]
const result = prepareMessagesForModel(messages, 'schema')
expect(result[0].parts).toEqual([])
})
it('exposes any tool part carrying a validly-tagged NotebookToolError, not just update_notebook', () => {
const error = new NotebookToolError('Notebook changed since expected_updated_at', {
exposeToAssistant: true,
})
const messages = [
assistantMessage([
toolPart({
type: 'tool-execute_sql',
state: 'output-error',
errorText: encodeNotebookToolError(error)!,
}),
]),
]
const result = prepareMessagesForModel(messages, 'schema')
expect(result[0].parts).toEqual([
toolPart({
type: 'tool-execute_sql',
state: 'output-error',
errorText: 'Notebook changed since expected_updated_at',
}),
])
})
it('still filters out input-streaming, input-available, and approval-requested parts', () => {
const messages = [
assistantMessage([
toolPart({ state: 'input-streaming' }),
toolPart({ state: 'input-available' }),
toolPart({ state: 'approval-requested', approval: { id: 'a1' } } as Partial<ToolUIPart>),
]),
]
const result = prepareMessagesForModel(messages, 'schema')
expect(result[0].parts).toEqual([])
})
it('strips update_notebook previous_content before it reaches the model on history replay', () => {
const messages = [
assistantMessage([
toolPart({
state: 'output-available',
output: {
id: 'notebook-1',
name: 'Signup funnel',
previous_content: { schema_version: 1, cells: [] },
},
}),
]),
]
const result = prepareMessagesForModel(messages, 'schema')
expect(result[0].parts).toEqual([
toolPart({
state: 'output-available',
output: { id: 'notebook-1', name: 'Signup funnel' },
}),
])
})
it('replays a self-hosted chat with legacy tool parts into model messages', async () => {
const rows = [
{ data: { definitions: [{ id: 16384, sql: 'CREATE TABLE public.todos (id bigint)' }] } },
]
const messages = [
assistantMessage([
toolPart({ type: 'tool-getSchemaTables', toolCallId: 'c1', output: rows }),
toolPart({ type: 'tool-getFunctions', toolCallId: 'c2', output: 'Function: add' }),
toolPart({ type: 'tool-getRlsKnowledge', toolCallId: 'c3', output: 42 }),
toolPart({ type: 'tool-getEdgeFunctionKnowledge', toolCallId: 'c4', output: 'Guidance' }),
]),
]
const outputs = async (level: 'disabled' | 'schema') => {
const prepared = prepareMessagesForModel(messages, level)
const modelMessages = await convertToModelMessages(prepared)
return modelMessages
.filter((message) => message.role === 'tool')
.flatMap((message) => message.content)
.flatMap((content) => (content.type === 'tool-result' ? [content.output] : []))
}
expect(await outputs('schema')).toEqual([
{ type: 'json', value: rows },
{ type: 'text', value: 'Function: add' },
{ type: 'text', value: expect.stringContaining('could not be read') },
{ type: 'text', value: expect.stringContaining('load_knowledge') },
])
const hidden = await outputs('disabled')
expect(hidden[0]).toEqual({ type: 'text', value: expect.stringContaining('`schema`') })
expect(hidden[1]).toEqual(hidden[0])
expect(hidden[3]).toEqual({ type: 'text', value: expect.stringContaining('load_knowledge') })
})
it('keeps non-tool parts untouched', () => {
const messages = [assistantMessage([{ type: 'text', text: 'hello' }])]
const result = prepareMessagesForModel(messages, 'schema')
expect(result[0].parts).toEqual([{ type: 'text', text: 'hello' }])
})
})
describe('hideToolErrorsFromModel', () => {
const toolError = (toolName: string): ModelMessage => ({
role: 'tool',
content: [
{
type: 'tool-result',
toolCallId: 'call-1',
toolName,
output: { type: 'error-text', value: 'duplicate key (email)=(a@b.c)' },
},
],
})
it('hides execute_sql errors below the data level', () => {
expect(hideToolErrorsFromModel([toolError('execute_sql')], 'schema')).toEqual([
{
role: 'tool',
content: [
{
type: 'tool-result',
toolCallId: 'call-1',
toolName: 'execute_sql',
output: { type: 'error-text', value: NO_DATA_ERROR },
},
],
},
])
})
it('keeps errors at the data level and from other tools', () => {
const messages = [toolError('execute_sql'), toolError('search_docs')]
expect(hideToolErrorsFromModel(messages, 'schema_and_log_and_data')).toEqual(messages)
expect(hideToolErrorsFromModel([toolError('search_docs')], 'schema')).toEqual([
toolError('search_docs'),
])
})
})