Skip to content

An AI-powered search engine with a generative UI

feat: add delete action to individual chat items with confirmation dialog

Yoshiki Miura53e99b814a8e
diff --git a/app/api/chat/[id]/route.ts b/app/api/chat/[id]/route.ts
new file mode 100644
index 00000000..7ae37b7e
--- /dev/null
+++ b/app/api/chat/[id]/route.ts
@@ -0,0 +1,40 @@
+import { deleteChat } from '@/lib/actions/chat'
+import { NextRequest, NextResponse } from 'next/server'
+
+export async function DELETE(
+ request: NextRequest,
+ { params }: { params: { id: string } }
+) {
+ const enableSaveChatHistory = process.env.ENABLE_SAVE_CHAT_HISTORY === 'true'
+ if (!enableSaveChatHistory) {
+ return NextResponse.json(
+ { error: 'Chat history saving is disabled.' },
+ { status: 403 }
+ )
+ }
+
+ const chatId = params.id
+ if (!chatId) {
+ return NextResponse.json({ error: 'Chat ID is required' }, { status: 400 })
+ }
+
+ // Replace 'anonymous' with your actual user ID logic if needed
+ const userId = 'anonymous'
+
+ try {
+ const result = await deleteChat(chatId, userId)
+
+ if (result.error) {
+ const statusCode = result.error === 'Chat not found' ? 404 : 500
+ return NextResponse.json({ error: result.error }, { status: statusCode })
+ }
+
+ return NextResponse.json({ ok: true })
+ } catch (error) {
+ console.error(`API route error deleting chat ${chatId}:`, error)
+ return NextResponse.json(
+ { error: 'Internal Server Error' },
+ { status: 500 }
+ )
+ }
+}
diff --git a/components/sidebar/chat-menu-item.tsx b/components/sidebar/chat-menu-item.tsx
index de0bd851..9a36feb2 100644
--- a/components/sidebar/chat-menu-item.tsx
+++ b/components/sidebar/chat-menu-item.tsx
@@ -1,9 +1,34 @@
'use client'
-import { SidebarMenuButton, SidebarMenuItem } from '@/components/ui/sidebar'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger
+} from '@/components/ui/alert-dialog'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import {
+ SidebarMenuAction,
+ SidebarMenuButton,
+ SidebarMenuItem
+} from '@/components/ui/sidebar'
import { Chat } from '@/lib/types'
+import { MoreHorizontal, Trash2 } from 'lucide-react'
import Link from 'next/link'
-import { usePathname } from 'next/navigation'
+import { usePathname, useRouter } from 'next/navigation'
+import { useState, useTransition } from 'react'
+import { toast } from 'sonner'
+import { Spinner } from '../ui/spinner'
interface ChatMenuItemProps {
chat: Chat
@@ -50,13 +75,46 @@ const formatDateWithTime = (date: Date | string) => {
export function ChatMenuItem({ chat }: ChatMenuItemProps) {
const pathname = usePathname()
const isActive = pathname === chat.path
+ const router = useRouter()
+ const [isPending, startTransition] = useTransition()
+ const [isMenuOpen, setIsMenuOpen] = useState(false)
+ const [dialogOpen, setDialogOpen] = useState(false)
+
+ const onDelete = () => {
+ startTransition(async () => {
+ try {
+ const res = await fetch(`/api/chat/${chat.id}`, { method: 'DELETE' })
+
+ if (!res.ok) {
+ const errorData = await res.json()
+ throw new Error(errorData.error || 'Failed to delete chat')
+ }
+
+ toast.success('Chat deleted')
+ setIsMenuOpen(false) // Close menu on success
+ setDialogOpen(false) // Close dialog on success
+
+ // If deleting the currently active chat, navigate home
+ if (isActive) {
+ router.push('/')
+ }
+ // Refresh data for the sidebar
+ router.refresh()
+ } catch (error) {
+ console.error('Failed to delete chat:', error)
+ toast.error((error as Error).message || 'Failed to delete chat')
+ setIsMenuOpen(false) // Close menu on error
+ setDialogOpen(false) // Close dialog on error
+ }
+ })
+ }
return (
<SidebarMenuItem>
<SidebarMenuButton
asChild
isActive={isActive}
- className="h-auto flex-col gap-0.5 items-start p-2"
+ className="h-auto flex-col gap-0.5 items-start p-2 pr-8"
>
<Link href={chat.path}>
<div className="text-xs font-medium truncate select-none w-full">
@@ -67,6 +125,65 @@ export function ChatMenuItem({ chat }: ChatMenuItemProps) {
</div>
</Link>
</SidebarMenuButton>
+
+ <DropdownMenu open={isMenuOpen} onOpenChange={setIsMenuOpen}>
+ <DropdownMenuTrigger asChild>
+ <SidebarMenuAction disabled={isPending} className="size-7 p-1 mr-1">
+ {isPending ? (
+ <div className="flex items-center justify-center size-full">
+ <Spinner />
+ </div>
+ ) : (
+ <MoreHorizontal size={16} />
+ )}
+ <span className="sr-only">Chat Actions</span>
+ </SidebarMenuAction>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="right" align="start">
+ <AlertDialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ <AlertDialogTrigger asChild>
+ <DropdownMenuItem
+ disabled={isPending}
+ className="gap-2 text-destructive focus:text-destructive"
+ onSelect={e => {
+ e.preventDefault()
+ // Don't call onDelete directly, just open the dialog
+ }}
+ >
+ <Trash2 size={14} />
+ Delete Chat
+ </DropdownMenuItem>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This action cannot be undone. This will permanently delete
+ this chat history.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={isPending}>
+ Cancel
+ </AlertDialogCancel>
+ <AlertDialogAction
+ disabled={isPending}
+ onClick={onDelete} // Call onDelete here
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ >
+ {isPending ? (
+ <div className="flex items-center justify-center">
+ <Spinner />
+ </div>
+ ) : (
+ 'Delete'
+ )}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </DropdownMenuContent>
+ </DropdownMenu>
</SidebarMenuItem>
)
}
diff --git a/components/ui/spinner.tsx b/components/ui/spinner.tsx
index 91c843c8..1cf111dc 100644
--- a/components/ui/spinner.tsx
+++ b/components/ui/spinner.tsx
@@ -1,9 +1,11 @@
// Based on: https://github.com/vercel/ai/blob/main/examples/next-ai-rsc/components/llm-stocks/spinner.tsx
-import { Card } from './card'
+import { cn } from '@/lib/utils'
import { IconLogo } from './icons'
-export const Spinner = () => (
+interface SpinnerProps extends React.SVGProps<SVGSVGElement> {}
+
+export const Spinner = ({ className, ...props }: SpinnerProps) => (
<svg
fill="none"
stroke="currentColor"
@@ -12,7 +14,8 @@ export const Spinner = () => (
strokeLinecap="round"
strokeLinejoin="round"
xmlns="http://www.w3.org/2000/svg"
- className="h-5 w-5 animate-spin stroke-zinc-400"
+ className={cn('h-5 w-5 animate-spin stroke-zinc-400', className)}
+ {...props}
>
<path d="M12 3v3m6.366-.366-2.12 2.12M21 12h-3m.366 6.366-2.12-2.12M12 21v-3m-6.366.366 2.12-2.12M3 12h3m-.366-6.366 2.12 2.12"></path>
</svg>
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
index f6a9516b..d07b7247 100644
--- a/lib/actions/chat.ts
+++ b/lib/actions/chat.ts
@@ -165,6 +165,42 @@ export async function clearChats(
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()