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:
@@ -69,6 +69,20 @@ export async function checkAndIncrementTierLimit(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refunds one aiCall credit for the current month. Call this when an AI
|
||||
* request failed after the quota was already charged (e.g. provider error)
|
||||
* so users aren't billed against their limit for a call that never succeeded.
|
||||
*/
|
||||
export async function refundAiCall(userId: string): Promise<void> {
|
||||
const month = currentMonth();
|
||||
await db.execute(sql`
|
||||
UPDATE user_usage
|
||||
SET ai_calls_used = GREATEST(ai_calls_used - 1, 0)
|
||||
WHERE user_id = ${userId} AND month = ${month}
|
||||
`);
|
||||
}
|
||||
|
||||
export async function incrementUsage(
|
||||
userId: string,
|
||||
key: LimitKey,
|
||||
|
||||
Reference in New Issue
Block a user