An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: improve chat history with pagination and infinite scroll
Yoshiki Miura10f64ee086d2
diff --git a/app/api/chats/route.ts b/app/api/chats/route.tsnew file mode 100644index 00000000..b935981d--- /dev/null+++ b/app/api/chats/route.ts@@ -0,0 +1,33 @@+import { getChatsPage } from '@/lib/actions/chat'+import { type Chat } from '@/lib/types'+import { NextRequest, NextResponse } from 'next/server'++interface ChatPageResponse {+ chats: Chat[]+ nextOffset: number | null+}++export async function GET(request: NextRequest) {+ const enableSaveChatHistory = process.env.ENABLE_SAVE_CHAT_HISTORY === 'true'+ if (!enableSaveChatHistory) {+ return NextResponse.json<ChatPageResponse>({ chats: [], nextOffset: null })+ }++ const { searchParams } = new URL(request.url)+ const offset = parseInt(searchParams.get('offset') || '0', 10)+ const limit = parseInt(searchParams.get('limit') || '20', 10)++ // Replace 'anonymous' with your actual user ID logic+ const userId = 'anonymous'++ try {+ const result = await getChatsPage(userId, limit, offset)+ return NextResponse.json<ChatPageResponse>(result)+ } catch (error) {+ console.error('API route error fetching chats:', error)+ return NextResponse.json<ChatPageResponse>(+ { chats: [], nextOffset: null },+ { status: 500 }+ )+ }+}diff --git a/components/sidebar/chat-history-client.tsx b/components/sidebar/chat-history-client.tsxnew file mode 100644index 00000000..8abb25ec--- /dev/null+++ b/components/sidebar/chat-history-client.tsx@@ -0,0 +1,109 @@+'use client'++import { SidebarMenu } from '@/components/ui/sidebar'+import { Chat } from '@/lib/types'+import { useCallback, useEffect, useRef, useState, useTransition } from 'react'+import { toast } from 'sonner'+import { ChatHistorySkeleton } from './chat-history-skeleton'+import { ChatMenuItem } from './chat-menu-item'++interface ChatHistoryClientProps {+ initialChats: Chat[]+ initialNextOffset: number | null+}++interface ChatPageResponse {+ chats: Chat[]+ nextOffset: number | null+}++export function ChatHistoryClient({+ initialChats,+ initialNextOffset+}: ChatHistoryClientProps) {+ const [chats, setChats] = useState<Chat[]>(initialChats)+ const [nextOffset, setNextOffset] = useState<number | null>(initialNextOffset)+ const [isLoading, setIsLoading] = useState(false)+ const loadMoreRef = useRef<HTMLDivElement>(null)+ const [isPending, startTransition] = useTransition()++ // Synchronize state with props when initial data changes (e.g., after router.refresh)+ useEffect(() => {+ setChats(initialChats)+ setNextOffset(initialNextOffset)+ }, [initialChats, initialNextOffset])++ const fetchMoreChats = useCallback(async () => {+ if (isLoading || nextOffset === null) return++ setIsLoading(true)+ try {+ const response = await fetch(`/api/chats?offset=${nextOffset}&limit=20`)+ if (!response.ok) {+ throw new Error('Failed to fetch chat history')+ }+ const { chats: newChats, nextOffset: newNextOffset } =+ (await response.json()) as ChatPageResponse++ startTransition(() => {+ setChats(prevChats => [...prevChats, ...newChats])+ setNextOffset(newNextOffset)+ })+ } catch (error) {+ console.error('Failed to load more chats:', error)+ toast.error('Failed to load more chat history.')+ // Optionally stop trying to load more if there's an error+ setNextOffset(null)+ } finally {+ setIsLoading(false)+ }+ }, [nextOffset, isLoading])++ useEffect(() => {+ const observerRefValue = loadMoreRef.current+ if (!observerRefValue || nextOffset === null) return++ const observer = new IntersectionObserver(+ ([entry]) => {+ if (entry.isIntersecting && !isLoading) {+ fetchMoreChats()+ }+ },+ { threshold: 0.1 } // Trigger when 10% visible+ )++ observer.observe(observerRefValue)++ return () => {+ if (observerRefValue) {+ observer.unobserve(observerRefValue)+ }+ }+ }, [fetchMoreChats, nextOffset, isLoading])++ return (+ <div className="flex-1 overflow-y-auto mb-2 relative">+ {!chats?.length && !isLoading && nextOffset === null ? (+ <div className="px-2 text-foreground/30 text-sm text-center py-4">+ No search history+ </div>+ ) : (+ <SidebarMenu>+ {chats.map(+ (chat: Chat) => chat && <ChatMenuItem key={chat.id} chat={chat} />+ )}+ </SidebarMenu>+ )}++ {/* Sentinel Element */}+ <div ref={loadMoreRef} style={{ height: '1px' }} />++ {/* Loading Skeleton/Spinner */}+ {(isLoading || isPending) && (+ <div className="py-2">+ <ChatHistorySkeleton />+ </div>+ )}+ </div>+ )+}diff --git a/components/sidebar/chat-history-section.tsx b/components/sidebar/chat-history-section.tsxindex b4cb67c0..a3a6a317 100644--- a/components/sidebar/chat-history-section.tsx+++ b/components/sidebar/chat-history-section.tsx@@ -1,11 +1,6 @@-import {- SidebarGroup,- SidebarGroupLabel,- SidebarMenu-} from '@/components/ui/sidebar'-import { getChats } from '@/lib/actions/chat'-import { Chat } from '@/lib/types'-import { ChatMenuItem } from './chat-menu-item'+import { SidebarGroup, SidebarGroupLabel } from '@/components/ui/sidebar'+import { getChatsPage } from '@/lib/actions/chat'+import { ChatHistoryClient } from './chat-history-client'import { ClearHistoryAction } from './clear-history-action'export async function ChatHistorySection() {@@ -14,30 +9,19 @@ export async function ChatHistorySection() {return null}- // Replace with your own user ID- const chats = await getChats('anonymous')+ // Fetch the initial page of chats+ // Replace 'anonymous' with your actual user ID logic+ const { chats, nextOffset } = await getChatsPage('anonymous', 20, 0)return (<div className="flex flex-col flex-1 h-full"><SidebarGroup><div className="flex items-center justify-between w-full"><SidebarGroupLabel className="p-0">History</SidebarGroupLabel>- <ClearHistoryAction empty={!chats?.length} />+ <ClearHistoryAction empty={!chats?.length && !nextOffset} /></div></SidebarGroup>- <div className="flex-1 overflow-y-auto mb-2">- {!chats?.length ? (- <div className="px-2 text-foreground/30 text-sm text-center py-4">- No search history- </div>- ) : (- <SidebarMenu>- {chats.map(- (chat: Chat) => chat && <ChatMenuItem key={chat.id} chat={chat} />- )}- </SidebarMenu>- )}- </div>+ <ChatHistoryClient initialChats={chats} initialNextOffset={nextOffset} /></div>)}diff --git a/lib/actions/chat.ts b/lib/actions/chat.tsindex 3efa4033..f6a9516b 100644--- a/lib/actions/chat.ts+++ b/lib/actions/chat.ts@@ -1,9 +1,9 @@'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'-import { type Chat } from '@/lib/types'-import { getRedisClient, RedisWrapper } from '@/lib/redis/config'async function getRedis(): Promise<RedisWrapper> {return await getRedisClient()@@ -62,6 +62,62 @@ export async function getChats(userId?: string | null) {}}+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}`)