feat: cooking assistant can propose creating a recipe

Gives the general chat a createRecipe tool (Vercel AI SDK, stepCountIs(3))
scoped so it can only ever produce a draft — the tool's execute is a pure
echo, no DB write. The route surfaces the tool call as proposedRecipe
alongside the normal text answer; the chat UI renders it as a card with
explicit Create/Discard buttons. Create POSTs to the existing
/api/v1/recipes endpoint — the same code path and tier/recipe-count limit
the manual editor already goes through — so there's exactly one place
that actually creates a recipe row, and nothing happens without the user
clicking Create.

Scoped to the general assistant only (not per-recipe chat), and to one
tool for now — addToShoppingList/generateMealPlan are follow-ups.

v0.45.0
This commit is contained in:
Arnaud
2026-07-17 18:26:19 +02:00
parent 7d290c5b1f
commit 982d4e3264
10 changed files with 222 additions and 37 deletions
@@ -1,19 +1,35 @@
"use client";
import { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { MessageCircle, Send, Bot, User, Maximize2, Minimize2 } from "lucide-react";
import { MessageCircle, Send, Bot, User, Maximize2, Minimize2, ChefHat, Check, X, Loader2 } from "lucide-react";
import ReactMarkdown from "react-markdown";
import { cn } from "@/lib/utils";
import { ChatHistorySearch } from "./chat-history-search";
import { ConversationMenu, type Conversation } from "./conversation-menu";
type RecipeProposal = {
title: string;
description?: string;
baseServings: number;
recipeType: "dish" | "drink";
difficulty?: "easy" | "medium" | "hard";
prepMins?: number;
cookMins?: number;
ingredients: Array<{ rawName: string; quantity?: number; unit?: string }>;
steps: Array<{ instruction: string }>;
};
type Message = {
role: "user" | "assistant";
content: string;
proposedRecipe?: RecipeProposal;
proposalStatus?: "pending" | "creating" | "created" | "discarded";
};
type HistoryEntry = { role: "user" | "assistant"; content: string };
@@ -21,6 +37,7 @@ type HistoryEntry = { role: "user" | "assistant"; content: string };
export function CookingAssistantPanel() {
const t = useTranslations("cookingChat");
const tCommon = useTranslations("common");
const router = useRouter();
const [open, setOpen] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
const [messages, setMessages] = useState<Message[]>([]);
@@ -102,10 +119,15 @@ export function CookingAssistantPanel() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question, conversationId: conversationId ?? undefined }),
});
const data = await res.json() as { answer?: string; error?: string };
const data = await res.json() as { answer?: string; error?: string; proposedRecipe?: RecipeProposal };
setMessages((prev) => [
...prev,
{ role: "assistant", content: data.answer ?? t("sorry") },
{
role: "assistant",
content: data.answer ?? t("sorry"),
proposedRecipe: data.proposedRecipe,
proposalStatus: data.proposedRecipe ? "pending" : undefined,
},
]);
} catch {
setMessages((prev) => [
@@ -117,6 +139,49 @@ export function CookingAssistantPanel() {
}
};
async function handleCreateProposal(index: number) {
const proposal = messages[index]?.proposedRecipe;
if (!proposal) return;
setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, proposalStatus: "creating" } : m)));
try {
const res = await fetch("/api/v1/recipes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title: proposal.title,
description: proposal.description,
baseServings: proposal.baseServings,
recipeType: proposal.recipeType,
difficulty: proposal.difficulty,
prepMins: proposal.prepMins,
cookMins: proposal.cookMins,
visibility: "private",
aiGenerated: true,
ingredients: proposal.ingredients.map((ing, i) => ({ rawName: ing.rawName, quantity: ing.quantity, unit: ing.unit, order: i })),
steps: proposal.steps.map((step, i) => ({ instruction: step.instruction, order: i })),
}),
});
if (!res.ok) {
setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, proposalStatus: "pending" } : m)));
toast.error(t("proposalCreateFailed"));
return;
}
const { id } = await res.json() as { id: string };
setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, proposalStatus: "created" } : m)));
toast.success(t("proposalCreated"));
router.push(`/recipes/${id}/edit`);
} catch {
setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, proposalStatus: "pending" } : m)));
toast.error(t("proposalCreateFailed"));
}
}
function handleDiscardProposal(index: number) {
setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, proposalStatus: "discarded" } : m)));
}
const suggestions = [
t("suggestion1"),
t("suggestion2"),
@@ -195,33 +260,77 @@ export function CookingAssistantPanel() {
)}
{messages.map((msg, i) => (
<div
key={i}
className={cn(
"flex gap-2 items-start",
msg.role === "user" && "flex-row-reverse"
)}
>
<div className={cn(
"h-7 w-7 shrink-0 rounded-full flex items-center justify-center",
msg.role === "user"
? "bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground"
)}>
{msg.role === "user" ? <User className="h-3.5 w-3.5" /> : <Bot className="h-3.5 w-3.5" />}
</div>
<div className={cn(
"rounded-xl px-3 py-2 text-sm max-w-[80%] leading-relaxed",
msg.role === "user"
? "bg-primary text-primary-foreground whitespace-pre-wrap"
: "bg-muted space-y-2 [&_ul]:list-disc [&_ol]:list-decimal [&_ul]:pl-4 [&_ol]:pl-4 [&_strong]:font-semibold [&_li]:my-0.5"
)}>
{msg.role === "assistant" ? (
<ReactMarkdown>{msg.content}</ReactMarkdown>
) : (
msg.content
<div key={i} className="space-y-2">
<div
className={cn(
"flex gap-2 items-start",
msg.role === "user" && "flex-row-reverse"
)}
>
<div className={cn(
"h-7 w-7 shrink-0 rounded-full flex items-center justify-center",
msg.role === "user"
? "bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground"
)}>
{msg.role === "user" ? <User className="h-3.5 w-3.5" /> : <Bot className="h-3.5 w-3.5" />}
</div>
<div className={cn(
"rounded-xl px-3 py-2 text-sm max-w-[80%] leading-relaxed",
msg.role === "user"
? "bg-primary text-primary-foreground whitespace-pre-wrap"
: "bg-muted space-y-2 [&_ul]:list-disc [&_ol]:list-decimal [&_ul]:pl-4 [&_ol]:pl-4 [&_strong]:font-semibold [&_li]:my-0.5"
)}>
{msg.role === "assistant" ? (
<ReactMarkdown>{msg.content}</ReactMarkdown>
) : (
msg.content
)}
</div>
</div>
{msg.proposedRecipe && (
<div className="ml-9 rounded-lg border bg-card p-3 space-y-2 max-w-[80%]">
<div className="flex items-center gap-2">
<ChefHat className="h-3.5 w-3.5 text-primary shrink-0" />
<span className="font-medium text-sm truncate">{msg.proposedRecipe.title}</span>
</div>
<p className="text-xs text-muted-foreground">
{t("proposalSummary", {
ingredients: msg.proposedRecipe.ingredients.length,
steps: msg.proposedRecipe.steps.length,
})}
</p>
{msg.proposalStatus === "created" ? (
<p className="text-xs text-primary flex items-center gap-1"><Check className="h-3 w-3" />{t("proposalCreated")}</p>
) : msg.proposalStatus === "discarded" ? (
<p className="text-xs text-muted-foreground flex items-center gap-1"><X className="h-3 w-3" />{t("proposalDiscarded")}</p>
) : (
<div className="flex gap-2">
<Button
size="sm"
className="h-7 text-xs gap-1"
disabled={msg.proposalStatus === "creating"}
onClick={() => void handleCreateProposal(i)}
>
{msg.proposalStatus === "creating"
? <Loader2 className="h-3 w-3 animate-spin" />
: <Check className="h-3 w-3" />}
{t("proposalCreateButton")}
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 text-xs"
disabled={msg.proposalStatus === "creating"}
onClick={() => handleDiscardProposal(i)}
>
{t("proposalDiscardButton")}
</Button>
</div>
)}
</div>
)}
</div>
))}