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
+4 -1
View File
@@ -5,6 +5,7 @@ import { requireSessionOrApiKey } from "@/lib/api-auth";
const Schema = z.object({
recipeId: z.string().uuid().optional(),
conversationId: z.string().uuid().optional(),
// "general" restricts to the homepage cooking assistant (recipeId null);
// omit both recipeId and scope to search across everything.
scope: z.enum(["general"]).optional(),
@@ -19,6 +20,7 @@ export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const parsed = Schema.safeParse({
recipeId: searchParams.get("recipeId") ?? undefined,
conversationId: searchParams.get("conversationId") ?? undefined,
scope: searchParams.get("scope") ?? undefined,
q: searchParams.get("q") ?? undefined,
limit: searchParams.get("limit") ?? undefined,
@@ -26,10 +28,11 @@ export async function GET(req: NextRequest) {
if (!parsed.success) {
return NextResponse.json({ error: "Validation error" }, { status: 400 });
}
const { recipeId, scope, q, limit } = parsed.data;
const { recipeId, conversationId, scope, q, limit } = parsed.data;
const conditions = [eq(chatMessages.userId, session!.user.id)];
if (recipeId) conditions.push(eq(chatMessages.recipeId, recipeId));
else if (conversationId) conditions.push(eq(chatMessages.conversationId, conversationId));
else if (scope === "general") conditions.push(isNull(chatMessages.recipeId));
if (q?.trim()) conditions.push(ilike(chatMessages.content, `%${q.trim()}%`));
@@ -0,0 +1,45 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, aiConversations, eq, and } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
type Params = { params: Promise<{ id: string }> };
const RenameSchema = z.object({ title: z.string().max(100).nullable() });
export async function PATCH(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const { id } = await params;
const body = await req.json() as unknown;
const parsed = RenameSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error" }, { status: 400 });
}
const [updated] = await db
.update(aiConversations)
.set({ title: parsed.data.title?.trim() || null, updatedAt: new Date() })
.where(and(eq(aiConversations.id, id), eq(aiConversations.userId, session!.user.id)))
.returning();
if (!updated) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json({ id: updated.id, title: updated.title });
}
export async function DELETE(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const { id } = await params;
const [deleted] = await db
.delete(aiConversations)
.where(and(eq(aiConversations.id, id), eq(aiConversations.userId, session!.user.id)))
.returning({ id: aiConversations.id });
if (!deleted) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from "next/server";
import { db, aiConversations, eq, desc } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
export async function GET(req: NextRequest) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const rows = await db.query.aiConversations.findMany({
where: eq(aiConversations.userId, session!.user.id),
orderBy: desc(aiConversations.updatedAt),
});
return NextResponse.json({
data: rows.map((r) => ({
id: r.id,
title: r.title,
createdAt: r.createdAt.toISOString(),
updatedAt: r.updatedAt.toISOString(),
})),
});
}
export async function POST(req: NextRequest) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const id = crypto.randomUUID();
const now = new Date();
await db.insert(aiConversations).values({ id, userId: session!.user.id, title: null, createdAt: now, updatedAt: now });
return NextResponse.json({ id, title: null, createdAt: now.toISOString(), updatedAt: now.toISOString() }, { status: 201 });
}
+18 -3
View File
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { generateText } from "ai";
import { db, chatMessages } from "@epicure/db";
import { db, chatMessages, aiConversations, sql } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
@@ -11,6 +11,7 @@ import { getUserPrivateBio, buildUserBioContext } from "@/lib/ai/user-bio";
const Schema = z.object({
question: z.string().min(1).max(500),
conversationId: z.string().uuid().optional(),
});
const LANG: Record<string, string> = { en: "English", fr: "French" };
@@ -48,10 +49,24 @@ export async function POST(req: NextRequest) {
);
if (!result.ok) return result.response;
const { conversationId } = parsed.data;
void db.insert(chatMessages).values([
{ id: crypto.randomUUID(), userId: session!.user.id, recipeId: null, role: "user", content: parsed.data.question },
{ id: crypto.randomUUID(), userId: session!.user.id, recipeId: null, role: "assistant", content: result.data.text },
{ id: crypto.randomUUID(), userId: session!.user.id, recipeId: null, conversationId, role: "user", content: parsed.data.question },
{ id: crypto.randomUUID(), userId: session!.user.id, recipeId: null, conversationId, role: "assistant", content: result.data.text },
]).catch((err) => console.error("[cooking-chat] failed to persist chat history", err));
if (conversationId) {
// Bumps updatedAt (for the conversation list's sort order) and, only if
// this is the conversation's first message, auto-titles it from the
// opening question — so users aren't left staring at "Untitled" entries;
// they can still rename it later.
void db.execute(sql`
UPDATE ${aiConversations}
SET updated_at = now(), title = COALESCE(title, ${parsed.data.question.slice(0, 60)})
WHERE ${aiConversations.id} = ${conversationId} AND ${aiConversations.userId} = ${session!.user.id}
`).catch((err) => console.error("[cooking-chat] failed to touch conversation", err));
}
return NextResponse.json({ answer: result.data.text });
}
@@ -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>
+8 -1
View File
@@ -1,5 +1,5 @@
// Mirrors CHANGELOG.md at the repo root — update both together.
export const APP_VERSION = "0.42.0";
export const APP_VERSION = "0.43.0";
export type ChangelogEntry = {
version: string;
@@ -11,6 +11,13 @@ export type ChangelogEntry = {
};
export const CHANGELOG: ChangelogEntry[] = [
{
version: "0.43.0",
date: "2026-07-17 15:45",
added: [
"The cooking assistant now supports multiple named conversations — start a new one, rename, or delete from the conversations menu in the chat header. Auto-titled from your first question; older single-thread history stays as-is but isn't shown in the new list.",
],
},
{
version: "0.42.0",
date: "2026-07-17 15:15",
+9 -2
View File
@@ -313,9 +313,16 @@ export function generateOpenApiSpec(): object {
registry.registerPath({ method: "post", path: "/api/v1/ai/batch-cook/generate", summary: "Generate a batch-cooking plan (multiple dishes) as a new recipe", description: "Rate-limited: 3 req/min. Consumes AI quota.", security, request: { body: { content: { "application/json": { schema: z.object({ dinners: z.number().int().min(0).max(6).default(4), lunches: z.number().int().min(0).max(6).default(0), servings: z.number().int().min(1).max(12).default(4), dietaryPrefs: z.string().max(200).optional(), difficulty: z.enum(["easy", "medium", "hard"]).optional(), description: z.string().max(500).optional() }) } }, required: true } }, responses: { 200: { description: "New recipe id", content: { "application/json": { schema: z.object({ id: z.string() }) } } }, 400: { description: "Validation error or no dinners/lunches chosen", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited or AI quota exhausted", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/ai/meal-plan/generate", summary: "Generate a week's meal plan (creates a draft recipe per entry)", description: "Rate-limited: 3 req/min. Consumes AI quota. Charges your tier's recipe limit for each generated entry (refunded if the limit is exceeded).", security, request: { body: { content: { "application/json": { schema: z.object({ weekStart: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), dietaryPrefs: z.string().max(200).optional(), servings: z.number().int().min(1).max(20).default(2), days: z.array(z.enum(["mon", "tue", "wed", "thu", "fri", "sat", "sun"])).min(1).max(7).default(["mon", "tue", "wed", "thu", "fri", "sat", "sun"]), usePantry: z.boolean().default(false), pantryMode: z.boolean().default(false), difficulty: z.enum(["easy", "medium", "hard"]).optional(), targetNutritionGoals: z.boolean().default(false) }) } }, required: true } }, responses: { 200: { description: "Created entries", content: { "application/json": { schema: z.object({ weekStart: z.string(), entries: z.array(z.object({ id: z.string(), day: z.string(), mealType: z.string(), recipeId: z.string(), recipeTitle: z.string() })) }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Recipe limit reached for your tier", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited or AI quota exhausted", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/ai/recipe-ideas", summary: "Generate 6 diverse recipe idea cards (not saved)", description: "Rate-limited: 10 req/min. Consumes AI quota.", security, request: { body: { content: { "application/json": { schema: z.object({ prompt: z.string().max(300).optional() }) } } } }, responses: { 200: { description: "Six recipe ideas", content: { "application/json": { schema: z.array(z.object({ title: z.string(), description: z.string(), tags: z.array(z.string()).max(4), difficulty: z.enum(["easy", "medium", "hard"]), totalMins: z.number().int().optional() })) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited or AI quota exhausted", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/ai/cooking-chat", summary: "Ask the general (not recipe-specific) cooking assistant a question", description: "Rate-limited: 30 req/min. Consumes AI quota. Returns a single JSON response (not streamed); persists the exchange to chat history.", security, request: { body: { content: { "application/json": { schema: z.object({ question: z.string().min(1).max(500) }) } }, required: true } }, responses: { 200: { description: "Answer", content: { "application/json": { schema: z.object({ answer: z.string() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited or AI quota exhausted", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/ai/cooking-chat", summary: "Ask the general (not recipe-specific) cooking assistant a question", description: "Rate-limited: 30 req/min. Consumes AI quota. Returns a single JSON response (not streamed); persists the exchange to chat history. Pass conversationId (from POST /api/v1/ai/conversations) to group messages into a named conversation and auto-title it from the first question.", security, request: { body: { content: { "application/json": { schema: z.object({ question: z.string().min(1).max(500), conversationId: z.string().uuid().optional() }) } }, required: true } }, responses: { 200: { description: "Answer", content: { "application/json": { schema: z.object({ answer: z.string() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited or AI quota exhausted", content: { "application/json": { schema: ApiErrorRef } } } } });
const AiConversationRef = registry.register("AiConversation", z.object({
id: z.string(), title: z.string().nullable(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
}));
registry.registerPath({ method: "get", path: "/api/v1/ai/conversations", summary: "List your general-assistant conversations, most recently active first", security, responses: { 200: { description: "Conversations", content: { "application/json": { schema: z.object({ data: z.array(AiConversationRef) }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/ai/conversations", summary: "Start a new (untitled) general-assistant conversation", security, responses: { 201: { description: "Created", content: { "application/json": { schema: AiConversationRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "patch", path: "/api/v1/ai/conversations/{id}", summary: "Rename a conversation (null clears the title back to auto-generated)", security, request: { params: z.object({ id: z.string() }), body: { content: { "application/json": { schema: z.object({ title: z.string().max(100).nullable() }) } }, required: true } }, responses: { 200: { description: "Renamed", content: { "application/json": { schema: z.object({ id: z.string(), title: z.string().nullable() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "delete", path: "/api/v1/ai/conversations/{id}", summary: "Delete a conversation and its messages", security, request: { params: z.object({ id: z.string() }) }, responses: { 200: { description: "Deleted", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/ai/recipe-chat", summary: "Ask a question about a specific recipe (author only)", description: "Rate-limited: 30 req/min. Consumes AI quota. Returns a single JSON response (not streamed); persists the exchange to chat history.", security, request: { body: { content: { "application/json": { schema: z.object({ recipeId: z.string().uuid(), question: z.string().min(1).max(500) }) } }, required: true } }, responses: { 200: { description: "Answer", content: { "application/json": { schema: z.object({ answer: z.string() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Recipe not found", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited or AI quota exhausted", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/ai/chat-history", summary: "List your AI chat history (general assistant and/or per-recipe)", description: "Omit both recipeId and scope to search across everything; pass scope=general to restrict to the homepage assistant (no recipe).", security, request: { query: z.object({ recipeId: z.string().uuid().optional(), scope: z.enum(["general"]).optional(), q: z.string().max(200).optional(), limit: z.coerce.number().int().min(1).max(100).default(30) }) }, responses: { 200: { description: "Messages", content: { "application/json": { schema: z.object({ data: z.array(AiChatMessageRef) }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/ai/chat-history", summary: "List your AI chat history (general assistant and/or per-recipe)", description: "Omit recipeId, conversationId, and scope to search across everything; pass conversationId for one general-assistant conversation, or scope=general for the legacy single general thread.", security, request: { query: z.object({ recipeId: z.string().uuid().optional(), conversationId: z.string().uuid().optional(), scope: z.enum(["general"]).optional(), q: z.string().max(200).optional(), limit: z.coerce.number().int().min(1).max(100).default(30) }) }, responses: { 200: { description: "Messages", content: { "application/json": { schema: z.object({ data: z.array(AiChatMessageRef) }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "delete", path: "/api/v1/ai/chat-history", summary: "Clear your AI chat history (general assistant and/or per-recipe)", security, request: { query: z.object({ recipeId: z.string().uuid().optional(), scope: z.enum(["general"]).optional() }) }, responses: { 200: { description: "Cleared", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
const FeedRecipeRef = registry.register("FeedRecipe", z.object({
id: z.string(), title: z.string(), description: z.string().nullable(),
+18
View File
@@ -461,6 +461,24 @@
"inputPlaceholder": "Ask a question…",
"send": "Send message"
},
"conversations": {
"menuAriaLabel": "Conversations",
"newConversation": "New conversation",
"loading": "Loading…",
"empty": "No conversations yet.",
"untitled": "Untitled",
"renameSave": "Save",
"renameCancel": "Cancel",
"renameAriaLabel": "Rename",
"deleteAriaLabel": "Delete",
"deleteConfirmTitle": "Delete this conversation?",
"deleteConfirmDescription": "This deletes the conversation and all its messages. This can't be undone.",
"deleteCancel": "Cancel",
"deleteConfirm": "Delete",
"createFailed": "Failed to start a new conversation",
"renameFailed": "Failed to rename conversation",
"deleteFailed": "Failed to delete conversation"
},
"servingScaler": {
"servings": "Servings",
"reset": "Reset",
+18
View File
@@ -461,6 +461,24 @@
"inputPlaceholder": "Posez une question…",
"send": "Envoyer le message"
},
"conversations": {
"menuAriaLabel": "Conversations",
"newConversation": "Nouvelle conversation",
"loading": "Chargement…",
"empty": "Aucune conversation pour le moment.",
"untitled": "Sans titre",
"renameSave": "Enregistrer",
"renameCancel": "Annuler",
"renameAriaLabel": "Renommer",
"deleteAriaLabel": "Supprimer",
"deleteConfirmTitle": "Supprimer cette conversation ?",
"deleteConfirmDescription": "Ceci supprime la conversation et tous ses messages. Cette action est irréversible.",
"deleteCancel": "Annuler",
"deleteConfirm": "Supprimer",
"createFailed": "Échec de la création d'une nouvelle conversation",
"renameFailed": "Échec du renommage de la conversation",
"deleteFailed": "Échec de la suppression de la conversation"
},
"servingScaler": {
"servings": "Portions",
"reset": "Réinitialiser",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@epicure/web",
"version": "0.42.0",
"version": "0.43.0",
"private": true,
"scripts": {
"dev": "next dev",