Skip to content

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

rls changes (#29118)

Terry Suttona40ccd11bc72
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
index d047d8cdb10..a77d22b887d 100644
--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
@@ -20,7 +20,6 @@ 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_RLS_AI_ASSISTANT]: false,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]: false,
})
@@ -31,8 +30,6 @@ export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren<{}
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_RLS_AI_ASSISTANT]:
- localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_AI_ASSISTANT) === 'true',
[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]:
localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS) === 'true',
})
@@ -60,11 +57,6 @@ export const useIsAPIDocsSidePanelEnabled = () => {
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL]
}
-export const useIsRLSAIAssistantEnabled = () => {
- const { flags } = useFeaturePreviewContext()
- return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_AI_ASSISTANT]
-}
-
export const useIsColumnLevelPrivilegesEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx
index 9437d9ffd03..8bc19e260d2 100644
--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx
+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx
@@ -11,7 +11,6 @@ import { Button, Modal, ScrollArea, cn } from 'ui'
import APISidePanelPreview from './APISidePanelPreview'
import CLSPreview from './CLSPreview'
import { useFeaturePreviewContext } from './FeaturePreviewContext'
-import RLSAIAssistantPreview from './RLSAIAssistantPreview'
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.
@@ -22,12 +21,6 @@ const FeaturePreviewModal = () => {
content: <APISidePanelPreview />,
discussionsUrl: 'https://github.com/orgs/supabase/discussions/18038',
},
- {
- key: LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_AI_ASSISTANT,
- name: 'Supabase Assistant for RLS policies',
- content: <RLSAIAssistantPreview />,
- discussionsUrl: 'https://github.com/orgs/supabase/discussions/21882',
- },
{
key: LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS,
name: 'Column-level privileges',
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/RLSAIAssistantPreview.tsx b/apps/studio/components/interfaces/App/FeaturePreview/RLSAIAssistantPreview.tsx
deleted file mode 100644
index 11f111d8f46..00000000000
--- a/apps/studio/components/interfaces/App/FeaturePreview/RLSAIAssistantPreview.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useParams } from 'common'
-import { Markdown } from 'components/interfaces/Markdown'
-import { BASE_PATH } from 'lib/constants'
-import Image from 'next/image'
-
-const RLSAIAssistantPreview = () => {
- const { ref } = useParams()
-
- return (
- <div className="space-y-2">
- <div className="mb-4 flex flex-col gap-y-2">
- <Markdown
- className="text-foreground-light max-w-full"
- content={`[Postgres Row Level Security](https://supabase.com/docs/guides/database/postgres/row-level-security) (RLS) is a feature of Postgres that allows you to control which users are allowed to perform operations on specific rows within tables, views, and functions.`}
- />
- <Markdown
- className="text-foreground-light max-w-full"
- content={`Let our AI Assistant handle the SQL while you focus on building the rules for your policies.`}
- />
- </div>
- <Image
- src={`${BASE_PATH}/img/previews/rls-ai-assistant-preview.png`}
- width={1860}
- height={970}
- alt="api-docs-side-panel-preview"
- className="rounded border"
- />
- <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={`Replace the existing wizard-like UI for creating/updating RLS policies [here](/project/${ref}/auth/policies). Create policies in code with Supabase Assistant`}
- />
- </li>
- <li>
- <Markdown
- className="text-foreground-light"
- content={`Supabase Assistant will iteratively generate SQL from your natural language prompts`}
- />
- </li>
- </ul>
- </div>
- </div>
- )
-}
-
-export default RLSAIAssistantPreview
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
index f48f6a6a524..ae28725e3e4 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
@@ -1,6 +1,6 @@
import Telemetry from 'lib/telemetry'
import { compact, last } from 'lodash'
-import { ChevronsUpDown } from 'lucide-react'
+import { ChevronsUpDown, Lightbulb } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect, useRef, useState } from 'react'
@@ -14,25 +14,35 @@ import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { IS_PLATFORM } from 'lib/constants'
import { useProfile } from 'lib/profile'
-import { AiIconAnimation } from 'ui'
+import {
+ AiIconAnimation,
+ Button,
+ Tooltip_Shadcn_,
+ TooltipContent_Shadcn_,
+ TooltipTrigger_Shadcn_,
+} from 'ui'
import { AssistantChatForm } from 'ui-patterns/AssistantChat'
import { MessageWithDebug } from './AIPolicyEditorPanel.utils'
import Message from './Message'
interface AIPolicyChatProps {
+ selectedTable: string
messages: MessageWithDebug[]
selectedMessage?: string
loading: boolean
onSubmit: (s: string) => void
onDiff: (message: { id: string; content: string }) => void
+ clearHistory?: () => void
}
export const AIPolicyChat = ({
+ selectedTable,
messages,
selectedMessage,
loading,
onSubmit,
onDiff,
+ clearHistory,
}: AIPolicyChatProps) => {
const router = useRouter()
const project = useSelectedProject()
@@ -43,6 +53,7 @@ export const AIPolicyChat = ({
const [selectedSchemas, setSelectedSchemas] = useSchemasForAi(project?.ref!)
const [value, setValue] = useState<string>('')
+ const [hasSuggested, setHasSuggested] = useState(false)
const inputRef = useRef<HTMLTextAreaElement>(null)
const isOptedInToAI = useOrgOptedIntoAi()
@@ -70,7 +81,14 @@ export const AIPolicyChat = ({
return (
<div id={'ai-chat-assistant'} className="flex flex-col h-full max-w-full">
- <div className="overflow-auto flex-1 divide-y divide-border">
+ <div className="overflow-auto flex-1 divide-y divide-border relative">
+ <div className="flex gap-2 absolute right-4 top-4">
+ {messages.length > 0 && (
+ <Button type="warning" onClick={clearHistory}>
+ Clear history
+ </Button>
+ )}
+ </div>
<Message
key="zero"
role="assistant"
@@ -81,19 +99,24 @@ export const AIPolicyChat = ({
learn and improve.`}
>
{includeSchemaMetadata ? (
- <SchemaComboBox
- className="w-fit"
- disabled={!includeSchemaMetadata}
- selectedSchemas={selectedSchemas}
- onSelectSchemas={setSelectedSchemas}
- label={
- includeSchemaMetadata && selectedSchemas.length > 0
- ? `${selectedSchemas.length} schema${
- selectedSchemas.length > 1 ? 's' : ''
- } selected`
- : 'No schemas selected'
- }
- />
+ <div className="grid gap-2 mt-2">
+ <span className="inline-block text-lighter">
+ Include these schemas in your prompts:
+ </span>
+ <SchemaComboBox
+ className="w-fit"
+ disabled={!includeSchemaMetadata}
+ selectedSchemas={selectedSchemas}
+ onSelectSchemas={setSelectedSchemas}
+ label={
+ includeSchemaMetadata && selectedSchemas.length > 0
+ ? `${selectedSchemas.length} schema${
+ selectedSchemas.length > 1 ? 's' : ''
+ } selected`
+ : 'No schemas selected'
+ }
+ />
+ </div>
) : (
<ButtonTooltip
disabled
@@ -124,7 +147,6 @@ export const AIPolicyChat = ({
</ButtonTooltip>
)}
</Message>
-
{messages.map((m) => (
<Message
key={`message-${m.id}`}
@@ -137,12 +159,33 @@ export const AIPolicyChat = ({
onDiff={(content) => onDiff({ id: m.id, content })}
/>
))}
-
{pendingReply && <Message key="thinking" role="assistant" content="Thinking..." />}
-
<div ref={bottomRef} className="h-1" />
</div>
-
+ {!hasSuggested && (
+ <div className="flex flex-row justify-between m-4">
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_ asChild>
+ <Button
+ type="outline"
+ className="rounded-full"
+ icon={<Lightbulb size={14} />}
+ onClick={() => {
+ onSubmit(
+ `Suggest policies for ${selectedTable} table. Don't duplicate any of my existing policies.`
+ )
+ setHasSuggested(true)
+ }}
+ >
+ <span>Suggest</span>
+ </Button>
+ </TooltipTrigger_Shadcn_>
+ <TooltipContent_Shadcn_ side="right">
+ Suggest policies for this table
+ </TooltipContent_Shadcn_>
+ </Tooltip_Shadcn_>
+ </div>
+ )}
<div className="sticky p-5 flex-0 border-t">
<AssistantChatForm
textAreaRef={inputRef}
@@ -154,7 +197,7 @@ export const AIPolicyChat = ({
className="[&>div>div]:border-black dark:[&>div>div]:border-white"
/>
}
- placeholder="Ask for some changes to your policy"
+ placeholder="Ask for help with your RLS policies"
value={value}
onValueChange={(e) => setValue(e.target.value)}
onSubmit={(event) => {
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
index fc8fd7316e3..81056928795 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
@@ -2,7 +2,6 @@ import type { PostgresPolicy } from '@supabase/postgres-meta'
import { ChevronDown, PanelLeftClose, PanelRightClose, X } from 'lucide-react'
import { useState } from 'react'
-import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import {
CollapsibleContent_Shadcn_,
CollapsibleTrigger_Shadcn_,
@@ -26,19 +25,16 @@ export const AIPolicyHeader = ({
setAssistantVisible: (v: boolean) => void
}) => {
const [showDetails, setShowDetails] = useState(false)
- const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
return (
<SheetHeader className={cn('py-3 flex flex-row justify-between items-start border-b')}>
- <div
- className={`flex flex-row gap-3 max-w-[75%] ${isAiAssistantEnabled ? 'items-start' : 'items-center'}`}
- >
+ <div className="flex flex-row gap-3 max-w-[75%] items-start">
<SheetClose
className={cn(
'text-muted hover:text ring-offset-background transition-opacity hover:opacity-100',
'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
'transition disabled:pointer-events-none data-[state=open]:bg-secondary',
- isAiAssistantEnabled ? 'mt-1.5' : ''
+ 'mt-1.5'
)}
>
<X className="h-3 w-3" />
@@ -51,7 +47,7 @@ export const AIPolicyHeader = ({
? `Update policy: ${selectedPolicy.name}`
: 'Create a new Row Level Security policy'}
</SheetTitle>
- {isAiAssistantEnabled && selectedPolicy !== undefined && (
+ {selectedPolicy !== undefined && (
<Collapsible_Shadcn_
className="-mt-1.5 pb-1.5"
open={showDetails}
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
index 9e7e2383302..a6b44e6e50f 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
@@ -3,7 +3,6 @@ import { initial, last } from 'lodash'
import { Dispatch, SetStateAction } from 'react'
import { useTelemetryProps } from 'common'
-import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { subscriptionHasHipaaAddon } from 'components/interfaces/Billing/Subscription/Subscription.utils'
import { QueryResponseError } from 'data/sql/execute-sql-mutation'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
@@ -31,7 +30,6 @@ const QueryError = ({
setOpen: Dispatch<SetStateAction<boolean>>
onSelectDebug: () => void
}) => {
- const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
const formattedError =
(error?.formattedError?.split('\n') ?? [])?.filter((x: string) => x.length > 0) ?? []
@@ -76,7 +74,7 @@ const QueryError = ({
{open ? 'Hide error details' : 'Show error details'}
</Button>
</CollapsibleTrigger_Shadcn_>
- {!hasHipaaAddon && isAiAssistantEnabled && (
+ {!hasHipaaAddon && (
<Button
size="tiny"
type="default"
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
index babff3766a2..1323ec5c305 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
@@ -29,6 +29,7 @@ interface RLSCodeEditorProps {
editorRef: MutableRefObject<editor.IStandaloneCodeEditor | null>
monacoRef?: MutableRefObject<Monaco>
+ editView: 'templates' | 'conversation' // someone help
}
const RLSCodeEditor = ({
@@ -47,6 +48,7 @@ const RLSCodeEditor = ({
editorRef,
monacoRef,
+ editView,
}: RLSCodeEditorProps) => {
const hasValue = useRef<any>()
const monaco = useMonaco()
@@ -66,6 +68,9 @@ 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/AIPolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
index e96411f8853..6f30963a52b 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
@@ -29,14 +29,15 @@ import * as z from 'zod'
import { Monaco } from '@monaco-editor/react'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { subscriptionHasHipaaAddon } from 'components/interfaces/Billing/Subscription/Subscription.utils'
import {
IStandaloneCodeEditor,
IStandaloneDiffEditor,
} from 'components/interfaces/SQLEditor/SQLEditor.types'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useSqlDebugMutation } from 'data/ai/sql-debug-mutation'
+import { useDatabasePoliciesQuery } from 'data/database-policies/database-policies-query'
import { useDatabasePolicyUpdateMutation } from 'data/database-policies/database-policy-update-mutation'
import { databasePoliciesKeys } from 'data/database-policies/keys'
import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
@@ -50,6 +51,7 @@ import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { BASE_PATH } from 'lib/constants'
import { uuidv4 } from 'lib/helpers'
import Telemetry from 'lib/telemetry'
+import { useQueryState } from 'nuqs'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { AIPolicyChat } from './AIPolicyChat'
import {
@@ -101,9 +103,10 @@ export const AIPolicyEditorPanel = memo(function ({
const selectedOrganization = useSelectedOrganization()
const telemetryProps = useTelemetryProps()
- const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
const canUpdatePolicies = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')
+ const [editView, setEditView] = useQueryState('view', { defaultValue: 'templates' as const })
+
// [Joshen] Hyrid form fields, just spit balling to get a decent POC out
const [using, setUsing] = useState('')
const [check, setCheck] = useState('')
@@ -122,7 +125,9 @@ export const AIPolicyEditorPanel = memo(function ({
// Use chat id because useChat doesn't have a reset function to clear all messages
const [chatId, setChatId] = useState(uuidv4())
- const [tabId, setTabId] = useState<'templates' | 'conversation'>('templates')
+ const [tabId, setTabId] = useState<'templates' | 'conversation'>(
+ editView as 'templates' | 'conversation'
+ )
const diffEditorRef = useRef<IStandaloneDiffEditor | null>(null)
const placeholder = generatePlaceholder(selectedPolicy)
@@ -166,6 +171,8 @@ export const AIPolicyEditorPanel = memo(function ({
const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)
const [selectedSchemas] = useSchemasForAi(selectedProject?.ref!)
+
+ // get entitiy (tables/views/materialized views/etc) definitions to pass to AI Assistant
const { data: entities } = useEntityDefinitionsQuery(
{
schemas: selectedSchemas,
@@ -180,6 +187,28 @@ export const AIPolicyEditorPanel = memo(function ({
const supportWithCheck = ['update', 'all'].includes(command)
const isRenamingPolicy = selectedPolicy !== undefined && name !== selectedPolicy.name
+ const { project } = useProjectContext()
+ const { data } = useDatabasePoliciesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const existingPolicies = (data ?? [])
+ .filter((policy) => policy.schema === schema && policy.table === selectedTable)
+ .sort((a, b) => a.name.localeCompare(b.name))
+
+ const existingPolicyDefinition = existingPolicies
+ .map((policy) => {
+ const definition = generatePolicyDefinition(policy)
+ return (
+ definition
+ .trim()
+ .replace(/\s*;\s*$/, '')
+ .replace(/\n\s*$/, '') + ';'
+ )
+ })
+ .join('\n\n')
+
const {
messages: chatMessages,
append,
@@ -189,6 +218,7 @@ export const AIPolicyEditorPanel = memo(function ({
api: `${BASE_PATH}/api/ai/sql/suggest`,
body: {
entityDefinitions: isOptedInToAI || !IS_PLATFORM ? entityDefinitions : undefined,
+ existingPolicies,
policyDefinition:
selectedPolicy !== undefined ? generatePolicyDefinition(selectedPolicy) : undefined,
},
@@ -264,6 +294,7 @@ export const AIPolicyEditorPanel = memo(function ({
setIsClosingPolicyEditorPanel(true)
} else {
onSelectCancel()
+ setEditView(null)
}
}
@@ -386,6 +417,10 @@ export const AIPolicyEditorPanel = memo(function ({
}
}
+ const clearHistory = () => {
+ setChatId(uuidv4())
+ }
+
// when the panel is closed, reset all values
useEffect(() => {
if (!visible) {
@@ -437,6 +472,11 @@ export const AIPolicyEditorPanel = memo(function ({
})
}, [showDetails, error, errorPanelOpen])
+ // update tabId when the editView changes
+ useEffect(() => {
+ editView === 'conversation' ? setTabId('conversation') : setTabId('templates')
+ }, [editView])
+
return (
<>
<Form_Shadcn_ {...form}>
@@ -448,7 +488,7 @@ export const AIPolicyEditorPanel = memo(function ({
className={cn(
'bg-surface-200',
'p-0 flex flex-row gap-0',
- assistantVisible ? '!min-w-[1200px]' : '!min-w-[600px]'
+ assistantVisible ? '!min-w-[1000px]' : '!min-w-[600px]'
)}
>
<div className={cn('flex flex-col grow w-full', assistantVisible && 'w-[60%]')}>
@@ -530,13 +570,16 @@ export const AIPolicyEditorPanel = memo(function ({
/>
) : null}
- {isAiAssistantEnabled ? (
+ {/* which left side editor to show in the sheet */}
+ {editView === 'conversation' ? (
<div className={`relative h-full ${incomingChange ? 'hidden' : 'block'}`}>
<RLSCodeEditor
id="rls-sql-policy"
defaultValue={''}
+ value={existingPolicyDefinition}
placeholder={placeholder}
editorRef={editorOneRef}
+ editView={editView as 'templates' | 'conversation'} // someone help
/>
</div>
) : (
@@ -577,6 +620,7 @@ export const AIPolicyEditorPanel = memo(function ({
disableTabToUsePlaceholder
readOnly={!canUpdatePolicies}
id="rls-exp-one-editor"
+ editView={editView as 'templates' | 'conversation'} // someone help
placeholder={
command === 'insert'
? '-- Provide a SQL expression for the with check statement'
@@ -649,6 +693,7 @@ export const AIPolicyEditorPanel = memo(function ({
editorRef={editorTwoRef}
monacoRef={monacoTwoRef as any}
lineNumberStart={7 + expOneLineCount}
+ editView={editView as 'templates' | 'conversation'} // someone help
onChange={() => {
setExpTwoContentHeight(
editorTwoRef.current?.getContentHeight() ?? 0
@@ -752,18 +797,16 @@ export const AIPolicyEditorPanel = memo(function ({
incomingChange !== undefined
}
onClick={() => {
- if (isAiAssistantEnabled) {
- const sql = editorOneRef.current?.getValue().trim()
- if (!sql) return onSelectCancel()
- executeMutation({
- sql: sql,
- projectRef: selectedProject?.ref,
- connectionString: selectedProject?.connectionString,
- handleError: (error) => {
- throw error
- },
- })
- }
+ const sql = editorOneRef.current?.getValue().trim()
+ if (!sql) return onSelectCancel()
+ executeMutation({
+ sql: sql,
+ projectRef: selectedProject?.ref,
+ connectionString: selectedProject?.connectionString,
+ handleError: (error) => {
+ throw error
+ },
+ })
}}
tooltip={{
content: {
@@ -783,7 +826,7 @@ export const AIPolicyEditorPanel = memo(function ({
className={cn(
'border-l shadow-[rgba(0,0,0,0.13)_-4px_0px_6px_0px] z-10',
assistantVisible && 'w-[50%]',
- 'bg-studio'
+ 'bg-studio overflow-auto'
)}
>
<Tabs_Shadcn_
@@ -792,15 +835,18 @@ export const AIPolicyEditorPanel = memo(function ({
className="flex flex-col h-full w-full"
>
<TabsList_Shadcn_ className="flex gap-4 px-content pt-2">
- <TabsTrigger_Shadcn_
- key="templates"
- value="templates"
- onClick={() => setTabId('templates')}
- className="px-0 data-[state=active]:bg-transparent"
- >
- Templates
- </TabsTrigger_Shadcn_>
- {isAiAssistantEnabled && !hasHipaaAddon && (
+ {editView === 'templates' && (
+ <TabsTrigger_Shadcn_
+ key="templates"
+ value="templates"
+ onClick={() => setTabId('templates')}
+ className="px-0 data-[state=active]:bg-transparent"
+ >
+ Templates
+ </TabsTrigger_Shadcn_>
+ )}
+
+ {editView === 'conversation' && !hasHipaaAddon && (
<TabsTrigger_Shadcn_
key="conversation"
value="conversation"
@@ -811,26 +857,22 @@ export const AIPolicyEditorPanel = memo(function ({
</TabsTrigger_Shadcn_>
)}
</TabsList_Shadcn_>
- <TabsContent_Shadcn_
- value="templates"
- className={cn(
- '!mt-0 overflow-y-auto',
- 'data-[state=active]:flex data-[state=active]:grow'
- )}
- >
- <ScrollArea className="h-full w-full">
- <PolicyTemplates
- schema={schema}
- table={table}
- selectedPolicy={selectedPolicy}
- selectedTemplate={selectedDiff}
- onSelectTemplate={(value) => {
- if (isAiAssistantEnabled) {
- updateEditorWithCheckForDiff({
- id: value.id,
- content: value.statement,
- })
- } else {
+
+ {editView === 'templates' && (
+ <TabsContent_Shadcn_
+ value="templates"
+ className={cn(
+ '!mt-0 overflow-y-auto',
+ 'data-[state=active]:flex data-[state=active]:grow'
+ )}
+ >
+ <ScrollArea className="h-full w-full">
+ <PolicyTemplates
+ schema={schema}
+ table={table}
+ selectedPolicy={selectedPolicy}
+ selectedTemplate={selectedDiff}
+ onSelectTemplate={(value) => {
form.setValue('name', value.name)
form.setValue('behavior', 'permissive')
form.setValue('command', value.command.toLowerCase())
@@ -849,16 +891,18 @@ export const AIPolicyEditorPanel = memo(function ({
} else {
setShowCheckBlock(false)
}
- }
- }}
- />
- </ScrollArea>
- </TabsContent_Shadcn_>
+ }}
+ />
+ </ScrollArea>
+ </TabsContent_Shadcn_>
+ )}
+
<TabsContent_Shadcn_
value="conversation"
className="flex grow !mt-0 overflow-y-auto"
>
<AIPolicyChat
+ selectedTable={selectedTable!}
messages={messages}
selectedMessage={selectedDiff}
onSubmit={(message) =>
@@ -870,6 +914,7 @@ export const AIPolicyEditorPanel = memo(function ({
}
onDiff={updateEditorWithCheckForDiff}
loading={isLoading || isDebugSqlLoading}
+ clearHistory={clearHistory}
/>
</TabsContent_Shadcn_>
</Tabs_Shadcn_>
@@ -890,6 +935,7 @@ export const AIPolicyEditorPanel = memo(function ({
onConfirm={() => {
onSelectCancel()
setIsClosingPolicyEditorPanel(false)
+ setEditView(null)
}}
>
<p className="text-sm text-foreground-light">
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx
index ee6273c9deb..2d639a4649b 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx
@@ -96,7 +96,6 @@ const PolicyEditorModal = ({
const onSelectBackFromTemplates = () => setView(previousView)
const onToggleFeaturePreviewModal = () => {
- snap.setSelectedFeaturePreview(LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_AI_ASSISTANT)
snap.setShowFeaturePreviewModal(!snap.showFeaturePreviewModal)
onSelectCancel()
}
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
index 4fac00d72db..87b385513f5 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
@@ -1,14 +1,20 @@
import type { PostgresTable } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { noop } from 'lodash'
import { Lock, Unlock } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
-
-import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { Badge } from 'ui'
+import { useQueryState } from 'nuqs'
+import {
+ AiIconAnimation,
+ Badge,
+ Button,
+ TooltipContent_Shadcn_,
+ TooltipTrigger_Shadcn_,
+ Tooltip_Shadcn_,
+} from 'ui'
interface PolicyTableRowHeaderProps {
table: PostgresTable
@@ -26,12 +32,12 @@ const PolicyTableRowHeader = ({
const router = useRouter()
const { ref } = router.query
- const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
const canToggleRLS = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')
const isRealtimeSchema = table.schema === 'realtime'
const isRealtimeMessagesTable = isRealtimeSchema && table.name === 'messages'
const isTableLocked = isRealtimeSchema ? !isRealtimeMessagesTable : isLocked
+ const [_, setEditView] = useQueryState('view', { defaultValue: '' })
return (
<div id={table.id.toString()} className="flex w-full items-center justify-between">
@@ -76,21 +82,41 @@ const PolicyTableRowHeader = ({
{table.rls_enabled ? 'Disable RLS' : 'Enable RLS'}
</ButtonTooltip>
)}
- {!isAiAssistantEnabled && (
- <ButtonTooltip
- type="default"
- disabled={!canToggleRLS}
- onClick={() => onSelectCreatePolicy()}
- tooltip={{
- content: {
- side: 'bottom',
- text: 'You need additional permissions to create RLS policies',
- },
- }}
- >
- Create policy
- </ButtonTooltip>
- )}
+ <ButtonTooltip
+ type="default"
+ disabled={!canToggleRLS}
+ onClick={() => onSelectCreatePolicy()}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: !canToggleRLS
+ ? 'You need additional permissions to create RLS policies'
+ : undefined,
+ },
+ }}
+ >
+ Create policy
+ </ButtonTooltip>
+
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_ asChild>
+ <Button
+ type="default"
+ className="px-1"
+ onClick={() => {
+ onSelectCreatePolicy()
+ setEditView('conversation')
+ }}
+ >
+ <AiIconAnimation className="scale-75 [&>div>div]:border-black dark:[&>div>div]:border-white" />
+ </Button>
+ </TooltipTrigger_Shadcn_>
+ <TooltipContent_Shadcn_ side="top">
+ {!canToggleRLS
+ ? 'You need additional permissions to create RLS policies'
+ : 'Create with Supabase Assistant'}
+ </TooltipContent_Shadcn_>
+ </Tooltip_Shadcn_>
</div>
</div>
)}
diff --git a/apps/studio/lib/constants/index.ts b/apps/studio/lib/constants/index.ts
index 6539a444c64..0b75ce4ae57 100644
--- a/apps/studio/lib/constants/index.ts
+++ b/apps/studio/lib/constants/index.ts
@@ -33,7 +33,6 @@ 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_RLS_AI_ASSISTANT: 'supabase-ui-rls-ai-assistant',
UI_PREVIEW_CLS: 'supabase-ui-cls',
UI_ONBOARDING_NEW_PAGE_SHOWN: 'supabase-ui-onboarding-new-page-shown',
diff --git a/apps/studio/lib/local-storage.ts b/apps/studio/lib/local-storage.ts
index 07775331f48..0e9f0d8d477 100644
--- a/apps/studio/lib/local-storage.ts
+++ b/apps/studio/lib/local-storage.ts
@@ -9,7 +9,6 @@ const LOCAL_STORAGE_KEYS_ALLOWLIST = [
LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT,
LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL,
LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT,
- LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_AI_ASSISTANT,
LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS,
LOCAL_STORAGE_KEYS.LAST_SIGN_IN_METHOD,
]
diff --git a/apps/studio/pages/api/ai/sql/suggest.ts b/apps/studio/pages/api/ai/sql/suggest.ts
index df98ca480f7..b32c923039c 100644
--- a/apps/studio/pages/api/ai/sql/suggest.ts
+++ b/apps/studio/pages/api/ai/sql/suggest.ts
@@ -2,12 +2,13 @@ import { StreamingTextResponse } from 'ai'
import { chatRlsPolicy } from 'ai-commands/edge'
import { NextRequest } from 'next/server'
import OpenAI from 'openai'
+import { DatabasePoliciesData } from '../../../../data/database-policies/database-policies-query'
export const config = {
runtime: 'edge',
/* To avoid OpenAI errors, restrict to the Vercel Edge Function regions that
overlap with the OpenAI API regions.
-
+
Reference for Vercel regions: https://vercel.com/docs/edge-network/regions#region-list
Reference for OpenAI regions: https://help.openai.com/en/articles/5347006-openai-api-supported-countries-and-territories
*/
@@ -69,13 +70,20 @@ async function handlePost(request: NextRequest) {
const body = await (request.json() as Promise<{
messages: { content: string; role: 'user' | 'assistant' }[]
entityDefinitions: string[]
+ existingPolicies: DatabasePoliciesData
policyDefinition: string
}>)
- const { messages, entityDefinitions, policyDefinition } = body
+ const { messages, entityDefinitions, existingPolicies, policyDefinition } = body
try {
- const stream = await chatRlsPolicy(openai, messages, entityDefinitions, policyDefinition)
+ const stream = await chatRlsPolicy(
+ openai,
+ messages,
+ entityDefinitions,
+ existingPolicies,
+ policyDefinition
+ )
return new StreamingTextResponse(stream)
} catch (error) {
console.error(error)
diff --git a/apps/studio/pages/project/[ref]/auth/policies.tsx b/apps/studio/pages/project/[ref]/auth/policies.tsx
index 23e750d5e89..1c3bb93b5a8 100644
--- a/apps/studio/pages/project/[ref]/auth/policies.tsx
+++ b/apps/studio/pages/project/[ref]/auth/policies.tsx
@@ -4,7 +4,6 @@ import { partition } from 'lodash'
import { ExternalLink, Search } from 'lucide-react'
import { useState } from 'react'
-import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { AIPolicyEditorPanel } from 'components/interfaces/Auth/Policies/AIPolicyEditorPanel'
import Policies from 'components/interfaces/Auth/Policies/Policies'
import AuthLayout from 'components/layouts/AuthLayout/AuthLayout'
@@ -65,7 +64,6 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
}>()
const { schema = 'public', search: searchString = '' } = params
const { project } = useProjectContext()
- const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
const [selectedTable, setSelectedTable] = useState<string>()
const [showPolicyAiEditor, setShowPolicyAiEditor] = useState(false)
@@ -145,26 +143,6 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
Documentation
</a>
</Button>
-
- {isAiAssistantEnabled && (
- <ButtonTooltip
- type="primary"
- disabled={!canCreatePolicies || schemaHasNoTables}
- onClick={() => setShowPolicyAiEditor(true)}
- tooltip={{
- content: {
- side: 'bottom',
- text: !canCreatePolicies
- ? 'You need additional permissions to create RLS policies'
- : schemaHasNoTables
- ? `No table in schema ${schema} to create policies on`
- : undefined,
- },
- }}
- >
- Create a new policy
- </ButtonTooltip>
- )}
</div>
</div>
</div>
diff --git a/packages/ai-commands/package.json b/packages/ai-commands/package.json
index d60f94f559d..2db6c03668b 100644
--- a/packages/ai-commands/package.json
+++ b/packages/ai-commands/package.json
@@ -20,6 +20,7 @@
"openai": "^4.26.1"
},
"devDependencies": {
+ "api-types": "*",
"@babel/core": "^7.23.6",
"@babel/preset-env": "^7.23.6",
"@jest/globals": "^29.7.0",
diff --git a/packages/ai-commands/src/sql/rls.ts b/packages/ai-commands/src/sql/rls.ts
index 9bc1bfd6f5c..905bb276b67 100644
--- a/packages/ai-commands/src/sql/rls.ts
+++ b/packages/ai-commands/src/sql/rls.ts
@@ -3,6 +3,9 @@ import { codeBlock, oneLine, stripIndent } from 'common-tags'
import type OpenAI from 'openai'
import { ContextLengthError } from '../errors'
import type { Message } from '../types'
+import { components } from 'api-types'
+
+type DatabasePoliciesData = components['schemas']['PostgresPolicy']
/**
* Responds to a conversation about building an RLS policy.
@@ -13,14 +16,15 @@ export async function chatRlsPolicy(
openai: OpenAI,
messages: Message[],
entityDefinitions?: string[],
+ existingPolicies?: DatabasePoliciesData[],
policyDefinition?: string
): Promise<ReadableStream<Uint8Array>> {
const initMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{
role: 'system',
content: 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
+ 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.
The output should use the following instructions:
@@ -36,11 +40,11 @@ export async function chatRlsPolicy(
- DELETE policies should always have USING but not WITH CHECK
- Don't use \`FOR ALL\`. Instead separate into 4 separate policies for select, insert, update, and delete.
- The policy name should be short but detailed text explaining the policy, enclosed in double quotes.
- - Always put explanations as separate text. Never use inline SQL comments.
- - If the user asks for something that's not related to SQL policies, explain to the user
+ - Always put explanations as separate text. Never use inline SQL comments.
+ - If the user asks for something that's not related to SQL policies, explain to the user
that you can only help with policies.
- Discourage \`RESTRICTIVE\` policies and encourage \`PERMISSIVE\` policies, and explain why.
-
+
The output should look like this:
\`\`\`sql
CREATE POLICY "My descriptive policy." ON books FOR INSERT to authenticated USING ( (select auth.uid()) = author_id ) WITH ( true );
@@ -267,6 +271,29 @@ export async function chatRlsPolicy(
})
}
+ if (existingPolicies !== undefined && existingPolicies.length > 0) {
+ const formattedPolicies = existingPolicies
+ .map(
+ (policy: DatabasePoliciesData) => `
+ Policy Name: "${policy.name}"
+ Action: ${policy.action}
+ Roles: ${policy.roles.join(', ')}
+ Command: ${policy.command}
+ Definition: ${policy.definition}
+ ${policy.check ? `Check: ${policy.check}` : ''}
+ `
+ )
+ .join('\n')
+
+ initMessages.push({
+ role: 'user',
+ content: codeBlock`
+ Here are my existing policy definitions on this table for reference:
+ ${formattedPolicies}
+ `.trim(),
+ })
+ }
+
if (policyDefinition !== undefined) {
const definitionBlock = codeBlock`${policyDefinition}`
initMessages.push({