The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/database functions v2 (#29969)
Joshen Limf521109ce276
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/APISidePanelPreview.tsx b/apps/studio/components/interfaces/App/FeaturePreview/APISidePanelPreview.tsxindex 5e96abfb824..9a4bde83334 100644--- a/apps/studio/components/interfaces/App/FeaturePreview/APISidePanelPreview.tsx+++ b/apps/studio/components/interfaces/App/FeaturePreview/APISidePanelPreview.tsx@@ -3,7 +3,7 @@ import { Markdown } from 'components/interfaces/Markdown'import { BASE_PATH } from 'lib/constants'import Image from 'next/image'-const APISidePanelPreview = () => {+export const APISidePanelPreview = () => {const { ref } = useParams()return (@@ -38,5 +38,3 @@ const APISidePanelPreview = () => {</div>)}--export default APISidePanelPreviewdiff --git a/apps/studio/components/interfaces/App/FeaturePreview/CLSPreview.tsx b/apps/studio/components/interfaces/App/FeaturePreview/CLSPreview.tsxindex 56293f7b9b0..a88c1eddc96 100644--- a/apps/studio/components/interfaces/App/FeaturePreview/CLSPreview.tsx+++ b/apps/studio/components/interfaces/App/FeaturePreview/CLSPreview.tsx@@ -5,7 +5,7 @@ import { Markdown } from 'components/interfaces/Markdown'import { BASE_PATH } from 'lib/constants'import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, WarningIcon } from 'ui'-const CLSPreview = () => {+export const CLSPreview = () => {const { ref } = useParams()return (@@ -53,5 +53,3 @@ const CLSPreview = () => {</div>)}--export default CLSPreviewdiff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsxindex a77d22b887d..84aa5f6c7fe 100644--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx@@ -3,6 +3,33 @@ import { PropsWithChildren, createContext, useContext, useEffect, useState } froimport { LOCAL_STORAGE_KEYS } from 'lib/constants'import { EMPTY_OBJ } from 'lib/void'+import { APISidePanelPreview } from './APISidePanelPreview'+import { CLSPreview } from './CLSPreview'+import { FunctionsAssistantPreview } from './FunctionsAssistantPreview'++export const FEATURE_PREVIEWS = [+ {+ key: LOCAL_STORAGE_KEYS.UI_PREVIEW_FUNCTIONS_ASSISTANT,+ name: 'Database Functions Assistant',+ content: <FunctionsAssistantPreview />,+ discussionsUrl: undefined,+ isNew: true,+ },+ {+ key: LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL,+ name: 'Project API documentation',+ content: <APISidePanelPreview />,+ discussionsUrl: 'https://github.com/orgs/supabase/discussions/18038',+ isNew: false,+ },+ {+ key: LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS,+ name: 'Column-level privileges',+ content: <CLSPreview />,+ discussionsUrl: 'https://github.com/orgs/supabase/discussions/20295',+ isNew: false,+ },+]type FeaturePreviewContextType = {flags: { [key: string]: boolean }@@ -17,22 +44,19 @@ const FeaturePreviewContext = createContext<FeaturePreviewContextType>({export const useFeaturePreviewContext = () => useContext(FeaturePreviewContext)export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren<{}>) => {- const [flags, setFlags] = useState({- [LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT]: false,- [LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL]: false,- [LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]: false,- })+ const [flags, setFlags] = useState(() =>+ FEATURE_PREVIEWS.reduce((a, b) => {+ return { ...a, [b.key]: false }+ }, {})+ )useEffect(() => {if (typeof window !== 'undefined') {- setFlags({- [LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT]:- localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT) === 'true',- [LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL]:- localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL) === 'true',- [LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]:- localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS) === 'true',- })+ setFlags(+ FEATURE_PREVIEWS.reduce((a, b) => {+ return { ...a, [b.key]: localStorage.getItem(b.key) === 'true' }+ }, {})+ )}}, [])@@ -61,3 +85,8 @@ export const useIsColumnLevelPrivilegesEnabled = () => {const { flags } = useFeaturePreviewContext()return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]}++export const useIsDatabaseFunctionsAssistantEnabled = () => {+ const { flags } = useFeaturePreviewContext()+ return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_FUNCTIONS_ASSISTANT]+}diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsxindex de6979679e8..01cbee09063 100644--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx@@ -3,38 +3,23 @@ import Link from 'next/link'import { useEffect, useState } from 'react'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'-import { LOCAL_STORAGE_KEYS } from 'lib/constants'import { useAppStateSnapshot } from 'state/app-state'-import { Button, Modal, ScrollArea, cn } from 'ui'-import APISidePanelPreview from './APISidePanelPreview'-import CLSPreview from './CLSPreview'-import { useFeaturePreviewContext } from './FeaturePreviewContext'+import { Badge, Button, Modal, ScrollArea, cn } from 'ui'+import { FEATURE_PREVIEWS, useFeaturePreviewContext } from './FeaturePreviewContext'+import { useFlag } from 'hooks/ui/useFlag'const FeaturePreviewModal = () => {- // [Ivan] We should probably move this to a separate file, together with LOCAL_STORAGE_KEYS. We should make adding new feature previews as simple as possible.- const FEATURE_PREVIEWS: { key: string; name: string; content: any; discussionsUrl?: string }[] = [- {- key: LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL,- name: 'Project API documentation',- content: <APISidePanelPreview />,- discussionsUrl: 'https://github.com/orgs/supabase/discussions/18038',- },- {- key: LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS,- name: 'Column-level privileges',- content: <CLSPreview />,- discussionsUrl: 'https://github.com/orgs/supabase/discussions/20295',- },- ]-const snap = useAppStateSnapshot()const featurePreviewContext = useFeaturePreviewContext()const { mutate: sendEvent } = useSendEventMutation()+ const enableFunctionsAssistant = useFlag('functionsAssistantV2')const selectedFeaturePreview =snap.selectedFeaturePreview === '' ? FEATURE_PREVIEWS[0].key : snap.selectedFeaturePreviewconst [selectedFeatureKey, setSelectedFeatureKey] = useState<string>(selectedFeaturePreview)+ const isNotReleased =+ selectedFeatureKey === 'supabase-ui-functions-assistant' && !enableFunctionsAssistant// this modal can be triggered on other pages// Update local state when valtio state changes@@ -103,8 +88,11 @@ const FeaturePreviewModal = () => {</div><div className="flex-grow max-h-[550px] p-4 space-y-3 overflow-y-auto"><div className="flex items-center justify-between">- <p>{selectedFeature?.name}</p>- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-x-2">+ <p>{selectedFeature?.name}</p>+ {selectedFeature?.isNew && <Badge color="green">New</Badge>}+ </div>+ <div className="flex items-center gap-x-2">{selectedFeature?.discussionsUrl !== undefined && (<Button asChild type="default" icon={<ExternalLink strokeWidth={1.5} />}><Link href={selectedFeature.discussionsUrl} target="_blank" rel="noreferrer">@@ -112,9 +100,15 @@ const FeaturePreviewModal = () => {</Link></Button>)}- <Button type="default" onClick={() => toggleFeature()}>- {isSelectedFeatureEnabled ? 'Disable' : 'Enable'} feature- </Button>+ {isNotReleased ? (+ <Button disabled type="default">+ Coming soon+ </Button>+ ) : (+ <Button type="default" onClick={() => toggleFeature()}>+ {isSelectedFeatureEnabled ? 'Disable' : 'Enable'} feature+ </Button>+ )}</div></div>{selectedFeature?.content}diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FunctionsAssistantPreview.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FunctionsAssistantPreview.tsxnew file mode 100644index 00000000000..3b48059d6bd--- /dev/null+++ b/apps/studio/components/interfaces/App/FeaturePreview/FunctionsAssistantPreview.tsx@@ -0,0 +1,54 @@+import { useParams } from 'common'+import { Markdown } from 'components/interfaces/Markdown'+import { BASE_PATH } from 'lib/constants'+import { detectOS } from 'lib/helpers'+import Image from 'next/image'++export const FunctionsAssistantPreview = () => {+ const os = detectOS()+ const { ref } = useParams()++ return (+ <div className="flex flex-col gap-y-2">+ <p className="text-foreground-light text-sm mb-4">+ We're providing an additional alternative UX to creating database functions through the+ dashboard with the integration of our AI Assistant that you might have seen in the Auth+ Policies section.+ </p>+ <Image+ src={`${BASE_PATH}/img/previews/functions-assistant.png`}+ width={1860}+ height={970}+ alt="api-docs-side-panel-preview"+ className="rounded border"+ />+ <p className="text-foreground-light text-sm mb-4">+ This preview also shares an improved Assistant interface where you may provide the Assistant+ with contexts in hopes to generate more relevant and higher quality outputs. Contexts that+ you may provide include specific schemas, and / or specific tables from your database.+ </p>+ <p className="text-foreground-light text-sm mb-4">+ We'd hope to use this as a consistent pattern throughout the dashboard eventually if this+ feature preview proves itself to benefit most of our users, so as usual please do feel free+ to let us know what you think if the attached GitHub discussion above!+ </p>+ <div className="space-y-2 !mt-4">+ <p className="text-sm">Enabling this preview will:</p>+ <ul className="list-disc pl-6 text-sm text-foreground-light space-y-1">+ <li>+ <Markdown+ className="text-foreground-light"+ content={`Add a button beside the "Create new function" button on the [Database Functions page](/project/${ref}/database/functions) that will open up a code editor paired with a contextualized AI assistant in a side panel.`}+ />+ </li>+ <li>+ <Markdown+ className="text-foreground-light"+ content={`Add a keyboard shortcut (${os === 'macos' ? 'Cmd' : 'Ctrl'} + I) that will open the Assistant in an uncontextualized mode, along with a quick SQL Editor that you can run queries with from anywhere in the dashboard`}+ />+ </li>+ </ul>+ </div>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsxindex 1323ec5c305..e27f8699a4d 100644--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx@@ -68,9 +68,6 @@ const RLSCodeEditor = ({lineNumbersMinChars: 4,folding: undefined,scrollBeyondLastLine: false,- padding: {- top: editView === 'conversation' ? 20 : 0,- },}const onMount: OnMount = async (editor, monaco) => {diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsxindex 87b385513f5..fafc704b6ea 100644--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx@@ -111,7 +111,7 @@ const PolicyTableRowHeader = ({<AiIconAnimation className="scale-75 [&>div>div]:border-black dark:[&>div>div]:border-white" /></Button></TooltipTrigger_Shadcn_>- <TooltipContent_Shadcn_ side="top">+ <TooltipContent_Shadcn_ side="bottom">{!canToggleRLS? 'You need additional permissions to create RLS policies': 'Create with Supabase Assistant'}diff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsxindex 759a4dac823..65f4bf35f2c 100644--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx@@ -17,9 +17,18 @@ import { useSchemasQuery } from 'data/database/schemas-query'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'-import { Input } from 'ui'+import {+ AiIconAnimation,+ Button,+ Input,+ Tooltip_Shadcn_,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+} from 'ui'import ProtectedSchemaWarning from '../../ProtectedSchemaWarning'import FunctionList from './FunctionList'+import { useAppStateSnapshot } from 'state/app-state'+import { useIsDatabaseFunctionsAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'interface FunctionsListProps {createFunction: () => void@@ -32,10 +41,13 @@ const FunctionsList = ({editFunction = noop,deleteFunction = noop,}: FunctionsListProps) => {- const { project } = useProjectContext()const router = useRouter()const { search } = useParams()+ const { project } = useProjectContext()+ const { setAiAssistantPanel } = useAppStateSnapshot()+ const enableFunctionsAssistant = useIsDatabaseFunctionsAssistantEnabled()const { selectedSchema, setSelectedSchema } = useQuerySchemaState()+const filterString = search ?? ''const setFilterString = (str: string) => {@@ -122,20 +134,41 @@ const FunctionsList = ({/></div>- {!isLocked && (- <ButtonTooltip- disabled={!canCreateFunctions}- onClick={() => createFunction()}- tooltip={{- content: {- side: 'bottom',- text: 'You need additional permissions to create functions',- },- }}- >- Create a new function- </ButtonTooltip>- )}+ <div className="flex items-center gap-x-2">+ {!isLocked && (+ <ButtonTooltip+ disabled={!canCreateFunctions}+ onClick={() => createFunction()}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to create functions',+ },+ }}+ >+ Create a new function+ </ButtonTooltip>+ )}+ {enableFunctionsAssistant && (+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="default"+ className="px-1 pointer-events-auto"+ icon={+ <AiIconAnimation className="scale-75 [&>div>div]:border-black dark:[&>div>div]:border-white" />+ }+ onClick={() => setAiAssistantPanel({ open: true, editor: 'functions' })}+ />+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom">+ {!canCreateFunctions+ ? 'You need additional permissions to create functions'+ : 'Create with Supabase Assistant'}+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ )}+ </div></div>{isLocked && <ProtectedSchemaWarning schema={selectedSchema} entity="functions" />}diff --git a/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx b/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsxindex 9faecac311e..983bb4f4283 100644--- a/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx+++ b/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx@@ -61,7 +61,7 @@ const CreateIndexSidePanel = ({ visible, onClose }: CreateIndexSidePanelProps) =connectionString: project?.connectionString,})const { data: entities, isLoading: isLoadingEntities } = useEntityTypesQuery({- schema: selectedSchema,+ schemas: [selectedSchema],sort: 'alphabetical',search: searchTerm,projectRef: project?.ref,diff --git a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeFilterPopover/TableSelector.tsx b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeFilterPopover/TableSelector.tsxindex 921598b6d12..4161433b7b8 100644--- a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeFilterPopover/TableSelector.tsx+++ b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeFilterPopover/TableSelector.tsx@@ -47,7 +47,7 @@ const TableSelector = ({projectRef: project?.ref,search: searchInput,connectionString: project?.connectionString,- schema: selectedSchemaName,+ schemas: [selectedSchemaName],})useEffect(() => {if (!initiallyLoaded && isSuccess) {diff --git a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsx b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsxindex fa82c7a654f..8b2003a699a 100644--- a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsx+++ b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsx@@ -54,7 +54,7 @@ export const AiMessagePre = ({ onDiff, children, className }: AiMessagePreProps)'!bg-transparent !py-3 !px-3.5 prose dark:prose-dark',// change the look of the code block. The flex hack is so that the code is wrapping since// every word is a separate span- '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap'+ '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap [&>code]:block')}hideCopyhideLineNumbersdiff --git a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/Message.tsx b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/Message.tsxindex edd29cd1987..e7bbd9dd31c 100644--- a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/Message.tsx+++ b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/Message.tsx@@ -30,7 +30,7 @@ const Message = memo(function Message({isSelected = false,onDiff = noop,children,- action = <></>,+ action = null,}: PropsWithChildren<MessageProps>) {const { profile } = useProfile()diff --git a/apps/studio/components/interfaces/TableGridEditor/EmptyState.tsx b/apps/studio/components/interfaces/TableGridEditor/EmptyState.tsxindex bd8f0a90362..07a77e633d8 100644--- a/apps/studio/components/interfaces/TableGridEditor/EmptyState.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/EmptyState.tsx@@ -27,7 +27,7 @@ const EmptyState = ({}: EmptyStateProps) => {const { data } = useEntityTypesQuery({projectRef: project?.ref,connectionString: project?.connectionString,- schema: selectedSchema,+ schemas: [selectedSchema],sort,})diff --git a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsxindex 1e985ecf34d..c859e571e41 100644--- a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx+++ b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx@@ -67,7 +67,7 @@ const TableEditorMenu = () => {{projectRef: project?.ref,connectionString: project?.connectionString,- schema: selectedSchema,+ schemas: [selectedSchema],search: searchText.trim() || undefined,sort,filterTypes: visibleTypes,diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsxnew file mode 100644index 00000000000..90a008b41b0--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx@@ -0,0 +1,696 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { AnimatePresence, motion } from 'framer-motion'+import { last } from 'lodash'+import { ExternalLink, FileText, MessageCircleMore, Plus, WandSparkles } from 'lucide-react'+import Link from 'next/link'+import { useEffect, useMemo, useRef, useState } from 'react'+import { toast } from 'sonner'++import type { Message as MessageType } from 'ai/react'+import { useChat } from 'ai/react'+import { useParams } from 'common'+import OptInToOpenAIToggle from 'components/interfaces/Organization/GeneralSettings/OptInToOpenAIToggle'+import { MessageWithDebug } from 'components/interfaces/SQLEditor/AiAssistantPanel'+import { DiffType } from 'components/interfaces/SQLEditor/SQLEditor.types'+import { useSqlDebugMutation } from 'data/ai/sql-debug-mutation'+import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'+import { useOrganizationUpdateMutation } from 'data/organizations/organization-update-mutation'+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'+import { useSchemasForAi } from 'hooks/misc/useSchemasForAi'+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'+import { BASE_PATH, IS_PLATFORM, OPT_IN_TAGS } from 'lib/constants'+import { useAppStateSnapshot } from 'state/app-state'+import {+ AiIconAnimation,+ Alert_Shadcn_,+ AlertDescription_Shadcn_,+ Button,+ cn,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+ SheetHeader,+ SheetSection,+ Tooltip_Shadcn_,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+} from 'ui'+import { Admonition, AssistantChatForm } from 'ui-patterns'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import { ASSISTANT_SUPPORT_ENTITIES } from './AiAssistant.constants'+import { SupportedAssistantEntities, SupportedAssistantQuickPromptTypes } from './AIAssistant.types'+import { generatePrompt, retrieveDocsUrl } from './AIAssistant.utils'+import { ContextBadge } from './ContextBadge'+import { EntitiesDropdownMenu } from './EntitiesDropdownMenu'+import { Message } from './Message'+import { SchemasDropdownMenu } from './SchemasDropdownMenu'++const ANIMATION_DURATION = 0.3++interface AIAssistantProps {+ id: string+ className?: string+ debugThread: MessageWithDebug[]+ onDiff: ({ id, diffType, sql }: { id: string; diffType: DiffType; sql: string }) => void+ onResetConversation: () => void+}++// [Joshen] For some reason I'm having issues working with dropdown menu and scroll area++export const AIAssistant = ({+ id,+ className,+ debugThread,+ onDiff,+ onResetConversation,+}: AIAssistantProps) => {+ const { ref } = useParams()+ const project = useSelectedProject()+ const isOptedInToAI = useOrgOptedIntoAi()+ const selectedOrganization = useSelectedOrganization()+ const includeSchemaMetadata = isOptedInToAI || !IS_PLATFORM++ const { aiAssistantPanel } = useAppStateSnapshot()+ const { editor } = aiAssistantPanel++ const inputRef = useRef<HTMLTextAreaElement>(null)+ const bottomRef = useRef<HTMLDivElement>(null)++ const [value, setValue] = useState<string>('')+ const [selectedDatabaseEntity, setSelectedDatabaseEntity] = useState<+ SupportedAssistantEntities | ''+ >('')+ const [selectedSchemas, setSelectedSchemas] = useSchemasForAi(project?.ref!)+ const [selectedTables, setSelectedTables] = useState<{ schema: string; name: string }[]>([])+ const [contextHistory, setContextHistory] = useState<{+ [key: string]: { entity: string; schemas: string[]; tables: string[] }+ }>({})+ // [Joshen] Mainly for error handling on useChat - cause last sent messages will be voided+ const [assistantError, setAssistantError] = useState<string>()+ const [lastSentMessage, setLastSentMessage] = useState<MessageType>()+ const [isConfirmOptInModalOpen, setIsConfirmOptInModalOpen] = useState(false)++ const docsUrl = retrieveDocsUrl(selectedDatabaseEntity as SupportedAssistantEntities)+ const entityContext = ASSISTANT_SUPPORT_ENTITIES.find((x) => x.id === selectedDatabaseEntity)+ const noContextAdded =+ selectedDatabaseEntity.length === 0 &&+ selectedSchemas.length === 0 &&+ selectedTables.length === 0++ const { data } = useEntityDefinitionsQuery(+ {+ schemas: selectedSchemas,+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ },+ { enabled: includeSchemaMetadata }+ )++ const entityDefinitions = includeSchemaMetadata+ ? selectedTables.length === 0+ ? data?.map((def) => def.sql.trim())+ : data+ ?.filter((def) => {+ return selectedTables.some((table) => {+ return def.sql.startsWith(`CREATE TABLE ${table.schema}.${table.name}`)+ })+ })+ .map((def) => def.sql.trim())+ : undefined++ const {+ messages: chatMessages,+ isLoading: isChatLoading,+ append,+ } = useChat({+ id,+ api: `${BASE_PATH}/api/ai/sql/generate-v2`,+ body: { entityDefinitions, context: selectedDatabaseEntity },+ onError: (error) => setAssistantError(JSON.parse(error.message).error),+ })++ const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')+ const { mutate: updateOrganization, isLoading: isUpdating } = useOrganizationUpdateMutation()++ const { isLoading: isDebugSqlLoading } = useSqlDebugMutation()+ const isLoading = isChatLoading || isDebugSqlLoading++ const messages = useMemo(() => {+ const merged = [+ ...debugThread,+ ...chatMessages.map((m) => ({ ...m, isDebug: false })),+ ...(assistantError !== undefined && lastSentMessage !== undefined ? [lastSentMessage] : []),+ ]++ return merged.sort(+ (a, b) =>+ (a.createdAt?.getTime() ?? 0) - (b.createdAt?.getTime() ?? 0) ||+ a.role.localeCompare(b.role)+ )+ }, [chatMessages, debugThread, assistantError, lastSentMessage])++ const hasMessages = messages.length > 0+ const lastMessage = last(messages)+ const pendingChatReply = isLoading && lastMessage?.role === 'user'+ const pendingDebugReply =+ (lastMessage as MessageWithDebug)?.isDebug &&+ lastMessage?.role === 'assistant' &&+ lastMessage.content === 'Thinking...'+ const pendingReply = pendingChatReply || pendingDebugReply++ const sendMessageToAssistant = (content: string) => {+ const payload = { role: 'user', createdAt: new Date(), content } as MessageType+ append(payload)+ setAssistantError(undefined)+ setLastSentMessage(payload)+ }++ const toggleSchema = (schema: string) => {+ if (selectedSchemas.includes(schema)) {+ setSelectedSchemas(selectedSchemas.filter((s) => s !== schema))+ } else {+ const newSelectedSchemas = [...selectedSchemas, schema].sort((a, b) => a.localeCompare(b))+ setSelectedSchemas(newSelectedSchemas)+ }+ }++ const toggleEntity = ({ schema, name }: { schema: string; name: string }) => {+ const isExisting = selectedTables.find((x) => x.schema === schema && x.name === name)+ if (isExisting) {+ setSelectedTables(selectedTables.filter((x) => !(x.schema === schema && x.name === name)))+ } else {+ const newselectedTables = [...selectedTables, { schema, name }].sort(+ (a, b) => a.schema.localeCompare(b.schema) || a.name.localeCompare(b.name)+ )+ setSelectedTables(newselectedTables)+ }+ }++ const onClickQuickPrompt = (type: SupportedAssistantQuickPromptTypes) => {+ const prompt = generatePrompt({+ type,+ context: selectedDatabaseEntity as any,+ schemas: selectedSchemas,+ tables: selectedTables,+ })+ if (prompt) {+ setValue(prompt)+ sendMessageToAssistant(prompt)+ }+ }++ const confirmOptInToShareSchemaData = async () => {+ if (!canUpdateOrganization) {+ return toast.error('You do not have the required permissions to update this organization')+ }++ if (!selectedOrganization?.slug) return console.error('Organization slug is required')++ const existingOptInTags = selectedOrganization?.opt_in_tags ?? []++ const updatedOptInTags = existingOptInTags.includes(OPT_IN_TAGS.AI_SQL)+ ? existingOptInTags+ : [...existingOptInTags, OPT_IN_TAGS.AI_SQL]++ updateOrganization(+ { slug: selectedOrganization?.slug, opt_in_tags: updatedOptInTags },+ {+ onSuccess: () => {+ toast.success('Successfully opted-in')+ setIsConfirmOptInModalOpen(false)+ },+ }+ )+ }++ useEffect(() => {+ if (editor) {+ const mode = ASSISTANT_SUPPORT_ENTITIES.find((x) => x.id === editor)+ if (mode) setSelectedDatabaseEntity(mode.id)+ }+ }, [editor])++ useEffect(() => {+ if (!isLoading) {+ setValue('')+ if (inputRef.current) inputRef.current.focus()+ }++ setTimeout(+ () => {+ if (bottomRef.current) bottomRef.current.scrollIntoView({ behavior: 'smooth' })+ },+ isLoading ? 100 : 500+ )+ }, [isLoading])++ useEffect(() => {+ if (bottomRef.current) bottomRef.current.scrollIntoView({ behavior: 'smooth' })+ }, [messages])++ useEffect(() => {+ const lastMessage = last(messages)+ if (lastMessage?.role === 'user') {+ const entity = entityContext?.label ?? selectedDatabaseEntity+ setContextHistory({+ ...contextHistory,+ [lastMessage.id]: {+ entity,+ schemas: selectedSchemas,+ tables: selectedTables.map((x) =>+ selectedSchemas.length > 1 ? `${x.schema}.${x.name}` : x.name+ ),+ },+ })+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [messages.length])++ return (+ <>+ <div className={cn('flex flex-col', className)}>+ <SheetHeader className="flex items-center justify-between py-3">+ <div className="flex items-center gap-x-2">+ <AiIconAnimation+ allowHoverEffect+ className="[&>div>div]:border-black dark:[&>div>div]:border-white"+ />+ <p>Assistant</p>+ </div>+ <AnimatePresence>+ {hasMessages && (+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 100 }}+ exit={{ opacity: 0 }}+ transition={{ duration: 0.2 }}+ >+ <Button type="default" disabled={isLoading} onClick={() => onResetConversation()}>+ Reset conversation+ </Button>+ </motion.div>+ )}+ </AnimatePresence>+ </SheetHeader>++ <SheetSection+ className={cn(+ 'flex-grow flex flex-col items-center !p-0',+ hasMessages ? 'justify-between h-[90%]' : 'justify-center h-full'+ )}+ >+ {hasMessages && (+ <motion.div+ initial={{ height: 0 }}+ transition={{ duration: ANIMATION_DURATION }}+ className="w-full overflow-auto flex-1"+ >+ {messages.map((m, index) => {+ const isFirstUserMessage =+ m.role === 'user' && messages.slice(0, index).every((msg) => msg.role !== 'user')++ return (+ <Message+ key={`message-${m.id}`}+ name={m.name}+ role={m.role}+ content={m.content}+ createdAt={new Date(m.createdAt || new Date()).getTime()}+ isDebug={(m as MessageWithDebug).isDebug}+ context={contextHistory[m.id]}+ onDiff={(diffType, sql) => onDiff({ id: m.id, diffType, sql })}+ >+ {isFirstUserMessage && !includeSchemaMetadata && (+ <Admonition+ type="default"+ title="Project metadata is not shared with the Assistant"+ description="The Assistant can improve the quality of the answers if you send project metadata along with your prompts. Opt into sending anonymous data to share your schema and table definitions."+ >+ <Button+ type="default"+ className="w-fit"+ onClick={() => setIsConfirmOptInModalOpen(true)}+ >+ Update AI settings+ </Button>+ </Admonition>+ )}+ {isFirstUserMessage &&+ includeSchemaMetadata &&+ selectedSchemas.length === 0 && (+ <Admonition+ type="default"+ title="We recommend including schemas for better answers from the Assistant"+ />+ )}+ </Message>+ )+ })}+ {assistantError !== undefined && (+ <Message+ key="assistant-error"+ role="assistant"+ variant="warning"+ createdAt={new Date().getTime()}+ content={`Sorry! We ran into the following error while trying to respond to your message: ${assistantError}. Please try again shortly or reach out to us via support if the issue still persists!`}+ >+ <Button asChild type="default" className="w-min">+ <Link+ target="_blank"+ rel="noreferrer"+ href={`/support/new?ref=${ref}&category=dashboard_bug&subject=Error%20with%20assistant%20response&message=Assistant%20error:%20${assistantError}`}+ >+ Contact support+ </Link>+ </Button>+ </Message>+ )}+ {!isLoading && !pendingReply && assistantError === undefined && (+ <p className="px-content text-xs text-right text-foreground-lighter pb-2">+ Please verify all responses as the Assistant can make mistakes+ </p>+ )}+ {pendingChatReply && (+ <Message key="thinking" role="assistant" content="Thinking..." />+ )}+ <div ref={bottomRef} className="h-1" />+ </motion.div>+ )}++ <div+ className={cn(+ 'w-full px-content py-content',+ hasMessages ? 'sticky flex-0 border-t' : 'flex flex-col gap-y-4'+ )}+ >+ <AnimatePresence>+ {!hasMessages && (+ <motion.div+ exit={{ opacity: 0 }}+ initial={{ opacity: 100 }}+ transition={{ duration: ANIMATION_DURATION }}+ >+ <p className="text-center text-base text-foreground-light">+ How can I help you+ {!!entityContext ? (+ <>+ {' '}+ with{' '}+ <span className="text-foreground">+ {entityContext.id === 'rls-policies'+ ? entityContext.label+ : `Database ${entityContext.label}`}+ </span>+ </>+ ) : (+ ' today'+ )}+ ?+ </p>+ </motion.div>+ )}+ </AnimatePresence>+ <div className="flex flex-col gap-y-2">+ <div className="w-full border rounded">+ <div className="py-2 px-3 border-b flex gap-2 flex-wrap">+ <DropdownMenu>+ <DropdownMenuTrigger>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="default"+ icon={<Plus />}+ className={noContextAdded ? '' : 'px-1.5 !space-x-0'}+ >+ <span className={noContextAdded ? '' : 'sr-only'}>Add context</span>+ </Button>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side={hasMessages ? 'top' : 'bottom'}>+ Add context for the assistant+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-[310px]">+ <DropdownMenuLabel>+ Improve the output quality of the assistant by giving it context about what+ you need help with+ </DropdownMenuLabel>+ <DropdownMenuSeparator />+ {editor === null && (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <div className="flex flex-col gap-y-1">+ <p>Database Entity</p>+ <p className="text-foreground-lighter">+ Inform about what you're working with+ </p>+ </div>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <DropdownMenuRadioGroup+ value={selectedDatabaseEntity}+ onValueChange={(value) =>+ setSelectedDatabaseEntity(value as SupportedAssistantEntities)+ }+ >+ {ASSISTANT_SUPPORT_ENTITIES.map((x) => (+ <DropdownMenuRadioItem key={x.id} value={x.id}>+ {x.label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )}+ {includeSchemaMetadata && (+ <>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-x-2">+ <div className="flex flex-col gap-y-1">+ <p>Schemas</p>+ <p className="text-foreground-lighter">+ Share table definitions in the selected schemas+ </p>+ </div>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="p-0 w-52">+ <SchemasDropdownMenu+ selectedSchemas={selectedSchemas}+ onToggleSchema={toggleSchema}+ />+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ {selectedSchemas.length > 0 && (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-x-2">+ <div className="flex flex-col gap-y-1">+ <p>Tables</p>+ <p className="text-foreground-lighter">+ Select specific tables to share definitions for+ </p>+ </div>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="p-0 w-52">+ <EntitiesDropdownMenu+ selectedSchemas={selectedSchemas}+ selectedEntities={selectedTables}+ onToggleEntity={toggleEntity}+ />+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )}+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>++ {!!entityContext && (+ <ContextBadge+ label="Entity"+ value={entityContext.label}+ onRemove={editor === null ? () => setSelectedDatabaseEntity('') : undefined}+ />+ )}++ {selectedSchemas.length > 0 && (+ <ContextBadge+ label="Schemas"+ value={`${selectedSchemas.slice(0, 2).join(', ')}${selectedSchemas.length > 2 ? ` and ${selectedSchemas.length - 2} other${selectedSchemas.length > 3 ? 's' : ''}` : ''}`}+ onRemove={() => {+ setSelectedSchemas([])+ setSelectedTables([])+ }}+ tooltip={+ selectedSchemas.length > 2 ? (+ <>+ <p className="text-foreground-light">+ {selectedSchemas.length} schemas selected:+ </p>+ <ul className="list-disc pl-4">+ {selectedSchemas.map((x) => (+ <li key={x}>{x}</li>+ ))}+ </ul>+ </>+ ) : undefined+ }+ />+ )}++ {selectedTables.length > 0 && (+ <ContextBadge+ label="Tables"+ value={`${selectedTables+ .slice(0, 2)+ .map((x) => x.name)+ .join(+ ', '+ )}${selectedTables.length > 2 ? ` and ${selectedTables.length - 2} other${selectedTables.length > 3 ? 's' : ''}` : ''}`}+ onRemove={() => setSelectedTables([])}+ tooltip={+ selectedTables.length > 2 ? (+ <>+ <p className="text-foreground-light">+ {selectedTables.length} tables selected:+ </p>+ <ul className="list-disc pl-4">+ {selectedTables.map((x) => (+ <li key={`${x.schema}.${x.name}`}>+ {x.schema}.{x.name}+ </li>+ ))}+ </ul>+ </>+ ) : undefined+ }+ />+ )}+ </div>++ <AssistantChatForm+ textAreaRef={inputRef}+ className={cn(+ '[&>textarea]:rounded-none [&>textarea]:border-0 [&>textarea]:!outline-none [&>textarea]:!ring-offset-0 [&>textarea]:!ring-0'+ )}+ loading={isLoading}+ disabled={isLoading}+ placeholder={+ hasMessages ? 'Reply to the assistant...' : 'How can we help you today?'+ }+ value={value}+ onValueChange={(e) => setValue(e.target.value)}+ onSubmit={(event) => {+ event.preventDefault()+ sendMessageToAssistant(value)+ }}+ />+ </div>+ <AnimatePresence>+ {!hasMessages && (+ <motion.div+ exit={{ opacity: 0 }}+ initial={{ opacity: 100 }}+ transition={{ duration: ANIMATION_DURATION }}+ className={cn('w-full')}+ >+ <div+ className={cn(+ 'flex items-center gap-x-2 transition',+ entityContext !== undefined ? 'opacity-100' : 'opacity-0'+ )}+ >+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="default"+ icon={<WandSparkles />}+ onClick={() => onClickQuickPrompt('suggest')}+ >+ Suggest+ </Button>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom">+ Suggest some{' '}+ {entityContext?.id === 'rls-policies'+ ? entityContext.label+ : `database ${entityContext?.label.toLowerCase()}`}+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="default"+ icon={<FileText />}+ onClick={() => onClickQuickPrompt('examples')}+ >+ Examples+ </Button>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom">+ Provide some examples of{' '}+ {entityContext?.id === 'rls-policies'+ ? entityContext.label+ : `database ${entityContext?.label.toLowerCase()}`}+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="default"+ icon={<MessageCircleMore />}+ onClick={() => onClickQuickPrompt('ask')}+ >+ Ask+ </Button>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom">+ What are{' '}+ {entityContext?.id === 'rls-policies'+ ? entityContext.label+ : `database ${entityContext?.label.toLowerCase()}`}+ ?+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ {docsUrl !== undefined && (+ <Button asChild type="default" icon={<ExternalLink />}>+ <a href={docsUrl} target="_blank" rel="noreferrer">+ Documentation+ </a>+ </Button>+ )}+ </div>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ </div>+ </SheetSection>+ </div>+ <ConfirmationModal+ visible={isConfirmOptInModalOpen}+ size="large"+ title="Confirm sending anonymous data to OpenAI"+ confirmLabel="Confirm"+ onCancel={() => setIsConfirmOptInModalOpen(false)}+ onConfirm={confirmOptInToShareSchemaData}+ loading={isUpdating}+ >+ <p className="text-sm text-foreground-light">+ By opting into sending anonymous data, Supabase AI can improve the answers it shows you.+ This is an organization-wide setting, and affects all projects in your organization.+ </p>++ <OptInToOpenAIToggle />+ </ConfirmationModal>+ </>+ )+}diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.tsnew file mode 100644index 00000000000..38fb580b306--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts@@ -0,0 +1,2 @@+export type SupportedAssistantEntities = 'rls-policies' | 'functions'+export type SupportedAssistantQuickPromptTypes = 'suggest' | 'examples' | 'ask'diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.tsnew file mode 100644index 00000000000..b0b28d12550--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts@@ -0,0 +1,125 @@+import { SupportedAssistantEntities, SupportedAssistantQuickPromptTypes } from './AIAssistant.types'++const PLACEHOLDER_PREFIX = `-- Press tab to use this code+\n \n`++const PLACEHOLDER_LIMIT = `Just three examples will do.`++export const generateTitle = (editor?: SupportedAssistantEntities | null) => {+ switch (editor) {+ case 'functions':+ return 'Create a new function'+ case 'rls-policies':+ return 'Create a new RLS policy'+ default:+ return 'SQL Scratch Pad'+ }+}++export const generateCTA = (editor?: SupportedAssistantEntities | null) => {+ switch (editor) {+ case 'functions':+ return 'Save function'+ case 'rls-policies':+ return 'Save policy'+ default:+ return 'Run query'+ }+}++export const generatePlaceholder = (editor?: SupportedAssistantEntities | null) => {+ switch (editor) {+ case 'functions':+ return `${PLACEHOLDER_PREFIX}+CREATE FUNCTION *schema*.*function_name*(*param1 type*, *param2 type*)\n+ RETURNS *return_type*\n+ LANGUAGE *plpgsql*\n+ SECURITY DEFINER\n+ SET *search_path = ''*\n+AS $$\n+DECLARE\n+ *-- Variable declarations*\n+BEGIN\n+ *-- Function logic*\n+END;\n+$$;+`+ case 'rls-policies':+ return `${PLACEHOLDER_PREFIX}+CREATE POLICY *name* ON *table_name*\n+AS PERMISSIVE -- PERMISSIVE | RESTRICTIVE\n+FOR ALL -- ALL | SELECT | INSERT | UPDATE | DELETE\n+TO *role_name* -- Default: public\n+USING ( *using_expression* )\n+WITH CHECK ( *check_expression* );+`+ default:+ return undefined+ }+}++export const retrieveDocsUrl = (editor?: SupportedAssistantEntities | null) => {+ switch (editor) {+ case 'functions':+ return 'https://supabase.com/docs/guides/database/functions'+ case 'rls-policies':+ return 'https://supabase.com/docs/guides/database/postgres/row-level-security'+ default:+ return undefined+ }+}++// [Joshen] This is just very basic validation, but possible can extend perhaps+export const validateQuery = (editor: SupportedAssistantEntities | null, query: string) => {+ const formattedQuery = query.toLowerCase().replaceAll('\n', ' ')++ switch (editor) {+ case 'functions':+ return (+ formattedQuery.includes('create function') ||+ formattedQuery.includes('create or replace function')+ )+ case 'rls-policies':+ return formattedQuery.includes('create policy')+ default:+ return true+ }+}++export const generatePrompt = ({+ type,+ context,+ schemas,+ tables,+}: {+ type: SupportedAssistantQuickPromptTypes+ context: SupportedAssistantEntities+ schemas: string[]+ tables: { schema: string; name: string }[]+}) => {+ if (type === 'examples') {+ return `What are some common examples of user-defined database ${context}? ${PLACEHOLDER_LIMIT}`+ } else if (type === 'ask') {+ return `Could you explain to me what are used-defined database ${context}?`+ } else if (type === 'suggest') {+ const output =+ context === 'functions'+ ? 'user-defined database functions'+ : context === 'rls-policies'+ ? 'RLS policies'+ : ''++ const suffix =+ context === 'functions' ? 'Let me know for which tables each function will be useful' : ''++ const basePrompt = `Suggest some ${output} that might be useful`++ if (tables.length > 0 && schemas.length > 0) {+ return `${basePrompt} for the following tables within this database: ${tables.map((x) => `${x.schema}.${x.name}`)}. ${PLACEHOLDER_LIMIT} ${suffix}`.trim()+ } else if (schemas.length > 0) {+ return `${basePrompt} for the tables in the following schemas within this database: ${schemas.join(', ')}. ${suffix}`.trim()+ }++ return basePrompt+ }+}diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsxnew file mode 100644index 00000000000..c2d0379154a--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx@@ -0,0 +1,439 @@+import { useQueryClient } from '@tanstack/react-query'+import { uniqBy } from 'lodash'+import { Command, CornerDownLeft, Loader2, X } from 'lucide-react'+import { useRouter } from 'next/router'+import { useCallback, useEffect, useRef, useState } from 'react'+import { toast } from 'sonner'++import { useChat } from 'ai/react'+import { useParams } from 'common'+import { generateThreadMessage } from 'components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils'+import { MessageWithDebug } from 'components/interfaces/SQLEditor/AiAssistantPanel'+import { sqlAiDisclaimerComment } from 'components/interfaces/SQLEditor/SQLEditor.constants'+import { DiffType, IStandaloneCodeEditor } from 'components/interfaces/SQLEditor/SQLEditor.types'+import { suffixWithLimit } from 'components/interfaces/SQLEditor/SQLEditor.utils'+import Results from 'components/interfaces/SQLEditor/UtilityPanel/Results'+import { useSqlDebugMutation } from 'data/ai/sql-debug-mutation'+import { databasePoliciesKeys } from 'data/database-policies/keys'+import { QueryResponseError, useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'+import { sqlKeys } from 'data/sql/keys'+import { usePrevious } from 'hooks/deprecated'+import { useLocalStorage } from 'hooks/misc/useLocalStorage'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'+import { SqlEditor } from 'icons'+import { BASE_PATH, LOCAL_STORAGE_KEYS } from 'lib/constants'+import { detectOS, uuidv4 } from 'lib/helpers'+import { useAppStateSnapshot } from 'state/app-state'+import {+ Button,+ cn,+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ Tooltip_Shadcn_,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+} from 'ui'+import { Admonition } from 'ui-patterns'+import CodeEditor from '../CodeEditor/CodeEditor'+import { AIAssistant } from './AIAssistant'+import { generateCTA, generatePlaceholder, generateTitle, validateQuery } from './AIAssistant.utils'+import { ASSISTANT_SUPPORT_ENTITIES } from './AiAssistant.constants'++export const AiAssistantPanel = () => {+ const os = detectOS()+ const router = useRouter()+ const { ref } = useParams()+ const project = useSelectedProject()+ const queryClient = useQueryClient()+ const { aiAssistantPanel, setAiAssistantPanel } = useAppStateSnapshot()++ const { open, editor, content } = aiAssistantPanel+ const previousEditor = usePrevious(editor)++ const [isAcknowledged, setIsAcknowledged] = useLocalStorage(+ LOCAL_STORAGE_KEYS.SQL_SCRATCH_PAD_BANNER_ACKNOWLEDGED,+ false+ )++ const [chatId, setChatId] = useState(() => uuidv4())+ const [error, setError] = useState<QueryResponseError>()+ const [results, setResults] = useState<undefined | any[]>(undefined)+ const [showResults, setShowResults] = useState(false)+ const [showWarning, setShowWarning] = useState<boolean>(false)+ const [debugThread, setDebugThread] = useState<MessageWithDebug[]>([])++ // [Joshen] JFYI I'm opting to just have the assistant always show and not toggle-able+ // I don't really see any negatives of keeping it open (or benefits from hiding) tbh+ // const [showAssistant, setShowAssistant] = useState(true)+ const title = generateTitle(editor)+ const placeholder = generatePlaceholder(editor)+ const ctaText = generateCTA(editor)+ const editorRef = useRef<IStandaloneCodeEditor | undefined>()+ const editorModel = editorRef.current?.getModel()++ const numResults = (results ?? []).length+ const [errorHeader, ...errorContent] =+ (error?.formattedError?.split('\n') ?? [])?.filter((x: string) => x.length > 0) ?? []+ const entityContext = ASSISTANT_SUPPORT_ENTITIES.find((x) => x.id === editor)++ const { mutate: executeSql, isLoading: isExecuting } = useExecuteSqlMutation({+ onSuccess: async (res) => {+ // [Joshen] If in a specific editor context mode, assume that intent was to create/update+ // a database entity - so close it once success. Otherwise it's in Quick SQL mode and we+ // show the results. Currently though it assumes we're "creating", thinking need to support "updating" too+ if (editor !== null) {+ switch (editor) {+ case 'functions':+ await queryClient.invalidateQueries(sqlKeys.query(ref, ['functions-list']))+ break+ case 'rls-policies':+ await queryClient.invalidateQueries(databasePoliciesKeys.list(ref))+ break+ }++ toast.success(`Successfully created ${entityContext?.name}!`)+ setAiAssistantPanel({ open: false })+ } else {+ setShowResults(true)+ setResults(res.result)+ }+ },+ onError: (error) => {+ setError(error)+ setResults([])+ },+ })++ const { append } = useChat({+ id: chatId,+ api: `${BASE_PATH}/api/ai/sql/generate-v2`,+ // [Joshen] Don't need entity definitions if calling here cause support action+ // via AI here is just to explain code segment, no need for context+ body: {},+ })++ const { mutateAsync: debugSql } = useSqlDebugMutation({ onError: () => {} })++ const onExecuteSql = (skipValidation = false) => {+ setError(undefined)+ setShowWarning(false)++ const query = editorRef.current?.getValue() ?? ''+ if (query.length === 0) return++ if (editor !== undefined && !skipValidation) {+ // [Joshen] Some basic validation logic+ const validated = validateQuery(editor, query)+ if (!validated) {+ return setShowWarning(true)+ }+ }++ executeSql({+ sql: suffixWithLimit(query, 100),+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ handleError: (error) => {+ throw error+ },+ })+ }++ const onFixWithAssistant = async () => {+ if (!error) return++ const messageId = uuidv4()+ const query = editorRef.current?.getValue() ?? ''++ const assistantMessageBefore = generateThreadMessage({+ id: messageId,+ content: 'Thinking...',+ isDebug: true,+ })++ setDebugThread([...debugThread, assistantMessageBefore])++ try {+ const { solution, sql } = await debugSql({+ sql: query,+ errorMessage: error.message,+ })++ const assistantMessageAfter = generateThreadMessage({+ id: messageId,+ content: `${solution}\n\`\`\`sql\n${sql}\n\`\`\``,+ isDebug: true,+ })+ const cleanedMessages = uniqBy([...debugThread, assistantMessageAfter], (m) => m.id)+ setDebugThread(cleanedMessages)+ } catch (error) {+ const assistantMessageAfter = generateThreadMessage({+ id: messageId,+ content: `Hmm, Sorry but I'm unable to find a solution for the error that you're facing`,+ isDebug: true,+ })+ const cleanedMessages = uniqBy([...debugThread, assistantMessageAfter], (m) => m.id)+ setDebugThread(cleanedMessages)+ }+ }++ const onExplainSql = (value: string) => {+ append({+ role: 'user',+ createdAt: new Date(),+ content: `+ Can you explain this section to me in more detail?\n+ ${value}+ `.trim(),+ })+ }++ const updateEditorWithCheckForDiff = useCallback(+ ({ id, diffType, sql }: { id: string; diffType: DiffType; sql: string }) => {+ if (!editorModel) return++ 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: `${sqlAiDisclaimerComment}\n\n${sql}`,+ range: editorModel.getFullModelRange(),+ },+ ])+ } else {+ const currentSql = editorRef.current?.getValue()+ editorRef.current?.executeEdits('apply-ai-message', [+ {+ text: `${currentSql}\n\n${sqlAiDisclaimerComment}\n\n${sql}`,+ range: editorModel.getFullModelRange(),+ },+ ])+ }+ },+ [editorModel]+ )++ useEffect(() => {+ if (open) {+ // [Joshen] Only reset the assistant if the editor changed+ if (previousEditor !== editor) {+ setChatId(uuidv4())+ setError(undefined)+ setShowWarning(false)+ setDebugThread([])+ setResults(undefined)+ setShowResults(false)+ } else {+ // [Joshen] Repopulate the code editor with the content from where the user left off+ // setTimeout is just to give time for the editorRef to get associated+ setTimeout(() => {+ const editorModel = editorRef.current?.getModel()+ if (content && editorModel) {+ editorRef.current?.executeEdits('apply-ai-message', [+ { text: content, range: editorModel.getFullModelRange() },+ ])+ }+ }, 100)+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open])++ // [Joshen] Just to test the concept of a universal assistant of sorts+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && e.code === 'KeyI') {+ setAiAssistantPanel({ open: true, editor: null })+ }+ }+ if (project !== undefined) window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [project])++ // [Joshen] Whenever the deps change recalculate the height of the editor+ useEffect(() => {+ editorRef.current?.layout({ width: 0, height: 0 })+ window.requestAnimationFrame(() => editorRef.current?.layout())+ }, [error, showWarning, isExecuting, numResults, showResults])++ return (+ <Sheet+ open={open}+ onOpenChange={() => {+ if (open) {+ // [Joshen] Save the code content when closing - should allow users to continue from+ // where they left off IF they are opening the assistant again in the same "editor" context+ const existingValue = editorRef.current?.getValue() ?? ''+ setAiAssistantPanel({ open: false, content: existingValue })+ } else {+ setAiAssistantPanel({ open: true })+ }+ }}+ >+ <SheetContent showClose={true} className={cn('flex gap-0 w-[1200px]')}>+ {/* Assistant */}+ <AIAssistant+ id={chatId}+ className="border-r w-1/2"+ debugThread={debugThread}+ onDiff={updateEditorWithCheckForDiff}+ onResetConversation={() => setChatId(uuidv4())}+ />++ {/* Editor */}+ <div className={cn('flex flex-col grow w-1/2')}>+ <SheetHeader className="flex items-center justify-between py-3 pr-12">+ {title}+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="outline"+ icon={<SqlEditor />}+ className="px-1"+ onClick={() => {+ const content = editorRef.current?.getValue() ?? ''+ router.push(`/project/${ref}/sql/new?content=${encodeURIComponent(content)}`)+ setAiAssistantPanel({ open: false })+ }}+ />+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom">Open in SQL Editor</TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ </SheetHeader>+ {editor === null && !isAcknowledged && (+ <Admonition+ showIcon={false}+ type="default"+ title="This is a quick access SQL editor to run queries on your database"+ className="relative m-0 rounded-none border-x-0 border-t-0 [&>div]:m-0"+ >+ <span>+ Queries written here will not be saved and results are limited up to only 100 rows+ </span>+ <Button+ type="text"+ icon={<X />}+ className="px-1.5 absolute top-2 right-2"+ onClick={() => setIsAcknowledged(true)}+ />+ </Admonition>+ )}+ <div className="flex flex-col h-full justify-between">+ <div className="relative flex-grow block">+ <CodeEditor+ id="assistant-code-editor"+ language="pgsql"+ editorRef={editorRef}+ placeholder={placeholder}+ actions={{+ runQuery: { enabled: true, callback: () => onExecuteSql() },+ explainCode: { enabled: true, callback: onExplainSql },+ }}+ />+ </div>+ <div className="flex flex-col">+ {error !== undefined && (+ <Admonition+ type="warning"+ className="m-0 rounded-none border-x-0 border-b-0 [&>div>div>pre]:text-sm [&>div]:flex [&>div]:flex-col [&>div]:gap-y-2"+ title={errorHeader || 'Error running SQL query'}+ description={+ <>+ <div>+ {errorContent.length > 0 ? (+ errorContent.map((errorText: string, i: number) => (+ <pre key={`err-${i}`} className="font-mono text-xs whitespace-pre-wrap">+ {errorText}+ </pre>+ ))+ ) : (+ <p className="font-mono text-xs">{error.error}</p>+ )}+ </div>+ <Button type="default" className="w-min" onClick={() => onFixWithAssistant()}>+ Fix with Assistant+ </Button>+ </>+ }+ />+ )}+ {showWarning && (+ <Admonition+ type="default"+ className="m-0 rounded-none border-x-0 border-b-0 [&>div>pre]:text-sm [&>div]:flex [&>div]:flex-col [&>div]:gap-y-2"+ title={`Your query doesn't seem to be relevant to ${+ entityContext?.id === 'rls-policies'+ ? entityContext?.label+ : `Database ${entityContext?.label}`+ }`}+ description={+ <>+ <p>Are you sure you want to run this query?</p>+ <Button type="default" className="w-min" onClick={() => onExecuteSql(true)}>+ Confirm run query+ </Button>+ </>+ }+ />+ )}+ {results !== undefined && results.length > 0 && (+ <>+ <div className={cn(showResults ? 'h-72 border-t' : 'h-0')}>+ <Results rows={results} />+ </div>+ <div className="flex items-center justify-between border-t bg-surface-100 py-2 pl-2 pr-5">+ <p className="text-xs text-foreground-light">+ {results.length} rows+ {results.length >= 100 && ` (Limited to only 100 rows)`}+ </p>+ <Button size="tiny" type="default" onClick={() => setShowResults(!showResults)}>+ {showResults ? 'Hide' : 'Show'} results+ </Button>+ </div>+ </>+ )}+ {results !== undefined && results.length === 0 && (+ <div className="flex items-center justify-between border-t bg-surface-100 h-[43px] pl-2 pr-5">+ <p className="text-xs text-foreground-light">Success. No rows returned.</p>+ </div>+ )}+ <SheetFooter className="bg-surface-100 flex items-center !justify-end px-5 py-4 w-full border-t">+ <Button+ type="default"+ disabled={isExecuting}+ onClick={() => setAiAssistantPanel({ open: false })}+ >+ Cancel+ </Button>+ <Button+ loading={isExecuting}+ onClick={() => onExecuteSql()}+ iconRight={+ isExecuting ? (+ <Loader2 className="animate-spin" size={10} strokeWidth={1.5} />+ ) : (+ <div className="flex items-center space-x-1">+ {os === 'macos' ? (+ <Command size={10} strokeWidth={1.5} />+ ) : (+ <p className="text-xs text-foreground-light">CTRL</p>+ )}+ <CornerDownLeft size={10} strokeWidth={1.5} />+ </div>+ )+ }+ >+ {ctaText}+ </Button>+ </SheetFooter>+ </div>+ </div>+ </div>+ </SheetContent>+ </Sheet>+ )+}diff --git a/apps/studio/components/ui/AIAssistantPanel/AiAssistant.constants.ts b/apps/studio/components/ui/AIAssistantPanel/AiAssistant.constants.tsnew file mode 100644index 00000000000..e9bc5bdeb55--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/AiAssistant.constants.ts@@ -0,0 +1,10 @@+import { SupportedAssistantEntities } from './AIAssistant.types'++export const ASSISTANT_SUPPORT_ENTITIES: {+ id: SupportedAssistantEntities+ label: string+ name: string+}[] = [+ { id: 'rls-policies', label: 'RLS Policies', name: 'RLS policy' },+ { id: 'functions', label: 'Functions', name: 'database function' },+]diff --git a/apps/studio/components/ui/AIAssistantPanel/ContextBadge.tsx b/apps/studio/components/ui/AIAssistantPanel/ContextBadge.tsxnew file mode 100644index 00000000000..ba205b176e0--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/ContextBadge.tsx@@ -0,0 +1,33 @@+import { X } from 'lucide-react'+import { ReactNode } from 'react'+import { Tooltip_Shadcn_, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_ } from 'ui'++interface ContextBadgeProps {+ label: string+ value: string+ tooltip?: ReactNode+ onRemove?: () => void+}++export const ContextBadge = ({ label, value, tooltip, onRemove }: ContextBadgeProps) => {+ return (+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <div className="border bg-surface-200 rounded px-2 py-1 flex items-center justify-between gap-x-2">+ <div className="flex items-center gap-x-1">+ <span className="text-foreground-lighter text-xs">{label}</span>+ <span className="text-xs">{value}</span>+ </div>+ {onRemove !== undefined && (+ <X+ size={12}+ className="text-foreground-light hover:text-foreground transition cursor-pointer"+ onClick={() => onRemove()}+ />+ )}+ </div>+ </TooltipTrigger_Shadcn_>+ {tooltip !== undefined && <TooltipContent_Shadcn_>{tooltip}</TooltipContent_Shadcn_>}+ </Tooltip_Shadcn_>+ )+}diff --git a/apps/studio/components/ui/AIAssistantPanel/DropdownScrollArea.tsx b/apps/studio/components/ui/AIAssistantPanel/DropdownScrollArea.tsxnew file mode 100644index 00000000000..1bbe09c0190--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/DropdownScrollArea.tsx@@ -0,0 +1,36 @@+import { PropsWithChildren, useEffect } from 'react'+import { ScrollArea } from 'ui'++interface DropdownScrollAreaProps {+ id?: string+ className?: string+}++// [Joshen] This is a temporary solution to a really odd behavior i've observed with the components in Shadcn+// Specifically if we're using a ScrollArea (or even just anything with overflow) within a DropdownMenu, within a Sheet+// The mouse wheel event to scroll in the ScrollArea is somehow getting ignored in this specific context, hence the fix here++export const DropdownScrollArea = ({+ id,+ className,+ children,+}: PropsWithChildren<DropdownScrollAreaProps>) => {+ useEffect(() => {+ const scrollFix = (e: WheelEvent) => e.stopPropagation()++ if (id) {+ const el = document.getElementById(id)+ if (el) {+ el.addEventListener('wheel', scrollFix, { passive: false })+ return () => el.removeEventListener('wheel', scrollFix)+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])++ return (+ <ScrollArea id={id} className={className}>+ {children}+ </ScrollArea>+ )+}diff --git a/apps/studio/components/ui/AIAssistantPanel/EntitiesDropdownMenu.tsx b/apps/studio/components/ui/AIAssistantPanel/EntitiesDropdownMenu.tsxnew file mode 100644index 00000000000..d301fb5814e--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/EntitiesDropdownMenu.tsx@@ -0,0 +1,110 @@+import { useEntityTypesQuery } from 'data/entity-types/entity-types-infinite-query'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'+import { debounce } from 'lodash'+import { Check, Loader2, Search } from 'lucide-react'+import { useCallback, useState } from 'react'+import {+ Command_Shadcn_,+ CommandEmpty_Shadcn_,+ CommandGroup_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+ ScrollArea,+} from 'ui'+import { Input } from 'ui-patterns/DataInputs/Input'+import { DropdownScrollArea } from './DropdownScrollArea'+import { Admonition } from 'ui-patterns'++interface EntitiesDropdownMenuProps {+ selectedSchemas: string[]+ selectedEntities: { schema: string; name: string }[]+ onToggleEntity: (value: { schema: string; name: string }) => void+}++export const EntitiesDropdownMenu = ({+ selectedSchemas,+ selectedEntities,+ onToggleEntity,+}: EntitiesDropdownMenuProps) => {+ const project = useSelectedProject()+ const [search, setSearch] = useState('')++ // [Joshen] Not gonna do infinite loading here, but rather just try to load sufficient tables+ // I reckon users will opt to just search if there's many tables here given the small real estate+ const {+ data: entitiesData,+ error,+ isLoading,+ isFetching,+ isError,+ } = useEntityTypesQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ schemas: selectedSchemas,+ limit: 100,+ search: search.length === 0 ? undefined : search,+ })+ const entities = (+ entitiesData?.pages[0].data.entities ? [...entitiesData?.pages[0].data.entities] : []+ ).sort((a, b) => (a.name > b.name ? 0 : -1))++ // eslint-disable-next-line react-hooks/exhaustive-deps+ const searchInputHandler = useCallback(debounce(setSearch, 1000), [])++ if (isError) {+ return (+ <Admonition+ type="default"+ className="m-0 rounded-none border-0 [&>h5]:text-xs [&>div]:text-xs"+ showIcon={false}+ title="Failed to retrieve tables"+ description={`Error: ${(error as any)?.message ?? 'Unknown'}`}+ />+ )+ }++ return (+ <Command_Shadcn_>+ <CommandList_Shadcn_>+ {/* Separate input for async searching */}+ <Input+ autoFocus+ placeholder="Find table..."+ icon={<Search size={14} />}+ className="text-xs outline-none rounded-b-none border-0 border-b pl-9 pr-7"+ onChange={(e) => searchInputHandler(e.target.value)}+ actions={+ (isLoading || isFetching) && (+ <Loader2 key="hint" size={14} className="mr-1 animate-spin" />+ )+ }+ />+ <CommandEmpty_Shadcn_>No tables found</CommandEmpty_Shadcn_>+ <CommandGroup_Shadcn_>+ <DropdownScrollArea+ id="tables-scroll"+ className={(entities || []).length > 7 ? 'h-[210px]' : ''}+ >+ {entities?.map((entity) => (+ <CommandItem_Shadcn_+ key={entity.id}+ value={entity.id.toString()}+ className="justify-between"+ onSelect={() => onToggleEntity({ schema: entity.schema, name: entity.name })}+ onClick={() => onToggleEntity({ schema: entity.schema, name: entity.name })}+ >+ <span className="flex gap-x-1">+ <span className="text-foreground-lighter">{entity.schema}</span>+ <span>{entity.name}</span>+ </span>+ {selectedEntities.find(+ (x) => x.name === entity.name && x.schema === entity.schema+ ) && <Check className="text-brand" strokeWidth={2} size={16} />}+ </CommandItem_Shadcn_>+ ))}+ </DropdownScrollArea>+ </CommandGroup_Shadcn_>+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ )+}diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.tsxnew file mode 100644index 00000000000..3d20ff3c6c6--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/Message.tsx@@ -0,0 +1,146 @@+import dayjs from 'dayjs'+import { noop } from 'lodash'+import Image from 'next/image'+import { PropsWithChildren, memo, useMemo } from 'react'+import ReactMarkdown from 'react-markdown'+import remarkGfm from 'remark-gfm'+import { AiIconAnimation, Badge, cn, markdownComponents, WarningIcon } from 'ui'++import { DiffType } from 'components/interfaces/SQLEditor/SQLEditor.types'+import { useProfile } from 'lib/profile'+import { MessagePre } from './MessagePre'++interface MessageProps {+ name?: string+ role: 'function' | 'system' | 'user' | 'assistant' | 'data' | 'tool'+ content?: string+ createdAt?: number+ isDebug?: boolean+ isSelected?: boolean+ action?: React.ReactNode+ context?: { entity: string; schemas: string[]; tables: string[] }+ onDiff?: (type: DiffType, s: string) => void+ variant?: 'default' | 'warning'+}++export const Message = memo(function Message({+ name,+ role,+ content,+ createdAt,+ isDebug,+ isSelected = false,+ context,+ children,+ action = null,+ variant = 'default',+ onDiff = noop,+}: PropsWithChildren<MessageProps>) {+ const { profile } = useProfile()+ const isUser = role === 'user'++ const icon = useMemo(() => {+ return role === 'assistant' ? (+ <AiIconAnimation+ loading={content === 'Thinking...'}+ className="[&>div>div]:border-black dark:[&>div>div]:border-white"+ />+ ) : (+ <div className="relative border shadow-lg w-8 h-8 rounded-full overflow-hidden">+ <Image+ src={`https://github.com/${profile?.username}.png` || ''}+ width={30}+ height={30}+ alt="avatar"+ className="relative"+ />+ </div>+ )+ }, [content, profile?.username, role])++ const formattedContext =+ context !== undefined+ ? Object.entries(context)+ .filter(([_, value]) => value.length > 0)+ .map(([key, value]) => {+ return `${key.charAt(0).toUpperCase() + key.slice(1)}: ${Array.isArray(value) ? value.join(', ') : value}`+ })+ .join(' • ')+ : undefined++ if (!content) return null++ return (+ <div+ className={cn(+ 'flex flex-col py-4 gap-4 px-5 text-foreground-light text-sm border-t first:border-0',+ variant === 'warning' && 'bg-warning-200',+ isUser && 'bg-default'+ )}+ >+ <div className="flex justify-between items-center">+ <div className="flex gap-x-3 items-center">+ {variant === 'warning' ? <WarningIcon className="w-6 h-6" /> : icon}++ <div className="flex flex-col -gap-y-1">+ <div className="flex items-center gap-x-3">+ <span className="text-sm">{!isUser ? 'Assistant' : name ? name : 'You'}</span>+ {createdAt && (+ <span+ className={cn(+ 'text-xs text-foreground-muted',+ variant === 'warning' && 'text-warning-500'+ )}+ >+ {dayjs(createdAt).fromNow()}+ </span>+ )}+ </div>+ {role === 'user' && context !== undefined && (+ <span className="text-xs text-foreground-lighter">{formattedContext}</span>+ )}+ </div>++ {isDebug && <Badge variant="warning">Debug request</Badge>}+ </div>{' '}+ {action}+ </div>++ <ReactMarkdown+ className="gap-x-2.5 gap-y-4 flex flex-col [&>*>code]:text-xs [&>*>*>code]:text-xs"+ remarkPlugins={[remarkGfm]}+ components={{+ ...markdownComponents,+ pre: (props: any) => {+ return (+ <MessagePre+ onDiff={onDiff}+ className={cn(+ 'transition [&>div>pre]:max-w-full',+ isSelected ? '[&>div>pre]:!border-stronger [&>div>pre]:!bg-surface-200' : ''+ )}+ >+ {props.children[0].props.children}+ </MessagePre>+ )+ },+ ol: (props: any) => {+ return <ol className="flex flex-col gap-y-4">{props.children}</ol>+ },+ li: (props: any) => {+ return <li className="[&>pre]:mt-2">{props.children}</li>+ },+ h3: (props: any) => {+ return <h3 className="underline">{props.children}</h3>+ },+ code: (props: any) => {+ return <code className={cn('text-xs', props.className)}>{props.children}</code>+ },+ }}+ >+ {content}+ </ReactMarkdown>+ {children}+ </div>+ )+})diff --git a/apps/studio/components/ui/AIAssistantPanel/MessagePre.tsx b/apps/studio/components/ui/AIAssistantPanel/MessagePre.tsxnew file mode 100644index 00000000000..414b5fc0917--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/MessagePre.tsx@@ -0,0 +1,113 @@+import { InsertCode, ReplaceCode } from 'icons'+import { Check, Copy } from 'lucide-react'+import { useEffect, useState } from 'react'+import { format } from 'sql-formatter'+import {+ Button,+ CodeBlock,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,+ cn,+} from 'ui'++import { useSendEventMutation } from 'data/telemetry/send-event-mutation'+import { DiffType } from 'components/interfaces/SQLEditor/SQLEditor.types'++interface MessagePreProps {+ onDiff: (type: DiffType, s: string) => void+ children: string[]+ className?: string+}++export const MessagePre = ({ onDiff, children, className }: MessagePreProps) => {+ const [copied, setCopied] = useState(false)++ const { mutate: sendEvent } = useSendEventMutation()++ useEffect(() => {+ if (!copied) return+ const timer = setTimeout(() => setCopied(false), 2000)+ return () => clearTimeout(timer)+ }, [copied])++ let formatted = (children || [''])[0]+ try {+ formatted = format(formatted, { language: 'postgresql', keywordCase: 'upper' })+ } catch {}++ if (formatted.length === 0) {+ return null+ }++ function handleCopy(formatted: string) {+ navigator.clipboard.writeText(formatted).then()+ setCopied(true)+ }++ return (+ <pre className={cn('rounded-md relative group', className)}>+ <CodeBlock+ value={formatted}+ language="sql"+ className={cn(+ '!bg-transparent !py-3 !px-3.5 prose dark:prose-dark',+ // change the look of the code block. The flex hack is so that the code is wrapping since+ // every word is a separate span+ '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap [&>code]:block'+ )}+ hideCopy+ hideLineNumbers+ />+ <div className="absolute top-2 right-2 bg-surface-100 border-muted border rounded-lg h-[28px] hidden group-hover:block">+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="text"+ size="tiny"+ onClick={() => {+ onDiff(DiffType.Addition, formatted)+ sendEvent({+ category: 'sql_editor_ai_assistant_v2',+ label: 'sql-editor-ai-assistant-v2',+ action: 'ai_suggestion_inserted',+ })+ }}+ >+ <InsertCode className="h-4 w-4 text-foreground-light" strokeWidth={1.5} />+ </Button>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom" className="font-sans">+ Insert code+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>++ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="text"+ size="tiny"+ onClick={() => {+ handleCopy(formatted)+ sendEvent({+ category: 'sql_editor_ai_assistant_v2',+ label: 'sql-editor-ai-assistant-v2',+ action: 'ai_suggestion_copied',+ })+ }}+ >+ {copied ? (+ <Check size={16} className="text-brand-600" />+ ) : (+ <Copy size={16} className="text-foreground-light" strokeWidth={1.5} />+ )}+ </Button>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom" className="font-sans">+ Copy code+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ </div>+ </pre>+ )+}diff --git a/apps/studio/components/ui/AIAssistantPanel/SchemasDropdownMenu.tsx b/apps/studio/components/ui/AIAssistantPanel/SchemasDropdownMenu.tsxnew file mode 100644index 00000000000..6db2472077c--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/SchemasDropdownMenu.tsx@@ -0,0 +1,61 @@+import {+ cn,+ Command_Shadcn_,+ CommandEmpty_Shadcn_,+ CommandGroup_Shadcn_,+ CommandInput_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+} from 'ui'+import { DropdownScrollArea } from './DropdownScrollArea'+import { Check } from 'lucide-react'+import { useSchemasQuery } from 'data/database/schemas-query'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'++interface SchemasDropdownMenuProps {+ selectedSchemas: string[]+ onToggleSchema: (schema: string) => void+}++export const SchemasDropdownMenu = ({+ selectedSchemas,+ onToggleSchema,+}: SchemasDropdownMenuProps) => {+ const project = useSelectedProject()++ const { data: schemaDatas } = useSchemasQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })+ const schemas = (schemaDatas || []).sort((a, b) => a.name.localeCompare(b.name))++ return (+ <Command_Shadcn_>+ <CommandInput_Shadcn_ autoFocus placeholder="Find schema..." />+ <CommandList_Shadcn_>+ <CommandEmpty_Shadcn_>No schemas found</CommandEmpty_Shadcn_>+ <CommandGroup_Shadcn_>+ <DropdownScrollArea+ id="schema-scroll"+ className={cn((schemas || []).length > 7 ? 'h-[210px]' : '')}+ >+ {schemas?.map((schema) => (+ <CommandItem_Shadcn_+ key={schema.id}+ value={schema.id.toString()}+ className="justify-between"+ onSelect={() => onToggleSchema(schema.name)}+ onClick={() => onToggleSchema(schema.name)}+ >+ {schema.name}+ {selectedSchemas.includes(schema.name) && (+ <Check className="text-brand" strokeWidth={2} size={16} />+ )}+ </CommandItem_Shadcn_>+ ))}+ </DropdownScrollArea>+ </CommandGroup_Shadcn_>+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ )+}diff --git a/apps/studio/components/ui/CodeEditor/CodeEditor.tsx b/apps/studio/components/ui/CodeEditor/CodeEditor.tsxindex 24eeb0d677d..62c08d73b6b 100644--- a/apps/studio/components/ui/CodeEditor/CodeEditor.tsx+++ b/apps/studio/components/ui/CodeEditor/CodeEditor.tsx@@ -1,13 +1,23 @@-import Editor, { EditorProps, Monaco, OnChange, OnMount } from '@monaco-editor/react'+import Editor, { EditorProps, Monaco, OnChange, OnMount, useMonaco } from '@monaco-editor/react'import { merge, noop } from 'lodash'import { editor } from 'monaco-editor'-import { useEffect, useRef, useState } from 'react'+import { MutableRefObject, useEffect, useRef, useState } from 'react'import { Markdown } from 'components/interfaces/Markdown'import { timeout } from 'lib/helpers'import { cn } from 'ui'import { Loading } from '../Loading'import { alignEditor } from './CodeEditor.utils'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'+import { formatQuery } from 'data/sql/format-sql-query'++type CodeEditorActions = { enabled: boolean; callback: (value: any) => void }+const DEFAULT_ACTIONS = {+ runQuery: { enabled: false, callback: noop },+ explainCode: { enabled: false, callback: noop },+ formatDocument: { enabled: true, callback: noop },+ placeholderFill: { enabled: true },+}interface CodeEditorProps {id: string@@ -15,15 +25,21 @@ interface CodeEditorProps {autofocus?: booleandefaultValue?: stringisReadOnly?: boolean- onInputChange?: (value?: string) => void- onInputRun?: (value: string) => voidhideLineNumbers?: booleanclassName?: stringloading?: booleanoptions?: EditorProps['options']value?: stringplaceholder?: string- disableTabToUsePlaceholder?: boolean+ /* Determines what actions to add for code editor context menu */+ actions?: Partial<{+ runQuery: CodeEditorActions+ formatDocument: CodeEditorActions+ placeholderFill: Omit<CodeEditorActions, 'callback'>+ explainCode: CodeEditorActions+ }>+ editorRef?: MutableRefObject<editor.IStandaloneCodeEditor | undefined>+ onInputChange?: (value?: string) => void}const CodeEditor = ({@@ -33,23 +49,64 @@ const CodeEditor = ({autofocus = true,isReadOnly = false,hideLineNumbers = false,- onInputChange = noop,- onInputRun = noop,className,loading,options,value,placeholder,- disableTabToUsePlaceholder = false,+ actions = DEFAULT_ACTIONS,+ editorRef: editorRefProps,+ onInputChange = noop,}: CodeEditorProps) => {- const hasValue = useRef<any>()+ const monaco = useMonaco()+ const project = useSelectedProject()- const editorRef = useRef<editor.IStandaloneCodeEditor>()+ const hasValue = useRef<any>()+ const ref = useRef<editor.IStandaloneCodeEditor>()+ const editorRef = editorRefProps || refconst monacoRef = useRef<Monaco>()+ const { runQuery, placeholderFill, formatDocument, explainCode } = {+ ...DEFAULT_ACTIONS,+ ...actions,+ }+const showPlaceholderDefault = placeholder !== undefined && (value ?? '').trim().length === 0const [showPlaceholder, setShowPlaceholder] = useState(showPlaceholderDefault)+ const optionsMerged = merge(+ {+ tabSize: 2,+ fontSize: 13,+ readOnly: isReadOnly,+ minimap: { enabled: false },+ wordWrap: 'on',+ fixedOverflowWidgets: true,+ contextmenu: true,+ lineNumbers: hideLineNumbers ? 'off' : undefined,+ glyphMargin: hideLineNumbers ? false : undefined,+ lineNumbersMinChars: hideLineNumbers ? 0 : 4,+ folding: hideLineNumbers ? false : undefined,+ scrollBeyondLastLine: false,+ },+ options+ )++ const formatPgsql = async (value: string) => {+ try {+ if (!project) throw new Error('No project')+ const formatted = await formatQuery({+ projectRef: project.ref,+ connectionString: project.connectionString,+ sql: value,+ })+ return formatted.result+ } catch (error) {+ console.error('formatPgsql error:', error)+ return value+ }+ }+const onMount: OnMount = async (editor, monaco) => {editorRef.current = editormonacoRef.current = monaco@@ -59,7 +116,7 @@ const CodeEditor = ({hasValue.current.set(value !== undefined && value.trim().length > 0)setShowPlaceholder(showPlaceholderDefault)- if (!disableTabToUsePlaceholder) {+ if (placeholderFill.enabled) {editor.addCommand(monaco.KeyCode.Tab,() => {@@ -72,7 +129,7 @@ const CodeEditor = ({.split('\n\n').join('\n').replaceAll('*', '')- .replaceAll(' ', ''),+ .replaceAll(' ', ' '),},])},@@ -80,19 +137,36 @@ const CodeEditor = ({)}- editor.addAction({- id: 'supabase',- label: 'Run Query',- keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.Enter],- contextMenuGroupId: 'operation',- contextMenuOrder: 0,- run: async () => {- const selectedValue = (editorRef?.current as any)- .getModel()- .getValueInRange((editorRef?.current as any)?.getSelection())- onInputRun(selectedValue || (editorRef?.current as any)?.getValue())- },- })+ if (runQuery.enabled) {+ editor.addAction({+ id: 'run-query',+ label: 'Run Query',+ keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.Enter],+ contextMenuGroupId: 'operation',+ contextMenuOrder: 0,+ run: () => {+ const selectedValue = (editorRef?.current as any)+ .getModel()+ .getValueInRange((editorRef?.current as any)?.getSelection())+ runQuery.callback(selectedValue || (editorRef?.current as any)?.getValue())+ },+ })+ }++ if (explainCode.enabled) {+ editor.addAction({+ id: 'explain-code',+ label: 'Explain Code',+ contextMenuGroupId: 'operation',+ contextMenuOrder: 1,+ run: () => {+ const selectedValue = (editorRef?.current as any)+ .getModel()+ .getValueInRange((editorRef?.current as any)?.getSelection())+ explainCode.callback(selectedValue)+ },+ })+ }const model = editor.getModel()if (model) {@@ -110,31 +184,13 @@ const CodeEditor = ({onInputChange(value)}- const optionsMerged = merge(- {- tabSize: 2,- fontSize: 13,- readOnly: isReadOnly,- minimap: { enabled: false },- wordWrap: 'on',- fixedOverflowWidgets: true,- contextmenu: true,- lineNumbers: hideLineNumbers ? 'off' : undefined,- glyphMargin: hideLineNumbers ? false : undefined,- lineNumbersMinChars: hideLineNumbers ? 0 : 4,- folding: hideLineNumbers ? false : undefined,- scrollBeyondLastLine: false,- },- options- )-useEffect(() => {setShowPlaceholder(showPlaceholderDefault)}, [showPlaceholderDefault])useEffect(() => {if (- !disableTabToUsePlaceholder &&+ placeholderFill.enabled &&editorRef.current !== undefined &&monacoRef.current !== undefined) {@@ -160,7 +216,22 @@ const CodeEditor = ({'!hasValue')}- }, [placeholder, disableTabToUsePlaceholder])+ }, [placeholder, placeholderFill.enabled])++ useEffect(() => {+ if (monaco && project && formatDocument.enabled) {+ const formatProvider = monaco.languages.registerDocumentFormattingEditProvider('pgsql', {+ async provideDocumentFormattingEdits(model: any) {+ const value = model.getValue()+ const formatted = await formatPgsql(value)+ formatDocument.callback(formatted)+ return [{ range: model.getFullModelRange(), text: formatted }]+ },+ })+ return () => formatProvider.dispose()+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [monaco, project, formatDocument.enabled])return (<>diff --git a/apps/studio/components/ui/SchemaComboBox.tsx b/apps/studio/components/ui/SchemaComboBox.tsxindex dc93562dc9c..f4810f6df7c 100644--- a/apps/studio/components/ui/SchemaComboBox.tsx+++ b/apps/studio/components/ui/SchemaComboBox.tsx@@ -19,6 +19,7 @@ import {Popover_Shadcn_,ScrollArea,} from 'ui'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'interface SchemaComboBoxProps {className?: string@@ -44,7 +45,7 @@ export const SchemaComboBox = ({}: SchemaComboBoxProps) => {const [open, setOpen] = useState(false)- const { project } = useProjectContext()+ const project = useSelectedProject()const {data,isLoading: isSchemasLoading,diff --git a/apps/studio/data/database/entity-definitions-query.ts b/apps/studio/data/database/entity-definitions-query.tsindex 0e820869fcf..e288f81fa0e 100644--- a/apps/studio/data/database/entity-definitions-query.ts+++ b/apps/studio/data/database/entity-definitions-query.ts@@ -3,7 +3,13 @@ import { ExecuteSqlData, ExecuteSqlError, useExecuteSqlQuery } from '../sql/execimport { CREATE_PG_GET_TABLEDEF_SQL } from './database-query-constants'import { databaseKeys } from './keys'-export const getEntityDefinitionsQuery = (schemas: string[], limit = 100) => {+export const getEntityDefinitionsQuery = ({+ schemas,+ limit = 100,+}: {+ schemas: string[]+ limit?: number+}) => {const sql = /* SQL */ `${CREATE_PG_GET_TABLEDEF_SQL}@@ -99,7 +105,7 @@ export const useEntityDefinitionsQuery = <{projectRef,connectionString,- sql: getEntityDefinitionsQuery(schemas, limit),+ sql: getEntityDefinitionsQuery({ schemas, limit }),queryKey: databaseKeys.entityDefinitions(projectRef, schemas),},{diff --git a/apps/studio/data/entity-types/entity-types-infinite-query.ts b/apps/studio/data/entity-types/entity-types-infinite-query.tsindex 470bd56933b..3931fb892e9 100644--- a/apps/studio/data/entity-types/entity-types-infinite-query.ts+++ b/apps/studio/data/entity-types/entity-types-infinite-query.ts@@ -5,7 +5,7 @@ import { entityTypeKeys } from './keys'export type EntityTypesVariables = {projectRef?: string- schema?: string+ schemas?: string[]search?: stringlimit?: numberpage?: number@@ -24,7 +24,7 @@ export async function getEntityTypes({projectRef,connectionString,- schema = 'public',+ schemas = ['public'],search,limit = 100,page = 0,@@ -67,7 +67,7 @@ export async function getEntityTypes()or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES'))- and nc.nspname = '${schema}'+ and nc.nspname in (${schemas.map((x) => `'${x}'`)})${search ? `and c.relname ilike '%${search}%'` : ''}order by ${innerOrderBy}limit ${limit}@@ -111,7 +111,7 @@ export const useEntityTypesQuery = <TData = EntityTypesData>({projectRef,connectionString,- schema = 'public',+ schemas = ['public'],search,limit = 100,sort,@@ -123,10 +123,19 @@ export const useEntityTypesQuery = <TData = EntityTypesData>(}: UseInfiniteQueryOptions<EntityTypesData, EntityTypesError, TData> = {}) =>useInfiniteQuery<EntityTypesData, EntityTypesError, TData>(- entityTypeKeys.list(projectRef, { schema, search, sort, limit, filterTypes }),+ entityTypeKeys.list(projectRef, { schemas, search, sort, limit, filterTypes }),({ signal, pageParam }) =>getEntityTypes(- { projectRef, connectionString, schema, search, limit, page: pageParam, sort, filterTypes },+ {+ projectRef,+ connectionString,+ schemas,+ search,+ limit,+ page: pageParam,+ sort,+ filterTypes,+ },signal),{diff --git a/apps/studio/data/entity-types/keys.ts b/apps/studio/data/entity-types/keys.tsindex c04fc7dbd12..7e3505fdffc 100644--- a/apps/studio/data/entity-types/keys.ts+++ b/apps/studio/data/entity-types/keys.ts@@ -2,7 +2,7 @@ export const entityTypeKeys = {list: (projectRef: string | undefined,params?: {- schema?: string+ schemas?: string[]search?: stringsort?: 'alphabetical' | 'grouped-alphabetical'limit?: numberdiff --git a/apps/studio/lib/constants/index.ts b/apps/studio/lib/constants/index.tsindex da484ef951d..c1e359bda6f 100644--- a/apps/studio/lib/constants/index.ts+++ b/apps/studio/lib/constants/index.ts@@ -36,8 +36,11 @@ export const LOCAL_STORAGE_KEYS = {UI_PREVIEW_NAVIGATION_LAYOUT: 'supabase-ui-preview-nav-layout',UI_PREVIEW_API_SIDE_PANEL: 'supabase-ui-api-side-panel',UI_PREVIEW_CLS: 'supabase-ui-cls',+ UI_PREVIEW_FUNCTIONS_ASSISTANT: 'supabase-ui-functions-assistant',UI_ONBOARDING_NEW_PAGE_SHOWN: 'supabase-ui-onboarding-new-page-shown',+ SQL_SCRATCH_PAD_BANNER_ACKNOWLEDGED: 'supabase-sql-scratch-pad-banner-acknowledged',+DASHBOARD_HISTORY: (ref: string) => `dashboard-history-${ref}`,SQL_EDITOR_INTELLISENSE: 'supabase_sql-editor-intellisense-enabled',diff --git a/apps/studio/pages/_app.tsx b/apps/studio/pages/_app.tsxindex 6c7899c806b..63fa4d1a825 100644--- a/apps/studio/pages/_app.tsx+++ b/apps/studio/pages/_app.tsx@@ -41,6 +41,7 @@ import { StudioCommandMenu } from 'components/interfaces/App/CommandMenu'import { FeaturePreviewContextProvider } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'import FeaturePreviewModal from 'components/interfaces/App/FeaturePreview/FeaturePreviewModal'import { GenerateSql } from 'components/interfaces/SqlGenerator/SqlGenerator'+import { AiAssistantPanel } from 'components/ui/AIAssistantPanel/AIAssistantPanel'import { ErrorBoundaryState } from 'components/ui/ErrorBoundaryState'import FlagProvider from 'components/ui/Flag/FlagProvider'import PageTelemetry from 'components/ui/PageTelemetry'@@ -147,6 +148,7 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {<StudioCommandMenu /><GenerateSql /><FeaturePreviewModal />+ <AiAssistantPanel /></FeaturePreviewContextProvider></AppBannerWrapper><SonnerToaster position="top-right" />diff --git a/apps/studio/pages/api/ai/sql/generate-v2.ts b/apps/studio/pages/api/ai/sql/generate-v2.tsindex d529568da0b..d21b384a479 100644--- a/apps/studio/pages/api/ai/sql/generate-v2.ts+++ b/apps/studio/pages/api/ai/sql/generate-v2.ts@@ -1,5 +1,6 @@import { StreamingTextResponse } from 'ai'import { chatSql } from 'ai-commands/edge'+import { SupportedAssistantEntities } from 'components/ui/AIAssistantPanel/AIAssistant.types'import { NextRequest } from 'next/server'import OpenAI from 'openai'@@ -70,12 +71,13 @@ async function handlePost(request: NextRequest) {messages: { content: string; role: 'user' | 'assistant' }[]existingSql?: stringentityDefinitions: string[]+ context?: SupportedAssistantEntities}>)- const { messages, existingSql, entityDefinitions } = body+ const { messages, existingSql, entityDefinitions, context } = bodytry {- const stream = await chatSql(openai, messages, existingSql, entityDefinitions)+ const stream = await chatSql(openai, messages, existingSql, entityDefinitions, context)return new StreamingTextResponse(stream)} catch (error) {if (error instanceof Error) {diff --git a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx b/apps/studio/pages/project/[ref]/logs/explorer/index.tsxindex cb349d96b56..f2640fc356a 100644--- a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx+++ b/apps/studio/pages/project/[ref]/logs/explorer/index.tsx@@ -366,7 +366,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {language="pgsql" // its bq sql but monaco doesn't have a language for itdefaultValue={warehouseEditorValue}onInputChange={(v) => setWarehouseEditorValue(v || '')}- onInputRun={handleRun}+ actions={{ runQuery: { enabled: true, callback: handleRun } }}/>) : (<CodeEditor@@ -374,7 +374,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {language="pgsql"defaultValue={editorValue}onInputChange={(v) => setEditorValue(v || '')}- onInputRun={handleRun}+ actions={{ runQuery: { enabled: true, callback: handleRun } }}/>)}</ResizablePanel>diff --git a/apps/studio/public/img/previews/functions-assistant.png b/apps/studio/public/img/previews/functions-assistant.pngnew file mode 100644index 00000000000..7fc3f94c8f7Binary files /dev/null and b/apps/studio/public/img/previews/functions-assistant.png differdiff --git a/apps/studio/state/app-state.ts b/apps/studio/state/app-state.tsindex 7f4246a26dc..3e5902c7cc4 100644--- a/apps/studio/state/app-state.ts+++ b/apps/studio/state/app-state.ts@@ -1,3 +1,4 @@+import { SupportedAssistantEntities } from 'components/ui/AIAssistantPanel/AIAssistant.types'import { LOCAL_STORAGE_KEYS } from 'lib/constants'import { proxy, snapshot, useSnapshot } from 'valtio'@@ -9,6 +10,12 @@ const EMPTY_DASHBOARD_HISTORY: {editor: undefined,}+type AiAssistantPanelType = {+ open: boolean+ editor?: SupportedAssistantEntities | null+ content?: string+}+export const appState = proxy({// [Joshen] Last visited "entity" for any page that we wanna trackdashboardHistory: EMPTY_DASHBOARD_HISTORY,@@ -92,6 +99,11 @@ export const appState = proxy({setNavigationPanelJustClosed: (value: boolean) => {appState.navigationPanelJustClosed = value},++ aiAssistantPanel: { open: false, editor: null, content: '' } as AiAssistantPanelType,+ setAiAssistantPanel: (value: AiAssistantPanelType) => {+ appState.aiAssistantPanel = { ...appState.aiAssistantPanel, ...value }+ },})export const getAppStateSnapshot = () => snapshot(appState)diff --git a/packages/ai-commands/src/sql/chat.ts b/packages/ai-commands/src/sql/chat.tsindex 3b8deb258f0..4b8457cd74f 100644--- a/packages/ai-commands/src/sql/chat.ts+++ b/packages/ai-commands/src/sql/chat.ts@@ -13,26 +13,55 @@ export async function chatSql(openai: OpenAI,messages: Message[],existingSql?: string,- entityDefinitions?: string[]+ entityDefinitions?: string[],+ context?: 'rls-policies' | 'functions'): Promise<ReadableStream<Uint8Array>> {const initMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [{role: 'system',content: stripIndent`- The generated SQL (must be valid SQL).- - For primary keys, always use "id bigint primary key generated always as identity" (not serial)- - Prefer creating foreign key references in the create statement- - Prefer 'text' over 'varchar'- - Prefer 'timestamp with time zone' over 'date'- - Use vector(384) data type for any embedding/vector related query+ The generated SQL (must be valid SQL), and must adhere to the following:- Always use double apostrophe in SQL strings (eg. 'Night''s watch')- Always use semicolons- Output as markdown- Always include code snippets if available+ - Use vector(384) data type for any embedding/vector related query++ When generating tables, do the following:+ - For primary keys, always use "id bigint primary key generated always as identity" (not serial)+ - Prefer creating foreign key references in the create statement+ - Prefer 'text' over 'varchar'+ - Prefer 'timestamp with time zone' over 'date'++ Feel free to suggest corrections for suspected typos.`,},]+ if (context) {+ // [Joshen] Thinking how we can prompt-engineer to give even better results, what I have below+ // is definitely not optimal at all, but just to get an idea started+ const generateInstructionsBasedOnContext = () => {+ switch (context) {+ case 'rls-policies':+ return stripIndent`+ You're a Supabase Postgres expert in writing row level security policies. Your purpose is to+ generate a policy with the constraints given by the user. You will be provided a schema+ on which the policy should be applied.`+ case 'functions':+ return stripIndent`+ You're a Supabase Postgres expert in writing database functions. Your purpose is to generate a+ database function with the constraints given by the user. The output may also include a database trigger+ if the function returns a type of trigger. When generating functions, do the following:+ - If the function returns a trigger type, ensure that it uses security definer, otherwise default to security invoker. Include this in the create functions SQL statement.+ - Ensure to set the search_path configuration parameter as '', include this in the create functions SQL statement.+ Please make sure that all queries are valid Postgres SQL queries.+ `+ }+ }+ initMessages.push({ role: 'user', content: generateInstructionsBasedOnContext() })+ }+if (entityDefinitions) {const definitions = codeBlock`${entityDefinitions.join('\n\n')}`initMessages.push({@@ -48,6 +77,7 @@ export async function chatSql(content: codeBlock`Here is the existing SQL I wrote for reference:${sqlBlock}+ Any SQL output should follow the casing of the existing SQL that I've written.`.trim(),})}diff --git a/packages/ui-patterns/AssistantChat/AssistantChatForm.tsx b/packages/ui-patterns/AssistantChat/AssistantChatForm.tsxindex 71885449bd0..4e384513e0b 100644--- a/packages/ui-patterns/AssistantChat/AssistantChatForm.tsx+++ b/packages/ui-patterns/AssistantChat/AssistantChatForm.tsx@@ -68,7 +68,12 @@ const AssistantChatForm = React.forwardRef<HTMLFormElement, FormProps>(}return (- <form ref={formRef} className="relative" {...props} onSubmit={onSubmit}>+ <form+ ref={formRef}+ {...props}+ onSubmit={onSubmit}+ className={cn('relative', props.className)}+ >{icon && (<div className={cn('absolute', 'top-2 left-2', 'ml-1 w-6 h-6 rounded-full bg-dbnew')}>{icon}diff --git a/packages/ui-patterns/admonition.tsx b/packages/ui-patterns/admonition.tsxindex 0754ec46867..eb4943d35b2 100644--- a/packages/ui-patterns/admonition.tsx+++ b/packages/ui-patterns/admonition.tsx@@ -110,9 +110,9 @@ export const Admonition = forwardRef<>{(showIcon && typeMapped === 'warning') || typeMapped === 'destructive' ? (<WarningIcon />- ) : (+ ) : showIcon ? (<InfoIcon />- )}+ ) : null}{label || title ? (<><AlertTitle_Shadcn_