The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/rls ai assistant updates 041223 (#19404)
Joshen Lim9d48e8c770cb
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.ts b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.tsindex 74258a2d4d7..108072df1ca 100644--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.ts+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.ts@@ -74,3 +74,14 @@ COMMIT;`.trim()}}++export const generatePolicyDefinition = (policy: PostgresPolicy) => {+ return `+CREATE POLICY "${policy.name}" on "${policy.schema}"."${policy.table}"+AS ${policy.action} FOR ${policy.command}+TO ${policy.roles.join(', ')}+${policy.definition ? `USING (${policy.definition})` : ''}+${policy.check ? `WITH CHECK (${policy.check})` : ''}+;+`.trim()+}diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsxindex 72ed2bfef49..ef7f8e8e412 100644--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx@@ -14,7 +14,11 @@ export const AIPolicyHeader = ({setAssistantVisible: (v: boolean) => void}) => {return (- <SheetHeader_Shadcn_ className="py-3 flex flex-row justify-between items-center">+ <SheetHeader_Shadcn_+ className={`${+ selectedPolicy !== undefined ? 'pt-3 pb-0' : 'py-3'+ } flex flex-row justify-between items-center`}+ ><div className="flex flex-row gap-3 items-center max-w-[75%]"><SheetClose_Shadcn_className={clsx(diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetails.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetails.tsxnew file mode 100644index 00000000000..839e42e6b12--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetails.tsx@@ -0,0 +1,68 @@+import { PostgresPolicy } from '@supabase/postgres-meta'+import {+ CollapsibleContent_Shadcn_,+ CollapsibleTrigger_Shadcn_,+ Collapsible_Shadcn_,+ IconChevronDown,+} from 'ui'++interface PolicyDetailsProps {+ policy?: PostgresPolicy+ showDetails: boolean+ toggleShowDetails: () => void+}++const PolicyDetails = ({ policy, showDetails, toggleShowDetails }: PolicyDetailsProps) => {+ if (!policy) return null++ return (+ <Collapsible_Shadcn_+ className="-mt-1.5 pb-1.5"+ open={showDetails}+ onOpenChange={toggleShowDetails}+ >+ <CollapsibleTrigger_Shadcn_ className="group pl-[3.6rem] font-normal p-0 [&[data-state=open]>div>svg]:!-rotate-180">+ <div className="flex items-center gap-x-2 w-full">+ <p className="text-xs text-foreground-light group-hover:text-foreground transition">+ View policy details+ </p>+ <IconChevronDown+ className="transition-transform duration-200"+ strokeWidth={1.5}+ size={14}+ />+ </div>+ </CollapsibleTrigger_Shadcn_>+ <CollapsibleContent_Shadcn_ className="pl-[3.6rem] mt-1">+ <div className="text-xs flex items-start space-x-2">+ <p className="w-[110px] text-foreground-light">Name:</p>+ <p className="">{policy.name}</p>+ </div>+ <div className="text-xs flex items-start space-x-2">+ <p className="w-[110px] text-foreground-light">Action:</p>+ <p className="font-mono">{policy.action}</p>+ </div>+ <div className="text-xs flex items-start space-x-2">+ <p className="w-[110px] text-foreground-light">Command:</p>+ <p className="font-mono">{policy.command}</p>+ </div>+ <div className="text-xs flex items-start space-x-2">+ <p className="w-[110px] text-foreground-light">Target roles:</p>+ <p className="font-mono">{policy.roles.join(', ')}</p>+ </div>+ <div className="text-xs flex items-start space-x-2">+ <p className="w-[110px] text-foreground-light">USING expression:</p>+ <p className="font-mono">{policy.definition}</p>+ </div>+ <div className="text-xs flex items-start space-x-2">+ <p className="w-[110px] text-foreground-light">CHECK expression:</p>+ <p className={`${policy.check ? '' : 'text-foreground-light'} font-mono`}>+ {policy.check ?? 'None'}+ </p>+ </div>+ </CollapsibleContent_Shadcn_>+ </Collapsible_Shadcn_>+ )+}++export default PolicyDetailsdiff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsxindex 42cf0e7e381..f5eb371da3c 100644--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx@@ -16,11 +16,17 @@ import { useRlsSuggestQuery } from 'data/ai/rls-suggest-query'import { useSqlDebugMutation } from 'data/ai/sql-debug-mutation'import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'import { QueryResponseError, useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'-import { useSelectedProject, useStore } from 'hooks'+import { useSelectedOrganization, useSelectedProject, useStore } from 'hooks'+import { OPT_IN_TAGS } from 'lib/constants'import { uuidv4 } from 'lib/helpers'import { AIPolicyChat } from './AIPolicyChat'-import { generatePlaceholder, generateThreadMessage } from './AIPolicyEditorPanel.utils'+import {+ generatePlaceholder,+ generatePolicyDefinition,+ generateThreadMessage,+} from './AIPolicyEditorPanel.utils'import { AIPolicyHeader } from './AIPolicyHeader'+import PolicyDetails from './PolicyDetails'import QueryError from './QueryError'import RLSCodeEditor from './RLSCodeEditor'@@ -45,12 +51,15 @@ export const AIPolicyEditorPanel = memo(function ({}: AIPolicyEditorPanelProps) {const { meta } = useStore()const selectedProject = useSelectedProject()+ const selectedOrganization = useSelectedOrganization()const editorRef = useRef<IStandaloneCodeEditor | null>(null)const diffEditorRef = useRef<IStandaloneDiffEditor | null>(null)const placeholder = generatePlaceholder(selectedPolicy)+ const isOptedInToAI = selectedOrganization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? falseconst [error, setError] = useState<QueryResponseError>()+ const [showDetails, setShowDetails] = useState(false)// [Joshen] Separate state here as there's a delay between submitting and the API updating the loading statusconst [loading, setLoading] = useState(false)const [keepPreviousData, setKeepPreviousData] = useState(false)@@ -130,8 +139,10 @@ export const AIPolicyEditorPanel = memo(function ({} else {addPromptMutation({thread_id: ids?.threadId,- entityDefinitions,prompt: message,+ entityDefinitions: isOptedInToAI ? entityDefinitions : undefined,+ policyDefinition:+ selectedPolicy !== undefined ? generatePolicyDefinition(selectedPolicy) : undefined,})}},@@ -139,7 +150,12 @@ export const AIPolicyEditorPanel = memo(function ({)const messages = useMemo(- () => [...(data?.messages ?? []), ...debugThread],+ () => [+ ...(data?.messages ?? []).sort(+ (a, b) => b.created_at - a.created_at || a.role.localeCompare(b.role)+ ),+ ...debugThread,+ ],[data?.messages, debugThread])@@ -245,6 +261,7 @@ export const AIPolicyEditorPanel = memo(function ({setError(undefined)setDebugThread([])setKeepPreviousData(false)+ setShowDetails(false)} else {setKeepPreviousData(true)}@@ -254,6 +271,24 @@ export const AIPolicyEditorPanel = memo(function ({if (data?.status === 'completed') setLoading(false)}, [data?.status])+ // [Joshen] Problem with monaco is that it's height cannot be dynamically updated once its initialized+ // So this is sort of a hacky way to do so, until we find a better solution at least+ const footerHeight = 58+ const createPolicyEditorHeight =+ error === undefined+ ? `calc(100vh - ${footerHeight}px - 54px)`+ : `calc(100vh - ${footerHeight}px - 151px - ${20 * errorLines}px)`+ const updatePolicyEditorHeight =+ showDetails && error === undefined+ ? `calc(100vh - ${footerHeight}px - 172px)`+ : showDetails && error !== undefined+ ? `calc(100vh - ${footerHeight}px - 172px - 122px - ${16 * errorLines}px)`+ : !showDetails && error === undefined+ ? `calc(100vh - ${footerHeight}px - 72px)`+ : !showDetails && error !== undefined+ ? `calc(100vh - ${footerHeight}px - 72px - 122px - ${16 * errorLines}px)`+ : '0'+return (<><Sheet_Shadcn_ open={visible} onOpenChange={() => onClosingPanel()}>@@ -270,19 +305,26 @@ export const AIPolicyEditorPanel = memo(function ({assistantVisible={assistantVisible}setAssistantVisible={setAssistantPanel}/>++ <PolicyDetails+ policy={selectedPolicy}+ showDetails={showDetails}+ toggleShowDetails={() => setShowDetails(!showDetails)}+ />+<div className="flex flex-col h-full w-full justify-between">{incomingChange ? (<div className="px-5 py-3 flex justify-between gap-3 bg-muted"><div className="flex gap-2 items-center text-foreground-light"><FileDiff className="h-4 w-4" />- <span className="text-sm">Apply changes from assistant</span>+ <span className="text-sm">Accept changes from assistant</span></div><div className="flex gap-3"><Button type="default" onClick={() => setIncomingChange(undefined)}>Discard</Button><Button type="primary" onClick={() => acceptChange()}>- Apply+ Accept</Button></div></div>@@ -292,7 +334,7 @@ export const AIPolicyEditorPanel = memo(function ({<DiffEditortheme="supabase"language="pgsql"- className="flex grow"+ className="grow"original={editorRef.current?.getValue()}modified={incomingChange}onMount={(editor) => (diffEditorRef.current = editor)}@@ -309,9 +351,9 @@ export const AIPolicyEditorPanel = memo(function ({className={`relative ${incomingChange ? 'hidden' : 'block'}`}style={{height:- error === undefined- ? 'calc(100vh - 58px - 54px)'- : `calc(100vh - 58px - 151px - ${20 * errorLines}px)`,+ selectedPolicy !== undefined+ ? updatePolicyEditorHeight+ : createPolicyEditorHeight,}}><RLSCodeEditordiff --git a/apps/studio/components/interfaces/SQLEditor/AISettingsModal.tsx b/apps/studio/components/interfaces/SQLEditor/AISettingsModal.tsxnew file mode 100644index 00000000000..8ab1da2e8b8--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/AISettingsModal.tsx@@ -0,0 +1,64 @@+import { ModalProps } from '@ui/components/Modal/Modal'+import { useLocalStorageQuery, useSelectedOrganization, useStore } from 'hooks'+import { IS_PLATFORM, OPT_IN_TAGS } from 'lib/constants'+import Link from 'next/link'+import { Alert, IconExternalLink, Modal, Toggle } from 'ui'+export interface AISettingsModalProps {+ visible: boolean+}++const AISettingsModal = (props: ModalProps) => {+ const selectedOrganization = useSelectedOrganization()+ const isOptedInToAI = selectedOrganization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false+ const [hasEnabledAISchema, setHasEnabledAISchema] = useLocalStorageQuery(+ 'supabase_sql-editor-ai-schema-enabled',+ true+ )+ const { ui } = useStore()++ const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema++ const handleOptInToggle = () => {+ setHasEnabledAISchema((prev) => !prev)+ ui.setNotification({ category: 'success', message: 'Successfully saved settings' })+ }++ return (+ <Modal header="SQL Editor AI Settings" hideFooter closable {...props}>+ <div className="flex flex-col items-start justify-between gap-4 px-6 py-3">+ {IS_PLATFORM && !isOptedInToAI && selectedOrganization && (+ <Alert+ variant="warning"+ title="This option is only available if your organization has opted-in to sending anonymous data to OpenAI."+ >+ <Link+ href={`/org/${selectedOrganization.slug}/general`}+ className="flex flex-row gap-1 items-center"+ target="_blank"+ rel="noopener"+ >+ Go to your organization's settings to opt-in.+ <IconExternalLink className="inline-block w-3 h-3" />+ </Link>+ </Alert>+ )}+ <div className="flex justify-between gap-8 mr-8 my-4">+ <Toggle+ disabled={IS_PLATFORM && !isOptedInToAI}+ checked={includeSchemaMetadata}+ onChange={handleOptInToggle}+ />+ <div className="grid gap-2">+ <p className="text-sm">Include anonymous database metadata in AI queries</p>+ <p className="text-sm text-foreground-light">+ Includes table names, column names and their corresponding data types in the request.+ This will generate queries that are more relevant to your project.+ </p>+ </div>+ </div>+ </div>+ </Modal>+ )+}++export default AISettingsModaldiff --git a/apps/studio/data/ai/rls-suggest-mutation.ts b/apps/studio/data/ai/rls-suggest-mutation.tsindex 2fdf15e8926..0ab2d0bcf2e 100644--- a/apps/studio/data/ai/rls-suggest-mutation.ts+++ b/apps/studio/data/ai/rls-suggest-mutation.ts@@ -4,6 +4,7 @@ import toast from 'react-hot-toast'import { isResponseOk, post } from 'lib/common/fetch'import { BASE_PATH } from 'lib/constants'import { ResponseError } from 'types'+import { PostgresPolicy } from '@supabase/postgres-meta'export type RlsSuggestResponse = {threadId: string@@ -12,15 +13,22 @@ export type RlsSuggestResponse = {export type RlsSuggestVariables = {thread_id?: string- entityDefinitions?: string[]prompt: string+ entityDefinitions?: string[]+ policyDefinition?: string}-export async function rlsSuggest({ thread_id, entityDefinitions, prompt }: RlsSuggestVariables) {+export async function rlsSuggest({+ thread_id,+ prompt,+ entityDefinitions,+ policyDefinition,+}: RlsSuggestVariables) {const response = await post<RlsSuggestResponse>(BASE_PATH + '/api/ai/sql/suggest', {thread_id,- entityDefinitions,prompt,+ entityDefinitions,+ policyDefinition,})if (!isResponseOk(response)) {diff --git a/apps/studio/pages/api/ai/sql/suggest/index.ts b/apps/studio/pages/api/ai/sql/suggest/index.tsindex 07437d3e01f..dc499377db9 100644--- a/apps/studio/pages/api/ai/sql/suggest/index.ts+++ b/apps/studio/pages/api/ai/sql/suggest/index.ts@@ -29,7 +29,7 @@ export async function handlePost(req: NextApiRequest, res: NextApiResponse) {try {let {- body: { thread_id, entityDefinitions, prompt },+ body: { thread_id, prompt, entityDefinitions, policyDefinition },} = reqif (!thread_id) {@@ -37,17 +37,34 @@ export async function handlePost(req: NextApiRequest, res: NextApiResponse) {thread_id = thread.id}+ const prerequisites = []+if (entityDefinitions) {- const one = await openai.beta.threads.messages.create(thread_id, {+ prerequisites.push(+ codeBlock`+ Here is my database schema for reference:+ ${entityDefinitions.join('\n\n')}+ `.trim()+ )+ }++ if (policyDefinition !== undefined) {+ prerequisites.push(+ codeBlock`+ Here is my policy definition for reference:+ ${policyDefinition}+ `.trim()+ )+ }++ if (prerequisites.length > 0) {+ await openai.beta.threads.messages.create(thread_id, {role: 'user',- content: codeBlock`- Here is my database schema for reference:- ${entityDefinitions.join('\n\n')}- `,+ content: prerequisites.join('\n'),})}- const two = await openai.beta.threads.messages.create(thread_id, {+ await openai.beta.threads.messages.create(thread_id, {role: 'user',content: prompt,})