Skip to content

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

Chore/deprecate old ai assistants (#30888)

Joshen Lim21017c9cfb1e
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
deleted file mode 100644
index 29545a60c92..00000000000
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
+++ /dev/null
@@ -1,214 +0,0 @@
-import { compact, last } from 'lodash'
-import { ChevronsUpDown, Lightbulb } from 'lucide-react'
-import Link from 'next/link'
-import { useEffect, useRef, useState } from 'react'
-
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
-import { SchemaComboBox } from 'components/ui/SchemaComboBox'
-import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
-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 { IS_PLATFORM } from 'lib/constants'
-import { useProfile } from 'lib/profile'
-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 { profile } = useProfile()
- const project = useSelectedProject()
- const selectedOrganization = useSelectedOrganization()
-
- const bottomRef = useRef<HTMLDivElement>(null)
- const [selectedSchemas, setSelectedSchemas] = useSchemasForAi(project?.ref!)
- const [value, setValue] = useState<string>('')
- const [hasSuggested, setHasSuggested] = useState(false)
- const inputRef = useRef<HTMLTextAreaElement>(null)
-
- const isOptedInToAI = useOrgOptedIntoAi()
- const includeSchemaMetadata = isOptedInToAI || !IS_PLATFORM
-
- const name = compact([profile?.first_name, profile?.last_name]).join(' ')
- const pendingReply = loading && last(messages)?.role === 'user'
-
- const { mutate: sendEvent } = useSendEventMutation()
-
- useEffect(() => {
- if (!loading) {
- setValue('')
- if (inputRef.current) inputRef.current.focus()
- }
-
- // Try to scroll on each rerender to the bottom
- setTimeout(
- () => {
- if (bottomRef.current) {
- bottomRef.current.scrollIntoView({ behavior: 'smooth' })
- }
- },
- loading ? 100 : 500
- )
- }, [loading])
-
- 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 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"
- content={`Hi${
- name ? ' ' + name : ''
- }, I can help you to write RLS policies. I'm powered by AI, so surprises and mistakes are possible.
- Make sure to verify any generated code or suggestions, and share feedback so that we can
- learn and improve.`}
- >
- {includeSchemaMetadata ? (
- <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
- size="tiny"
- type="default"
- className="w-min"
- iconRight={<ChevronsUpDown size={14} />}
- tooltip={{
- content: {
- side: 'bottom',
- className: 'w-72',
- text: (
- <>
- Opt in to sending anonymous data to OpenAI in your{' '}
- <Link
- className="underline"
- href={`/org/${selectedOrganization?.slug}/general`}
- >
- organization settings
- </Link>{' '}
- to share schemas with the Assistant for more accurate responses.
- </>
- ),
- },
- }}
- >
- No schemas selected
- </ButtonTooltip>
- )}
- </Message>
- {messages.map((m) => (
- <Message
- key={`message-${m.id}`}
- name={m.name}
- role={m.role}
- content={m.content}
- createdAt={new Date(m.createdAt || new Date()).getTime()}
- isDebug={m.isDebug}
- isSelected={m.id === selectedMessage}
- 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}
- loading={loading}
- disabled={loading}
- icon={
- <AiIconAnimation
- allowHoverEffect
- className="[&>div>div]:border-black dark:[&>div>div]:border-white"
- />
- }
- placeholder="Ask for help with your RLS policies"
- value={value}
- onValueChange={(e) => setValue(e.target.value)}
- onSubmit={(event) => {
- event.preventDefault()
- onSubmit(value)
- sendEvent({
- category: 'rls_editor',
- action: 'ai_suggestion_asked',
- label: 'rls-ai-assistant',
- })
- }}
- />
- </div>
- </div>
- )
-}
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyPre.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyPre.tsx
deleted file mode 100644
index b6c88f2d44f..00000000000
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyPre.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import * as Tooltip from '@radix-ui/react-tooltip'
-import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
-import { Check, Copy, FileDiff } from 'lucide-react'
-import { useEffect, useState } from 'react'
-import { format } from 'sql-formatter'
-import { Button, CodeBlock, cn } from 'ui'
-
-interface AAIPolicyPreProps {
- onDiff: (s: string) => void
- children: string[]
- className?: string
-}
-
-export const AIPolicyPre = ({ onDiff, children, className }: AAIPolicyPreProps) => {
- 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(
- '!py-3 !px-3.5 prose dark:prose-dark transition',
- // 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'
- )}
- hideCopy
- hideLineNumbers
- />
- <div
- className={cn(
- 'absolute',
- 'top-0 right-2',
- 'bg-surface-300',
- 'border border-strong',
- 'rounded',
- 'h-[28px]',
- 'opacity-0 group-hover:opacity-100',
- 'group-hover:top-2',
- 'transition-all'
- )}
- >
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
- <Button
- type="text"
- size="tiny"
- className={cn('text-foreground-lighter hover:text-foreground', 'transition')}
- onClick={() => {
- onDiff(formatted)
- sendEvent({
- category: 'rls_editor',
- action: 'ai_suggestion_diffed',
- label: 'rls-ai-assistant',
- })
- }}
- >
- <FileDiff className={cn('h-4 w-4')} />
- </Button>
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <span className="text-xs text-foreground">Apply changes</span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
- <Button
- type="text"
- size="tiny"
- className={cn('text-foreground-lighter hover:text-foreground', 'transition')}
- onClick={() => {
- handleCopy(formatted)
- sendEvent({
- category: 'rls_editor',
- action: 'ai_suggestion_copied',
- label: 'rls-ai-assistant',
- })
- }}
- >
- {copied ? (
- <Check size={16} className="text-brand-600" />
- ) : (
- <Copy size={16} className={cn('h-4 w-4')} />
- )}
- </Button>
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <span className="text-xs text-foreground">Copy code</span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
- </div>
- </pre>
- )
-}
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/Message.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/Message.tsx
deleted file mode 100644
index de1f663d796..00000000000
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/Message.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-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 } from 'ui'
-
-import { useProfile } from 'lib/profile'
-import { AIPolicyPre } from './AIPolicyPre'
-
-interface MessageProps {
- name?: string
- role: 'function' | 'system' | 'user' | 'assistant' | 'data' | 'tool'
- content?: string
- createdAt?: number
- isDebug?: boolean
- isSelected?: boolean
- onDiff?: (s: string) => void
-}
-
-const Message = memo(function Message({
- name,
- role,
- content,
- createdAt,
- isDebug,
- isSelected,
- onDiff = noop,
- children,
-}: PropsWithChildren<MessageProps>) {
- const { profile } = useProfile()
-
- const icon = useMemo(() => {
- return role === 'assistant' ? (
- <div
- className={cn(
- 'bg-foreground border border-foreground-light rounded-full',
- 'w-8 h-8',
- 'flex items-center justify-center'
- )}
- >
- <AiIconAnimation
- loading={content === 'Thinking...'}
- className={cn('scale-75', '[&>div>div]:border-background')}
- />
- </div>
- ) : (
- <div className="relative border shadow-lg w-8 h-8 rounded-full overflow-hidden">
- {/* // TODO: this only works for GitHub profiles */}
- <Image
- src={`https://github.com/${profile?.username}.png` || ''}
- width={30}
- height={30}
- alt="avatar"
- className="relative"
- />
- </div>
- )
- }, [content, profile?.username, role])
-
- if (!content) return null
-
- return (
- <div className="flex flex-col py-4 gap-4 px-5 text-foreground-light text-sm">
- <div className="flex flex-row gap-3 items-center">
- {icon}
- <span className="text-foreground">
- {role === 'assistant' ? 'Assistant' : name ? name : 'You'}
- </span>
- {createdAt && (
- <span className="text-xs text-foreground-muted">{dayjs(createdAt).fromNow()}</span>
- )}
- {isDebug && <Badge variant="warning">Debug request</Badge>}
- </div>
- <ReactMarkdown
- className="gap-2.5 flex flex-col"
- remarkPlugins={[remarkGfm]}
- components={{
- ...markdownComponents,
- pre: (props: any) => {
- return (
- <AIPolicyPre
- onDiff={onDiff}
- className={cn(
- 'transition',
- isSelected ? '[&>div>pre]:!border-stronger [&>div>pre]:!bg-surface-200' : ''
- )}
- >
- {props.children[0].props.children}
- </AIPolicyPre>
- )
- },
- }}
- >
- {content}
- </ReactMarkdown>
- {children}
- </div>
- )
-})
-
-export default Message
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
deleted file mode 100644
index 62dfc833efb..00000000000
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
+++ /dev/null
@@ -1,943 +0,0 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import { Monaco } from '@monaco-editor/react'
-import type { PostgresPolicy } from '@supabase/postgres-meta'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useQueryClient } from '@tanstack/react-query'
-import { isEqual, uniqBy } from 'lodash'
-import { FileDiff } from 'lucide-react'
-import dynamic from 'next/dynamic'
-import { useQueryState } from 'nuqs'
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { useForm } from 'react-hook-form'
-import { toast } from 'sonner'
-import * as z from 'zod'
-
-import { useChat } from 'ai/react'
-import { IS_PLATFORM, useParams } from 'common'
-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'
-import { QueryResponseError, useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
-import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useSendEventMutation } from 'data/telemetry/send-event-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 } from 'lib/constants'
-import { uuidv4 } from 'lib/helpers'
-import {
- Button,
- Checkbox_Shadcn_,
- Form_Shadcn_,
- Label_Shadcn_,
- ScrollArea,
- Sheet,
- SheetContent,
- SheetFooter,
- TabsContent_Shadcn_,
- TabsList_Shadcn_,
- TabsTrigger_Shadcn_,
- Tabs_Shadcn_,
- cn,
-} from 'ui'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import { AIPolicyChat } from './AIPolicyChat'
-import {
- MessageWithDebug,
- checkIfPolicyHasChanged,
- generateCreatePolicyQuery,
- generatePlaceholder,
- generatePolicyDefinition,
- generateThreadMessage,
-} from './AIPolicyEditorPanel.utils'
-import { AIPolicyHeader } from './AIPolicyHeader'
-import { LockedCreateQuerySection, LockedRenameQuerySection } from './LockedQuerySection'
-import { PolicyDetailsV2 } from './PolicyDetailsV2'
-import { PolicyTemplates } from './PolicyTemplates'
-import QueryError from './QueryError'
-import RLSCodeEditor from './RLSCodeEditor'
-
-const DiffEditor = dynamic(
- () => import('@monaco-editor/react').then(({ DiffEditor }) => DiffEditor),
- { ssr: false }
-)
-
-interface AIPolicyEditorPanelProps {
- visible: boolean
- schema: string
- searchString?: string
- selectedTable?: string
- selectedPolicy?: PostgresPolicy
- onSelectCancel: () => void
- authContext: 'database' | 'realtime'
-}
-
-/**
- * Using memo for this component because everything rerenders on window focus because of outside fetches
- */
-export const AIPolicyEditorPanel = memo(function ({
- visible,
- schema,
- searchString,
- selectedTable,
- selectedPolicy,
- onSelectCancel,
- authContext,
-}: AIPolicyEditorPanelProps) {
- const { ref } = useParams()
- const queryClient = useQueryClient()
- const selectedProject = useSelectedProject()
- const selectedOrganization = useSelectedOrganization()
-
- 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('')
- const [fieldError, setFieldError] = useState<string>()
- const [showCheckBlock, setShowCheckBlock] = useState(true)
-
- const monacoOneRef = useRef<Monaco | null>(null)
- const editorOneRef = useRef<IStandaloneCodeEditor | null>(null)
- const [expOneLineCount, setExpOneLineCount] = useState(1)
- const [expOneContentHeight, setExpOneContentHeight] = useState(0)
-
- const monacoTwoRef = useRef<Monaco | null>(null)
- const editorTwoRef = useRef<IStandaloneCodeEditor | null>(null)
- const [expTwoLineCount, setExpTwoLineCount] = useState(1)
- const [expTwoContentHeight, setExpTwoContentHeight] = useState(0)
-
- // 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'>(
- editView as 'templates' | 'conversation'
- )
-
- const diffEditorRef = useRef<IStandaloneDiffEditor | null>(null)
- const placeholder = generatePlaceholder(selectedPolicy)
- const isOptedInToAI = useOrgOptedIntoAi()
-
- const [error, setError] = useState<QueryResponseError>()
- const [errorPanelOpen, setErrorPanelOpen] = useState<boolean>(true)
- const [showDetails, setShowDetails] = useState<boolean>(false)
- const [selectedDiff, setSelectedDiff] = useState<string>()
- // [Joshen] Separate state here as there's a delay between submitting and the API updating the loading status
- const [debugThread, setDebugThread] = useState<MessageWithDebug[]>([])
- const [assistantVisible, setAssistantPanel] = useState<boolean>(false)
- const [incomingChange, setIncomingChange] = useState<string>()
- // Used for confirmation when closing the panel with unsaved changes
- const [isClosingPolicyEditorPanel, setIsClosingPolicyEditorPanel] = useState<boolean>(false)
-
- const formId = 'rls-editor'
- const FormSchema = z.object({
- name: z.string().min(1, 'Please provide a name'),
- table: z.string(),
- behavior: z.string(),
- command: z.string(),
- roles: z.string(),
- })
- const defaultValues = {
- name: '',
- table: '',
- behavior: 'permissive',
- command: 'select',
- roles: '',
- }
- const form = useForm<z.infer<typeof FormSchema>>({
- mode: 'onBlur',
- reValidateMode: 'onBlur',
- resolver: zodResolver(FormSchema),
- defaultValues,
- })
-
- // Customers on HIPAA plans should not have access to Supabase AI
- const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: selectedOrganization?.slug })
- 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,
- projectRef: selectedProject?.ref,
- connectionString: selectedProject?.connectionString,
- },
- { enabled: true, refetchOnWindowFocus: false }
- )
- const entityDefinitions = entities?.map((def) => def.sql.trim())
-
- const { name, table, behavior, command, roles } = form.watch()
- 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,
- isLoading,
- } = useChat({
- id: chatId,
- api: `${BASE_PATH}/api/ai/sql/suggest`,
- body: {
- entityDefinitions: isOptedInToAI || !IS_PLATFORM ? entityDefinitions : undefined,
- existingPolicies,
- policyDefinition:
- selectedPolicy !== undefined ? generatePolicyDefinition(selectedPolicy) : undefined,
- },
- })
-
- const messages = useMemo(() => {
- const merged = [...debugThread, ...chatMessages.map((m) => ({ ...m, isDebug: false }))]
-
- return merged.sort(
- (a, b) =>
- (a.createdAt?.getTime() ?? 0) - (b.createdAt?.getTime() ?? 0) ||
- a.role.localeCompare(b.role)
- )
- }, [chatMessages, debugThread])
-
- const { mutate: sendEvent } = useSendEventMutation()
-
- const { mutate: executeMutation, isLoading: isExecuting } = useExecuteSqlMutation({
- onSuccess: async () => {
- // refresh all policies
- await queryClient.invalidateQueries(databasePoliciesKeys.list(ref))
- toast.success('Successfully created new policy')
- onSelectCancel()
- },
- onError: (error) => setError(error),
- })
-
- const { mutate: updatePolicy, isLoading: isUpdating } = useDatabasePolicyUpdateMutation({
- onSuccess: () => {
- toast.success('Successfully updated policy')
- onSelectCancel()
- },
- })
-
- const { mutateAsync: debugSql, isLoading: isDebugSqlLoading } = useSqlDebugMutation()
-
- const acceptChange = useCallback(async () => {
- if (!incomingChange || !editorOneRef.current || !diffEditorRef.current) return
-
- const editorModel = editorOneRef.current.getModel()
- const diffModel = diffEditorRef.current.getModel()
- if (!editorModel || !diffModel) return
-
- const sql = diffModel.modified.getValue()
-
- // apply the incoming change in the editor directly so that Undo/Redo work properly
- editorOneRef.current.executeEdits('apply-ai-edit', [
- { text: sql, range: editorModel.getFullModelRange() },
- ])
-
- // remove the incoming change to revert to the original editor
- setIncomingChange(undefined)
- }, [incomingChange])
-
- const onClosingPanel = () => {
- const editorOneValue = editorOneRef.current?.getValue().trim() ?? null
- const editorOneFormattedValue = !editorOneValue ? null : editorOneValue
- const editorTwoValue = editorTwoRef.current?.getValue().trim() ?? null
- const editorTwoFormattedValue = !editorTwoValue ? null : editorTwoValue
-
- const policyCreateUnsaved =
- selectedPolicy === undefined &&
- (name.length > 0 || roles.length > 0 || editorOneFormattedValue || editorTwoFormattedValue)
- const policyUpdateUnsaved =
- selectedPolicy !== undefined
- ? checkIfPolicyHasChanged(selectedPolicy, {
- name,
- roles: roles.length === 0 ? ['public'] : roles.split(', '),
- definition: editorOneFormattedValue,
- check: command === 'INSERT' ? editorOneFormattedValue : editorTwoFormattedValue,
- })
- : false
-
- if (policyCreateUnsaved || policyUpdateUnsaved || messages.length > 0) {
- setIsClosingPolicyEditorPanel(true)
- } else {
- onSelectCancel()
- setEditView(null)
- }
- }
-
- const onSelectDebug = async () => {
- const policy = editorOneRef.current?.getValue().replaceAll('\n', ' ').replaceAll(' ', ' ')
- if (error === undefined || policy === undefined) return
-
- setAssistantPanel(true)
- const messageId = uuidv4()
-
- const assistantMessageBefore = generateThreadMessage({
- id: messageId,
- content: 'Thinking...',
- isDebug: true,
- })
- setDebugThread([...debugThread, assistantMessageBefore])
-
- const { solution, sql } = await debugSql({
- sql: policy.trim(),
- errorMessage: error.message,
- entityDefinitions,
- })
-
- const assistantMessageAfter = generateThreadMessage({
- id: messageId,
- content: `${solution}\n\`\`\`sql\n${sql}\n\`\`\``,
- isDebug: true,
- })
- const cleanedMessages = uniqBy([...debugThread, assistantMessageAfter], (m) => m.id)
-
- setDebugThread(cleanedMessages)
- }
-
- const updateEditorWithCheckForDiff = (value: { id: string; content: string }) => {
- const editorModel = editorOneRef.current?.getModel()
- if (!editorModel) return
-
- const existingValue = editorOneRef.current?.getValue() ?? ''
- if (existingValue.length === 0) {
- editorOneRef.current?.executeEdits('apply-template', [
- {
- text: value.content,
- range: editorModel.getFullModelRange(),
- },
- ])
- } else {
- setSelectedDiff(value.id)
- setIncomingChange(value.content)
- }
- }
-
- const onSubmit = (data: z.infer<typeof FormSchema>) => {
- const { name, table, behavior, command, roles } = data
- let using = editorOneRef.current?.getValue().trim() ?? undefined
- let check = editorTwoRef.current?.getValue().trim()
-
- // [Terry] b/c editorOneRef will be the check statement in this scenario
- if (command === 'insert') {
- check = using
- }
-
- if (command === 'insert' && (check === undefined || check.length === 0)) {
- return setFieldError('Please provide a SQL expression for the WITH CHECK statement')
- } else if (command !== 'insert' && (using === undefined || using.length === 0)) {
- return setFieldError('Please provide a SQL expression for the USING statement')
- } else {
- setFieldError(undefined)
- }
-
- if (selectedPolicy === undefined) {
- const sql = generateCreatePolicyQuery({
- name: name,
- schema,
- table,
- behavior,
- command,
- roles: roles.length === 0 ? 'public' : roles,
- using: using ?? '',
- check: command === 'insert' ? using ?? '' : check ?? '',
- })
-
- setError(undefined)
- executeMutation({
- sql,
- projectRef: selectedProject?.ref,
- connectionString: selectedProject?.connectionString,
- handleError: (error) => {
- throw error
- },
- })
- } else if (selectedProject !== undefined) {
- const payload: {
- name?: string
- definition?: string
- check?: string
- roles?: string[]
- } = {}
- const updatedRoles = roles.length === 0 ? ['public'] : roles.split(', ')
-
- if (name !== selectedPolicy.name) payload.name = name
- if (!isEqual(selectedPolicy.roles, updatedRoles)) payload.roles = updatedRoles
- if (selectedPolicy.definition !== null && selectedPolicy.definition !== using)
- payload.definition = using
-
- if (selectedPolicy.command === 'INSERT') {
- // [Joshen] Cause editorOneRef will be the check statement in this scenario
- if (selectedPolicy.check !== null && selectedPolicy.check !== using) payload.check = using
- } else {
- if (selectedPolicy.check !== null && selectedPolicy.check !== check) payload.check = check
- }
-
- if (Object.keys(payload).length === 0) return onSelectCancel()
-
- updatePolicy({
- id: selectedPolicy.id,
- projectRef: selectedProject.ref,
- connectionString: selectedProject?.connectionString,
- payload,
- })
- }
- }
-
- const clearHistory = () => {
- setChatId(uuidv4())
- }
-
- // when the panel is closed, reset all values
- useEffect(() => {
- if (!visible) {
- editorOneRef.current?.setValue('')
- editorTwoRef.current?.setValue('')
- setIncomingChange(undefined)
- setAssistantPanel(false)
- setIsClosingPolicyEditorPanel(false)
- setError(undefined)
- setDebugThread([])
- setChatId(uuidv4())
- setShowDetails(false)
- setSelectedDiff(undefined)
-
- setUsing('')
- setCheck('')
- setShowCheckBlock(false)
- setFieldError(undefined)
-
- form.reset(defaultValues)
- } else {
- if (canUpdatePolicies) setAssistantPanel(true)
- if (selectedPolicy !== undefined) {
- const { name, action, table, command, roles } = selectedPolicy
- form.reset({
- name,
- table,
- behavior: action.toLowerCase(),
- command: command.toLowerCase(),
- roles: roles.length === 1 && roles[0] === 'public' ? '' : roles.join(', '),
- })
- if (selectedPolicy.definition) setUsing(` ${selectedPolicy.definition}`)
- if (selectedPolicy.check) setCheck(` ${selectedPolicy.check}`)
- if (selectedPolicy.check && selectedPolicy.command !== 'INSERT') {
- setShowCheckBlock(true)
- }
- } else if (selectedTable !== undefined) {
- form.reset({ ...defaultValues, table: selectedTable })
- }
- }
- }, [visible])
-
- // whenever the deps (current policy details, new error or error panel opens) change, recalculate
- // the height of the editor
- useEffect(() => {
- editorOneRef.current?.layout({ width: 0, height: 0 })
- window.requestAnimationFrame(() => {
- editorOneRef.current?.layout()
- })
- }, [showDetails, error, errorPanelOpen])
-
- // update tabId when the editView changes
- useEffect(() => {
- editView === 'conversation' ? setTabId('conversation') : setTabId('templates')
- }, [editView])
-
- return (
- <>
- <Form_Shadcn_ {...form}>
- <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>
- <Sheet open={visible} onOpenChange={() => onClosingPanel()}>
- <SheetContent
- showClose={false}
- size={assistantVisible ? 'lg' : 'default'}
- className={cn(
- 'bg-surface-200',
- 'p-0 flex flex-row gap-0',
- assistantVisible ? '!min-w-[1000px]' : '!min-w-[600px]'
- )}
- >
- <div className={cn('flex flex-col grow w-full', assistantVisible && 'w-[60%]')}>
- <AIPolicyHeader
- selectedPolicy={selectedPolicy}
- assistantVisible={assistantVisible}
- setAssistantVisible={setAssistantPanel}
- />
-
- <div className="flex flex-col h-full w-full justify-between overflow-y-auto">
- {incomingChange ? (
- <div className="px-5 py-3 flex justify-between gap-3 bg-surface-75">
- <div className="flex gap-2 items-center text-foreground-light">
- <FileDiff className="h-4 w-4" />
- <span className="text-sm">Accept changes from assistant</span>
- </div>
- <div className="flex gap-3">
- <Button
- type="default"
- onClick={() => {
- setIncomingChange(undefined)
- setSelectedDiff(undefined)
- sendEvent({
- category: 'rls_editor',
- action: 'ai_suggestion_discarded',
- label: 'rls-ai-assistant',
- })
- }}
- >
- Discard
- </Button>
- <Button
- type="primary"
- onClick={() => {
- acceptChange()
- setSelectedDiff(undefined)
- sendEvent({
- category: 'rls_editor',
- action: 'ai_suggestion_accepted',
- label: 'rls-ai-assistant',
- })
- }}
- >
- Accept
- </Button>
- </div>
- </div>
- ) : null}
-
- {incomingChange ? (
- <DiffEditor
- theme="supabase"
- language="pgsql"
- className="grow"
- original={editorOneRef.current?.getValue()}
- modified={incomingChange}
- onMount={(editor) => (diffEditorRef.current = editor)}
- options={{
- wordWrap: 'on',
- renderSideBySide: false,
- scrollBeyondLastLine: false,
- renderOverviewRuler: false,
- renderLineHighlight: 'none',
- minimap: { enabled: false },
- occurrencesHighlight: false,
- folding: false,
- selectionHighlight: false,
- lineHeight: 20,
- padding: { top: 10, bottom: 10 },
- }}
- />
- ) : null}
-
- {/* 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>
- ) : (
- <>
- <PolicyDetailsV2
- schema={schema}
- searchString={searchString}
- selectedTable={selectedTable}
- isEditing={selectedPolicy !== undefined}
- form={form}
- onUpdateCommand={(command: string) => {
- setFieldError(undefined)
- if (!['update', 'all'].includes(command)) {
- setShowCheckBlock(false)
- } else {
- setShowCheckBlock(true)
- }
- }}
- authContext={authContext}
- />
- <div className="h-full">
- <LockedCreateQuerySection
- schema={schema}
- selectedPolicy={selectedPolicy}
- formFields={{ name, table, behavior, command, roles }}
- />
-
- <div
- className={`mt-1 relative ${incomingChange ? 'hidden' : 'block'}`}
- style={{
- height:
- expOneContentHeight <= 100 ? `${8 + expOneContentHeight}px` : '108px',
- }}
- >
- <RLSCodeEditor
- 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'
- : '-- Provide a SQL expression for the using statement'
- }
- defaultValue={command === 'insert' ? check : using}
- value={command === 'insert' ? check : using}
- editorRef={editorOneRef}
- monacoRef={monacoOneRef as any}
- lineNumberStart={6}
- onChange={() => {
- setExpOneContentHeight(editorOneRef.current?.getContentHeight() ?? 0)
- setExpOneLineCount(
- editorOneRef.current?.getModel()?.getLineCount() ?? 1
- )
- }}
- onMount={() => {
- setTimeout(() => {
- setExpOneContentHeight(
- editorOneRef.current?.getContentHeight() ?? 0
- )
- setExpOneLineCount(
- editorOneRef.current?.getModel()?.getLineCount() ?? 1
- )
- }, 200)
- }}
- />
- </div>
-
- <div className="bg-surface-300 py-1">
- <div className="flex items-center" style={{ fontSize: '14px' }}>
- <div className="w-[57px]">
- <p className="w-[31px] flex justify-end font-mono text-sm text-foreground-light select-none">
- {7 + expOneLineCount}
- </p>
- </div>
- <p className="font-mono tracking-tighter">
- {showCheckBlock ? (
- <>
- <span className="text-[#569cd6]">with check</span>{' '}
- <span className="text-[#ffd700]">(</span>
- </>
- ) : (
- <>
- <span className="text-[#ffd700]">)</span>;
- </>
- )}
- </p>
- </div>
- </div>
-
- {showCheckBlock && (
- <>
- <div
- className={`mt-1 min-h-[28px] relative ${incomingChange ? 'hidden' : 'block'}`}
- style={{
- height:
- expTwoContentHeight <= 100
- ? `${8 + expTwoContentHeight}px`
- : '108px',
- }}
- >
- <RLSCodeEditor
- disableTabToUsePlaceholder
- readOnly={!canUpdatePolicies}
- id="rls-exp-two-editor"
- placeholder="-- Provide a SQL expression for the with check statement"
- defaultValue={check}
- value={check}
- editorRef={editorTwoRef}
- monacoRef={monacoTwoRef as any}
- lineNumberStart={7 + expOneLineCount}
- editView={editView as 'templates' | 'conversation'} // someone help
- onChange={() => {
- setExpTwoContentHeight(
- editorTwoRef.current?.getContentHeight() ?? 0
- )
- setExpTwoLineCount(
- editorTwoRef.current?.getModel()?.getLineCount() ?? 1
- )
- }}
- onMount={() => {
- setTimeout(() => {
- setExpTwoContentHeight(
- editorTwoRef.current?.getContentHeight() ?? 0
- )
- setExpTwoLineCount(
- editorTwoRef.current?.getModel()?.getLineCount() ?? 1
- )
- }, 200)
- }}
- />
- </div>
- <div className="bg-surface-300 py-1">
- <div className="flex items-center" style={{ fontSize: '14px' }}>
- <div className="w-[57px]">
- <p className="w-[31px] flex justify-end font-mono text-sm text-foreground-light select-none">
- {8 + expOneLineCount + expTwoLineCount}
- </p>
- </div>
- <p className="font-mono tracking-tighter">
- <span className="text-[#ffd700]">)</span>;
- </p>
- </div>
- </div>
- </>
- )}
-
- {isRenamingPolicy && (
- <LockedRenameQuerySection
- oldName={selectedPolicy.name}
- newName={name}
- schema={schema}
- table={table}
- lineNumber={
- 8 + expOneLineCount + (showCheckBlock ? expTwoLineCount : 0)
- }
- />
- )}
-
- {fieldError !== undefined && (
- <p className="px-5 py-2 pb-0 text-sm text-red-900">{fieldError}</p>
- )}
-
- {supportWithCheck && (
- <div className="px-5 py-3 flex items-center gap-x-2">
- <Checkbox_Shadcn_
- id="use-check"
- name="use-check"
- checked={showCheckBlock}
- onCheckedChange={() => {
- setFieldError(undefined)
- setShowCheckBlock(!showCheckBlock)
- }}
- />
- <Label_Shadcn_ className="text-xs cursor-pointer" htmlFor="use-check">
- Use check expression
- </Label_Shadcn_>
- </div>
- )}
- </div>
- </>
- )}
-
- <div className="flex flex-col">
- {error !== undefined && (
- <QueryError
- error={error}
- onSelectDebug={() => {
- setTabId('conversation')
- onSelectDebug()
- }}
- open={errorPanelOpen}
- setOpen={setErrorPanelOpen}
- />
- )}
- <SheetFooter className="flex items-center !justify-end px-5 py-4 w-full border-t">
- <Button
- type="default"
- disabled={isExecuting || isUpdating}
- onClick={() => onClosingPanel()}
- >
- Cancel
- </Button>
-
- <ButtonTooltip
- form={formId}
- htmlType="submit"
- loading={isExecuting || isUpdating}
- disabled={
- !canUpdatePolicies ||
- isExecuting ||
- isUpdating ||
- incomingChange !== undefined
- }
- onClick={() => {
- if (editView === 'conversation') {
- 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: {
- side: 'top',
- text: !canUpdatePolicies
- ? 'You need additional permissions to update policies'
- : undefined,
- },
- }}
- >
- Save policy
- </ButtonTooltip>
- </SheetFooter>
- </div>
- </div>
- </div>
- {assistantVisible && (
- <div
- className={cn(
- 'border-l shadow-[rgba(0,0,0,0.13)_-4px_0px_6px_0px] z-10',
- assistantVisible && 'w-[50%]',
- 'bg-studio overflow-auto'
- )}
- >
- <Tabs_Shadcn_
- value={tabId}
- defaultValue="templates"
- className="flex flex-col h-full w-full"
- >
- <TabsList_Shadcn_ className="flex gap-4 px-content pt-2">
- {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"
- onClick={() => setTabId('conversation')}
- className="px-0 data-[state=active]:bg-transparent"
- >
- Assistant
- </TabsTrigger_Shadcn_>
- )}
- </TabsList_Shadcn_>
-
- {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())
- form.setValue('roles', value.roles.join(', ') ?? '')
-
- setUsing(` ${value.definition}`)
- setCheck(` ${value.check}`)
- setExpOneLineCount(1)
- setExpTwoLineCount(1)
- setFieldError(undefined)
-
- if (!['update', 'all'].includes(value.command.toLowerCase())) {
- setShowCheckBlock(false)
- } else if (value.check.length > 0) {
- setShowCheckBlock(true)
- } else {
- setShowCheckBlock(false)
- }
- }}
- />
- </ScrollArea>
- </TabsContent_Shadcn_>
- )}
-
- <TabsContent_Shadcn_
- value="conversation"
- className="flex grow !mt-0 overflow-y-auto"
- >
- <AIPolicyChat
- selectedTable={selectedTable!}
- messages={messages}
- selectedMessage={selectedDiff}
- onSubmit={(message) =>
- append({
- content: message,
- role: 'user',
- createdAt: new Date(),
- })
- }
- onDiff={updateEditorWithCheckForDiff}
- loading={isLoading || isDebugSqlLoading}
- clearHistory={clearHistory}
- />
- </TabsContent_Shadcn_>
- </Tabs_Shadcn_>
- </div>
- )}
- </SheetContent>
- </Sheet>
- </form>
- </Form_Shadcn_>
-
- <ConfirmationModal
- visible={isClosingPolicyEditorPanel}
- title="Discard changes"
- confirmLabel="Discard"
- onCancel={() => {
- setIsClosingPolicyEditorPanel(false)
- }}
- onConfirm={() => {
- onSelectCancel()
- setIsClosingPolicyEditorPanel(false)
- setEditView(null)
- }}
- >
- <p className="text-sm text-foreground-light">
- Are you sure you want to close the editor? Any unsaved changes on your policy and
- conversations with the Assistant will be lost.
- </p>
- </ConfirmationModal>
- </>
- )
-})
-
-AIPolicyEditorPanel.displayName = 'AIPolicyEditorPanel'
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/LockedQuerySection.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/LockedQuerySection.tsx
similarity index 100%
rename from apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/LockedQuerySection.tsx
rename to apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/LockedQuerySection.tsx
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetailsV2.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyDetailsV2.tsx
similarity index 100%
rename from apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetailsV2.tsx
rename to apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyDetailsV2.tsx
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.ts b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts
similarity index 63%
rename from apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.ts
rename to apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts
index 937eaaa4f1d..ba3c1e73b10 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.ts
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyEditorPanel.utils.ts
@@ -1,30 +1,7 @@
import type { PostgresPolicy } from '@supabase/postgres-meta'
import { isEqual } from 'lodash'
-import type { Message } from 'ai/react'
-import { uuidv4 } from 'lib/helpers'
-
-export type MessageWithDebug = Message & { isDebug: boolean }
-
-export const generateThreadMessage = ({
- id,
- content,
- isDebug,
-}: {
- id?: string
- content: string
- isDebug: boolean
-}) => {
- const message: MessageWithDebug = {
- id: id ?? uuidv4(),
- role: 'assistant',
- content,
- createdAt: new Date(),
- isDebug: isDebug,
- }
- return message
-}
-
+// [Joshen] Not used but keeping this for now in case we do an inline editor
export const generatePlaceholder = (policy?: PostgresPolicy) => {
if (policy === undefined) {
return `
@@ -69,17 +46,6 @@ COMMIT;
}
}
-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()
-}
-
export const generateCreatePolicyQuery = ({
name,
schema,
@@ -107,34 +73,6 @@ export const generateCreatePolicyQuery = ({
return query
}
-export const generateAlterPolicyQuery = ({
- name,
- newName,
- schema,
- table,
- command,
- roles,
- using,
- check,
-}: {
- name: string
- newName: string
- schema: string
- table: string
- command: string
- roles: string
- using: string
- check: string
-}) => {
- const querySkeleton = `alter policy "${name}" on "${schema}"."${table}" to ${roles}`
- const query =
- command === 'insert'
- ? `${querySkeleton} with check (${check});`
- : `${querySkeleton} using (${using})${(check ?? '').length > 0 ? `with check (${check});` : ';'}`
- if (newName === name) return query
- else return `${query}\n${querySkeleton} rename to "${newName}"`
-}
-
export const checkIfPolicyHasChanged = (
selectedPolicy: PostgresPolicy,
policyForm: {
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyEditorPanelHeader.tsx
similarity index 92%
rename from apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
rename to apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyEditorPanelHeader.tsx
index 81056928795..a35fc09846f 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyEditorPanelHeader.tsx
@@ -15,14 +15,14 @@ import {
cn,
} from 'ui'
-export const AIPolicyHeader = ({
+export const PolicyEditorPanelHeader = ({
selectedPolicy,
- assistantVisible,
- setAssistantVisible,
+ showTools,
+ setShowTools,
}: {
selectedPolicy?: PostgresPolicy
- assistantVisible: boolean
- setAssistantVisible: (v: boolean) => void
+ showTools: boolean
+ setShowTools: (v: boolean) => void
}) => {
const [showDetails, setShowDetails] = useState(false)
@@ -106,15 +106,15 @@ export const AIPolicyHeader = ({
<Tooltip_Shadcn_>
<TooltipTrigger_Shadcn_ asChild>
<button
- aria-expanded={assistantVisible}
+ aria-expanded={showTools}
aria-controls="ai-chat-assistant"
className={cn(
- !assistantVisible ? 'text-foreground-lighter' : 'text-light',
+ !showTools ? 'text-foreground-lighter' : 'text-light',
'mt-1 hover:text-foreground transition'
)}
- onClick={() => setAssistantVisible(!assistantVisible)}
+ onClick={() => setShowTools(!showTools)}
>
- {!assistantVisible ? (
+ {!showTools ? (
<PanelLeftClose size={19} strokeWidth={1} />
) : (
<PanelRightClose size={19} strokeWidth={1} />
@@ -122,7 +122,7 @@ export const AIPolicyHeader = ({
</button>
</TooltipTrigger_Shadcn_>
<TooltipContent_Shadcn_ side="left">
- {assistantVisible ? 'Hide' : 'Show'} tools
+ {showTools ? 'Hide' : 'Show'} tools
</TooltipContent_Shadcn_>
</Tooltip_Shadcn_>
</SheetHeader>
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyTemplates.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyTemplates.tsx
similarity index 100%
rename from apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyTemplates.tsx
rename to apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyTemplates.tsx
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/QueryError.tsx
similarity index 68%
rename from apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
rename to apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/QueryError.tsx
index 0ac3fa00896..ba1a1e5128d 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/QueryError.tsx
@@ -2,11 +2,7 @@ import { initial, last } from 'lodash'
import { Dispatch, SetStateAction } from 'react'
import styles from '@ui/layout/ai-icon-animation/ai-icon-animation-style.module.css'
-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'
-import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import {
AlertTitle_Shadcn_,
Alert_Shadcn_,
@@ -17,24 +13,15 @@ import {
cn,
} from 'ui'
-const QueryError = ({
+export const QueryError = ({
error,
open,
setOpen,
- onSelectDebug,
}: {
error: QueryResponseError
open: boolean
setOpen: Dispatch<SetStateAction<boolean>>
- onSelectDebug: () => void
}) => {
- // Customers on HIPAA plans should not have access to Supabase AI
- const organization = useSelectedOrganization()
- const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })
- const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)
-
- const { mutate: sendEvent } = useSendEventMutation()
-
const formattedError =
(error?.formattedError?.split('\n') ?? [])?.filter((x: string) => x.length > 0) ?? []
@@ -72,27 +59,6 @@ const QueryError = ({
{open ? 'Hide error details' : 'Show error details'}
</Button>
</CollapsibleTrigger_Shadcn_>
- {/* [Joshen] Temp hidden as new assistant doesnt support this. Current assistant's UX is not great too tbh so okay to hide this */}
- {/* {!hasHipaaAddon && (
- <Button
- size="tiny"
- type="default"
- className={cn(
- 'group',
- styles['ai-icon__container--allow-hover-effect h-[21px] !py-0']
- )}
- onClick={() => {
- onSelectDebug()
- sendEvent({
- category: 'rls_editor',
- action: 'ai_debugger_requested',
- label: 'rls-ai-assistant',
- })
- }}
- >
- Fix with Assistant
- </Button>
- )} */}
</div>
<CollapsibleContent_Shadcn_ className="overflow-auto">
{formattedError.length > 0 ? (
@@ -137,5 +103,3 @@ const QueryError = ({
</div>
)
}
-
-export default QueryError
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/RLSCodeEditor.tsx
similarity index 97%
rename from apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
rename to apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/RLSCodeEditor.tsx
index e27f8699a4d..fdaec522c6b 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/RLSCodeEditor.tsx
@@ -29,10 +29,9 @@ interface RLSCodeEditorProps {
editorRef: MutableRefObject<editor.IStandaloneCodeEditor | null>
monacoRef?: MutableRefObject<Monaco>
- editView: 'templates' | 'conversation' // someone help
}
-const RLSCodeEditor = ({
+export const RLSCodeEditor = ({
id,
defaultValue,
wrapperClassName,
@@ -48,7 +47,6 @@ const RLSCodeEditor = ({
editorRef,
monacoRef,
- editView,
}: RLSCodeEditorProps) => {
const hasValue = useRef<any>()
const monaco = useMonaco()
@@ -199,5 +197,3 @@ const RLSCodeEditor = ({
</>
)
}
-
-export default RLSCodeEditor
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
new file mode 100644
index 00000000000..4ee9c0d21d6
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx
@@ -0,0 +1,585 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { Monaco } from '@monaco-editor/react'
+import type { PostgresPolicy } from '@supabase/postgres-meta'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQueryClient } from '@tanstack/react-query'
+import { isEqual } from 'lodash'
+import { memo, useEffect, useRef, useState } from 'react'
+import { useForm } from 'react-hook-form'
+import { toast } from 'sonner'
+import * as z from 'zod'
+
+import { useParams } from 'common'
+import { IStandaloneCodeEditor } from 'components/interfaces/SQLEditor/SQLEditor.types'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { useDatabasePolicyUpdateMutation } from 'data/database-policies/database-policy-update-mutation'
+import { databasePoliciesKeys } from 'data/database-policies/keys'
+import { QueryResponseError, useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import {
+ Button,
+ Checkbox_Shadcn_,
+ Form_Shadcn_,
+ Label_Shadcn_,
+ ScrollArea,
+ Sheet,
+ SheetContent,
+ SheetFooter,
+ TabsContent_Shadcn_,
+ TabsList_Shadcn_,
+ TabsTrigger_Shadcn_,
+ Tabs_Shadcn_,
+ cn,
+} from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { checkIfPolicyHasChanged, generateCreatePolicyQuery } from './PolicyEditorPanel.utils'
+import { LockedCreateQuerySection, LockedRenameQuerySection } from './LockedQuerySection'
+import { PolicyDetailsV2 } from './PolicyDetailsV2'
+import { PolicyEditorPanelHeader } from './PolicyEditorPanelHeader'
+import { PolicyTemplates } from './PolicyTemplates'
+import { QueryError } from './QueryError'
+import { RLSCodeEditor } from './RLSCodeEditor'
+
+interface PolicyEditorPanelProps {
+ visible: boolean
+ schema: string
+ searchString?: string
+ selectedTable?: string
+ selectedPolicy?: PostgresPolicy
+ onSelectCancel: () => void
+ authContext: 'database' | 'realtime'
+}
+
+/**
+ * Using memo for this component because everything rerenders on window focus because of outside fetches
+ */
+export const PolicyEditorPanel = memo(function ({
+ visible,
+ schema,
+ searchString,
+ selectedTable,
+ selectedPolicy,
+ onSelectCancel,
+ authContext,
+}: PolicyEditorPanelProps) {
+ const { ref } = useParams()
+ const queryClient = useQueryClient()
+ const selectedProject = useSelectedProject()
+
+ const canUpdatePolicies = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')
+
+ // [Joshen] Hyrid form fields, just spit balling to get a decent POC out
+ const [using, setUsing] = useState('')
+ const [check, setCheck] = useState('')
+ const [fieldError, setFieldError] = useState<string>()
+ const [showCheckBlock, setShowCheckBlock] = useState(true)
+
+ const monacoOneRef = useRef<Monaco | null>(null)
+ const editorOneRef = useRef<IStandaloneCodeEditor | null>(null)
+ const [expOneLineCount, setExpOneLineCount] = useState(1)
+ const [expOneContentHeight, setExpOneContentHeight] = useState(0)
+
+ const monacoTwoRef = useRef<Monaco | null>(null)
+ const editorTwoRef = useRef<IStandaloneCodeEditor | null>(null)
+ const [expTwoLineCount, setExpTwoLineCount] = useState(1)
+ const [expTwoContentHeight, setExpTwoContentHeight] = useState(0)
+
+ const [error, setError] = useState<QueryResponseError>()
+ const [errorPanelOpen, setErrorPanelOpen] = useState<boolean>(true)
+ const [showDetails, setShowDetails] = useState<boolean>(false)
+ const [selectedDiff, setSelectedDiff] = useState<string>()
+
+ const [showTools, setShowTools] = useState<boolean>(false)
+ const [isClosingPolicyEditorPanel, setIsClosingPolicyEditorPanel] = useState<boolean>(false)
+
+ const formId = 'rls-editor'
+ const FormSchema = z.object({
+ name: z.string().min(1, 'Please provide a name'),
+ table: z.string(),
+ behavior: z.string(),
+ command: z.string(),
+ roles: z.string(),
+ })
+ const defaultValues = {
+ name: '',
+ table: '',
+ behavior: 'permissive',
+ command: 'select',
+ roles: '',
+ }
+ const form = useForm<z.infer<typeof FormSchema>>({
+ mode: 'onBlur',
+ reValidateMode: 'onBlur',
+ resolver: zodResolver(FormSchema),
+ defaultValues,
+ })
+
+ const { name, table, behavior, command, roles } = form.watch()
+ const supportWithCheck = ['update', 'all'].includes(command)
+ const isRenamingPolicy = selectedPolicy !== undefined && name !== selectedPolicy.name
+
+ const { mutate: executeMutation, isLoading: isExecuting } = useExecuteSqlMutation({
+ onSuccess: async () => {
+ // refresh all policies
+ await queryClient.invalidateQueries(databasePoliciesKeys.list(ref))
+ toast.success('Successfully created new policy')
+ onSelectCancel()
+ },
+ onError: (error) => setError(error),
+ })
+
+ const { mutate: updatePolicy, isLoading: isUpdating } = useDatabasePolicyUpdateMutation({
+ onSuccess: () => {
+ toast.success('Successfully updated policy')
+ onSelectCancel()
+ },
+ })
+
+ const onClosingPanel = () => {
+ const editorOneValue = editorOneRef.current?.getValue().trim() ?? null
+ const editorOneFormattedValue = !editorOneValue ? null : editorOneValue
+ const editorTwoValue = editorTwoRef.current?.getValue().trim() ?? null
+ const editorTwoFormattedValue = !editorTwoValue ? null : editorTwoValue
+
+ const policyCreateUnsaved =
+ selectedPolicy === undefined &&
+ (name.length > 0 || roles.length > 0 || editorOneFormattedValue || editorTwoFormattedValue)
+ const policyUpdateUnsaved =
+ selectedPolicy !== undefined
+ ? checkIfPolicyHasChanged(selectedPolicy, {
+ name,
+ roles: roles.length === 0 ? ['public'] : roles.split(', '),
+ definition: editorOneFormattedValue,
+ check: command === 'INSERT' ? editorOneFormattedValue : editorTwoFormattedValue,
+ })
+ : false
+
+ if (policyCreateUnsaved || policyUpdateUnsaved) {
+ setIsClosingPolicyEditorPanel(true)
+ } else {
+ onSelectCancel()
+ }
+ }
+
+ const onSubmit = (data: z.infer<typeof FormSchema>) => {
+ const { name, table, behavior, command, roles } = data
+ let using = editorOneRef.current?.getValue().trim() ?? undefined
+ let check = editorTwoRef.current?.getValue().trim()
+
+ // [Terry] b/c editorOneRef will be the check statement in this scenario
+ if (command === 'insert') {
+ check = using
+ }
+
+ if (command === 'insert' && (check === undefined || check.length === 0)) {
+ return setFieldError('Please provide a SQL expression for the WITH CHECK statement')
+ } else if (command !== 'insert' && (using === undefined || using.length === 0)) {
+ return setFieldError('Please provide a SQL expression for the USING statement')
+ } else {
+ setFieldError(undefined)
+ }
+
+ if (selectedPolicy === undefined) {
+ const sql = generateCreatePolicyQuery({
+ name: name,
+ schema,
+ table,
+ behavior,
+ command,
+ roles: roles.length === 0 ? 'public' : roles,
+ using: using ?? '',
+ check: command === 'insert' ? using ?? '' : check ?? '',
+ })
+
+ setError(undefined)
+ executeMutation({
+ sql,
+ projectRef: selectedProject?.ref,
+ connectionString: selectedProject?.connectionString,
+ handleError: (error) => {
+ throw error
+ },
+ })
+ } else if (selectedProject !== undefined) {
+ const payload: {
+ name?: string
+ definition?: string
+ check?: string
+ roles?: string[]
+ } = {}
+ const updatedRoles = roles.length === 0 ? ['public'] : roles.split(', ')
+
+ if (name !== selectedPolicy.name) payload.name = name
+ if (!isEqual(selectedPolicy.roles, updatedRoles)) payload.roles = updatedRoles
+ if (selectedPolicy.definition !== null && selectedPolicy.definition !== using)
+ payload.definition = using
+
+ if (selectedPolicy.command === 'INSERT') {
+ // [Joshen] Cause editorOneRef will be the check statement in this scenario
+ if (selectedPolicy.check !== null && selectedPolicy.check !== using) payload.check = using
+ } else {
+ if (selectedPolicy.check !== null && selectedPolicy.check !== check) payload.check = check
+ }
+
+ if (Object.keys(payload).length === 0) return onSelectCancel()
+
+ updatePolicy({
+ id: selectedPolicy.id,
+ projectRef: selectedProject.ref,
+ connectionString: selectedProject?.connectionString,
+ payload,
+ })
+ }
+ }
+
+ // when the panel is closed, reset all values
+ useEffect(() => {
+ if (!visible) {
+ editorOneRef.current?.setValue('')
+ editorTwoRef.current?.setValue('')
+ setShowTools(false)
+ setIsClosingPolicyEditorPanel(false)
+ setError(undefined)
+ setShowDetails(false)
+ setSelectedDiff(undefined)
+
+ setUsing('')
+ setCheck('')
+ setShowCheckBlock(false)
+ setFieldError(undefined)
+
+ form.reset(defaultValues)
+ } else {
+ if (canUpdatePolicies) setShowTools(true)
+ if (selectedPolicy !== undefined) {
+ const { name, action, table, command, roles } = selectedPolicy
+ form.reset({
+ name,
+ table,
+ behavior: action.toLowerCase(),
+ command: command.toLowerCase(),
+ roles: roles.length === 1 && roles[0] === 'public' ? '' : roles.join(', '),
+ })
+ if (selectedPolicy.definition) setUsing(` ${selectedPolicy.definition}`)
+ if (selectedPolicy.check) setCheck(` ${selectedPolicy.check}`)
+ if (selectedPolicy.check && selectedPolicy.command !== 'INSERT') {
+ setShowCheckBlock(true)
+ }
+ } else if (selectedTable !== undefined) {
+ form.reset({ ...defaultValues, table: selectedTable })
+ }
+ }
+ }, [visible])
+
+ // whenever the deps (current policy details, new error or error panel opens) change, recalculate
+ // the height of the editor
+ useEffect(() => {
+ editorOneRef.current?.layout({ width: 0, height: 0 })
+ window.requestAnimationFrame(() => {
+ editorOneRef.current?.layout()
+ })
+ }, [showDetails, error, errorPanelOpen])
+
+ return (
+ <>
+ <Form_Shadcn_ {...form}>
+ <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>
+ <Sheet open={visible} onOpenChange={() => onClosingPanel()}>
+ <SheetContent
+ showClose={false}
+ size={showTools ? 'lg' : 'default'}
+ className={cn(
+ 'bg-surface-200 p-0 flex flex-row gap-0',
+ showTools ? '!min-w-[1000px]' : '!min-w-[600px]'
+ )}
+ >
+ <div className={cn('flex flex-col grow w-full', showTools && 'w-[60%]')}>
+ <PolicyEditorPanelHeader
+ selectedPolicy={selectedPolicy}
+ showTools={showTools}
+ setShowTools={setShowTools}
+ />
+
+ <div className="flex flex-col h-full w-full justify-between overflow-y-auto">
+ <PolicyDetailsV2
+ schema={schema}
+ searchString={searchString}
+ selectedTable={selectedTable}
+ isEditing={selectedPolicy !== undefined}
+ form={form}
+ onUpdateCommand={(command: string) => {
+ setFieldError(undefined)
+ if (!['update', 'all'].includes(command)) {
+ setShowCheckBlock(false)
+ } else {
+ setShowCheckBlock(true)
+ }
+ }}
+ authContext={authContext}
+ />
+ <div className="h-full">
+ <LockedCreateQuerySection
+ schema={schema}
+ selectedPolicy={selectedPolicy}
+ formFields={{ name, table, behavior, command, roles }}
+ />
+
+ <div
+ className="mt-1 relative block"
+ style={{
+ height:
+ expOneContentHeight <= 100 ? `${8 + expOneContentHeight}px` : '108px',
+ }}
+ >
+ <RLSCodeEditor
+ disableTabToUsePlaceholder
+ readOnly={!canUpdatePolicies}
+ id="rls-exp-one-editor"
+ placeholder={
+ command === 'insert'
+ ? '-- Provide a SQL expression for the with check statement'
+ : '-- Provide a SQL expression for the using statement'
+ }
+ defaultValue={command === 'insert' ? check : using}
+ value={command === 'insert' ? check : using}
+ editorRef={editorOneRef}
+ monacoRef={monacoOneRef as any}
+ lineNumberStart={6}
+ onChange={() => {
+ setExpOneContentHeight(editorOneRef.current?.getContentHeight() ?? 0)
+ setExpOneLineCount(editorOneRef.current?.getModel()?.getLineCount() ?? 1)
+ }}
+ onMount={() => {
+ setTimeout(() => {
+ setExpOneContentHeight(editorOneRef.current?.getContentHeight() ?? 0)
+ setExpOneLineCount(
+ editorOneRef.current?.getModel()?.getLineCount() ?? 1
+ )
+ }, 200)
+ }}
+ />
+ </div>
+
+ <div className="bg-surface-300 py-1">
+ <div className="flex items-center" style={{ fontSize: '14px' }}>
+ <div className="w-[57px]">
+ <p className="w-[31px] flex justify-end font-mono text-sm text-foreground-light select-none">
+ {7 + expOneLineCount}
+ </p>
+ </div>
+ <p className="font-mono tracking-tighter">
+ {showCheckBlock ? (
+ <>
+ <span className="text-[#569cd6]">with check</span>{' '}
+ <span className="text-[#ffd700]">(</span>
+ </>
+ ) : (
+ <>
+ <span className="text-[#ffd700]">)</span>;
+ </>
+ )}
+ </p>
+ </div>
+ </div>
+
+ {showCheckBlock && (
+ <>
+ <div
+ className="mt-1 min-h-[28px] relative block"
+ style={{
+ height:
+ expTwoContentHeight <= 100 ? `${8 + expTwoContentHeight}px` : '108px',
+ }}
+ >
+ <RLSCodeEditor
+ disableTabToUsePlaceholder
+ readOnly={!canUpdatePolicies}
+ id="rls-exp-two-editor"
+ placeholder="-- Provide a SQL expression for the with check statement"
+ defaultValue={check}
+ value={check}
+ editorRef={editorTwoRef}
+ monacoRef={monacoTwoRef as any}
+ lineNumberStart={7 + expOneLineCount}
+ onChange={() => {
+ setExpTwoContentHeight(editorTwoRef.current?.getContentHeight() ?? 0)
+ setExpTwoLineCount(
+ editorTwoRef.current?.getModel()?.getLineCount() ?? 1
+ )
+ }}
+ onMount={() => {
+ setTimeout(() => {
+ setExpTwoContentHeight(
+ editorTwoRef.current?.getContentHeight() ?? 0
+ )
+ setExpTwoLineCount(
+ editorTwoRef.current?.getModel()?.getLineCount() ?? 1
+ )
+ }, 200)
+ }}
+ />
+ </div>
+ <div className="bg-surface-300 py-1">
+ <div className="flex items-center" style={{ fontSize: '14px' }}>
+ <div className="w-[57px]">
+ <p className="w-[31px] flex justify-end font-mono text-sm text-foreground-light select-none">
+ {8 + expOneLineCount + expTwoLineCount}
+ </p>
+ </div>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#ffd700]">)</span>;
+ </p>
+ </div>
+ </div>
+ </>
+ )}
+
+ {isRenamingPolicy && (
+ <LockedRenameQuerySection
+ oldName={selectedPolicy.name}
+ newName={name}
+ schema={schema}
+ table={table}
+ lineNumber={8 + expOneLineCount + (showCheckBlock ? expTwoLineCount : 0)}
+ />
+ )}
+
+ {fieldError !== undefined && (
+ <p className="px-5 py-2 pb-0 text-sm text-red-900">{fieldError}</p>
+ )}
+
+ {supportWithCheck && (
+ <div className="px-5 py-3 flex items-center gap-x-2">
+ <Checkbox_Shadcn_
+ id="use-check"
+ name="use-check"
+ checked={showCheckBlock}
+ onCheckedChange={() => {
+ setFieldError(undefined)
+ setShowCheckBlock(!showCheckBlock)
+ }}
+ />
+ <Label_Shadcn_ className="text-xs cursor-pointer" htmlFor="use-check">
+ Use check expression
+ </Label_Shadcn_>
+ </div>
+ )}
+ </div>
+
+ <div className="flex flex-col">
+ {error !== undefined && (
+ <QueryError error={error} open={errorPanelOpen} setOpen={setErrorPanelOpen} />
+ )}
+ <SheetFooter className="flex items-center !justify-end px-5 py-4 w-full border-t">
+ <Button
+ type="default"
+ disabled={isExecuting || isUpdating}
+ onClick={() => onClosingPanel()}
+ >
+ Cancel
+ </Button>
+
+ <ButtonTooltip
+ form={formId}
+ htmlType="submit"
+ loading={isExecuting || isUpdating}
+ disabled={!canUpdatePolicies || isExecuting || isUpdating}
+ tooltip={{
+ content: {
+ side: 'top',
+ text: !canUpdatePolicies
+ ? 'You need additional permissions to update policies'
+ : undefined,
+ },
+ }}
+ >
+ Save policy
+ </ButtonTooltip>
+ </SheetFooter>
+ </div>
+ </div>
+ </div>
+ {showTools && (
+ <div
+ className={cn(
+ 'border-l shadow-[rgba(0,0,0,0.13)_-4px_0px_6px_0px] z-10',
+ showTools && 'w-[50%]',
+ 'bg-studio overflow-auto'
+ )}
+ >
+ <Tabs_Shadcn_ defaultValue="templates" className="flex flex-col h-full w-full">
+ <TabsList_Shadcn_ className="flex gap-4 px-content pt-2">
+ <TabsTrigger_Shadcn_
+ key="templates"
+ value="templates"
+ className="px-0 data-[state=active]:bg-transparent"
+ >
+ Templates
+ </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) => {
+ form.setValue('name', value.name)
+ form.setValue('behavior', 'permissive')
+ form.setValue('command', value.command.toLowerCase())
+ form.setValue('roles', value.roles.join(', ') ?? '')
+
+ setUsing(` ${value.definition}`)
+ setCheck(` ${value.check}`)
+ setExpOneLineCount(1)
+ setExpTwoLineCount(1)
+ setFieldError(undefined)
+
+ if (!['update', 'all'].includes(value.command.toLowerCase())) {
+ setShowCheckBlock(false)
+ } else if (value.check.length > 0) {
+ setShowCheckBlock(true)
+ } else {
+ setShowCheckBlock(false)
+ }
+ }}
+ />
+ </ScrollArea>
+ </TabsContent_Shadcn_>
+ </Tabs_Shadcn_>
+ </div>
+ )}
+ </SheetContent>
+ </Sheet>
+ </form>
+ </Form_Shadcn_>
+
+ <ConfirmationModal
+ visible={isClosingPolicyEditorPanel}
+ title="Discard changes"
+ confirmLabel="Discard"
+ onCancel={() => setIsClosingPolicyEditorPanel(false)}
+ onConfirm={() => {
+ onSelectCancel()
+ setIsClosingPolicyEditorPanel(false)
+ }}
+ >
+ <p className="text-sm text-foreground-light">
+ Are you sure you want to close the editor? Any unsaved changes on your policy and
+ conversations with the Assistant will be lost.
+ </p>
+ </ConfirmationModal>
+ </>
+ )
+})
+
+PolicyEditorPanel.displayName = 'PolicyEditorPanel'
diff --git a/apps/studio/components/interfaces/Realtime/Policies.tsx b/apps/studio/components/interfaces/Realtime/Policies.tsx
index daa7c887744..56a17b589f8 100644
--- a/apps/studio/components/interfaces/Realtime/Policies.tsx
+++ b/apps/studio/components/interfaces/Realtime/Policies.tsx
@@ -1,7 +1,7 @@
import { PostgresPolicy } from '@supabase/postgres-meta'
import { useState } from 'react'
-import { AIPolicyEditorPanel } from 'components/interfaces/Auth/Policies/AIPolicyEditorPanel'
+import { PolicyEditorPanel } from 'components/interfaces/Auth/Policies/PolicyEditorPanel'
import Policies from 'components/interfaces/Auth/Policies/Policies'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import AlertError from 'components/ui/AlertError'
@@ -60,7 +60,7 @@ export const RealtimePolicies = () => {
</div>
)}
- <AIPolicyEditorPanel
+ <PolicyEditorPanel
visible={showPolicyEditor}
searchString="messages"
schema="realtime"
diff --git a/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx b/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx
deleted file mode 100644
index c8d94bf6051..00000000000
--- a/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import * as Popover from '@radix-ui/react-popover'
-import { motion } from 'framer-motion'
-import { Info } from 'lucide-react'
-import { PropsWithChildren, useEffect, useState } from 'react'
-
-import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
-import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { IS_PLATFORM } from 'lib/constants'
-import { Button } from 'ui'
-
-export interface AISchemaSuggestionPopoverProps {
- delay?: number
- onClickSettings?: () => void
-}
-
-const AISchemaSuggestionPopover = ({
- children,
- delay = 300,
- onClickSettings,
-}: PropsWithChildren<AISchemaSuggestionPopoverProps>) => {
- const selectedOrganization = useSelectedOrganization()
- const isOptedInToAI = useOrgOptedIntoAi()
- const [hasEnabledAISchema] = useLocalStorageQuery('supabase_sql-editor-ai-schema', true)
- const [isDelayComplete, setIsDelayComplete] = useState(false)
- const [aiQueryCount] = useLocalStorageQuery('supabase_sql-editor-ai-query-count', 0)
-
- const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema
-
- const [isSchemaSuggestionDismissed, setIsSchemaSuggestionDismissed] = useLocalStorageQuery(
- 'supabase_sql-editor-ai-schema-suggestion-dismissed',
- false
- )
-
- useEffect(() => {
- const timeout = window.setTimeout(() => {
- setIsDelayComplete(true)
- }, delay)
-
- return () => window.clearTimeout(timeout)
- })
-
- return (
- <Popover.Root
- open={
- isDelayComplete &&
- !includeSchemaMetadata &&
- aiQueryCount >= 3 &&
- !isSchemaSuggestionDismissed
- }
- >
- <Popover.Anchor asChild>{children}</Popover.Anchor>
-
- <Popover.Portal>
- <Popover.Content side="bottom" sideOffset={5}>
- <motion.div
- variants={{
- visible: {
- opacity: 1,
- y: 0,
- },
- hidden: {
- opacity: 0,
- y: -10,
- },
- }}
- initial="hidden"
- animate="visible"
- >
- <Popover.Arrow className="fill-background-surface-300" />
- <div className="flex flex-col gap-2 border border-default rounded-md p-4 bg-surface-100 shadow-xl">
- <div className="flex flex-row gap-4 max-w-sm xl:max-w-xl xl:items-center">
- <Info size={18} />
- <p className="text-sm">
- Generate more relevant queries by including database metadata in your requests.
- </p>
- </div>
- <div className="flex flex-row gap-2 justify-end">
- <Button
- type="default"
- onClick={() => {
- setIsSchemaSuggestionDismissed(true)
- }}
- >
- Dismiss
- </Button>
- <Button
- onClick={() => {
- setIsSchemaSuggestionDismissed(true)
- onClickSettings?.()
- }}
- >
- Open settings
- </Button>
- </div>
- </div>
- </motion.div>
- </Popover.Content>
- </Popover.Portal>
- </Popover.Root>
- )
-}
-
-export default AISchemaSuggestionPopover
diff --git a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsx b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsx
deleted file mode 100644
index 86d7cabdca8..00000000000
--- a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-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 '../SQLEditor.types'
-
-interface AiMessagePreProps {
- onDiff: (type: DiffType, s: string) => void
- children: string[]
- className?: string
-}
-
-// [DEPRECATED] To delete
-export const AiMessagePre = ({ onDiff, children, className }: AiMessagePreProps) => {
- 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',
- action: 'ai_suggestion_inserted',
- label: 'sql-editor-ai-assistant',
- })
- }}
- >
- <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={() => {
- onDiff(DiffType.Modification, formatted)
- sendEvent({
- category: 'sql_editor_ai_assistant',
- action: 'ai_suggestion_replaced',
- label: 'sql-editor-ai-assistant',
- })
- }}
- >
- <ReplaceCode className="h-4 w-4 text-foreground-light" strokeWidth={1.5} />
- </Button>
- </TooltipTrigger_Shadcn_>
- <TooltipContent_Shadcn_ side="bottom" className="font-sans">
- Replace code
- </TooltipContent_Shadcn_>
- </Tooltip_Shadcn_>
-
- <Tooltip_Shadcn_>
- <TooltipTrigger_Shadcn_ asChild>
- <Button
- type="text"
- size="tiny"
- onClick={() => {
- handleCopy(formatted)
- sendEvent({
- category: 'sql_editor_ai_assistant',
- action: 'ai_suggestion_copied',
- label: 'sql-editor-ai-assistant',
- })
- }}
- >
- {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/interfaces/SQLEditor/AiAssistantPanel/Message.tsx b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/Message.tsx
deleted file mode 100644
index 03c2156d57c..00000000000
--- a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/Message.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-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 } from 'ui'
-
-import { useProfile } from 'lib/profile'
-import { DiffType } from '../SQLEditor.types'
-import { AiMessagePre } from './AiMessagePre'
-
-interface MessageProps {
- name?: string
- role: 'function' | 'system' | 'user' | 'assistant' | 'data' | 'tool'
- content?: string
- createdAt?: number
- isDebug?: boolean
- isSelected?: boolean
- onDiff?: (type: DiffType, s: string) => void
- action?: React.ReactNode
-}
-
-// [DEPRECATED] To delete
-const Message = memo(function Message({
- name,
- role,
- content,
- createdAt,
- isDebug,
- isSelected = false,
- onDiff = noop,
- children,
- action = null,
-}: PropsWithChildren<MessageProps>) {
- const { profile } = useProfile()
-
- 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])
-
- if (!content) return null
-
- return (
- <div className="flex flex-col py-4 gap-4 border-t px-5 text-foreground-light text-sm">
- <div className="flex flex-row justify-between items-center">
- <div className="flex flex-row gap-3 items-center">
- {icon}
-
- <span className="text-sm">
- {role === 'assistant' ? 'Assistant' : name ? name : 'You'}
- </span>
- {createdAt && (
- <span className="text-xs text-foreground-muted">{dayjs(createdAt).fromNow()}</span>
- )}
- {isDebug && <Badge variant="warning">Debug request</Badge>}
- </div>{' '}
- {action}
- </div>
- <ReactMarkdown
- className="gap-2.5 flex flex-col [&>*>code]:text-xs [&>*>*>code]:text-xs"
- remarkPlugins={[remarkGfm]}
- components={{
- ...markdownComponents,
- pre: (props: any) => {
- return (
- <AiMessagePre
- onDiff={onDiff}
- className={cn(
- 'transition',
- isSelected ? '[&>div>pre]:!border-stronger [&>div>pre]:!bg-surface-200' : ''
- )}
- >
- {props.children[0].props.children}
- </AiMessagePre>
- )
- },
- }}
- >
- {content}
- </ReactMarkdown>
- {children}
- </div>
- )
-})
-
-export default Message
diff --git a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx
deleted file mode 100644
index 0424b2d477b..00000000000
--- a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx
+++ /dev/null
@@ -1,357 +0,0 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { compact, last } from 'lodash'
-import { Info } from 'lucide-react'
-import { useEffect, useMemo, useRef, useState } from 'react'
-import { toast } from 'sonner'
-
-import { Alert, AlertDescription, AlertTitle } from '@ui/components/shadcn/ui/alert'
-import { Message as MessageType } from 'ai'
-import { useChat } from 'ai/react'
-import { useParams } from 'common'
-import { IS_PLATFORM } from 'common/constants/environment'
-import { Markdown } from 'components/interfaces/Markdown'
-import { SchemaComboBox } from 'components/ui/SchemaComboBox'
-import { useCheckOpenAIKeyQuery } from 'data/ai/check-api-key-query'
-import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
-import { useOrganizationUpdateMutation } from 'data/organizations/organization-update-mutation'
-import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
-import { useSchemasForAi } from 'hooks/misc/useSchemasForAi'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { useSelectedProject } from 'hooks/misc/useSelectedProject'
-import { BASE_PATH, LOCAL_STORAGE_KEYS, OPT_IN_TAGS } from 'lib/constants'
-import { useProfile } from 'lib/profile'
-import uuidv4 from 'lib/uuid'
-import {
- AiIconAnimation,
- Alert_Shadcn_,
- AlertDescription_Shadcn_,
- AlertTitle_Shadcn_,
- Button,
- cn,
- Tooltip_Shadcn_,
- TooltipContent_Shadcn_,
- TooltipTrigger_Shadcn_,
- WarningIcon,
-} from 'ui'
-import { AssistantChatForm } from 'ui-patterns/AssistantChat'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import OptInToOpenAIToggle from '../../Organization/GeneralSettings/OptInToOpenAIToggle'
-import { DiffType } from '../SQLEditor.types'
-import Message from './Message'
-
-export type MessageWithDebug = MessageType & { isDebug: boolean }
-
-interface AiAssistantPanelProps {
- selectedMessage?: string
- existingSql: string
- includeSchemaMetadata: boolean
- onDiff: ({ id, diffType, sql }: { id: string; diffType: DiffType; sql: string }) => void
- onClose: () => void
-}
-
-// [DEPRECATED] To delete
-export const AiAssistantPanel = ({
- selectedMessage,
- existingSql,
- onDiff,
- onClose,
- includeSchemaMetadata,
-}: AiAssistantPanelProps) => {
- const { ref } = useParams()
- const { profile } = useProfile()
- const project = useSelectedProject()
- const selectedOrganization = useSelectedOrganization()
-
- const bottomRef = useRef<HTMLDivElement>(null)
- const inputRef = useRef<HTMLTextAreaElement>(null)
-
- const [chatId, setChatId] = useState(uuidv4())
- const [value, setValue] = useState<string>('')
- const [isConfirmOptInModalOpen, setIsConfirmOptInModalOpen] = useState(false)
- const [selectedSchemas, setSelectedSchemas] = useSchemasForAi(project?.ref!)
-
- const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
- const [showAiNotOptimizedWarningSetting, setShowAiNotOptimizedWarningSetting] =
- useLocalStorageQuery(LOCAL_STORAGE_KEYS.SHOW_AI_NOT_OPTIMIZED_WARNING(ref as string), true)
- const shouldShowNotOptimizedAlert =
- selectedOrganization && !includeSchemaMetadata && showAiNotOptimizedWarningSetting
-
- const { data: check } = useCheckOpenAIKeyQuery()
- const isApiKeySet = IS_PLATFORM || !!check?.hasKey
-
- const { data } = useEntityDefinitionsQuery(
- {
- schemas: selectedSchemas,
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- },
- { enabled: includeSchemaMetadata }
- )
-
- const entityDefinitions = includeSchemaMetadata ? data?.map((def) => def.sql.trim()) : undefined
-
- // Use chat id because useChat doesn't have a reset function to clear all messages
- const {
- messages: chatMessages,
- isLoading,
- append,
- } = useChat({
- id: chatId,
- api: `${BASE_PATH}/api/ai/sql/generate-v2`,
- body: {
- existingSql,
- entityDefinitions: entityDefinitions,
- },
- })
- const messages = useMemo(() => {
- const merged = [...chatMessages.map((m) => ({ ...m, isDebug: false }))]
-
- return merged.sort(
- (a, b) =>
- (a.createdAt?.getTime() ?? 0) - (b.createdAt?.getTime() ?? 0) ||
- a.role.localeCompare(b.role)
- )
- }, [chatMessages])
-
- const name = compact([profile?.first_name, profile?.last_name]).join(' ')
- const pendingReply = isLoading && last(messages)?.role === 'user'
-
- const { mutate: sendEvent } = useSendEventMutation()
- const { mutate: updateOrganization, isLoading: isUpdating } = useOrganizationUpdateMutation()
-
- 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 (!isLoading) {
- setValue('')
- if (inputRef.current) inputRef.current.focus()
- }
-
- // Try to scroll on each rerender to the bottom
- setTimeout(
- () => {
- if (bottomRef.current) {
- bottomRef.current.scrollIntoView({ behavior: 'smooth' })
- }
- },
- isLoading ? 100 : 500
- )
- }, [isLoading])
-
- return (
- <div className="flex flex-col h-full border-l border-control">
- <div
- className={cn(
- 'overflow-auto flex-1',
- messages.length === 0 ? 'flex flex-col justify-between' : ''
- )}
- >
- <Message
- key="zero"
- role="assistant"
- content={`Hi${
- name ? ' ' + name : ''
- }, how can I help you? I'm powered by AI, so surprises and mistakes are possible.
- Make sure to verify any generated code or suggestions, and share feedback so that we can
- learn and improve.`}
- action={
- <div className="flex gap-2">
- {messages.length > 0 && (
- <Button type="warning" onClick={() => setChatId(uuidv4())}>
- Clear history
- </Button>
- )}
- <Button type="default" onClick={onClose}>
- Close Assistant
- </Button>
- </div>
- }
- >
- {includeSchemaMetadata ? (
- <div className="mt-2">
- <span className="inline-block text-lighter">
- Include these schemas in your prompts:
- </span>
- <div className="flex flex-row justify-between space-x-2 mt-2">
- <div className="flex items-center gap-2">
- <SchemaComboBox
- disabled={!includeSchemaMetadata}
- selectedSchemas={selectedSchemas}
- onSelectSchemas={setSelectedSchemas}
- label={
- includeSchemaMetadata && selectedSchemas.length > 0
- ? `${selectedSchemas.length} schema${
- selectedSchemas.length > 1 ? 's' : ''
- } selected`
- : 'No schemas selected'
- }
- />
- <Tooltip_Shadcn_>
- <TooltipTrigger_Shadcn_ className="flex items-center gap-2 text-lighter">
- <Info className="text-lighter w-4 h-4" />
- </TooltipTrigger_Shadcn_>
- <TooltipContent_Shadcn_ className="w-72" side="right">
- Select specific schemas to send with your queries. Supabase AI can use this
- data to improve the responses it shows you.
- </TooltipContent_Shadcn_>
- </Tooltip_Shadcn_>
- </div>
- </div>
- </div>
- ) : (
- <>
- {shouldShowNotOptimizedAlert ? (
- <Alert_Shadcn_ className="[&>svg]:left-5 border-l-0 border-r-0 rounded-none -mx-5 px-5 w-[calc(100%+40px)]">
- <WarningIcon />
- <AlertTitle_Shadcn_>AI Assistant is not optimized</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>
- You need to agree to share anonymous schema data with OpenAI for the best
- experience.
- </AlertDescription_Shadcn_>
- <div className="flex items-center gap-4 mt-6">
- <Button type="default" onClick={() => setIsConfirmOptInModalOpen(true)}>
- Update AI settings
- </Button>
-
- <Button type="text" onClick={() => setShowAiNotOptimizedWarningSetting(false)}>
- Dismiss
- </Button>
- </div>
- </Alert_Shadcn_>
- ) : (
- <></>
- )}
- </>
- )}
- </Message>
- {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.isDebug}
- isSelected={selectedMessage === m.id}
- onDiff={(diffType, sql) => onDiff({ id: m.id, diffType, sql })}
- >
- {isFirstUserMessage && !includeSchemaMetadata && !shouldShowNotOptimizedAlert && (
- <Alert_Shadcn_>
- <AlertDescription_Shadcn_ className="flex flex-col gap-4">
- <span>
- Quick reminder that you're not sending project metadata with your queries. By
- opting into sending anonymous data, Supabase AI can improve the answers it
- shows you.
- </span>
- <Button
- type="default"
- className="w-fit"
- onClick={() => setIsConfirmOptInModalOpen(true)}
- >
- Update AI settings
- </Button>
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- )}
- {isFirstUserMessage && includeSchemaMetadata && selectedSchemas.length === 0 && (
- <Alert_Shadcn_>
- <AlertDescription_Shadcn_ className="flex flex-col gap-4">
- <span>
- We recommend including the schemas for better answers by Supabase AI.
- </span>
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- )}
- </Message>
- )
- })}
- {pendingReply && <Message key="thinking" role="assistant" content="Thinking..." />}
- <div ref={bottomRef} className="h-1" />
- </div>
-
- <div className="sticky p-5 flex-0 border-t grid gap-4">
- {!isApiKeySet && (
- <Alert>
- <AlertTitle>OpenAI API key not set</AlertTitle>
- <AlertDescription>
- <Markdown
- content={'Add your `OPENAI_API_KEY` to `./docker/.env` to use the AI Assistant.'}
- />
- </AlertDescription>
- </Alert>
- )}
- <AssistantChatForm
- textAreaRef={inputRef}
- loading={isLoading}
- disabled={isLoading || !isApiKeySet}
- icon={
- <AiIconAnimation
- allowHoverEffect
- className="[&>div>div]:border-black dark:[&>div>div]:border-white"
- />
- }
- placeholder="Ask a question about your SQL query"
- value={value}
- onValueChange={(e) => setValue(e.target.value)}
- onSubmit={(event) => {
- event.preventDefault()
- append({
- content: value,
- role: 'user',
- createdAt: new Date(),
- })
- sendEvent({
- category: 'sql_editor_ai_assistant',
- action: 'ai_suggestion_asked',
- label: 'sql-editor-ai-assistant',
- })
- }}
- />
- </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>
- </div>
- )
-}
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 620c265b844..fd6408d24b0 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -50,7 +50,6 @@ import {
} from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { subscriptionHasHipaaAddon } from '../Billing/Subscription/Subscription.utils'
-import AISchemaSuggestionPopover from './AISchemaSuggestionPopover'
import { DiffActionBar } from './DiffActionBar'
import {
ROWS_PER_PAGE_OPTIONS,
@@ -82,7 +81,7 @@ const DiffEditor = dynamic(
{ ssr: false }
)
-const SQLEditor = () => {
+export const SQLEditor = () => {
const router = useRouter()
const { ref, id: urlId } = useParams()
@@ -101,13 +100,10 @@ const SQLEditor = () => {
const databaseSelectorState = useDatabaseSelectorStateSnapshot()
const queryClient = useQueryClient()
- const { open } = appSnap.aiAssistantPanel
-
const { mutate: formatQuery } = useFormatQueryMutation()
const { mutateAsync: generateSqlTitle } = useSqlTitleGenerateMutation()
const { mutateAsync: debugSql, isLoading: isDebugSqlLoading } = useSqlDebugMutation()
- const [debugSolution, setDebugSolution] = useState<string>()
const [sourceSqlDiff, setSourceSqlDiff] = useState<ContentDiff>()
const [pendingTitle, setPendingTitle] = useState<string>()
const [hasSelection, setHasSelection] = useState<boolean>(false)
@@ -457,11 +453,10 @@ const SQLEditor = () => {
sendEvent({
category: 'sql_editor',
action: 'ai_suggestion_accepted',
- label: debugSolution ? 'debug_snippet' : 'edit_snippet',
+ label: 'edit_snippet',
})
setSelectedDiffType(DiffType.Modification)
- setDebugSolution(undefined)
setSourceSqlDiff(undefined)
setPendingTitle(undefined)
} finally {
@@ -472,7 +467,6 @@ const SQLEditor = () => {
selectedDiffType,
handleNewQuery,
generateSqlTitle,
- debugSolution,
router,
id,
pendingTitle,
@@ -483,13 +477,12 @@ const SQLEditor = () => {
sendEvent({
category: 'sql_editor',
action: 'ai_suggestion_rejected',
- label: debugSolution ? 'debug_snippet' : 'edit_snippet',
+ label: 'edit_snippet',
})
- setDebugSolution(undefined)
setSourceSqlDiff(undefined)
setPendingTitle(undefined)
- }, [debugSolution, router])
+ }, [router])
useEffect(() => {
const handler = (e: KeyboardEvent) => {
@@ -659,39 +652,26 @@ const SQLEditor = () => {
direction="vertical"
autoSaveId={LOCAL_STORAGE_KEYS.SQL_EDITOR_SPLIT_SIZE}
>
- {(open || isDiffOpen) && !hasHipaaAddon && (
- <AISchemaSuggestionPopover
- onClickSettings={() => {
- appSnap.setShowAiSettingsModal(true)
- }}
- >
- {isDiffOpen && (
- <motion.div
- key="ask-ai-input-container"
- layoutId="ask-ai-input-container"
- variants={{ visible: { borderRadius: 0, x: 0 }, hidden: { x: 100 } }}
- initial={isFirstRender ? 'visible' : 'hidden'}
- animate="visible"
- className={cn(
- 'flex flex-row items-center gap-3 justify-end px-2 py-2 w-full z-10',
- 'bg-brand-200 border-b border-brand-400 !shadow-none'
- )}
- >
- {debugSolution && (
- <div className="h-full w-full flex flex-row items-center overflow-y-hidden text-sm text-brand-600">
- {debugSolution}
- </div>
- )}
- <DiffActionBar
- loading={isAcceptDiffLoading}
- selectedDiffType={selectedDiffType || DiffType.Modification}
- onChangeDiffType={(diffType) => setSelectedDiffType(diffType)}
- onAccept={acceptAiHandler}
- onCancel={discardAiHandler}
- />
- </motion.div>
+ {!hasHipaaAddon && isDiffOpen && (
+ <motion.div
+ key="ask-ai-input-container"
+ layoutId="ask-ai-input-container"
+ variants={{ visible: { borderRadius: 0, x: 0 }, hidden: { x: 100 } }}
+ initial={isFirstRender ? 'visible' : 'hidden'}
+ animate="visible"
+ className={cn(
+ 'flex flex-row items-center gap-3 justify-end px-2 py-2 w-full z-10',
+ 'bg-brand-200 border-b border-brand-400 !shadow-none'
)}
- </AISchemaSuggestionPopover>
+ >
+ <DiffActionBar
+ loading={isAcceptDiffLoading}
+ selectedDiffType={selectedDiffType || DiffType.Modification}
+ onChangeDiffType={(diffType) => setSelectedDiffType(diffType)}
+ onAccept={acceptAiHandler}
+ onCancel={discardAiHandler}
+ />
+ </motion.div>
)}
<ResizablePanel maxSize={70}>
<div className="flex-grow overflow-y-auto border-b h-full">
@@ -830,5 +810,3 @@ const SQLEditor = () => {
</>
)
}
-
-export default SQLEditor
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.types.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.types.ts
index a01bbb7697c..3988a93a7cd 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.types.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.types.ts
@@ -22,8 +22,6 @@ export type SQLEditorContextValues = {
setAiInput: Dispatch<SetStateAction<string>>
sqlDiff?: ContentDiff
setSqlDiff: Dispatch<SetStateAction<ContentDiff | undefined>>
- debugSolution?: string
- setDebugSolution: Dispatch<SetStateAction<string | undefined>>
setSelectedDiffType: Dispatch<SetStateAction<DiffType | undefined>>
}
diff --git a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
index 25baed47a08..443dde995d2 100644
--- a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
@@ -4,7 +4,7 @@ import { forwardRef, Fragment, PropsWithChildren, ReactNode, useEffect, useState
import { useParams } from 'common'
import ProjectAPIDocs from 'components/interfaces/ProjectAPIDocs/ProjectAPIDocs'
-import { AiAssistantPanel } from 'components/ui/AIAssistantPanel/AIAssistantPanel'
+import { AIAssistantPanel } from 'components/ui/AIAssistantPanel/AIAssistantPanel'
import AISettingsModal from 'components/ui/AISettingsModal'
import { Loading } from 'components/ui/Loading'
import ResourceExhaustionWarningBanner from 'components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner'
@@ -212,7 +212,7 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
'2xl:min-w-[500px] 2xl:max-w-[600px]'
)}
>
- <AiAssistantPanel />
+ <AIAssistantPanel />
</ResizablePanel>
</>
)}
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx
index a37fa7765fa..0d657513cf4 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx
@@ -5,7 +5,7 @@ import { useAppStateSnapshot } from 'state/app-state'
import { cn } from 'ui'
import { AIAssistant } from './AIAssistant'
-export const AiAssistantPanel = () => {
+export const AIAssistantPanel = () => {
const { aiAssistantPanel, resetAiAssistantPanel } = useAppStateSnapshot()
const [initialMessages, setInitialMessages] = useState<MessageType[] | undefined>(
aiAssistantPanel.messages?.length > 0 ? (aiAssistantPanel.messages as any) : undefined
diff --git a/apps/studio/pages/_app.tsx b/apps/studio/pages/_app.tsx
index dee68c98b40..900cc483375 100644
--- a/apps/studio/pages/_app.tsx
+++ b/apps/studio/pages/_app.tsx
@@ -41,7 +41,6 @@ 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'
diff --git a/apps/studio/pages/project/[ref]/auth/policies.tsx b/apps/studio/pages/project/[ref]/auth/policies.tsx
index 2db8fb416a5..948571b3ac5 100644
--- a/apps/studio/pages/project/[ref]/auth/policies.tsx
+++ b/apps/studio/pages/project/[ref]/auth/policies.tsx
@@ -4,7 +4,7 @@ import { partition } from 'lodash'
import { Search } from 'lucide-react'
import { useState } from 'react'
-import { AIPolicyEditorPanel } from 'components/interfaces/Auth/Policies/AIPolicyEditorPanel'
+import { PolicyEditorPanel } from 'components/interfaces/Auth/Policies/PolicyEditorPanel'
import Policies from 'components/interfaces/Auth/Policies/Policies'
import AuthLayout from 'components/layouts/AuthLayout/AuthLayout'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
@@ -156,7 +156,7 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
/>
)}
- <AIPolicyEditorPanel
+ <PolicyEditorPanel
visible={showPolicyAiEditor}
schema={schema}
searchString={searchString}
diff --git a/apps/studio/pages/project/[ref]/sql/[id].tsx b/apps/studio/pages/project/[ref]/sql/[id].tsx
index 33bc4c7eb6d..b627a7237be 100644
--- a/apps/studio/pages/project/[ref]/sql/[id].tsx
+++ b/apps/studio/pages/project/[ref]/sql/[id].tsx
@@ -3,7 +3,7 @@ import { useRouter } from 'next/router'
import { useEffect, useRef } from 'react'
import { useParams } from 'common/hooks/useParams'
-import SQLEditor from 'components/interfaces/SQLEditor/SQLEditor'
+import { SQLEditor } from 'components/interfaces/SQLEditor/SQLEditor'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import SQLEditorLayout from 'components/layouts/SQLEditorLayout/SQLEditorLayout'
import getPgsqlCompletionProvider from 'components/ui/CodeEditor/Providers/PgSQLCompletionProvider'