The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Assistant UI refine (#38228)
Saxon Fletcher2538a5c8aff9
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsxindex da0603309ca..84db19d38db 100644--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx@@ -2,9 +2,9 @@ import type { UIMessage as MessageType } from '@ai-sdk/react'import { useChat } from '@ai-sdk/react'import { DefaultChatTransport } from 'ai'import { AnimatePresence, motion } from 'framer-motion'-import { ArrowDown, Eraser, Info, Pencil, Settings, X } from 'lucide-react'+import { Eraser, Info, Pencil, X } from 'lucide-react'import { useRouter } from 'next/router'-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { LOCAL_STORAGE_KEYS, useFlag } from 'common'import { useParams, useSearchParamsShallow } from 'common/hooks'@@ -23,65 +23,21 @@ import uuidv4 from 'lib/uuid'import type { AssistantMessageType } from 'state/ai-assistant-state'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'-import { AiIconAnimation, Button, cn, KeyboardShortcut } from 'ui'-import { Admonition, GenericSkeletonLoader } from 'ui-patterns'+import { Button, cn, KeyboardShortcut } from 'ui'+import { Admonition } from 'ui-patterns'import { ButtonTooltip } from '../ButtonTooltip'import { ErrorBoundary } from '../ErrorBoundary'import { type SqlSnippet } from './AIAssistant.types'import { onErrorChat } from './AIAssistant.utils'-import { AIAssistantChatSelector } from './AIAssistantChatSelector'+import { AIAssistantHeader } from './AIAssistantHeader'import { AIOnboarding } from './AIOnboarding'-import { AIOptInModal } from './AIOptInModal'import { AssistantChatForm } from './AssistantChatForm'-import { Message } from './Message'-import { useAutoScroll } from './hooks'--const MemoizedMessage = memo(- ({- message,- isLoading,- onResults,- onDelete,- onEdit,- isAfterEditedMessage,- isBeingEdited,- onCancelEdit,- }: {- message: MessageType- isLoading: boolean- onResults: ({- messageId,- resultId,- results,- }: {- messageId: string- resultId?: string- results: any[]- }) => void- onDelete: (id: string) => void- onEdit: (id: string) => void- isAfterEditedMessage: boolean- isBeingEdited: boolean- onCancelEdit: () => void- }) => {- return (- <Message- id={message.id}- message={message}- readOnly={message.role === 'user'}- isLoading={isLoading}- onResults={onResults}- onDelete={onDelete}- onEdit={onEdit}- isAfterEditedMessage={isAfterEditedMessage}- isBeingEdited={isBeingEdited}- onCancelEdit={onCancelEdit}- />- )- }-)--MemoizedMessage.displayName = 'MemoizedMessage'+import {+ Conversation,+ ConversationContent,+ ConversationScrollButton,+} from './elements/Conversation'+import { MemoizedMessage } from './Message'interface AIAssistantProps {initialMessages?: MessageType[] | undefined@@ -107,7 +63,6 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {)const inputRef = useRef<HTMLTextAreaElement>(null)- const { ref: scrollContainerRef, isSticky, scrollToEnd, setIsSticky } = useAutoScroll()const { aiOptInLevel, isHipaaProjectDisallowed } = useOrgAiOptInLevel()const showMetadataWarning =@@ -119,7 +74,6 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {const lastUserMessageRef = useRef<MessageType | null>(null)const [value, setValue] = useState<string>(snap.initialInput || '')- const [isConfirmOptInModalOpen, setIsConfirmOptInModalOpen] = useState(false)const [editingMessageId, setEditingMessageId] = useState<string | null>(null)const [isResubmitting, setIsResubmitting] = useState(false)@@ -130,7 +84,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {const snippet = snippets[entityId ?? '']const snippetContent = snippet?.snippet?.content?.sql- const { data: tables, isLoading: isLoadingTables } = useTablesQuery(+ const { data: tables } = useTablesQuery({projectRef: project?.ref,connectionString: project?.connectionString,@@ -235,7 +189,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {onFinish: handleChatFinish,})- const isChatLoading = chatStatus === 'submitted' || chatStatus === 'streaming' || isResubmitting+ const isChatLoading = chatStatus === 'submitted' || chatStatus === 'streaming'const updateMessage = useCallback(({@@ -316,7 +270,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {<MemoizedMessagekey={message.id}message={message}- isLoading={isChatLoading && message.id === chatMessages[chatMessages.length - 1].id}+ status={chatStatus}onResults={updateMessage}onDelete={deleteMessageFromHere}onEdit={editMessage}@@ -328,12 +282,12 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {}),[chatMessages,- isChatLoading,updateMessage,deleteMessageFromHere,editMessage,cancelEdit,editingMessageId,+ chatStatus,])@@ -395,17 +349,6 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {}}, [isResubmitting, chatStatus, error])- // Update scroll behavior for new messages- useEffect(() => {- if (!isChatLoading) {- if (inputRef.current) inputRef.current.focus()- }-- if (isSticky) {- setTimeout(scrollToEnd, 0)- }- }, [isChatLoading, isSticky, scrollToEnd])-useEffect(() => {setValue(snap.initialInput || '')if (inputRef.current && snap.initialInput) {@@ -421,10 +364,6 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [snap.open, isInSQLEditor, snippetContent])- useEffect(() => {- if (chatMessages.length === 0 && !isSticky) setIsSticky(true)- }, [chatMessages, isSticky, setIsSticky])-return (<ErrorBoundarymessage="Something went wrong with the AI Assistant"@@ -445,102 +384,19 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {]}><div className={cn('flex flex-col h-full', className)}>- <div ref={scrollContainerRef} className={cn('flex-grow overflow-auto flex flex-col')}>- <div className="z-30 sticky top-0">- <div className="border-b border-b-muted flex items-center bg gap-x-4 px-3 h-[46px]">- <div className="text-sm flex-1 flex items-center">- <AiIconAnimation size={20} allowHoverEffect={false} />- <span className="text-border-stronger dark:text-border-strong ml-3">- <svg- viewBox="0 0 24 24"- width="16"- height="16"- stroke="currentColor"- strokeWidth="1"- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- shapeRendering="geometricPrecision"- >- <path d="M16 3.549L7.12 20.600"></path>- </svg>- </span>- <AIAssistantChatSelector disabled={isChatLoading} />- </div>- <div className="flex items-center gap-x-4">- <div className="flex items-center">- <ButtonTooltip- type="text"- size="tiny"- icon={<Settings strokeWidth={1.5} />}- onClick={() => setIsConfirmOptInModalOpen(true)}- className="h-7 w-7 p-0"- disabled={isChatLoading}- tooltip={{- content: {- side: 'bottom',- text: 'Permission settings',- },- }}- />- <ButtonTooltip- type="text"- size="tiny"- icon={<Eraser strokeWidth={1.5} />}- onClick={handleClearMessages}- className="h-7 w-7 p-0"- disabled={isChatLoading}- tooltip={{ content: { side: 'bottom', text: 'Clear messages' } }}- />- <ButtonTooltip- type="text"- className="w-7 h-7"- onClick={snap.closeAssistant}- icon={<X strokeWidth={1.5} />}- tooltip={{ content: { side: 'bottom', text: 'Close assistant' } }}- />- </div>- </div>- </div>- {showMetadataWarning && (- <Admonition- type="default"- title={- !updatedOptInSinceMCP- ? 'The Assistant has just been updated to help you better!'- : isHipaaProjectDisallowed- ? 'Project metadata is not shared due to HIPAA'- : aiOptInLevel === 'disabled'- ? 'Project metadata is currently not shared'- : 'Limited metadata is shared to the Assistant'- }- description={- !updatedOptInSinceMCP- ? 'You may now opt-in to share schema metadata and even logs for better results'- : isHipaaProjectDisallowed- ? 'Your organization has the HIPAA addon and will not send project metadata with your prompts for projects marked as HIPAA.'- : aiOptInLevel === 'disabled'- ? 'The Assistant can provide better answers if you opt-in to share schema metadata.'- : aiOptInLevel === 'schema'- ? 'Sharing query data in addition to schema can further improve responses. Update AI settings to enable this.'- : ''- }- className="border-0 border-b rounded-none bg-background mb-0"- >- {!isHipaaProjectDisallowed && (- <Button- type="default"- className="w-fit mt-4"- onClick={() => setIsConfirmOptInModalOpen(true)}- >- Permission settings- </Button>- )}- </Admonition>- )}- </div>- {hasMessages ? (- <div className="w-full px-7 py-8 mb-10">+ <Conversation className={cn('flex-1')}>+ <AIAssistantHeader+ isChatLoading={isChatLoading}+ onClearMessages={handleClearMessages}+ onCloseAssistant={snap.closeAssistant}+ showMetadataWarning={showMetadataWarning}+ updatedOptInSinceMCP={updatedOptInSinceMCP}+ isHipaaProjectDisallowed={isHipaaProjectDisallowed as boolean}+ aiOptInLevel={aiOptInLevel}+ />++ {hasMessages && (+ <ConversationContent className="w-full px-7 py-8 mb-10">{renderedMessages}{error && (<div className="border rounded-md px-2 py-2 flex items-center justify-between gap-x-4">@@ -575,65 +431,18 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {</div></div>)}- <AnimatePresence>- {isChatLoading && (- <motion.div- initial={{ opacity: 0, y: 10 }}- animate={{ opacity: 1, y: 0 }}- exit={{ opacity: 0, y: -10 }}- transition={{ duration: 0.2 }}- className="flex gap-4 w-auto overflow-hidden"- >- <div className="text-foreground-lighter text-sm flex gap-1.5 items-center">- <span>Thinking</span>- <div className="flex gap-1">- <motion.span- animate={{ opacity: [0, 1, 0] }}- transition={{ duration: 1.5, repeat: Infinity, delay: 0 }}- >- .- </motion.span>- <motion.span- animate={{ opacity: [0, 1, 0] }}- transition={{ duration: 1.5, repeat: Infinity, delay: 0.3 }}- >- .- </motion.span>- <motion.span- animate={{ opacity: [0, 1, 0] }}- transition={{ duration: 1.5, repeat: Infinity, delay: 0.6 }}- >- .- </motion.span>- </div>- </div>- </motion.div>- )}- </AnimatePresence>- </div>- ) : isLoadingTables && isApiKeySet ? (- <div className="w-full h-full flex-1 flex flex-col justify-center items-center p-5">- <GenericSkeletonLoader className="w-4/5 flex flex-col items-center" />- </div>- ) : isShowingOnboarding ? (- <AIOnboarding- onMessageSend={sendMessageToAssistant}- value={value}- onValueChange={setValue}- sqlSnippets={snap.sqlSnippets as SqlSnippet[] | undefined}- onRemoveSnippet={(index) => {- const newSnippets = [...(snap.sqlSnippets ?? [])]- newSnippets.splice(index, 1)- snap.setSqlSnippets(newSnippets)- }}- suggestions={- snap.suggestions as- | { title?: string; prompts?: { label: string; description: string }[] }- | undefined- }- />- ) : null}- </div>+ {isChatLoading && (+ <motion.span+ animate={{ opacity: [1, 0] }}+ transition={{ duration: 1, repeat: Infinity, ease: 'linear' }}+ className="inline-block w-1.5 h-4 bg-foreground-lighter"+ />+ )}+ </ConversationContent>+ )}++ <ConversationScrollButton />+ </Conversation><AnimatePresence>{editingMessageId && (@@ -677,111 +486,83 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {</div></motion.div>)}- {!isSticky && !editingMessageId && (- <motion.div- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- exit={{ opacity: 0 }}- className="pointer-events-none z-10 -mt-24"- >- <div className="h-24 w-full bg-gradient-to-t from-background to-transparent relative">- <motion.div- className="absolute z-20 bottom-8 left-1/2 -translate-x-1/2 pointer-events-auto"- variants={{- hidden: { y: 5, opacity: 0 },- show: { y: 0, opacity: 1 },- }}- transition={{ duration: 0.1 }}- initial="hidden"- animate="show"- exit="hidden"- >- <Button- type="default"- className="rounded-full w-8 h-8 p-1.5"- onClick={() => {- scrollToEnd()- if (inputRef.current) inputRef.current.focus()- }}- >- <ArrowDown size={16} />- </Button>- </motion.div>- </div>- </motion.div>- )}</AnimatePresence>- {!isShowingOnboarding && (- <div className="px-3 pb-3 z-20 relative">- {disablePrompts && (- <Admonition- showIcon={false}- type="default"- title="Assistant has been temporarily disabled"- description="We're currently looking into getting it back online"- />- )}-- {isSuccess && !isApiKeySet && (- <Admonition- type="default"- title="OpenAI API key not set"- description={- <Markdown- content={- 'Add your `OPENAI_API_KEY` to your environment variables to use the AI Assistant.'- }- />- }- />- )}+ <div className="px-3 pb-3 z-20 relative">+ {disablePrompts && (+ <Admonition+ showIcon={false}+ type="default"+ title="Assistant has been temporarily disabled"+ description="We're currently looking into getting it back online"+ />+ )}- <AssistantChatForm- textAreaRef={inputRef}- className={cn(- 'z-20 [&>form>textarea]:text-base [&>form>textarea]:md:text-sm [&>form>textarea]:border-1 [&>form>textarea]:rounded-md [&>form>textarea]:!outline-none [&>form>textarea]:!ring-offset-0 [&>form>textarea]:!ring-0'- )}- loading={isChatLoading}- isEditing={!!editingMessageId}- disabled={!isApiKeySet || disablePrompts || (isChatLoading && !editingMessageId)}- placeholder={- hasMessages- ? 'Ask a follow up question...'- : (snap.sqlSnippets ?? [])?.length > 0- ? 'Ask a question or make a change...'- : 'Chat to Postgres...'+ {isSuccess && !isApiKeySet && (+ <Admonition+ type="default"+ title="OpenAI API key not set"+ description={+ <Markdown+ content={+ 'Add your `OPENAI_API_KEY` to your environment variables to use the AI Assistant.'+ }+ />}- value={value}- onValueChange={(e) => setValue(e.target.value)}- onSubmit={(finalMessage) => {- sendMessageToAssistant(finalMessage)- scrollToEnd()- }}- onStop={() => {- stop()- // to save partial responses from the AI- const lastMessage = chatMessages[chatMessages.length - 1]- if (lastMessage && lastMessage.role === 'assistant') {- handleChatFinish({ message: lastMessage })- }- }}+ />+ )}++ {isShowingOnboarding && (+ <AIOnboardingsqlSnippets={snap.sqlSnippets as SqlSnippet[] | undefined}- onRemoveSnippet={(index) => {- const newSnippets = [...(snap.sqlSnippets ?? [])]- newSnippets.splice(index, 1)- snap.setSqlSnippets(newSnippets)- }}- includeSnippetsInMessage={aiOptInLevel !== 'disabled'}+ suggestions={+ snap.suggestions as+ | { title?: string; prompts?: { label: string; description: string }[] }+ | undefined+ }+ onValueChange={(val) => setValue(val)}+ onFocusInput={() => inputRef.current?.focus()}/>- </div>- )}- </div>+ )}- <AIOptInModal- visible={isConfirmOptInModalOpen}- onCancel={() => setIsConfirmOptInModalOpen(false)}- />+ <AssistantChatForm+ textAreaRef={inputRef}+ className={cn(+ 'z-20 [&>form>textarea]:text-base [&>form>textarea]:md:text-sm [&>form>textarea]:border-1 [&>form>textarea]:rounded-md [&>form>textarea]:!outline-none [&>form>textarea]:!ring-offset-0 [&>form>textarea]:!ring-0'+ )}+ loading={isChatLoading}+ isEditing={!!editingMessageId}+ disabled={!isApiKeySet || disablePrompts || (isChatLoading && !editingMessageId)}+ placeholder={+ hasMessages+ ? 'Ask a follow up question...'+ : (snap.sqlSnippets ?? [])?.length > 0+ ? 'Ask a question or make a change...'+ : 'Chat to Postgres...'+ }+ value={value}+ onValueChange={(e) => setValue(e.target.value)}+ onSubmit={(finalMessage) => {+ sendMessageToAssistant(finalMessage)+ }}+ onStop={() => {+ stop()+ // to save partial responses from the AI+ const lastMessage = chatMessages[chatMessages.length - 1]+ if (lastMessage && lastMessage.role === 'assistant') {+ handleChatFinish({ message: lastMessage })+ }+ }}+ sqlSnippets={snap.sqlSnippets as SqlSnippet[] | undefined}+ onRemoveSnippet={(index) => {+ const newSnippets = [...(snap.sqlSnippets ?? [])]+ newSnippets.splice(index, 1)+ snap.setSqlSnippets(newSnippets)+ }}+ includeSnippetsInMessage={aiOptInLevel !== 'disabled'}+ />+ </div>+ </div></ErrorBoundary>)}diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistantHeader.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistantHeader.tsxnew file mode 100644index 00000000000..b2211f62c70--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistantHeader.tsx@@ -0,0 +1,119 @@+import { Eraser, Settings, X } from 'lucide-react'+import { useState } from 'react'++import { AiIconAnimation, Button } from 'ui'+import { Admonition } from 'ui-patterns'+import { ButtonTooltip } from '../ButtonTooltip'+import { AIAssistantChatSelector } from './AIAssistantChatSelector'+import { AIOptInModal } from './AIOptInModal'++interface AIAssistantHeaderProps {+ isChatLoading: boolean+ onClearMessages: () => void+ onCloseAssistant: () => void+ showMetadataWarning: boolean+ updatedOptInSinceMCP: boolean+ isHipaaProjectDisallowed: boolean+ aiOptInLevel: 'disabled' | 'schema' | 'full' | string | undefined+}++export const AIAssistantHeader = ({+ isChatLoading,+ onClearMessages,+ onCloseAssistant,+ showMetadataWarning,+ updatedOptInSinceMCP,+ isHipaaProjectDisallowed,+ aiOptInLevel,+}: AIAssistantHeaderProps) => {+ const [isOptInModalOpen, setIsOptInModalOpen] = useState(false)+ return (+ <div className="z-30 sticky top-0">+ <div className="border-b border-b-muted flex items-center bg gap-x-4 px-3 h-[46px]">+ <div className="text-sm flex-1 flex items-center">+ <AiIconAnimation size={20} allowHoverEffect={false} />+ <span className="text-border-stronger dark:text-border-strong ml-3">+ <svg+ viewBox="0 0 24 24"+ width="16"+ height="16"+ stroke="currentColor"+ strokeWidth="1"+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ shapeRendering="geometricPrecision"+ >+ <path d="M16 3.549L7.12 20.600" />+ </svg>+ </span>+ <AIAssistantChatSelector disabled={isChatLoading} />+ </div>+ <div className="flex items-center gap-x-4">+ <div className="flex items-center">+ <ButtonTooltip+ type="text"+ size="tiny"+ icon={<Settings strokeWidth={1.5} />}+ onClick={() => setIsOptInModalOpen(true)}+ className="h-7 w-7 p-0"+ disabled={isChatLoading}+ tooltip={{+ content: { side: 'bottom', text: 'Permission settings' },+ }}+ />+ <ButtonTooltip+ type="text"+ size="tiny"+ icon={<Eraser strokeWidth={1.5} />}+ onClick={onClearMessages}+ className="h-7 w-7 p-0"+ disabled={isChatLoading}+ tooltip={{ content: { side: 'bottom', text: 'Clear messages' } }}+ />+ <ButtonTooltip+ type="text"+ className="w-7 h-7"+ onClick={onCloseAssistant}+ icon={<X strokeWidth={1.5} />}+ tooltip={{ content: { side: 'bottom', text: 'Close assistant' } }}+ />+ </div>+ </div>+ </div>+ {showMetadataWarning && (+ <Admonition+ type="default"+ title={+ !updatedOptInSinceMCP+ ? 'The Assistant has just been updated to help you better!'+ : isHipaaProjectDisallowed+ ? 'Project metadata is not shared due to HIPAA'+ : aiOptInLevel === 'disabled'+ ? 'Project metadata is currently not shared'+ : 'Limited metadata is shared to the Assistant'+ }+ description={+ !updatedOptInSinceMCP+ ? 'You may now opt-in to share schema metadata and even logs for better results'+ : isHipaaProjectDisallowed+ ? 'Your organization has the HIPAA addon and will not send project metadata with your prompts for projects marked as HIPAA.'+ : aiOptInLevel === 'disabled'+ ? 'The Assistant can provide better answers if you opt-in to share schema metadata.'+ : aiOptInLevel === 'schema'+ ? 'Sharing query data in addition to schema can further improve responses. Update AI settings to enable this.'+ : ''+ }+ className="border-0 border-b rounded-none bg-background mb-0"+ >+ {!isHipaaProjectDisallowed && (+ <Button type="default" className="w-fit mt-4" onClick={() => setIsOptInModalOpen(true)}>+ Permission settings+ </Button>+ )}+ </Admonition>+ )}+ <AIOptInModal visible={isOptInModalOpen} onCancel={() => setIsOptInModalOpen(false)} />+ </div>+ )+}diff --git a/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx b/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsxindex d291245a00a..225dc189bca 100644--- a/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx@@ -1,34 +1,26 @@import { motion } from 'framer-motion'import { FileText } from 'lucide-react'-import { useRef } from 'react'-import { Button, cn } from 'ui'-import { AssistantChatForm } from './AssistantChatForm'+import { Button } from 'ui'import { type SqlSnippet } from './AIAssistant.types'import { codeSnippetPrompts, defaultPrompts } from './AIAssistant.prompts'interface AIOnboardingProps {- onMessageSend: (message: string) => voidsqlSnippets?: SqlSnippet[]- onRemoveSnippet?: (index: number) => voidsuggestions?: {title?: stringprompts?: { label: string; description: string }[]}- value: stringonValueChange: (value: string) => void+ onFocusInput?: () => void}export const AIOnboarding = ({- onMessageSend,sqlSnippets,- onRemoveSnippet,suggestions,- value,onValueChange,+ onFocusInput,}: AIOnboardingProps) => {- const inputRef = useRef<HTMLTextAreaElement>(null)-const prompts = suggestions?.prompts? suggestions.prompts.map((suggestion) => ({title: suggestion.label,@@ -40,64 +32,36 @@ export const AIOnboarding = ({: defaultPromptsreturn (- <div className="w-full h-full flex flex-col">- {/* Header Section */}- <div className="flex-1 flex flex-col items-center justify-center p-6">- <motion.div- initial={{ y: 10, opacity: 0 }}- animate={{ y: 0, opacity: 1 }}- transition={{ duration: 0.5 }}- className="text-center max-w-xl w-full overflow-hiddenflex flex-col items-center"- >- <h2 className="text-2xl mb-6">How can I assist you?</h2>-- <div className="w-full mb-6">- <AssistantChatForm- textAreaRef={inputRef}- className={cn(- 'z-20 [&>form>textarea]:text-base [&>form>textarea]:md:text-sm [&>form>textarea]:border-1 [&>form>textarea]:rounded-md [&>form>textarea]:!outline-none [&>form>textarea]:!ring-offset-0 [&>form>textarea]:!ring-0'- )}- loading={false}- disabled={false}- placeholder="Ask me anything..."- value={value}- onValueChange={(e) => onValueChange(e.target.value)}- onSubmit={(finalMessage) => {- if (finalMessage.trim()) {- onMessageSend(finalMessage)- onValueChange('')- }+ <div className="w-full mb-6">+ <div className="px-4 mb-4">+ <h2 className="heading-section text-foreground mb-1">How can I assist you?</h2>+ <p className="text-foreground-light text-sm">+ Generate SQL, RLS policies and edge functions, debug issues or check on your project+ health.+ </p>+ </div>+ <div>+ {prompts.map((item, index) => (+ <motion.div+ key={index}+ initial={{ y: 5, opacity: 0 }}+ animate={{ y: 0, opacity: 1 }}+ transition={{ duration: 0.3, delay: index * 0.05 }}+ >+ <Button+ size="small"+ type="text"+ className="w-full justify-start"+ icon={<FileText strokeWidth={1.5} size={14} className="text-foreground-light" />}+ onClick={() => {+ onValueChange(item.prompt)+ onFocusInput?.()}}- sqlSnippets={sqlSnippets}- onRemoveSnippet={onRemoveSnippet}- snippetsClassName="text-left"- includeSnippetsInMessage={true}- />- </div>-- <div className="flex flex-wrap items-center justify-center gap-2">- {prompts.map((item, index) => (- <motion.div- key={index}- initial={{ y: 5, opacity: 0 }}- animate={{ y: 0, opacity: 1 }}- transition={{ duration: 0.3, delay: index * 0.1 }}- >- <Button- size="small"- type="outline"- className="text-xs rounded-full !h-auto py-1 px-2 text-foreground-light"- onClick={() => {- onValueChange(item.prompt)- inputRef.current?.focus()- }}- >- {item.title}- </Button>- </motion.div>- ))}- </div>- </motion.div>+ >+ {item.title}+ </Button>+ </motion.div>+ ))}</div></div>)diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.tsxindex 4306c4078a1..a692bade1e0 100644--- a/apps/studio/components/ui/AIAssistantPanel/Message.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/Message.tsx@@ -1,6 +1,6 @@import { UIMessage as VercelMessage } from '@ai-sdk/react'-import { Loader2, Pencil, Trash2 } from 'lucide-react'-import { createContext, PropsWithChildren, ReactNode, useMemo, useState } from 'react'+import { CheckIcon, Loader2, Pencil, Trash2 } from 'lucide-react'+import { createContext, memo, PropsWithChildren, ReactNode, useMemo, useState } from 'react'import ReactMarkdown from 'react-markdown'import { Components } from 'react-markdown/lib/ast-to-react'import remarkGfm from 'remark-gfm'@@ -11,8 +11,8 @@ import { useProfile } from 'lib/profile'import { cn, markdownComponents, WarningIcon } from 'ui'import { ButtonTooltip } from '../ButtonTooltip'import { EdgeFunctionBlock } from '../EdgeFunctionBlock/EdgeFunctionBlock'-import { DisplayBlockRenderer } from './DisplayBlockRenderer'import { DeleteMessageConfirmModal } from './DeleteMessageConfirmModal'+import { DisplayBlockRenderer } from './DisplayBlockRenderer'import {Heading3,Hyperlink,@@ -21,6 +21,7 @@ import {MarkdownPre,OrderedList,} from './MessageMarkdown'+import { Reasoning } from './elements/Reasoning'interface MessageContextType {isLoading: boolean@@ -42,6 +43,7 @@ interface MessageProps {message: VercelMessageisLoading: booleanreadOnly?: boolean+ status?: stringaction?: ReactNodevariant?: 'default' | 'warning'onResults: ({@@ -60,7 +62,7 @@ interface MessageProps {onCancelEdit: () => void}-export const Message = function Message({+const Message = function Message({id,message,isLoading,@@ -72,6 +74,7 @@ export const Message = function Message({onEdit,isAfterEditedMessage = false,isBeingEdited = false,+ status,onCancelEdit,}: PropsWithChildren<MessageProps>) {const { profile } = useProfile()@@ -125,23 +128,59 @@ export const Message = function Message({<ProfileImagealt={profile?.username}src={profile?.profileImageUrl}- className="w-5 h-5 shrink-0 rounded-full"+ className="w-5 h-5 shrink-0 rounded-full translate-y-0.5"/>)}- <div className="flex-1 min-w-0 [&>div:first-child]:!mt-1">+ <div className="flex-1 min-w-0">{shouldUsePartsRendering ? ((() => {- const shownLoadingTools = new Set<string>()return parts.map((part: NonNullable<VercelMessage['parts']>[number], index: number) => {switch (part.type) {+ case 'dynamic-tool': {+ return (+ <div+ key={`${id}-tool-${part.toolCallId}`}+ className={cn(+ 'border rounded-md border-muted heading-meta flex items-center gap-2 text-foreground-lighter py-2 px-3 dynamic-tool-item',+ '[&:not(.dynamic-tool-item+.dynamic-tool-item)]:mt-4 [&.dynamic-tool-item+.dynamic-tool-item]:mt-1 first:!mt-0',+ '[&:not(:has(+.dynamic-tool-item))]:mb-4'+ )}+ >+ {part.state === 'input-streaming' ? (+ <Loader2 strokeWidth={1.5} size={12} className="animate-spin" />+ ) : (+ <CheckIcon+ strokeWidth={1.5}+ size={12}+ className="text-foreground-muted"+ />+ )}+ {`${part.toolName}`}+ </div>+ )+ }+ case 'reasoning':+ return (+ <Reasoning+ key={`${message.id}-${index}}`}+ className={cn(+ 'w-full dynamic-tool-item',+ '[&:not(.dynamic-tool-item+.dynamic-tool-item)]:mt-4 [&.dynamic-tool-item+.dynamic-tool-item]:mt-1 first:!mt-0',+ '[&:not(:has(+.dynamic-tool-item))]:mb-4'+ )}+ isStreaming={part.state === 'streaming'}+ >+ {part.text}+ </Reasoning>+ )case 'text':return (<ReactMarkdownkey={`${id}-part-${index}`}className={cn(- 'prose prose-sm [&>div]:my-4 prose-h1:text-xl prose-h1:mt-6 prose-h3:no-underline prose-h3:text-base prose-h3:mb-4 prose-strong:font-medium prose-strong:text-foreground break-words [&>p:not(:last-child)]:!mb-2 [&>*>p:first-child]:!mt-0 [&>*>p:last-child]:!mb-0 [&>*>*>p:first-child]:!mt-0 [&>*>*>p:last-child]:!mb-0 [&>ol>li]:!pl-4',+ 'max-w-none prose prose-sm [&>div]:my-4 prose-h1:text-xl prose-h1:mt-6 prose-h2:text-lg prose-h3:no-underline prose-h3:text-base prose-h3:mb-4 prose-strong:font-medium prose-strong:text-foreground prose-ol:space-y-3 prose-ul:space-y-3 prose-li:my-0 break-words [&>p:not(:last-child)]:!mb-2 [&>*>p:first-child]:!mt-0 [&>*>p:last-child]:!mb-0 [&>*>*>p:first-child]:!mt-0 [&>*>*>p:last-child]:!mb-0 [&>ol>li]:!pl-4',isUser && 'text-foreground [&>p]:font-medium',isBeingEdited && 'animate-pulse')}@@ -155,10 +194,6 @@ export const Message = function Message({case 'tool-display_query': {const { toolCallId, state, input } = partif (state === 'input-streaming' || state === 'input-available') {- if (shownLoadingTools.has('display_query')) {- return null- }- shownLoadingTools.add('display_query')return (<divkey={`${id}-tool-loading-display_query`}@@ -188,10 +223,6 @@ export const Message = function Message({case 'tool-display_edge_function': {const { toolCallId, state, input } = partif (state === 'input-streaming' || state === 'input-available') {- if (shownLoadingTools.has('display_edge_function')) {- return null- }- shownLoadingTools.add('display_edge_function')return (<divkey={`${id}-tool-loading-display_edge_function`}@@ -206,7 +237,7 @@ export const Message = function Message({return (<divkey={`${id}-tool-${toolCallId}`}- className="w-auto overflow-x-hidden"+ className="w-auto overflow-x-hidden my-4"><EdgeFunctionBlocklabel={(input as any).name || 'Edge Function'}@@ -219,7 +250,6 @@ export const Message = function Message({}return null}- case 'reasoning':case 'source-url':case 'source-document':case 'file':@@ -242,8 +272,8 @@ export const Message = function Message({<span className="text-foreground-lighter italic">Assistant is thinking...</span>)}- {/* Action buttons - only show for user messages on hover */}- <div className="opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1">+ {/* Action button - only show for user messages on hover */}+ <div className="opacity-0 group-hover:opacity-100 transition-opacity mt-1 mb-2">{message.role === 'user' && (<><ButtonTooltip@@ -293,3 +323,51 @@ export const Message = function Message({</MessageContext.Provider>)}++export const MemoizedMessage = memo(+ ({+ message,+ status,+ onResults,+ onDelete,+ onEdit,+ isAfterEditedMessage,+ isBeingEdited,+ onCancelEdit,+ }: {+ message: VercelMessage+ status: string+ onResults: ({+ messageId,+ resultId,+ results,+ }: {+ messageId: string+ resultId?: string+ results: any[]+ }) => void+ onDelete: (id: string) => void+ onEdit: (id: string) => void+ isAfterEditedMessage: boolean+ isBeingEdited: boolean+ onCancelEdit: () => void+ }) => {+ return (+ <Message+ id={message.id}+ message={message}+ readOnly={message.role === 'user'}+ isLoading={status === 'submitted' || status === 'streaming'}+ status={status}+ onResults={onResults}+ onDelete={onDelete}+ onEdit={onEdit}+ isAfterEditedMessage={isAfterEditedMessage}+ isBeingEdited={isBeingEdited}+ onCancelEdit={onCancelEdit}+ />+ )+ }+)++MemoizedMessage.displayName = 'MemoizedMessage'diff --git a/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx b/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsxindex 4d98316feb8..f6b5d3a9868 100644--- a/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx@@ -305,7 +305,7 @@ export const MarkdownPre = ({}return (- <div className="w-auto overflow-x-hidden not-prose">+ <div className="w-auto overflow-x-hidden not-prose my-4 ">{language === 'edge' ? (<EdgeFunctionBlocklabel={title}@@ -346,7 +346,7 @@ export const MarkdownPre = ({value={cleanContent}language={language as CodeBlockLang}className={cn(- 'max-h-96 max-w-none block border rounded !bg-transparent !py-3 !px-3.5 prose dark:prose-dark text-foreground',+ 'my-4 max-h-96 max-w-none block border rounded !bg-transparent !py-3 !px-3.5 prose dark:prose-dark text-foreground','[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap [&>code]:block [&>code>span]:text-foreground')}/>diff --git a/apps/studio/components/ui/AIAssistantPanel/elements/Conversation.tsx b/apps/studio/components/ui/AIAssistantPanel/elements/Conversation.tsxnew file mode 100644index 00000000000..ff375a7dde5--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/elements/Conversation.tsx@@ -0,0 +1,49 @@+import { ArrowDownIcon } from 'lucide-react'+import type { ComponentProps } from 'react'+import { useCallback } from 'react'+import { StickToBottom, useStickToBottomContext } from 'use-stick-to-bottom'++import { Button, cn } from 'ui'++type ConversationProps = ComponentProps<typeof StickToBottom>+type ConversationContentProps = ComponentProps<typeof StickToBottom.Content>+type ConversationScrollButtonProps = ComponentProps<typeof Button>++export const Conversation = ({ className, ...props }: ConversationProps) => (+ <StickToBottom+ className={cn('relative flex-1 overflow-y-auto', className)}+ initial="smooth"+ resize="smooth"+ role="log"+ {...props}+ />+)++export const ConversationContent = ({ className, ...props }: ConversationContentProps) => (+ <StickToBottom.Content className={cn('p-4', className)} {...props} />+)++export const ConversationScrollButton = ({+ className,+ ...props+}: ConversationScrollButtonProps) => {+ const { isAtBottom, scrollToBottom } = useStickToBottomContext()++ const handleScrollToBottom = useCallback(() => {+ scrollToBottom()+ }, [scrollToBottom])++ return (+ !isAtBottom && (+ <Button+ className={cn('absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full', className)}+ onClick={handleScrollToBottom}+ size="tiny"+ type="default"+ {...props}+ >+ <ArrowDownIcon className="size-4" />+ </Button>+ )+ )+}diff --git a/apps/studio/components/ui/AIAssistantPanel/elements/Reasoning.tsx b/apps/studio/components/ui/AIAssistantPanel/elements/Reasoning.tsxnew file mode 100644index 00000000000..2144519bd1a--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/elements/Reasoning.tsx@@ -0,0 +1,51 @@+import { BrainIcon, ChevronDownIcon, Loader2 } from 'lucide-react'+import type { ComponentProps } from 'react'+import { memo } from 'react'+import ReactMarkdown from 'react-markdown'++import {+ cn,+ Collapsible,+ CollapsibleContent_Shadcn_ as CollapsibleContent,+ CollapsibleTrigger_Shadcn_ as CollapsibleTrigger,+} from 'ui'++type ReasoningProps = Omit<ComponentProps<typeof Collapsible>, 'children'> & {+ isStreaming?: boolean+ children: string+}++export const Reasoning = memo(({ className, isStreaming, children, ...props }: ReasoningProps) => (+ <Collapsible+ className={cn('not-prose border rounded-md border-muted', className)}+ defaultOpen={false}+ {...props}+ >+ <CollapsibleTrigger+ className={cn(+ 'flex items-center gap-2 text-foreground-lighter heading-meta px-3 py-2 w-full'+ )}+ >+ {isStreaming ? (+ <>+ <Loader2 strokeWidth={1.5} size={12} className="animate-spin" />+ <p>Thinking...</p>+ </>+ ) : (+ <>+ <BrainIcon strokeWidth={1.5} size={12} className="text-foreground-muted" />+ <p>Reasoned</p>+ </>+ )}+ <ChevronDownIcon strokeWidth={1.5} size={12} className="text-foreground-muted" />+ </CollapsibleTrigger>++ <CollapsibleContent+ className={cn('p-5 pt-2 text-xs leading-normal', 'max-h-64 overflow-y-auto')}+ >+ <ReactMarkdown>{children}</ReactMarkdown>+ </CollapsibleContent>+ </Collapsible>+))++Reasoning.displayName = 'Reasoning'diff --git a/apps/studio/lib/ai/prompts.ts b/apps/studio/lib/ai/prompts.tsindex 83b4aa10235..0a9176265b5 100644--- a/apps/studio/lib/ai/prompts.ts+++ b/apps/studio/lib/ai/prompts.ts@@ -842,22 +842,22 @@ You are a Supabase Postgres expert. Your goals are to help people manage their Sexport const CHAT_PROMPT = `# Response Style:- Be **direct and concise**. Focus on delivering the essential information.+ - Prefer lists over tables to display information+ - Limit use of emojis# Response Format-## CommonMark Markdown - mandatory--Always format your entire response in CommonMark. Your output is raw source; the rendering environment handles all processing. Details:- - Output must be valid CommonMark, supporting UTF-8. Use rich Markdown naturally and fluently: headings, lists (hyphen bullets), blockquotes, *italics*, **bold**- - Structure:- - Use a clear heading hierarchy (H1–H4) without skipping levels when useful.- - Do not use tables to display information- - Use bold text only to highlight important information.+## Markdown+ - Conform to CommonMark specification+ - Use a clear heading hierarchy (H1–H4) without skipping levels when useful.+ - Use bold text only to highlight important information+ - **Never** use tables to display information# Rename Chat**:- **Always call \`rename_chat\` before you respond at the start of the conversation** with a 2-4 word descriptive name. Examples: "User Authentication Setup", "Sales Data Analysis", "Product Table Creation"**.# Query rendering**:- **Always call the \`display_query\` tool to render sql queries. You do not need to write the query yourself. ie Do not use markdown code blocks.**+ - Before using display_query, explain the query in natural language.- READ ONLY: Use \`display_query\` with \`sql\` and \`label\`. If results may be visualized, also provide \`view\` ('table' or 'chart'), \`xAxis\`, and \`yAxis\`.- The user can run the query from the UI when you use display_query.- Use \`display_query\` in the natural flow of the conversation. **Do not output the query in markdown**@@ -866,7 +866,12 @@ Always format your entire response in CommonMark. Your output is raw source; the# Edge functions**:- **Always use \`display_edge_function\` to render Edge Function code instead of markdown code blocks**- - Use \`display_edge_function\` with the function \`name\` and TypeScript code to propose an Edge Function. Only use this to display Edge Function code (not logs or other content). The user can deploy the function from the UI when you use display_edge_function.+ - Use \`display_edge_function\` with the function \`name\` and TypeScript code to propose an Edge Function. Only use this to display Edge Function code (not logs or other content).+ - The user can deploy the function directly from the dashboard when you use display_edge_function++# Checking health+ - Use \`get_advisors\` to check for any issues with the project.+ - If the user does not have access to the \`get_advisors\` tool, they will have to use the Supabase dashboard to check for issues# Checking health- Use \`get_advisors\` to check for any issues with the project.diff --git a/apps/studio/package.json b/apps/studio/package.jsonindex 76f867c8c4b..33def8d179e 100644--- a/apps/studio/package.json+++ b/apps/studio/package.json@@ -138,6 +138,7 @@"ui": "workspace:*","ui-patterns": "workspace:*","use-debounce": "^7.0.1",+ "use-stick-to-bottom": "^1.1.1","uuid": "^9.0.1","valtio": "catalog:","yup": "^1.4.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 480f03fee11..d3056b2a9d9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1038,6 +1038,9 @@ importers:use-debounce:specifier: ^7.0.1version: 7.0.1([email protected])+ use-stick-to-bottom:+ specifier: ^1.1.1+ version: 1.1.1([email protected])uuid:specifier: ^9.0.1version: 9.0.1@@ -17428,6 +17431,11 @@ packages:'@types/react':optional: true+ resolution: {integrity: sha512-JkDp0b0tSmv7HQOOpL1hT7t7QaoUBXkq045WWWOFDTlLGRzgIIyW7vyzOIJzY7L2XVIG7j1yUxeDj2LHm9Vwng==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+resolution: {integrity: sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==}peerDependencies:@@ -37875,6 +37883,10 @@ snapshots:optionalDependencies:'@types/react': 18.3.3+ dependencies:+ react: 18.3.1+dependencies:react: 18.3.1