Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(studio): assistant logs context and reports guard (#48514)

Charis21511042a3d1
diff --git a/apps/studio/components/interfaces/Reports/ReportBlock/LogsSnippetReportBlock.tsx b/apps/studio/components/interfaces/Reports/ReportBlock/LogsSnippetReportBlock.tsx
new file mode 100644
index 00000000000..c6114a47613
--- /dev/null
+++ b/apps/studio/components/interfaces/Reports/ReportBlock/LogsSnippetReportBlock.tsx
@@ -0,0 +1,37 @@
+import { ScrollText } from 'lucide-react'
+import { ReactNode } from 'react'
+
+import { ReportBlockContainer } from './ReportBlockContainer'
+
+interface LogsSnippetReportBlockProps {
+ label: string
+ actions?: ReactNode
+}
+
+/**
+ * Stands in for a snippet that queries the logs backend. Reports only run SQL
+ * against the user's database, so a `log_sql` snippet reference renders this
+ * instead of executing — see ReportBlock, which never issues a query for one.
+ */
+export const LogsSnippetReportBlock = ({ label, actions }: LogsSnippetReportBlockProps) => {
+ return (
+ <ReportBlockContainer
+ draggable
+ showDragHandle
+ loading={false}
+ icon={<ScrollText size={14} className="text-foreground-muted" />}
+ label={label}
+ actions={actions}
+ >
+ <div className="flex flex-1 flex-col justify-center gap-y-1 px-5 py-4">
+ <p className="text-xs text-foreground-light">
+ Logs snippets aren't supported in reports yet
+ </p>
+ <p className="text-xs text-foreground-lighter">
+ Reports can't run queries against the logs backend yet. Open this snippet in the SQL
+ editor to view results, or remove it from this report.
+ </p>
+ </div>
+ </ReportBlockContainer>
+ )
+}
diff --git a/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlock.tsx b/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlock.tsx
index ba68a57a127..2fea6cc8265 100644
--- a/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlock.tsx
+++ b/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlock.tsx
@@ -9,6 +9,7 @@ import { applyAutoLimit } from '../../SQLEditor/SQLEditor.utils'
import { BURSTABLE_IO_METRIC_KEYS, DEPRECATED_REPORTS } from '../Reports.constants'
import { ChartBlock } from './ChartBlock'
import { DeprecatedChartBlock } from './DeprecatedChartBlock'
+import { LogsSnippetReportBlock } from './LogsSnippetReportBlock'
import { UnavailableChartBlock } from './UnavailableChartBlock'
import { hasBurstableIO } from '@/components/interfaces/DiskManagement/DiskManagement.utils'
import { ChartConfig } from '@/components/interfaces/SQLEditor/UtilityPanel/ChartConfig'
@@ -79,8 +80,11 @@ export const ReportBlock = ({
}
)
+ const isLogsSnippet = data?.type === 'log_sql'
+
const autoLimit = 100
- const sql = isSnippet ? (data?.content as SqlSnippets.Content)?.unchecked_sql : undefined
+ const sql =
+ isSnippet && !isLogsSnippet ? (data?.content as SqlSnippets.Content)?.unchecked_sql : undefined
// acceptUntrustedSql is usually not allowed outside a user-action event
// handler, but it's explicitly fine here: adding this block to a report is
// itself the user action that approves running its SQL.
@@ -125,7 +129,7 @@ export const ReportBlock = ({
sql: formattedSql,
})
},
- enabled: !isLoadingContent && contentError == null,
+ enabled: !isLoadingContent && contentError == null && !isLogsSnippet,
refetchOnWindowFocus: false,
})
@@ -151,6 +155,25 @@ export const ReportBlock = ({
}
}, [isRefreshing, refetch])
+ if (isLogsSnippet) {
+ return (
+ <LogsSnippetReportBlock
+ label={item.label}
+ actions={
+ !disableUpdate ? (
+ <ButtonTooltip
+ variant="text"
+ icon={<X />}
+ className="w-7 h-7"
+ onClick={() => onRemoveChart({ metric: { key: item.attribute } })}
+ tooltip={{ content: { side: 'bottom', text: 'Remove chart' } }}
+ />
+ ) : null
+ }
+ />
+ )
+ }
+
return (
<>
{isSnippet ? (
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
index aeefbdcfe32..d981a2da927 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
@@ -393,13 +393,26 @@ describe('SQLEditor.utils.ts:buildDebugChatArgs', () => {
test('builds the newChat payload from the snippet sql and error message', () => {
const snippet = buildDebugSnippet('select 1;')
const result = { error: { message: 'relation does not exist' } }
- expect(buildDebugChatArgs(snippet, result)).toEqual({
+ expect(buildDebugChatArgs(snippet, result, 'database')).toEqual({
name: 'Debug SQL snippet',
- sqlSnippets: ['select 1;'],
+ sqlSnippets: [{ label: 'Current Query', content: 'select 1;', source: 'database' }],
initialInput:
'Help me to debug the attached sql snippet which gives the following error: \n\nrelation does not exist',
})
})
+
+ // The attachment is what puts sqlSource on the message the user then submits, so
+ // the debug flow has to attach a sourced snippet, not a bare string.
+ test('attaches the query with its source and names the dialect', () => {
+ const snippet = buildDebugSnippet('select count(*) from logs;')
+ const result = { error: { message: 'Unknown expression identifier' } }
+ expect(buildDebugChatArgs(snippet, result, 'logs').sqlSnippets).toEqual([
+ { label: 'Current Query', content: 'select count(*) from logs;', source: 'logs' },
+ ])
+ expect(buildDebugChatArgs(snippet, result, 'logs').initialInput).toEqual(
+ 'Help me to debug the attached sql snippet which gives the following error: \n\nUnknown expression identifier\n\nThis query runs against the Supabase logs table on a ClickHouse-backed engine, not Postgres.'
+ )
+ })
})
describe('SQLEditor.utils.ts:buildCompletionRequestBody', () => {
@@ -1464,9 +1477,21 @@ describe('SQLEditor.utils:assembleCompletionDiff', () => {
describe('SQLEditor.utils:buildDebugPromptText', () => {
it('builds the debug prompt with the error message and SQL block', () => {
- const result = buildDebugPromptText('select 1;', 'relation does not exist')
+ const result = buildDebugPromptText('select 1;', 'relation does not exist', 'database')
expect(result).toContain('relation does not exist')
expect(result).toContain('```sql\nselect 1;\n```')
+ expect(result).not.toContain('ClickHouse')
+ })
+
+ // This text is copyable and gets pasted into external models, so it has to name
+ // the dialect itself rather than relying on the message metadata.
+ it('names the dialect for a logs snippet', () => {
+ const sql = "select count() from logs where source = 'edge_logs'"
+ const result = buildDebugPromptText(sql, 'Unknown expression identifier', 'logs')
+ expect(result).toContain('Unknown expression identifier')
+ expect(result).toContain('ClickHouse')
+ expect(result).toContain('not Postgres')
+ expect(result).toContain('```clickhouse\n' + sql + '\n```')
})
})
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
index 33ec043398d..188c8c0fdce 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
@@ -7,7 +7,7 @@ import {
} from '@supabase/pg-meta'
import { TABLE_EVENT_ACTIONS } from 'common/telemetry-constants'
-import type { SqlSnippetSource } from './querySource'
+import { isLogsSource, sqlSourceToFenceLanguage, type SqlSnippetSource } from './querySource'
import {
alterDatabasePreventConnectionStatements,
destructiveSqlRegex,
@@ -509,7 +509,7 @@ export type SqlDialect = 'postgres' | 'clickhouse'
* else runs against the user's Postgres database.
*/
export function sqlSourceToDialect(source: SqlSnippetSource): SqlDialect {
- return source === 'logs' ? 'clickhouse' : 'postgres'
+ return isLogsSource(source) ? 'clickhouse' : 'postgres'
}
/**
@@ -550,11 +550,31 @@ export function buildCompletionRequestBody({
}
/**
- * Builds the prompt text used to ask the assistant to debug a failing snippet.
+ * Names the dialect for a logs snippet, whose SQL is ClickHouse against the `logs`
+ * table. The in-app assistant also learns this from the message's `sqlSource`
+ * metadata, but the same text is offered as "Copy prompt" and pasted into external
+ * models, so it has to stand on its own — otherwise a logs error gets Postgres advice.
*/
-export function buildDebugPromptText(sql: string, errorMessage: string): string {
- const prompt = `Help me to debug the attached sql snippet which gives the following error: \n\n${errorMessage}`
- return `${prompt}\n\nSQL Query:\n\`\`\`sql\n${sql}\n\`\`\``
+const CLICKHOUSE_LOGS_DEBUG_HINT =
+ 'This query runs against the Supabase logs table on a ClickHouse-backed engine, not Postgres.'
+
+/** The shared ask + error + dialect preamble behind both debug entry points. */
+function buildDebugRequestText(errorMessage: string, source: SqlSnippetSource): string {
+ const ask = `Help me to debug the attached sql snippet which gives the following error: \n\n${errorMessage}`
+ return isLogsSource(source) ? `${ask}\n\n${CLICKHOUSE_LOGS_DEBUG_HINT}` : ask
+}
+
+/**
+ * Builds the prompt text used to ask the assistant to debug a failing snippet, and
+ * offered verbatim as the dropdown's copyable prompt.
+ */
+export function buildDebugPromptText(
+ sql: string,
+ errorMessage: string,
+ source: SqlSnippetSource
+): string {
+ const fence = sqlSourceToFenceLanguage(source)
+ return `${buildDebugRequestText(errorMessage, source)}\n\nSQL Query:\n\`\`\`${fence}\n${sql}\n\`\`\``
}
// Accepts either brand: the debug flow only reads the SQL as text (it's stripped
@@ -586,13 +606,18 @@ export function extractDebugContext(
*/
export function buildDebugChatArgs(
snippet: DebugSnippet,
- result: DebugResult
-): { name: string; sqlSnippets: string[]; initialInput: string } {
+ result: DebugResult,
+ source: SqlSnippetSource
+): {
+ name: string
+ sqlSnippets: Array<{ label: string; content: string; source: SqlSnippetSource }>
+ initialInput: string
+} {
const { sql, errorMessage } = extractDebugContext(snippet, result)
return {
name: 'Debug SQL snippet',
- sqlSnippets: [sql],
- initialInput: `Help me to debug the attached sql snippet which gives the following error: \n\n${errorMessage}`,
+ sqlSnippets: [{ label: 'Current Query', content: sql, source }],
+ initialInput: buildDebugRequestText(errorMessage, source),
}
}
diff --git a/apps/studio/components/interfaces/SQLEditor/querySource.test.ts b/apps/studio/components/interfaces/SQLEditor/querySource.test.ts
index 5b79d3b7768..d0e4659d0da 100644
--- a/apps/studio/components/interfaces/SQLEditor/querySource.test.ts
+++ b/apps/studio/components/interfaces/SQLEditor/querySource.test.ts
@@ -5,10 +5,13 @@ import {
datePickerValueToLogDateRange,
DEFAULT_LOG_DATE_RANGE,
getSnippetSource,
+ isLogsSource,
isoDateTimeString,
logDateRangesEqual,
logDateRangeToDatePickerValue,
resolveLogRunRange,
+ resolveSnippetSource,
+ sqlSourceToFenceLanguage,
type LogDateRange,
} from './querySource'
import {
@@ -50,6 +53,45 @@ describe('querySource.ts:getSnippetSource', () => {
})
})
+describe('querySource.ts:isLogsSource', () => {
+ it('is true only for the logs source', () => {
+ expect(isLogsSource('logs')).toBe(true)
+ expect(isLogsSource('database')).toBe(false)
+ })
+
+ it('is false for an absent source', () => {
+ expect(isLogsSource(undefined)).toBe(false)
+ })
+})
+
+describe('querySource.ts:sqlSourceToFenceLanguage', () => {
+ it('labels a logs query as clickhouse and everything else as sql', () => {
+ expect(sqlSourceToFenceLanguage('logs')).toBe('clickhouse')
+ expect(sqlSourceToFenceLanguage('database')).toBe('sql')
+ })
+
+ // Attachments can carry no source; those are Postgres SQL.
+ it('treats an absent source as sql', () => {
+ expect(sqlSourceToFenceLanguage(undefined)).toBe('sql')
+ })
+})
+
+describe('querySource.ts:resolveSnippetSource', () => {
+ it('prefers the snippet type over the URL param', () => {
+ expect(resolveSnippetSource({ type: 'log_sql' }, undefined)).toBe('logs')
+ // A stale/mismatched param must not override a snippet that already exists.
+ expect(resolveSnippetSource({ type: 'sql' }, 'logs')).toBe('database')
+ })
+
+ // A fresh `/sql/new` tab has no snippet until the first keystroke, so the param is
+ // the only signal that it is a logs tab.
+ it('falls back to the URL param before the snippet exists', () => {
+ expect(resolveSnippetSource(undefined, 'logs')).toBe('logs')
+ expect(resolveSnippetSource(undefined, undefined)).toBe('database')
+ expect(resolveSnippetSource(undefined, 'nonsense')).toBe('database')
+ })
+})
+
describe('querySource.ts:isoDateTimeString', () => {
it('accepts a valid ISO datetime', () => {
const raw = '2025-01-01T12:00:00.000Z'
diff --git a/apps/studio/components/interfaces/SQLEditor/querySource.ts b/apps/studio/components/interfaces/SQLEditor/querySource.ts
index 1ba1c4fd1ea..32e84bd78a3 100644
--- a/apps/studio/components/interfaces/SQLEditor/querySource.ts
+++ b/apps/studio/components/interfaces/SQLEditor/querySource.ts
@@ -1,7 +1,7 @@
import dayjs from 'dayjs'
-import { generateDynamicHelper } from '@/components/interfaces/Settings/Logs/Logs.datePickerHelpers'
import type { Unit } from '@/components/interfaces/Settings/Logs/Logs.datePickerHelpers'
+import { generateDynamicHelper } from '@/components/interfaces/Settings/Logs/Logs.datePickerHelpers'
import type { DatePickerValue } from '@/components/interfaces/Settings/Logs/Logs.DatePickers'
import type { ResolvedLogDateRange } from '@/components/interfaces/Settings/Logs/logsDateRange'
import type { Snippet } from '@/data/content/sql-folders-query'
@@ -25,6 +25,19 @@ export function getSnippetSource(snippet: Pick<Snippet, 'type'>): SqlSnippetSour
return snippet.type === 'log_sql' ? 'logs' : 'database'
}
+export function isLogsSource(source: SqlSnippetSource | undefined): boolean {
+ return source === 'logs'
+}
+
+/**
+ * The markdown fence language a source's SQL is written into a prompt with, so the model
+ * can tell a ClickHouse logs query from Postgres SQL. */
+export function sqlSourceToFenceLanguage(
+ source: SqlSnippetSource | undefined
+): 'sql' | 'clickhouse' {
+ return isLogsSource(source) ? 'clickhouse' : 'sql'
+}
+
/**
* Parse a raw `source` value (e.g. the `?source=` query param a creation entry
* threads through `/sql/new`) into a `SqlSnippetSource`. Only the explicit
@@ -35,6 +48,18 @@ export function parseSqlSnippetSource(raw: string | undefined): SqlSnippetSource
return raw === 'logs' ? 'logs' : 'database'
}
+/**
+ * Resolve where an open snippet's query runs, falling back to the `?source=` URL param
+ * when the snippet isn't in the store yet — a fresh `/sql/new` tab is materialized
+ * lazily on the first keystroke, and until then the param is the only signal.
+ */
+export function resolveSnippetSource(
+ snippet: Pick<Snippet, 'type'> | undefined,
+ sourceParam: string | undefined
+): SqlSnippetSource {
+ return snippet !== undefined ? getSnippetSource(snippet) : parseSqlSnippetSource(sourceParam)
+}
+
/**
* An ISO-8601 datetime proven valid at construction via a dayjs parse. Absolute
* log ranges carry these instead of raw strings so an unvalidated datetime can
diff --git a/apps/studio/components/interfaces/SQLEditor/useRunSource.ts b/apps/studio/components/interfaces/SQLEditor/useRunSource.ts
index aa7cbf05b6f..95c83d782a5 100644
--- a/apps/studio/components/interfaces/SQLEditor/useRunSource.ts
+++ b/apps/studio/components/interfaces/SQLEditor/useRunSource.ts
@@ -3,10 +3,9 @@ import { useMemo } from 'react'
import {
DEFAULT_LOG_DATE_RANGE,
- getSnippetSource,
- parseSqlSnippetSource,
+ isLogsSource,
+ resolveSnippetSource,
type QuerySource,
- type SqlSnippetSource,
} from './querySource'
import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
@@ -29,12 +28,11 @@ export function useRunSource(id: string): QuerySource {
const sessionSnap = useSqlEditorSessionSnapshot()
const snippet = snapV2.snippets[id]?.snippet
- const source: SqlSnippetSource =
- snippet !== undefined ? getSnippetSource(snippet) : parseSqlSnippetSource(sourceParam)
+ const source = resolveSnippetSource(snippet, sourceParam)
const logRange = sessionSnap.logRange[id]
return useMemo<QuerySource>(() => {
- if (source === 'logs') {
+ if (isLogsSource(source)) {
return { type: 'logs', dateRange: logRange ?? DEFAULT_LOG_DATE_RANGE }
}
return { type: 'database' }
diff --git a/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.test.tsx b/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.test.tsx
index 60f2a399f3c..b62fb4f45ec 100644
--- a/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.test.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.test.tsx
@@ -245,7 +245,11 @@ describe('useSqlEditorAi — debug', () => {
const activeChat = aiAssistantState.chats[aiAssistantState.activeChatId ?? '']
expect(activeChat?.name).toBe('Debug SQL snippet')
- expect(aiAssistantState.sqlSnippets).toEqual(['selct 1;'])
+ // Attached with its source, which is what carries sqlSource onto the message the
+ // user submits from the prefilled composer.
+ expect(aiAssistantState.sqlSnippets).toEqual([
+ { label: 'Current Query', content: 'selct 1;', source: 'database' },
+ ])
expect(aiAssistantState.initialInput).toContain('syntax error at or near "selct"')
})
diff --git a/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.ts b/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.ts
index 240d3462404..36359ffe49a 100644
--- a/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.ts
+++ b/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.ts
@@ -128,15 +128,15 @@ export function useSqlEditorAi({
const result = sessionSnap.results[id]?.[0]
const { sql, errorMessage } = extractDebugContext(snippet, result)
- return buildDebugPromptText(sql, errorMessage)
- }, [id, sessionSnap.results, snapV2.snippets])
+ return buildDebugPromptText(sql, errorMessage, sqlSource)
+ }, [id, sessionSnap.results, snapV2.snippets, sqlSource])
const onDebug = useCallback(async () => {
try {
const snippet = snapV2.snippets[id]
const result = sessionSnap.results[id]?.[0]
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
- aiSnap.newChat(buildDebugChatArgs(snippet, result))
+ aiSnap.newChat(buildDebugChatArgs(snippet, result, sqlSource))
} catch (error: unknown) {
// [Joshen] There's a tendency for the SQL debug to chuck a lengthy error message
// that's not relevant for the user - so we prettify it here by avoiding to return the
@@ -147,7 +147,7 @@ export function useSqlEditorAi({
)
}
}
- }, [id, sessionSnap.results, snapV2.snippets, aiSnap, openSidebar])
+ }, [id, sessionSnap.results, snapV2.snippets, aiSnap, openSidebar, sqlSource])
const acceptAiHandler = useCallback(async () => {
try {
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
index ca13118c5bc..02c2844a139 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
@@ -15,8 +15,8 @@ import { ButtonTooltip } from '../ButtonTooltip'
import { ErrorBoundary } from '../ErrorBoundary/ErrorBoundary'
import { InlineLinkClassName } from '../InlineLink'
import { ASSISTANT_ERRORS } from './AiAssistant.constants'
-import type { SqlSnippet } from './AIAssistant.types'
import {
+ containsLogsSnippets,
hasPendingToolApproval,
onErrorChat,
resolvePendingToolApprovalsAsDenied,
@@ -31,6 +31,7 @@ import {
} from './elements/Conversation'
import { Message } from './Message'
import { Markdown } from '@/components/interfaces/Markdown'
+import { resolveSnippetSource } from '@/components/interfaces/SQLEditor/querySource'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { useCheckOpenAIKeyQuery } from '@/data/ai/check-api-key-query'
import { useRateMessageMutation } from '@/data/ai/rate-message-mutation'
@@ -40,6 +41,7 @@ import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { useOrgAiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import type { AssistantMessageMetadata } from '@/lib/ai/assistant-message-metadata'
import { getParallelApprovalIdsToReject } from '@/lib/ai/message-utils'
import {
DEFAULT_ASSISTANT_BASE_MODEL_ID,
@@ -50,7 +52,7 @@ import {
import { IS_PLATFORM } from '@/lib/constants'
import { uuidv4 } from '@/lib/helpers'
import { useTrack } from '@/lib/telemetry/track'
-import type { AssistantModel } from '@/state/ai-assistant-state'
+import type { AssistantModel, SqlSnippet } from '@/state/ai-assistant-state'
import { useAiAssistantState, useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
@@ -64,7 +66,7 @@ interface AIAssistantProps {
export const AIAssistant = ({ className }: AIAssistantProps) => {
const router = useRouter()
- const { id: entityId } = useParams()
+ const { id: entityId, source: sourceParam } = useParams()
const { data: project } = useSelectedProjectQuery()
const searchParams = useSearchParamsShallow()
@@ -108,6 +110,10 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
const inputRef = useRef<HTMLTextAreaElement>(null)
const { aiOptInLevel, isHipaaProjectDisallowed } = useOrgAiOptInLevel()
+ // Whether attached queries are sent at all. One definition, shared by the chat form
+ // (which folds them into the message text) and the message metadata (which states
+ // whether any of them was a logs query), so the two can't disagree.
+ const includeSnippetsInMessage = aiOptInLevel !== 'disabled'
const showMetadataWarning =
IS_PLATFORM &&
!!selectedOrganization &&
@@ -136,6 +142,10 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
const snippet = snippets[entityId ?? '']
const snippetContent = snippet?.snippet?.content?.unchecked_sql
+ const openSnippetSource = isInSQLEditor
+ ? resolveSnippetSource(snippet?.snippet, sourceParam)
+ : undefined
+
const { data: tables } = useTablesQuery(
{
projectRef: project?.ref,
@@ -355,11 +365,23 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
setEditingMessageId(null)
}
+ // Read off the attachments this message actually carries, so detaching the
+ // "Current Query" chip also drops the claim. Gated on the same condition that
+ // decides whether attachments make it into the text at all: with AI opt-in
+ // disabled the chip is shown but no query is sent, and claiming otherwise would
+ // have the server prepend ClickHouse context for a message holding no query.
+ // Rides on the message rather than the request, so a Retry reproduces the context
+ // the message was asked in.
+ const metadata: AssistantMessageMetadata = {
+ containsLogsSnippets: includeSnippetsInMessage && containsLogsSnippets(snap.sqlSnippets),
+ }
+
const payload = {
role: 'user',
createdAt: new Date(),
parts: [{ type: 'text', text: finalContent }],
id: uuidv4(),
+ metadata,
} as MessageType
snap.clearSqlSnippets()
@@ -421,10 +443,12 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
useEffect(() => {
const isOpen = activeSidebar?.id === SIDEBAR_KEYS.AI_ASSISTANT
if (isOpen && isInSQLEditor && !!snippetContent) {
- snap.setSqlSnippets([{ label: 'Current Query', content: snippetContent }])
+ snap.setSqlSnippets([
+ { label: 'Current Query', content: snippetContent, source: openSnippetSource },
+ ])
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [activeSidebar?.id, isInSQLEditor, snippetContent])
+ }, [activeSidebar?.id, isInSQLEditor, snippetContent, openSnippetSource])
return (
<ErrorBoundary
@@ -673,7 +697,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
newSnippets.splice(index, 1)
snap.setSqlSnippets(newSnippets)
}}
- includeSnippetsInMessage={aiOptInLevel !== 'disabled'}
+ includeSnippetsInMessage={includeSnippetsInMessage}
selectedModel={selectedModel}
onSelectModel={(model) => snap.setModel(model)}
/>
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts
index b87d413d76a..ea3611c4133 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts
@@ -10,5 +10,3 @@ export interface AssistantSnippetProps {
yAxis?: string
name?: string
}
-
-export type SqlSnippet = string | { label: string; content: string }
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.ts
index 49648982aaa..2f28dda6bdb 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.ts
@@ -2,6 +2,8 @@ import type { UIMessage } from 'ai'
import { describe, expect, test } from 'vitest'
import {
+ containsLogsSnippets,
+ formatAttachedSnippets,
hasPendingToolApproval,
isReadOnlySelect,
resolvePendingToolApprovalsAsDenied,
@@ -157,3 +159,72 @@ describe('AIAssistant.utils.ts:resolvePendingToolApprovalsAsDenied', () => {
expect(resolvePendingToolApprovalsAsDenied(messages)).toEqual(messages)
})
})
+
+describe('containsLogsSnippets', () => {
+ test('is true when an attached query is a logs query', () => {
+ expect(
+ containsLogsSnippets([{ label: 'Current Query', content: 'select 1', source: 'logs' }])
+ ).toBe(true)
+ })
+
+ test('is false for a database query', () => {
+ expect(
+ containsLogsSnippets([{ label: 'Current Query', content: 'select 1', source: 'database' }])
+ ).toBe(false)
+ })
+
+ test('is false once nothing is attached', () => {
+ expect(containsLogsSnippets([])).toBe(false)
+ expect(containsLogsSnippets(undefined)).toBe(false)
+ })
+
+ test('ignores plain string attachments, which carry no source', () => {
+ expect(containsLogsSnippets(['select 1'])).toBe(false)
+ })
+
+ test('is true when only some of several attachments are logs queries', () => {
+ expect(
+ containsLogsSnippets([
+ 'select 1',
+ { label: 'Current Query', content: 'select 2', source: 'database' },
+ { label: 'Other', content: 'select 3', source: 'logs' },
+ ])
+ ).toBe(true)
+ })
+})
+
+describe('formatAttachedSnippets', () => {
+ test('fences a database query as sql', () => {
+ expect(
+ formatAttachedSnippets([{ label: 'Current Query', content: 'select 1', source: 'database' }])
+ ).toBe('```sql\nselect 1\n```')
+ })
+
+ // The fence is how the model tells which attachment is ClickHouse. It also keeps a
+ // logs query out of MessageMarkdown's `sql` branch, which offers to run the block
+ // against Postgres and brands it with untrustedSql.
+ test('fences a logs query as clickhouse', () => {
+ expect(
+ formatAttachedSnippets([
+ {
+ label: 'Current Query',
+ content: "select count() from logs where source = 'edge_logs'",
+ source: 'logs',
+ },
+ ])
+ ).toBe("```clickhouse\nselect count() from logs where source = 'edge_logs'\n```")
+ })
+
+ test('labels each attachment with its own dialect', () => {
+ expect(
+ formatAttachedSnippets([
+ { label: 'A', content: 'select 1', source: 'database' },
+ { label: 'B', content: 'select 2', source: 'logs' },
+ ])
+ ).toBe('```sql\nselect 1\n```\n```clickhouse\nselect 2\n```')
+ })
+
+ test('falls back to sql for a plain string attachment', () => {
+ expect(formatAttachedSnippets(['select 1'])).toBe('```sql\nselect 1\n```')
+ })
+})
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
index 801f35fb939..92d4b1d694e 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
@@ -2,6 +2,10 @@ import { isToolUIPart, type UIMessage } from 'ai'
import { toast } from 'sonner'
import { SAFE_FUNCTIONS } from './AiAssistant.constants'
+import {
+ isLogsSource,
+ sqlSourceToFenceLanguage,
+} from '@/components/interfaces/SQLEditor/querySource'
import { authKeys } from '@/data/auth/keys'
import { databaseExtensionsKeys } from '@/data/database-extensions/keys'
import { databaseIndexesKeys } from '@/data/database-indexes/keys'
@@ -12,6 +16,7 @@ import { enumeratedTypesKeys } from '@/data/enumerated-types/keys'
import { handleError } from '@/data/fetchers'
import { tableKeys } from '@/data/tables/keys'
import { tryParseJson } from '@/lib/helpers'
+import type { SqlSnippet } from '@/state/ai-assistant-state'
import { ResponseError } from '@/types'
export type MutationCategory = 'functions' | 'rls-policies'
@@ -159,3 +164,41 @@ export const onErrorChat = (error: Error) => {
}
}
}
+
+export function containsLogsSnippets(snippets: readonly SqlSnippet[] | undefined): boolean {
+ return (snippets ?? []).some(
+ (snippet) => typeof snippet !== 'string' && isLogsSource(snippet.source)
+ )
+}
+
+export const getSnippetLabel = (snippet: SqlSnippet, index: number): string =>
+ typeof snippet === 'string' ? `Snippet ${index + 1}` : snippet.label
+
+export const getSnippetContent = (snippet: SqlSnippet): string =>
+ typeof snippet === 'string' ? snippet : snippet.content
+
+/**
+ * The fence language an attached query is written into the message with. A logs query
+ * is fenced as `clickhouse` so the model can tell which attachment is ClickHouse
+ * against the `logs` table — a single message can carry both dialects.
+ *
+ * It also keeps the two apart in the rendered message: MessageMarkdown treats a `sql`
+ * fence as runnable Postgres (`DisplayBlockRenderer`, branded with `untrustedSql`),
+ * which a ClickHouse query must never be offered as.
+ */
+function getSnippetFenceLanguage(snippet: SqlSnippet): 'sql' | 'clickhouse' {
+ return sqlSourceToFenceLanguage(typeof snippet === 'string' ? undefined : snippet.source)
+}
+
+/**
+ * Renders attached queries as the fenced code blocks appended to the message text,
+ * each labelled with its own dialect.
+ */
+export function formatAttachedSnippets(snippets: readonly SqlSnippet[]): string {
+ return snippets
+ .map(
+ (snippet) =>
+ '```' + getSnippetFenceLanguage(snippet) + '\n' + getSnippetContent(snippet) + '\n```'
+ )
+ .join('\n')
+}
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx b/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx
index 928312db5d3..83df5deb1a1 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx
@@ -4,10 +4,10 @@ import { BarChart, FileText, Shield } from 'lucide-react'
import { AiIconAnimation, Button, Skeleton } from 'ui'
import { codeSnippetPrompts, defaultPrompts } from './AIAssistant.prompts'
-import type { SqlSnippet } from './AIAssistant.types'
import { LINTER_LEVELS } from '@/components/interfaces/Linter/Linter.constants'
import { createLintSummaryPrompt } from '@/components/interfaces/Linter/Linter.utils'
import { useProjectLintsQuery, type Lint } from '@/data/lint/lint-query'
+import type { SqlSnippet } from '@/state/ai-assistant-state'
interface AIOnboardingProps {
sqlSnippets?: SqlSnippet[]
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx
index 41bec723181..12913d7bdfa 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx
@@ -5,10 +5,11 @@ import { ExpandingTextArea } from 'ui'
import { cn } from 'ui/src/lib/utils'
import { ButtonTooltip } from '../ButtonTooltip'
-import { type SqlSnippet } from './AIAssistant.types'
+import { formatAttachedSnippets } from './AIAssistant.utils'
import { ModelSelector } from './ModelSelector'
-import { getSnippetContent, SnippetRow } from './SnippetRow'
+import { SnippetRow } from './SnippetRow'
import type { AssistantModelId } from '@/lib/ai/model.utils'
+import { type SqlSnippet } from '@/state/ai-assistant-state'
export interface FormProps {
/* The ref for the textarea, optional. Exposed for the CommandsPopover to attach events. */
@@ -83,10 +84,7 @@ const AssistantChatFormComponent = forwardRef<HTMLFormElement, FormProps>(
let finalMessage = value
if (includeSnippetsInMessage && sqlSnippets && sqlSnippets.length > 0) {
- const sqlSnippetsString = sqlSnippets
- .map((snippet: SqlSnippet) => '```sql\n' + getSnippetContent(snippet) + '\n```')
- .join('\n')
- finalMessage = [value, sqlSnippetsString].filter(Boolean).join('\n\n')
+ finalMessage = [value, formatAttachedSnippets(sqlSnippets)].filter(Boolean).join('\n\n')
}
onSubmit(finalMessage)
diff --git a/apps/studio/components/ui/AIAssistantPanel/SnippetRow.tsx b/apps/studio/components/ui/AIAssistantPanel/SnippetRow.tsx
index 581b7fa92b6..2f68ab7cf02 100644
--- a/apps/studio/components/ui/AIAssistantPanel/SnippetRow.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/SnippetRow.tsx
@@ -3,21 +3,8 @@ import React from 'react'
import { Button, HoverCard, HoverCardContent, HoverCardTrigger } from 'ui'
import { CodeBlock } from 'ui-patterns/CodeBlock'
-import { type SqlSnippet } from './AIAssistant.types'
-
-export const getSnippetLabel = (snippet: SqlSnippet, index: number): string => {
- if (typeof snippet === 'string') {
- return `Snippet ${index + 1}`
- }
- return snippet.label
-}
-
-export const getSnippetContent = (snippet: SqlSnippet): string => {
- if (typeof snippet === 'string') {
- return snippet
- }
- return snippet.content
-}
+import { getSnippetContent, getSnippetLabel } from './AIAssistant.utils'
+import { type SqlSnippet } from '@/state/ai-assistant-state'
interface SnippetRowProps {
snippets: SqlSnippet[]
diff --git a/apps/studio/lib/ai/assistant-context.test.ts b/apps/studio/lib/ai/assistant-context.test.ts
new file mode 100644
index 00000000000..8f641d01577
--- /dev/null
+++ b/apps/studio/lib/ai/assistant-context.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest'
+
+import { buildAssistantContextMessages, NO_SCHEMA_ACCESS_MESSAGE } from '@/lib/ai/assistant-context'
+
+const SCHEMAS = 'The available database schema names are: ["public"]'
+
+describe('buildAssistantContextMessages', () => {
+ it('describes the project when there is project context', () => {
+ const messages = buildAssistantContextMessages({
+ projectRef: 'abcdefghijklmnopqrst',
+ chatName: 'Slow queries',
+ schemasString: SCHEMAS,
+ })
+
+ expect(messages).toHaveLength(1)
+ expect(messages[0].role).toBe('assistant')
+ expect(messages[0].content).toContain('abcdefghijklmnopqrst')
+ expect(messages[0].content).toContain(SCHEMAS)
+ expect(messages[0].content).toContain('Slow queries')
+ })
+
+ it('omits the project message when there is nothing to say', () => {
+ const messages = buildAssistantContextMessages({
+ schemasString: NO_SCHEMA_ACCESS_MESSAGE,
+ })
+
+ expect(messages).toEqual([])
+ })
+
+ it('adds the support instructions in support mode', () => {
+ const messages = buildAssistantContextMessages({
+ schemasString: NO_SCHEMA_ACCESS_MESSAGE,
+ supportMode: true,
+ })
+
+ expect(messages).toHaveLength(1)
+ expect(messages[0].content).toContain('escalate_to_human')
+ })
+
+ it('adds ClickHouse instructions when the conversation attached a logs query', () => {
+ const messages = buildAssistantContextMessages({
+ projectRef: 'abcdefghijklmnopqrst',
+ schemasString: SCHEMAS,
+ includesLogsSnippets: true,
+ })
+
+ expect(messages).toHaveLength(2)
+ const logsContext = messages[1].content
+ // The dialect rules, so it doesn't answer in Postgres...
+ expect(logsContext).toContain('ClickHouse')
+ // ...and the table reference, so it doesn't invent BigQuery-style unnests.
+ expect(logsContext).toContain('log_attributes')
+ expect(logsContext).toContain("where source = 'edge_logs'")
+ })
+
+ it('adds nothing extra for a database-only conversation', () => {
+ const messages = buildAssistantContextMessages({
+ projectRef: 'abcdefghijklmnopqrst',
+ schemasString: SCHEMAS,
+ includesLogsSnippets: false,
+ })
+
+ expect(messages).toHaveLength(1)
+ expect(messages[0].content).not.toContain('ClickHouse')
+ })
+})
diff --git a/apps/studio/lib/ai/assistant-context.ts b/apps/studio/lib/ai/assistant-context.ts
new file mode 100644
index 00000000000..1c4032b77a3
--- /dev/null
+++ b/apps/studio/lib/ai/assistant-context.ts
@@ -0,0 +1,79 @@
+import {
+ buildClickhouseLogsSchemaSection,
+ CLICKHOUSE_LOGS_COMPLETION_INSTRUCTIONS,
+} from '@/lib/ai/clickhouse-logs'
+
+/**
+ * Stands in for the schema list when the org hasn't opted into sharing schemas.
+ * Doubles as a sentinel — "no project context worth sending" is decided by
+ * comparing against this exact sentence — so the producer and the comparison have
+ * to agree on it, hence one exported constant instead of copies per call site.
+ */
+export const NO_SCHEMA_ACCESS_MESSAGE = "You don't have access to any schemas."
+
+/**
+ * A request-scoped context message, sent as an assistant turn ahead of the
+ * conversation. Deliberately NOT part of the system prompt: the system prompt is
+ * static so Bedrock can cache it, and anything derived from the current project,
+ * chat, or open editor tab would break that cache.
+ */
+export type AssistantContextMessage = { role: 'assistant'; content: string }
+
+/**
+ * Tells the model that the snippet in the SQL editor targets the logs backend, so
+ * SQL it writes for that snippet comes back as ClickHouse for the `logs` table
+ * rather than Postgres. Carries the same dialect rules and table reference the
+ * inline editor completions use, so there's one description of the logs schema.
+ */
+function buildLogsSnippetContext(): string {
+ return [
+ "Some SQL snippets are marked with the dialect 'clickhouse', which means they query the Supabase logs backend, not the Postgres database. Any SQL you write, edit, or debug for that snippet must be ClickHouse SQL against the logs table described below — the database schema and the Postgres tools don't apply to it. You can help a user iterate on their ClickHouse SQL query, but you cannot run it for them (the execute_query tool does not run log queries). Postgres SQL is still the right answer for anything else the user asks about their database, or for non-ClickHouse marked queries.",
+ CLICKHOUSE_LOGS_COMPLETION_INSTRUCTIONS.trim(),
+ buildClickhouseLogsSchemaSection().trim(),
+ ].join('\n\n')
+}
+
+/**
+ * Assemble the context messages that precede the conversation: what project and
+ * chat this is, whether it's a support chat, and which backend the open SQL editor
+ * snippet targets. Pure and per-request — see {@link AssistantContextMessage} for
+ * why none of this belongs in the system prompt.
+ */
+export function buildAssistantContextMessages({
+ projectRef,
+ chatName,
+ schemasString,
+ supportMode,
+ includesLogsSnippets,
+}: {
+ projectRef?: string
+ chatName?: string
+ schemasString: string
+ supportMode?: boolean
+ /** Whether any user message in the conversation attached a logs (ClickHouse) query. */
+ includesLogsSnippets?: boolean
+}): AssistantContextMessage[] {
+ const messages: AssistantContextMessage[] = []
+
+ const hasProjectContext = !!projectRef || !!chatName || schemasString !== NO_SCHEMA_ACCESS_MESSAGE
+ if (hasProjectContext) {
+ messages.push({
+ role: 'assistant',
+ content: `The user's current project is ${projectRef || 'unknown'}. Their available schemas are: ${schemasString}. The current chat name is: ${chatName || 'unnamed'}.`,
+ })
+ }
+
+ if (supportMode) {
+ messages.push({
+ role: 'assistant',
+ content:
+ 'This is an active support chat. Help the user while they wait for a human agent. Keep guidance practical and concise. If the user asks for a human, or if the issue cannot be safely resolved, call escalate_to_human with a short reason. Only call resolve_support_conversation after the user explicitly confirms the issue is resolved; otherwise keep helping.',
+ })
+ }
+
+ if (includesLogsSnippets) {
+ messages.push({ role: 'assistant', content: buildLogsSnippetContext() })
+ }
+
+ return messages
+}
diff --git a/apps/studio/lib/ai/assistant-message-metadata.test.ts b/apps/studio/lib/ai/assistant-message-metadata.test.ts
new file mode 100644
index 00000000000..2206121e900
--- /dev/null
+++ b/apps/studio/lib/ai/assistant-message-metadata.test.ts
@@ -0,0 +1,90 @@
+import type { UIMessage } from 'ai'
+import { describe, expect, it } from 'vitest'
+
+import {
+ assistantMessageMetadataSchema,
+ 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): UIMessage {
+ return { id, role: 'assistant', parts: [{ type: 'text', text }] } 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)
+ })
+})
diff --git a/apps/studio/lib/ai/assistant-message-metadata.ts b/apps/studio/lib/ai/assistant-message-metadata.ts
new file mode 100644
index 00000000000..d30af08387e
--- /dev/null
+++ b/apps/studio/lib/ai/assistant-message-metadata.ts
@@ -0,0 +1,30 @@
+import type { UIMessage } from 'ai'
+import z from 'zod'
+
+export const assistantMessageMetadataSchema = z
+ .object({
+ /**
+ * Whether any query attached to this message is a logs (ClickHouse) query. A boolean
+ * rather than a single source, because one message can attach several queries and
+ * only some of them may target the logs backend — the per-attachment dialect is
+ * carried by each snippet's own fence in the message text.
+ */
+ containsLogsSnippets: z.boolean().optional(),
+ })
+ .optional()
+
+export type AssistantMessageMetadata = z.infer<typeof assistantMessageMetadataSchema>
+
+/**
+ * Whether any user message in the conversation attached a logs query.
+ *
+ * Parsed rather than cast — `UIMessage['metadata']` is `unknown`, and metadata can come
+ * from a chat persisted by an older build.
+ */
+export function messagesIncludeLogsSnippets(messages: UIMessage[]): boolean {
+ return messages.some((message) => {
+ if (message.role !== 'user') return false
+ const metadata = assistantMessageMetadataSchema.safeParse(message.metadata)
+ return metadata.success && metadata.data?.containsLogsSnippets === true
+ })
+}
diff --git a/apps/studio/lib/ai/generate-assistant-response.ts b/apps/studio/lib/ai/generate-assistant-response.ts
index 9679be6fb9b..f131119b549 100644
--- a/apps/studio/lib/ai/generate-assistant-response.ts
+++ b/apps/studio/lib/ai/generate-assistant-response.ts
@@ -14,6 +14,7 @@ import { source } from 'common-tags'
import type { AssistantEvalInput } from '@/evals/scorer'
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
+import { buildAssistantContextMessages, NO_SCHEMA_ACCESS_MESSAGE } from '@/lib/ai/assistant-context'
import { IS_TRACING_ENABLED } from '@/lib/ai/braintrust-logger'
import { CHAT_PROMPT, GENERAL_PROMPT, LIMITATIONS_PROMPT, SECURITY_PROMPT } from '@/lib/ai/prompts'
import { sanitizeMessagePart } from '@/lib/ai/tools/tool-sanitizer'
@@ -34,6 +35,7 @@ export async function generateAssistantResponse({
userId,
orgId,
planId,
+ includesLogsSnippets,
systemProviderOptions,
providerOptions,
requestedModel,
@@ -53,6 +55,8 @@ export async function generateAssistantResponse({
userId?: string
orgId?: number
planId?: string
+ /** Whether any user message in the conversation attached a logs (ClickHouse) query. */
+ includesLogsSnippets?: boolean
requestedModel?: string
systemProviderOptions?: Record<string, any>
providerOptions?: Record<string, any>
@@ -98,7 +102,7 @@ export async function generateAssistantResponse({
? shouldTrace
? await traced(async () => getSchemas(), { name: 'getSchemas', type: 'function' })
: await getSchemas()
- : "You don't have access to any schemas."
+ : NO_SCHEMA_ACCESS_MESSAGE
// Important: do not use dynamic content in the system prompt or Bedrock will not cache it
const system = source`
@@ -117,16 +121,6 @@ export async function generateAssistantResponse({
- \`realtime\` — Supabase Realtime
`
- const hasProjectContext =
- projectRef || chatName || schemasString !== "You don't have access to any schemas."
-
- const assistantContent = hasProjectContext
- ? `The user's current project is ${projectRef || 'unknown'}. Their available schemas are: ${schemasString}. The current chat name is: ${chatName || 'unnamed'}.`
- : undefined
- const supportAssistantContent = supportMode
- ? `This is an active support chat. Help the user while they wait for a human agent. Keep guidance practical and concise. If the user asks for a human, or if the issue cannot be safely resolved, call escalate_to_human with a short reason. Only call resolve_support_conversation after the user explicitly confirms the issue is resolved; otherwise keep helping.`
- : undefined
-
const systemMessage: SystemModelMessage = {
role: 'system',
content: system,
@@ -134,22 +128,13 @@ export async function generateAssistantResponse({
}
const coreMessages: ModelMessage[] = [
- ...(assistantContent
- ? [
- {
- role: 'assistant' as const,
- content: assistantContent,
- },
- ]
- : []),
- ...(supportAssistantContent
- ? [
- {
- role: 'assistant' as const,
- content: supportAssistantContent,
- },
- ]
- : []),
+ ...buildAssistantContextMessages({
+ projectRef,
+ chatName,
+ schemasString,
+ supportMode,
+ includesLogsSnippets,
+ }),
...(await convertToModelMessages(messages)),
]
diff --git a/apps/studio/pages/api/ai/sql/generate-v4.ts b/apps/studio/pages/api/ai/sql/generate-v4.ts
index 3bb67ff91b1..5535ce02c60 100644
--- a/apps/studio/pages/api/ai/sql/generate-v4.ts
+++ b/apps/studio/pages/api/ai/sql/generate-v4.ts
@@ -8,6 +8,11 @@ import z from 'zod'
import { executeSql } from '@/data/sql/execute-sql-mutation'
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
import { getOrgAIDetails, getProjectAIDetails } from '@/lib/ai/ai-details'
+import { NO_SCHEMA_ACCESS_MESSAGE } from '@/lib/ai/assistant-context'
+import {
+ assistantMessageMetadataSchema,
+ messagesIncludeLogsSnippets,
+} from '@/lib/ai/assistant-message-metadata'
import { isTracingAllowed } from '@/lib/ai/braintrust-logger'
import { generateAssistantResponse } from '@/lib/ai/generate-assistant-response'
import { getModel } from '@/lib/ai/model'
@@ -100,6 +105,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: Jw
const messagesValidation = await safeValidateUIMessages({
messages: rawMessages,
+ metadataSchema: assistantMessageMetadataSchema,
})
if (!messagesValidation.success) {
return res.status(400).json({
@@ -109,6 +115,8 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: Jw
}
const messages = messagesValidation.data
+ const includesLogsSnippets = messagesIncludeLogsSnippets(messages)
+
let aiOptInLevel: AiOptInLevel = 'disabled'
let hasAccessToAdvanceModel = false
let orgHasHipaaAddon: boolean | undefined
@@ -203,7 +211,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: Jw
return schemas?.length > 0
? `The available database schema names are: ${JSON.stringify(schemas)}`
- : "You don't have access to any schemas."
+ : NO_SCHEMA_ACCESS_MESSAGE
}
const result = await generateAssistantResponse({
@@ -224,6 +232,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: Jw
userId,
orgId,
planId,
+ includesLogsSnippets,
requestedModel,
systemProviderOptions,
abortSignal: abortController.signal,
diff --git a/apps/studio/state/ai-assistant-state.tsx b/apps/studio/state/ai-assistant-state.tsx
index 9e51958f1ab..5355074cf65 100644
--- a/apps/studio/state/ai-assistant-state.tsx
+++ b/apps/studio/state/ai-assistant-state.tsx
@@ -7,6 +7,7 @@ import { createContext, PropsWithChildren, useContext, useEffect, useState } fro
import { v4 as uuidv4 } from 'uuid'
import { proxy, ref, snapshot, subscribe, useSnapshot } from 'valtio'
+import type { SqlSnippetSource } from '@/components/interfaces/SQLEditor/querySource'
import type { AiSupportStatus } from '@/data/feedback/ai-chat-front-sync'
import { constructHeaders } from '@/data/fetchers'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
@@ -22,7 +23,12 @@ type SuggestionsType = {
export type AssistantMessageType = MessageType
-export type SqlSnippet = string | { label: string; content: string }
+/**
+ * A query attached to the composer (the "Current Query" chip). `source` records which
+ * backend the attached query runs against, so the dialect travels with the query it
+ * describes.
+ */
+export type SqlSnippet = string | { label: string; content: string; source?: SqlSnippetSource }
export type AssistantModel = AssistantModelId