Skip to content

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

feat(studio): add AssistantQueryCell on the shared QueryEditor (#49169)

Saxon Fletcher6e64ad039c86
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
index 150df0f12d3..50985ecf9e9 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
@@ -80,6 +80,9 @@ export type QueryEditorProps = {
roleImpersonationState?: RoleImpersonationController
display?: QueryDisplay
toolbarActions?: ReactNode
+ className?: string
+ /** When true, toolbar and editor run actions are disabled. */
+ isRunDisabled?: boolean
onTitleChange: (title: string) => void
onSqlChange: (sql: string) => void
onSqlCommit?: (sql: string) => void
@@ -87,6 +90,7 @@ export type QueryEditorProps = {
onResultChange: (result: QueryResult) => void
onRowLimitChange?: (val: number) => void
onDisplayChange?: (display: QueryDisplay) => void
+ onRun?: () => void
}
export type QueryEditorHandle = {
@@ -108,6 +112,8 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
roleImpersonationState,
display,
toolbarActions,
+ className,
+ isRunDisabled = false,
onTitleChange,
onSqlChange,
onSqlCommit,
@@ -115,6 +121,7 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
onResultChange,
onRowLimitChange,
onDisplayChange,
+ onRun,
}: QueryEditorProps,
ref
) {
@@ -166,8 +173,9 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
* Postgres SQL cannot reach the analytics wire or vice versa.
*/
const handleRunQuery = async (rawSql: string = sql) => {
- if (!project || isBusy || rewriteProposal || rawSql.trim().length === 0) return
+ if (!project || isBusy || rewriteProposal || isRunDisabled || rawSql.trim().length === 0) return
+ onRun?.()
onSqlCommit?.(rawSql)
if (query._tag === 'logs') {
@@ -227,7 +235,7 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
const Shell = variant === 'viewport' ? ExplorerQueryViewport : ExplorerQuery
return (
- <Shell className={variant === 'embedded' ? 'mx-auto max-w-4xl' : undefined}>
+ <Shell className={cn(variant === 'embedded' && 'mx-auto max-w-4xl', className)}>
<ExplorerToolbar>
<ExplorerToolbarIcon>
<CodeSquare size={14} />
@@ -268,7 +276,11 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
icon={<Play />}
tooltip="Run query"
disabled={
- isLoadingProject || isExecuting || rewriteProposal !== null || sql.trim().length === 0
+ isLoadingProject ||
+ isExecuting ||
+ rewriteProposal !== null ||
+ isRunDisabled ||
+ sql.trim().length === 0
}
onClick={() => handleRunQuery()}
>
@@ -296,7 +308,7 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
placeholder="select * from your_table limit 100;"
placeholderClassName="top-[13px]"
className={variant === 'embedded' ? 'h-44' : undefined}
- actions={{ runQuery: { enabled: true, callback: handleRunQuery } }}
+ actions={{ runQuery: { enabled: !isRunDisabled, callback: handleRunQuery } }}
options={{ minimap: { enabled: false }, padding: { top: 8 } }}
onInputChange={(value) => onSqlChange(value ?? '')}
onMount={(editor) => {
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx
new file mode 100644
index 00000000000..17d79b8b6d4
--- /dev/null
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx
@@ -0,0 +1,143 @@
+import { useRef, useState } from 'react'
+
+import { identifyQueryType } from './AIAssistant.utils'
+import {
+ changeAssistantQuerySource,
+ createAssistantQueryModel,
+ DEFAULT_ASSISTANT_QUERY_TITLE,
+ getAssistantQueryDisplay,
+ setAssistantQuerySql,
+ toAssistantQueryResult,
+} from './AssistantQueryCell.utils'
+import { Confirm } from './Confirm'
+import { type ConfirmFooterApprovalState } from './Confirm.utils'
+import { QueryEditor } from '@/components/interfaces/Explorer/QueryEditor'
+import { type QueryDisplay, type QueryResult } from '@/components/interfaces/Explorer/types'
+import { type QuerySourceBinding } from '@/data/query-sources/query-source-registry'
+import { useTrack } from '@/lib/telemetry/track'
+import { useLocalRoleImpersonationState } from '@/state/role-impersonation-state'
+
+interface AssistantQueryCellProps {
+ id: string
+ sql: string
+ title?: string
+ initialRows?: unknown
+ view?: 'table' | 'chart'
+ xAxis?: string
+ yAxis?: string
+ /** Follow incoming SQL while the assistant is still streaming the query text. */
+ isStreaming?: boolean
+ confirmState?: ConfirmFooterApprovalState
+ onApprove?: () => void
+ onDeny?: () => void
+}
+
+/** Assistant adapter around the shared QueryEditor. Local state only — nothing is persisted. */
+export const AssistantQueryCell = ({
+ id,
+ sql: initialSql,
+ title: initialTitle,
+ initialRows,
+ view,
+ xAxis,
+ yAxis,
+ isStreaming = false,
+ confirmState,
+ onApprove,
+ onDeny,
+}: AssistantQueryCellProps) => {
+ const track = useTrack()
+ const roleImpersonationState = useLocalRoleImpersonationState()
+
+ const [title, setTitle] = useState(initialTitle?.trim() || DEFAULT_ASSISTANT_QUERY_TITLE)
+ const [query, setQuery] = useState(() => createAssistantQueryModel(initialSql))
+ const [result, setResult] = useState<QueryResult | undefined>(() =>
+ toAssistantQueryResult(initialRows)
+ )
+ const [display, setDisplay] = useState<QueryDisplay>(() =>
+ getAssistantQueryDisplay({ view, xAxis, yAxis })
+ )
+
+ const prevId = useRef(id)
+ const prevSql = useRef(initialSql)
+ const prevRows = useRef(initialRows)
+
+ if (prevId.current !== id) {
+ prevId.current = id
+ prevSql.current = initialSql
+ prevRows.current = initialRows
+ setTitle(initialTitle?.trim() || DEFAULT_ASSISTANT_QUERY_TITLE)
+ setQuery(createAssistantQueryModel(initialSql))
+ setResult(toAssistantQueryResult(initialRows))
+ setDisplay(getAssistantQueryDisplay({ view, xAxis, yAxis }))
+ }
+
+ if (prevSql.current !== initialSql) {
+ prevSql.current = initialSql
+ if (isStreaming) {
+ setQuery((current) => setAssistantQuerySql(current, initialSql))
+ }
+ }
+
+ if (prevRows.current !== initialRows) {
+ prevRows.current = initialRows
+ setResult(toAssistantQueryResult(initialRows))
+ }
+
+ const handleTitleChange = (value: string) => {
+ const nextTitle = value.trim()
+ if (!nextTitle) return
+ setTitle(nextTitle)
+ }
+
+ const handleSourceChange = (source: QuerySourceBinding) => {
+ const isBackendChange = source._tag !== query._tag
+ if (isBackendChange) setResult(undefined)
+ setQuery((current) => changeAssistantQuerySource(current, source))
+ }
+
+ const handleRun = () => {
+ const sql = query.uncheckedSql
+ const mutationType = identifyQueryType(sql)
+ track('assistant_suggestion_run_query_clicked', {
+ queryType: mutationType ? 'mutation' : 'select',
+ ...(mutationType ? { mutationType } : {}),
+ })
+ }
+
+ const isConfirming = confirmState !== undefined
+
+ return (
+ <Confirm
+ fill
+ className="h-96"
+ state={confirmState}
+ message="Assistant wants to run this query"
+ cancelLabel="Skip"
+ confirmLabel="Run query"
+ confirmLabelLoading="Running..."
+ onCancel={onDeny}
+ onConfirm={onApprove}
+ >
+ <QueryEditor
+ id={id}
+ variant="viewport"
+ title={title}
+ query={query}
+ result={result}
+ roleImpersonationState={roleImpersonationState}
+ display={display}
+ isRunDisabled={isConfirming}
+ onTitleChange={handleTitleChange}
+ onSqlChange={(sql) => setQuery((current) => setAssistantQuerySql(current, sql))}
+ onSourceChange={handleSourceChange}
+ onResultChange={setResult}
+ onRowLimitChange={(rowLimit) =>
+ setQuery((current) => (current._tag === 'database' ? { ...current, rowLimit } : current))
+ }
+ onDisplayChange={setDisplay}
+ onRun={handleRun}
+ />
+ </Confirm>
+ )
+}
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.test.ts b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.test.ts
new file mode 100644
index 00000000000..b64eddf7e3e
--- /dev/null
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.test.ts
@@ -0,0 +1,90 @@
+import { untrustedSql } from '@supabase/pg-meta'
+import { describe, expect, it } from 'vitest'
+
+import {
+ changeAssistantQuerySource,
+ createAssistantQueryModel,
+ getAssistantQueryDisplay,
+ setAssistantQuerySql,
+ toAssistantQueryResult,
+} from './AssistantQueryCell.utils'
+import { DEFAULT_CELL_ROW_LIMIT } from '@/components/interfaces/Explorer/QueryCell/QueryCell.utils'
+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
+
+describe('getAssistantQueryDisplay', () => {
+ it('defaults to a table view with no chart when axes are missing', () => {
+ expect(getAssistantQueryDisplay({})).toEqual({ view: 'table', chart: undefined })
+ })
+
+ it('builds a bar chart config from axis hints', () => {
+ expect(getAssistantQueryDisplay({ view: 'chart', xAxis: 'day', yAxis: 'signups' })).toEqual({
+ view: 'chart',
+ chart: {
+ type: 'bar',
+ x_column: 'day',
+ y_columns: ['signups'],
+ cumulative: false,
+ scale: 'linear',
+ show_labels: false,
+ },
+ })
+ })
+
+ it('keeps an empty y-axis list when only the x-axis is provided', () => {
+ expect(getAssistantQueryDisplay({ xAxis: 'day' }).chart?.y_columns).toEqual([])
+ })
+})
+
+describe('toAssistantQueryResult', () => {
+ it('returns undefined when the output is not an array of row objects', () => {
+ expect(toAssistantQueryResult(undefined)).toBeUndefined()
+ expect(toAssistantQueryResult('error')).toBeUndefined()
+ expect(toAssistantQueryResult({ rows: [] })).toBeUndefined()
+ })
+
+ it('keeps row objects and drops primitives, arrays, and nulls', () => {
+ expect(toAssistantQueryResult([{ id: 1 }, null, ['x'], 4, { id: 2 }])).toEqual({
+ rows: [{ id: 1 }, { id: 2 }],
+ })
+ })
+
+ it('accepts an empty array as a successful empty result', () => {
+ expect(toAssistantQueryResult([])).toEqual({ rows: [] })
+ })
+})
+
+describe('assistant query model', () => {
+ it('starts as a database query with the notebook default row limit', () => {
+ expect(createAssistantQueryModel('select 1')).toEqual({
+ _tag: 'database',
+ uncheckedSql: untrustedSql('select 1'),
+ rowLimit: DEFAULT_CELL_ROW_LIMIT,
+ })
+ })
+
+ it('rebrands the live SQL for the current backend', () => {
+ const database = createAssistantQueryModel('select 1')
+ expect(setAssistantQuerySql(database, 'select 2').uncheckedSql).toBe(untrustedSql('select 2'))
+
+ const logs = changeAssistantQuerySource(database, {
+ _tag: 'logs',
+ time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 1 },
+ })
+ expect(logs._tag).toBe('logs')
+ expect(setAssistantQuerySql(logs, 'select 3').uncheckedSql).toBe(untrustedLogSql('select 3'))
+ })
+
+ it('carries the SQL across a source change and restores the default row limit onto logs → database', () => {
+ const logs = changeAssistantQuerySource(createAssistantQueryModel('select 1'), {
+ _tag: 'logs',
+ time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 1 },
+ })
+ const database = changeAssistantQuerySource(logs, { _tag: 'database' })
+
+ expect(database).toEqual({
+ _tag: 'database',
+ uncheckedSql: untrustedSql('select 1'),
+ rowLimit: DEFAULT_CELL_ROW_LIMIT,
+ })
+ })
+})
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.ts
new file mode 100644
index 00000000000..a09fc6fba58
--- /dev/null
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.utils.ts
@@ -0,0 +1,77 @@
+import { untrustedSql } from '@supabase/pg-meta'
+
+import { DEFAULT_CELL_ROW_LIMIT } from '@/components/interfaces/Explorer/QueryCell/QueryCell.utils'
+import { type ExplorerQueryModel } from '@/components/interfaces/Explorer/QueryEditor'
+import { type QueryDisplay, type QueryResult } from '@/components/interfaces/Explorer/types'
+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
+import { type QuerySourceBinding } from '@/data/query-sources/query-source-registry'
+
+export const DEFAULT_ASSISTANT_QUERY_TITLE = 'SQL query'
+
+export function getAssistantQueryDisplay({
+ view,
+ xAxis,
+ yAxis,
+}: {
+ view?: 'table' | 'chart'
+ xAxis?: string
+ yAxis?: string
+}): QueryDisplay {
+ const hasChartAxes = Boolean(xAxis || yAxis)
+
+ return {
+ view: view ?? 'table',
+ chart: hasChartAxes
+ ? {
+ type: 'bar',
+ x_column: xAxis ?? '',
+ y_columns: yAxis ? [yAxis] : [],
+ cumulative: false,
+ scale: 'linear',
+ show_labels: false,
+ }
+ : undefined,
+ }
+}
+
+export function toAssistantQueryResult(output: unknown): QueryResult | undefined {
+ if (!Array.isArray(output)) return undefined
+
+ const rows = output.filter(
+ (row): row is Record<string, unknown> =>
+ row !== null && typeof row === 'object' && !Array.isArray(row)
+ )
+
+ return { rows }
+}
+
+export function createAssistantQueryModel(sql: string): ExplorerQueryModel {
+ return {
+ _tag: 'database',
+ uncheckedSql: untrustedSql(sql),
+ rowLimit: DEFAULT_CELL_ROW_LIMIT,
+ }
+}
+
+export function setAssistantQuerySql(query: ExplorerQueryModel, sql: string): ExplorerQueryModel {
+ if (query._tag === 'logs') {
+ return { ...query, uncheckedSql: untrustedLogSql(sql) }
+ }
+
+ return { ...query, uncheckedSql: untrustedSql(sql) }
+}
+
+export function changeAssistantQuerySource(
+ query: ExplorerQueryModel,
+ source: QuerySourceBinding
+): ExplorerQueryModel {
+ if (source._tag === 'logs') {
+ return { ...source, uncheckedSql: untrustedLogSql(query.uncheckedSql) }
+ }
+
+ return {
+ ...source,
+ uncheckedSql: untrustedSql(query.uncheckedSql),
+ rowLimit: query._tag === 'database' ? query.rowLimit : DEFAULT_CELL_ROW_LIMIT,
+ }
+}