Skip to content

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

Fix 'Fix with assistant' for RLS editor (#22283)

Joshen Lim05400d88ec8e
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
index d699fec55f3..c75de7dde2d 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
@@ -18,6 +18,7 @@ import { useSelectedOrganization } from 'hooks'
import Telemetry from 'lib/telemetry'
import { useTelemetryProps } from 'common'
import { useRouter } from 'next/router'
+import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
const QueryError = ({
error,
@@ -30,6 +31,7 @@ const QueryError = ({
setOpen: Dispatch<SetStateAction<boolean>>
onSelectDebug: () => void
}) => {
+ const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
const formattedError =
(error?.formattedError?.split('\n') ?? [])?.filter((x: string) => x.length > 0) ?? []
@@ -74,7 +76,7 @@ const QueryError = ({
{open ? 'Hide error details' : 'Show error details'}
</Button>
</CollapsibleTrigger_Shadcn_>
- {!hasHipaaAddon && (
+ {!hasHipaaAddon && isAiAssistantEnabled && (
<Button
size={'tiny'}
type="default"
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
index 3cf30731b8b..4e43237932b 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
@@ -1,13 +1,16 @@
-import Editor, { Monaco, OnChange, OnMount } from '@monaco-editor/react'
+import Editor, { Monaco, OnChange, OnMount, useMonaco } from '@monaco-editor/react'
import type { editor } from 'monaco-editor'
-import { MutableRefObject, useRef } from 'react'
+import { MutableRefObject, useEffect, useRef } from 'react'
import { cn } from 'ui'
import { Markdown } from 'components/interfaces/Markdown'
import { noop } from 'lodash'
+import { formatQuery } from 'data/sql/format-sql-query'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
// [Joshen] Is there a way we can just have one single MonacoEditor component that's shared across the dashboard?
-// Feels like we're creating multiple copies of Editor
+// Feels like we're creating multiple copies of Editor. I'm keen to make this one the defacto as well so lets make sure
+// this component does not have RLS specific logic
interface RLSCodeEditorProps {
id: string
@@ -21,6 +24,7 @@ interface RLSCodeEditorProps {
lineNumberStart?: number
onChange?: () => void
+ onMount?: () => void
editorRef: MutableRefObject<editor.IStandaloneCodeEditor | null>
monacoRef?: MutableRefObject<Monaco>
@@ -37,11 +41,14 @@ const RLSCodeEditor = ({
lineNumberStart,
onChange = noop,
+ onMount: _onMount = noop,
editorRef,
monacoRef,
}: RLSCodeEditorProps) => {
const hasValue = useRef<any>()
+ const monaco = useMonaco()
+ const { project } = useProjectContext()
const options: editor.IStandaloneEditorConstructionOptions = {
tabSize: 2,
@@ -86,6 +93,8 @@ const RLSCodeEditor = ({
)
editor.focus()
+
+ _onMount()
}
const onChangeContent: OnChange = (value) => {
@@ -103,6 +112,42 @@ const RLSCodeEditor = ({
onChange()
}
+ async function formatPgsql(value: any) {
+ try {
+ const formatted = await formatQuery({
+ projectRef: project?.ref!,
+ connectionString: project?.connectionString,
+ sql: value,
+ })
+ return formatted
+ } catch (error) {
+ console.error('formatPgsql error:', error)
+ return value
+ }
+ }
+
+ useEffect(() => {
+ if (monaco) {
+ // Enable pgsql format
+ const formatprovider = monaco.languages.registerDocumentFormattingEditProvider('pgsql', {
+ async provideDocumentFormattingEdits(model: any) {
+ const value = model.getValue()
+ const formatted = await formatPgsql(value)
+ return [
+ {
+ range: model.getFullModelRange(),
+ text: formatted.result.trim(),
+ },
+ ]
+ },
+ })
+
+ return () => {
+ formatprovider.dispose()
+ }
+ }
+ }, [monaco])
+
return (
<>
<Editor
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
index 81012c8d24e..9f73aa4ced0 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
@@ -103,13 +103,16 @@ export const AIPolicyEditorPanel = memo(function ({
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'>('templates')
const diffEditorRef = useRef<IStandaloneDiffEditor | null>(null)
const placeholder = generatePlaceholder(selectedPolicy)
@@ -551,7 +554,7 @@ export const AIPolicyEditorPanel = memo(function ({
className={`py-1 relative ${incomingChange ? 'hidden' : 'block'}`}
style={{
height:
- expOneLineCount <= 5 ? `${8 + expOneLineCount * 20}px` : '108px',
+ expOneContentHeight <= 100 ? `${8 + expOneContentHeight}px` : '108px',
}}
>
<RLSCodeEditor
@@ -562,10 +565,21 @@ export const AIPolicyEditorPanel = memo(function ({
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>
@@ -597,7 +611,9 @@ export const AIPolicyEditorPanel = memo(function ({
className={`py-1 relative ${incomingChange ? 'hidden' : 'block'}`}
style={{
height:
- expTwoLineCount <= 5 ? `${8 + expTwoLineCount * 20}px` : '108px',
+ expTwoContentHeight <= 100
+ ? `${8 + expTwoContentHeight}px`
+ : '108px',
}}
>
<RLSCodeEditor
@@ -608,10 +624,23 @@ export const AIPolicyEditorPanel = memo(function ({
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">
@@ -668,7 +697,10 @@ export const AIPolicyEditorPanel = memo(function ({
{error !== undefined && (
<QueryError
error={error}
- onSelectDebug={onSelectDebug}
+ onSelectDebug={() => {
+ setTabId('conversation')
+ onSelectDebug()
+ }}
open={errorPanelOpen}
setOpen={setErrorPanelOpen}
/>
@@ -715,11 +747,16 @@ export const AIPolicyEditorPanel = memo(function ({
'bg-studio'
)}
>
- <Tabs_Shadcn_ defaultValue="templates" className="flex flex-col h-full w-full">
+ <Tabs_Shadcn_
+ value={tabId}
+ 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"
+ onClick={() => setTabId('templates')}
className="px-0 data-[state=active]:bg-transparent"
>
Templates
@@ -728,6 +765,7 @@ export const AIPolicyEditorPanel = memo(function ({
<TabsTrigger_Shadcn_
key="conversation"
value="conversation"
+ onClick={() => setTabId('conversation')}
className="px-0 data-[state=active]:bg-transparent"
>
Assistant