The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Implement message editing functionality in AI Assistant (#37603)
Taishi2976d572e14c
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsxindex 4d4c0346ad1..ad98e71ee94 100644--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx@@ -2,7 +2,7 @@ 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, Settings, X } from 'lucide-react'+import { ArrowDown, Eraser, Info, Pencil, Settings, X } from 'lucide-react'import { useRouter } from 'next/router'import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'@@ -18,13 +18,13 @@ import { useOrgAiOptInLevel } from 'hooks/misc/useOrgOptedIntoAi'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { useFlag } from 'hooks/ui/useFlag'+import { useHotKey } from 'hooks/ui/useHotKey'import { BASE_PATH, IS_PLATFORM } from 'lib/constants'-import { tryParseJson } from 'lib/helpers'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 } from 'ui'+import { AiIconAnimation, Button, cn, KeyboardShortcut } from 'ui'import { Admonition, GenericSkeletonLoader } from 'ui-patterns'import { ButtonTooltip } from '../ButtonTooltip'import { ErrorBoundary } from '../ErrorBoundary'@@ -42,6 +42,10 @@ const MemoizedMessage = memo(message,isLoading,onResults,+ onEdit,+ isAfterEditedMessage,+ isBeingEdited,+ onCancelEdit,}: {message: MessageTypeisLoading: boolean@@ -54,15 +58,22 @@ const MemoizedMessage = memo(resultId?: stringresults: any[]}) => void+ onEdit: (id: string) => void+ isAfterEditedMessage: boolean+ isBeingEdited: boolean+ onCancelEdit: () => void}) => {return (<Message- key={message.id}id={message.id}message={message}readOnly={message.role === 'user'}isLoading={isLoading}onResults={onResults}+ onEdit={onEdit}+ isAfterEditedMessage={isAfterEditedMessage}+ isBeingEdited={isBeingEdited}+ onCancelEdit={onCancelEdit}/>)}@@ -82,6 +93,8 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {const { ref, id: entityId } = useParams()const searchParams = useSearchParamsShallow()+ useHotKey(() => cancelEdit(), 'Escape')+const disablePrompts = useFlag('disableAssistantPrompts')const { snippets } = useSqlEditorV2StateSnapshot()const snap = useAiAssistantStateSnapshot()@@ -105,6 +118,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 { data: check, isSuccess } = useCheckOpenAIKeyQuery()const isApiKeySet = IS_PLATFORM || !!check?.hasKey@@ -235,25 +249,74 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {[snap])+ const editMessage = useCallback(+ (messageId: string) => {+ const messageIndex = chatMessages.findIndex((msg) => msg.id === messageId)+ if (messageIndex === -1) return++ // Target message+ const messageToEdit = chatMessages[messageIndex]++ // Activate editing mode+ setEditingMessageId(messageId)+ const textContent =+ messageToEdit.parts+ ?.filter((part) => part.type === 'text')+ .map((part) => part.text)+ .join('') ?? ''+ setValue(textContent)++ if (inputRef.current) {+ inputRef.current.focus()+ }+ },+ [chatMessages, setValue]+ )++ const cancelEdit = useCallback(() => {+ setEditingMessageId(null)+ setValue('')+ }, [setValue])+const renderedMessages = useMemo(() =>- chatMessages.map((message) => {+ chatMessages.map((message, index) => {+ const isBeingEdited = editingMessageId === message.id+ const isAfterEditedMessage = editingMessageId+ ? chatMessages.findIndex((m) => m.id === editingMessageId) < index+ : false+return (<MemoizedMessagekey={message.id}message={message}isLoading={isChatLoading && message.id === chatMessages[chatMessages.length - 1].id}onResults={updateMessage}+ onEdit={editMessage}+ isAfterEditedMessage={isAfterEditedMessage}+ isBeingEdited={isBeingEdited}+ onCancelEdit={cancelEdit}/>)}),- [chatMessages, isChatLoading, updateMessage]+ [chatMessages, isChatLoading, updateMessage, editMessage, editingMessageId, cancelEdit])const hasMessages = chatMessages.length > 0const isShowingOnboarding = !hasMessages && isApiKeySetconst 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)+ setEditingMessageId(null)+ }+const payload = {role: 'user',createdAt: new Date(),@@ -289,6 +352,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {snap.clearMessages()setMessages([])lastUserMessageRef.current = null+ setEditingMessageId(null)}// Update scroll behavior for new messages@@ -432,7 +496,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {)}</div>{hasMessages ? (- <div className="w-full px-7 py-8 space-y-6">+ <div 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">@@ -528,40 +592,79 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {</div><AnimatePresence>- {!isSticky && (- <>- <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 },+ {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 left-1/2 z-20 bottom-8 pointer-events-auto"+ variants={{+ hidden: { y: 5, opacity: 0 },+ show: { y: 0, opacity: 1 },+ }}+ transition={{ duration: 0.1 }}+ initial="hidden"+ animate="show"+ exit="hidden"+ >+ <div className="-translate-x-1/2 bg-alternative dark:bg-muted border rounded-md px-3 py-2 min-w-[180px] flex items-center justify-between gap-x-2">+ <div className="flex items-center gap-x-2 text-sm text-foreground">+ <Pencil size={14} />+ <span>Editing message</span>+ </div>+ <ButtonTooltip+ type="outline"+ size="tiny"+ icon={<X size={14} />}+ onClick={cancelEdit}+ className="w-6 h-6 p-0"+ title="Cancel editing"+ aria-label="Cancel editing"+ tooltip={{+ content: { side: 'top', text: <KeyboardShortcut keys={['Meta', 'Esc']} /> },+ }}+ />+ </div>+ </motion.div>+ </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()}}- 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>- </>+ <ArrowDown size={16} />+ </Button>+ </motion.div>+ </div>+ </motion.div>)}</AnimatePresence>diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsxindex 75bca4790a0..f06425388fb 100644--- a/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsx@@ -1,12 +1,12 @@import { ArrowUp, Loader2, Square } from 'lucide-react'-import React, { ChangeEvent, memo, useRef } from 'react'+import { ChangeEvent, FormEvent, forwardRef, KeyboardEvent, memo, useRef } from 'react'import { useBreakpoint } from 'common'import { ExpandingTextArea } from 'ui'import { cn } from 'ui/src/lib/utils'import { ButtonTooltip } from '../ButtonTooltip'import { type SqlSnippet } from './AIAssistant.types'-import { SnippetRow, getSnippetContent } from './SnippetRow'+import { getSnippetContent, SnippetRow } from './SnippetRow'export interface FormProps {/* The ref for the textarea, optional. Exposed for the CommandsPopover to attach events. */@@ -43,7 +43,7 @@ export interface FormProps {className?: string}-const AssistantChatFormComponent = React.forwardRef<HTMLFormElement, FormProps>(+const AssistantChatFormComponent = forwardRef<HTMLFormElement, FormProps>(({loading = false,@@ -66,7 +66,7 @@ const AssistantChatFormComponent = React.forwardRef<HTMLFormElement, FormProps>(const formRef = useRef<HTMLFormElement>(null)const isMobile = useBreakpoint('md')- const handleSubmit = (event?: React.FormEvent<HTMLFormElement>) => {+ const handleSubmit = (event?: FormEvent<HTMLFormElement>) => {if (event) event.preventDefault()if (!value || loading) return@@ -81,7 +81,7 @@ const AssistantChatFormComponent = React.forwardRef<HTMLFormElement, FormProps>(onSubmit(finalMessage)}- const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {+ const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {if (event.key === 'Enter' && !event.shiftKey) {event.preventDefault()handleSubmit()diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.tsxindex 7838c5ceda0..3a295e2d6ce 100644--- a/apps/studio/components/ui/AIAssistantPanel/Message.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/Message.tsx@@ -1,5 +1,5 @@import { UIMessage as VercelMessage } from '@ai-sdk/react'-import { Loader2 } from 'lucide-react'+import { Loader2, Pencil } from 'lucide-react'import { createContext, PropsWithChildren, ReactNode, useMemo } from 'react'import ReactMarkdown from 'react-markdown'import { Components } from 'react-markdown/lib/ast-to-react'@@ -8,6 +8,7 @@ import remarkGfm from 'remark-gfm'import { ProfileImage } from 'components/ui/ProfileImage'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 {@@ -50,6 +51,10 @@ interface MessageProps {resultId?: stringresults: any[]}) => void+ onEdit: (id: string) => void+ isAfterEditedMessage: boolean+ isBeingEdited: boolean+ onCancelEdit: () => void}export const Message = function Message({@@ -60,6 +65,10 @@ export const Message = function Message({action = null,variant = 'default',onResults,+ onEdit,+ isAfterEditedMessage = false,+ isBeingEdited = false,+ onCancelEdit,}: PropsWithChildren<MessageProps>) {const { profile } = useProfile()const allMarkdownComponents: Partial<Components> = useMemo(@@ -95,16 +104,18 @@ export const Message = function Message({<MessageContext.Provider value={{ isLoading, readOnly }}><divclassName={cn(- 'text-foreground-light text-sm',- isUser && 'text-foreground',- variant === 'warning' && 'bg-warning-200'+ 'text-foreground-light text-sm first:mt-0',+ isUser ? 'text-foreground mt-6' : '',+ variant === 'warning' && 'bg-warning-200',+ isAfterEditedMessage && 'opacity-50 cursor-pointer transition-opacity')}+ onClick={isAfterEditedMessage ? onCancelEdit : undefined}>{variant === 'warning' && <WarningIcon className="w-6 h-6" />}{action}- <div className="flex gap-4 w-auto overflow-hidden">+ <div className="flex gap-4 w-auto overflow-hidden group">{isUser && (<ProfileImagealt={profile?.username}@@ -113,7 +124,7 @@ export const Message = function Message({/>)}- <div className="flex-1 min-w-0 space-y-2">+ <div className="flex-1 min-w-0">{shouldUsePartsRendering ? ((() => {const shownLoadingTools = new Set<string>()@@ -126,7 +137,8 @@ export const Message = function Message({key={`${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',- isUser && 'text-foreground [&>p]:font-medium'+ isUser && 'text-foreground [&>p]:font-medium',+ isBeingEdited && 'animate-pulse')}remarkPlugins={[remarkGfm]}components={allMarkdownComponents}@@ -145,7 +157,7 @@ export const Message = function Message({return (<divkey={`${id}-tool-loading-display_query`}- 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"+ className="rounded-lg border bg-surface-75 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 display_query...`}@@ -178,7 +190,7 @@ export const Message = function Message({return (<divkey={`${id}-tool-loading-display_edge_function`}- 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"+ className="rounded-lg border bg-surface-75 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 display_edge_function...`}@@ -224,6 +236,28 @@ 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">+ {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',+ },+ }}+ />+ )}+ </div></div></div></div>diff --git a/apps/studio/state/ai-assistant-state.tsx b/apps/studio/state/ai-assistant-state.tsxindex a9034f084d1..4d2836c070c 100644--- a/apps/studio/state/ai-assistant-state.tsx+++ b/apps/studio/state/ai-assistant-state.tsx@@ -304,6 +304,19 @@ export const createAiAssistantState = (): AiAssistantState => {}},+ deleteMessagesAfter: (id: string, { includeSelf = true } = {}) => {+ const chat = state.activeChat+ if (!chat) return++ const messageIndex = chat.messages.findIndex((msg) => msg.id === id)+ if (messageIndex === -1) return++ // Delete all messages from the target message (optionally including) to the end+ const startIndex = includeSelf ? messageIndex : messageIndex + 1+ chat.messages.splice(startIndex)+ chat.updatedAt = new Date()+ },+saveMessage: (message: MessageType | MessageType[]) => {const chat = state.activeChatif (!chat) return@@ -420,6 +433,7 @@ export type AiAssistantState = AiAssistantData & {deleteChat: (id: string) => voidrenameChat: (id: string, name: string) => voidclearMessages: () => void+ deleteMessagesAfter: (id: string, options?: { includeSelf?: boolean }) => voidsaveMessage: (message: MessageType | MessageType[]) => voidupdateMessage: (args: { id: string; resultId?: string; results: any[] }) => voidsetSqlSnippets: (snippets: SqlSnippet[]) => void