An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Refactor(chat): Enhance chat data fetching and UI message handling
Yoshiki Miurab07b9e7b3a30
diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsxindex a196eb8c..4a8ef461 100644--- a/app/search/[id]/page.tsx+++ b/app/search/[id]/page.tsx@@ -1,8 +1,8 @@import { Chat } from '@/components/chat'-import { getChat } from '@/lib/actions/chat'+import { getChat } from '@/lib/actions/chat-db'import { getCurrentUserId } from '@/lib/auth/get-current-user'import { getModels } from '@/lib/config/models'-import { convertToUIMessages } from '@/lib/utils'+import { Message } from 'ai'import { notFound, redirect } from 'next/navigation'export const maxDuration = 60@@ -12,7 +12,13 @@ export async function generateMetadata(props: {}) {const { id } = await props.paramsconst userId = await getCurrentUserId()++ if (!userId) {+ redirect('/auth/login')+ }+const chat = await getChat(id, userId)+return {title: chat?.title.toString().slice(0, 50) || 'Search'}@@ -21,21 +27,27 @@ export async function generateMetadata(props: {export default async function SearchPage(props: {params: Promise<{ id: string }>}) {- const userId = await getCurrentUserId()const { id } = await props.params+ const userId = await getCurrentUserId()++ if (!userId) {+ redirect('/auth/login')+ }const chat = await getChat(id, userId)- // convertToUIMessages for useChat hook- const messages = convertToUIMessages(chat?.messages || [])if (!chat) {- redirect('/')- }-- if (chat?.userId !== userId && chat?.userId !== 'anonymous') {notFound()}+ const messages: Message[] = chat.messages.map(message => ({+ id: message.id,+ parts: message.parts as Message['parts'],+ role: message.role as Message['role'],+ content: '',+ createdAt: new Date(message.createdAt)+ }))+const models = await getModels()return <Chat id={id} savedMessages={messages} models={models} />}diff --git a/components/render-message.tsx b/components/render-message.tsxindex 827c0ac8..ea0aac09 100644--- a/components/render-message.tsx+++ b/components/render-message.tsx@@ -100,7 +100,7 @@ export function RenderMessage({if (message.role === 'user') {return (<UserMessage- message={message.content}+ message={message}messageId={messageId}onUpdateMessage={onUpdateMessage}/>diff --git a/components/user-message.tsx b/components/user-message.tsxindex f6b3e2f2..9fc32b7f 100644--- a/components/user-message.tsx+++ b/components/user-message.tsx@@ -1,6 +1,7 @@'use client'import { cn } from '@/lib/utils'+import { Message } from 'ai'import { Pencil } from 'lucide-react'import React, { useState } from 'react'import TextareaAutosize from 'react-textarea-autosize'@@ -8,7 +9,7 @@ import { CollapsibleMessage } from './collapsible-message'import { Button } from './ui/button'type UserMessageProps = {- message: string+ message: MessagemessageId?: stringonUpdateMessage?: (messageId: string, newContent: string) => Promise<void>}@@ -18,12 +19,17 @@ export const UserMessage: React.FC<UserMessageProps> = ({messageId,onUpdateMessage}) => {+ const messageText =+ message.parts+ ?.filter(part => part.type === 'text')+ .map(part => part.text)+ .join('') || ''const [isEditing, setIsEditing] = useState(false)- const [editedContent, setEditedContent] = useState(message)+ const [editedContent, setEditedContent] = useState(messageText)const handleEditClick = (e: React.MouseEvent<HTMLButtonElement>) => {e.stopPropagation()- setEditedContent(message)+ setEditedContent(messageText)setIsEditing(true)}@@ -70,7 +76,7 @@ export const UserMessage: React.FC<UserMessageProps> = ({</div>) : (<div className="flex justify-between items-start">- <div className="flex-1">{message}</div>+ <div className="flex-1">{messageText}</div><divclassName={cn('absolute top-1 right-1 transition-opacity ml-2',diff --git a/lib/actions/chat-db.ts b/lib/actions/chat-db.tsindex a544b359..b782acb2 100644--- a/lib/actions/chat-db.ts+++ b/lib/actions/chat-db.ts@@ -14,9 +14,56 @@ export async function getChatsPage(userId: string, limit = 20, offset = 0) {return chatDb.getChatsPage(userId, limit, offset)}-// Get a single chat by ID-export async function getChat(id: string, userId: string) {- return chatDb.getChat(id, userId)+// Get a single chat by ID, including its messages, with permission checks.+export async function getChat(+ chatId: string,+ requestingUserId?: string // Optional: for logged-in user context+): Promise<(DBChat & { messages: DBMessage[] }) | null> {+ let chat: DBChat | null = null++ // Attempt to fetch chat data.+ // Try getSharedChat first; it might be a public chat or one shared via a link (if system supports).+ // We assume getSharedChat fetches by ID and doesn't require a userId for public/shared entities.+ const potentialSharedChat = await chatDb.getSharedChat(chatId)+ if (potentialSharedChat) {+ // Assuming potentialSharedChat is compatible with DBChat or is DBChat itself.+ // If it's a different type, appropriate mapping/casting would be needed here.+ chat = potentialSharedChat as DBChat+ }++ // If not found through getSharedChat (e.g., it's private) AND a user is logged in,+ // try to fetch it as a chat belonging to that user.+ if (!chat && requestingUserId) {+ chat = await chatDb.getChat(chatId, requestingUserId)+ }++ // If chat is still not found after these attempts, it either doesn't exist or isn't accessible+ // through the primary fetch mechanisms used.+ if (!chat) {+ return null+ }++ // Authorization check+ const isOwner = requestingUserId && chat.userId === requestingUserId+ const isPublic = chat.visibility === 'public'++ if (isPublic) {+ // Public chat: access granted.+ } else if (chat.visibility === 'private') {+ if (!isOwner) {+ return null // Private chat, but the requesting user is not the owner.+ }+ // Private chat and user is owner: access granted.+ } else {+ // Chat is neither 'public' nor 'private' (e.g., unknown visibility status),+ // or some other condition not met. Deny access.+ return null+ }++ // If access is granted, fetch messages for the chat.+ const messages = await chatDb.getChatMessages(chatId)++ return { ...chat, messages }}// Clear all chats for a user