The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): render assistant SQL with AssistantQueryCell (#49170)
Saxon Fletcherfd8ccf85b78e
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsxindex 55c13a34c31..52958c120b7 100644--- a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx@@ -81,45 +81,43 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {}return (- <Chart>- <ChartCard className="rounded-none border-0">- <ChartContent>- <div className="h-40">- {type === 'bar' && (- <ChartBar- isFullHeight- xKey={x_column}- dataKey={y_columns[0]}- dataKeys={y_columns}- config={chartConfig}- showXAxis={show_labels}- showYAxis={show_labels}- data={resultToRender}- YAxisProps={{- scale: effectiveScale === 'log' ? 'log' : 'auto',- domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,- tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,- }}- />- )}- {type === 'line' && (- <ChartLine- isFullHeight- xKey={x_column}- dataKey={y_columns[0]}- dataKeys={y_columns}- config={chartConfig}- showXAxis={show_labels}- showYAxis={show_labels}- data={resultToRender}- YAxisProps={{- scale: effectiveScale === 'log' ? 'log' : 'auto',- domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,- tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,- }}- />- )}- </div>+ <Chart className="flex h-full min-h-0 flex-col">+ <ChartCard className="flex h-full min-h-0 flex-col rounded-none border-0">+ <ChartContent className="flex h-full min-h-0 flex-1 flex-col">+ {type === 'bar' && (+ <ChartBar+ isFullHeight+ xKey={x_column}+ dataKey={y_columns[0]}+ dataKeys={y_columns}+ config={chartConfig}+ showXAxis={show_labels}+ showYAxis={show_labels}+ data={resultToRender}+ YAxisProps={{+ scale: effectiveScale === 'log' ? 'log' : 'auto',+ domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,+ tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,+ }}+ />+ )}+ {type === 'line' && (+ <ChartLine+ isFullHeight+ xKey={x_column}+ dataKey={y_columns[0]}+ dataKeys={y_columns}+ config={chartConfig}+ showXAxis={show_labels}+ showYAxis={show_labels}+ data={resultToRender}+ YAxisProps={{+ scale: effectiveScale === 'log' ? 'log' : 'auto',+ domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,+ tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,+ }}+ />+ )}</ChartContent></ChartCard></Chart>diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.tsindex a3cb9b63a3f..fad2f53f0d2 100644--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts@@ -184,7 +184,7 @@ export const getSnippetContent = (snippet: SqlSnippet): string =>* 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`),+ * fence as runnable Postgres (`AssistantQueryCell`, branded with `untrustedSql`),* which a ClickHouse query must never be offered as.*/function getSnippetFenceLanguage(snippet: SqlSnippet): 'sql' | 'clickhouse' {diff --git a/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsx b/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsxdeleted file mode 100644index bd2eb162070..00000000000--- a/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsx+++ /dev/null@@ -1,265 +0,0 @@-import { acceptUntrustedSql, type UntrustedSqlFragment } from '@supabase/pg-meta'-import { PermissionAction } from '@supabase/shared-types/out/constants'-import { useQueryClient } from '@tanstack/react-query'-import type { ToolUIPart } from 'ai'-import { useParams } from 'common'-import { useRouter } from 'next/router'-import { useRef, useState, type DragEvent, type PropsWithChildren } from 'react'--import { DEFAULT_CHART_CONFIG, QueryBlock } from '../QueryBlock/QueryBlock'-import { identifyQueryType } from './AIAssistant.utils'-import { ConfirmFooter } from './Confirm'-import { ChartConfig } from '@/components/interfaces/SQLEditor/UtilityPanel/ChartConfig'-import { entityTypeKeys } from '@/data/entity-types/keys'-import { lintKeys } from '@/data/lint/keys'-import { usePrimaryDatabase } from '@/data/read-replicas/replicas-query'-import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'-import { useChangedSync } from '@/hooks/misc/useChanged'-import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'-import { useProfile } from '@/lib/profile'-import { useTrack } from '@/lib/telemetry/track'--interface DisplayBlockRendererProps {- messageId: string- toolCallId: string- initialArgs: {- sql: UntrustedSqlFragment- label?: string- isWriteQuery?: boolean- view?: 'table' | 'chart'- xAxis?: string- yAxis?: string- }- initialResults?: unknown- /** Called when locally running SQL fails before or during client-side execution. */- onError?: (args: { messageId: string; errorText: string }) => void- /** Responds affirmatively to an AI SDK tool approval request; does not run SQL directly. */- onApprove?: () => void- /** Responds negatively to an AI SDK tool approval request; does not run SQL directly. */- onDeny?: () => void- /** AI SDK tool state used to show approval UI for pending tool calls. */- toolState?: ToolUIPart['state']- toolApprovalRespondedApproved?: boolean- isLastPart?: boolean- isLastMessage?: boolean- showConfirmFooter?: boolean- onChartConfigChange?: (chartConfig: ChartConfig) => void- /** Called when the user clicks the query block play button to run SQL locally. */- onQueryRun?: (queryType: 'select' | 'mutation') => void-}--export const DisplayBlockRenderer = ({- messageId,- toolCallId,- initialArgs,- initialResults,- onError,- onApprove,- onDeny,- toolState,- toolApprovalRespondedApproved,- isLastPart = false,- isLastMessage = false,- showConfirmFooter = true,- onChartConfigChange,- onQueryRun,-}: PropsWithChildren<DisplayBlockRendererProps>) => {- const queryClient = useQueryClient()-- const savedInitialArgs = useRef(initialArgs)- const savedInitialResults = useRef(initialResults)- const savedInitialConfig = useRef<ChartConfig>({- ...DEFAULT_CHART_CONFIG,- view: initialArgs.view === 'chart' ? 'chart' : 'table',- xKey: initialArgs.xAxis ?? '',- yKey: initialArgs.yAxis ?? '',- })-- const router = useRouter()- const { ref } = useParams()- const { profile } = useProfile()-- const track = useTrack()- const { can: canCreateSQLSnippet } = useAsyncCheckPermissions(- PermissionAction.CREATE,- 'user_content',- {- resource: { type: 'sql', owner_id: profile?.id },- subject: { id: profile?.id },- }- )-- const [chartConfig, setChartConfig] = useState<ChartConfig>(() => ({- ...DEFAULT_CHART_CONFIG,- view: initialArgs.view === 'chart' ? 'chart' : 'table',- xKey: initialArgs.xAxis ?? '',- yKey: initialArgs.yAxis ?? '',- }))-- const [rows, setRows] = useState<any[] | undefined>(- Array.isArray(initialResults) ? initialResults : undefined- )- const isReportsPage = router.pathname.endsWith('/reports/[id]')- const isHomePage = router.pathname === '/project/[ref]'- const isDraggableToReports = canCreateSQLSnippet && (isReportsPage || isHomePage)- const label = initialArgs.label || 'SQL Results'- const [isWriteQuery, setIsWriteQuery] = useState<boolean>(initialArgs.isWriteQuery || false)- const sqlQuery = initialArgs.sql-- const { database: primaryDatabase } = usePrimaryDatabase({ projectRef: ref })-- const readOnlyConnectionString = primaryDatabase?.connection_string_read_only- const postgresConnectionString = primaryDatabase?.connectionString-- const {- mutate: executeSql,- error: executeSqlError,- isPending: executeSqlLoading,- } = useExecuteSqlMutation({- onError: () => {- // Suppress toast because error message is displayed inline- },- })-- const toolCallIdChanged = useChangedSync(toolCallId)- if (toolCallIdChanged) {- setChartConfig(savedInitialConfig.current)- onChartConfigChange?.(savedInitialConfig.current)- setIsWriteQuery(savedInitialArgs.current.isWriteQuery || false)- setRows(Array.isArray(savedInitialResults.current) ? savedInitialResults.current : undefined)- }-- const initialResultsChanged = useChangedSync(initialResults)- if (initialResultsChanged) {- const normalized = Array.isArray(initialResults) ? initialResults : undefined- if (!normalized || normalized === rows) return- setRows(normalized)- }-- const handleRunQuery = (queryType: 'select' | 'mutation') => {- if (!sqlQuery) return-- onQueryRun?.(queryType)-- track('assistant_suggestion_run_query_clicked', {- queryType,- ...(queryType === 'mutation'- ? { mutationType: identifyQueryType(sqlQuery) ?? 'unknown' }- : {}),- })- }-- const runQuery = (queryType: 'select' | 'mutation') => {- if (!ref || !sqlQuery) return-- const connectionString =- queryType === 'mutation'- ? postgresConnectionString- : (readOnlyConnectionString ?? postgresConnectionString)-- if (!connectionString) {- const fallbackMessage = 'Unable to find a database connection to execute this query.'- onError?.({ messageId, errorText: fallbackMessage })- return- }-- if (queryType === 'mutation') {- setIsWriteQuery(true)- }- executeSql(- { projectRef: ref, connectionString, sql: acceptUntrustedSql(sqlQuery) },- {- onSuccess: (data) => {- setRows(Array.isArray(data.result) ? data.result : undefined)- setIsWriteQuery(queryType === 'mutation' || initialArgs.isWriteQuery || false)- if (queryType === 'mutation') {- queryClient.invalidateQueries({ queryKey: lintKeys.lint(ref) })- queryClient.invalidateQueries({ queryKey: entityTypeKeys.list(ref) })- }- },- onError: (error) => {- const lowerMessage = error.message.toLowerCase()- const isReadOnlyError =- lowerMessage.includes('read-only transaction') ||- lowerMessage.includes('permission denied') ||- lowerMessage.includes('must be owner')-- if (queryType === 'select' && isReadOnlyError) {- setIsWriteQuery(true)- }-- onError?.({ messageId, errorText: error.message })- },- }- )- }-- const handleExecute = (queryType: 'select' | 'mutation') => {- handleRunQuery(queryType)- runQuery(queryType)- }-- const handleUpdateChartConfig = ({- chartConfig: updatedValues,- }: {- chartConfig: Partial<ChartConfig>- }) => {- setChartConfig((prev) => {- const next = { ...prev, ...updatedValues }- onChartConfigChange?.(next)- return next- })- }-- const handleDragStart = (e: DragEvent<Element>) => {- e.dataTransfer.setData(- 'application/json',- JSON.stringify({ label, sql: sqlQuery, config: chartConfig })- )- }-- const isApprovalRequested = toolState === 'approval-requested'- const isApprovalResponded = toolState === 'approval-responded'- const isApprovalDenied = isApprovalResponded && toolApprovalRespondedApproved === false- const shouldShowConfirmFooter =- showConfirmFooter &&- (isApprovalRequested || (isApprovalResponded && !isApprovalDenied)) &&- isLastPart &&- isLastMessage &&- (isApprovalResponded || (!!onApprove && !!onDeny))- const isRunningApprovedTool = (isApprovalResponded && !isApprovalDenied) || executeSqlLoading-- return (- <div className="display-block w-auto overflow-x-hidden">- <div className="relative z-10">- <QueryBlock- label={label}- isWriteQuery={isWriteQuery}- sql={sqlQuery}- results={rows}- errorText={executeSqlError?.message}- chartConfig={chartConfig}- onExecute={handleExecute}- onUpdateChartConfig={handleUpdateChartConfig}- draggable={isDraggableToReports}- onDragStart={handleDragStart}- disabled={shouldShowConfirmFooter}- isExecuting={isRunningApprovedTool}- />- </div>- {shouldShowConfirmFooter && (- <div className="mx-4">- <ConfirmFooter- message="Assistant wants to run this query"- cancelLabel="Skip"- confirmLabel="Run Query"- confirmLabelLoading="Running..."- isLoading={isApprovalResponded || executeSqlLoading}- onCancel={isApprovalRequested ? onDeny : undefined}- onConfirm={isApprovalRequested ? onApprove : undefined}- />- </div>- )}- </div>- )-}diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.Display.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.Display.tsxindex eb8451215ed..a6cd55409fa 100644--- a/apps/studio/components/ui/AIAssistantPanel/Message.Display.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/Message.Display.tsx@@ -53,8 +53,7 @@ function MessageDisplayContent({ message }: { message: VercelMessage }) {<div className="flex-1 min-w-0">{messageParts?.length > 0? messageParts.map((part: NonNullable<VercelMessage['parts'][number]>, idx) => {- const isLastPart = idx === messageParts.length - 1- return <MessagePartSwitcher key={idx} part={part} isLastPart={isLastPart} />+ return <MessagePartSwitcher key={idx} part={part} />}): content && (<MessageDisplayTextMessage id={id} isLoading={isLoading} readOnly={readOnly}>diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsxindex d53bb3e099d..62cd84b4ba2 100644--- a/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/Message.Parts.tsx@@ -3,8 +3,8 @@ import { type DynamicToolUIPart, type ReasoningUIPart, type TextUIPart, type Tooimport { BrainIcon, CheckIcon, Loader2 } from 'lucide-react'import { cn } from 'ui'-import { getManualToolApprovalHandlers, USER_SKIPPED_TOOL_REASON } from './Confirm.utils'-import { DisplayBlockRenderer } from './DisplayBlockRenderer'+import { AssistantQueryCell } from './AssistantQueryCell'+import { getManualToolApprovalHandlers } from './Confirm.utils'import { EdgeFunctionRenderer } from './EdgeFunctionRenderer'import { Tool } from './elements/Tool'import { useMessageActionsContext, useMessageInfoContext } from './Message.Context'@@ -111,14 +111,8 @@ function ToolDisplayExecuteSqlFailure() {return <div className="text-xs text-danger">Failed to execute SQL.</div>}-function MessagePartExecuteSql({- toolPart,- isLastPart,-}: {- toolPart: ToolUIPart- isLastPart?: boolean-}) {- const { id, isLastMessage } = useMessageInfoContext()+function MessagePartExecuteSql({ toolPart }: { toolPart: ToolUIPart }) {+ const { id } = useMessageInfoContext()const { addToolApprovalResponse } = useMessageActionsContext()const { toolCallId, state, input, output } = toolPart@@ -141,40 +135,25 @@ function MessagePartExecuteSql({state === 'output-denied' ||state === 'output-available') {- const approvalId = state === 'approval-requested' ? toolPart.approval?.id : undefined+ const { confirmState, onApprove, onDeny } = getManualToolApprovalHandlers({+ state,+ approval: toolPart.approval,+ addToolApprovalResponse,+ })+return (<div className="w-auto overflow-x-hidden my-4 space-y-2">- <DisplayBlockRenderer- messageId={id}- toolCallId={toolCallId}- initialArgs={{- sql: chart.sql,- label: chart.label,- isWriteQuery: chart.isWriteQuery,- view: chart.view,- xAxis: chart.xAxis,- yAxis: chart.yAxis,- }}- initialResults={output}- toolState={state}- toolApprovalRespondedApproved={toolPart.approval?.approved}- isLastPart={isLastPart}- isLastMessage={isLastMessage}- onApprove={- approvalId- ? () => addToolApprovalResponse?.({ id: approvalId, approved: true })- : undefined- }- onDeny={- approvalId- ? () =>- addToolApprovalResponse?.({- id: approvalId,- approved: false,- reason: USER_SKIPPED_TOOL_REASON,- })- : undefined- }+ <AssistantQueryCell+ id={`${id}-${toolCallId}`}+ sql={chart.sql}+ title={chart.label}+ initialRows={output}+ view={chart.view}+ xAxis={chart.xAxis}+ yAxis={chart.yAxis}+ confirmState={confirmState}+ onApprove={onApprove}+ onDeny={onDeny}/></div>)@@ -302,10 +281,8 @@ const MessagePart = {export function MessagePartSwitcher({part,- isLastPart,}: {part: NonNullable<VercelMessage['parts']>[number]- isLastPart?: boolean}) {switch (part.type) {case 'dynamic-tool': {@@ -323,7 +300,7 @@ export function MessagePartSwitcher({return <MessagePart.Text textPart={part} />case 'tool-execute_sql': {- return <MessagePart.ExecuteSql toolPart={part} isLastPart={isLastPart} />+ return <MessagePart.ExecuteSql toolPart={part} />}case 'tool-deploy_edge_function': {return <MessagePart.DeployEdgeFunction toolPart={part} />diff --git a/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx b/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsxindex 7a6ff7ff488..745fe9fdfc9 100644--- a/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx@@ -1,15 +1,6 @@-import { untrustedSql } from '@supabase/pg-meta'import dynamic from 'next/dynamic'import Link from 'next/link'-import React, {- isValidElement,- memo,- ReactNode,- useEffect,- useMemo,- useRef,- type ReactElement,-} from 'react'+import React, { isValidElement, memo, ReactNode, useMemo, type ReactElement } from 'react'import type { StreamdownProps } from 'streamdown'import {Button,@@ -28,10 +19,9 @@ import { markdownComponents } from 'ui-patterns/Markdown'import { EdgeFunctionBlock } from '../EdgeFunctionBlock/EdgeFunctionBlock'import { AssistantSnippetProps } from './AIAssistant.types'+import { AssistantQueryCell } from './AssistantQueryCell'import { CollapsibleCodeBlock } from './CollapsibleCodeBlock'-import { DisplayBlockRenderer } from './DisplayBlockRenderer'import { defaultUrlTransform, wrapPlaceholderUrls } from './Message.utils'-import { ChartConfig } from '@/components/interfaces/SQLEditor/UtilityPanel/ChartConfig'const Streamdown = dynamic<StreamdownProps>(() => import('streamdown').then((mod) => mod.Streamdown),@@ -188,7 +178,7 @@ export function MessageMarkdown({export const MarkdownPre = ({children,id,- isLoading: _isLoading,+ isLoading,readOnly,}: {children: any@@ -196,15 +186,6 @@ export const MarkdownPre = ({isLoading: booleanreadOnly?: boolean}) => {- // [Joshen] Using a ref as this data doesn't need to trigger a re-render- const chartConfig = useRef<ChartConfig>({- view: 'table',- type: 'bar',- xKey: '',- yKey: '',- cumulative: false,- })-const childArray = Array.isArray(children) ? children : [children]const codeElement = childArray.find((child): child is ReactElement<{ className?: string; children: ReactNode }> =>@@ -231,23 +212,13 @@ export const MarkdownPre = ({const { xAxis, yAxis } = snippetPropsconst snippetId = snippetProps.id- const title = snippetProps.title || (language === 'edge' ? 'Edge Function' : 'SQL Query')+ const title = snippetProps.title || (language === 'edge' ? 'Edge Function' : 'SQL query')const isChart = snippetProps.isChart === 'true'// Strip props from the content for both SQL and edge functionsconst cleanContent = rawContent.replace(/(?:--|\/\/)\s*props:\s*\{[^}]+\}/, '').trim()const toolCallId = String(snippetId ?? id)- useEffect(() => {- chartConfig.current = {- ...chartConfig.current,- view: isChart ? 'chart' : 'table',- xKey: xAxis ?? '',- yKey: yAxis ?? '',- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [snippetProps])-if (!codeElement) {return <pre className="w-auto overflow-x-auto not-prose my-4">{children}</pre>}@@ -265,22 +236,14 @@ export const MarkdownPre = ({readOnly ? (<CollapsibleCodeBlock value={cleanContent} language="sql" hideLineNumbers />) : (- <DisplayBlockRenderer- messageId={id}- toolCallId={toolCallId}- initialArgs={{- sql: untrustedSql(cleanContent),- label: title,- isWriteQuery: false,- view: isChart ? 'chart' : 'table',- xAxis: xAxis ?? '',- yAxis: yAxis ?? '',- }}- onError={() => {}}- showConfirmFooter={false}- onChartConfigChange={(config) => {- chartConfig.current = { ...config }- }}+ <AssistantQueryCell+ id={toolCallId}+ sql={cleanContent}+ title={title}+ view={isChart ? 'chart' : 'table'}+ xAxis={xAxis}+ yAxis={yAxis}+ isStreaming={isLoading}/>)) : (