An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Fix reload and edit functionality to use messageId-based operations
Yoshiki Miuraacf226bf33d8
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex dcdf8463..d7072957 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -19,25 +19,21 @@ const DEFAULT_MODEL: Model = {export async function POST(req: Request) {try {const body = await req.json()- const { messages, chatId, trigger, messageId } = body+ const { message, chatId, trigger, messageId } = body// Handle different triggers- let message-- if (trigger === 'regenerate-assistant-message') {- // For regeneration, we'll fetch the messages from DB and use the last user message- // This will be handled in createChatStreamResponse- message = null- } else {- // Get the last message from the messages array (the new user message)- message = messages?.[messages.length - 1]+ if (trigger === 'regenerate-assistant-message' && !messageId) {+ return new Response('messageId is required for regeneration', {+ status: 400,+ statusText: 'Bad Request'+ })+ }- if (!message) {- return new Response('No message provided', {- status: 400,- statusText: 'Bad Request'- })- }+ if (trigger === 'submit-user-message' && !message) {+ return new Response('message is required for submission', {+ status: 400,+ statusText: 'Bad Request'+ })}const referer = req.headers.get('referer')diff --git a/app/search/loading.tsx b/app/search/loading.tsxindex 9f1b9e3b..8f4de58b 100644--- a/app/search/loading.tsx+++ b/app/search/loading.tsx@@ -4,7 +4,7 @@ import { DefaultSkeleton } from '../../components/default-skeleton'export default function Loading() {return (- <div className="flex h-full min-w-0 flex-1 flex-col items-center justify-center">+ <div className="flex min-w-0 flex-1 flex-col items-center justify-center"><div className="w-full max-w-3xl px-4 pt-12"><DefaultSkeleton /></div>diff --git a/components/chat.tsx b/components/chat.tsxindex 2a614dcf..3242d0bf 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -7,7 +7,6 @@ import { DefaultChatTransport } from 'ai'import { toast } from 'sonner'import { z } from 'zod'-import { deleteTrailingMessages } from '@/lib/actions/chat-db'import { generateId } from '@/lib/db/schema'import { UploadedFile } from '@/lib/types'import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'@@ -58,12 +57,15 @@ export function Chat({prepareSendMessagesRequest: ({ messages, trigger, messageId }) => {switch (trigger) {case 'regenerate-assistant-message':- // Only send messageId, not message data+ // Find the message being regenerated+ const messageToRegenerate = messages.find(m => m.id === messageId)return {body: {trigger: 'regenerate-assistant-message',chatId: id,- messageId+ messageId,+ // Include the message if it's a user message (for edit cases)+ message: messageToRegenerate?.role === 'user' ? messageToRegenerate : undefined}}@@ -74,7 +76,7 @@ export function Chat({body: {trigger: 'submit-user-message',chatId: id,- messages: [messages[messages.length - 1]],+ message: messages[messages.length - 1],messageId}}@@ -182,40 +184,25 @@ export function Chat({return}- 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.metadata as { createdAt?: Date }- )?.createdAt?.toISOString() ?? new Date(0).toISOString()-try {+ // Update the message locally with the same IDsetMessages(prevMessages => {const messageIndex = prevMessages.findIndex(m => m.id === editedMessageId)- const messagesBeforeEdited =- messageIndex !== -1- ? prevMessages.slice(0, messageIndex)- : prevMessages-- const newUIMessage: UIMessage = {- id: generateId(),- role: 'user',+ if (messageIndex === -1) return prevMessages++ const updatedMessages = [...prevMessages]+ updatedMessages[messageIndex] = {+ ...updatedMessages[messageIndex],parts: [{ type: 'text', text: newContentText }]}- return [...messagesBeforeEdited, newUIMessage]+ return updatedMessages})- await deleteTrailingMessages(id, pivotTimestamp)- await regenerate()+ // Regenerate from this message+ await regenerate({ messageId: editedMessageId })} catch (error) {console.error('Error during message edit and reload process:', error)toast.error(@@ -230,64 +217,12 @@ export function Chat({return}- const followerMessageIndex = messages.findIndex(- m => m.id === reloadFromFollowerMessageId- )-- if (followerMessageIndex < 1) {- toast.error(- 'Cannot reload: No preceding message found or message is the first.'- )- console.error(- `handleReloadFrom: No message found before id ${reloadFromFollowerMessageId} or it is the first message.`- )- return- }-- const targetUserMessageIndex = followerMessageIndex - 1- const targetUserMessage = messages[targetUserMessageIndex]-- if (targetUserMessage.role !== 'user') {- toast.error(- 'Cannot reload: The message to resend must be a user message.'- )- console.error(- `handleReloadFrom: Preceding message (id: ${targetUserMessage.id}) is not a user message.`- )- return- }-- const deletionTimestamp =- (- targetUserMessage.metadata as { createdAt?: Date }- )?.createdAt?.toISOString() ?? new Date(0).toISOString()-- const contentToResend =- targetUserMessage.parts- ?.filter((p: any) => p.type === 'text')- .map((p: any) => p.text)- .join('') || ''-try {- setMessages(prevMessages => {- const messagesBeforeTarget = prevMessages.slice(- 0,- targetUserMessageIndex- )-- const newResentUserMessage: UIMessage = {- id: generateId(),- role: 'user',- parts: [{ type: 'text', text: contentToResend }]- }- return [...messagesBeforeTarget, newResentUserMessage]- })-- await deleteTrailingMessages(id, deletionTimestamp)- await regenerate()+ // Use the SDK's regenerate function with the specific messageId+ await regenerate({ messageId: reloadFromFollowerMessageId })} catch (error) {console.error(- `Error during reload from message preceding ${reloadFromFollowerMessageId}:`,+ `Error during reload from message ${reloadFromFollowerMessageId}:`,error)toast.error(`Failed to reload conversation: ${(error as Error).message}`)diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.tsindex 065a0ddc..596afbd4 100644--- a/lib/streaming/create-chat-stream-response.ts+++ b/lib/streaming/create-chat-stream-response.ts@@ -58,16 +58,40 @@ export async function createChatStreamResponse(if (trigger === 'regenerate-assistant-message' && messageId) {// Handle regeneration- // Delete messages from the specified messageId onwards- await deleteMessagesFromIndex(chatId, messageId)+ // Find the message to regenerate from+ const currentChat = await getChatAction(chatId, userId)+ if (!currentChat || !currentChat.messages.length) {+ throw new Error('No messages found')+ }- // Get updated messages- const updatedChat = await getChatAction(chatId, userId)- if (!updatedChat || !updatedChat.messages.length) {- throw new Error('No messages to regenerate')+ const messageIndex = currentChat.messages.findIndex(+ m => m.id === messageId+ )+ if (messageIndex === -1) {+ throw new Error(`Message ${messageId} not found`)}- messagesToModel = updatedChat.messages+ // Check if it's an assistant message that needs regeneration+ const targetMessage = currentChat.messages[messageIndex]+ if (targetMessage.role === 'assistant') {+ // Delete from this assistant message onwards+ await deleteMessagesFromIndex(chatId, messageId)+ // Use messages up to (but not including) this assistant message+ messagesToModel = currentChat.messages.slice(0, messageIndex)+ } else {+ // If it's a user message that was edited, save the updated message first+ if (message && message.id === messageId) {+ await saveMessage(chatId, message)+ }+ // Delete everything after this user message+ const messagesToDelete = currentChat.messages.slice(messageIndex + 1)+ if (messagesToDelete.length > 0) {+ await deleteMessagesFromIndex(chatId, messagesToDelete[0].id)+ }+ // Get updated messages including the edited one+ const updatedChat = await getChatAction(chatId, userId)+ messagesToModel = updatedChat?.messages || currentChat.messages.slice(0, messageIndex + 1)+ }} else {// Handle normal message submissionif (!message) {