Skip to content

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

fix: Add some more instructions to the AI Editor (#19507)

Ivan Vasiloveb83b51d98fb
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
index ef7f8e8e412..38d5e8d59bc 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
@@ -34,7 +34,7 @@ export const AIPolicyHeader = ({
<SheetTitle_Shadcn_ className="truncate">
{selectedPolicy !== undefined
? `Update policy: ${selectedPolicy.name}`
- : 'Create a new row level security policy'}
+ : 'Create a new Row Level Security policy'}
</SheetTitle_Shadcn_>
</div>
<Button
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyPre.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyPre.tsx
index 7d249f98aa5..75b0b6df278 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyPre.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyPre.tsx
@@ -1,5 +1,6 @@
import * as Tooltip from '@radix-ui/react-tooltip'
-import { Copy, FileDiff } from 'lucide-react'
+import { Check, Copy, FileDiff } from 'lucide-react'
+import { useEffect, useState } from 'react'
import { format } from 'sql-formatter'
import { Button, CodeBlock, cn } from 'ui'
@@ -10,6 +11,14 @@ interface AAIPolicyPreProps {
}
export const AIPolicyPre = ({ onDiff, children, className }: AAIPolicyPreProps) => {
+ const [copied, setCopied] = useState(false)
+
+ 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' })
@@ -18,6 +27,12 @@ export const AIPolicyPre = ({ onDiff, children, className }: AAIPolicyPreProps)
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
@@ -55,12 +70,8 @@ export const AIPolicyPre = ({ onDiff, children, className }: AAIPolicyPreProps)
</Tooltip.Root>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger asChild>
- <Button
- type="text"
- size="tiny"
- onClick={() => navigator.clipboard.writeText(formatted).then()}
- >
- <Copy className="h-4 w-4" />
+ <Button type="text" size="tiny" onClick={() => handleCopy(formatted)}>
+ {copied ? <Check size={16} className="text-brand-600" /> : <Copy size={16} />}
</Button>
</Tooltip.Trigger>
<Tooltip.Portal>
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetails.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetails.tsx
index 839e42e6b12..85e1d6ea69e 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetails.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetails.tsx
@@ -33,32 +33,36 @@ const PolicyDetails = ({ policy, showDetails, toggleShowDetails }: PolicyDetails
/>
</div>
</CollapsibleTrigger_Shadcn_>
- <CollapsibleContent_Shadcn_ className="pl-[3.6rem] mt-1">
- <div className="text-xs flex items-start space-x-2">
- <p className="w-[110px] text-foreground-light">Name:</p>
- <p className="">{policy.name}</p>
- </div>
- <div className="text-xs flex items-start space-x-2">
- <p className="w-[110px] text-foreground-light">Action:</p>
- <p className="font-mono">{policy.action}</p>
- </div>
- <div className="text-xs flex items-start space-x-2">
- <p className="w-[110px] text-foreground-light">Command:</p>
- <p className="font-mono">{policy.command}</p>
- </div>
- <div className="text-xs flex items-start space-x-2">
- <p className="w-[110px] text-foreground-light">Target roles:</p>
- <p className="font-mono">{policy.roles.join(', ')}</p>
- </div>
- <div className="text-xs flex items-start space-x-2">
- <p className="w-[110px] text-foreground-light">USING expression:</p>
- <p className="font-mono">{policy.definition}</p>
- </div>
- <div className="text-xs flex items-start space-x-2">
- <p className="w-[110px] text-foreground-light">CHECK expression:</p>
- <p className={`${policy.check ? '' : 'text-foreground-light'} font-mono`}>
- {policy.check ?? 'None'}
- </p>
+ <CollapsibleContent_Shadcn_ className="pl-[3.6rem] my-2 grid gap-1.5">
+ <div className="flex">
+ <div>
+ <div className="text-xs flex items-start space-x-2 border-b py-1.5">
+ <p className="w-[110px] text-foreground-light">Name:</p>
+ <p className="pr-4">{policy.name}</p>
+ </div>
+ <div className="text-xs flex items-start space-x-2 border-b py-1.5">
+ <p className="w-[110px] text-foreground-light">Action:</p>
+ <p className="font-mono pr-4">{policy.action}</p>
+ </div>
+ <div className="text-xs flex items-start space-x-2 border-b py-1.5">
+ <p className="w-[110px] text-foreground-light">Command:</p>
+ <p className="font-mono pr-4">{policy.command}</p>
+ </div>
+ <div className="text-xs flex items-start space-x-2 border-b py-1.5">
+ <p className="w-[110px] text-foreground-light">Target roles:</p>
+ <p className="font-mono pr-4">{policy.roles.join(', ')}</p>
+ </div>
+ <div className="text-xs flex items-start space-x-2 border-b py-1.5">
+ <p className="w-[110px] text-foreground-light">USING expression:</p>
+ <p className="font-mono pr-4">{policy.definition}</p>
+ </div>
+ <div className="text-xs flex items-start space-x-2 pt-1.5">
+ <p className="w-[110px] text-foreground-light">CHECK expression:</p>
+ <p className={`${policy.check ? '' : 'text-foreground-light'} font-mono pr-4`}>
+ {policy.check ?? 'None'}
+ </p>
+ </div>
+ </div>
</div>
</CollapsibleContent_Shadcn_>
</Collapsible_Shadcn_>
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
index 3b355cd4453..cf4137443ca 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/QueryError.tsx
@@ -1,8 +1,8 @@
import styles from '@ui/layout/ai-icon-animation/ai-icon-animation-style.module.css'
import { QueryResponseError } from 'data/sql/execute-sql-mutation'
-import { useState } from 'react'
+import { initial, last } from 'lodash'
+import { Dispatch, SetStateAction } from 'react'
import {
- AiIcon,
AlertTitle_Shadcn_,
Alert_Shadcn_,
Button,
@@ -14,13 +14,15 @@ import {
const QueryError = ({
error,
+ open,
+ setOpen,
onSelectDebug,
}: {
error: QueryResponseError
+ open: boolean
+ setOpen: Dispatch<SetStateAction<boolean>>
onSelectDebug: () => void
}) => {
- const [open, setOpen] = useState(true)
-
const formattedError =
(error?.formattedError?.split('\n') ?? [])?.filter((x: string) => x.length > 0) ?? []
@@ -76,15 +78,33 @@ const QueryError = ({
<CollapsibleContent_Shadcn_ className="overflow-auto">
{formattedError.length > 0 ? (
formattedError.map((x: string, i: number) => (
- <pre key={`error-${i}`} className="font-mono text-xs overflow">
- {x.split(' ').map((x: string, i: number) => (
- <span
- className={cn(x === 'ERROR:' && 'text-destructive')}
- key={`error-${i}-${x}`}
- >
- {x}{' '}
- </span>
- ))}
+ <pre key={`error-${i}`} className="font-mono text-xs whitespace-pre-wrap">
+ {x
+ .split(' ')
+ .reduce((arr, cur) => {
+ // Split the ERROR string so that it can be wrapped in a red span
+ const l = last(arr)
+
+ if (l && l !== 'ERROR:') {
+ return initial(arr).concat([[l, cur].join(' ')])
+ }
+
+ if (l === '') {
+ return arr.concat([' '])
+ }
+
+ return arr.concat([cur])
+ }, [] as string[])
+ .map((str, index, arr) => {
+ return (
+ <span
+ key={index}
+ className={cn('break-all', str === 'ERROR:' && 'text-destructive')}
+ >
+ {str}
+ </span>
+ )
+ })}
</pre>
))
) : (
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
index 6e9a47a0bb7..74771988f0f 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
@@ -61,6 +61,7 @@ export const AIPolicyEditorPanel = memo(function ({
const isOptedInToAI = selectedOrganization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false
const [error, setError] = useState<QueryResponseError>()
+ const [errorPanelOpen, setErrorPanelOpen] = useState(true)
const [showDetails, setShowDetails] = useState(false)
// [Joshen] Separate state here as there's a delay between submitting and the API updating the loading status
const [debugThread, setDebugThread] = useState<MessageWithDebug[]>([])
@@ -218,23 +219,14 @@ export const AIPolicyEditorPanel = memo(function ({
}
}, [visible])
- // [Joshen] Problem with monaco is that it's height cannot be dynamically updated once its initialized
- // So this is sort of a hacky way to do so, until we find a better solution at least
- const footerHeight = 58
- const createPolicyEditorHeight =
- error === undefined
- ? `calc(100vh - ${footerHeight}px - 54px)`
- : `calc(100vh - ${footerHeight}px - 151px - ${20 * errorLines}px)`
- const updatePolicyEditorHeight =
- showDetails && error === undefined
- ? `calc(100vh - ${footerHeight}px - 172px)`
- : showDetails && error !== undefined
- ? `calc(100vh - ${footerHeight}px - 172px - 122px - ${16 * errorLines}px)`
- : !showDetails && error === undefined
- ? `calc(100vh - ${footerHeight}px - 72px)`
- : !showDetails && error !== undefined
- ? `calc(100vh - ${footerHeight}px - 72px - 122px - ${16 * errorLines}px)`
- : '0'
+ // whenever the deps (current policy details, new error or error panel opens) change, recalculate
+ // the height of the editor
+ useEffect(() => {
+ editorRef.current?.layout({ width: 0, height: 0 })
+ window.requestAnimationFrame(() => {
+ editorRef.current?.layout()
+ })
+ }, [showDetails, error, errorPanelOpen])
return (
<>
@@ -290,23 +282,19 @@ export const AIPolicyEditorPanel = memo(function ({
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}
- <div
- // [Joshen] Not the cleanest but its to force the editor to re-render its height
- // for now, till we can find a better solution
- className={`relative ${incomingChange ? 'hidden' : 'block'}`}
- style={{
- height:
- selectedPolicy !== undefined
- ? updatePolicyEditorHeight
- : createPolicyEditorHeight,
- }}
- >
+ <div className={`relative h-full ${incomingChange ? 'hidden' : 'block'}`}>
<RLSCodeEditor
id="rls-sql-policy"
- wrapperClassName={incomingChange ? '!hidden' : ''}
defaultValue={''}
editorRef={editorRef}
placeholder={placeholder}
@@ -314,7 +302,14 @@ export const AIPolicyEditorPanel = memo(function ({
</div>
<div className="flex flex-col">
- {error !== undefined && <QueryError error={error} onSelectDebug={onSelectDebug} />}
+ {error !== undefined && (
+ <QueryError
+ error={error}
+ onSelectDebug={onSelectDebug}
+ open={errorPanelOpen}
+ setOpen={setErrorPanelOpen}
+ />
+ )}
<SheetFooter_Shadcn_ className="flex flex-col gap-12 px-5 py-4 w-full">
<div className="flex justify-end gap-x-2">
<Button type="default" disabled={isExecuting} onClick={() => onSelectCancel()}>
diff --git a/apps/studio/pages/api/ai/sql/suggest.ts b/apps/studio/pages/api/ai/sql/suggest.ts
index 9c9a2712bc1..70d15dc26ab 100644
--- a/apps/studio/pages/api/ai/sql/suggest.ts
+++ b/apps/studio/pages/api/ai/sql/suggest.ts
@@ -58,14 +58,16 @@ async function handlePost(request: NextRequest) {
The output should use the following instructions:
- The generated SQL must be valid SQL.
- Always use double apostrophe in SQL strings (eg. 'Night''s watch')
- - You can use only CREATE POLICY queries, no other queries are allowed.
+ - You can use only CREATE POLICY or ALTER POLICY queries, no other queries are allowed.
- You can add short explanations to your messages.
- The result should be a valid markdown. The SQL code should be wrapped in \`\`\`.
- Always use "auth.uid()" instead of "current_user".
- - Only use "WITH CHECK" on INSERT or UPDATE policies.
+ - You can't use "USING" expression on INSERT policies.
+ - Only use "WITH CHECK" expression on INSERT or UPDATE policies.
- The policy name should be short text explaining the policy, enclosed in double quotes.
- - Always make sure that every \`\`\` has a corresponding ending tag \`\`\`.
- - Always put explanations as separate text. Don't use inline SQL comments.
+ - Always put explanations as separate text. Never use inline SQL comments.
+ - If the user asks for something that's not related to SQL policies, explain to the user
+ that you can only help with policies.
The output should look like this:
"CREATE POLICY user_policy ON users FOR INSERT USING (user_name = current_user) WITH (true);"
@@ -82,11 +84,12 @@ async function handlePost(request: NextRequest) {
}
if (policyDefinition !== undefined) {
+ const definitionBlock = codeBlock`${policyDefinition}`
initMessages.push({
role: 'user',
content: codeBlock`
Here is my policy definition for reference:
- ${policyDefinition}
+ ${definitionBlock}
`.trim(),
})
}