fix: return clean errors and refund quota on AI provider failures

AI routes had no consistent error handling — a provider failure (e.g.
OpenRouter returning a degraded-model error) crashed the route as an
uncaught 500 and, worse, still charged the user's monthly aiCall
quota for a request that never succeeded.

Adds withAiQuota()/aiErrorResponse() (lib/ai/ai-error.ts) and applies
them across all 12 AI generation routes: charges the quota, runs the
AI call, refunds the credit and returns a clean user-facing message
if it throws. Frontend needs no changes — existing dialogs already
toast whatever `error` string comes back.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-02 12:32:31 +02:00
parent e5d1080fb9
commit 524310433c
16 changed files with 325 additions and 165 deletions
@@ -4,6 +4,7 @@ import { db, recipes, recipeIngredients, recipeSteps, mealPlans, mealPlanEntries
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { aiErrorResponse } from "@/lib/ai/ai-error";
import { generateMealPlan } from "@/lib/ai/features/generate-meal-plan";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
@@ -52,18 +53,23 @@ export async function POST(req: NextRequest) {
pantryItemNames = pantry.map((p) => p.rawName);
}
const plan = await generateMealPlan(
{
dietaryPrefs: parsed.data.dietaryPrefs,
servings: parsed.data.servings,
pantryItems: pantryItemNames,
days: parsed.data.days,
pantryMode: parsed.data.pantryMode,
difficulty: parsed.data.difficulty,
},
{ ...config, userContext: privateBio ?? undefined },
locale
);
let plan;
try {
plan = await generateMealPlan(
{
dietaryPrefs: parsed.data.dietaryPrefs,
servings: parsed.data.servings,
pantryItems: pantryItemNames,
days: parsed.data.days,
pantryMode: parsed.data.pantryMode,
difficulty: parsed.data.difficulty,
},
{ ...config, userContext: privateBio ?? undefined },
locale
);
} catch (err) {
return aiErrorResponse(err);
}
// Ensure meal plan row exists for the week
let mealPlan = await db.query.mealPlans.findFirst({