feat: multiple named conversations for the cooking assistant

The general assistant had exactly one conversation per user forever
(recipeId null on chat_messages) — no way to start fresh or organize
by topic. Adds an ai_conversations table (title, timestamps) and a
nullable conversationId FK on chat_messages; the assistant panel gets
a conversations menu to create/switch/rename/delete, auto-titling a
new conversation from its first question.

Per-recipe chat is untouched — each recipe already has one natural
thread, so multi-conversation support only applies to the homepage
assistant. Pre-existing general messages (no conversationId) aren't
migrated into the new model and won't appear in the conversation list.

Requires migration 0042 to run against a live DB — not applied in
this sandbox (no Docker here); run `pnpm db:migrate`.

v0.43.0
This commit is contained in:
Arnaud
2026-07-17 17:18:49 +02:00
parent 25e624f618
commit c5a8f94b26
17 changed files with 5671 additions and 18 deletions
@@ -0,0 +1,238 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { List, Plus, Pencil, Trash2, Check, X } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { useLocale } from "@/lib/i18n/provider";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
export type Conversation = { id: string; title: string | null; createdAt: string; updatedAt: string };
/**
* Lists, creates, renames, and deletes the general assistant's conversations
* — the homepage chat can hold more than one thread, unlike the per-recipe
* chat (which stays single-threaded, one conversation per recipe, by design).
*/
export function ConversationMenu({
activeId,
onSelect,
onCreated,
onDeletedActive,
}: {
activeId: string | null;
onSelect: (id: string) => void;
onCreated: (conversation: Conversation) => void;
onDeletedActive: () => void;
}) {
const t = useTranslations("conversations");
const { locale } = useLocale();
const [open, setOpen] = useState(false);
const [conversations, setConversations] = useState<Conversation[]>([]);
const [loading, setLoading] = useState(false);
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
const loadedRef = useRef(false);
useEffect(() => {
function handleClickOutside(e: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setOpen(false);
setRenamingId(null);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
async function loadConversations() {
setLoading(true);
try {
const res = await fetch("/api/v1/ai/conversations");
if (!res.ok) return;
const json = await res.json() as { data: Conversation[] };
setConversations(json.data);
} finally {
setLoading(false);
}
}
function handleToggle() {
setOpen((v) => !v);
if (!loadedRef.current) {
loadedRef.current = true;
void loadConversations();
}
}
async function handleCreate() {
const res = await fetch("/api/v1/ai/conversations", { method: "POST" });
if (!res.ok) {
toast.error(t("createFailed"));
return;
}
const created = await res.json() as Conversation;
setConversations((prev) => [created, ...prev]);
onCreated(created);
setOpen(false);
}
function startRename(conversation: Conversation) {
setRenamingId(conversation.id);
setRenameValue(conversation.title ?? "");
}
async function submitRename() {
if (!renamingId) return;
const id = renamingId;
const title = renameValue.trim() || null;
setRenamingId(null);
const res = await fetch(`/api/v1/ai/conversations/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title }),
});
if (!res.ok) {
toast.error(t("renameFailed"));
return;
}
setConversations((prev) => prev.map((c) => (c.id === id ? { ...c, title } : c)));
}
async function confirmDelete() {
const id = deleteTargetId;
setDeleteTargetId(null);
if (!id) return;
const res = await fetch(`/api/v1/ai/conversations/${id}`, { method: "DELETE" });
if (!res.ok) {
toast.error(t("deleteFailed"));
return;
}
setConversations((prev) => prev.filter((c) => c.id !== id));
if (id === activeId) onDeletedActive();
}
return (
<div ref={containerRef} className="relative">
<button
type="button"
onClick={handleToggle}
className="p-1.5 rounded-md hover:bg-muted transition-colors text-muted-foreground"
aria-label={t("menuAriaLabel")}
>
<List className="h-4 w-4" />
</button>
{open && (
<div className="absolute right-0 top-full mt-1 w-72 rounded-lg border bg-popover shadow-lg z-50 max-h-96 flex flex-col">
<div className="p-1.5 border-b">
<button
type="button"
onClick={() => void handleCreate()}
className="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-muted transition-colors text-left"
>
<Plus className="h-3.5 w-3.5" />
{t("newConversation")}
</button>
</div>
<div className="overflow-y-auto flex-1 p-1">
{loading && <p className="text-xs text-muted-foreground text-center py-4">{t("loading")}</p>}
{!loading && conversations.length === 0 && (
<p className="text-xs text-muted-foreground text-center py-4">{t("empty")}</p>
)}
{!loading && conversations.map((c) => (
<div
key={c.id}
className={cn(
"group flex items-center gap-1 px-2 py-1.5 rounded-md text-sm",
c.id === activeId ? "bg-accent" : "hover:bg-muted/60"
)}
>
{renamingId === c.id ? (
<>
<input
autoFocus
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void submitRename();
if (e.key === "Escape") setRenamingId(null);
}}
maxLength={100}
className="flex-1 min-w-0 bg-transparent border-b border-primary text-sm outline-none"
/>
<button type="button" onClick={() => void submitRename()} className="p-1 rounded-md hover:bg-muted shrink-0" aria-label={t("renameSave")}>
<Check className="h-3.5 w-3.5" />
</button>
<button type="button" onClick={() => setRenamingId(null)} className="p-1 rounded-md hover:bg-muted shrink-0" aria-label={t("renameCancel")}>
<X className="h-3.5 w-3.5" />
</button>
</>
) : (
<>
<button
type="button"
onClick={() => { onSelect(c.id); setOpen(false); }}
className="flex-1 min-w-0 text-left truncate"
>
<span className="truncate block">{c.title || t("untitled")}</span>
<span className="text-xs text-muted-foreground">
{new Date(c.updatedAt).toLocaleDateString(locale, { month: "short", day: "numeric" })}
</span>
</button>
<button
type="button"
onClick={() => startRename(c)}
className="p-1 rounded-md hover:bg-muted shrink-0 opacity-0 group-hover:opacity-100 transition-opacity"
aria-label={t("renameAriaLabel")}
>
<Pencil className="h-3.5 w-3.5" />
</button>
<button
type="button"
onClick={() => setDeleteTargetId(c.id)}
className="p-1 rounded-md hover:bg-muted shrink-0 opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground"
aria-label={t("deleteAriaLabel")}
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</>
)}
</div>
))}
</div>
</div>
)}
<AlertDialog open={!!deleteTargetId} onOpenChange={(v) => { if (!v) setDeleteTargetId(null); }}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("deleteConfirmTitle")}</AlertDialogTitle>
<AlertDialogDescription>{t("deleteConfirmDescription")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t("deleteCancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={() => { void confirmDelete(); }}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{t("deleteConfirm")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
@@ -9,7 +9,7 @@ import { MessageCircle, Send, Bot, User, Maximize2, Minimize2 } from "lucide-rea
import ReactMarkdown from "react-markdown";
import { cn } from "@/lib/utils";
import { ChatHistorySearch } from "./chat-history-search";
import { ClearChatHistoryButton } from "./clear-chat-history-button";
import { ConversationMenu, type Conversation } from "./conversation-menu";
type Message = {
role: "user" | "assistant";
@@ -26,18 +26,59 @@ export function CookingAssistantPanel() {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState("");
const [loading, setLoading] = useState(false);
const [conversationId, setConversationId] = useState<string | null>(null);
const bottomRef = useRef<HTMLDivElement>(null);
const historyLoadedRef = useRef(false);
async function loadMessages(id: string) {
try {
const res = await fetch(`/api/v1/ai/chat-history?conversationId=${id}&limit=50`);
const json = res.ok ? (await res.json()) as { data?: HistoryEntry[] } : null;
setMessages(json?.data?.length ? json.data.map((m) => ({ role: m.role, content: m.content })) : []);
} catch {
setMessages([]);
}
}
function handleSelectConversation(id: string) {
setConversationId(id);
void loadMessages(id);
}
function handleConversationCreated(conversation: Conversation) {
setConversationId(conversation.id);
setMessages([]);
}
function handleActiveConversationDeleted() {
// Fall back to a fresh conversation rather than leaving the panel
// pointed at an id that no longer exists.
fetch("/api/v1/ai/conversations", { method: "POST" })
.then((res) => (res.ok ? res.json() : null))
.then((created: Conversation | null) => {
if (created) {
setConversationId(created.id);
setMessages([]);
}
})
.catch(() => {});
}
useEffect(() => {
if (!open || historyLoadedRef.current) return;
historyLoadedRef.current = true;
fetch("/api/v1/ai/chat-history?scope=general&limit=50")
.then((res) => (res.ok ? res.json() : null))
.then((json: { data?: HistoryEntry[] } | null) => {
if (json?.data?.length) setMessages(json.data.map((m) => ({ role: m.role, content: m.content })));
})
.catch(() => {});
(async () => {
const listRes = await fetch("/api/v1/ai/conversations");
const list = listRes.ok ? ((await listRes.json()) as { data: Conversation[] }).data : [];
const id = list.length > 0
? list[0]!.id
: await fetch("/api/v1/ai/conversations", { method: "POST" })
.then((res) => (res.ok ? res.json() : null))
.then((created: Conversation | null) => created?.id ?? null);
if (!id) return;
setConversationId(id);
await loadMessages(id);
})().catch(() => {});
}, [open]);
useEffect(() => {
@@ -59,7 +100,7 @@ export function CookingAssistantPanel() {
const res = await fetch("/api/v1/ai/cooking-chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question }),
body: JSON.stringify({ question, conversationId: conversationId ?? undefined }),
});
const data = await res.json() as { answer?: string; error?: string };
setMessages((prev) => [
@@ -122,7 +163,12 @@ export function CookingAssistantPanel() {
{fullscreen ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
</button>
<ChatHistorySearch />
<ClearChatHistoryButton disabled={messages.length === 0} onCleared={() => setMessages([])} />
<ConversationMenu
activeId={conversationId}
onSelect={handleSelectConversation}
onCreated={handleConversationCreated}
onDeletedActive={handleActiveConversationDeleted}
/>
</div>
</div>
<p className="text-xs text-muted-foreground text-left">{t("subtitle")}</p>