fix: substitute lookup, zero-quantity display, chatbot close button + markdown

- Substitute finder never applied the user's BYOK/admin AI key (only fell
  back to raw process.env), so it silently failed whenever the key was
  stored via settings rather than a literal env var. Now resolves via
  getDefaultProviderWithKey like every other AI route. Popover also
  surfaces real error messages instead of swallowing failures.
- Ingredients with quantity 0 (salt, pepper, "to taste") rendered the
  literal digit "0" in cooking mode, print view, public recipe page,
  shopping lists, and serving scaler — several sites relied on generic
  truthiness/filter(Boolean), which doesn't catch a stored "0" string.
  Added a shared hasQuantity() helper and applied it everywhere quantity
  is rendered, plus in the AI recipe-chat context sent to the model.
- Recipe chat panel rendered a duplicate close button on top of shadcn
  Sheet's own built-in close X, producing a garbled overlapping glyph.
  Removed the duplicate.
- Recipe chat assistant replies are markdown from the model but were
  rendered as raw text; added react-markdown so formatting actually
  renders.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-02 07:43:37 +02:00
parent 5ff8ef5547
commit afff6cf9eb
13 changed files with 716 additions and 25 deletions
+2 -1
View File
@@ -7,6 +7,7 @@ import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
import { resolveModel } from "@/lib/ai/factory";
import { db, recipes, eq, and } from "@epicure/db";
import { getUserPrivateBio, buildUserBioContext } from "@/lib/ai/user-bio";
import { hasQuantity } from "@/lib/fractions";
const Schema = z.object({
recipeId: z.string().uuid(),
@@ -39,7 +40,7 @@ export async function POST(req: NextRequest) {
}
const ingredientList = recipe.ingredients
.map((ing) => [ing.quantity, ing.unit, ing.rawName, ing.note ? `(${ing.note})` : ""].filter(Boolean).join(" "))
.map((ing) => [hasQuantity(ing.quantity) ? ing.quantity : null, ing.unit, ing.rawName, ing.note ? `(${ing.note})` : ""].filter(Boolean).join(" "))
.join("\n");
const stepList = recipe.steps
+6 -1
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { requireSession } from "@/lib/api-auth";
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { substituteIngredient } from "@/lib/ai/features/substitute-ingredient";
const Schema = z.object({
@@ -36,10 +37,14 @@ export async function POST(req: NextRequest) {
? `recipe "${parsed.data.recipeTitle}"`
: "a general recipe";
const aiConfig = parsed.data.provider
? { provider: parsed.data.provider, model: parsed.data.model }
: await getDefaultProviderWithKey(session!.user.id);
const substitutions = await substituteIngredient(
parsed.data.ingredient,
context,
{ provider: parsed.data.provider, model: parsed.data.model }
aiConfig
);
return NextResponse.json({ substitutions });
+2 -1
View File
@@ -3,6 +3,7 @@ import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, recipes, eq, and } from "@epicure/db";
import { PrintTrigger } from "@/components/recipe/print-trigger";
import { hasQuantity } from "@/lib/fractions";
type Params = { params: Promise<{ id: string }> };
@@ -109,7 +110,7 @@ export default async function RecipePrintPage({ params }: Params) {
{recipe.ingredients.map((ing) => (
<li key={ing.id}>
<span className="qty">
{[ing.quantity, ing.unit].filter(Boolean).join(" ")}
{[hasQuantity(ing.quantity) ? ing.quantity : null, ing.unit].filter(Boolean).join(" ")}
</span>
{ing.rawName}
{ing.note && <span style={{ color: "#888" }}> ({ing.note})</span>}
+2 -1
View File
@@ -11,6 +11,7 @@ import { buttonVariants } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ServingScaler } from "@/components/recipe/serving-scaler";
import { getPublicUrl } from "@/lib/storage";
import { hasQuantity } from "@/lib/fractions";
import { cn } from "@/lib/utils";
type Params = { params: Promise<{ id: string }> };
@@ -68,7 +69,7 @@ export default async function PublicRecipePage({ params }: Params) {
prepTime: recipe.prepMins ? `PT${recipe.prepMins}M` : undefined,
cookTime: recipe.cookMins ? `PT${recipe.cookMins}M` : undefined,
recipeIngredient: recipe.ingredients.map((i) =>
[i.quantity, i.unit, i.rawName].filter(Boolean).join(" ")
[hasQuantity(i.quantity) ? i.quantity : null, i.unit, i.rawName].filter(Boolean).join(" ")
),
recipeInstructions: recipe.steps.map((s) => ({
"@type": "HowToStep",
@@ -6,6 +6,7 @@ import { X, ChevronLeft, ChevronRight, List, Mic, MicOff, Play, Square, HelpCirc
import { cn } from "@/lib/utils";
import { useTranslations } from "next-intl";
import { useLocale } from "@/lib/i18n/provider";
import { hasQuantity } from "@/lib/fractions";
type Step = { id: string; instruction: string; timerSeconds: number | null };
type Ingredient = { rawName: string; quantity: string | null; unit: string | null };
@@ -345,7 +346,7 @@ export function CookingMode({
{ingredients.map((ing, i) => (
<li key={i} className="text-sm flex gap-2">
<span className="text-muted-foreground shrink-0 w-16 text-right">
{ing.quantity}{ing.unit ? ` ${ing.unit}` : ""}
{hasQuantity(ing.quantity) ? ing.quantity : ""}{ing.unit ? ` ${ing.unit}` : ""}
</span>
<span>{ing.rawName}</span>
</li>
@@ -5,6 +5,7 @@ import { cn } from "@/lib/utils";
import { Check, Package, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { hasQuantity } from "@/lib/fractions";
type Item = {
id: string;
@@ -104,9 +105,9 @@ export function ShoppingListView({
<span className={cn("flex-1 text-sm", item.checked && "line-through text-muted-foreground")}>
{item.rawName}
</span>
{(item.quantity || item.unit) && (
{(hasQuantity(item.quantity) || item.unit) && (
<span className={cn("text-xs text-muted-foreground tabular-nums shrink-0", item.checked && "opacity-50")}>
{item.quantity}{item.unit ? ` ${item.unit}` : ""}
{hasQuantity(item.quantity) ? item.quantity : ""}{item.unit ? ` ${item.unit}` : ""}
</span>
)}
</button>
@@ -29,6 +29,7 @@ function scaleQty(quantity: string | number | null | undefined, scale: number):
if (!quantity) return undefined;
const n = typeof quantity === "number" ? quantity : parseFloat(quantity);
if (isNaN(n)) return String(quantity);
if (n === 0) return undefined;
const scaled = n * scale;
return scaled % 1 === 0 ? String(scaled) : scaled.toFixed(2).replace(/\.?0+$/, "");
}
@@ -4,7 +4,8 @@ import { useState, useRef, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { MessageCircle, Send, X, Bot, User } from "lucide-react";
import { MessageCircle, Send, Bot, User } from "lucide-react";
import ReactMarkdown from "react-markdown";
import { cn } from "@/lib/utils";
type Message = {
@@ -81,16 +82,11 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent side="right" className="w-full sm:w-[420px] flex flex-col p-0">
<SheetHeader className="px-4 py-3 border-b shrink-0">
<div className="flex items-center justify-between">
<SheetTitle className="text-base flex items-center gap-2">
<Bot className="h-4 w-4 text-primary" />
Ask about this recipe
</SheetTitle>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setOpen(false)}>
<X className="h-4 w-4" />
</Button>
</div>
<SheetHeader className="px-4 py-3 pr-10 border-b shrink-0">
<SheetTitle className="text-base flex items-center gap-2">
<Bot className="h-4 w-4 text-primary" />
Ask about this recipe
</SheetTitle>
<p className="text-xs text-muted-foreground text-left">{recipeTitle}</p>
</SheetHeader>
@@ -131,12 +127,16 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
{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 whitespace-pre-wrap",
"rounded-xl px-3 py-2 text-sm max-w-[80%] leading-relaxed",
msg.role === "user"
? "bg-primary text-primary-foreground"
: "bg-muted"
? "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.content}
{msg.role === "assistant" ? (
<ReactMarkdown>{msg.content}</ReactMarkdown>
) : (
msg.content
)}
</div>
</div>
))}
@@ -3,7 +3,7 @@
import { useState } from "react";
import { Minus, Plus, Sparkles, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { scaleQuantity } from "@/lib/fractions";
import { scaleQuantity, hasQuantity } from "@/lib/fractions";
import { SubstituteIngredientPopover } from "@/components/recipe/substitute-ingredient-popover";
type Ingredient = {
@@ -135,7 +135,7 @@ export function ServingScaler({
<li key={ing.id} className="flex gap-2 text-sm group">
<span className="font-medium tabular-nums min-w-[3rem] text-right">
{aiIng
? `${aiIng.quantity}${aiIng.unit ? ` ${aiIng.unit}` : ""}`
? `${hasQuantity(aiIng.quantity) ? aiIng.quantity : ""}${aiIng.unit ? ` ${aiIng.unit}` : ""}`
: scaled
? `${scaled}${ing.unit ? ` ${ing.unit}` : ""}`
: ing.unit ?? ""}
@@ -33,20 +33,28 @@ export function SubstituteIngredientPopover({
const [loading, setLoading] = useState(false);
const [substitutions, setSubstitutions] = useState<Substitution[]>([]);
const [fetched, setFetched] = useState(false);
const [error, setError] = useState<string | null>(null);
async function fetchSubstitutions() {
if (fetched) return;
setLoading(true);
setError(null);
try {
const res = await fetch("/api/v1/ai/substitute", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ingredient, recipeTitle }),
});
if (!res.ok) return;
if (!res.ok) {
const body = await res.json().catch(() => null) as { error?: string } | null;
setError(body?.error ?? "Couldn't fetch substitutes.");
return;
}
const data = await res.json() as { substitutions: Substitution[] };
setSubstitutions(data.substitutions);
setFetched(true);
} catch {
setError("Couldn't fetch substitutes.");
} finally {
setLoading(false);
}
@@ -91,6 +99,9 @@ export function SubstituteIngredientPopover({
))}
</div>
)}
{!loading && error && (
<p className="text-sm text-destructive py-1">{error}</p>
)}
{!loading && fetched && substitutions.length === 0 && (
<p className="text-sm text-muted-foreground py-1">No substitutions found.</p>
)}
+7
View File
@@ -36,10 +36,17 @@ export function formatQuantity(value: number): string {
return whole === 0 ? bestFraction : `${whole} ${bestFraction}`;
}
export function hasQuantity(quantity: string | null | undefined): boolean {
if (!quantity) return false;
const raw = parseFloat(quantity);
return !isNaN(raw) && raw !== 0;
}
export function scaleQuantity(baseQuantity: string | null, base: number, desired: number): string {
if (!baseQuantity) return "";
const raw = parseFloat(baseQuantity);
if (isNaN(raw)) return baseQuantity;
if (raw === 0) return "";
const scale = base === 0 ? 1 : desired / base;
return formatQuantity(raw * scale);
}
+1
View File
@@ -36,6 +36,7 @@
"react": "19.2.4",
"react-dom": "19.2.4",
"react-hook-form": "^7.80.0",
"react-markdown": "^10.1.0",
"shadcn": "^4.11.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.6.0",
+661
View File
File diff suppressed because it is too large Load Diff