Skip to content

An AI-powered search engine with a generative UI

fix: update reload function type to support void return type and remove unused files

Yoshiki Miura48b1f091d76d
diff --git a/components/answer-section.tsx b/components/answer-section.tsx
index 01fef859..d2188fda 100644
--- a/components/answer-section.tsx
+++ b/components/answer-section.tsx
@@ -16,7 +16,7 @@ export type AnswerSectionProps = {
reload?: (
messageId: string,
options?: ChatRequestOptions
- ) => Promise<string | null | undefined>
+ ) => Promise<void | string | null | undefined>
}
export function AnswerSection({
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsx
index 5cf0ca2b..38fd2838 100644
--- a/components/chat-messages.tsx
+++ b/components/chat-messages.tsx
@@ -19,7 +19,7 @@ interface ChatMessagesProps {
/** Ref for the scroll container */
scrollContainerRef: React.RefObject<HTMLDivElement>
onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>
- reload?: (messageId: string) => Promise<void>
+ reload?: (messageId: string) => Promise<void | string | null | undefined>
/** 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/message-actions.tsx b/components/message-actions.tsx
index 094d309e..0356d235 100644
--- a/components/message-actions.tsx
+++ b/components/message-actions.tsx
@@ -12,7 +12,7 @@ import { Button } from './ui/button'
interface MessageActionsProps {
message: string
messageId: string
- reload?: () => Promise<string | null | undefined>
+ reload?: () => Promise<void | string | null | undefined>
chatId?: string
enableShare?: boolean
className?: string
diff --git a/components/render-message.tsx b/components/render-message.tsx
index ea0aac09..9ae2bdf0 100644
--- a/components/render-message.tsx
+++ b/components/render-message.tsx
@@ -1,4 +1,4 @@
-import { ChatRequestOptions, JSONValue, Message, ToolInvocation } from 'ai'
+import { JSONValue, Message, ToolInvocation } from 'ai'
import { useMemo } from 'react'
import { AnswerSection } from './answer-section'
import { ReasoningSection } from './reasoning-section'
@@ -15,10 +15,7 @@ interface RenderMessageProps {
chatId?: string
addToolResult?: (params: { toolCallId: string; result: any }) => void
onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>
- reload?: (
- messageId: string,
- options?: ChatRequestOptions
- ) => Promise<string | null | undefined>
+ reload?: (messageId: string) => Promise<void | string | null | undefined>
}
export function RenderMessage({
diff --git a/components/retry-button.tsx b/components/retry-button.tsx
index 0916e100..d90e529d 100644
--- a/components/retry-button.tsx
+++ b/components/retry-button.tsx
@@ -4,7 +4,7 @@ import { RotateCcw } from 'lucide-react'
import { Button } from './ui/button'
interface RetryButtonProps {
- reload: () => Promise<string | null | undefined>
+ reload: () => Promise<void | string | null | undefined>
messageId: string
}
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
deleted file mode 100644
index d07b7247..00000000
--- a/lib/actions/chat.ts
+++ /dev/null
@@ -1,252 +0,0 @@
-'use server'
-
-import { getRedisClient, RedisWrapper } from '@/lib/redis/config'
-import { type Chat } from '@/lib/types'
-import { revalidatePath } from 'next/cache'
-import { redirect } from 'next/navigation'
-
-async function getRedis(): Promise<RedisWrapper> {
- return await getRedisClient()
-}
-
-const CHAT_VERSION = 'v2'
-function getUserChatKey(userId: string) {
- return `user:${CHAT_VERSION}:chat:${userId}`
-}
-
-export async function getChats(userId?: string | null) {
- if (!userId) {
- return []
- }
-
- try {
- const redis = await getRedis()
- const chats = await redis.zrange(getUserChatKey(userId), 0, -1, {
- rev: true
- })
-
- if (chats.length === 0) {
- return []
- }
-
- const results = await Promise.all(
- chats.map(async chatKey => {
- const chat = await redis.hgetall(chatKey)
- return chat
- })
- )
-
- return results
- .filter((result): result is Record<string, any> => {
- if (result === null || Object.keys(result).length === 0) {
- return false
- }
- return true
- })
- .map(chat => {
- const plainChat = { ...chat }
- if (typeof plainChat.messages === 'string') {
- try {
- plainChat.messages = JSON.parse(plainChat.messages)
- } catch (error) {
- plainChat.messages = []
- }
- }
- if (plainChat.createdAt && !(plainChat.createdAt instanceof Date)) {
- plainChat.createdAt = new Date(plainChat.createdAt)
- }
- return plainChat as Chat
- })
- } catch (error) {
- return []
- }
-}
-
-export async function getChatsPage(
- userId: string,
- limit = 20,
- offset = 0
-): Promise<{ chats: Chat[]; nextOffset: number | null }> {
- try {
- const redis = await getRedis()
- const userChatKey = getUserChatKey(userId)
- const start = offset
- const end = offset + limit - 1
-
- const chatKeys = await redis.zrange(userChatKey, start, end, {
- rev: true
- })
-
- if (chatKeys.length === 0) {
- return { chats: [], nextOffset: null }
- }
-
- const results = await Promise.all(
- chatKeys.map(async chatKey => {
- const chat = await redis.hgetall(chatKey)
- return chat
- })
- )
-
- const chats = results
- .filter((result): result is Record<string, any> => {
- if (result === null || Object.keys(result).length === 0) {
- return false
- }
- return true
- })
- .map(chat => {
- const plainChat = { ...chat }
- if (typeof plainChat.messages === 'string') {
- try {
- plainChat.messages = JSON.parse(plainChat.messages)
- } catch (error) {
- plainChat.messages = []
- }
- }
- if (plainChat.createdAt && !(plainChat.createdAt instanceof Date)) {
- plainChat.createdAt = new Date(plainChat.createdAt)
- }
- return plainChat as Chat
- })
-
- const nextOffset = chatKeys.length === limit ? offset + limit : null
- return { chats, nextOffset }
- } catch (error) {
- console.error('Error fetching chat page:', error)
- return { chats: [], nextOffset: null }
- }
-}
-
-export async function getChat(id: string, userId: string = 'anonymous') {
- const redis = await getRedis()
- const chat = await redis.hgetall<Chat>(`chat:${id}`)
-
- if (!chat) {
- return null
- }
-
- // Parse the messages if they're stored as a string
- if (typeof chat.messages === 'string') {
- try {
- chat.messages = JSON.parse(chat.messages)
- } catch (error) {
- chat.messages = []
- }
- }
-
- // Ensure messages is always an array
- if (!Array.isArray(chat.messages)) {
- chat.messages = []
- }
-
- return chat
-}
-
-export async function clearChats(
- userId: string = 'anonymous'
-): Promise<{ error?: string }> {
- const redis = await getRedis()
- const userChatKey = getUserChatKey(userId)
- const chats = await redis.zrange(userChatKey, 0, -1)
- if (!chats.length) {
- return { error: 'No chats to clear' }
- }
- const pipeline = redis.pipeline()
-
- for (const chat of chats) {
- pipeline.del(chat)
- pipeline.zrem(userChatKey, chat)
- }
-
- await pipeline.exec()
-
- revalidatePath('/')
- redirect('/')
-}
-
-export async function deleteChat(
- chatId: string,
- userId = 'anonymous'
-): Promise<{ error?: string }> {
- try {
- const redis = await getRedis()
- const userKey = getUserChatKey(userId)
- const chatKey = `chat:${chatId}`
-
- const chatDetails = await redis.hgetall<Chat>(chatKey)
- if (!chatDetails || Object.keys(chatDetails).length === 0) {
- console.warn(`Attempted to delete non-existent chat: ${chatId}`)
- return { error: 'Chat not found' }
- }
-
- // Optional: Check if the chat actually belongs to the user if userId is provided and matters
- // if (chatDetails.userId !== userId) {
- // console.warn(`Unauthorized attempt to delete chat ${chatId} by user ${userId}`)
- // return { error: 'Unauthorized' }
- // }
-
- const pipeline = redis.pipeline()
- pipeline.del(chatKey)
- pipeline.zrem(userKey, chatKey) // Use chatKey consistently
- await pipeline.exec()
-
- // Revalidate the root path where the chat history is displayed
- revalidatePath('/')
-
- return {}
- } catch (error) {
- console.error(`Error deleting chat ${chatId}:`, error)
- return { error: 'Failed to delete chat' }
- }
-}
-
-export async function saveChat(chat: Chat, userId: string = 'anonymous') {
- try {
- const redis = await getRedis()
- const pipeline = redis.pipeline()
-
- const chatToSave = {
- ...chat,
- messages: JSON.stringify(chat.messages)
- }
-
- pipeline.hmset(`chat:${chat.id}`, chatToSave)
- pipeline.zadd(getUserChatKey(userId), Date.now(), `chat:${chat.id}`)
-
- const results = await pipeline.exec()
-
- return results
- } catch (error) {
- throw error
- }
-}
-
-export async function getSharedChat(id: string) {
- const redis = await getRedis()
- const chat = await redis.hgetall<Chat>(`chat:${id}`)
-
- if (!chat || !chat.sharePath) {
- return null
- }
-
- return chat
-}
-
-export async function shareChat(id: string, userId: string = 'anonymous') {
- const redis = await getRedis()
- const chat = await redis.hgetall<Chat>(`chat:${id}`)
-
- if (!chat || chat.userId !== userId) {
- return null
- }
-
- const payload = {
- ...chat,
- sharePath: `/share/${id}`
- }
-
- await redis.hmset(`chat:${id}`, payload)
-
- return payload
-}
diff --git a/lib/streaming/create-manual-tool-stream.ts b/lib/streaming/create-manual-tool-stream.ts
deleted file mode 100644
index 6a59be08..00000000
--- a/lib/streaming/create-manual-tool-stream.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import {
- convertToCoreMessages,
- createDataStreamResponse,
- DataStreamWriter,
- JSONValue,
- streamText
-} from 'ai'
-import { manualResearcher } from '../agents/manual-researcher'
-import { ExtendedCoreMessage } from '../types'
-import { getMaxAllowedTokens, truncateMessages } from '../utils/context-window'
-import { handleStreamFinish } from './handle-stream-finish'
-import { executeToolCall } from './tool-execution'
-import { BaseStreamConfig } from './types'
-
-export function createManualToolStreamResponse(config: BaseStreamConfig) {
- return createDataStreamResponse({
- execute: async (dataStream: DataStreamWriter) => {
- const { messages, model, chatId, searchMode, userId } = config
- const modelId = `${model.providerId}:${model.id}`
- let toolCallModelId = model.toolCallModel
- ? `${model.providerId}:${model.toolCallModel}`
- : modelId
-
- try {
- const coreMessages = convertToCoreMessages(messages)
- const truncatedMessages = truncateMessages(
- coreMessages,
- getMaxAllowedTokens(model)
- )
-
- const { toolCallDataAnnotation, toolCallMessages } =
- await executeToolCall(
- truncatedMessages,
- dataStream,
- toolCallModelId,
- searchMode
- )
-
- const researcherConfig = manualResearcher({
- messages: [...truncatedMessages, ...toolCallMessages],
- model: modelId,
- isSearchEnabled: searchMode
- })
-
- // Variables to track the reasoning timing.
- let reasoningStartTime: number | null = null
- let reasoningDuration: number | null = null
-
- const result = streamText({
- ...researcherConfig,
- onFinish: async result => {
- const annotations: ExtendedCoreMessage[] = [
- ...(toolCallDataAnnotation ? [toolCallDataAnnotation] : []),
- {
- role: 'data',
- content: {
- type: 'reasoning',
- data: {
- time: reasoningDuration ?? 0,
- reasoning: result.reasoning
- }
- } as JSONValue
- }
- ]
-
- await handleStreamFinish({
- responseMessages: result.response.messages,
- originalMessages: messages,
- model: modelId,
- chatId,
- dataStream,
- userId,
- skipRelatedQuestions: true,
- annotations
- })
- },
- onChunk(event) {
- const chunkType = event.chunk?.type
-
- if (chunkType === 'reasoning') {
- if (reasoningStartTime === null) {
- reasoningStartTime = Date.now()
- }
- } else {
- if (reasoningStartTime !== null) {
- const elapsedTime = Date.now() - reasoningStartTime
- reasoningDuration = elapsedTime
- dataStream.writeMessageAnnotation({
- type: 'reasoning',
- data: { time: elapsedTime }
- } as JSONValue)
- reasoningStartTime = null
- }
- }
- }
- })
-
- result.mergeIntoDataStream(dataStream, {
- sendReasoning: true
- })
- } catch (error) {
- console.error('Stream execution error:', error)
- }
- },
- onError: error => {
- console.error('Stream error:', error)
- return error instanceof Error ? error.message : String(error)
- }
- })
-}
diff --git a/lib/streaming/handle-stream-finish.ts b/lib/streaming/handle-stream-finish.ts
deleted file mode 100644
index 52e145e5..00000000
--- a/lib/streaming/handle-stream-finish.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { getChat, saveChat } from '@/lib/actions/chat'
-import { generateRelatedQuestions } from '@/lib/agents/generate-related-questions'
-import { ExtendedCoreMessage } from '@/lib/types'
-import { convertToExtendedCoreMessages } from '@/lib/utils'
-import { CoreMessage, DataStreamWriter, JSONValue, Message } from 'ai'
-
-interface HandleStreamFinishParams {
- responseMessages: CoreMessage[]
- originalMessages: Message[]
- model: string
- chatId: string
- dataStream: DataStreamWriter
- userId: string
- skipRelatedQuestions?: boolean
- annotations?: ExtendedCoreMessage[]
-}
-
-export async function handleStreamFinish({
- responseMessages,
- originalMessages,
- model,
- chatId,
- dataStream,
- userId,
- skipRelatedQuestions = false,
- annotations = []
-}: HandleStreamFinishParams) {
- try {
- const extendedCoreMessages = convertToExtendedCoreMessages(originalMessages)
- let allAnnotations = [...annotations]
-
- if (!skipRelatedQuestions) {
- // Notify related questions loading
- const relatedQuestionsAnnotation: JSONValue = {
- type: 'related-questions',
- data: { items: [] }
- }
- dataStream.writeMessageAnnotation(relatedQuestionsAnnotation)
-
- // Generate related questions
- const relatedQuestions = await generateRelatedQuestions(
- responseMessages,
- model
- )
-
- // Create and add related questions annotation
- const updatedRelatedQuestionsAnnotation: ExtendedCoreMessage = {
- role: 'data',
- content: {
- type: 'related-questions',
- data: relatedQuestions.object
- } as JSONValue
- }
-
- dataStream.writeMessageAnnotation(
- updatedRelatedQuestionsAnnotation.content as JSONValue
- )
- allAnnotations.push(updatedRelatedQuestionsAnnotation)
- }
-
- // Create the message to save
- const generatedMessages = [
- ...extendedCoreMessages,
- ...responseMessages.slice(0, -1),
- ...allAnnotations, // Add annotations before the last message
- ...responseMessages.slice(-1)
- ] as ExtendedCoreMessage[]
-
- if (process.env.ENABLE_SAVE_CHAT_HISTORY !== 'true') {
- return
- }
-
- // Get the chat from the database if it exists, otherwise create a new one
- const savedChat = (await getChat(chatId, userId)) ?? {
- messages: [],
- createdAt: new Date(),
- userId: userId,
- path: `/search/${chatId}`,
- title: originalMessages[0].content,
- id: chatId
- }
-
- // Save chat with complete response and related questions
- await saveChat(
- {
- ...savedChat,
- messages: generatedMessages
- },
- userId
- ).catch(error => {
- console.error('Failed to save chat:', error)
- throw new Error('Failed to save chat history')
- })
- } catch (error) {
- console.error('Error in handleStreamFinish:', error)
- throw error
- }
-}