An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
refactor(chat): Adjust message edit logic for new ID generation Refactor handleUpdateAndReloadMessage to: - Delete relevant messages from DB *after* updating local state with a new user message (containing edited content and a new ID). - Call reload() to get a new assistant response. - Rename AIMessage type alias to UIMessage. - Remove success toast and setData(undefined) in this specific f.
Yoshiki Miuracb6bae3f3fc1
diff --git a/components/chat.tsx b/components/chat.tsxindex 98e11911..0b317277 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -1,12 +1,12 @@'use client'+import { deleteTrailingMessages } from '@/lib/actions/chat-db'import { CHAT_ID } from '@/lib/constants'import { useAutoScroll } from '@/lib/hooks/use-auto-scroll'import { Model } from '@/lib/types/models'import { cn, generateUUID } from '@/lib/utils'import { useChat } from '@ai-sdk/react'-import { ChatRequestOptions } from 'ai'-import { Message } from 'ai/react'+import { ChatRequestOptions, Message as UIMessage } from 'ai'import { useRouter } from 'next/navigation'import { useEffect, useRef, useTransition } from 'react'import { toast } from 'sonner'@@ -20,7 +20,7 @@ export function Chat({models}: {id: string- savedMessages?: Message[]+ savedMessages?: UIMessage[]query?: stringmodels?: Model[]}) {@@ -51,7 +51,7 @@ export function Chat({onError: error => {toast.error(`Error in chat: ${error.message}`)},- sendExtraMessageFields: false, // Disable extra message fields,+ sendExtraMessageFields: false,experimental_throttle: 100,generateId: generateUUID,experimental_prepareRequestBody: body => ({@@ -86,34 +86,56 @@ export function Chat({}const handleUpdateAndReloadMessage = async (- messageId: string,- newContent: string+ editedMessageId: string,+ newContentText: string) => {- setMessages(currentMessages =>- currentMessages.map(msg =>- msg.id === messageId ? { ...msg, content: newContent } : msg+ if (!id) {+ toast.error('Chat ID is missing.')+ console.error(+ 'handleUpdateAndReloadMessage: chatId (id prop) is undefined.')- )-- try {- const messageIndex = messages.findIndex(msg => msg.id === messageId)- if (messageIndex === -1) return-- const messagesUpToEdited = messages.slice(0, messageIndex + 1)-- setMessages(messagesUpToEdited)+ return+ }- setData(undefined)+ const pivotMessage = messages.find(m => m.id === editedMessageId)+ if (!pivotMessage) {+ toast.error('Original message not found to edit locally.')+ console.error(+ 'handleUpdateAndReloadMessage: Pivot message not found for timestamp.'+ )+ return+ }+ const pivotTimestamp =+ pivotMessage.createdAt?.toISOString() ?? new Date(0).toISOString()- await reload({- body: {- chatId: id,- regenerate: true+ try {+ setMessages(prevMessages => {+ const messageIndex = prevMessages.findIndex(+ m => m.id === editedMessageId+ )+ const messagesBeforeEdited =+ messageIndex !== -1+ ? prevMessages.slice(0, messageIndex)+ : prevMessages++ const newUIMessage: UIMessage = {+ id: generateUUID(),+ role: 'user',+ content: newContentText,+ parts: [{ type: 'text', text: newContentText }],+ createdAt: new Date()}++ return [...messagesBeforeEdited, newUIMessage]})++ await deleteTrailingMessages(id, pivotTimestamp)+ await reload()} catch (error) {- console.error('Failed to reload after message update:', error)- toast.error(`Failed to reload conversation: ${(error as Error).message}`)+ console.error('Error during message edit and reload process:', error)+ toast.error(+ `Error processing edited message: ${(error as Error).message}`+ )}}@@ -124,7 +146,7 @@ export function Chat({const messageIndex = messages.findIndex(m => m.id === messageId)if (messageIndex !== -1) {const userMessageIndex = messages- .slice(0, messageIndex)+ .slice(0, messageIndex + 1).findLastIndex(m => m.role === 'user')if (userMessageIndex !== -1) {const trimmedMessages = messages.slice(0, userMessageIndex + 1)diff --git a/lib/actions/chat-db.ts b/lib/actions/chat-db.tsindex ee21d9e4..b24c01b7 100644--- a/lib/actions/chat-db.ts+++ b/lib/actions/chat-db.ts@@ -274,81 +274,6 @@ export async function saveChat(}}-// Server action to update the content of a specific message-export async function updateMessageContent(- chatId: string,- messageId: string,- newParts: DBMessage['parts'] // Use the type from DBMessage for parts-): Promise<DBMessage | null> {- const userId = await getCurrentUserId()- if (!userId) {- console.error('updateMessageContent: User not authenticated')- // Optionally, you could throw an error or return an object indicating failure- return null- }-- try {- // 1. Verify chat access for the current user- const chat = await chatDb.getChat(chatId, userId)- if (!chat) {- console.warn(- `updateMessageContent: Chat ${chatId} not found or user ${userId} unauthorized.`- )- return null- }-- // 2. Fetch the specific message to check its role and ensure it belongs to the chat- // This also implicitly checks if messageId is valid for this chatId- const messagesInChat = await chatDb.getChatMessages(chatId)- const messageToUpdate = messagesInChat.find(msg => msg.id === messageId)-- if (!messageToUpdate) {- console.warn(- `updateMessageContent: Message ${messageId} not found in chat ${chatId}.`- )- return null- }-- // 3. Permission: Allow user to only update their own 'user' messages- // Adjust this logic if other roles can be edited or if admins have broader permissions.- if (messageToUpdate.role !== 'user' || chat.userId !== userId) {- // If message is not a 'user' message, or if the chat doesn't belong to the user- // (this latter check is a bit redundant if getChat already scopes by userId for private chats,- // but good for 'public' chats where anyone can see but only owner should edit their user messages within it).- // For this specific app's UserMessage component, we are editing a 'user' message.- console.warn(- `updateMessageContent: User ${userId} not permitted to update message ${messageId} (role: ${messageToUpdate.role}, chat owner: ${chat.userId}).`- )- return null- }-- // 4. Call the database function to update message content- const updatedMessage = await chatDb.updateMessageContent(- messageId,- newParts- )-- if (updatedMessage) {- // Optional: Revalidate relevant paths if needed- // revalidatePath(`/chat/${chatId}`)- return updatedMessage- }-- // Log if chatDb.updateMessageContent returned null without throwing an error- console.error(- `updateMessageContent: Failed to update message ${messageId} in DB.`- )- return null- } catch (error: any) {- console.error(- `Error in server action updateMessageContent for message ID ${messageId}:`,- error- )- // Rethrow or return an error structure if preferred- return null- }-}-// Action to delete messages in a chat after a specific message (the pivot)export async function deleteTrailingMessages(chatId: string,diff --git a/lib/db/chat.ts b/lib/db/chat.tsindex 313199e2..33817f41 100644--- a/lib/db/chat.ts+++ b/lib/db/chat.ts@@ -1,4 +1,4 @@-import { and, desc, eq, gt } from 'drizzle-orm'+import { and, desc, eq, gte, inArray } from 'drizzle-orm'import { revalidatePath } from 'next/cache'import { redirect } from 'next/navigation'import { db } from '.'@@ -170,26 +170,40 @@ export async function getChatMessages(chatId: string): Promise<Message[]> {.orderBy(messages.createdAt)}-// Delete all messages created after (strictly greater than) the-// given timestamp in the same chat.+// Delete all messages created at or after the given timestamp in the same chat.+// This will include the message whose createdAt matches the timestamp.export async function deleteMessagesByChatIdAfterTimestamp(chatId: string,- timestamp: string // Assuming this is an ISO 8601 string+ timestamp: string // Expecting ISO 8601 string): Promise<{ count: number; error?: string }> {try {- const result = await db- .delete(messages)+ // Select IDs of messages to delete+ const messagesToDelete = await db+ .select({ id: messages.id })+ .from(messages).where(and(eq(messages.chatId, chatId),- gt(messages.createdAt, timestamp) // Use the ISO string directly+ gte(messages.createdAt, timestamp) // Use ISO string directly))- .returning({ id: messages.id }) // Returning something to count++ const messageIds = messagesToDelete.map(message => message.id)++ if (messageIds.length === 0) {+ return { count: 0 } // No messages to delete+ }++ // Delete the actual messages+ const result = await db+ .delete(messages)+ .where(and(eq(messages.chatId, chatId), inArray(messages.id, messageIds)))+ .returning({ id: messages.id })+return { count: result.length }} catch (error) {console.error(- `Error deleting messages for chat ${chatId} after ${timestamp}:`,+ `Error deleting messages for chat ${chatId} at or after ${timestamp}:`,error)return { count: 0, error: 'Failed to delete messages' }@@ -306,28 +320,3 @@ export async function shareChat(id: string, userId: string) {return null}}--// Update the content (parts) of a specific message-export async function updateMessageContent(- messageId: string,- newParts: any // Assuming parts can be of any structure, similar to addMessage-): Promise<Message | null> {- try {- const [updatedMessage] = await db- .update(messages)- .set({- parts: newParts,- updatedAt: new Date().toISOString() // Convert Date to ISO string- })- .where(eq(messages.id, messageId))- .returning()-- return updatedMessage || null- } catch (error) {- console.error(- `Error updating message content for message ${messageId}:`,- error- )- return null- }-}