diff --git a/apps/web/app/api/v1/ai/chat-history/route.ts b/apps/web/app/api/v1/ai/chat-history/route.ts new file mode 100644 index 0000000..e7c016c --- /dev/null +++ b/apps/web/app/api/v1/ai/chat-history/route.ts @@ -0,0 +1,53 @@ +import { NextRequest, NextResponse } from "next/server"; +import { z } from "zod"; +import { db, chatMessages, eq, and, isNull, desc, asc, ilike } from "@epicure/db"; +import { requireSession } from "@/lib/api-auth"; + +const Schema = z.object({ + recipeId: 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(), + q: z.string().max(200).optional(), + limit: z.coerce.number().int().min(1).max(100).default(30), +}); + +export async function GET(req: NextRequest) { + const { session, response } = await requireSession(); + if (response) return response; + + const { searchParams } = new URL(req.url); + const parsed = Schema.safeParse({ + recipeId: searchParams.get("recipeId") ?? undefined, + scope: searchParams.get("scope") ?? undefined, + q: searchParams.get("q") ?? undefined, + limit: searchParams.get("limit") ?? undefined, + }); + if (!parsed.success) { + return NextResponse.json({ error: "Validation error" }, { status: 400 }); + } + const { recipeId, scope, q, limit } = parsed.data; + + const conditions = [eq(chatMessages.userId, session!.user.id)]; + if (recipeId) conditions.push(eq(chatMessages.recipeId, recipeId)); + else if (scope === "general") conditions.push(isNull(chatMessages.recipeId)); + if (q?.trim()) conditions.push(ilike(chatMessages.content, `%${q.trim()}%`)); + + const rows = await db.query.chatMessages.findMany({ + where: and(...conditions), + orderBy: q?.trim() ? [desc(chatMessages.createdAt)] : [asc(chatMessages.createdAt)], + limit, + with: { recipe: { columns: { id: true, title: true } } }, + }); + + return NextResponse.json({ + data: rows.map((r) => ({ + id: r.id, + role: r.role, + content: r.content, + createdAt: r.createdAt.toISOString(), + recipeId: r.recipeId, + recipeTitle: r.recipe?.title ?? null, + })), + }); +} diff --git a/apps/web/app/api/v1/ai/cooking-chat/route.ts b/apps/web/app/api/v1/ai/cooking-chat/route.ts index 5d6e597..3947f58 100644 --- a/apps/web/app/api/v1/ai/cooking-chat/route.ts +++ b/apps/web/app/api/v1/ai/cooking-chat/route.ts @@ -1,6 +1,7 @@ import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { generateText } from "ai"; +import { db, chatMessages } from "@epicure/db"; import { requireSession } from "@/lib/api-auth"; import { applyRateLimit } from "@/lib/rate-limit"; import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error"; @@ -46,5 +47,10 @@ export async function POST(req: NextRequest) { ); if (!result.ok) return result.response; + 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 }, + ]).catch((err) => console.error("[cooking-chat] failed to persist chat history", err)); + return NextResponse.json({ answer: result.data.text }); } diff --git a/apps/web/app/api/v1/ai/recipe-chat/route.ts b/apps/web/app/api/v1/ai/recipe-chat/route.ts index 86970c6..f8a9ebd 100644 --- a/apps/web/app/api/v1/ai/recipe-chat/route.ts +++ b/apps/web/app/api/v1/ai/recipe-chat/route.ts @@ -6,7 +6,7 @@ import { applyRateLimit } from "@/lib/rate-limit"; import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error"; import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key"; import { resolveModel } from "@/lib/ai/factory"; -import { db, recipes, eq, and } from "@epicure/db"; +import { db, recipes, chatMessages, eq, and } from "@epicure/db"; import { getUserPrivateBio, buildUserBioContext } from "@/lib/ai/user-bio"; import { hasQuantity } from "@/lib/fractions"; @@ -84,5 +84,10 @@ ${recipeContext}${bioContext}`, ); if (!result.ok) return result.response; + void db.insert(chatMessages).values([ + { id: crypto.randomUUID(), userId: session!.user.id, recipeId: recipe.id, role: "user", content: parsed.data.question }, + { id: crypto.randomUUID(), userId: session!.user.id, recipeId: recipe.id, role: "assistant", content: result.data.text }, + ]).catch((err) => console.error("[recipe-chat] failed to persist chat history", err)); + return NextResponse.json({ answer: result.data.text }); } diff --git a/apps/web/components/recipe/chat-history-search.tsx b/apps/web/components/recipe/chat-history-search.tsx new file mode 100644 index 0000000..639ba90 --- /dev/null +++ b/apps/web/components/recipe/chat-history-search.tsx @@ -0,0 +1,108 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { useTranslations } from "next-intl"; +import { Search, X, Bot, User } from "lucide-react"; +import { Input } from "@/components/ui/input"; +import { cn } from "@/lib/utils"; + +type SearchResult = { + id: string; + role: "user" | "assistant"; + content: string; + createdAt: string; + recipeId: string | null; + recipeTitle: string | null; +}; + +/** + * Search across the user's own AI-chat history. With `recipeId` set, scopes + * to that recipe's conversation; omit it to search everything the user has + * ever asked (both per-recipe chats and the general cooking assistant). + */ +export function ChatHistorySearch({ recipeId }: { recipeId?: string }) { + const t = useTranslations("chatHistory"); + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(""); + const [results, setResults] = useState([]); + const [loading, setLoading] = useState(false); + const containerRef = useRef(null); + + useEffect(() => { + function handleClickOutside(e: MouseEvent) { + if (containerRef.current && !containerRef.current.contains(e.target as Node)) { + setOpen(false); + } + } + document.addEventListener("mousedown", handleClickOutside); + return () => document.removeEventListener("mousedown", handleClickOutside); + }, []); + + useEffect(() => { + if (!query.trim()) return; + const timeout = setTimeout(() => { + setLoading(true); + const params = new URLSearchParams({ q: query.trim() }); + if (recipeId) params.set("recipeId", recipeId); + fetch(`/api/v1/ai/chat-history?${params.toString()}`) + .then((res) => (res.ok ? res.json() : null)) + .then((json: { data?: SearchResult[] } | null) => setResults(json?.data ?? [])) + .catch(() => setResults([])) + .finally(() => setLoading(false)); + }, 300); + return () => clearTimeout(timeout); + }, [query, recipeId]); + + return ( +
+ + + {open && ( +
+
+ setQuery(e.target.value)} + placeholder={t("searchPlaceholder")} + className="h-8 text-sm" + /> + +
+
+ {loading &&

{t("searching")}

} + {!loading && query.trim() && results.length === 0 && ( +

{t("noResults")}

+ )} + {!loading && query.trim() && results.map((r) => ( +
+
+ {r.role === "user" ? : } + {new Date(r.createdAt).toLocaleDateString()} + {r.recipeTitle && !recipeId && ( + · {r.recipeTitle} + )} +
+

{r.content}

+
+ ))} +
+
+ )} +
+ ); +} diff --git a/apps/web/components/recipe/cooking-assistant-panel.tsx b/apps/web/components/recipe/cooking-assistant-panel.tsx index e0613a4..9f4af72 100644 --- a/apps/web/components/recipe/cooking-assistant-panel.tsx +++ b/apps/web/components/recipe/cooking-assistant-panel.tsx @@ -8,12 +8,15 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sh import { MessageCircle, Send, Bot, User } from "lucide-react"; import ReactMarkdown from "react-markdown"; import { cn } from "@/lib/utils"; +import { ChatHistorySearch } from "./chat-history-search"; type Message = { role: "user" | "assistant"; content: string; }; +type HistoryEntry = { role: "user" | "assistant"; content: string }; + export function CookingAssistantPanel() { const t = useTranslations("cookingChat"); const [open, setOpen] = useState(false); @@ -21,6 +24,18 @@ export function CookingAssistantPanel() { const [input, setInput] = useState(""); const [loading, setLoading] = useState(false); const bottomRef = useRef(null); + const historyLoadedRef = useRef(false); + + 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(() => {}); + }, [open]); useEffect(() => { if (open && bottomRef.current) { @@ -83,10 +98,13 @@ export function CookingAssistantPanel() { - - - {t("title")} - +
+ + + {t("title")} + + +

{t("subtitle")}

diff --git a/apps/web/components/recipe/recipe-chat-panel.tsx b/apps/web/components/recipe/recipe-chat-panel.tsx index cdac16b..b529911 100644 --- a/apps/web/components/recipe/recipe-chat-panel.tsx +++ b/apps/web/components/recipe/recipe-chat-panel.tsx @@ -8,12 +8,15 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sh import { MessageCircle, Send, Bot, User } from "lucide-react"; import ReactMarkdown from "react-markdown"; import { cn } from "@/lib/utils"; +import { ChatHistorySearch } from "./chat-history-search"; type Message = { role: "user" | "assistant"; content: string; }; +type HistoryEntry = { role: "user" | "assistant"; content: string }; + type Props = { recipeId: string; recipeTitle: string; @@ -26,6 +29,18 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) { const [input, setInput] = useState(""); const [loading, setLoading] = useState(false); const bottomRef = useRef(null); + const historyLoadedRef = useRef(false); + + useEffect(() => { + if (!open || historyLoadedRef.current) return; + historyLoadedRef.current = true; + fetch(`/api/v1/ai/chat-history?recipeId=${recipeId}&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(() => {}); + }, [open, recipeId]); useEffect(() => { if (open && bottomRef.current) { @@ -85,10 +100,13 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) { - - - {t("title")} - +
+ + + {t("title")} + + +

{recipeTitle}

diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json index dc91d32..d7c7e44 100644 --- a/apps/web/messages/en.json +++ b/apps/web/messages/en.json @@ -388,6 +388,13 @@ "inputPlaceholder": "Ask a question…", "send": "Send message" }, + "chatHistory": { + "searchAriaLabel": "Search chat history", + "searchPlaceholder": "Search past questions…", + "searching": "Searching…", + "noResults": "No matching messages", + "close": "Close" + }, "cookingChat": { "sorry": "Sorry, I couldn't answer that.", "error": "Something went wrong. Please try again.", @@ -1147,6 +1154,9 @@ "lastUsedOn": "Last used {date}", "neverUsed": "Never used", "revoke": "Revoke", + "apiKeyScopeFull": "Full access", + "apiKeyScopeRead": "Read-only", + "apiKeyScopeHelp": "Read-only keys can only make GET requests — they can't create, edit, or delete anything.", "webhookUrlPlaceholder": "https://example.com/webhook", "webhookAdding": "Adding…", "webhookAddButton": "Add webhook", diff --git a/apps/web/messages/fr.json b/apps/web/messages/fr.json index 74d5aae..d0323ba 100644 --- a/apps/web/messages/fr.json +++ b/apps/web/messages/fr.json @@ -388,6 +388,13 @@ "inputPlaceholder": "Posez une question…", "send": "Envoyer le message" }, + "chatHistory": { + "searchAriaLabel": "Rechercher dans l'historique", + "searchPlaceholder": "Rechercher une question passée…", + "searching": "Recherche…", + "noResults": "Aucun message correspondant", + "close": "Fermer" + }, "cookingChat": { "sorry": "Désolé, je n'ai pas pu répondre à cela.", "error": "Une erreur s'est produite. Veuillez réessayer.", @@ -1153,6 +1160,9 @@ "lastUsedOn": "Utilisée le {date}", "neverUsed": "Jamais utilisée", "revoke": "Révoquer", + "apiKeyScopeFull": "Accès complet", + "apiKeyScopeRead": "Lecture seule", + "apiKeyScopeHelp": "Les clés en lecture seule ne peuvent faire que des requêtes GET — elles ne peuvent rien créer, modifier ou supprimer.", "copyFailed": "Échec de la copie dans le presse-papiers", "byokSaved": "Clé {provider} enregistrée", "byokSaveFailed": "Échec de l'enregistrement de la clé",