Skip to content

Open source CapCut alternative.

TypeScript

feat(site): consume vision-call grants in vision and api-keys routes

David Lebadfb722acd9
diff --git a/site/src/app/api/api-keys/route.ts b/site/src/app/api/api-keys/route.ts
index ea243e44..d12bbbe7 100644
--- a/site/src/app/api/api-keys/route.ts
+++ b/site/src/app/api/api-keys/route.ts
@@ -2,7 +2,6 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { auth, visionApiKeyPrefix } from "@/lib/auth";
-import { getActiveVisionSubscription } from "@/lib/billing/vision-subscription";
import {
donkeySessionUserId,
withDonkeyAuth,
@@ -63,19 +62,16 @@ export const GET = withDonkeyAuth(async (request) => {
return NextResponse.json({ apiKeys: ownKeys.map(toSafeApiKey) });
});
-// Create a new key. Gated on an active Vision API subscription. The full secret
-// is returned exactly once here and never again.
+// Create a new key. Any signed-in user can mint one; the key only returns data
+// when the user has capacity (an active subscription or remaining vision-call
+// grants), which the Vision API route enforces per call. The full secret is
+// returned exactly once here and never again.
export const POST = withDonkeyAuth(async (request) => {
const userId = donkeySessionUserId(request);
if (!userId) {
return unauthorized();
}
- const subscription = await getActiveVisionSubscription(userId);
- if (!subscription) {
- return unauthorized();
- }
-
const body = await request.json().catch(() => null);
const parsed = createApiKeySchema.safeParse(body);
if (!parsed.success) {
diff --git a/site/src/app/api/vision/route.ts b/site/src/app/api/vision/route.ts
index 6477a6f3..4caa0a18 100644
--- a/site/src/app/api/vision/route.ts
+++ b/site/src/app/api/vision/route.ts
@@ -12,10 +12,13 @@ import {
releaseVisionApiCall,
reserveVisionApiCall,
} from "@/lib/billing/vision-subscription";
+import {
+ releaseVisionCallGrant,
+ reserveVisionCallGrant,
+} from "@/lib/credits/vision-grants";
import {
type DonkeyAuthenticatedRequest,
shouldBypassDonkeyInferenceCredits,
- unauthorizedResponse,
withDonkeyAuth,
} from "@/lib/donkey-api-auth";
import { InferenceProviderError } from "@/lib/inference/providers";
@@ -53,6 +56,13 @@ const visionApiKeyRateLimit = {
const inferenceProvider = "omniparser";
const parseModel = "omniparser-v2";
+// How an api-key call's capacity was reserved, so the right bucket is credited
+// back if the request fails: the subscription's monthly quota or a one-time
+// vision-call grant.
+type VisionReservation =
+ | { kind: "subscription"; limit: number; remaining: number }
+ | { kind: "grant"; grantId: string; remaining: number };
+
// This route accepts third-party API keys in addition to app sessions.
export const POST = withDonkeyAuth(visionParseHandler, { allowApiKey: true });
@@ -100,30 +110,49 @@ async function visionParseHandler(request: DonkeyAuthenticatedRequest) {
// The dev-bypass user has no real account, so skip the credit preflight and
// usage recording (both reference a real user row) when bypassing auth.
const bypassCredits = shouldBypassDonkeyInferenceCredits(request.donkey);
- // For the api-key path, the reserved quota call is released if the request
- // later fails, so a failed parse doesn't burn the developer's quota.
- let apiKeyQuota: { limit: number; remaining: number } | null = null;
+ // For the api-key path, the reserved call is released if the request later
+ // fails, so a failed parse doesn't burn the developer's subscription quota or
+ // their grant allotment.
+ let visionReservation: VisionReservation | null = null;
if (isApiKey) {
- const subscription = await getActiveVisionSubscription(request.donkey.userId);
- if (!subscription) {
- return unauthorizedResponse();
+ const userId = request.donkey.userId;
+ // Spend the subscription's monthly quota first (it resets each period), then
+ // fall back to one-time vision-call grants.
+ const subscription = await getActiveVisionSubscription(userId);
+ if (subscription) {
+ const reserved = await reserveVisionApiCall({
+ monthlyCallQuota: subscription.monthlyCallQuota,
+ userId,
+ });
+ if (reserved.ok) {
+ visionReservation = {
+ kind: "subscription",
+ limit: subscription.monthlyCallQuota,
+ remaining: reserved.remaining,
+ };
+ }
}
- const reservation = await reserveVisionApiCall({
- monthlyCallQuota: subscription.monthlyCallQuota,
- userId: request.donkey.userId,
- });
- if (!reservation.ok) {
- // Operational limit, not an auth failure — keep it distinct so API
- // clients can tell "out of quota" apart from a bad key.
+ if (!visionReservation) {
+ const granted = await reserveVisionCallGrant(userId);
+ if (granted.ok) {
+ visionReservation = {
+ grantId: granted.grantId,
+ kind: "grant",
+ remaining: Number(granted.remaining),
+ };
+ }
+ }
+ if (!visionReservation) {
+ // Valid key, but no capacity on either the subscription or grants.
+ // Operational limit, not an auth failure — keep it distinct from a bad key.
return NextResponse.json(
- { error: "quota_exceeded", limit: subscription.monthlyCallQuota },
+ {
+ error: "quota_exceeded",
+ ...(subscription ? { limit: subscription.monthlyCallQuota } : {}),
+ },
{ status: 402 },
);
}
- apiKeyQuota = {
- limit: subscription.monthlyCallQuota,
- remaining: reservation.remaining,
- };
} else if (!bypassCredits) {
const credits = await requireInferenceCredits({
model: billedModel,
@@ -167,10 +196,12 @@ async function visionParseHandler(request: DonkeyAuthenticatedRequest) {
status: "succeeded",
userId: request.donkey.userId,
});
- usageHeaders = apiKeyQuota
+ usageHeaders = visionReservation
? {
- "X-Donkey-Calls-Limit": String(apiKeyQuota.limit),
- "X-Donkey-Calls-Remaining": String(apiKeyQuota.remaining),
+ "X-Donkey-Calls-Remaining": String(visionReservation.remaining),
+ ...(visionReservation.kind === "subscription"
+ ? { "X-Donkey-Calls-Limit": String(visionReservation.limit) }
+ : {}),
}
: creditUsageHeaders(recordedUsage);
}
@@ -179,9 +210,13 @@ async function visionParseHandler(request: DonkeyAuthenticatedRequest) {
headers: usageHeaders,
});
} catch (error) {
- // Give the reserved quota call back — a failed parse shouldn't be billed.
- if (apiKeyQuota) {
- await releaseVisionApiCall(request.donkey.userId);
+ // Give the reserved call back — a failed parse shouldn't be billed.
+ if (visionReservation) {
+ if (visionReservation.kind === "subscription") {
+ await releaseVisionApiCall(request.donkey.userId);
+ } else {
+ await releaseVisionCallGrant(visionReservation.grantId);
+ }
}
if (!bypassCredits) {
await recordFailedInferenceUsage({