Skip to content

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

refactor(sql-editor): extract AI/diff + shortcuts hooks (decompose 5/6) (#47935)

Charis52a25c2ebb1b
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 20156f9480a..aa10baf4cf8 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -2,50 +2,30 @@ import { acceptUntrustedSql, untrustedSql, type UntrustedSqlFragment } from '@su
import { LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common'
import { Loader2 } from 'lucide-react'
import dynamic from 'next/dynamic'
-import { useRouter } from 'next/router'
import { useCallback, useEffect, useEffectEvent, useState } from 'react'
-import { toast } from 'sonner'
import { cn, ResizableHandle, ResizablePanel, ResizablePanelGroup } from 'ui'
import { useSqlEditorDiff, useSqlEditorPrompt } from './hooks'
import { RunQueryWarningModal } from './RunQueryWarningModal'
-import { sqlAiDisclaimerComment } from './SQLEditor.constants'
-import { DiffType } from './SQLEditor.types'
-import {
- appendEnableRLSStatements,
- assembleCompletionDiff,
- buildDebugPromptText,
- createSqlSnippetSkeletonV2,
-} from './SQLEditor.utils'
+import { appendEnableRLSStatements } from './SQLEditor.utils'
import { SQLEditorProvider, useSQLEditorContext } from './SQLEditorContext'
import { useAddDefinitions } from './useAddDefinitions'
import { useEditorMount } from './useEditorMount'
import { usePrettifyQuery } from './usePrettifyQuery'
import { useSnippetIdentity } from './useSnippetIdentity'
import { useSnippetTitleGenerator } from './useSnippetTitleGenerator'
+import { useSqlEditorAi } from './useSqlEditorAi'
import { useSqlEditorExecution } from './useSqlEditorExecution'
import { useSqlEditorExplain } from './useSqlEditorExplain'
+import { useSqlEditorShortcuts } from './useSqlEditorShortcuts'
import { UtilityActions } from './UtilityPanel/UtilityActions'
import { UtilityPanel } from './UtilityPanel/UtilityPanel'
-import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import ResizableAIWidget from '@/components/ui/AIEditor/ResizableAIWidget'
-import { constructHeaders, isValidConnString } from '@/data/fetchers'
+import { isValidConnString } from '@/data/fetchers'
import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'
-import { isError } from '@/data/utils/error-check'
-import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
-import { BASE_PATH } from '@/lib/constants'
-import { formatSql } from '@/lib/formatSql'
import { detectOS } from '@/lib/helpers'
-import { useProfile } from '@/lib/profile'
-import { useTrack } from '@/lib/telemetry/track'
-import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
-import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
-import { useShortcut } from '@/state/shortcuts/useShortcut'
-import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
-import { useSqlEditorDiffRequestSnapshot } from '@/state/sql-editor/sql-editor-diff-request'
-import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'
import {
getSqlEditorV2StateSnapshot,
useSqlEditorV2StateSnapshot,
@@ -75,59 +55,25 @@ const SQLEditorContent = () => {
} = useSQLEditorContext()
const os = detectOS()
- const router = useRouter()
const { ref } = useParams()
- const { profile } = useProfile()
const { data: project } = useSelectedProjectQuery()
- const { data: org } = useSelectedOrganizationQuery()
const tabs = useTabsStateSnapshot()
- const aiSnap = useAiAssistantStateSnapshot()
- const { openSidebar } = useSidebarManagerSnapshot()
const snapV2 = useSqlEditorV2StateSnapshot()
- const sessionSnap = useSqlEditorSessionSnapshot()
- const diffRequest = useSqlEditorDiffRequestSnapshot()
const databaseSelectorState = useDatabaseSelectorStateSnapshot()
// [Ali] Kill switch to hide the SQL Editor Explain tab and its entry points
const disablePrettyExplain = useFlag('DisablePrettyExplainOnSqlEditor')
- const {
- sourceSqlDiff,
- setSourceSqlDiff,
- selectedDiffType,
- setSelectedDiffType,
- setIsAcceptDiffLoading,
- isDiffOpen,
- defaultSqlDiff,
- closeDiff,
- } = useSqlEditorDiff()
- const { promptState, setPromptState, promptInput, setPromptInput, resetPrompt } =
- useSqlEditorPrompt()
+ const diff = useSqlEditorDiff()
+ const { isDiffOpen, defaultSqlDiff } = diff
+ const prompt = useSqlEditorPrompt()
+ const { promptState, setPromptState, promptInput, setPromptInput, resetPrompt } = prompt
const [hasSelection, setHasSelection] = useState<boolean>(false)
- const [isDiffEditorMounted, setIsDiffEditorMounted] = useState(false)
-
- const [showWidget, setShowWidget] = useState(false)
const [activeUtilityTab, setActiveUtilityTab] = useState<string>('results')
- useShortcut(SHORTCUT_IDS.SQL_EDITOR_FOCUS_EDITOR, refocusEditor, {
- registerInCommandMenu: true,
- })
-
- const openNewSnippet = useCallback(() => {
- if (!ref) return
- // skip=true bypasses the "load last visited snippet" redirect on /sql/new.
- // Without it, the effect in pages/project/[ref]/sql/[id].tsx bounces back
- // to the previous snippet.
- router.push(`/project/${ref}/sql/new?skip=true`)
- }, [ref, router])
-
- useShortcut(SHORTCUT_IDS.SQL_EDITOR_NEW_SNIPPET, openNewSnippet, {
- registerInCommandMenu: true,
- })
-
const { id, urlId, generatedNewSnippetName, isLoading } = useSnippetIdentity()
const { onMount, editorMountCount } = useEditorMount({ id })
@@ -140,19 +86,14 @@ const SQLEditorContent = () => {
{ enabled: isValidConnString(project?.connectionString) }
)
- const { generateSqlTitle, setAiTitle } = useSnippetTitleGenerator()
- const track = useTrack()
+ const { setAiTitle } = useSnippetTitleGenerator()
const prettifyQuery = usePrettifyQuery({ id, isDiffOpen })
- useShortcut(SHORTCUT_IDS.SQL_EDITOR_FORMAT, prettifyQuery, {
- registerInCommandMenu: true,
- })
-
// Reads the SQL to run from the editor as an UntrustedSqlFragment. The
- // untrusted→safe promotion (acceptUntrustedSql) happens in the small run /
- // explain gesture handlers below — never inside the longer execute* helpers,
- // which by construction only accept already-reviewed SafeSqlFragments.
+ // untrusted→safe promotion (acceptUntrustedSql) happens in the run / explain
+ // gesture + warning-modal handlers below — as close to the user action as
+ // possible — before the SQL reaches the execute* pipelines.
const readEditorSql = useCallback((): UntrustedSqlFragment | undefined => {
const snippet = getSqlEditorV2StateSnapshot().snippets[id]
return getEditorSqlFromEditor(snippet?.snippet.content?.unchecked_sql)
@@ -195,218 +136,30 @@ const SQLEditorContent = () => {
if (sql !== undefined) void executeExplainQuery(acceptUntrustedSql(sql))
}, [executeExplainQuery, readEditorSql])
- useShortcut(SHORTCUT_IDS.SQL_EDITOR_EXPLAIN, handleRunExplain, {
- enabled: !disablePrettyExplain,
- registerInCommandMenu: true,
+ const {
+ handlePrompt,
+ acceptAiHandler,
+ discardAiHandler,
+ onDebug,
+ buildDebugPrompt,
+ handleDiffEditorMount,
+ isCompletionLoading,
+ showWidget,
+ } = useSqlEditorAi({ id, editorMountCount, diff, prompt })
+
+ useSqlEditorShortcuts({
+ isDiffOpen,
+ isPromptOpen: promptState.isOpen,
+ disablePrettyExplain,
+ prettifyQuery,
+ runExplain: handleRunExplain,
+ acceptAiHandler,
+ discardAiHandler,
+ resetPrompt,
})
- const handleNewQuery = useCallback(
- async (sql: string, name: string) => {
- if (!ref) return console.error('Project ref is required')
- if (!profile) return console.error('Profile is required')
- if (!project) return console.error('Project is required')
-
- try {
- const snippet = createSqlSnippetSkeletonV2({
- name,
- sql,
- owner_id: profile.id,
- project_id: project.id,
- })
- snapV2.addSnippet({ projectRef: ref, snippet })
- snapV2.addNeedsSaving(snippet.id!)
- router.push(`/project/${ref}/sql/${snippet.id}`)
- } catch (error: any) {
- toast.error(`Failed to create new query: ${error.message}`)
- }
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [profile?.id, project?.id, ref, router, snapV2]
- )
-
- const buildDebugPrompt = useCallback(() => {
- const snippet = snapV2.snippets[id]
- const result = sessionSnap.results[id]?.[0]
- const sql = (snippet?.snippet.content?.unchecked_sql ?? '')
- .replace(sqlAiDisclaimerComment, '')
- .trim()
- const errorMessage = result?.error?.message ?? 'Unknown error'
-
- return buildDebugPromptText(sql, errorMessage)
- }, [id, sessionSnap.results, snapV2.snippets])
-
- const onDebug = useCallback(async () => {
- try {
- const snippet = snapV2.snippets[id]
- const result = sessionSnap.results[id]?.[0]
- openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
- aiSnap.newChat({
- name: 'Debug SQL snippet',
- sqlSnippets: [
- (snippet.snippet.content?.unchecked_sql ?? '').replace(sqlAiDisclaimerComment, '').trim(),
- ],
- initialInput: `Help me to debug the attached sql snippet which gives the following error: \n\n${result.error.message}`,
- })
- } 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
- // entire error body from the assistant
- if (isError(error)) {
- toast.error(
- `Sorry, the assistant failed to debug your query! Please try again with a different one.`
- )
- }
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [id, sessionSnap.results, snapV2.snippets])
-
- const acceptAiHandler = useCallback(async () => {
- try {
- setIsAcceptDiffLoading(true)
-
- // TODO: show error if undefined
- if (!sourceSqlDiff || !editorRef.current || !diffEditorRef.current) return
-
- const editorModel = editorRef.current.getModel()
- const diffModel = diffEditorRef.current.getModel()
-
- if (!editorModel || !diffModel) return
-
- const sql = diffModel.modified.getValue()
-
- if (selectedDiffType === DiffType.NewSnippet) {
- const { title } = await generateSqlTitle({ sql })
- await handleNewQuery(sql, title)
- } else {
- editorRef.current.executeEdits('apply-ai-edit', [
- {
- text: sql,
- range: editorModel.getFullModelRange(),
- },
- ])
- }
-
- track('assistant_sql_diff_handler_evaluated', { handlerAccepted: true })
-
- setSelectedDiffType(DiffType.Modification)
- resetPrompt()
- closeDiff()
- } finally {
- setIsAcceptDiffLoading(false)
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [sourceSqlDiff, selectedDiffType, handleNewQuery, generateSqlTitle, router, id, snapV2, track])
-
- const discardAiHandler = useCallback(() => {
- track('assistant_sql_diff_handler_evaluated', { handlerAccepted: false })
- resetPrompt()
- closeDiff()
- }, [closeDiff, resetPrompt, track])
-
- const [isCompletionLoading, setIsCompletionLoading] = useState<boolean>(false)
-
- const complete = useCallback(
- async (
- _prompt: string,
- options?: {
- headers?: Record<string, string>
- body?: { completionMetadata?: any }
- }
- ) => {
- try {
- setIsCompletionLoading(true)
-
- const response = await fetch(`${BASE_PATH}/api/ai/code/complete`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- ...(options?.headers ?? {}),
- },
- body: JSON.stringify({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- language: 'sql',
- orgSlug: org?.slug,
- ...(options?.body ?? {}),
- }),
- })
-
- if (!response.ok) {
- const errorText = await response.text()
- throw new Error(errorText || 'Failed to generate completion')
- }
-
- // API returns a JSON-encoded string
- const text: string = await response.json()
-
- const meta = options?.body?.completionMetadata ?? {}
- const { original, modified } = assembleCompletionDiff(meta, text)
-
- const formattedModified = formatSql(modified)
- setSourceSqlDiff({ original, modified: formattedModified })
- setSelectedDiffType(DiffType.Modification)
- setPromptState((prev) => ({ ...prev, isLoading: false }))
- setIsCompletionLoading(false)
- } catch (error: any) {
- toast.error(`Failed to generate SQL: ${error?.message ?? 'Unknown error'}`)
- setIsCompletionLoading(false)
- throw error
- }
- },
- [
- org?.slug,
- project?.connectionString,
- project?.ref,
- setPromptState,
- setSelectedDiffType,
- setSourceSqlDiff,
- ]
- )
-
- const handlePrompt = async (
- prompt: string,
- context: {
- beforeSelection: string
- selection: string
- afterSelection: string
- }
- ) => {
- try {
- setPromptState((prev) => ({
- ...prev,
- selection: context.selection,
- beforeSelection: context.beforeSelection,
- afterSelection: context.afterSelection,
- }))
- const headerData = await constructHeaders()
-
- const authorizationHeader = headerData.get('Authorization')
-
- await complete(prompt, {
- ...(authorizationHeader ? { headers: { Authorization: authorizationHeader } } : undefined),
- body: {
- completionMetadata: {
- textBeforeCursor: context.beforeSelection,
- textAfterCursor: context.afterSelection,
- language: 'pgsql',
- prompt,
- selection: context.selection,
- },
- },
- })
- } catch (error) {
- setPromptState((prev) => ({ ...prev, isLoading: false }))
- }
- }
-
/** All useEffects are at the bottom before returning the TSX */
- const resetDiff = useEffectEvent(() => {
- if (id) {
- closeDiff()
- setPromptState((prev) => ({ ...prev, isOpen: false }))
- }
- })
const saveScrollPosition = useEffectEvent((snippetId: string) => {
if (ref) {
const tabId = createTabId('sql', { id: snippetId })
@@ -414,58 +167,12 @@ const SQLEditorContent = () => {
}
})
useEffect(() => {
- resetDiff()
+ // Save the departing snippet's scroll position on unmount / snippet switch.
return () => saveScrollPosition(id)
// Temporary until we update eslint to ignore useEffectEvent
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id])
- useEffect(() => {
- const handler = (e: KeyboardEvent) => {
- if (!isDiffOpen && !promptState.isOpen) return
-
- switch (e.key) {
- case 'Enter':
- if ((os === 'macos' ? e.metaKey : e.ctrlKey) && isDiffOpen) {
- acceptAiHandler()
- resetPrompt()
- }
- return
- case 'Escape':
- if (isDiffOpen) discardAiHandler()
- resetPrompt()
- editorRef.current?.focus()
- return
- }
- }
- window.addEventListener('keydown', handler)
- return () => window.removeEventListener('keydown', handler)
- }, [
- editorRef,
- os,
- isDiffOpen,
- promptState.isOpen,
- acceptAiHandler,
- discardAiHandler,
- resetPrompt,
- ])
-
- useEffect(() => {
- if (isDiffOpen) {
- const diffEditor = diffEditorRef.current
- const model = diffEditor?.getModel()
- if (model && model.original && model.modified) {
- model.original.setValue(defaultSqlDiff.original)
- model.modified.setValue(defaultSqlDiff.modified)
- // scroll to the start line of the modification
- const modifiedEditor = diffEditor!.getModifiedEditor()
- const startLine = promptState.startLineNumber
- modifiedEditor.revealLineInCenter(startLine)
- }
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [selectedDiffType, sourceSqlDiff])
-
useEffect(() => {
if (isSuccessReadReplicas) {
const primaryDatabase = databases.find((db) => db.identifier === ref)
@@ -474,53 +181,6 @@ const SQLEditorContent = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isSuccessReadReplicas, databases, ref])
- const drainDiffRequest = useEffectEvent(() => {
- const request = diffRequest.pending
- if (request === undefined) return
-
- const editorModel = editorRef.current?.getModel()
- // Editor isn't ready yet; leave the request pending. editorMountCount bumps
- // on mount and re-runs this effect, so the request applies once mounted.
- if (!editorModel) return
-
- const { diffType, sql } = request
- const existingValue = editorRef.current?.getValue() ?? ''
- if (existingValue.length === 0) {
- // if the editor is empty, just copy over the code
- editorRef.current?.executeEdits('apply-ai-message', [
- {
- text: `${sql}`,
- range: editorModel.getFullModelRange(),
- },
- ])
- } else {
- const currentSql = editorRef.current?.getValue()
- const diff = { original: currentSql || '', modified: sql }
- setSourceSqlDiff(diff)
- setSelectedDiffType(diffType)
- }
-
- // One-shot: drain the request so it can't re-apply to a later editor or session.
- diffRequest.consumeDiffRequest()
- })
- useEffect(() => {
- drainDiffRequest()
- // until we can upgrade eslint to ignore useEffectEvent
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [diffRequest.pending, editorMountCount])
-
- // We want to check if the diff editor is mounted and if it is, we want to show the widget
- // We also want to cleanup the widget when the diff editor is closed
- useEffect(() => {
- if (!isDiffOpen) {
- setIsDiffEditorMounted(false)
- setShowWidget(false)
- } else if (diffEditorRef.current && isDiffEditorMounted) {
- setShowWidget(true)
- return () => setShowWidget(false)
- }
- }, [diffEditorRef, isDiffOpen, isDiffEditorMounted])
-
return (
<>
<RunQueryWarningModal
@@ -582,10 +242,7 @@ const SQLEditorContent = () => {
language="pgsql"
original={defaultSqlDiff.original}
modified={defaultSqlDiff.modified}
- onMount={(editor) => {
- diffEditorRef.current = editor
- setIsDiffEditorMounted(true)
- }}
+ onMount={handleDiffEditorMount}
/>
{showWidget && (
<ResizableAIWidget
diff --git a/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.ts b/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.ts
new file mode 100644
index 00000000000..d49d4fa036c
--- /dev/null
+++ b/apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.ts
@@ -0,0 +1,373 @@
+import { useParams } from 'common'
+import { useRouter } from 'next/router'
+import { useCallback, useEffect, useEffectEvent, useState } from 'react'
+import { toast } from 'sonner'
+
+import type { useSqlEditorDiff, useSqlEditorPrompt } from './hooks'
+import { sqlAiDisclaimerComment } from './SQLEditor.constants'
+import { DiffType, type IStandaloneDiffEditor } from './SQLEditor.types'
+import {
+ assembleCompletionDiff,
+ buildDebugPromptText,
+ createSqlSnippetSkeletonV2,
+} from './SQLEditor.utils'
+import { useSQLEditorContext } from './SQLEditorContext'
+import { useSnippetTitleGenerator } from './useSnippetTitleGenerator'
+import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import { constructHeaders } from '@/data/fetchers'
+import { isError } from '@/data/utils/error-check'
+import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import { BASE_PATH } from '@/lib/constants'
+import { formatSql } from '@/lib/formatSql'
+import { useProfile } from '@/lib/profile'
+import { useTrack } from '@/lib/telemetry/track'
+import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
+import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
+import { useSqlEditorDiffRequestSnapshot } from '@/state/sql-editor/sql-editor-diff-request'
+import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'
+import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
+
+type UseSqlEditorAiArgs = {
+ id: string
+ /** Bumped on every editor mount; drives one-shot draining of a pending diff request. */
+ editorMountCount: number
+ diff: ReturnType<typeof useSqlEditorDiff>
+ prompt: ReturnType<typeof useSqlEditorPrompt>
+}
+
+/**
+ * Owns the Assistant / diff cluster: SQL completion, the ask-AI prompt flow, the
+ * accept/discard diff handlers, the debug-prompt helpers, and the fragile diff
+ * lifecycle effects (one-shot diff-request drain, diff-editor value sync, and the
+ * ask-AI widget visibility).
+ */
+export function useSqlEditorAi({ id, editorMountCount, diff, prompt }: UseSqlEditorAiArgs) {
+ const {
+ sourceSqlDiff,
+ setSourceSqlDiff,
+ selectedDiffType,
+ setSelectedDiffType,
+ setIsAcceptDiffLoading,
+ isDiffOpen,
+ defaultSqlDiff,
+ closeDiff,
+ } = diff
+ const { promptState, setPromptState, resetPrompt } = prompt
+
+ const { editorRef, diffEditorRef } = useSQLEditorContext()
+
+ const router = useRouter()
+ const { ref } = useParams()
+ const { profile } = useProfile()
+ const { data: project } = useSelectedProjectQuery()
+ const { data: org } = useSelectedOrganizationQuery()
+ const track = useTrack()
+ const snapV2 = useSqlEditorV2StateSnapshot()
+ const sessionSnap = useSqlEditorSessionSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
+ const { openSidebar } = useSidebarManagerSnapshot()
+ const diffRequest = useSqlEditorDiffRequestSnapshot()
+ const { generateSqlTitle } = useSnippetTitleGenerator()
+
+ const [isCompletionLoading, setIsCompletionLoading] = useState<boolean>(false)
+ const [isDiffEditorMounted, setIsDiffEditorMounted] = useState(false)
+ const [showWidget, setShowWidget] = useState(false)
+
+ const handleNewQuery = useCallback(
+ async (sql: string, name: string) => {
+ if (!ref) return console.error('Project ref is required')
+ if (!profile) return console.error('Profile is required')
+ if (!project) return console.error('Project is required')
+
+ try {
+ const snippet = createSqlSnippetSkeletonV2({
+ name,
+ sql,
+ owner_id: profile.id,
+ project_id: project.id,
+ })
+ snapV2.addSnippet({ projectRef: ref, snippet })
+ snapV2.addNeedsSaving(snippet.id!)
+ router.push(`/project/${ref}/sql/${snippet.id}`)
+ } catch (error: any) {
+ toast.error(`Failed to create new query: ${error.message}`)
+ }
+ },
+ [profile, project, ref, router, snapV2]
+ )
+
+ const buildDebugPrompt = useCallback(() => {
+ const snippet = snapV2.snippets[id]
+ const result = sessionSnap.results[id]?.[0]
+ const sql = (snippet?.snippet.content?.unchecked_sql ?? '')
+ .replace(sqlAiDisclaimerComment, '')
+ .trim()
+ const errorMessage = result?.error?.message ?? 'Unknown error'
+
+ return buildDebugPromptText(sql, errorMessage)
+ }, [id, sessionSnap.results, snapV2.snippets])
+
+ const onDebug = useCallback(async () => {
+ try {
+ const snippet = snapV2.snippets[id]
+ const result = sessionSnap.results[id]?.[0]
+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
+ aiSnap.newChat({
+ name: 'Debug SQL snippet',
+ sqlSnippets: [
+ (snippet.snippet.content?.unchecked_sql ?? '').replace(sqlAiDisclaimerComment, '').trim(),
+ ],
+ initialInput: `Help me to debug the attached sql snippet which gives the following error: \n\n${result.error.message}`,
+ })
+ } 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
+ // entire error body from the assistant
+ if (isError(error)) {
+ toast.error(
+ `Sorry, the assistant failed to debug your query! Please try again with a different one.`
+ )
+ }
+ }
+ }, [id, sessionSnap.results, snapV2.snippets, aiSnap, openSidebar])
+
+ const acceptAiHandler = useCallback(async () => {
+ try {
+ setIsAcceptDiffLoading(true)
+
+ // TODO: show error if undefined
+ if (!sourceSqlDiff || !editorRef.current || !diffEditorRef.current) return
+
+ const editorModel = editorRef.current.getModel()
+ const diffModel = diffEditorRef.current.getModel()
+
+ if (!editorModel || !diffModel) return
+
+ const sql = diffModel.modified.getValue()
+
+ if (selectedDiffType === DiffType.NewSnippet) {
+ const { title } = await generateSqlTitle({ sql })
+ await handleNewQuery(sql, title)
+ } else {
+ editorRef.current.executeEdits('apply-ai-edit', [
+ {
+ text: sql,
+ range: editorModel.getFullModelRange(),
+ },
+ ])
+ }
+
+ track('assistant_sql_diff_handler_evaluated', { handlerAccepted: true })
+
+ setSelectedDiffType(DiffType.Modification)
+ resetPrompt()
+ closeDiff()
+ } finally {
+ setIsAcceptDiffLoading(false)
+ }
+ }, [
+ editorRef,
+ diffEditorRef,
+ sourceSqlDiff,
+ selectedDiffType,
+ generateSqlTitle,
+ handleNewQuery,
+ track,
+ setIsAcceptDiffLoading,
+ setSelectedDiffType,
+ resetPrompt,
+ closeDiff,
+ ])
+
+ const discardAiHandler = useCallback(() => {
+ track('assistant_sql_diff_handler_evaluated', { handlerAccepted: false })
+ resetPrompt()
+ closeDiff()
+ }, [closeDiff, resetPrompt, track])
+
+ const complete = useCallback(
+ async (
+ _prompt: string,
+ options?: {
+ headers?: Record<string, string>
+ body?: { completionMetadata?: any }
+ }
+ ) => {
+ try {
+ setIsCompletionLoading(true)
+
+ const response = await fetch(`${BASE_PATH}/api/ai/code/complete`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(options?.headers ?? {}),
+ },
+ body: JSON.stringify({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ language: 'sql',
+ orgSlug: org?.slug,
+ ...(options?.body ?? {}),
+ }),
+ })
+
+ if (!response.ok) {
+ const errorText = await response.text()
+ throw new Error(errorText || 'Failed to generate completion')
+ }
+
+ // API returns a JSON-encoded string
+ const text: string = await response.json()
+
+ const meta = options?.body?.completionMetadata ?? {}
+ const { original, modified } = assembleCompletionDiff(meta, text)
+
+ const formattedModified = formatSql(modified)
+ setSourceSqlDiff({ original, modified: formattedModified })
+ setSelectedDiffType(DiffType.Modification)
+ setPromptState((prev) => ({ ...prev, isLoading: false }))
+ setIsCompletionLoading(false)
+ } catch (error: any) {
+ toast.error(`Failed to generate SQL: ${error?.message ?? 'Unknown error'}`)
+ setIsCompletionLoading(false)
+ throw error
+ }
+ },
+ [
+ org?.slug,
+ project?.connectionString,
+ project?.ref,
+ setPromptState,
+ setSelectedDiffType,
+ setSourceSqlDiff,
+ ]
+ )
+
+ const handlePrompt = async (
+ prompt: string,
+ context: {
+ beforeSelection: string
+ selection: string
+ afterSelection: string
+ }
+ ) => {
+ try {
+ setPromptState((prev) => ({
+ ...prev,
+ selection: context.selection,
+ beforeSelection: context.beforeSelection,
+ afterSelection: context.afterSelection,
+ }))
+ const headerData = await constructHeaders()
+
+ const authorizationHeader = headerData.get('Authorization')
+
+ await complete(prompt, {
+ ...(authorizationHeader ? { headers: { Authorization: authorizationHeader } } : undefined),
+ body: {
+ completionMetadata: {
+ textBeforeCursor: context.beforeSelection,
+ textAfterCursor: context.afterSelection,
+ language: 'pgsql',
+ prompt,
+ selection: context.selection,
+ },
+ },
+ })
+ } catch (error) {
+ setPromptState((prev) => ({ ...prev, isLoading: false }))
+ }
+ }
+
+ const handleDiffEditorMount = (editor: IStandaloneDiffEditor) => {
+ diffEditorRef.current = editor
+ setIsDiffEditorMounted(true)
+ }
+
+ const resetDiff = useEffectEvent(() => {
+ if (id) {
+ closeDiff()
+ setPromptState((prev) => ({ ...prev, isOpen: false }))
+ }
+ })
+ useEffect(() => {
+ resetDiff()
+ // Temporary until we update eslint to ignore useEffectEvent
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [id])
+
+ useEffect(() => {
+ if (isDiffOpen) {
+ const diffEditor = diffEditorRef.current
+ const model = diffEditor?.getModel()
+ if (model && model.original && model.modified) {
+ model.original.setValue(defaultSqlDiff.original)
+ model.modified.setValue(defaultSqlDiff.modified)
+ // scroll to the start line of the modification
+ const modifiedEditor = diffEditor!.getModifiedEditor()
+ const startLine = promptState.startLineNumber
+ modifiedEditor.revealLineInCenter(startLine)
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selectedDiffType, sourceSqlDiff])
+
+ const drainDiffRequest = useEffectEvent(() => {
+ const request = diffRequest.pending
+ if (request === undefined) return
+
+ const editorModel = editorRef.current?.getModel()
+ // Editor isn't ready yet; leave the request pending. editorMountCount bumps
+ // on mount and re-runs this effect, so the request applies once mounted.
+ if (!editorModel) return
+
+ const { diffType, sql } = request
+ const existingValue = editorRef.current?.getValue() ?? ''
+ if (existingValue.length === 0) {
+ // if the editor is empty, just copy over the code
+ editorRef.current?.executeEdits('apply-ai-message', [
+ {
+ text: `${sql}`,
+ range: editorModel.getFullModelRange(),
+ },
+ ])
+ } else {
+ const currentSql = editorRef.current?.getValue()
+ const diff = { original: currentSql || '', modified: sql }
+ setSourceSqlDiff(diff)
+ setSelectedDiffType(diffType)
+ }
+
+ // One-shot: drain the request so it can't re-apply to a later editor or session.
+ diffRequest.consumeDiffRequest()
+ })
+ useEffect(() => {
+ drainDiffRequest()
+ // until we can upgrade eslint to ignore useEffectEvent
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [diffRequest.pending, editorMountCount])
+
+ // We want to check if the diff editor is mounted and if it is, we want to show the widget
+ // We also want to cleanup the widget when the diff editor is closed
+ useEffect(() => {
+ if (!isDiffOpen) {
+ setIsDiffEditorMounted(false)
+ setShowWidget(false)
+ } else if (diffEditorRef.current && isDiffEditorMounted) {
+ setShowWidget(true)
+ return () => setShowWidget(false)
+ }
+ }, [diffEditorRef, isDiffOpen, isDiffEditorMounted])
+
+ return {
+ handlePrompt,
+ acceptAiHandler,
+ discardAiHandler,
+ onDebug,
+ buildDebugPrompt,
+ handleDiffEditorMount,
+ isCompletionLoading,
+ showWidget,
+ }
+}
diff --git a/apps/studio/components/interfaces/SQLEditor/useSqlEditorShortcuts.ts b/apps/studio/components/interfaces/SQLEditor/useSqlEditorShortcuts.ts
new file mode 100644
index 00000000000..4f119980d36
--- /dev/null
+++ b/apps/studio/components/interfaces/SQLEditor/useSqlEditorShortcuts.ts
@@ -0,0 +1,87 @@
+import { useParams } from 'common'
+import { useRouter } from 'next/router'
+import { useCallback, useEffect } from 'react'
+
+import { useSQLEditorContext } from './SQLEditorContext'
+import { detectOS } from '@/lib/helpers'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useShortcut } from '@/state/shortcuts/useShortcut'
+
+type UseSqlEditorShortcutsArgs = {
+ isDiffOpen: boolean
+ isPromptOpen: boolean
+ disablePrettyExplain: boolean
+ prettifyQuery: () => void
+ runExplain: () => void
+ acceptAiHandler: () => void
+ discardAiHandler: () => void
+ resetPrompt: () => void
+}
+
+/**
+ * Registers the SQL editor's keyboard shortcuts (focus editor, new snippet,
+ * format, explain) plus the window keydown that accepts/discards an open AI diff
+ * or dismisses the prompt.
+ */
+export function useSqlEditorShortcuts({
+ isDiffOpen,
+ isPromptOpen,
+ disablePrettyExplain,
+ prettifyQuery,
+ runExplain,
+ acceptAiHandler,
+ discardAiHandler,
+ resetPrompt,
+}: UseSqlEditorShortcutsArgs) {
+ const os = detectOS()
+ const router = useRouter()
+ const { ref } = useParams()
+ const { editorRef, refocusEditor } = useSQLEditorContext()
+
+ const openNewSnippet = useCallback(() => {
+ if (!ref) return
+ // skip=true bypasses the "load last visited snippet" redirect on /sql/new.
+ // Without it, the effect in pages/project/[ref]/sql/[id].tsx bounces back
+ // to the previous snippet.
+ router.push(`/project/${ref}/sql/new?skip=true`)
+ }, [ref, router])
+
+ useShortcut(SHORTCUT_IDS.SQL_EDITOR_FOCUS_EDITOR, refocusEditor, {
+ registerInCommandMenu: true,
+ })
+
+ useShortcut(SHORTCUT_IDS.SQL_EDITOR_NEW_SNIPPET, openNewSnippet, {
+ registerInCommandMenu: true,
+ })
+
+ useShortcut(SHORTCUT_IDS.SQL_EDITOR_FORMAT, prettifyQuery, {
+ registerInCommandMenu: true,
+ })
+
+ useShortcut(SHORTCUT_IDS.SQL_EDITOR_EXPLAIN, runExplain, {
+ enabled: !disablePrettyExplain,
+ registerInCommandMenu: true,
+ })
+
+ useEffect(() => {
+ const handler = (e: KeyboardEvent) => {
+ if (!isDiffOpen && !isPromptOpen) return
+
+ switch (e.key) {
+ case 'Enter':
+ if ((os === 'macos' ? e.metaKey : e.ctrlKey) && isDiffOpen) {
+ acceptAiHandler()
+ resetPrompt()
+ }
+ return
+ case 'Escape':
+ if (isDiffOpen) discardAiHandler()
+ resetPrompt()
+ editorRef.current?.focus()
+ return
+ }
+ }
+ window.addEventListener('keydown', handler)
+ return () => window.removeEventListener('keydown', handler)
+ }, [editorRef, os, isDiffOpen, isPromptOpen, acceptAiHandler, discardAiHandler, resetPrompt])
+}
diff --git a/apps/studio/tests/components/SQLEditor/SQLEditor.test.tsx b/apps/studio/tests/components/SQLEditor/SQLEditor.test.tsx
index 8a90205a360..bb7b7ae1bac 100644
--- a/apps/studio/tests/components/SQLEditor/SQLEditor.test.tsx
+++ b/apps/studio/tests/components/SQLEditor/SQLEditor.test.tsx
@@ -429,11 +429,12 @@ describe('SQLEditor characterization', () => {
sqlEditorDiffRequestState.requestDiff('select 42;', DiffType.Modification)
await renderEditor()
- await screen.findByTestId('diff-editor')
+ // The queued request drains on mount and opens a diff, which disables Run.
+ // (Assert via the run button rather than the dynamically-imported diff editor.)
+ await waitFor(() => expect(screen.getByTestId('run-button')).toBeDisabled())
const addResult = vi.spyOn(sqlEditorSessionState, 'addResult')
// The run button is disabled while diffing; clicking should not execute.
- expect(screen.getByTestId('run-button')).toBeDisabled()
fireEvent.click(screen.getByTestId('run-button'))
// Give any async work a chance to (not) happen.
await new Promise((r) => setTimeout(r, 20))