Skip to content

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

AI UI refine and renaming (#36819)

Saxon Fletcher94c45c286326
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx
index 6ef65ea048f..e59ef503ed1 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx
@@ -128,9 +128,18 @@ const PolicyRow = ({
suggestions: {
title: `I can help you make a change to the policy "${policy.name}" in the ${policy.schema} schema on the ${policy.table} table, here are a few example prompts to get you started:`,
prompts: [
- 'Tell me how I can improve this policy...',
- 'Duplicate this policy for another table...',
- 'Add extra conditions to this policy...',
+ {
+ label: 'Improve Policy',
+ description: 'Tell me how I can improve this policy...',
+ },
+ {
+ label: 'Duplicate Policy',
+ description: 'Duplicate this policy for another table...',
+ },
+ {
+ label: 'Add Conditions',
+ description: 'Add extra conditions to this policy...',
+ },
],
},
})
diff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
index 7fe3674f943..f5de47e02cb 100644
--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
@@ -139,9 +139,19 @@ const FunctionList = ({
title:
'I can help you make a change to this function, here are a few example prompts to get you started:',
prompts: [
- 'Rename this function to ...',
- 'Modify this function so that it ...',
- 'Add a trigger for this function that calls it when ...',
+ {
+ label: 'Rename Function',
+ description: 'Rename this function to ...',
+ },
+ {
+ label: 'Modify Function',
+ description: 'Modify this function so that it ...',
+ },
+ {
+ label: 'Add Trigger',
+ description:
+ 'Add a trigger for this function that calls it when ...',
+ },
],
},
sqlSnippets: [x.complete_statement],
diff --git a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx
index 35517b03e3d..621bc0b353b 100644
--- a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx
+++ b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx
@@ -164,9 +164,19 @@ const TriggerList = ({
title:
'I can help you make a change to this trigger, here are a few example prompts to get you started:',
prompts: [
- 'Rename this trigger to ...',
- 'Change the events this trigger responds to ...',
- 'Modify this trigger to run after instead of before ...',
+ {
+ label: 'Rename Trigger',
+ description: 'Rename this trigger to ...',
+ },
+ {
+ label: 'Change Events',
+ description: 'Change the events this trigger responds to ...',
+ },
+ {
+ label: 'Modify Timing',
+ description:
+ 'Modify this trigger to run after instead of before ...',
+ },
],
},
sqlSnippets: [sql],
diff --git a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx
index 8a5e5074b2c..03cf7348cd3 100644
--- a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx
+++ b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx
@@ -151,9 +151,19 @@ const TriggersList = ({
title:
'I can help you create a new trigger, here are a few example prompts to get you started:',
prompts: [
- 'Create a trigger that logs changes to the users table',
- 'Create a trigger that updates updated_at timestamp',
- 'Create a trigger that validates email format before insert',
+ {
+ label: 'Log Changes',
+ description: 'Create a trigger that logs changes to the users table',
+ },
+ {
+ label: 'Update Timestamp',
+ description: 'Create a trigger that updates updated_at timestamp',
+ },
+ {
+ label: 'Validate Email',
+ description:
+ 'Create a trigger that validates email format before insert',
+ },
],
},
})
diff --git a/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionButton.tsx b/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionButton.tsx
index 2fb39567cd2..6517056113f 100644
--- a/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionButton.tsx
+++ b/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionButton.tsx
@@ -93,9 +93,19 @@ export const DeployEdgeFunctionButton = () => {
title:
'I can help you create a new edge function. Here are a few example prompts to get you started:',
prompts: [
- 'Create a new edge function that processes payments with Stripe',
- 'Create a new edge function that sends emails with Resend',
- 'Create a new edge function that generates PDFs from HTML templates',
+ {
+ label: 'Stripe Payments',
+ description: 'Create a new edge function that processes payments with Stripe',
+ },
+ {
+ label: 'Email with Resend',
+ description: 'Create a new edge function that sends emails with Resend',
+ },
+ {
+ label: 'PDF Generator',
+ description:
+ 'Create a new edge function that generates PDFs from HTML templates',
+ },
],
},
})
diff --git a/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx b/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx
index f13adcdacbe..92a46f598da 100644
--- a/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx
+++ b/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx
@@ -90,9 +90,20 @@ export const FunctionsEmptyState = () => {
title:
'I can help you create a new edge function. Here are a few example prompts to get you started:',
prompts: [
- 'Create a new edge function that processes payments with Stripe',
- 'Create a new edge function that sends emails with Resend',
- 'Create a new edge function that generates PDFs from HTML templates',
+ {
+ label: 'Stripe Payments',
+ description:
+ 'Create a new edge function that processes payments with Stripe',
+ },
+ {
+ label: 'Email with Resend',
+ description: 'Create a new edge function that sends emails with Resend',
+ },
+ {
+ label: 'PDF Generator',
+ description:
+ 'Create a new edge function that generates PDFs from HTML templates',
+ },
],
},
})
diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/HelpPopover.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/HelpPopover.tsx
index 83dc5e81d90..0860e5ee1d2 100644
--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/HelpPopover.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/HelpPopover.tsx
@@ -77,9 +77,18 @@ export const HelpPopover = () => {
title:
'I can help you with your project, here are some example prompts to get you started:',
prompts: [
- 'Summarise my database health and performance',
- 'View and debug my edge function logs',
- 'Implement row level security for my tables',
+ {
+ label: 'Database Health',
+ description: 'Summarise my database health and performance',
+ },
+ {
+ label: 'Debug Logs',
+ description: 'View and debug my edge function logs',
+ },
+ {
+ label: 'RLS Setup',
+ description: 'Implement row level security for my tables',
+ },
],
},
})
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
index 72383a6e61f..c54c899f46c 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
@@ -1,14 +1,13 @@
-import type { Message as MessageType } from 'ai/react'
-import { useChat } from 'ai/react'
+import type { Message as MessageType } from '@ai-sdk/react'
+import { useChat } from '@ai-sdk/react'
import { AnimatePresence, motion } from 'framer-motion'
-import { ArrowDown, FileText, Info, RefreshCw, X } from 'lucide-react'
+import { ArrowDown, FileText, Info, RefreshCw, Settings, X } from 'lucide-react'
import { useRouter } from 'next/router'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { LOCAL_STORAGE_KEYS } from 'common'
import { useParams, useSearchParamsShallow } from 'common/hooks'
import { Markdown } from 'components/interfaces/Markdown'
-import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.queries'
import { useCheckOpenAIKeyQuery } from 'data/ai/check-api-key-query'
import { constructHeaders } from 'data/fetchers'
import { useTablesQuery } from 'data/tables/tables-query'
@@ -22,18 +21,9 @@ import { BASE_PATH, IS_PLATFORM } from 'lib/constants'
import uuidv4 from 'lib/uuid'
import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
-import {
- AiIconAnimation,
- Button,
- cn,
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from 'ui'
+import { AiIconAnimation, Button, cn } from 'ui'
import { Admonition, AssistantChatForm, GenericSkeletonLoader } from 'ui-patterns'
import { ButtonTooltip } from '../ButtonTooltip'
-import { DotGrid } from '../DotGrid'
import { ErrorBoundary } from '../ErrorBoundary'
import { onErrorChat } from './AIAssistant.utils'
import { AIAssistantChatSelector } from './AIAssistantChatSelector'
@@ -42,10 +32,7 @@ import { AIOptInModal } from './AIOptInModal'
import { CollapsibleCodeBlock } from './CollapsibleCodeBlock'
import { Message } from './Message'
import { useAutoScroll } from './hooks'
-
-type ExtendedMessage = MessageType & {
- results?: any[]
-}
+import type { AssistantMessageType } from 'state/ai-assistant-state'
const MemoizedMessage = memo(
({
@@ -142,16 +129,17 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
const { mutate: sendEvent } = useSendEventMutation()
// Handle completion of the assistant's response
- const handleChatFinish = useCallback((message: MessageType) => {
- // If we have a user message stored in the ref, save both messages
- if (lastUserMessageRef.current) {
- snap.saveMessage([lastUserMessageRef.current, message])
- lastUserMessageRef.current = null
- } else {
- // Otherwise just save the assistant message
- snap.saveMessage(message)
- }
- }, [])
+ const handleChatFinish = useCallback(
+ (message: MessageType, options: { finishReason: string }) => {
+ if (lastUserMessageRef.current) {
+ snap.saveMessage([lastUserMessageRef.current, message])
+ lastUserMessageRef.current = null
+ } else {
+ snap.saveMessage(message)
+ }
+ },
+ [snap]
+ )
// TODO(refactor): This useChat hook should be moved down into each chat session.
// That way we won't have to disable switching chats while the chat is loading,
@@ -170,6 +158,16 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
// [Alaister] typecast is needed here because valtio returns readonly arrays
// and useChat expects a mutable array
initialMessages: snap.activeChat?.messages as unknown as MessageType[] | undefined,
+ async onToolCall({ toolCall }) {
+ if (toolCall.toolName === 'rename_chat') {
+ const { newName } = toolCall.args as { newName: string }
+ if (snap.activeChatId && newName?.trim()) {
+ snap.renameChat(snap.activeChatId, newName.trim())
+ return `Chat renamed to "${newName.trim()}"`
+ }
+ return 'Failed to rename chat: Invalid chat or name'
+ }
+ },
experimental_prepareRequestBody: ({ messages }) => {
// [Joshen] Specifically limiting the chat history that get's sent to reduce the
// size of the context that goes into the model. This should always be an odd number
@@ -180,8 +178,8 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
// Filter out results from messages before sending to the model
const cleanedMessages = slicedMessages.map((message) => {
- const cleanedMessage = { ...message } as ExtendedMessage
- if (message.role === 'assistant' && (message as ExtendedMessage).results) {
+ const cleanedMessage = { ...message } as AssistantMessageType
+ if (message.role === 'assistant' && (message as AssistantMessageType).results) {
delete cleanedMessage.results
}
return cleanedMessage
@@ -244,9 +242,26 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
)
const hasMessages = chatMessages.length > 0
+ const isShowingOnboarding = !hasMessages && isApiKeySet
const sendMessageToAssistant = (content: string) => {
- const payload = { role: 'user', createdAt: new Date(), content, id: uuidv4() } as MessageType
+ let finalContent = content
+
+ // Handle SQL snippets based on opt-in level
+ if (aiOptInLevel !== 'disabled') {
+ const sqlSnippetsString =
+ snap.sqlSnippets?.map((snippet: string) => '```sql\n' + snippet + '\n```').join('\n') || ''
+ finalContent = [content, sqlSnippetsString].filter(Boolean).join('\n\n')
+ } else {
+ snap.setSqlSnippets([])
+ }
+
+ const payload = {
+ role: 'user',
+ createdAt: new Date(),
+ content: finalContent,
+ id: uuidv4(),
+ } as MessageType
snap.clearSqlSnippets()
// Store the user message in the ref before appending
@@ -329,56 +344,56 @@ 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 flex items-center bg gap-x-3 pl-5 pr-4 h-[46px]">
- <AiIconAnimation allowHoverEffect />
-
- <div className="text-sm flex-1 flex items-center gap-x-2">
- Assistant
- <Tooltip>
- <TooltipTrigger asChild>
- <Info size={14} className="text-foreground-light" />
- </TooltipTrigger>
- <TooltipContent className="w-80">
- The Assistant is in Alpha and your prompts might be rate limited.{' '}
- {aiOptInLevel === 'schema_and_log_and_data' &&
- 'Schema, logs, and query data are being shared to improve Assistant responses.'}
- {aiOptInLevel === 'schema_and_log' &&
- 'Schema and logs are being shared to improve Assistant responses.'}
- {aiOptInLevel === 'schema' &&
- 'Only schema metadata is being shared to improve Assistant responses.'}
- {aiOptInLevel === 'disabled' &&
- 'Project metadata is not being shared. Opt in to improve Assistant responses.'}
- </TooltipContent>
- </Tooltip>
+ <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">
- <Tooltip>
- <TooltipTrigger>
- <p
- title={currentChat}
- className="text-xs text-foreground-light truncate max-w-[145px] 2xl:max-w-full"
- >
- {currentChat}
- </p>
- </TooltipTrigger>
- <TooltipContent side="bottom">Current chat: {currentChat}</TooltipContent>
- </Tooltip>
- <div className="flex items-center gap-x-2">
- <AIAssistantChatSelector disabled={isChatLoading} />
+ <div className="flex items-center">
<ButtonTooltip
- type="default"
+ type="text"
+ size="tiny"
+ icon={<Settings strokeWidth={1.5} size={14} />}
+ 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={<RefreshCw size={14} />}
+ icon={<RefreshCw strokeWidth={1.5} size={14} />}
onClick={handleClearMessages}
className="h-7 w-7 p-0"
disabled={isChatLoading}
tooltip={{ content: { side: 'bottom', text: 'Clear messages' } }}
/>
<ButtonTooltip
- type="default"
+ type="text"
className="w-7 h-7"
onClick={snap.closeAssistant}
- icon={<X />}
+ icon={<X strokeWidth={1.5} size={14} />}
tooltip={{ content: { side: 'bottom', text: 'Close assistant' } }}
/>
</div>
@@ -421,13 +436,8 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
</Admonition>
)}
</div>
- {!hasMessages && (
- <div className="h-48 flex-0 m-8">
- <DotGrid rows={10} columns={10} count={33} />
- </div>
- )}
{hasMessages ? (
- <div className="w-full p-5">
+ <div className="w-full px-7 py-8 space-y-6">
{renderedMessages}
<AnimatePresence>
{isChatLoading && (
@@ -465,94 +475,27 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
)}
</AnimatePresence>
</div>
- ) : snap.suggestions ? (
- <div className="w-full h-full px-8 py-0 flex flex-col flex-1 justify-end">
- <h3 className="text-foreground-light font-mono text-sm uppercase mb-3">
- Suggestions
- </h3>
- {snap.suggestions.title && <p>{snap.suggestions.title}</p>}
- <div className="-mx-3 mt-4 mb-12">
- {snap.suggestions?.prompts?.map((prompt: string, idx: number) => (
- <Button
- key={`suggestion-${idx}`}
- size="small"
- icon={<FileText strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() => {
- setValue(prompt)
- if (inputRef.current && snap.initialInput) {
- inputRef.current.focus()
- inputRef.current.setSelectionRange(
- snap.initialInput.length,
- snap.initialInput.length
- )
- }
- }}
- >
- {prompt}
- </Button>
- ))}
- </div>
- </div>
) : isLoadingTables && isApiKeySet ? (
- <div className="w-full h-full flex-1 flex flex-col justify-end items-start p-5">
- {/* [Joshen] We could try play around with a custom loader for the assistant here */}
- <GenericSkeletonLoader className="w-4/5" />
- </div>
- ) : (tables ?? [])?.length > 0 ? (
- <AIOnboarding onSendMessage={sendMessageToAssistant} />
- ) : isApiKeySet ? (
- <div className="w-full flex flex-col justify-end flex-1 h-full p-5">
- <h2 className="text-base mb-2">Welcome to Supabase!</h2>
- <p className="text-sm text-foreground-lighter mb-6">
- This is the Supabase assistant which will help you create, debug and modify tables,
- policies, functions and more. You can even use it to query your data using just your
- words. It looks like we have a blank canvas though, so what are you looking to
- build? Here are some ideas.
- </p>
- <div className="flex flex-wrap gap-2">
- <Button
- onClick={() => setValue('Generate a database schema for ...')}
- className="rounded-full"
- >
- Generate a ...
- </Button>
- {SQL_TEMPLATES.filter((t) => t.type === 'quickstart').map((qs) => (
- <TooltipProvider key={qs.title}>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="outline"
- className="rounded-full"
- onClick={() => {
- setMessages([
- {
- id: uuidv4(),
- role: 'user',
- createdAt: new Date(Date.now() - 3000),
- content: qs.description,
- },
- {
- id: uuidv4(),
- role: 'assistant',
- createdAt: new Date(),
- content: `Sure! I can help you with that. Here is a starting point you can run directly or customize further. Would you like to make any changes? \n\n\`\`\`sql\n-- props: {"title": "${qs.title}"}\n${qs.sql}\n\`\`\``,
- },
- ])
- }}
- >
- {qs.title}
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>{qs.description}</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ))}
- </div>
+ <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 string[] | 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>
@@ -565,109 +508,102 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
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" />
- </motion.div>
- <motion.div
- className="absolute bottom-20 left-1/2 -translate-x-1/2"
- 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>
+ <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>
- <div className="p-5 pt-0 z-20 relative">
- {snap.sqlSnippets && snap.sqlSnippets.length > 0 && (
- <div className="mb-2">
- {snap.sqlSnippets.map((snippet: string, index: number) => (
- <CollapsibleCodeBlock
- key={index}
- hideLineNumbers
- value={snippet}
- onRemove={() => {
- const newSnippets = [...(snap.sqlSnippets ?? [])]
- newSnippets.splice(index, 1)
- snap.setSqlSnippets(newSnippets)
- }}
- className="text-xs"
- />
- ))}
- </div>
- )}
- {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.'
- }
- />
- }
- />
- )}
+ {!isShowingOnboarding && (
+ <div className="px-3 pb-3 z-20 relative">
+ {snap.sqlSnippets && snap.sqlSnippets.length > 0 && (
+ <div className="mb-0 mx-4">
+ {snap.sqlSnippets.map((snippet: string, index: number) => (
+ <CollapsibleCodeBlock
+ key={index}
+ hideLineNumbers
+ value={snippet}
+ onRemove={() => {
+ const newSnippets = [...(snap.sqlSnippets ?? [])]
+ newSnippets.splice(index, 1)
+ snap.setSqlSnippets(newSnippets)
+ }}
+ className="text-xs rounded-b-none border-b-0"
+ />
+ ))}
+ </div>
+ )}
+ {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 [&>textarea]:text-base [&>textarea]:md:text-sm [&>textarea]:border-1 [&>textarea]:rounded-md [&>textarea]:!outline-none [&>textarea]:!ring-offset-0 [&>textarea]:!ring-0'
+ {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.'
+ }
+ />
+ }
+ />
)}
- loading={isChatLoading}
- disabled={!isApiKeySet || disablePrompts || isChatLoading}
- placeholder={
- hasMessages
- ? 'Reply to the assistant...'
- : (snap.sqlSnippets ?? [])?.length > 0
- ? 'Ask a question or make a change...'
- : 'Chat to Postgres...'
- }
- value={value}
- onValueChange={(e) => setValue(e.target.value)}
- onSubmit={(event) => {
- event.preventDefault()
- if (aiOptInLevel !== 'disabled') {
- const sqlSnippetsString =
- snap.sqlSnippets
- ?.map((snippet: string) => '```sql\n' + snippet + '\n```')
- .join('\n') || ''
- const valueWithSnippets = [value, sqlSnippetsString].filter(Boolean).join('\n\n')
- sendMessageToAssistant(valueWithSnippets)
- scrollToEnd()
- } else {
+
+ <AssistantChatForm
+ textAreaRef={inputRef}
+ className={cn(
+ 'z-20 [&>textarea]:text-base [&>textarea]:md:text-sm [&>textarea]:border-1 [&>textarea]:rounded-md [&>textarea]:!outline-none [&>textarea]:!ring-offset-0 [&>textarea]:!ring-0'
+ )}
+ loading={isChatLoading}
+ disabled={!isApiKeySet || disablePrompts || isChatLoading}
+ placeholder={
+ hasMessages
+ ? 'Ask a follow up question...'
+ : (snap.sqlSnippets ?? [])?.length > 0
+ ? 'Ask a question or make a change...'
+ : 'Chat to Postgres...'
+ }
+ value={value}
+ autoFocus
+ onValueChange={(e) => setValue(e.target.value)}
+ onSubmit={(event) => {
+ event.preventDefault()
sendMessageToAssistant(value)
- snap.setSqlSnippets([])
scrollToEnd()
- }
- }}
- />
- </div>
+ }}
+ />
+ </div>
+ )}
</div>
<AIOptInModal
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistantChatSelector.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistantChatSelector.tsx
index 1f332d3b1e2..903fb016f6f 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistantChatSelector.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistantChatSelector.tsx
@@ -1,4 +1,4 @@
-import { Check, Edit, MessageSquare, Plus, Trash, X } from 'lucide-react'
+import { Check, ChevronDown, Edit, MessageSquare, Plus, Trash, X } from 'lucide-react'
import { useState } from 'react'
import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
@@ -30,6 +30,7 @@ export const AIAssistantChatSelector = ({
disabled = false,
}: AIAssistantChatSelectorProps) => {
const snap = useAiAssistantStateSnapshot()
+ const currentChat = snap.activeChat?.name
const [chatSelectorOpen, setChatSelectorOpen] = useState(false)
const [editingChatId, setEditingChatId] = useState<string | null>(null)
@@ -91,15 +92,16 @@ export const AIAssistantChatSelector = ({
return (
<Popover_Shadcn_ open={chatSelectorOpen} onOpenChange={setChatSelectorOpen}>
<PopoverTrigger_Shadcn_ asChild>
- <ButtonTooltip
- type="default"
+ <Button
+ type="text"
size="tiny"
- icon={<MessageSquare size={14} />}
- className={cn('h-7 w-7', className)}
- tooltip={{ content: { side: 'bottom', text: 'View chats' } }}
- />
+ iconRight={<ChevronDown size={14} />}
+ className="max-w-64 truncate"
+ >
+ {currentChat}
+ </Button>
</PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ className="w-[250px] p-0" align="end">
+ <PopoverContent_Shadcn_ className="w-[250px] p-0" align="start">
<Command_Shadcn_>
<CommandInput_Shadcn_ placeholder="Search chats..." />
<CommandList_Shadcn_>
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx b/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx
index 8caf871ea3b..d6b7aa3617d 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsx
@@ -1,238 +1,167 @@
import { motion } from 'framer-motion'
-import { FileText, MessageCircleMore, WandSparkles } from 'lucide-react'
+import { Code, FileText, Heart, MessageCircleMore, Shield, WandSparkles } from 'lucide-react'
+import { useRef } from 'react'
-import { Button } from 'ui'
-import {
- InnerSideMenuCollapsible,
- InnerSideMenuCollapsibleContent,
- InnerSideMenuCollapsibleTrigger,
-} from 'ui-patterns/InnerSideMenu'
+import { Button, cn } from 'ui'
+import { AssistantChatForm } from 'ui-patterns'
+import { CollapsibleCodeBlock } from './CollapsibleCodeBlock'
interface AIOnboardingProps {
- onSendMessage: (message: string) => void
-}
-
-export const AIOnboarding = ({ onSendMessage }: AIOnboardingProps) => {
- const sendMessageToAssistant = (message: string) => {
- onSendMessage(message)
+ onMessageSend: (message: string) => void
+ sqlSnippets?: string[]
+ onRemoveSnippet?: (index: number) => void
+ suggestions?: {
+ title?: string
+ prompts?: { label: string; description: string }[]
}
+ value: string
+ onValueChange: (value: string) => void
+}
- return (
- <div className="w-full p-5 flex flex-col grow shrink-0 justify-end overflow-auto">
- <div className="shrink-0">
- <motion.div
- initial={{ x: -10, opacity: 0 }}
- animate={{ x: 0, opacity: 1 }}
- transition={{ delay: 0 }}
- >
- <p className="text-base mb-2">How can I assist you?</p>
- <p className="text-sm text-foreground-lighter mb-4">
- I can help you build and manage your database by writing SQL or supabase-js, set up
- policies, functions or triggers, and query your data - ask me anything.
- </p>
- </motion.div>
- <motion.div>
- <motion.div
- initial={{ x: -10, opacity: 0 }}
- animate={{ x: 0, opacity: 1 }}
- transition={{ delay: 0 }}
- >
- <InnerSideMenuCollapsible className="border-b border-muted py-3">
- <InnerSideMenuCollapsibleTrigger className="px-0 -mx-3" title="Tables" />
- <InnerSideMenuCollapsibleContent>
- <div className="mt-3 mb-1 space-y-1">
- <Button
- size="small"
- icon={<WandSparkles strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() =>
- sendMessageToAssistant(
- "Create a table of countries and a table of cities. The cities table should have a country column that's a foreign key to the countries table."
- )
- }
- >
- Create a new table
- </Button>
-
- <Button
- size="small"
- icon={<FileText strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() =>
- sendMessageToAssistant(
- 'Give me a list of new users from the auth.users table who signed up in the past week'
- )
- }
- >
- Query your data
- </Button>
-
- <Button
- size="small"
- icon={<MessageCircleMore strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() =>
- sendMessageToAssistant(
- 'Give me a chart showing the number of new sign ups in the auth.users table per day over the last week'
- )
- }
- >
- Chart your data
- </Button>
- </div>
- </InnerSideMenuCollapsibleContent>
- </InnerSideMenuCollapsible>
- </motion.div>
-
- <motion.div
- initial={{ x: -10, opacity: 0 }}
- animate={{ x: 0, opacity: 1 }}
- transition={{ delay: 0.1 }}
- >
- <InnerSideMenuCollapsible className="border-b border-muted py-3">
- <InnerSideMenuCollapsibleTrigger className="px-0 -mx-3" title="RLS Policies" />
- <InnerSideMenuCollapsibleContent>
- <div className="mt-3 mb-1 space-y-1">
- <Button
- size="small"
- icon={<WandSparkles strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() =>
- sendMessageToAssistant(
- 'Suggest some database RLS policies I can add to my public schema'
- )
- }
- >
- Suggest RLS policies
- </Button>
-
- <Button
- size="small"
- icon={<FileText strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() =>
- sendMessageToAssistant('Generate some examples of database RLS policies')
- }
- >
- Examples of RLS policies
- </Button>
-
- <Button
- size="small"
- icon={<MessageCircleMore strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() => sendMessageToAssistant(`What are database RLS policies`)}
- >
- What are RLS policies?
- </Button>
- </div>
- </InnerSideMenuCollapsibleContent>
- </InnerSideMenuCollapsible>
- </motion.div>
+export const AIOnboarding = ({
+ onMessageSend,
+ sqlSnippets,
+ onRemoveSnippet,
+ suggestions,
+ value,
+ onValueChange,
+}: AIOnboardingProps) => {
+ const inputRef = useRef<HTMLTextAreaElement>(null)
- <motion.div
- initial={{ x: -10, opacity: 0 }}
- animate={{ x: 0, opacity: 1 }}
- transition={{ delay: 0.2 }}
- >
- <InnerSideMenuCollapsible className="border-b border-muted py-3">
- <InnerSideMenuCollapsibleTrigger className="px-0 -mx-3" title="Functions" />
- <InnerSideMenuCollapsibleContent>
- <div className="mt-3 mb-1 space-y-1">
- <Button
- size="small"
- icon={<WandSparkles strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() =>
- sendMessageToAssistant(
- 'Suggest some database functions I can add to my public schema'
- )
- }
- >
- Suggest database functions
- </Button>
+ const defaultPrompts = [
+ {
+ title: 'Create a back-end',
+ prompt:
+ 'Create a messaging app with users, messages, and an edge function that uses OpenAI to summarize message threads.',
+ icon: <WandSparkles strokeWidth={1.25} size={14} className="!w-4 !h-4" />,
+ },
+ {
+ title: 'Health check',
+ prompt: 'Can you check if my database and edge functions are healthy?',
+ icon: <Heart strokeWidth={1.25} size={14} className="!w-4 !h-4" />,
+ },
+ {
+ title: 'Query your data',
+ prompt:
+ 'Give me a list of new users from the auth.users table who signed up in the past week',
+ icon: <FileText strokeWidth={1.25} size={14} className="!w-4 !h-4" />,
+ },
+ {
+ title: 'Set up RLS policies',
+ prompt: 'Create RLS policies to ensure users can only access their own data',
+ icon: <Shield strokeWidth={1.25} size={14} className="!w-4 !h-4" />,
+ },
+ {
+ title: 'Create a function',
+ prompt: 'Create an edge function that summarises the contents of a table row using OpenAI',
+ icon: <Code strokeWidth={1.25} size={14} className="!w-4 !h-4" />,
+ },
+ {
+ title: 'Generate sample data',
+ prompt: 'Generate sample data for a blog with users, posts, and comments tables',
+ icon: <FileText strokeWidth={1.25} size={14} className="!w-4 !h-4" />,
+ },
+ ]
- <Button
- size="small"
- icon={<FileText strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() =>
- sendMessageToAssistant('Generate some examples of database functions')
- }
- >
- Examples of database functions
- </Button>
+ const codeSnippetPrompts = [
+ {
+ title: 'Explain code',
+ prompt: 'Explain what this code does and how it works',
+ icon: <FileText strokeWidth={1.25} size={14} className="!w-4 !h-4" />,
+ },
+ {
+ title: 'Improve code',
+ prompt: 'How can I improve this code for better performance and readability?',
+ icon: <WandSparkles strokeWidth={1.25} size={14} className="!w-4 !h-4" />,
+ },
+ {
+ title: 'Debug issues',
+ prompt: 'Help me debug any potential issues with this code',
+ icon: <MessageCircleMore strokeWidth={1.25} size={14} className="!w-4 !h-4" />,
+ },
+ ]
- <Button
- size="small"
- icon={<MessageCircleMore strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() => sendMessageToAssistant('What are database functions')}
- >
- What are database functions?
- </Button>
- </div>
- </InnerSideMenuCollapsibleContent>
- </InnerSideMenuCollapsible>
- </motion.div>
+ // Use suggestions if available, otherwise use code-specific prompts if snippets exist, or default prompts
+ const prompts = suggestions?.prompts
+ ? suggestions.prompts.map((suggestion) => ({
+ title: suggestion.label,
+ prompt: suggestion.description,
+ icon: <FileText strokeWidth={1.25} size={14} className="!w-4 !h-4" />,
+ }))
+ : sqlSnippets && sqlSnippets.length > 0
+ ? codeSnippetPrompts
+ : defaultPrompts
- <motion.div
- initial={{ x: -10, opacity: 0 }}
- animate={{ x: 0, opacity: 1 }}
- transition={{ delay: 0.3 }}
- >
- <InnerSideMenuCollapsible className="py-3">
- <InnerSideMenuCollapsibleTrigger className="px-0 -mx-3" title="Triggers" />
- <InnerSideMenuCollapsibleContent>
- <div className="mt-3 mb-1 space-y-1">
- <Button
- size="small"
- icon={<WandSparkles strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() =>
- sendMessageToAssistant(
- 'Suggest some database triggers I can add to my public schema'
- )
- }
- >
- Suggest database Triggers
- </Button>
+ return (
+ <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>
- <Button
- size="small"
- icon={<FileText strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() =>
- sendMessageToAssistant(`Generate some examples of database triggers`)
- }
- >
- Examples of database triggers
- </Button>
+ <div className="w-full mb-6">
+ {sqlSnippets && sqlSnippets.length > 0 && (
+ <div className="mx-4">
+ {sqlSnippets.map((snippet: string, index: number) => (
+ <CollapsibleCodeBlock
+ key={index}
+ hideLineNumbers
+ value={snippet}
+ onRemove={() => onRemoveSnippet?.(index)}
+ className="text-xs rounded-b-none border-b-0 text-left"
+ />
+ ))}
+ </div>
+ )}
+ <AssistantChatForm
+ textAreaRef={inputRef}
+ className={cn(
+ 'z-20 [&>textarea]:text-base [&>textarea]:md:text-sm [&>textarea]:border-1 [&>textarea]:rounded-md [&>textarea]:!outline-none [&>textarea]:!ring-offset-0 [&>textarea]:!ring-0'
+ )}
+ loading={false}
+ disabled={false}
+ placeholder="Ask me anything..."
+ value={value}
+ onValueChange={(e) => onValueChange(e.target.value)}
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (value.trim()) {
+ onMessageSend(value)
+ onValueChange('')
+ }
+ }}
+ autoFocus
+ />
+ </div>
- <Button
- size="small"
- icon={<MessageCircleMore strokeWidth={1.5} size={16} />}
- type="text"
- className="w-full justify-start py-1 h-auto"
- onClick={() => sendMessageToAssistant('What are database triggers')}
- >
- What are database triggers?
- </Button>
- </div>
- </InnerSideMenuCollapsibleContent>
- </InnerSideMenuCollapsible>
- </motion.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"
+ icon={item.icon}
+ 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>
</div>
</div>
diff --git a/apps/studio/components/ui/AIAssistantPanel/CollapsibleCodeBlock.tsx b/apps/studio/components/ui/AIAssistantPanel/CollapsibleCodeBlock.tsx
index 92e83becffb..4386f5aa57f 100644
--- a/apps/studio/components/ui/AIAssistantPanel/CollapsibleCodeBlock.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/CollapsibleCodeBlock.tsx
@@ -1,49 +1,47 @@
-import { ChevronDown, ChevronUp, X } from 'lucide-react'
-import { useState } from 'react'
+import { Code, X } from 'lucide-react'
-import { Button, CodeBlock, CodeBlockProps, cn } from 'ui'
+import {
+ Button,
+ CodeBlock,
+ CodeBlockProps,
+ cn,
+ HoverCard_Shadcn_,
+ HoverCardContent_Shadcn_,
+ HoverCardTrigger_Shadcn_,
+} from 'ui'
interface CollapsibleCodeBlockProps extends CodeBlockProps {
onRemove?: () => void
}
export const CollapsibleCodeBlock = ({ onRemove, ...props }: CollapsibleCodeBlockProps) => {
- const [isExpanded, setIsExpanded] = useState(false)
-
const codeString = (props.value || props.children) as string
- const firstLine = isExpanded
- ? codeString
- : codeString?.substring(0, codeString.indexOf('\n')) || codeString
+ const firstLine = codeString?.substring(0, codeString.indexOf('\n')) || codeString
return (
<div className="relative">
<div
className={cn(
- 'flex items-center gap-1 p-1 bg-surface-100 border border-default w-full overflow-hidden',
- 'rounded-md'
+ 'flex items-center gap-1 px-2 py-1.5 bg-surface-100 border border-default w-full overflow-hidden',
+ 'rounded-md',
+ props.className
)}
>
- <Button
- type="text"
- size="tiny"
- className="w-6 h-6"
- onClick={() => setIsExpanded(!isExpanded)}
- icon={isExpanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
- />
- <div className="flex-1 shrink-1 overflow-auto [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
- <CodeBlock
- {...props}
- value={firstLine}
- hideCopy
- className={cn(
- 'block !bg-transparent max-h-32 max-w-full !py-0 !px-0 !border-t-0 prose dark:prose-dark border-0 text-foreground !rounded-none w-full text-wrap whitespace-pre-wrap',
- // 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 border-t-0 [&>code>span]:flex-wrap [&>code]:block [&>code>span]:text-foreground text-wrap whitespace-pre-wrap',
- props.className
- )}
- />
- </div>
+ <HoverCard_Shadcn_>
+ <HoverCardTrigger_Shadcn_ asChild>
+ <div className="flex flex-1 items-center gap-2 text-foreground-light px-2 hover:text-foreground cursor-pointer overflow-hidden">
+ <Code size={14} strokeWidth={1.5} />
+ <span className="text-xs font-mono flex-1 truncate pointer">{firstLine}...</span>
+ </div>
+ </HoverCardTrigger_Shadcn_>
+ <HoverCardContent_Shadcn_ className="w-96 max-h-96 overflow-auto p-0">
+ <CodeBlock
+ {...props}
+ value={codeString}
+ className={cn('text-xs font-mono border-none p-3')}
+ />
+ </HoverCardContent_Shadcn_>
+ </HoverCard_Shadcn_>
{onRemove && (
<Button
diff --git a/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsx b/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsx
index 8d1a94ec670..dc529d79a57 100644
--- a/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsx
@@ -105,7 +105,7 @@ export const DisplayBlockRenderer = ({
}
return (
- <div className="w-auto overflow-x-hidden">
+ <div className="display-block w-auto overflow-x-hidden !my-6">
<QueryBlock
label={label}
sql={sqlQuery}
diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.tsx
index 771626f60ea..5c9241c423e 100644
--- a/apps/studio/components/ui/AIAssistantPanel/Message.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/Message.tsx
@@ -1,10 +1,12 @@
import { Message as VercelMessage } from 'ai/react'
-import { User } from 'lucide-react'
+import { Loader2, User } from 'lucide-react'
import { createContext, PropsWithChildren, ReactNode, useMemo } from 'react'
import ReactMarkdown from 'react-markdown'
import { Components } from 'react-markdown/lib/ast-to-react'
import remarkGfm from 'remark-gfm'
+import { ProfileImage } from 'components/ui/ProfileImage'
+import { useProfile } from 'lib/profile'
import { cn, markdownComponents, WarningIcon } from 'ui'
import { EdgeFunctionBlock } from '../EdgeFunctionBlock/EdgeFunctionBlock'
import { DisplayBlockRenderer } from './DisplayBlockRenderer'
@@ -59,6 +61,7 @@ export const Message = function Message({
variant = 'default',
onResults,
}: PropsWithChildren<MessageProps>) {
+ const { profile } = useProfile()
const allMarkdownComponents: Partial<Components> = useMemo(
() => ({
...markdownComponents,
@@ -88,7 +91,7 @@ export const Message = function Message({
<MessageContext.Provider value={{ isLoading, readOnly }}>
<div
className={cn(
- 'mb-4 text-foreground-light text-sm',
+ 'text-foreground-light text-sm',
isUser && 'text-foreground',
variant === 'warning' && 'bg-warning-200'
)}
@@ -99,9 +102,11 @@ export const Message = function Message({
<div className="flex gap-4 w-auto overflow-hidden">
{isUser && (
- <figure className="w-5 h-5 shrink-0 bg-foreground rounded-full flex items-center justify-center">
- <User size={16} strokeWidth={1.5} className="text-background" />
- </figure>
+ <ProfileImage
+ alt={profile?.username}
+ src={profile?.profileImageUrl}
+ className="w-5 h-5 shrink-0 rounded-full"
+ />
)}
<div className="flex-1 min-w-0 space-y-2">
@@ -116,8 +121,8 @@ export const Message = function Message({
<ReactMarkdown
key={`${id}-part-${index}`}
className={cn(
- 'prose prose-sm max-w-full [&_h3]:text-base [&_ol>li]:pl-4 [&_ol>li]:my-0 [&_li>p]:mt-0 space-y-5 [&>*>code]:text-xs [&>*>*>code]:text-xs [&_li]:space-y-4',
- isUser && 'text-foreground font-semibold'
+ 'prose prose-sm 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',
+ isUser && 'text-foreground [&>p]:font-medium'
)}
remarkPlugins={[remarkGfm]}
components={allMarkdownComponents}
@@ -130,15 +135,15 @@ export const Message = function Message({
const { toolCallId, toolName, args, state } = part.toolInvocation
if (state === 'call' || state === 'partial-call') {
if (shownLoadingTools.has(toolName)) {
- // Already shown loading for this toolName in this step
return null
}
shownLoadingTools.add(toolName)
return (
<div
key={`${id}-tool-loading-${toolName}`}
- className="rounded border text-xs font-mono text-xs text-foreground-lighter py-2 px-3"
+ className="rounded-lg border bg-surface-75 text-xs font-mono text-xs text-foreground-lighter py-2 px-3 flex items-center gap-2"
>
+ <Loader2 className="w-4 h-4 animate-spin" />
{`Calling ${toolName}...`}
</div>
)
@@ -191,7 +196,7 @@ export const Message = function Message({
})()
) : hasTextContent ? (
<ReactMarkdown
- className="prose prose-sm [&_>h3]:text-base [&_ol>li]:pl-4 [&_ol>li]:my-0 space-y-5 flex-1 [&>*>code]:text-xs [&>*>*>code]:text-xs min-w-0 [&_li]:space-y-4"
+ className="prose prose-sm max-w-none break-words"
remarkPlugins={[remarkGfm]}
components={allMarkdownComponents}
>
diff --git a/apps/studio/components/ui/QueryBlock/BlockViewConfiguration.tsx b/apps/studio/components/ui/QueryBlock/BlockViewConfiguration.tsx
index d040354cfc9..2580eea2296 100644
--- a/apps/studio/components/ui/QueryBlock/BlockViewConfiguration.tsx
+++ b/apps/studio/components/ui/QueryBlock/BlockViewConfiguration.tsx
@@ -43,7 +43,7 @@ export const BlockViewConfiguration = ({
id="help-popover-button"
type="text"
className="px-1"
- icon={<Settings2 size={14} />}
+ icon={<Settings2 size={14} strokeWidth={1.5} />}
tooltip={{ content: { side: 'bottom', text: 'View data' } }}
/>
</PopoverTrigger_Shadcn_>
diff --git a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
index 545ec7eb58a..19cabf19ab1 100644
--- a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
+++ b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
@@ -62,7 +62,7 @@ export const EditQueryButton = ({
type={type}
size="tiny"
className={cn('w-7 h-7', className)}
- icon={<Edit size={14} />}
+ icon={<Edit size={14} strokeWidth={1.5} />}
tooltip={tooltip}
>
<Link href={`/project/${ref}/sql/${id}`} />
@@ -75,7 +75,7 @@ export const EditQueryButton = ({
type={type}
size="tiny"
className={cn('w-7 h-7', className)}
- icon={<Edit size={14} />}
+ icon={<Edit size={14} strokeWidth={1.5} />}
onClick={() => {
if (isInlineEditorEnabled) {
setEditorPanel({
@@ -105,7 +105,7 @@ export const EditQueryButton = ({
size="tiny"
disabled={!sql}
className={cn('w-7 h-7', className)}
- icon={<Edit size={14} />}
+ icon={<Edit size={14} strokeWidth={1.5} />}
tooltip={!!sql ? tooltip : { content: { side: 'bottom', text: undefined } }}
/>
</DropdownMenuTrigger>
diff --git a/apps/studio/components/ui/QueryBlock/QueryBlock.tsx b/apps/studio/components/ui/QueryBlock/QueryBlock.tsx
index afa9fc56408..b434044f48c 100644
--- a/apps/studio/components/ui/QueryBlock/QueryBlock.tsx
+++ b/apps/studio/components/ui/QueryBlock/QueryBlock.tsx
@@ -258,7 +258,7 @@ export const QueryBlock = ({
type="text"
size="tiny"
className="w-7 h-7"
- icon={<Code size={14} />}
+ icon={<Code size={14} strokeWidth={1.5} />}
onClick={() => setShowSql(!showSql)}
tooltip={{
content: { side: 'bottom', text: showSql ? 'Hide query' : 'Show query' },
@@ -302,7 +302,7 @@ export const QueryBlock = ({
type="text"
size="tiny"
className="w-7 h-7"
- icon={<Play size={14} />}
+ icon={<Play size={14} strokeWidth={1.5} />}
loading={isExecuting || isLoading}
disabled={isLoading}
onClick={() => {
diff --git a/apps/studio/pages/api/ai/sql/generate-v4.ts b/apps/studio/pages/api/ai/sql/generate-v4.ts
index 862bd19d8f7..afe72761799 100644
--- a/apps/studio/pages/api/ai/sql/generate-v4.ts
+++ b/apps/studio/pages/api/ai/sql/generate-v4.ts
@@ -50,6 +50,7 @@ const requestBodySchema = z.object({
connectionString: z.string(),
schema: z.string().optional(),
table: z.string().optional(),
+ chatName: z.string().optional(),
orgSlug: z.string().optional(),
})
@@ -68,7 +69,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
return res.status(400).json({ error: 'Invalid request body', issues: parseError.issues })
}
- const { messages, projectRef, connectionString, orgSlug } = data
+ const { messages, projectRef, connectionString, orgSlug, chatName } = data
// Get organizations and compute opt in level server-side
const [organizations, projects] = await Promise.all([
@@ -156,6 +157,15 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
return { status: 'Tool call sent to client for rendering.' }
},
}),
+ rename_chat: tool({
+ description: `Rename the current chat session when the current chat name doesn't describe the conversation topic.`,
+ parameters: z.object({
+ newName: z.string().describe('The new name for the chat session. Five words or less.'),
+ }),
+ execute: async () => {
+ return { status: 'Chat request sent to client' }
+ },
+ }),
}
// Get a list of all schemas to add to context
@@ -258,6 +268,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
# Core Principles:
- **Tool Usage Strategy**:
+ - **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"**. Current chat name: ${chatName}
- **Always attempt to use MCP tools** like \`list_tables\` and \`list_extensions\` to gather schema information if available. If these tools are not available or return a privacy message, state that you cannot access schema information and will proceed based on general Postgres/Supabase knowledge.
- For **READ ONLY** queries:
- Explain your plan.
@@ -325,6 +336,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
- UPDATE: \`USING (condition) WITH CHECK (condition)\` (often the same or related conditions)
- DELETE: \`USING (condition)\`
- Prefer \`PERMISSIVE\` policies unless \`RESTRICTIVE\` is explicitly needed.
+ - Avoid recursion errors when writing RLS policies that reference the same table. Use security definer functions to avoid this when needed.
- Leverage Supabase helper functions: \`auth.uid()\` for the user's ID, \`auth.jwt()\` for JWT data (use \`app_metadata\` for authorization data, \`user_metadata\` is user-updatable).
- **Performance**: Add indexes on columns used in RLS policies. Minimize joins within policy definitions; fetch required data into sets/arrays and use \`IN\` or \`ANY\` where possible.
- **Functions**:
@@ -386,6 +398,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
\`\`\`
# General Instructions:
+
- **Available Schemas**: ${schemasString}
- **Understand Context**: Attempt to use \`list_tables\`, \`list_extensions\` first. If they are not available or return a privacy/permission error, state this and proceed with caution, relying on the user's description and general knowledge.
`
@@ -401,7 +414,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
result.pipeDataStreamToResponse(res, {
getErrorMessage: (error) => {
if (error == null) {
- return 'unknown error'
+ return 'Untitled error'
}
if (typeof error === 'string') {
diff --git a/apps/studio/pages/project/[ref]/functions/new.tsx b/apps/studio/pages/project/[ref]/functions/new.tsx
index 278a875fd71..ef96fd11a00 100644
--- a/apps/studio/pages/project/[ref]/functions/new.tsx
+++ b/apps/studio/pages/project/[ref]/functions/new.tsx
@@ -171,10 +171,22 @@ const NewFunctionPage = () => {
title:
'I can help you understand and improve your edge function. Here are a few example prompts to get you started:',
prompts: [
- 'Explain what this function does...',
- 'Help me optimize this function...',
- 'Show me how to add more features...',
- 'Help me handle errors better...',
+ {
+ label: 'Explain Function',
+ description: 'Explain what this function does...',
+ },
+ {
+ label: 'Optimize Function',
+ description: 'Help me optimize this function...',
+ },
+ {
+ label: 'Add Features',
+ description: 'Show me how to add more features...',
+ },
+ {
+ label: 'Error Handling',
+ description: 'Help me handle errors better...',
+ },
],
},
})
diff --git a/apps/studio/state/ai-assistant-state.tsx b/apps/studio/state/ai-assistant-state.tsx
index 167965d1f59..b3de086f373 100644
--- a/apps/studio/state/ai-assistant-state.tsx
+++ b/apps/studio/state/ai-assistant-state.tsx
@@ -9,10 +9,10 @@ import { useSelectedProject } from 'hooks/misc/useSelectedProject'
type SuggestionsType = {
title: string
- prompts?: string[]
+ prompts?: { label: string; description: string }[]
}
-type AssistantMessageType = MessageType & { results?: { [id: string]: any[] } }
+export type AssistantMessageType = MessageType & { results?: { [id: string]: any[] } }
type ChatSession = {
id: string
@@ -286,6 +286,7 @@ export const createAiAssistantState = (): AiAssistantState => {
if (chat) {
chat.messages = []
chat.updatedAt = new Date()
+ state.suggestions = undefined
state.sqlSnippets = []
state.initialInput = ''
}
diff --git a/packages/ui-patterns/src/AssistantChat/AssistantChatForm.tsx b/packages/ui-patterns/src/AssistantChat/AssistantChatForm.tsx
index 8f37b777283..27efbd2b8b2 100644
--- a/packages/ui-patterns/src/AssistantChat/AssistantChatForm.tsx
+++ b/packages/ui-patterns/src/AssistantChat/AssistantChatForm.tsx
@@ -73,20 +73,16 @@ const AssistantChatFormComponent = React.forwardRef<HTMLFormElement, FormProps>(
ref={formRef}
{...props}
onSubmit={onSubmit}
- className={cn('relative', props.className)}
+ className={cn('relative ', props.className)}
>
- {icon && (
- <div className={cn('absolute', 'top-2 left-2', 'ml-1 w-6 h-6 rounded-full bg-dbnew')}>
- {icon}
- </div>
- )}
<ExpandingTextArea
ref={textAreaRef}
autoFocus={isMobile}
disabled={disabled}
- className={cn(icon ? 'pl-12' : '', 'text-sm pr-10 rounded-[18px]')}
+ className="text-sm pr-10 rounded max-h-64"
placeholder={placeholder}
spellCheck={false}
+ rows={3}
value={value}
onChange={(event) => onValueChange(event)}
onKeyDown={handleKeyDown}