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:
@@ -23,7 +23,7 @@ vi.mock("@epicure/db", () => ({
|
||||
}));
|
||||
|
||||
// Import after mock
|
||||
const { checkAndIncrementTierLimit, incrementUsage } = await import("../tiers");
|
||||
const { checkAndIncrementTierLimit, incrementUsage, refundAiCall } = await import("../tiers");
|
||||
|
||||
function makeChain(finalValue: unknown) {
|
||||
const chain = {
|
||||
@@ -93,6 +93,14 @@ describe("checkAndIncrementTierLimit", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("refundAiCall", () => {
|
||||
it("issues a decrement-with-floor UPDATE for the current month", async () => {
|
||||
mockDb.execute.mockResolvedValueOnce(undefined);
|
||||
await refundAiCall("user1");
|
||||
expect(mockDb.execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("incrementUsage", () => {
|
||||
it("calls insert with correct aiCall initial values", async () => {
|
||||
const chain = makeInsertChain();
|
||||
|
||||
Reference in New Issue
Block a user