Skip to content

An AI-powered search engine with a generative UI

feat: Refactor message edit and reload logic

Yoshiki Miurac5d143905429
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsx
index 97823174..5cf0ca2b 100644
--- a/components/chat-messages.tsx
+++ b/components/chat-messages.tsx
@@ -1,7 +1,7 @@
'use client'
import { cn } from '@/lib/utils'
-import { ChatRequestOptions, JSONValue, Message } from 'ai'
+import { JSONValue, Message } from 'ai'
import { useEffect, useMemo, useState } from 'react'
import { RenderMessage } from './render-message'
import { ToolSection } from './tool-section'
@@ -19,10 +19,7 @@ interface ChatMessagesProps {
/** Ref for the scroll container */
scrollContainerRef: React.RefObject<HTMLDivElement>
onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>
- reload?: (
- messageId: string,
- options?: ChatRequestOptions
- ) => Promise<string | null | undefined>
+ reload?: (messageId: string) => Promise<void>
/** Whether auto-scroll is enabled (used by the button, now removed) */
// isAutoScroll?: boolean // No longer needed
/** Function to enable auto-scroll (used by the button, now removed) */
diff --git a/components/chat.tsx b/components/chat.tsx
index 0b317277..c8e92747 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -6,7 +6,7 @@ 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, Message as UIMessage } from 'ai'
+import { Message as UIMessage } from 'ai'
import { useRouter } from 'next/navigation'
import { useEffect, useRef, useTransition } from 'react'
import { toast } from 'sonner'
@@ -139,22 +139,77 @@ export function Chat({
}
}
- const handleReloadFrom = async (
- messageId: string,
- options?: ChatRequestOptions
- ) => {
- const messageIndex = messages.findIndex(m => m.id === messageId)
- if (messageIndex !== -1) {
- const userMessageIndex = messages
- .slice(0, messageIndex + 1)
- .findLastIndex(m => m.role === 'user')
- if (userMessageIndex !== -1) {
- const trimmedMessages = messages.slice(0, userMessageIndex + 1)
- setMessages(trimmedMessages)
- return await reload(options)
- }
+ const handleReloadFrom = async (reloadFromFollowerMessageId: string) => {
+ if (!id) {
+ toast.error('Chat ID is missing for reload.')
+ 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 followerMessage = messages[followerMessageIndex]
+ const deletionTimestamp =
+ followerMessage.createdAt?.toISOString() ?? new Date(0).toISOString()
+
+ const contentToResend =
+ targetUserMessage.parts
+ ?.filter(p => p.type === 'text')
+ .map(p => p.text)
+ .join('') ||
+ targetUserMessage.content ||
+ ''
+
+ try {
+ setMessages(prevMessages => {
+ const messagesBeforeTarget = prevMessages.slice(
+ 0,
+ targetUserMessageIndex
+ )
+
+ const newResentUserMessage: UIMessage = {
+ id: generateUUID(),
+ role: 'user',
+ content: contentToResend,
+ parts: [{ type: 'text', text: contentToResend }],
+ createdAt: new Date()
+ }
+ return [...messagesBeforeTarget, newResentUserMessage]
+ })
+
+ await deleteTrailingMessages(id, deletionTimestamp)
+ await reload()
+ } catch (error) {
+ console.error(
+ `Error during reload from message preceding ${reloadFromFollowerMessageId}:`,
+ error
+ )
+ toast.error(`Failed to reload conversation: ${(error as Error).message}`)
}
- return await reload(options)
}
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {