Skip to content

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

Add message deletion functionality to AI Assistant (#37698)

Taishia8f6d85c4956
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
index ad98e71ee94..b189896edd7 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
@@ -42,6 +42,7 @@ const MemoizedMessage = memo(
message,
isLoading,
onResults,
+ onDelete,
onEdit,
isAfterEditedMessage,
isBeingEdited,
@@ -58,6 +59,7 @@ const MemoizedMessage = memo(
resultId?: string
results: any[]
}) => void
+ onDelete: (id: string) => void
onEdit: (id: string) => void
isAfterEditedMessage: boolean
isBeingEdited: boolean
@@ -70,6 +72,7 @@ const MemoizedMessage = memo(
readOnly={message.role === 'user'}
isLoading={isLoading}
onResults={onResults}
+ onDelete={onDelete}
onEdit={onEdit}
isAfterEditedMessage={isAfterEditedMessage}
isBeingEdited={isBeingEdited}
@@ -105,7 +108,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
)
const inputRef = useRef<HTMLTextAreaElement>(null)
- const { ref: scrollContainerRef, isSticky, scrollToEnd } = useAutoScroll()
+ const { ref: scrollContainerRef, isSticky, scrollToEnd, setIsSticky } = useAutoScroll()
const { aiOptInLevel, isHipaaProjectDisallowed } = useOrgAiOptInLevel()
const showMetadataWarning =
@@ -119,6 +122,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
const [value, setValue] = useState<string>(snap.initialInput || '')
const [isConfirmOptInModalOpen, setIsConfirmOptInModalOpen] = useState(false)
const [editingMessageId, setEditingMessageId] = useState<string | null>(null)
+ const [isResubmitting, setIsResubmitting] = useState(false)
const { data: check, isSuccess } = useCheckOpenAIKeyQuery()
const isApiKeySet = IS_PLATFORM || !!check?.hasKey
@@ -232,7 +236,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
onFinish: handleChatFinish,
})
- const isChatLoading = chatStatus === 'submitted' || chatStatus === 'streaming'
+ const isChatLoading = chatStatus === 'submitted' || chatStatus === 'streaming' || isResubmitting
const updateMessage = useCallback(
({
@@ -249,6 +253,22 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
[snap]
)
+ const deleteMessageFromHere = useCallback(
+ (messageId: string) => {
+ // Find the message index in current chatMessages
+ const messageIndex = chatMessages.findIndex((msg) => msg.id === messageId)
+ if (messageIndex === -1) return
+
+ if (isChatLoading) stop()
+
+ snap.deleteMessagesAfter(messageId, { includeSelf: true })
+
+ const updatedMessages = chatMessages.slice(0, messageIndex)
+ setMessages(updatedMessages)
+ },
+ [snap, setMessages, chatMessages, isChatLoading, stop]
+ )
+
const editMessage = useCallback(
(messageId: string) => {
const messageIndex = chatMessages.findIndex((msg) => msg.id === messageId)
@@ -266,9 +286,16 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
.join('') ?? ''
setValue(textContent)
- if (inputRef.current) {
- inputRef.current.focus()
- }
+ setTimeout(() => {
+ if (inputRef.current) {
+ inputRef?.current?.focus()
+
+ // [Joshen] This is just to make the cursor go to the end of the text when focusing
+ const val = inputRef.current.value
+ inputRef.current.value = ''
+ inputRef.current.value = val
+ }
+ }, 100)
},
[chatMessages, setValue]
)
@@ -292,6 +319,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
message={message}
isLoading={isChatLoading && message.id === chatMessages[chatMessages.length - 1].id}
onResults={updateMessage}
+ onDelete={deleteMessageFromHere}
onEdit={editMessage}
isAfterEditedMessage={isAfterEditedMessage}
isBeingEdited={isBeingEdited}
@@ -299,7 +327,15 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
/>
)
}),
- [chatMessages, isChatLoading, updateMessage, editMessage, editingMessageId, cancelEdit]
+ [
+ chatMessages,
+ isChatLoading,
+ updateMessage,
+ deleteMessageFromHere,
+ editMessage,
+ cancelEdit,
+ editingMessageId,
+ ]
)
const hasMessages = chatMessages.length > 0
@@ -308,12 +344,9 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
const sendMessageToAssistant = (finalContent: string) => {
if (editingMessageId) {
// Handling when the user is in edit mode
- const messageIndex = chatMessages.findIndex((msg) => msg.id === editingMessageId)
- if (messageIndex === -1) return
-
- snap.deleteMessagesAfter(editingMessageId, { includeSelf: true })
- const updatedMessages = chatMessages.slice(0, messageIndex)
- setMessages(updatedMessages)
+ // delete the message(s) from the chat just like the delete button
+ setIsResubmitting(true)
+ deleteMessageFromHere(editingMessageId)
setEditingMessageId(null)
}
@@ -355,6 +388,14 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
setEditingMessageId(null)
}
+ useEffect(() => {
+ // Keep "Thinking" visible while stopping and resubmitting during edit
+ // Only clear once the new response actually starts streaming (or errors)
+ if (isResubmitting && (chatStatus === 'streaming' || !!error)) {
+ setIsResubmitting(false)
+ }
+ }, [isResubmitting, chatStatus, error])
+
// Update scroll behavior for new messages
useEffect(() => {
if (!isChatLoading) {
@@ -381,6 +422,10 @@ 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 (
<ErrorBoundary
message="Something went wrong with the AI Assistant"
@@ -699,7 +744,8 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
'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}
- disabled={!isApiKeySet || disablePrompts || isChatLoading}
+ isEditing={!!editingMessageId}
+ disabled={!isApiKeySet || disablePrompts || (isChatLoading && !editingMessageId)}
placeholder={
hasMessages
? 'Ask a follow up question...'
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx
index 58c954f9a09..edf949772a2 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx
@@ -41,6 +41,8 @@ export interface FormProps {
snippetsClassName?: string
/* Additional class name for the form wrapper */
className?: string
+ /* If currently editing an existing message */
+ isEditing?: boolean
}
const AssistantChatFormComponent = forwardRef<HTMLFormElement, FormProps>(
@@ -59,6 +61,7 @@ const AssistantChatFormComponent = forwardRef<HTMLFormElement, FormProps>(
snippetsClassName,
includeSnippetsInMessage = false,
className,
+ isEditing = false,
...props
},
ref
@@ -68,7 +71,7 @@ const AssistantChatFormComponent = forwardRef<HTMLFormElement, FormProps>(
const handleSubmit = (event?: FormEvent<HTMLFormElement>) => {
if (event) event.preventDefault()
- if (!value || loading) return
+ if (!value || (loading && !isEditing)) return
let finalMessage = value
if (includeSnippetsInMessage && sqlSnippets && sqlSnippets.length > 0) {
@@ -107,8 +110,8 @@ const AssistantChatFormComponent = forwardRef<HTMLFormElement, FormProps>(
/>
)}
<ExpandingTextArea
+ autoFocus={!isMobile}
ref={textAreaRef}
- autoFocus={isMobile}
disabled={disabled}
className={cn(
'text-sm pr-10 max-h-64',
diff --git a/apps/studio/components/ui/AIAssistantPanel/DeleteMessageConfirmModal.tsx b/apps/studio/components/ui/AIAssistantPanel/DeleteMessageConfirmModal.tsx
new file mode 100644
index 00000000000..8e3796b4b70
--- /dev/null
+++ b/apps/studio/components/ui/AIAssistantPanel/DeleteMessageConfirmModal.tsx
@@ -0,0 +1,54 @@
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogSection,
+ DialogSectionSeparator,
+ DialogTitle,
+} from 'ui'
+
+type DeleteMessageConfirmModalProps = {
+ visible: boolean
+ onConfirm: () => void
+ onCancel: () => void
+}
+
+export const DeleteMessageConfirmModal = ({
+ visible,
+ onConfirm,
+ onCancel,
+}: DeleteMessageConfirmModalProps) => {
+ const onOpenChange = (open: boolean) => {
+ if (!open) onCancel()
+ }
+
+ return (
+ <Dialog open={visible} onOpenChange={onOpenChange}>
+ <DialogContent size="small">
+ <DialogHeader padding="small">
+ <DialogTitle>Delete Message</DialogTitle>
+ </DialogHeader>
+
+ <DialogSectionSeparator />
+
+ <DialogSection padding="small">
+ <p className="text-sm text-foreground-light">
+ Are you sure you want to delete this message and all subsequent messages? This action
+ cannot be undone.
+ </p>
+ </DialogSection>
+
+ <DialogFooter padding="small">
+ <Button type="default" onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button type="danger" onClick={onConfirm}>
+ Delete
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.tsx
index 3a295e2d6ce..c30bb9776a6 100644
--- a/apps/studio/components/ui/AIAssistantPanel/Message.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/Message.tsx
@@ -1,9 +1,10 @@
import { UIMessage as VercelMessage } from '@ai-sdk/react'
-import { Loader2, Pencil } from 'lucide-react'
-import { createContext, PropsWithChildren, ReactNode, useMemo } from 'react'
+import { Loader2, Pencil, Trash2 } from 'lucide-react'
+import { createContext, 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'
+import { toast } from 'sonner'
import { ProfileImage } from 'components/ui/ProfileImage'
import { useProfile } from 'lib/profile'
@@ -11,6 +12,7 @@ import { cn, markdownComponents, WarningIcon } from 'ui'
import { ButtonTooltip } from '../ButtonTooltip'
import { EdgeFunctionBlock } from '../EdgeFunctionBlock/EdgeFunctionBlock'
import { DisplayBlockRenderer } from './DisplayBlockRenderer'
+import { DeleteMessageConfirmModal } from './DeleteMessageConfirmModal'
import {
Heading3,
Hyperlink,
@@ -51,6 +53,7 @@ interface MessageProps {
resultId?: string
results: any[]
}) => void
+ onDelete: (id: string) => void
onEdit: (id: string) => void
isAfterEditedMessage: boolean
isBeingEdited: boolean
@@ -65,12 +68,14 @@ export const Message = function Message({
action = null,
variant = 'default',
onResults,
+ onDelete,
onEdit,
isAfterEditedMessage = false,
isBeingEdited = false,
onCancelEdit,
}: PropsWithChildren<MessageProps>) {
const { profile } = useProfile()
+ const [showDeleteConfirmModal, setShowDeleteConfirmModal] = useState(false)
const allMarkdownComponents: Partial<Components> = useMemo(
() => ({
...markdownComponents,
@@ -237,30 +242,54 @@ export const Message = function Message({
<span className="text-foreground-lighter italic">Assistant is thinking...</span>
)}
- {/* Action button - only show for user messages on hover */}
- <div className="opacity-0 group-hover:opacity-100 transition-opacity">
+ {/* Action buttons - only show for user messages on hover */}
+ <div className="opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1">
{message.role === 'user' && (
- <ButtonTooltip
- type="text"
- icon={<Pencil size={14} strokeWidth={1.5} />}
- onClick={isBeingEdited || isAfterEditedMessage ? onCancelEdit : () => onEdit(id)}
- className="text-foreground-light hover:text-foreground p-1 rounded"
- aria-label={
- isBeingEdited || isAfterEditedMessage ? 'Cancel editing' : 'Edit message'
- }
- tooltip={{
- content: {
- side: 'bottom',
- text:
- isBeingEdited || isAfterEditedMessage ? 'Cancel editing' : 'Edit message',
- },
- }}
- />
+ <>
+ <ButtonTooltip
+ type="text"
+ icon={<Pencil size={14} strokeWidth={1.5} />}
+ onClick={
+ isBeingEdited || isAfterEditedMessage ? onCancelEdit : () => onEdit(id)
+ }
+ className="text-foreground-light hover:text-foreground p-1 rounded"
+ aria-label={
+ isBeingEdited || isAfterEditedMessage ? 'Cancel editing' : 'Edit message'
+ }
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text:
+ isBeingEdited || isAfterEditedMessage ? 'Cancel editing' : 'Edit message',
+ },
+ }}
+ />
+
+ <ButtonTooltip
+ type="text"
+ icon={<Trash2 size={14} strokeWidth={1.5} />}
+ tooltip={{ content: { side: 'bottom', text: 'Delete message' } }}
+ onClick={() => setShowDeleteConfirmModal(true)}
+ className="text-foreground-light hover:text-foreground p-1 rounded"
+ title="Delete message"
+ aria-label="Delete message"
+ />
+ </>
)}
</div>
</div>
</div>
</div>
+
+ <DeleteMessageConfirmModal
+ visible={showDeleteConfirmModal}
+ onConfirm={() => {
+ onDelete(id)
+ setShowDeleteConfirmModal(false)
+ toast.success('Message deleted successfully')
+ }}
+ onCancel={() => setShowDeleteConfirmModal(false)}
+ />
</MessageContext.Provider>
)
}
diff --git a/apps/studio/components/ui/AIAssistantPanel/hooks.ts b/apps/studio/components/ui/AIAssistantPanel/hooks.ts
index 507c0708e55..9d5c9b231ae 100644
--- a/apps/studio/components/ui/AIAssistantPanel/hooks.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/hooks.ts
@@ -69,5 +69,5 @@ export function useAutoScroll({ enabled = true }: UseAutoScrollProps = {}) {
}
}, [container, enabled, scrollToEnd])
- return { ref, isSticky, scrollToEnd }
+ return { ref, isSticky, scrollToEnd, setIsSticky }
}