The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Use expanding text area fort RLS assistant (#28444)
Joshen Lim4e3b2daabe9f
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsxindex 32d5e5a9549..72bbe031a06 100644--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx@@ -1,27 +1,16 @@-import { zodResolver } from '@hookform/resolvers/zod'-import { useTelemetryProps } from 'common'import Telemetry from 'lib/telemetry'import { compact, last } from 'lodash'-import { Loader2 } from 'lucide-react'import { useRouter } from 'next/router'-import { useEffect, useRef } from 'react'-import { useForm } from 'react-hook-form'-import * as z from 'zod'+import { useEffect, useRef, useState } from 'react'+import { useTelemetryProps } from 'common'import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'import { IS_PLATFORM, LOCAL_STORAGE_KEYS, OPT_IN_TAGS } from 'lib/constants'import { useProfile } from 'lib/profile'import { useAppStateSnapshot } from 'state/app-state'-import {- Button,- FormControl_Shadcn_,- FormField_Shadcn_,- FormItem_Shadcn_,- Form_Shadcn_,- Input_Shadcn_,- cn,-} from 'ui'+import { Button, cn } from 'ui'+import { AssistantChatForm } from 'ui-patterns'import { AiIcon } from 'ui-patterns/Cmdk'import { MessageWithDebug } from './AIPolicyEditorPanel.utils'import Message from './Message'@@ -32,7 +21,6 @@ interface AIPolicyChatProps {loading: booleanonSubmit: (s: string) => voidonDiff: (message: { id: string; content: string }) => void- onChange: (value: boolean) => void}export const AIPolicyChat = ({@@ -41,7 +29,6 @@ export const AIPolicyChat = ({loading,onSubmit,onDiff,- onChange,}: AIPolicyChatProps) => {const router = useRouter()const { profile } = useProfile()@@ -50,41 +37,32 @@ export const AIPolicyChat = ({const bottomRef = useRef<HTMLDivElement>(null)const telemetryProps = useTelemetryProps()+ const [value, setValue] = useState<string>('')+ const inputRef = useRef<HTMLTextAreaElement>(null)+const isOptedInToAI = organization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? falseconst [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchemaconst name = compact([profile?.first_name, profile?.last_name]).join(' ')-- const FormSchema = z.object({ chat: z.string() })- const form = useForm<z.infer<typeof FormSchema>>({- mode: 'onBlur',- reValidateMode: 'onBlur',- resolver: zodResolver(FormSchema),- defaultValues: { chat: '' },- })- const formChatValue = form.getValues().chatconst pendingReply = loading && last(messages)?.role === 'user'- // try to scroll on each rerender to the bottom- useEffect(() => {- if (loading && bottomRef.current) {- setTimeout(() => {- bottomRef.current?.scrollIntoView({ behavior: 'smooth' })- }, 500)- }- })-useEffect(() => {if (!loading) {- form.setValue('chat', '')- form.setFocus('chat')+ setValue('')+ if (inputRef.current) inputRef.current.focus()}- }, [loading])- useEffect(() => {- onChange(formChatValue.length === 0)- }, [formChatValue])+ // 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">@@ -133,12 +111,18 @@ export const AIPolicyChat = ({<div ref={bottomRef} className="h-1" /></div>- <Form_Shadcn_ {...form}>- <form- id="rls-chat"- className="sticky p-5 flex-0 border-t"- onSubmit={form.handleSubmit((data: z.infer<typeof FormSchema>) => {- onSubmit(data.chat)+ <div className="sticky p-5 flex-0 border-t">+ <AssistantChatForm+ textAreaRef={inputRef}+ loading={loading}+ disabled={loading}+ icon={<AiIcon className="[&>div>div]:border-black dark:[&>div>div]:border-white" />}+ placeholder="Ask for some changes to your policy"+ value={value}+ onValueChange={(e) => setValue(e.target.value)}+ onSubmit={(event) => {+ event.preventDefault()+ onSubmit(value)Telemetry.sendEvent({category: 'rls_editor',@@ -148,34 +132,9 @@ export const AIPolicyChat = ({telemetryProps,router)- })}- >- <FormField_Shadcn_- control={form.control}- name="chat"- render={({ field }) => (- <FormItem_Shadcn_>- <FormControl_Shadcn_>- <div className="relative">- <AiIcon className="absolute top-2 left-3 [&>div>div]:border-black dark:[&>div>div]:border-white" />- <Input_Shadcn_- {...field}- autoComplete="off"- disabled={loading}- autoFocus- className={`bg-surface-300 dark:bg-black rounded-full pl-10 ${- loading ? 'pr-10' : ''- }`}- placeholder="Ask for some changes to your policy"- />- {loading && <Loader2 className="absolute top-2 right-3 animate-spin" />}- </div>- </FormControl_Shadcn_>- </FormItem_Shadcn_>- )}- />- </form>- </Form_Shadcn_>+ }}+ />+ </div></div>)}diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsxindex 79c61a87636..8e653c52ad6 100644--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx@@ -129,7 +129,6 @@ export const AIPolicyEditorPanel = memo(function ({// [Joshen] Separate state here as there's a delay between submitting and the API updating the loading statusconst [debugThread, setDebugThread] = useState<MessageWithDebug[]>([])const [assistantVisible, setAssistantPanel] = useState<boolean>(false)- const [isAssistantChatInputEmpty, setIsAssistantChatInputEmpty] = useState<boolean>(true)const [incomingChange, setIncomingChange] = useState<string>()// Used for confirmation when closing the panel with unsaved changesconst [isClosingPolicyEditorPanel, setIsClosingPolicyEditorPanel] = useState<boolean>(false)@@ -253,12 +252,7 @@ export const AIPolicyEditorPanel = memo(function ({}): false- if (- policyCreateUnsaved ||- policyUpdateUnsaved ||- messages.length > 0 ||- !isAssistantChatInputEmpty- ) {+ if (policyCreateUnsaved || policyUpdateUnsaved || messages.length > 0) {setIsClosingPolicyEditorPanel(true)} else {onSelectCancel()@@ -849,7 +843,6 @@ export const AIPolicyEditorPanel = memo(function ({})}onDiff={updateEditorWithCheckForDiff}- onChange={setIsAssistantChatInputEmpty}loading={isLoading || isDebugSqlLoading}/></TabsContent_Shadcn_>diff --git a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsxindex e6e19e3fa80..771abbfa586 100644--- a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx+++ b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx@@ -1,28 +1,17 @@-import { zodResolver } from '@hookform/resolvers/zod'import { Message as MessageType } from 'ai'-import { useTelemetryProps } from 'common'import Telemetry from 'lib/telemetry'import { compact, last } from 'lodash'-import { Loader2 } from 'lucide-react'import { useRouter } from 'next/router'-import { useEffect, useRef } from 'react'-import { useForm } from 'react-hook-form'-import * as z from 'zod'+import { useEffect, useRef, useState } from 'react'+import { useTelemetryProps } from 'common'import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'import { IS_PLATFORM, LOCAL_STORAGE_KEYS, OPT_IN_TAGS } from 'lib/constants'import { useProfile } from 'lib/profile'import { useAppStateSnapshot } from 'state/app-state'-import {- ExpandingTextArea,- Button,- FormControl_Shadcn_,- FormField_Shadcn_,- FormItem_Shadcn_,- Form_Shadcn_,- cn,-} from 'ui'+import { Button, cn } from 'ui'+import { AssistantChatForm } from 'ui-patterns'import { AiIcon } from 'ui-patterns/Cmdk'import { DiffType } from '../SQLEditor.types'import Message from './Message'@@ -55,38 +44,32 @@ export const AiAssistantPanel = ({const bottomRef = useRef<HTMLDivElement>(null)const telemetryProps = useTelemetryProps()+ const [value, setValue] = useState<string>('')+ const inputRef = useRef<HTMLTextAreaElement>(null)+const isOptedInToAI = organization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? falseconst [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchemaconst name = compact([profile?.first_name, profile?.last_name]).join(' ')-- const FormSchema = z.object({ chat: z.string() })- const form = useForm<z.infer<typeof FormSchema>>({- mode: 'onBlur',- reValidateMode: 'onBlur',- resolver: zodResolver(FormSchema),- defaultValues: { chat: '' },- })const pendingReply = loading && last(messages)?.role === 'user'- // try to scroll on each rerender to the bottom- useEffect(() => {- if (loading && bottomRef.current) {- setTimeout(() => {- bottomRef.current?.scrollIntoView({ behavior: 'smooth' })- }, 500)- }- })-useEffect(() => {if (!loading) {- form.setValue('chat', '')- form.setFocus('chat')+ setValue('')+ if (inputRef.current) inputRef.current.focus()}- }, [loading])- const formRef = useRef<HTMLFormElement>(null)+ // Try to scroll on each rerender to the bottom+ setTimeout(+ () => {+ if (bottomRef.current) {+ bottomRef.current.scrollIntoView({ behavior: 'smooth' })+ }+ },+ loading ? 100 : 500+ )+ }, [loading])return (<div className="flex flex-col h-full min-w-[400px] w-[400px] border-l border-control">@@ -150,12 +133,18 @@ export const AiAssistantPanel = ({<div ref={bottomRef} className="h-1" /></div>- <Form_Shadcn_ {...form}>- <form- ref={formRef}- className="sticky p-5 flex-0 border-t"- onSubmit={form.handleSubmit((data: z.infer<typeof FormSchema>) => {- onSubmit(data.chat)+ <div className="sticky p-5 flex-0 border-t">+ <AssistantChatForm+ textAreaRef={inputRef}+ loading={loading}+ disabled={loading}+ icon={<AiIcon 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()+ onSubmit(value)Telemetry.sendEvent({category: 'sql_editor_ai_assistant',@@ -165,39 +154,9 @@ export const AiAssistantPanel = ({telemetryProps,router)- })}- >- <FormField_Shadcn_- control={form.control}- name="chat"- render={({ field }) => (- <FormItem_Shadcn_ asChild>- <FormControl_Shadcn_>- <div className="relative">- <AiIcon className="absolute top-2 left-3 [&>div>div]:border-black dark:[&>div>div]:border-white" />- <ExpandingTextArea- {...field}- autoComplete="off"- disabled={loading}- autoFocus- spellCheck={false}- className="pl-12 text-sm rounded-[18px] max-h-96"- onKeyDown={(event) => {- if (event.key === 'Enter' && !event.shiftKey) {- event.preventDefault()- formRef?.current?.requestSubmit()- }- }}- placeholder="Ask a question about your SQL query"- />- {loading && <Loader2 className="absolute top-2 right-3 animate-spin" />}- </div>- </FormControl_Shadcn_>- </FormItem_Shadcn_>- )}- />- </form>- </Form_Shadcn_>+ }}+ />+ </div></div>)}diff --git a/packages/ui/src/components/ExpandingTextArea/index.tsx b/packages/ui/src/components/ExpandingTextArea/index.tsxindex b867ecea92b..8184f243e2e 100644--- a/packages/ui/src/components/ExpandingTextArea/index.tsx+++ b/packages/ui/src/components/ExpandingTextArea/index.tsx@@ -23,9 +23,10 @@ const ExpandingTextArea = forwardRef<HTMLTextAreaElement, ExpandingTextAreaProps*/useEffect(() => {if (textAreaRef) {- if (!value && textAreaRef && textAreaRef.current) {+ if (textAreaRef.current && !value) {textAreaRef.current.style.height = '40px'} else if (textAreaRef && textAreaRef.current) {+ textAreaRef.current.style.height = 'auto'const newHeight = textAreaRef.current.scrollHeight + 'px'textAreaRef.current.style.height = newHeight}